def drop_table(ret, table): """ Drop a table. @param ret Array to which query results will be added. @param table The table to be dropped. """ php.Reference.check(ref) php.array_merge( update_sql('DROP TABLE {' + table + '}'), ret, True )
def drop_table(ret, table): """ Drop a table. @param ret Array to which query results will be added. @param table The table to be dropped. """ php.Reference.check(ref) php.array_merge(update_sql('DROP TABLE {' + table + '}'), ret, True)
def registry_cache_path_files(): """ Save the files required by the registry for this path. """ used_code = registry_mark_code(None, None, True) if (used_code): files = [] type_sql = [] params = [] for type, names in used_code.items(): type_sql.append( "(name IN (" + db_placeholders(names, 'varchar') + \ ") AND type = '%s')" ) params = php.array_merge(params, names) params.append(type) res = db_query("SELECT DISTINCT filename FROM {registry} WHERE " + \ php.implode(' OR ', type_sql), params) while True: row = db_fetch_object(res) if (row == None): break files.append(row.filename) if (files): sort(files) # Only write this to cache if the file list we are going to cache # is different to what we loaded earlier in the request. if (files != registry_load_path_files(True)): menu = menu_get_item() cache_set('registry:' + menu['path'], php.implode(';', files), \ 'cache_registry')
def registry_cache_path_files(): """ Save the files required by the registry for this path. """ used_code = registry_mark_code(None, None, True) if used_code: files = [] type_sql = [] params = [] for type, names in used_code.items(): type_sql.append("(name IN (" + db_placeholders(names, "varchar") + ") AND type = '%s')") params = php.array_merge(params, names) params.append(type) res = db_query("SELECT DISTINCT filename FROM {registry} WHERE " + php.implode(" OR ", type_sql), params) while True: row = db_fetch_object(res) if row == None: break files.append(row.filename) if files: sort(files) # Only write this to cache if the file list we are going to cache # is different to what we loaded earlier in the request. if files != registry_load_path_files(True): menu = menu_get_item() cache_set("registry:" + menu["path"], php.implode(";", files), "cache_registry")
def scan_directory(dir, mask, nomask = ['.', '..', 'CVS'], \ callback = 0, recurse = True, key = 'filename', min_depth = 0, depth = 0): """ Finds all files that match a given mask in a given directory. Directories and files beginning with a period are excluded; this prevents hidden files and directories (such as SVN working directories) from being scanned. @param dir The base directory for the scan, without trailing slash. @param mask The regular expression of the files to find. @param nomask An array of files/directories to ignore. @param callback The callback function to call for each match. @param recurse When True, the directory scan will recurse the entire tree starting at the provided directory. @param key The key to be used for the returned array of files + Possible values are "filename", for the path starting with dir, "basename", for the basename of the file, and "name" for the name of the file without an extension. @param min_depth Minimum depth of directories to return files from. @param depth Current depth of recursion + This parameter is only used internally and should not be passed. @return An associative array (keyed on the provided key) of objects with "path", "basename", and "name" members corresponding to the matching files. """ key = (key if php.in_array(key, \ ('filename', 'basename', 'name')) else 'filename') files = [] if php.is_dir(dir): dir_files = php.scandir(dir) for file in dir_files: if (not php.in_array(file, nomask) and file[0] != '.'): if (php.is_dir("%s/%s" % (dir, file)) and recurse): # Give priority to files in this folder by # merging them in after any subdirectory files. files = php.array_merge(file_scan_directory("%s/%s" % (dir, file), \ mask, nomask, callback, recurse, key, min_depth, depth + 1), files) elif (depth >= min_depth and ereg(mask, file)): # Always use this match over anything already # set in files with the same $key. filename = "%s/%s" % (dir, file) basename_ = php.basename(file) name = php.substr(basename_, 0, php.strrpos(basename_, '.')) files[key] = php.stdClass() files[key].filename = filename files[key].basename = basename_ files[key].name = name if (callback): callback(filename) return files
def get_querystring(): """ Compose a query string to append to table sorting requests. @return A query string that consists of all components of the current page request except for those pertaining to table sorting. """ return lib_common.drupal_query_string_encode( _REQUEST, php.array_merge(['q', 'sort', 'order'], php.array_keys(_COOKIE)))
def drupal_get_schema(table=None, rebuild=False): """ Get the schema definition of a table, or the whole database schema. The returned schema will include any modifications made by any module that implements hook_schema_alter(). @param $table The name of the table. If not given, the schema of all tables is returned. @param $rebuild If true, the schema will be rebuilt instead of retrieved from the cache. """ php.static(drupal_get_schema, 'schema', []) if (php.empty(drupal_get_schema.schema) or rebuild): # Try to load the schema from cache. cached = lib_cache.get('schema') if (not rebuild and cached): drupal_get_schema.schema = cached.data # Otherwise, rebuild the schema cache. else: drupal_get_schema.schema = [] # Load the .install files to get hook_schema. # On some databases this function may be called before bootstrap has # been completed, so we force the functions we need to load just in case. if (drupal_function_exists('module_load_all_includes')): # There is currently a bug in module_list() where it caches what it # was last called with, which is not always what you want. # module_load_all_includes() calls module_list(), but if this function # is called very early in the bootstrap process then it will be # uninitialized and therefore return no modules. Instead, we have to # "prime" module_list() here to to values we want, specifically # "yes rebuild the list and don't limit to bootstrap". # TODO: Remove this call after http://drupal.org/node/222109 is fixed. lib_plugin.list(True, False) lib_plugin.load_all_includes('install') # Invoke hook_schema for all modules. for module in module_implements('schema'): current = lib_plugin.invoke(module, 'schema') if (drupal_function_exists('_drupal_initialize_schema')): _drupal_initialize_schema(module, current) schema = php.array_merge(schema, current) if (drupal_function_exists('drupal_alter')): drupal_alter('schema', schema) if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL): cache_set('schema', schema) if (table is None): return schema elif (php.isset(schema, table)): return schema[table] else: return False
def drupal_get_schema(table=None, rebuild=False): """ Get the schema definition of a table, or the whole database schema. The returned schema will include any modifications made by any module that implements hook_schema_alter(). @param $table The name of the table. If not given, the schema of all tables is returned. @param $rebuild If true, the schema will be rebuilt instead of retrieved from the cache. """ php.static(drupal_get_schema, "schema", []) if php.empty(drupal_get_schema.schema) or rebuild: # Try to load the schema from cache. cached = lib_cache.get("schema") if not rebuild and cached: drupal_get_schema.schema = cached.data # Otherwise, rebuild the schema cache. else: drupal_get_schema.schema = [] # Load the .install files to get hook_schema. # On some databases this function may be called before bootstrap has # been completed, so we force the functions we need to load just in case. if drupal_function_exists("module_load_all_includes"): # There is currently a bug in module_list() where it caches what it # was last called with, which is not always what you want. # module_load_all_includes() calls module_list(), but if this function # is called very early in the bootstrap process then it will be # uninitialized and therefore return no modules. Instead, we have to # "prime" module_list() here to to values we want, specifically # "yes rebuild the list and don't limit to bootstrap". # TODO: Remove this call after http://drupal.org/node/222109 is fixed. lib_plugin.list(True, False) lib_plugin.load_all_includes("install") # Invoke hook_schema for all modules. for module in module_implements("schema"): current = lib_plugin.invoke(module, "schema") if drupal_function_exists("_drupal_initialize_schema"): _drupal_initialize_schema(module, current) schema = php.array_merge(schema, current) if drupal_function_exists("drupal_alter"): drupal_alter("schema", schema) if drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL: cache_set("schema", schema) if table is None: return schema elif php.isset(schema, table): return schema[table] else: return False
def save_upload(source, validators = {}, dest = False, \ replace = FILE_EXISTS_RENAME): """ Saves a file upload to a new location + The source file is validated as a proper upload and handled as such. The file will be added to the files table as a temporary file. Temporary files are periodically cleaned + To make the file permanent file call file_set_status() to change its status. @param source A string specifying the name of the upload field to save. @param validators An optional, associative array of callback functions used to validate the file + The keys are function names and the values arrays of callback parameters which will be passed in after the user and file objects + The functions should return an array of error messages, an empty array indicates that the file passed validation. The functions will be called in the order specified. @param dest A string containing the directory source should be copied to + If this is not provided or is not writable, the temporary directory will be used. @param replace A boolean indicating whether an existing file of the same name in the destination directory should overwritten + A False value will generate a new, unique filename in the destination directory. @return An object containing the file information, or False in the event of an error. """ php.static(file_save_upload, 'upload_cache', {}) # Add in our check of the the file name length. validators['file_validate_name_length'] = {} # Return cached objects without processing since the file will have # already been processed and the paths in FILES will be invalid. if (php.isset(file_save_upload.uploadcache, source)): return file_save_upload.uploadcache[source] # If a file was uploaded, process it. if (php.isset(p.FILES, 'files') and p.FILES['files']['name'][source] and \ php.is_uploaded_file(p.FILES['files']['tmp_name'][source])): # Check for file upload errors and return False if a # lower level system error occurred. # @see http://php.net/manual/en/features.file-upload.errors.php if p.FILES['files']['error'][source] == UPLOAD_ERR_OK: pass elif p.FILES['files']['error'][source] == UPLOAD_ERR_INI_SIZE or \ p.FILES['files']['error'][source] == UPLOAD_ERR_FORM_SIZE: drupal_set_message(t(\ 'The file %file could not be saved, because it exceeds %maxsize, ' + \ 'the maximum allowed size for uploads.', \ {'%file' : source, '%maxsize' : \ format_size(file_upload_max_size())}), 'error') return False elif p.FILES['files']['error'][source] == UPLOAD_ERR_PARTIAL or \ p.FILES['files']['error'][source] == UPLOAD_ERR_NO_FILE: drupal_set_message(t('The file %file could not be saved, ' + \ 'because the upload did not complete.', {'%file' : source}), 'error') return False # Unknown error else: drupal_set_message(t('The file %file could not be saved. ' + \ 'An unknown error has occurred.', {'%file' : source}), 'error') return False # Build the list of non-munged extensions. # @todo: this should not be here + we need to figure out the right place. extensions = '' for rid, name in lib_appglobals.user.roles.items(): extensions += ' ' + variable_get("upload_extensions_rid", variable_get('upload_extensions_default', \ 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp')) # Begin building file object. file = php.stdClass() file.filename = file_munge_filename(php.trim(\ basename(p.FILES['files']['name'][source]), '.'), extensions) file.filepath = p.FILES['files']['tmp_name'][source] file.filemime = p.FILES['files']['type'][source] # Rename potentially executable files, to help prevent exploits. if (php.preg_match('/\.(php|pl|py|cgi|asp|js)$/i', file.filename) and \ (php.substr(file.filename, -4) != '.txt')): file.filemime = 'text/plain' file.filepath += '.txt' file.filename += '.txt' # If the destination is not provided, or is not writable, then use the # temporary directory. if (php.empty(dest) or file_check_path(dest) == False): dest = file_directory_temp() file.source = source file.destination = file_destination(file_create_path(dest + '/' + \ file.filename), replace) file.filesize = FILES['files']['size'][source] # Call the validation functions. errors = {} for function, args in validators.items(): array_unshift(args, file) errors = php.array_merge(errors, function(*args)) # Check for validation errors. if (not php.empty(errors)): message = t('The selected file %name could not be uploaded.', \ {'%name' : file.filename}) if (php.count(errors) > 1): message += '<ul><li>' + php.implode('</li><li>', errors) + '</li></ul>' else: message += ' ' + php.array_pop(errors) form_set_error(source, message) return False # Move uploaded files from PHP's upload_tmp_dir to # Drupal's temporary directory. # This overcomes open_basedir restrictions for future file operations. file.filepath = file.destination if (not move_uploaded_file(p.FILES['files']['tmp_name'][source], \ file.filepath)): form_set_error(source, t('File upload error. ' + \ 'Could not move uploaded file.')) watchdog('file', 'Upload error + Could not move uploaded file ' + \ '%file to destination %destination.', \ {'%file' : file.filename, '%destination' : file.filepath}) return False # If we made it this far it's safe to record this file in the database. file.uid = lib_appglobals.user.uid file.status = FILE_STATUS_TEMPORARY file.timestamp = time() drupal_write_record('files', file) # Add file to the cache. file_save_upload.upload_cache[source] = file return file return False
def save_upload(source, validators = {}, dest = False, \ replace = FILE_EXISTS_RENAME): """ Saves a file upload to a new location + The source file is validated as a proper upload and handled as such. The file will be added to the files table as a temporary file. Temporary files are periodically cleaned + To make the file permanent file call file_set_status() to change its status. @param source A string specifying the name of the upload field to save. @param validators An optional, associative array of callback functions used to validate the file + The keys are function names and the values arrays of callback parameters which will be passed in after the user and file objects + The functions should return an array of error messages, an empty array indicates that the file passed validation. The functions will be called in the order specified. @param dest A string containing the directory source should be copied to + If this is not provided or is not writable, the temporary directory will be used. @param replace A boolean indicating whether an existing file of the same name in the destination directory should overwritten + A False value will generate a new, unique filename in the destination directory. @return An object containing the file information, or False in the event of an error. """ php.static(file_save_upload, 'upload_cache', {}) # Add in our check of the the file name length. validators['file_validate_name_length'] = {} # Return cached objects without processing since the file will have # already been processed and the paths in FILES will be invalid. if (php.isset(file_save_upload.uploadcache, source)): return file_save_upload.uploadcache[source] # If a file was uploaded, process it. if (php.isset(p.FILES, 'files') and p.FILES['files']['name'][source] and \ php.is_uploaded_file(p.FILES['files']['tmp_name'][source])): # Check for file upload errors and return False if a # lower level system error occurred. # @see http://php.net/manual/en/features.file-upload.errors.php if p.FILES['files']['error'][source] == UPLOAD_ERR_OK: pass elif p.FILES['files']['error'][source] == UPLOAD_ERR_INI_SIZE or \ p.FILES['files']['error'][source] == UPLOAD_ERR_FORM_SIZE: drupal_set_message(t(\ 'The file %file could not be saved, because it exceeds %maxsize, ' + \ 'the maximum allowed size for uploads.', \ {'%file' : source, '%maxsize' : \ format_size(file_upload_max_size())}), 'error') return False elif p.FILES['files']['error'][source] == UPLOAD_ERR_PARTIAL or \ p.FILES['files']['error'][source] == UPLOAD_ERR_NO_FILE: drupal_set_message(t('The file %file could not be saved, ' + \ 'because the upload did not complete.', {'%file' : source}), 'error') return False # Unknown error else: drupal_set_message(t('The file %file could not be saved. ' + \ 'An unknown error has occurred.', {'%file' : source}), 'error') return False # Build the list of non-munged extensions. # @todo: this should not be here + we need to figure out the right place. extensions = '' for rid,name in lib_appglobals.user.roles.items(): extensions += ' ' + variable_get("upload_extensions_rid", variable_get('upload_extensions_default', \ 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp')) # Begin building file object. file = php.stdClass() file.filename = file_munge_filename(php.trim(\ basename(p.FILES['files']['name'][source]), '.'), extensions) file.filepath = p.FILES['files']['tmp_name'][source] file.filemime = p.FILES['files']['type'][source] # Rename potentially executable files, to help prevent exploits. if (php.preg_match('/\.(php|pl|py|cgi|asp|js)$/i', file.filename) and \ (php.substr(file.filename, -4) != '.txt')): file.filemime = 'text/plain' file.filepath += '.txt' file.filename += '.txt' # If the destination is not provided, or is not writable, then use the # temporary directory. if (php.empty(dest) or file_check_path(dest) == False): dest = file_directory_temp() file.source = source file.destination = file_destination(file_create_path(dest + '/' + \ file.filename), replace) file.filesize = FILES['files']['size'][source] # Call the validation functions. errors = {} for function,args in validators.items(): array_unshift(args, file) errors = php.array_merge(errors, function(*args)) # Check for validation errors. if (not php.empty(errors)): message = t('The selected file %name could not be uploaded.', \ {'%name' : file.filename}) if (php.count(errors) > 1): message += '<ul><li>' + php.implode('</li><li>', errors) + '</li></ul>' else: message += ' ' + php.array_pop(errors) form_set_error(source, message) return False # Move uploaded files from PHP's upload_tmp_dir to # Drupal's temporary directory. # This overcomes open_basedir restrictions for future file operations. file.filepath = file.destination if (not move_uploaded_file(p.FILES['files']['tmp_name'][source], \ file.filepath)): form_set_error(source, t('File upload error. ' + \ 'Could not move uploaded file.')) watchdog('file', 'Upload error + Could not move uploaded file ' + \ '%file to destination %destination.', \ {'%file' : file.filename, '%destination' : file.filepath}) return False # If we made it this far it's safe to record this file in the database. file.uid = lib_appglobals.user.uid file.status = FILE_STATUS_TEMPORARY file.timestamp = time() drupal_write_record('files', file) # Add file to the cache. file_save_upload.upload_cache[source] = file return file return False