def theme_preprocess_page(vars_): """ Override or insert variables into the page template. """ php.Reference.check(vars_) vars_['tabs2'] = menu_secondary_local_tasks() vars_['primary_nav'] = (lib_theme.theme('links', \ vars_['main_menu'], {'class' : 'links main-menu'}) if \ php.isset(vars_, 'main_menu') else False) vars_['secondary_nav'] = (lib_theme.theme('links', \ vars_['secondary_menu'], \ {'class' : 'links secondary-menu'}) if \ php.isset(vars_, 'secondary_menu') else False) vars_['ie_styles'] = get_ie_styles() # Prepare header site_fields = [] if (not php.empty(vars_['site_name'])): site_fields.append( check_plain(vars_['site_name']) ) if (not php.empty(vars_['site_slogan'])): site_fields.append( check_plain(vars_['site_slogan']) ) vars_['site_title'] = php.implode(' ', site_fields) if (not php.empty(site_fields)): site_fields[0] = '<span>' + site_fields[0] + '</span>' vars_['site_html'] = php.implode(' ', site_fields) # Hook into color.module if (lib_plugin.exists('color')): lib_plugin.plugins['color']._page_alter(vars_)
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 create_table_sql(name, table): """ Generate SQL to create a new table from a Drupal schema definition. @param name The name of the table to create. @param table A Schema API table definition array. @return An array of SQL statements to create the table. """ if (php.empty(table['mysql_suffix'])): table['mysql_suffix'] = "/*not 40100 DEFAULT CHARACTER SET UTF8 */" sql = "CREATE TABLE {" + name + "} (\n" # Add the SQL statement for each field. for field_name, field in table['fields'].items(): sql += _db_create_field_sql(field_name, _db_process_field(field)) + ", \n" # Process keys & indexes. keys = _db_create_keys_sql(table) if (php.count(keys)): sql += php.implode(", \n", keys) + ", \n" # Remove the last comma and space. sql = php.substr(sql, 0, -3) + "\n) " sql += table['mysql_suffix'] return array(sql)
def create_table_sql(name, table): """ Generate SQL to create a new table from a Drupal schema definition. @param name The name of the table to create. @param table A Schema API table definition array. @return An array of SQL statements to create the table. """ if (php.empty(table['mysql_suffix'])): table['mysql_suffix'] = "/*not 40100 DEFAULT CHARACTER SET UTF8 */" sql = "CREATE TABLE {" + name + "} (\n" # Add the SQL statement for each field. for field_name,field in table['fields'].items(): sql += _db_create_field_sql(field_name, _db_process_field(field)) + ", \n" # Process keys & indexes. keys = _db_create_keys_sql(table) if (php.count(keys)): sql += php.implode(", \n", keys) + ", \n" # Remove the last comma and space. sql = php.substr(sql, 0, -3) + "\n) " sql += table['mysql_suffix'] return array(sql)
def _create_key_sql(fields): ret = [] for field in fields: if (php.is_array(field)): ret.append(field[0] + '(' + field[1] + ')') else: ret.append(field) return php.implode(', ', ret)
def _create_key_sql(fields): ret = [] for field in fields: if (php.is_array(field)): ret.append( field[0] + '(' + field[1] + ')' ) else: ret.append( field ) return php.implode(', ', ret)
def theme_breadcrumb(breadcrumb): """ Return a themed breadcrumb trail. @param breadcrumb An array containing the breadcrumb links. @return a string containing the breadcrumb output. """ if (not php.empty(breadcrumb)): return '<div class="breadcrumb">' + \ php.implode(' › ', breadcrumb) + '</div>'
def _rewrite_sql(query = '', primary_table = 'n', primary_field = 'nid', \ args = []): where = [] join_ = [] distinct = False for plugin in lib_plugin.implements('db_rewrite_sql'): result = lib_plugin.invoke(plugin, 'db_rewrite_sql', query, \ primary_table, primary_field, args) if (php.isset(result) and php.is_array(result)): if (php.isset(result['where'])): where.append( result['where'] ) if (php.isset(result['join'])): join_.append( result['join'] ) if (php.isset(result['distinct']) and result['distinct']): distinct = True elif (php.isset(result)): where.append( result ) where = ('' if php.empty(where) else \ ('(' + php.implode(') AND (', where) + ')') ) join_ = ('' if php.empty(join) else php.implode(' ', join)) return (join, where, distinct)
def placeholders(arguments, type = 'int'): """ Generate placeholders for an array of query arguments of a single type. Given a Schema API field type, return correct %-placeholders to embed in a query @param arguments An array with at least one element. @param type The Schema API type of a field (e.g. 'int', 'text', or 'varchar'). """ placeholder = db_type_placeholder(type); return php.implode(',', php.array_fill(0, php.count(arguments), \ placeholder));
def add_field(ret, table, field, spec, keys_new=[]): """ Add a new field to a table. @param ret Array to which query results will be added. @param table Name of the table to be altered. @param field Name of the field to be added. @param spec The field specification array, as taken from a schema definition. The specification may also contain the key 'initial', the newly created field will be set to the value of the key in all rows. This is most useful for creating NOT None columns with no default value in existing tables. @param keys_new Optional keys and indexes specification to be created on the table along with adding the field. The format is the same as a table specification but without the 'fields' element. If you are adding a type 'serial' field, you MUST specify at least one key or index including it in this array. @see db_change_field for more explanation why. """ php.Reference.check(ret) fixNone = False if (not php.empty(spec['not None']) and not php.isset(spec, 'default')): fixNone = True spec['not None'] = False query = 'ALTER TABLE {' + table + '} ADD ' query += _db_create_field_sql(field, _db_process_field(spec)) if (php.count(keys_new)): query += ', ADD ' + php.implode(', ADD ', _db_create_keys_sql(keys_new)) ret.append(update_sql(query)) if (php.isset(spec, 'initial')): # All this because update_sql does not support %-placeholders. sql = 'UPDATE {' + table + '} SET ' + field + ' = ' + \ db_type_placeholder(spec['type']) result = db_query(sql, spec['initial']) ret.append( {'success' : result != False, \ 'query' : check_plain(sql + ' (' + spec['initial'] + ')')}) if (fixNone): spec['not None'] = True db_change_field(ret, table, field, field, spec)
def initialize(): """ Choose a language for the page, based on language negotiation settings. """ # Configured presentation language mode. mode = variable_get('language_negotiation', \ lib_bootstrap.LANGUAGE_NEGOTIATION_NONE) # Get a list of enabled languages. languages = lib_bootstrap.language_list('enabled') languages = languages[1] if mode == lib_bootstrap.LANGUAGE_NEGOTIATION_NONE: return language_default() elif mode == lib_bootstrap.LANGUAGE_NEGOTIATION_DOMAIN: for language in languages: parts = php.parse_url(language.domain) if (not php.empty(parts['host']) and \ (php.SERVER['php.SERVER_NAME'] == parts['host'])): return language return language_default() elif mode == lib_bootstrap.LANGUAGE_NEGOTIATION_PATH_DEFAULT or \ mode == lib_bootstrap.LANGUAGE_NEGOTIATION_PATH: # _GET['q'] might not be available at this time, because # path initialization runs after the language bootstrap phase. args = (php.explode('/', _GET['q']) if php.isset(_GET, 'q') else []) prefix = php.array_shift(args) # Search prefix within enabled languages. for language in languages: if (not php.empty(language.prefix) and language.prefix == prefix): # Rebuild php.GET['q'] with the language removed. php.GET['q'] = php.implode('/', args) return language if (mode == LANGUAGE_NEGOTIATION_PATH_DEFAULT): # If we did not found the language by prefix, choose the default. return language_default() # User language. if (lib_appglobals.user.uid and \ php.isset(languages[lib_appglobals.user.language])): return languages[lib_appglobals.user.language] # Browser accept-language parsing. language = language_from_browser() if (language): return language # Fall back on the default if everything else fails. return language_default()
def add_field(ret, table, field, spec, keys_new = []): """ Add a new field to a table. @param ret Array to which query results will be added. @param table Name of the table to be altered. @param field Name of the field to be added. @param spec The field specification array, as taken from a schema definition. The specification may also contain the key 'initial', the newly created field will be set to the value of the key in all rows. This is most useful for creating NOT None columns with no default value in existing tables. @param keys_new Optional keys and indexes specification to be created on the table along with adding the field. The format is the same as a table specification but without the 'fields' element. If you are adding a type 'serial' field, you MUST specify at least one key or index including it in this array. @see db_change_field for more explanation why. """ php.Reference.check(ret) fixNone = False if (not php.empty(spec['not None']) and not php.isset(spec, 'default')): fixNone = True spec['not None'] = False query = 'ALTER TABLE {' + table + '} ADD ' query += _db_create_field_sql(field, _db_process_field(spec)) if (php.count(keys_new)): query += ', ADD ' + php.implode(', ADD ', _db_create_keys_sql(keys_new)) ret.append( update_sql(query) ) if (php.isset(spec, 'initial')): # All this because update_sql does not support %-placeholders. sql = 'UPDATE {' + table + '} SET ' + field + ' = ' + \ db_type_placeholder(spec['type']) result = db_query(sql, spec['initial']) ret.append( {'success' : result != False, \ 'query' : check_plain(sql + ' (' + spec['initial'] + ')')}) if (fixNone): spec['not None'] = True db_change_field(ret, table, field, field, spec)
def download(): """ Call plugins that implement hook_file_download() to find out if a file is accessible and what headers it should be transferred with + If a plugin returns -1 drupal_access_denied() will be returned + If one or more plugins returned headers the download will start with the returned headers + If no plugins respond drupal_not_found() will be returned. """ # Merge remainder of arguments from php.GET['q'], into relative file path. args = func_get_args() filepath = php.implode('/', args) # Maintain compatibility with old ?file=paths saved in node bodies. if (php.isset(php.GET, 'file')): filepath = php.GET['file'] if (php.file_exists(file_create_path(filepath))): headers = plugin_invoke_all('file_download', filepath) if (php.in_array(-1, headers)): return drupal_access_denied() if (php.count(headers)): file_transfer(filepath, headers) return drupal_not_found()
def template_preprocess_maintenance_page(variables): """ The variables generated here is a mirror of template_preprocess_page(). This preprocessor will run it's course when theme_maintenance_page() is invoked. It is also used in theme_install_page() and theme_update_page() to keep all the variables consistent. An alternate template file of "maintenance-page-offline.tpl.php" can be used when the database is offline to hide errors and completely replace the content. The variables array contains the following arguments: - content - show_blocks @see maintenance-page.tpl.php """ php.Reference.check(variables) # Add favicon if (theme_get_setting('toggle_favicon')): drupal_set_html_head('<link rel="shortcut icon" href="' + \ check_url(theme_get_setting('favicon')) + '" type="image/x-icon" />'); # Retrieve the theme data to list all available regions. theme_data = _system_theme_data() regions = theme_data[lib_appglobals.theme].info['regions'] # Get all region content set with drupal_set_content(). for region in php.array_keys(regions): # Assign region to a region variable. region_content = drupal_get_content(region) if php.isset(variables, region): variables[region] += region_content else: variables[region] = region_content # Setup layout variable. variables['layout'] = 'none' if (not php.empty(variables['left'])): variables['layout'] = 'left' if (not php.empty(variables['right'])): variables['layout'] = ('both' if \ (variables['layout'] == 'left') else 'right') # Construct page title if (drupal_get_title()): head_title = [strip_tags(drupal_get_title()), \ variable_get('site_name', 'Drupal')]; else: head_title = [variable_get('site_name', 'Drupal')] if (variable_get('site_slogan', '')): head_title.append( variable_get('site_slogan', '') ) variables['head_title'] = php.implode(' | ', head_title) variables['base_path'] = base_path() variables['front_page'] = url() variables['breadcrumb'] = '' variables['feed_icons'] = '' variables['footer_message'] = \ filter_xss_admin(variable_get('site_footer', FALSE)) variables['head'] = drupal_get_html_head() variables['help'] = '' variables['language'] = lib_appglobals.language variables['language'].dir = \ ('rtl' if lib_appglobals.language.direction else 'ltr') variables['logo'] = theme_get_setting('logo'); variables['messages'] = (theme('status_messages') if \ variables['show_messages'] else '') variables['mission'] = ''; variables['main_menu'] = []; variables['secondary_menu'] = []; variables['search_box'] = ''; variables['site_name'] = \ (variable_get('site_name', 'Drupal') if \ theme_get_setting('toggle_name') else '') variables['site_slogan'] = (variable_get('site_slogan', '') if \ theme_get_setting('toggle_slogan') else '') variables['css'] = drupal_add_css() variables['styles'] = drupal_get_css() variables['scripts'] = drupal_get_js() variables['tabs'] = '' variables['title'] = drupal_get_title(); variables['closure'] = '' # Compile a list of classes that are going to be applied to the body element. body_classes = [] body_classes.append( 'in-maintenance' ) if (php.isset(variables, 'db_is_active') and \ not variables['db_is_active']): body_classes.append( 'db-offline' ) if (variables['layout'] == 'both'): body_classes.append( 'two-sidebars' ) elif (variables['layout'] == 'none'): body_classes.append( 'no-sidebars' ) else: body_classes.append( 'one-sidebar sidebar-' + variables['layout'] ) variables['body_classes'] = php.implode(' ', body_classes) # Dead databases will show error messages so supplying this template will # allow themers to override the page and the content completely. if (php.isset(variables, 'db_is_active') and \ not variables['db_is_active']): variables['template_file'] = 'maintenance-page-offline';
def change_field(ret, table, field, field_new, spec, keys_new = []): """ Change a field definition. IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field. That means that you have to drop all affected keys and indexes with db_drop_{primary_key,unique_key,index}() before calling db_change_field(). To recreate the keys and indices, pass the key definitions as the optional keys_new argument directly to db_change_field(). For example, suppose you have: @code schema['foo'] = array( 'fields' : array( 'bar' : array('type' : 'int', 'not None' : True) ), 'primary key' : array('bar') ) @endcode and you want to change foo.bar to be type serial, leaving it as the primary key. The correct sequence is: @code db_drop_primary_key(ret, 'foo') db_change_field(ret, 'foo', 'bar', 'bar', array('type' : 'serial', 'not None' : True), array('primary key' : array('bar'))) @endcode The reasons for this are due to the different database engines: On PostgreSQL, changing a field definition involves adding a new field and dropping an old one which* causes any indices, primary keys and sequences (from serial-type fields) that use the changed field to be dropped. On MySQL, all type 'serial' fields must be part of at least one key or index as soon as they are created. You cannot use db_add_{primary_key,unique_key,index}() for this purpose because the ALTER TABLE command will fail to add the column without a key or index specification. The solution is to use the optional keys_new argument to create the key or index at the same time as field. You could use db_add_{primary_key,unique_key,index}() in all cases unless you are converting a field to be type serial. You can use the keys_new argument in all cases. @param ret Array to which query results will be added. @param table Name of the table. @param field Name of the field to change. @param field_new New name for the field (set to the same as field if you don't want to change the name). @param spec The field specification for the new field. @param keys_new Optional keys and indexes specification to be created on the table along with changing the field. The format is the same as a table specification but without the 'fields' element. """ php.Reference.check(ret) sql = 'ALTER TABLE {' + table + '} CHANGE ' + field + ' ' + \ _db_create_field_sql(field_new, _db_process_field(spec)) if (php.count(keys_new) > 0): sql += ', ADD ' + php.implode(', ADD ', _db_create_keys_sql(keys_new)) ret.append( update_sql(sql) )
def template_preprocess_maintenance_page(variables): """ The variables generated here is a mirror of template_preprocess_page(). This preprocessor will run it's course when theme_maintenance_page() is invoked. It is also used in theme_install_page() and theme_update_page() to keep all the variables consistent. An alternate template file of "maintenance-page-offline.tpl.php" can be used when the database is offline to hide errors and completely replace the content. The variables array contains the following arguments: - content - show_blocks @see maintenance-page.tpl.php """ php.Reference.check(variables) # Add favicon if (theme_get_setting('toggle_favicon')): drupal_set_html_head('<link rel="shortcut icon" href="' + \ check_url(theme_get_setting('favicon')) + '" type="image/x-icon" />') # Retrieve the theme data to list all available regions. theme_data = _system_theme_data() regions = theme_data[lib_appglobals.theme].info['regions'] # Get all region content set with drupal_set_content(). for region in php.array_keys(regions): # Assign region to a region variable. region_content = drupal_get_content(region) if php.isset(variables, region): variables[region] += region_content else: variables[region] = region_content # Setup layout variable. variables['layout'] = 'none' if (not php.empty(variables['left'])): variables['layout'] = 'left' if (not php.empty(variables['right'])): variables['layout'] = ('both' if \ (variables['layout'] == 'left') else 'right') # Construct page title if (drupal_get_title()): head_title = [strip_tags(drupal_get_title()), \ variable_get('site_name', 'Drupal')] else: head_title = [variable_get('site_name', 'Drupal')] if (variable_get('site_slogan', '')): head_title.append(variable_get('site_slogan', '')) variables['head_title'] = php.implode(' | ', head_title) variables['base_path'] = base_path() variables['front_page'] = url() variables['breadcrumb'] = '' variables['feed_icons'] = '' variables['footer_message'] = \ filter_xss_admin(variable_get('site_footer', FALSE)) variables['head'] = drupal_get_html_head() variables['help'] = '' variables['language'] = lib_appglobals.language variables['language'].dir = \ ('rtl' if lib_appglobals.language.direction else 'ltr') variables['logo'] = theme_get_setting('logo') variables['messages'] = (theme('status_messages') if \ variables['show_messages'] else '') variables['mission'] = '' variables['main_menu'] = [] variables['secondary_menu'] = [] variables['search_box'] = '' variables['site_name'] = \ (variable_get('site_name', 'Drupal') if \ theme_get_setting('toggle_name') else '') variables['site_slogan'] = (variable_get('site_slogan', '') if \ theme_get_setting('toggle_slogan') else '') variables['css'] = drupal_add_css() variables['styles'] = drupal_get_css() variables['scripts'] = drupal_get_js() variables['tabs'] = '' variables['title'] = drupal_get_title() variables['closure'] = '' # Compile a list of classes that are going to be applied to the body element. body_classes = [] body_classes.append('in-maintenance') if (php.isset(variables, 'db_is_active') and \ not variables['db_is_active']): body_classes.append('db-offline') if (variables['layout'] == 'both'): body_classes.append('two-sidebars') elif (variables['layout'] == 'none'): body_classes.append('no-sidebars') else: body_classes.append('one-sidebar sidebar-' + variables['layout']) variables['body_classes'] = php.implode(' ', body_classes) # Dead databases will show error messages so supplying this template will # allow themers to override the page and the content completely. if (php.isset(variables, 'db_is_active') and \ not variables['db_is_active']): variables['template_file'] = 'maintenance-page-offline'
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
def change_field(ret, table, field, field_new, spec, keys_new=[]): """ Change a field definition. IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field. That means that you have to drop all affected keys and indexes with db_drop_{primary_key,unique_key,index}() before calling db_change_field(). To recreate the keys and indices, pass the key definitions as the optional keys_new argument directly to db_change_field(). For example, suppose you have: @code schema['foo'] = array( 'fields' : array( 'bar' : array('type' : 'int', 'not None' : True) ), 'primary key' : array('bar') ) @endcode and you want to change foo.bar to be type serial, leaving it as the primary key. The correct sequence is: @code db_drop_primary_key(ret, 'foo') db_change_field(ret, 'foo', 'bar', 'bar', array('type' : 'serial', 'not None' : True), array('primary key' : array('bar'))) @endcode The reasons for this are due to the different database engines: On PostgreSQL, changing a field definition involves adding a new field and dropping an old one which* causes any indices, primary keys and sequences (from serial-type fields) that use the changed field to be dropped. On MySQL, all type 'serial' fields must be part of at least one key or index as soon as they are created. You cannot use db_add_{primary_key,unique_key,index}() for this purpose because the ALTER TABLE command will fail to add the column without a key or index specification. The solution is to use the optional keys_new argument to create the key or index at the same time as field. You could use db_add_{primary_key,unique_key,index}() in all cases unless you are converting a field to be type serial. You can use the keys_new argument in all cases. @param ret Array to which query results will be added. @param table Name of the table. @param field Name of the field to change. @param field_new New name for the field (set to the same as field if you don't want to change the name). @param spec The field specification for the new field. @param keys_new Optional keys and indexes specification to be created on the table along with changing the field. The format is the same as a table specification but without the 'fields' element. """ php.Reference.check(ret) sql = 'ALTER TABLE {' + table + '} CHANGE ' + field + ' ' + \ _db_create_field_sql(field_new, _db_process_field(spec)) if (php.count(keys_new) > 0): sql += ', ADD ' + php.implode(', ADD ', _db_create_keys_sql(keys_new)) ret.append(update_sql(sql))