Exemplo n.º 1
0
def cell(cell, header, ts, i):
  """
   Format a table cell.

   Adds a class attribute to all cells in the currently active column.

   @param cell
     The cell to format.
   @param header
     An array of column headers in the format described in theme_table().
   @param ts
     The current table sort context as returned from hook_init().
   @param i
     The index of the cell's table column.
   @return
     A properly formatted cell, ready for _theme_table_cell().
  """
  if (php.isset(header[i]['data']) and header[i]['data'] == ts['name'] and
     not php.empty(header[i]['field'])):
    if php.is_array(cell):
      if php.isset(cell['class']):
        cell['class'] += ' active'
      else:
        cell['class'] = 'active'
    else:
      cell = {'data': cell, 'class': 'active'}
  return cell
Exemplo n.º 2
0
def get_order(headers):
  """
   Determine the current sort criterion.

   @param headers
     An array of column headers in the format described in theme_table().
   @return
     An associative array describing the criterion, containing the keys:
     - "name": The localized title of the table column.
     - "sql": The name of the database field to sort on.
  """
  order = php.GET['order'] if php.isset(php.GET['order']) else ''
  for header in headers:
    if php.isset(header['data']) and order == header['data']:
      return {
        'name': header['data'],
        'sql': header['field'] if php.isset(header['field']) else ''
      }
    if (php.isset(header['sort']) and (header['sort'] == 'asc' or
       header['sort'] == 'desc')):
      default = {
        'name': header['data'],
        'sql': header['field'] if php.isset(header['field']) else ''
      }
  if php.isset(default):
    return default
  else:
    # The first column specified is initial 'order by' field unless otherwise
    # specified
    if php.is_array(headers[0]):
      headers[0] += {'data': None, 'field': None}
      return {'name': headers[0]['data'], 'sql': headers[0]['field']}
    else:
      return {'name': headers[0]}
Exemplo n.º 3
0
def invoke_all(*args):
  """
   Invoke a hook in all enabled plugins that implement it.
  
   @param hook
     The name of the hook to invoke.
   @param ...
     Arguments to pass to the hook.
   @return
     An array of return values of the hook implementations. If plugins return
     arrays from their implementations, those are merged into one array.
  """
  global plugins
  args = list(args)
  hook = 'hook_%s' % args[0]
  del(args[0])
  return_ = []
  for plugin_ in implements(hook):
    if (lib_bootstrap.drupal_function_exists(hook, plugins[plugin_])):
      function = DrupyImport.getFunction(\
        plugins[plugin_], hook)
      result = php.call_user_func_array(function, args);
      if (result is not None and php.is_array(result)):
        return_ = p.array_merge_recursive(return_, result);
      elif (result is not None):
        return_.append( result );
  return return_
Exemplo n.º 4
0
def prefix_tables(sql):
  """
   Append a database prefix to all tables in a query.
  
   Queries sent to Drupal should wrap all table names in curly brackets. This
   function searches for this syntax and adds Drupal's table prefix to all
   tables, allowing Drupal to coexist with other systems in the same
   database if necessary.
  
   @param sql
     A string containing a partial or entire SQL query.
   @return
     The properly-prefixed string.
  """
  if (php.is_array(settings.db_prefix)):
    if (php.array_key_exists('default', settings.db_prefix)):
      tmp = settings.db_prefix;
      del(tmp['default']);
      for key,val in tmp.items():
        sql = php.strtr(sql, {('{' + key + '}') : (val + key)});
      return php.strtr(sql, {'{' : settings.db_prefix['default'], '}' : ''});
    else:
      for key,val in settings.db_prefix.items():
        sql = php.strtr(sql, {('{' + key + '}') : (val + key)});
      return php.strtr(sql, {'{' : '', '}' : ''});
  else:
    return php.strtr(sql, {'{' : settings.db_prefix, '}' : ''});
Exemplo n.º 5
0
def field_names(fields):
  ret = []
  for field in fields:
    if (php.is_array(field)):
      ret.append( field[0] )
    else:
      ret.append( field )
  return ret
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
def header(cell, header, ts):
  """
   Format a column header.

   If the cell in question is the column header for the current sort criterion,
   it gets special formatting. All possible sort criteria become links.

   @param cell
     The cell to format.
   @param header
     An array of column headers in the format described in theme_table().
   @param ts
     The current table sort context as returned from hook_init().
   @return
     A properly formatted cell, ready for _theme_table_cell().
  """
  # Special formatting for the currently sorted column header.
  if php.is_array(cell) and php.isset(cell['field']):
    title = t('sort by @s', {'@s': cell['data']})
    if cell['data'] == ts['name']:
      ts['sort'] = ('desc' if (ts['sort'] == 'asc') else 'asc')
      if php.isset(cell['class']):
        cell['class'] += ' active'
      else:
        cell['class'] = 'active'
      image = lib_theme.theme('tablesort_indicator', ts['sort'])
    else:
      # If the user clicks a different header, we want to sort ascending
      # initially.
      ts['sort'] = 'asc'
      image = ''
    if not php.empty(ts['query_string']):
      ts['query_string'] = '&' + ts['query_string']
    cell['data'] = l(
      cell['data'] + image, php.GET['q'], {
        'attributes':
          {
            'title': title,
            'query':
              'sort=' + ts['sort'] + '&order=' + rawurlencode(cell['data']) +
              ts['query_string'],
            'html': TRUE
          }
      }
    )
    php.unset(cell['field'], cell['sort'])
  return cell
Exemplo n.º 8
0
def query_temporary(query):
  """
   Runs a SELECT query and stores its results in a temporary table.
  
   Use this as a substitute for db_query() when the results need to stored
   in a temporary table. Temporary tables exist for the duration of the page
   request.
   User-supplied arguments to the query should be passed in as
   separate parameters
   so that they can be properly escaped to avoid SQL injection attacks.
  
   Note that if you need to know how many results were returned, you should do
   a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does
   not give consistent result across different database types in this case.
  
   @param query
     A string containing a normal SELECT SQL query.
   @param ...
     A variable number of arguments which are substituted into the query
     using printf() syntax. The query arguments can be enclosed in one
     array instead.
     Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
     in '') and %%.
  
     NOTE: using this syntax will cast None and False values to decimal 0,
     and True values to decimal 1.
  
   @param table
     The name of the temporary table to select into. This name will not be
     prefixed as there is no risk of collision.
   @return
     A database query result resource, or False if the query was not executed
     correctly.
  """
  args = func_get_args()
  tablename = php.array_pop(args)
  php.array_shift(args)
  query = php.preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE ' +  \
    tablename  + ' Engine=HEAP SELECT', db_prefix_tables(query))
  # 'All arguments in one array' syntax
  if (php.isset(args, 0) and php.is_array(args, 0)): 
    args = args[0]
  _db_query_callback(args, True)
  query = php.preg_replace_callback(DB_QUERY_REGEXP, \
    '_db_query_callback', query)
  return _db_query(query)
Exemplo n.º 9
0
def get_sort(headers):
  """
   Determine the current sort direction.

   @param headers
     An array of column headers in the format described in theme_table().
   @return
     The current sort direction ("asc" or "desc").
  """
  if php.isset(php.GET['sort']):
    return 'desc' if (php.GET['sort'] == 'desc')  else 'asc';
  # User has not specified a sort. Use default if specified; otherwise use
  # "asc".
  else:
    for header in headers:
      if php.is_array(header) and php.array_key_exists('sort', header):
        return header['sort']
  return 'asc'
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
def query_range(query):
    """
   Runs a limited-range query in the active database.
  
   Use this as a substitute for db_query() when a subset of the query is to be
   returned. User-supplied arguments to the query should be passed in as
   separate parameters so that they can be properly escaped to avoid SQL
   injection attacks.
  
   @param query
     A string containing an SQL query.
   @param ...
     A variable number of arguments which are substituted into the query
     using printf() syntax. The query arguments can be enclosed in one
     array instead.
     Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
     in '') and %%.
     NOTE: using this syntax will cast None and False values to decimal 0,
     and True values to decimal 1.
   @param from
     The first result row to return.
   @param count
     The maximum number of result rows to return.
   @return
     A database query result resource, or False if the query was not executed
     correctly.
  """
    args = func_get_args()
    count = php.array_pop(args)
    from_ = php.array_pop(args)
    php.array_shift(args)
    query = db_prefix_tables(query)
    # 'All arguments in one array' syntax
    if (php.isset(args, 0) and php.is_array(args, 0)):
        args = args[0]
    _db_query_callback(args, True)
    query = php.preg_replace_callback(DB_QUERY_REGEXP, \
      '_db_query_callback', query)
    query += ' LIMIT ' + int(from_) + ', '.int(count)
    return _db_query(query)
Exemplo n.º 12
0
def query_range(query):
  """
   Runs a limited-range query in the active database.
  
   Use this as a substitute for db_query() when a subset of the query is to be
   returned. User-supplied arguments to the query should be passed in as
   separate parameters so that they can be properly escaped to avoid SQL
   injection attacks.
  
   @param query
     A string containing an SQL query.
   @param ...
     A variable number of arguments which are substituted into the query
     using printf() syntax. The query arguments can be enclosed in one
     array instead.
     Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
     in '') and %%.
     NOTE: using this syntax will cast None and False values to decimal 0,
     and True values to decimal 1.
   @param from
     The first result row to return.
   @param count
     The maximum number of result rows to return.
   @return
     A database query result resource, or False if the query was not executed
     correctly.
  """
  args = func_get_args()
  count = php.array_pop(args)
  from_ = php.array_pop(args)
  php.array_shift(args)
  query = db_prefix_tables(query)
  # 'All arguments in one array' syntax
  if (php.isset(args, 0) and php.is_array(args, 0)): 
    args = args[0]
  _db_query_callback(args, True)
  query = php.preg_replace_callback(DB_QUERY_REGEXP, \
    '_db_query_callback', query)
  query += ' LIMIT ' +  int(from_)  + ', ' . int(count)
  return _db_query(query)
Exemplo n.º 13
0
def drupal_is_denied(ip):
    """
   Check to see if an IP address has been blocked.
  
   Blocked IP addresses are stored in the database by default. However for
   performance reasons we allow an override in settings.php. This allows us
   to avoid querying the database at this critical stage of the bootstrap if
   an administrative interface for IP address blocking is not required.
  
   @param $ip string
     IP address to check.
   @return bool
     TRUE if access is denied, FALSE if access is allowed.
  """
    # Because this function is called on every page request, we first check
    # for an array of IP addresses in settings.php before querying the
    # database.
    blocked_ips = variable_get("blocked_ips", None)
    if blocked_ips != None and php.is_array(blocked_ips):
        return php.in_array(ip, blocked_ips)
    else:
        sql = "SELECT 1 FROM {blocked_ips} WHERE ip = '%s'"
        return lib_database.result(lib_database.query(sql, ip)) != False
Exemplo n.º 14
0
def drupal_is_denied(ip):
    """
   Check to see if an IP address has been blocked.
  
   Blocked IP addresses are stored in the database by default. However for
   performance reasons we allow an override in settings.php. This allows us
   to avoid querying the database at this critical stage of the bootstrap if
   an administrative interface for IP address blocking is not required.
  
   @param $ip string
     IP address to check.
   @return bool
     TRUE if access is denied, FALSE if access is allowed.
  """
    # Because this function is called on every page request, we first check
    # for an array of IP addresses in settings.php before querying the
    # database.
    blocked_ips = variable_get('blocked_ips', None)
    if (blocked_ips != None and php.is_array(blocked_ips)):
        return php.in_array(ip, blocked_ips)
    else:
        sql = "SELECT 1 FROM {blocked_ips} WHERE ip = '%s'"
        return (lib_database.result(lib_database.query(sql, ip)) != False)
Exemplo n.º 15
0
def query(query_, *args):
    """
   Runs a basic query in the active database.
  
   User-supplied arguments to the query should be passed in as separate
   parameters so that they can be properly escaped to avoid SQL injection
   attacks.
  
   @param query
     A string containing an SQL query.
   @param ...
     A variable number of arguments which are substituted into the query
     using printf() syntax. Instead of a variable number of query arguments,
     you may also pass a single array containing the query arguments.
  
     Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
     in '') and %%.
  
     NOTE: using this syntax will cast None and False values to decimal 0,
    and True values to decimal 1.
  
   @return
     A database query result resource, or False if the query was not
     executed correctly.
  """
    this_query = lib_database.prefix_tables(query_)
    # 'All arguments in one array' syntax
    if (php.isset(args, 0) and php.is_array(args[0])):
        args = args[0]
    lib_database._query_callback(args, True)
    this_query = php.preg_replace_callback(lib_database.DB_QUERY_REGEXP, \
      lib_database._query_callback, this_query)
    #print
    #print "QUERY DEBUG:"
    #print this_query
    #print
    return _query(this_query)
Exemplo n.º 16
0
def query(query_, *args):
  """
   Runs a basic query in the active database.
  
   User-supplied arguments to the query should be passed in as separate
   parameters so that they can be properly escaped to avoid SQL injection
   attacks.
  
   @param query
     A string containing an SQL query.
   @param ...
     A variable number of arguments which are substituted into the query
     using printf() syntax. Instead of a variable number of query arguments,
     you may also pass a single array containing the query arguments.
  
     Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
     in '') and %%.
  
     NOTE: using this syntax will cast None and False values to decimal 0,
    and True values to decimal 1.
  
   @return
     A database query result resource, or False if the query was not
     executed correctly.
  """
  this_query = lib_database.prefix_tables(query_)
  # 'All arguments in one array' syntax
  if (php.isset(args, 0) and php.is_array(args[0])): 
    args = args[0]
  lib_database._query_callback(args, True)
  this_query = php.preg_replace_callback(lib_database.DB_QUERY_REGEXP, \
    lib_database._query_callback, this_query)
  #print
  #print "QUERY DEBUG:"
  #print this_query
  #print
  return _query(this_query)
Exemplo n.º 17
0
def _build_dependencies(files):
    """
   Find dependencies any level deep and fill in dependents information too.
  
   If plugin A depends on B which in turn depends on C then this function will
   add C to the list of plugins A depends on. This will be repeated until
   plugin A has a list of all plugins it depends on. If it depends on itself,
   called a circular dependency, that's marked by adding a nonexistent plugin,
   called -circular- to this list of plugins. Because this does not exist,
   it'll be impossible to switch plugin A on.
  
   Also we fill in a dependents array in file.info. Using the names above,
   the dependents array of plugin B lists A.
  
   @param files
     The array of filesystem objects used to rebuild the cache.
   @return
     The same array with dependencies and dependents added where applicable.
  """
    while True:
        new_dependency = False
        for filename, file in files.items():
            # We will modify this object (plugin A, see doxygen for plugin A, B, C).
            file = files[filename]
            if (php.isset(file.info, 'dependencies') and \
                php.is_array(file.info, 'dependencies')):
                for dependency_name in file.info['dependencies']:
                    # This is a nonexistent plugin.
                    if (dependency_name == '-circular-' or \
                        not php.isset(files[dependency_name])):
                        continue
                    # dependency_name is plugin B (again, see doxygen).
                    files[dependency_name].info['dependents'][
                        filename] = filename
                    dependency = files[dependency_name]
                    if (php.isset(dependency.info['dependencies']) and \
                        php.is_array(dependency.info['dependencies'])):
                        # Let's find possible C plugins.
                        for candidate in dependency.info['dependencies']:
                            if (array_search(
                                    candidate,
                                    file.info['dependencies']) == False):
                                # Is this a circular dependency?
                                if (candidate == filename):
                                    # As a plugin name can not contain dashes, this makes
                                    # impossible to switch on the plugin.
                                    candidate = '-circular-'
                                    # Do not display the message or add -circular-
                                    # more than once.
                                    if (array_search(candidate, \
                                        file.info['dependencies']) != False):
                                        continue
                                    drupal_set_message(\
                                      t('%plugin is part of a circular dependency. ' + \
                                        'This is not supported and you will not ' + \
                                        'be able to switch it on.', \
                                        {'%plugin' : file.info['name']}), 'error')
                                else:
                                    # We added a new dependency to plugin A. The next loop will
                                    # be able to use this as "B plugin" thus finding even
                                    # deeper dependencies.
                                    new_dependency = True
                                file.info['dependencies'].append(candidate)
            # Don't forget to break the reference.
            del (file)
        if (not new_dependency):
            break
    return files
Exemplo n.º 18
0
def _build_dependencies(files):
  """
   Find dependencies any level deep and fill in dependents information too.
  
   If plugin A depends on B which in turn depends on C then this function will
   add C to the list of plugins A depends on. This will be repeated until
   plugin A has a list of all plugins it depends on. If it depends on itself,
   called a circular dependency, that's marked by adding a nonexistent plugin,
   called -circular- to this list of plugins. Because this does not exist,
   it'll be impossible to switch plugin A on.
  
   Also we fill in a dependents array in file.info. Using the names above,
   the dependents array of plugin B lists A.
  
   @param files
     The array of filesystem objects used to rebuild the cache.
   @return
     The same array with dependencies and dependents added where applicable.
  """
  while True:
    new_dependency = False
    for filename,file in files.items():
      # We will modify this object (plugin A, see doxygen for plugin A, B, C).
      file = files[filename]
      if (php.isset(file.info, 'dependencies') and \
          php.is_array(file.info, 'dependencies')):
        for dependency_name in file.info['dependencies']:
          # This is a nonexistent plugin.
          if (dependency_name == '-circular-' or \
              not php.isset(files[dependency_name])):
            continue
          # dependency_name is plugin B (again, see doxygen).
          files[dependency_name].info['dependents'][filename] = filename
          dependency = files[dependency_name]
          if (php.isset(dependency.info['dependencies']) and \
              php.is_array(dependency.info['dependencies'])):
            # Let's find possible C plugins.
            for candidate in dependency.info['dependencies']:
              if (array_search(candidate, file.info['dependencies']) == False):
                # Is this a circular dependency?
                if (candidate == filename):
                  # As a plugin name can not contain dashes, this makes
                  # impossible to switch on the plugin.
                  candidate = '-circular-'
                  # Do not display the message or add -circular-
                  # more than once.
                  if (array_search(candidate, \
                      file.info['dependencies']) != False):
                    continue
                  drupal_set_message(\
                    t('%plugin is part of a circular dependency. ' + \
                      'This is not supported and you will not ' + \
                      'be able to switch it on.', \
                      {'%plugin' : file.info['name']}), 'error')
                else:
                  # We added a new dependency to plugin A. The next loop will
                  # be able to use this as "B plugin" thus finding even
                  # deeper dependencies.
                  new_dependency = True
                file.info['dependencies'].append( candidate )
      # Don't forget to break the reference.
      del(file)
    if (not new_dependency):
      break
  return files