Example #1
0
/**
 * Processes a string of HTML attributes.
 *
 * @return
 *   Cleaned up version of the HTML attributes.
 */
function _filter_xss_attributes($attr)
{
    $attrarr = array();
    $mode = 0;
    $attrname = '';
    while (strlen($attr) != 0) {
        // Was the last operation successful?
        $working = 0;
        switch ($mode) {
            case 0:
                // Attribute name, href for instance
                if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
                    $attrname = strtolower($match[1]);
                    $skip = $attrname == 'style' || substr($attrname, 0, 2) == 'on';
                    $working = $mode = 1;
                    $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
                }
                break;
            case 1:
                // Equals sign or valueless ("selected")
                if (preg_match('/^\\s*=\\s*/', $attr)) {
                    $working = 1;
                    $mode = 2;
                    $attr = preg_replace('/^\\s*=\\s*/', '', $attr);
                    break;
                }
                if (preg_match('/^\\s+/', $attr)) {
                    $working = 1;
                    $mode = 0;
                    if (!$skip) {
                        $attrarr[] = $attrname;
                    }
                    $attr = preg_replace('/^\\s+/', '', $attr);
                }
                break;
            case 2:
                // Attribute value, a URL after href= for instance
                if (preg_match('/^"([^"]*)"(\\s+|$)/', $attr, $match)) {
                    $thisval = filter_xss_bad_protocol($match[1]);
                    if (!$skip) {
                        $attrarr[] = "{$attrname}=\"{$thisval}\"";
                    }
                    $working = 1;
                    $mode = 0;
                    $attr = preg_replace('/^"[^"]*"(\\s+|$)/', '', $attr);
                    break;
                }
                if (preg_match("/^'([^']*)'(\\s+|\$)/", $attr, $match)) {
                    $thisval = filter_xss_bad_protocol($match[1]);
                    if (!$skip) {
                        $attrarr[] = "{$attrname}='{$thisval}'";
                    }
                    $working = 1;
                    $mode = 0;
                    $attr = preg_replace("/^'[^']*'(\\s+|\$)/", '', $attr);
                    break;
                }
                if (preg_match("%^([^\\s\"']+)(\\s+|\$)%", $attr, $match)) {
                    $thisval = filter_xss_bad_protocol($match[1]);
                    if (!$skip) {
                        $attrarr[] = "{$attrname}=\"{$thisval}\"";
                    }
                    $working = 1;
                    $mode = 0;
                    $attr = preg_replace("%^[^\\s\"']+(\\s+|\$)%", '', $attr);
                }
                break;
        }
        if ($working == 0) {
            // not well formed, remove and try again
            $attr = preg_replace('/
        ^
        (
        "[^"]*("|$)     # - a string that starts with a double quote, up until the next double quote or the end of the string
        |               # or
        \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
        |               # or
        \\S              # - a non-whitespace character
        )*              # any number of the above three
        \\s*             # any number of whitespaces
        /x', '', $attr);
            $mode = 0;
        }
    }
    // the attribute list ends with a valueless attribute like "selected"
    if ($mode == 1) {
        $attrarr[] = $attrname;
    }
    return $attrarr;
}
Example #2
0
/**
 * Gera uma URL interna ou externa.
 *
 * Quando criar links nos modulos, considere usar _l() pode ser melhor alternativa que url()
 *
 * @param $path
 * O caminho interno ou Externo que será lincado, como por exemplo "node/34" ou
 * "http://example.com/foo". Notas:
 * - Se você fornecer uma URL completa, será considerada uma URL externa.
 * - Se você fornecer apenas o camiho (ex. "node/34"), sera considerado
 * um link interno. neste caso, pode ser uma URL de sistema e será 
 * subistittuida por seu atalho, se existir. Argumentos de query adicionais
 * devem ser declarados em $options['query'], não incluidos na URL.
 * - Se for fornecido um caminho interno e $options['alias'] estiver definido como TRUE, 
 * este será assumido como o atalho correto para o caminho, e o atalho não será checado.
 * - A string especial '<front>' gera um link para a pagina principal do site.
 * - Se sua URL externa possuir uma query (ex. http://example.com/foo?a=b),
 * então voc~e pode decodificar as chaves e os valores por conta propria e inclui-la no $path,
 * ou usar em $options['query'] e deixar a função decodificar sua URL.
 * 
 * @param $options
 * An associative array of additional options, with the following elements:
 * - 'query': A URL-encoded query string to append to the link, or an array of
 * query key/value-pairs without any URL-encoding.
 * - 'fragment': A fragment identifier (named anchor) to append to the URL.
 * Do not include the leading '#' character.
 * - 'absolute' (default FALSE): Whether to force the output to be an absolute
 * link (beginning with http:). Useful for links that will be displayed
 * outside the site, such as in an RSS feed.
 * - 'alias' (default FALSE): Whether the given path is a URL alias already.
 * - 'external': Whether the given path is an external URL.
 * - 'language': An optional language object. Used to build the URL to link
 * to and look up the proper alias for the link.
 * - 'base_url': Only used internally, to modify the base URL when a language
 * dependent URL requires so.
 * - 'prefix': Only used internally, to modify the path when a language
 * dependent URL requires so.
 *
 * @return
 * A string containing a URL to the given path.
 */
function url($path = NULL, $options = array())
{
    // Merge in defaults.
    $options += array('fragment' => '', 'query' => '', 'absolute' => FALSE, 'alias' => FALSE, 'prefix' => '');
    if (!isset($options['external'])) {
        // Return an external link if $path contains an allowed absolute URL.
        // Only call the slow filter_xss_bad_protocol if $path contains a ':' before
        // any / ? or #.
        $colonpos = strpos($path, ':');
        $options['external'] = $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path);
    }
    // May need language dependent rewriting if language.inc is present.
    if (function_exists('language_url_rewrite')) {
        language_url_rewrite($path, $options);
    }
    if ($options['fragment']) {
        $options['fragment'] = '#' . $options['fragment'];
    }
    if (is_array($options['query'])) {
        $options['query'] = query_string_encode($options['query']);
    }
    if ($options['external']) {
        // Split off the fragment.
        if (strpos($path, '#') !== FALSE) {
            list($path, $old_fragment) = explode('#', $path, 2);
            if (isset($old_fragment) && !$options['fragment']) {
                $options['fragment'] = '#' . $old_fragment;
            }
        }
        // Append the query.
        if ($options['query']) {
            $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $options['query'];
        }
        // Reassemble.
        return $path . $options['fragment'];
    }
    global $cfg;
    static $script = null;
    if (!isset($script)) {
        // On some web servers, such as IIS, we can't omit "index.php". So, we
        // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
        // Apache.
        $script = strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE ? 'index.php' : '';
    }
    if (!isset($options['base_url'])) {
        // The base_url might be rewritten from the language rewrite in domain mode.
        $options['base_url'] = $cfg['base_url'];
    }
    // Preserve the original path before aliasing.
    $original_path = $path;
    // The special path '<front>' links to the default front page.
    if ($path == '<front>') {
        $path = '';
    } elseif (!empty($path) && !$options['alias']) {
        $path = get_path_alias($path, isset($options['language']) ? $options['language']->language : '');
    }
    /*
       * @todo verificar necessidade
       * if (function_exists('custom_url_rewrite_outbound')) {
        // Modules may alter outbound links by reference.
        custom_url_rewrite_outbound($path, $options, $original_path);
      }*/
    $base = $options['absolute'] ? $options['base_url'] . '/' : $cfg['base_path'];
    $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
    $path = SB_urlencode($prefix . $path);
    if (variable_get('clean_url', '0')) {
        // With Clean URLs.
        if ($options['query']) {
            return $base . $path . '?' . $options['query'] . $options['fragment'];
        } else {
            return $base . $path . $options['fragment'];
        }
    } else {
        // Without Clean URLs.
        $variables = array();
        if (!empty($path)) {
            $variables[] = 'q=' . $path;
        }
        if (!empty($options['query'])) {
            $variables[] = $options['query'];
        }
        $query = join('&', $variables);
        if (isset($query)) {
            return $base . $script . '?' . $query . $options['fragment'];
        } else {
            return $base . $options['fragment'];
        }
    }
}