urlmapper.php 7.39 KB
Newer Older
1 2 3 4 5 6
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * URL mapper
7
 *
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 * PHP version 5
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
23
 * @category  URL
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    // This check helps protect against security problems;
    // your code file can't be executed directly from the web.
    exit(1);
}

/**
 * URL mapper
 *
 * Converts a path into a set of parameters, and vice versa
 *
 * We used to use Net_URL_Mapper, so there's a wrapper class at Router, q.v.
43
 *
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
 * NUM's vagaries are the main reason we have weirdnesses here.
 *
 * @category  URL
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

class URLMapper
{
    const ACTION = 'action';

    protected $statics = array();
    protected $variables = array();
    protected $reverse = array();
61
    protected $allpaths = array();
62

63
    function connect($path, $args, $paramPatterns=array())
64 65 66 67 68
    {
        if (!array_key_exists(self::ACTION, $args)) {
            throw new Exception(sprintf("Can't connect %s; path has no action.", $path));
        }

69 70
        $allpaths[] = $path;

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        $action = $args[self::ACTION];

        $paramNames = $this->getParamNames($path);

        if (empty($paramNames)) {
            $this->statics[$path] = $args;
            if (array_key_exists($action, $this->reverse)) {
                $this->reverse[$args[self::ACTION]][] = array($args, $path);
            } else {
                $this->reverse[$args[self::ACTION]] = array(array($args, $path));
            }
        } else {

            // Eff if I understand why some go here and some go there.
            // Anyways, fixup my preconceptions

            foreach ($paramNames as $name) {
                if (!array_key_exists($name, $paramPatterns) &&
                    array_key_exists($name, $args)) {
                    $paramPatterns[$name] = $args[$name];
                    unset($args[$name]);
                }
            }

            $regex = $this->makeRegex($path, $paramPatterns);

            $this->variables[] = array($args, $regex, $paramNames);

            $format = $this->makeFormat($path, $paramPatterns);

            if (array_key_exists($action, $this->reverse)) {
                $this->reverse[$args[self::ACTION]][] = array($args, $format, $paramNames);
            } else {
                $this->reverse[$args[self::ACTION]] = array(array($args, $format, $paramNames));
            }
        }
    }

    function match($path)
    {
        if (array_key_exists($path, $this->statics)) {
            return $this->statics[$path];
        }

        foreach ($this->variables as $pattern) {
            list($args, $regex, $paramNames) = $pattern;
            if (preg_match($regex, $path, $match)) {
                $results = $args;
                foreach ($paramNames as $name) {
                    $results[$name] = $match[$name];
                }
                return $results;
            }
        }
125

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        throw new Exception(sprintf('No match for path "%s"', $path));
    }

    function generate($args, $qstring, $fragment)
    {
        if (!array_key_exists(self::ACTION, $args)) {
            throw new Exception("Every path needs an action.");
        }

        $action = $args[self::ACTION];

        if (!array_key_exists($action, $this->reverse)) {
            throw new Exception(sprintf('No candidate paths for action "%s"', $action));
        }

        $candidates = $this->reverse[$action];

        foreach ($candidates as $candidate) {
            if (count($candidate) == 2) { // static
                list($tryArgs, $tryPath) = $candidate;
                foreach ($tryArgs as $key => $value) {
                    if (!array_key_exists($key, $args) || $args[$key] != $value) {
                        // next candidate
                        continue 2;
                    }
                }
                // success
153
                $path = $tryPath;
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            } else {
                list($tryArgs, $format, $paramNames) = $candidate;

                foreach ($tryArgs as $key => $value) {
                    if (!array_key_exists($key, $args) || $args[$key] != $value) {
                        // next candidate
                        continue 2;
                    }
                }

                // success

                $toFormat = array();

                foreach ($paramNames as $name) {
                    if (!array_key_exists($name, $args)) {
                        // next candidate
                        continue 2;
                    }
                    $toFormat[] = $args[$name];
                }

                $path = vsprintf($format, $toFormat);
177
            }
178

179
            if (!empty($qstring)) {
180 181
                $formatted = http_build_query($qstring);
                $path .= '?' . $formatted;
182
            }
183 184

            return $path;
185 186
        }

187 188
        // failure; some reporting twiddles

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        unset($args['action']);

        if (empty($args)) {
            throw new Exception(sprintf('No matches for action "%s"', $action));
        }

        $argstring = '';

        foreach ($args as $key => $value) {
            $argstring .= "$key=$value ";
        }

        throw new Exception(sprintf('No matches for action "%s" with arguments "%s"', $action, $argstring));
    }

    protected function getParamNames($path)
    {
        preg_match_all('/:(?P<name>\w+)/', $path, $match);
        return $match['name'];
    }

    protected function makeRegex($path, $paramPatterns)
    {
        $pr = new PatternReplacer($paramPatterns);

        $regex = preg_replace_callback('/:(\w+)/',
                                       array($pr, 'toPattern'),
                                       $path);

Evan Prodromou's avatar
Evan Prodromou committed
218
        $regex = '#^' . str_replace('#', '\#', $regex) . '$#';
219 220 221 222 223 224 225 226 227 228

        return $regex;
    }

    protected function makeFormat($path, $paramPatterns)
    {
        $format = preg_replace('/(:\w+)/', '%s', $path);

        return $format;
    }
229 230 231 232 233

    public function getPaths()
    {
        return $this->allpaths;
    }
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
}

class PatternReplacer
{
    private $patterns;

    function __construct($patterns)
    {
        $this->patterns = $patterns;
    }

    function toPattern($matches)
    {
        // trim out the :
        $name = $matches[1];
        if (array_key_exists($name, $this->patterns)) {
            $pattern = $this->patterns[$name];
        } else {
            // ???
            $pattern = '\w+';
        }
        return '(?P<'.$name.'>'.$pattern.')';
    }
}