/** * Join all parameters into a URL path. This means all slashes are * normalized, removing all double slashes. If the first paramater has * a leading slash, the resulting string will also have a leading slash. If * it doesn't, the resulting string won't have one either. * * \param $parts * Any number of string parameters (or an array) * * \return * The resulting URL path * * \see URL::join_ext */ static function join($parts = null) { $args = func_get_args(); $num_args = func_num_args(); /* Accept one single array argument too */ if ($num_args == 1 && is_numeric_array($args[0])) { $args = $args[0]; } assert('is_numeric_array($args)'); $use_leading_slash = $args && is_string($args[0]) && str_has_prefix($args[0], '/'); $use_trailing_slash = false; // decide later $list = array(); while ($args) { $arg = array_shift($args); if (is_int($arg)) { $arg = (string) $arg; } assert('is_string($arg)'); /* Check the last item for a trailing slash */ if (!$args) { /* This is the last item */ $use_trailing_slash = str_has_suffix($arg, '/'); } /* Strip leading slashes */ if (str_has_prefix($arg, '/')) { $arg = preg_replace('#^/*(.*)$#', '\\1', $arg); } /* Strip trailing slashes */ if (str_has_suffix($arg, '/')) { $arg = preg_replace('#^(.*?)/+$#', '\\1', $arg); } /* Add to the list */ $list[] = $arg; } /* Only non-whitespace strings are taken into account */ $list = str_all_non_white($list); $joined = join('/', $list); /* Special case for empty results */ if (strlen($joined) == '') { return $use_leading_slash || $use_trailing_slash ? '/' : ''; } /* Leading slash */ if ($use_leading_slash) { $joined = '/' . $joined; } /* Trailing slash */ if ($use_trailing_slash) { $joined = $joined . '/'; } return $joined; }
/** * \private * * Helper function to create RSS XML elements. * * This is only for internal use. * * \param $obj * The object from which to retrieve the value * * \param $property * The property name * * \param $tagname * The XML tag name * * \param $status * Status of the element * * \param $type * Data type of the element * * \return * An AnewtXMLDomElement instance, or null. */ public static function _build_rss_element($obj, $property, $tagname, $status, $type) { if (!$obj->_isset($property)) { /* If an optional element not provided it's not a problem... */ if ($status == ANEWT_RSS_ELEMENT_STATUS_OPTIONAL) { return null; } /* ...but required means required! */ throw new AnewtException('AnewtRssItem::render(): Required property "%s" not set.', $property); } $value = $obj->_get($property); switch ($type) { case ANEWT_RSS_ELEMENT_TYPE_STRING: assert('is_string($value);'); break; case ANEWT_RSS_ELEMENT_TYPE_CANONICAL_URL: assert('is_string($value);'); if (str_has_prefix($value, '/')) { /* Fixup relative URL's without a http://hostname.ext/ part */ $value = AnewtRequest::canonical_base_url() . $value; } break; case ANEWT_RSS_ELEMENT_TYPE_INTEGER: assert('is_int($value);'); $value = (string) $value; break; case ANEWT_RSS_ELEMENT_TYPE_DATE: assert('$value instanceof AnewtDateTimeAtom;'); $value = AnewtDateTime::rfc2822($value); break; default: assert('false; // not reached'); break; } $element = new AnewtXMLDomElement($tagname); $element->append_child(new AnewtXMLDomText($value)); return $element; }
/** * Adds a mapping to the list of url mappings. * * \param $command_name * The name of the command to invoke when this url mapping matches. This * should be a simple string, eg. "archive". This string will be prefixed * with "command_" and called if the url matches, eg. the method * command_archive() will be called. This callback method needs to handle * the url. * * \param $url * The url pattern to match. Variable url parts should have a colon * prefix. Example: /news/:year/:month/:slug/comments. The year, month and * slug variables will be passed in an array to the method handling the * request if the url matches. * * \param $requirements * Optional parameter with regular expressions to match against the * variables in the url. Only variables matching the regular expression * will be handled by this mapping. This way you can be sure your method * will always be called with valid parameters (so you don't need to * repeat the input checking in your handler methods). Example: * array('year' => '/^\\d{4}$/', 'month' => '/^\\d{2}$/') * */ function add_urlmap($command_name, $url, $requirements = null) { /* Requirements are optional */ if (is_null($requirements)) { $requirements = array(); } /* Sanity checks */ assert('is_string($command_name) && strlen($command_name)'); assert('is_assoc_array($requirements)'); /* Split the url into smaller pieces. We split on the forward slash * character and put the parts in a list after stripping of leading and * trailing slashes. Eg. /foo/bar/baz/ is split in (foo, bar, baz). */ if (is_string($url)) { $url = str_strip_prefix($url, '/'); $url = str_strip_suffix($url, '/'); /* Special case for top level urls */ if (strlen($url) == 0) { $parts = array(); // no parts } else { $parts = split('/', $url); } } else { assert('is_array($url)'); $parts = array_trim_strings($url, '/'); } /* Parse the pieces and parameters */ $map = array(); foreach ($parts as $part) { /* Handle variables */ if (str_has_prefix($part, ':')) { $part = substr($part, 1); $requirement = array_get_default($requirements, $part, null); $map[] = array($part, $requirement); /* No variable */ } else { $map[] = $part; } } /* Add the url map to the list of registered url maps */ $urlmap = array($command_name, $map); $this->urlmaps[] = $urlmap; }
function prepare_query($q, $field_name = null) { $where = array(); foreach ($this->fields as $f) { if (isset($this->params[$f])) { $val = $this->params[$f]; $f = array_get_default($this->field_opts[$f], 'sql-name', $f); if (str_has_prefix($val, 'HAS:')) { $val = preg_replace('/^HAS:/', '', $val); array_push($where, sprintf("FIND_IN_SET('%s', %s)", mysql_real_escape_string($val), $f)); } elseif (str_has_prefix($val, 'LIKE:')) { $val = preg_replace('/^LIKE:/', '', $val); array_push($where, sprintf("%s LIKE '%s'", $f, mysql_real_escape_string($val))); } else { if (!is_numeric($val)) { $val = "'" . mysql_real_escape_string($val) . "'"; } array_push($where, sprintf("%s=%s", $f, $val)); } } } if ($this->time_field and $this->interval != '' and $this->interval != '*') { array_push($where, sprintf("(`%s` > NOW() - INTERVAL %s)", $this->time_field, $this->interval)); } $where = implode(' AND ', $where); $this->query_restriction = $where; if (str_contains($q, '?where?')) { if ($where) { $where = "WHERE {$where}"; } $q = str_replace('?where?', $where, $q); #$q = str_replace('?where?', '', $q); #die($qqq); } elseif (str_contains($q, '?where-and?')) { if ($where) { $where = "AND {$where}"; } $q = str_replace('?where-and?', $where, $q); } if (str_contains($q, '?temp-constraint?')) { $q = str_replace('?temp-constraint?', sprintf("(`%s` > NOW() - INTERVAL %s)", $field_name, $this->interval), $q); } $order_by = array_get_default($this->field_opts[$this->order_by], 'sql-name', $this->order_by); //$order_by = $this->order_by; $q = $q . " ORDER BY " . $order_by . " " . $this->order_dir . " LIMIT " . ($this->limit + 1) . " OFFSET " . $this->offset; return $q; }
#!/usr/bin/php <?php require_once dirname(__FILE__) . '/../anewt.lib.php'; anewt_include('textformatting'); /* Options */ array_shift($argv); // skip command name $use_page = !in_array('--no-page', $argv); $fd = STDIN; $title = ''; while (true) { $arg = array_shift($argv); if (is_null($arg)) { break; } if (str_has_prefix($arg, '--')) { continue; } $fd = fopen($arg, 'r'); $title = $arg; break; } /* Input */ $input_chunks = array(); while (!feof($fd)) { $input_chunks[] = fread($fd, 16384); } $input = join('', $input_chunks); fclose($fd); /* Output */ $output = TextFormatter::format($input, 'textile');
/** * Return the formatted text. * * \return * The formatted text */ function render() { // {{{ $formatter = $this->getdefault('formatter', $this->default_formatter); $text = $this->get('text'); assert('in_array($formatter, $this->formatters, true)'); assert('$this->is_set("text")'); assert('is_string($this->get("text"))'); /** * Simple heuristic for the automatic mode: check whether the first * non-whitespace character is a < character. If so, assume it's already * formatted as HTML and treat it as 'raw'. Otherwise, use textile. To * improve speed, only the first 50 characters are considered. */ if ($formatter == 'auto') { $formatter = str_has_prefix(ltrim(substr($text, 0, 50)), '<') ? 'raw' : 'textile'; } switch ($formatter) { case 'raw': break; case 'entities': $text = htmlentities($text); break; case 'specialchars': $text = htmlspecialchars($text); break; case 'textile': anewt_include('textile'); /* FIXME: remove the ANEWT_TEXTILE_DEVELOPMENT workaround when * textile code is ready for production code. */ if (defined('ANEWT_TEXTILE_DEVELOPMENT')) { $t = new AnewtTextile(); $result = $t->process($text); } else { $t = new Textile(); $result = $t->TextileThis($text); } $text = trim($result); break; default: trigger_error(sprintf('%s:%s(): Unknown formatter: \'%s\'', __CLASS__, __FUNCTION__, $formatter), E_USER_ERROR); } return $text; }
/** * Output the calendar to a browser. * * This renders the calendar and all its asssociated events, and sends the * output to the browser with the correct HTTP headers for the MIME type and * (optionally) the downoad filename. */ function flush() { header('Content-Type: text/calendar'); $filename = $this->filename; if (!is_null($filename)) { /* Make sure the filename ends with .ics */ if (!str_has_prefix($filename, 'ics')) { $filename = sprintf('%s.ics', $filename); } header(sprintf('Content-Disposition: inline; filename=%s', $filename)); } echo to_string($this), NL; }
/** * Log a message. * * \param $domain * \param $level * \param $message * * \see AnewtLogHandlerBase::log */ public function log($domain, $level, $message) { $name = AnewtLog::loglevel_to_string($level); $output = $this->format_log_message($domain, $level, $message); /* Optionally prefix with timestamp */ if ($this->timestamps) { $date = AnewtDateTime::iso8601(AnewtDateTime::now()); $output = sprintf('[%s] %s', $date, $output); } /* Make sure there is a trailing newline */ if (!str_has_prefix($output, NL)) { $output .= NL; } fwrite($this->fp, $output); }
/** * Return a list of all defined names. * * This method includes both keys in the internal storage and the name of * values available only through getter methods. * * \return * A numeric array with all keys. * * \see Container::_keys */ function keys() { /* All internal keys... */ $result = $this->_keys(); /* ... and all keys found in getter methods */ foreach (get_class_methods($this) as $method_name) { if (str_has_prefix($method_name, 'get_')) { /* Remove 'get_' prefix, handle caching getters and normalize */ $name = substr($method_name, 4); $name = str_strip_suffix($name, '_'); $name = str_replace('_', '-', $name); $result[] = $name; } } return $result; }
/** * Build a URL from the passed parameters. * * You can provide a single path string, or an array of strings, in which * case each of the items in \c $path is a path component. The path * components will be concatenated, separated by slashes. * * All slashes are normalized. If the first path component has a leading * slash, the resulting string will also have a leading slash and if it * doesn't, the resulting string won't have one either. The same goes for * the trailing slash: if the last path component ends with a slash, the * resulting string will have one as well. * * If \c $parameters is passed, a HTTP query string will be appended to the * url using the this associatve array. * * Example: * * <code>$url = AnewtURL::join(array('/path/to', $file), array('foo' => 'bar'));</code> * * \param $path * Single string or array of strings (each item is a path component of the url) * * \param $parameters * Associative array used to build a query string (optional) * * \return * The resulting URL path * * \see * AnewtURL::parse */ static function build($path, $parameters = null) { /* Input sanitizing */ if (is_string($path)) { $path_components = array($path); } else { $path_components = $path; } if (is_null($parameters)) { $parameters = array(); } assert('is_numeric_array($path_components);'); assert('is_assoc_array($parameters);'); /* Remove empty path components */ $path_components = str_all_non_white($path_components); /* Leading and trailing slashes */ if ($path_components) { /* Path is not empty */ $use_leading_slash = str_has_prefix($path_components[0], '/'); $use_trailing_slash = str_has_suffix($path_components[count($path_components) - 1], '/'); } else { /* Path is empty */ $use_leading_slash = false; $use_trailing_slash = false; } /* Loop over url parts and clean up */ $first_part_seen = false; $path_components_clean = array(); while ($path_components) { $part = array_shift($path_components); assert('is_string($part)'); $part = str_strip_prefix($part, '/'); $part = str_strip_suffix($part, '/'); if (!strlen($part)) { continue; } /* Use url encoding, but the first path component may be something * like "http://...", which should not be url encoded. */ if (!$first_part_seen && str_contains($part, '://')) { $first_part_seen = true; $part_encoded = $part; } else { $part_encoded = urlencode($part); /* Url decoding also escapes slashes and some other characters * we want to keep, since escaping those would disallow passing * path components like "/path/to/file". A slash cannot be used * in a filename anyway, so we special-case some characters. */ $part_encoded = str_replace(array('%2F', '%7E'), array('/', '~'), $part_encoded); } $path_components_clean[] = $part_encoded; } /* Build url by joining all cleaned parts, and adding a leading and * trailing slash, if appropriate. */ $url = join('/', $path_components_clean); if (strlen($url)) { /* Path is not empty */ if ($use_leading_slash) { $url = sprintf('/%s', $url); } if ($use_trailing_slash) { $url = sprintf('%s/', $url); } } elseif ($use_leading_slash || $use_trailing_slash) { /* Path is empty, a slash is required */ $url = '/'; } /* Query parameters */ assert('is_assoc_array($parameters)'); $parameters_escaped = array(); foreach ($parameters as $name => $value) { if (is_null($value)) { $parameters_escaped[] = urlencode($name); } else { assert('is_string($value);'); $parameters_escaped[] = sprintf('%s=%s', urlencode($name), urlencode($value)); } } if ($parameters_escaped) { $url = sprintf('%s?%s', $url, implode('&', $parameters_escaped)); } return $url; }
/** * (Really) dispatch an URL to the correct handlers. * * This method does the actual magic, such as URL parsing, matching and * command invocation. You can optionally provide a custom URL and tell the * dispatcher that some parts of the URL should be skipped when handling * this request. * * \param $url * \param $prefix * \see AnewtURLDispatcher::dispatch */ private function real_dispatch($url = null, $prefix = null) { /* Use the current URL if no explicit url was given */ if (is_null($url)) { $url = AnewtRequest::relative_url(); } /* Figure out the right base location if no prefix was given. If the URL * starts with the PHP script name, we assume no htaccess file has been * setup to beautify the website URLs. In this case the relevant parts * of the URL are added after the PHP script name. Example URL of such * a setup is http://.../dispatch.php/a/b/c/. Otherwise, it is quite * likely a htaccess file is used to point all requests to a script that * invokes the dispatcher. We assume this script is placed in the * toplevel directory, so we use that directory as the prefix. */ if (is_null($prefix)) { if (str_has_prefix($url, $_SERVER['SCRIPT_NAME'])) { $prefix = $_SERVER['SCRIPT_NAME']; } else { $prefix = dirname($_SERVER['SCRIPT_NAME']); } } assert('is_string($url)'); assert('is_string($prefix)'); /* Strip off the GET parameters from the URL */ $get_params = ''; $question_mark_pos = strpos($url, '?'); if ($question_mark_pos !== false) { $get_params = substr($url, $question_mark_pos); $url = substr($url, 0, $question_mark_pos); } /* Redirect GET requests when trailing slash is required but missing */ if (!str_has_suffix($url, '/') && $this->force_trailing_slash && AnewtRequest::is_get() && !preg_match('#^.*\\.[^\\/]*$#', $url)) { redirect(sprintf('%s/%s', $url, $get_params), HTTP_STATUS_MOVED_PERMANENTLY); } /* Strip off prefix and slashes */ $this->request_url_full = $url; $url = str_strip_prefix($url, $prefix); $url = str_strip_prefix($url, '/'); $url = str_strip_suffix($url, '/'); $this->request_url = $url; /* Try to find a matching route and extract the parameters */ $found_route = false; $command = null; $parameters = array(); $url_parts = strlen($url) > 0 ? explode('/', $url) : array(); foreach ($this->routes as $route) { $route_type = array_shift($route); $route_command = array_shift($route); $route_parameters = array(); /* Type I: Routes using regular expression */ if ($route_type == ANEWT_URL_DISPATCHER_ROUTE_TYPE_REGEX) { list($pattern) = $route; /* Try both with and without trailing slash */ if (preg_match($pattern, $url, $route_parameters) || preg_match($pattern, sprintf('%s/', $url), $route_parameters)) { /* We don't care about $parameters[0] (it contains the full match) */ array_shift($route_parameters); $route_parameters = array_map('urldecode', $route_parameters); $command = $route_command; $parameters = $route_parameters; $found_route = true; break; } } elseif ($route_type == ANEWT_URL_DISPATCHER_ROUTE_TYPE_URL_PARTS) { list($route_url, $additional_constraints) = $route; /* Route URL can be a string or an array */ if (is_string($route_url)) { $route_url = str_strip_prefix($route_url, '/'); $route_url = str_strip_suffix($route_url, '/'); $route_url_parts = strlen($route_url) > 0 ? explode('/', $route_url) : array(); } elseif (is_numeric_array($route_url)) { $route_url_parts = $route_url; } else { throw new AnewtException('Invalid url route: %s', $route_url); } /* Match the URL parts against the route URL parts */ if (count($url_parts) != count($route_url_parts)) { continue; } $constraints = array_merge($this->url_part_constraints, $additional_constraints); for ($i = 0; $i < count($url_parts); $i++) { /* If the URL starts with a ':' character it is * a parameter... */ if ($route_url_parts[$i][0] === ':') { $parameter_name = substr($route_url_parts[$i], 1); $parameter_value = $url_parts[$i]; /* If there is a constraint for this parameter, the * value must match the constraint. If not, this route * cannot be used. */ if (array_key_exists($parameter_name, $constraints)) { $pattern = $constraints[$parameter_name]; if (!preg_match($pattern, $parameter_value)) { continue 2; } } $route_parameters[$parameter_name] = urldecode($parameter_value); } elseif ($url_parts[$i] !== $route_url_parts[$i]) { continue 2; } } /* If this code is reached, we found a matching route with all * the constraints on the URL parts satisfied. */ $command = $route_command; $parameters = $route_parameters; $found_route = true; break; } else { assert('false; // not reached'); } } /* If no route matches, try an automatic route. Only the first URL part * is considered for this. */ if (!$found_route && $this->use_automatic_commands) { $url_parts = explode('/', $url, 2); if ($url_parts) { $command = array($this, sprintf('command_%s', $url_parts[0])); list($found_route, $error_message_to_ignore) = $this->is_valid_command($command); } } /* As a last resort try the default handler, if one was set. */ $default_command = $this->default_command; if (!$found_route && !is_null($default_command)) { $command = $default_command; $command = $this->validate_command($command); $found_route = true; } /* If we still don't have a command, we give up. Too bad... not found */ if (!$found_route) { throw new AnewtHTTPException(HTTP_STATUS_NOT_FOUND); } /* Check the command for validity. In most cases we already know the * command exists since that is already checked in the add_route_*() * methods or in the code above, except for lazily loaded commands, so * we try to load them and check for validity afterwards. */ if (is_array($command) && is_string($command[0])) { $this->include_command_class($command[0]); $command = $this->validate_command($command); } /* Finally... run the command and the pre and post command hooks. */ $this->pre_command($parameters); call_user_func($command, $parameters); $this->post_command($parameters); }
adjlahdf;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l adjlahdf;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l adjlahdf;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l adjlahdf;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l adjlahdf;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l adjlahdf;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l adjlahdf;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l '; $prefix = ' qwertyui;ljhdsf;ljhdsa;lfihsajfkldsajf;lksajdfkljdsafdsalhfwalrhflrwahfrwaflawhrlfhrwa;l adjlahdf'; $num_iterations = 1 * 1000 * 1000; $print_dot_for_each = 100000; $start_time = time(); for ($i = 0; $i < $num_iterations; $i++) { if ($i % $print_dot_for_each == 0) { echo '.'; } $result = str_has_prefix($str, $prefix); } $end_time = time(); echo "\nElapsed time for str_has_prefix: ", $end_time - $start_time, "\n"; $start_time = time(); for ($i = 0; $i < $num_iterations; $i++) { if ($i % $print_dot_for_each == 0) { echo '.'; } $result = str_has_prefix2($str, $prefix); } $end_time = time(); echo "\nElapsed time for str_has_prefix2: ", $end_time - $start_time, "\n";
/** * Internal default handler preprocessor that looks for XML comments. * * \param $parser The parser instance * \param $data A string containing text data */ private function _default_handler($parser, $data) { /* First flush the cdata buffer */ $this->flush_data(); /* Check if the data is comment */ $comment_start = '<!--'; $comment_end = '-->'; if (str_has_prefix($data, $comment_start) && str_has_suffix($data, $comment_end)) { $comment = substr($data, strlen($comment_start)); $comment = substr($comment, 0, strlen($comment) - strlen($comment_end)); /* strip whitespace */ $comment = trim($comment); $comment = preg_replace('/\\s+/', ' ', $comment); /* hand over control to the command handler */ $this->handle_comment($comment); return; } /* hand over control to the default handler */ $this->default_handler($data); }
<?php error_reporting(E_ALL); require_once '../anewt.lib.php'; anewt_include('validator'); function usage() { echo str_join_wrap('Error: please specify a filename with mail addresses to test against the validator. There should be one address per line.'); echo NL; } if ($_SERVER['argc'] != 2) { usage(); die; } $validator =& new AnewtValidatorEmail(); $filename = $_SERVER['argv'][1]; foreach (file($filename) as $line) { $line = trim($line); /* Skip empty lines and comments */ if (!strlen($line) || str_has_prefix($line, '#')) { continue; } $valid = $validator->is_valid($line); if (!$valid) { printf("Invalid address: %s\n", $line); } }
/** * \private * * Parse a block of text into a list structure. If this block is not a list * NULL is returned. * * \param $text * The text to parse into a list. */ function _parse_list($text) { assert('is_string($text);'); $markers = array('*' => 'ul', '#' => 'ol'); foreach ($markers as $marker => $list_type) { /* Check very first character of text */ if (!str_has_prefix($text, $marker)) { /* Too bad */ continue; } $lines = explode("\n", $text); /* Require all lines to start with the same list marker */ $items = array(); foreach ($lines as $line) { /* Bail out if this is not a list after all */ if (!str_has_prefix($line, $marker)) { return null; } /* Cut off the list marker */ $items[] = trim(substr($line, 1)); } return array($items, $list_type); } /* No list, no result. */ return null; }
/** * Parses raw headers and stores them in this message. This method should * only be called once during parsing. * * \param $headers * A string or array that contains the headers to be parsed */ private function parse_headers($headers) { /* Split string into an array */ if (is_string($headers)) { $headers = explode("\n", trim($headers)); } assert('is_array($headers)'); /** Ignore "^From .* if it's the first line (mbox) */ if ($headers && str_has_prefix($headers[0], 'From ')) { array_shift($headers); } /* Loop over all lines */ while (true) { /* No more lines? */ if (!$headers) { break; } $line = array_shift($headers); assert('strpos($line, ":") !== false'); /* New header line */ list($name, $value) = explode(':', $line, 2); /* Peek at next lines to see if this is a multi-line header. If it * is, concatenate the value to the existing value. */ while ($line = array_shift($headers)) { if (str_has_whitespace_prefix($line)) { /* Multi-line header detected */ $value .= ' ' . ltrim($line); } else { /* No multi-line. Put the header back in the list before * to allow further processing */ array_unshift($headers, $line); break; } } /* Sanitize values */ $name = trim($name); $value = trim($value); /* Store the header */ $this->add_header($name, $value); } }
/** * Dispatch an URL to the correct handlers. See the documentation on * URLDispatcher::dispatch() for more information on the parameters. * * \param $url * The url to dispatch (optional, defaults to null). * * \see URLDispatcher::dispatch */ function dispatch($url = null) { if (is_null($url)) { $url = AnewtRequest::relative_url(); } assert('is_string($url)'); /* Get the default settings */ $module_name = $this->_getdefault('default-module', null); $class_name = $this->_get('default-class'); $skip_path_components = 0; /* Iterate over the mappings and override the default if the mapping matches */ $test_url = str_strip_prefix($url, '/'); foreach ($this->prefix_to_dispatcher_mapping as $prefix => $mapping) { /* Try to match the prefix. Add a trailing slash, otherwise the url * /newsxyz would also match the /news mapping, which is not * intended behaviour. */ $test_prefix = $prefix . '/'; if (str_has_prefix($test_url, $test_prefix)) { /* The prefix matches the url */ list($module_name, $class_name) = $mapping; $skip_path_components = count(explode('/', $prefix)); break; } } /* Load module (if supplied) */ if (!is_null($module_name)) { $this->load_module($module_name); } /* Create and invoke dispatcher */ $dispatcher =& new $class_name(); $dispatcher->dispatch($url, $skip_path_components); }
/** * Strip a prefix from a string. * * If the string didn't start with the given prefix, this function is a no-op: the * string is returned unaltered. * * \param $str * The string to operate on. * * \param $prefix * The prefix to remove. * * \return * A string with the prefix removed, if found. */ function str_strip_prefix($str, $prefix) { assert('is_string($str)'); assert('is_string($prefix)'); if (strlen($prefix) == 0) { return $str; } if ($str == $prefix) { return ''; } if (str_has_prefix($str, $prefix)) { $startpos = strlen($prefix); return substr($str, $startpos); } return $str; }