当前位置: 首页>>代码示例>>Python>>正文


Python DrupyPHP.trim方法代码示例

本文整理汇总了Python中lib.drupy.DrupyPHP.trim方法的典型用法代码示例。如果您正苦于以下问题:Python DrupyPHP.trim方法的具体用法?Python DrupyPHP.trim怎么用?Python DrupyPHP.trim使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lib.drupy.DrupyPHP的用法示例。


在下文中一共展示了DrupyPHP.trim方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: munge_filename

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import trim [as 别名]
def munge_filename(filename, extensions, alerts = True):
  """
   Munge the filename as needed for security purposes + For instance the file
   name "exploit.php.pps" would become "exploit.php_.pps".
  
   @param filename The name of a file to modify.
   @param extensions A space separated list of extensions that should not
     be altered.
   @param alerts Whether alerts (watchdog, drupal_set_message()) should be
     displayed.
   @return filename The potentially modified filename.
  """
  original = filename
  # Allow potentially insecure uploads for very savvy users and admin
  if (not variable_get('allow_insecure_uploads', 0)):
    whitelist = array_unique(php.explode(' ', php.trim(extensions)))
    # Split the filename up by periods + The first part becomes the basename
    # the last part the final extension.
    filename_parts = php.explode('.', filename)
    new_filename = php.array_shift(filename_parts); # Remove file basename.
    final_extension = php.array_pop(filename_parts); # Remove final extension.
    # Loop through the middle parts of the name and add an underscore to the
    # end of each section that could be a file extension but isn't in the list
    # of allowed extensions.
    for filename_part in filename_parts:
      new_filename += '.' + filename_part
      if (not php.in_array(filename_part, whitelist) and \
          php.preg_match("/^[a-zA-Z]{2,5}\d?$/", filename_part)):
        new_filename += '_'
    filename = new_filename + '.' + final_extension
    if (alerts and original != filename):
      drupal_set_message(t('For security reasons, your upload has ' + \
        'been renamed to %filename.', {'%filename' : filename}))
  return filename
开发者ID:brendoncrawford,项目名称:drupy,代码行数:36,代码来源:file.py

示例2: _query_callback

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import trim [as 别名]
def _query_callback(match, init = False):
  """
   Helper function for db_query().
  """
  php.static(_query_callback, 'args')
  if (init):
    _query_callback.args = list(match);
    return;
  # We must use type casting to int to convert FALSE/NULL/(TRUE?)
  if match[1] == '%d': 
    # We don't need db_escape_string as numbers are db-safe
    return str(int(php.array_shift(_query_callback.args))); 
  elif match[1] == '%s':
    return db.escape_string(php.array_shift(_query_callback.args));
  elif match[1] == '%n':
    # Numeric values have arbitrary precision, so can't be treated as float.
    # is_numeric() allows hex values (0xFF), but they are not valid.
    value = php.trim(php.array_shift(args));
    return  (value if (php.is_numeric(value) and not \
      php.stripos(value, 'x')) else '0')
  elif match[1] == '%%':
    return '%';
  elif match[1] == '%f':
    return float(php.array_shift(_query_callback.args));
  elif match[1] == '%b': # binary data
    return db.encode_blob(php.array_shift(_query_callback.args));
开发者ID:brendoncrawford,项目名称:drupy,代码行数:28,代码来源:database.py

示例3: drupal_init_path

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import trim [as 别名]
def drupal_init_path():
  """
   Initialize the php.GET['q'] variable to the proper normal path.
  """
  if (php.isset(php.GET, 'q') and not php.empty(php.GET['q'])):
    php.GET['q'] = drupal_get_normal_path(php.trim(php.GET['q'], '/'))
  else:
    php.GET['q'] = drupal_get_normal_path( \
      lib_bootstrap.variable_get('site_frontpage', 'node'))
开发者ID:brendoncrawford,项目名称:drupy,代码行数:11,代码来源:path.py

示例4: create_url

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import trim [as 别名]
def create_url(path):
  """
   Create the download path to a file.
  
   @param path A string containing the path of the file to generate URL for.
   @return A string containing a URL that can be used to download the file.
  """
  # Strip file_directory_path from path + We only include relative paths in urls.
  if (php.strpos(path, file_directory_path() + '/') == 0):
    path = php.trim(php.substr(path, php.strlen(file_directory_path())), '\\/')
  dls = variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC);
  if dls == FILE_DOWNLOADS_PUBLIC:
    return settings.base_url + '/' + file_directory_path() + '/' + \
      php.str_replace('\\', '/', path)
  elif dls == FILE_DOWNLOADS_PRIVATE:
    return url('system/files/' + path, {'absolute' : True})
开发者ID:brendoncrawford,项目名称:drupy,代码行数:18,代码来源:file.py

示例5: from_browser

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import trim [as 别名]
def from_browser():
  """
   Identify language from the Accept-language HTTP php.header we got.
  """
  # Specified by the user via the browser's Accept Language setting
  # Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
  browser_langs = []
  if (php.isset(php.SERVER, 'HTTP_ACCEPT_LANGUAGE')):
    browser_accept = php.explode(",", php.SERVER['HTTP_ACCEPT_LANGUAGE'])
    for i in range(php.count(browser_accept)):
      # The language part is either a code or a code with a quality.
      # We cannot do anything with a * code, so it is skipped.
      # If the quality is missing, it is assumed to be 1 according to the RFC.
      if (php.preg_match("not ([a-z-]+)(;q=([0-9\\.]+))?not ", \
          php.trim(browser_accept[i]), found)):
        browser_langs[found[1]] = (float(found[3]) if \
          php.isset(found, 3) else 1.0)
  # Order the codes by quality
  arsort(browser_langs)
  # Try to find the first preferred language we have
  languages = language_list('enabled')
  for langcode,q in browser_langs.items():
    if (php.isset(languages['1'], langcode)):
      return languages['1'][langcode]
开发者ID:brendoncrawford,项目名称:drupy,代码行数:26,代码来源:language.py

示例6: conf_init

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import trim [as 别名]
def conf_init():
    """
   Loads the configuration and sets the base URL, cookie domain, and
   session name correctly.
  """
    # These will come from settings
    # db_url, db_prefix, cookie_domain, conf, installed_profile, update_free_access
    if lib_appglobals.base_url != None:
        # Parse fixed base URL from settings.php.
        parts = php.parse_url(lib_appglobals.base_url)
        if not php.isset(parts, "path"):
            parts["path"] = ""
        lib_appglobals.base_path = parts["path"] + "/"
        # Build base_root (everything until first slash after "scheme://").
        lib_appglobals.base_root = php.substr(
            lib_appglobals.base_url, 0, php.strlen(lib_appglobals.base_url) - php.strlen(parts["path"])
        )
    else:
        # Create base URL
        lib_appglobals.base_root = (
            "https" if (php.isset(php.SERVER, "HTTPS") and php.SERVER["HTTPS"] == "on") else "http"
        )
        # As php.SERVER['HTTP_HOST'] is user input, ensure it only contains
        # characters allowed in hostnames.
        lib_appglobals.base_root += "://" + php.preg_replace("/[^a-z0-9-:._]/i", "", php.SERVER["HTTP_HOST"])
        lib_appglobals.base_url = lib_appglobals.base_root
        # php.SERVER['SCRIPT_NAME'] can, in contrast to php.SERVER['PHP_SELF'], not
        # be modified by a visitor.
        dir = php.trim(php.dirname(php.SERVER["SCRIPT_NAME"]), "\,/")
        if len(dir) > 0:
            lib_appglobals.base_path = "/dir"
            lib_appglobals.base_url += lib_appglobals.base_path
            lib_appglobals.base_path += "/"
        else:
            lib_appglobals.base_path = "/"
    if settings.cookie_domain != None:
        # If the user specifies the cookie domain, also use it for session name.
        session_name_ = settings.cookie_domain
    else:
        # Otherwise use base_url as session name, without the protocol
        # to use the same session identifiers across http and https.
        session_name_ = php.explode("://", lib_appglobals.base_url, 2)[1]
        # We escape the hostname because it can be modified by a visitor.
        if not php.empty(php.SERVER["HTTP_HOST"]):
            settings.cookie_domain = check_plain(php.SERVER["HTTP_HOST"])
    # To prevent session cookies from being hijacked, a user can configure the
    # SSL version of their website to only transfer session cookies via SSL by
    # using PHP's session.cookie_secure setting. The browser will then use two
    # separate session cookies for the HTTPS and HTTP versions of the site. So we
    # must use different session identifiers for HTTPS and HTTP to prevent a
    # cookie collision.
    if php.ini_get("session.cookie_secure"):
        session_name_ += "SSL"
    # Strip leading periods, www., and port numbers from cookie domain.
    settings.cookie_domain = php.ltrim(settings.cookie_domain, ".")
    if php.strpos(settings.cookie_domain, "www.") == 0:
        settings.cookie_domain = php.substr(settings.cookie_domain, 4)
    settings.cookie_domain = php.explode(":", settings.cookie_domain)
    settings.cookie_domain = "." + settings.cookie_domain[0]
    # Per RFC 2109, cookie domains must contain at least one dot other than the
    # first. For hosts such as 'localhost' or IP Addresses we don't set a
    # cookie domain.
    if php.count(php.explode(".", settings.cookie_domain)) > 2 and not php.is_numeric(
        php.str_replace(".", "", settings.cookie_domain)
    ):
        php.ini_set("session.cookie_domain", settings.cookie_domain)
    # print session_name;
    lib_session.name("SESS" + php.md5(session_name_))
开发者ID:sabren,项目名称:drupy,代码行数:70,代码来源:bootstrap.py

示例7: save_upload

# 需要导入模块: from lib.drupy import DrupyPHP [as 别名]
# 或者: from lib.drupy.DrupyPHP import trim [as 别名]
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.', \
#.........这里部分代码省略.........
开发者ID:brendoncrawford,项目名称:drupy,代码行数:103,代码来源:file.py


注:本文中的lib.drupy.DrupyPHP.trim方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。