示例#1
0
文件: router.php 项目: nirix/avalon
    /**
     * Routes the request to the controller.
     *
     * @param Request $request
     */
    public static function route(Request $request)
    {
        $uri = "/" . trim($request->getUri(), '/');
        // Is this the root route?
        if ($uri === '/' and isset(static::$routes['root'])) {
            return static::setRoute(static::$routes['root']);
        }

        // Do we have an exact match?
        if (isset(static::$routes[$uri])) {
            return static::setRoute(static::$routes[$uri]);
        }

        // The fun begins
        foreach (static::$routes as $route) {
            // Does the route match the request?
            $pattern = "#^{$route['route']}" . '(?<extension>' . implode('|', static::$extensions) . ")?$#";
            if (preg_match($pattern, $uri, $params)) {
                unset($params[0]);
                $route['params'] = array_merge($route['params'], $params);
                $route['value'] = preg_replace($pattern, $route['value'], $uri);
                return static::setRoute($route);
            }
        }

        // No matches, try 404 route
        if (isset(static::$routes['404'])) {
            return static::setRoute(static::$routes['404']);
        }
        // No 404 route, Exception time! FUN :D
        else {
            throw new Exception("No routes found for '{$uri}'");
        }
    }
示例#2
0
 /**
  * Route the request and execute the controller.
  */
 public static function process()
 {
     Request::init();
     $route = Router::process();
     if (!$route) {
         $route = Router::getRoute('404');
     }
     if ($route) {
         list($class, $method) = explode('::', $route->controller);
         $action = "{$method}Action";
         Request::$properties->set(['controller' => $class, 'action' => $method]);
         if (!class_exists($class)) {
             throw new Exception("Controller class [{$class}] not found");
         }
         if (!method_exists($class, $action)) {
             throw new Exception("Controller action [{$route->controller}Action] not found");
         }
         $controller = new $class();
         $response = static::runFilters('before', $controller, $method);
         if (!$response) {
             $response = call_user_func_array([$controller, $action], $route->actionParams());
         }
         static::runFilters('after', $controller, $method);
         if (!$response instanceof Response) {
             throw new Exception("The controller returned an invalid response");
         }
         return $response;
     } else {
         throw new Exception(sprintf("No route matches [%s %s] and no 404 controller set", Request::$method, Request::$pathInfo));
     }
 }
示例#3
0
 /**
  * Question management page.
  */
 public function action_index()
 {
     // Set page title
     $this->title(l('security_questions'));
     // Extract questions
     $questions = json_decode(settings('security_questions'), true);
     // Add an empty question
     if (!count($questions)) {
         $questions[] = array('question' => '', 'answers' => '');
     }
     // Check if the form has been submitted
     $errors = array();
     if (Request::method() == 'post') {
         // Process questions
         $updated_questions = array();
         foreach (Request::$post['questions'] as $id => $question) {
             // Check fields
             foreach ($question as $field => $value) {
                 if (empty($value)) {
                     $errors[$id][$field] = true;
                 }
             }
             // Add if no errors
             if (!isset($errors[$id])) {
                 $updated_questions[] = $question;
             }
         }
         // Save and redirect
         if (!count($errors)) {
             $this->db->update('settings')->set(array('value' => json_encode($updated_questions)))->where('setting', 'security_questions')->exec();
             Request::redirect(Request::requestUri());
         }
     }
     View::set(compact('questions', 'errors'));
 }
示例#4
0
 public function destroyAction()
 {
     return $this->respondTo(function ($format) {
         if (Request::isXhr()) {
             $resp = $this->jsonResponse(['success' => 'You are now logged out']);
         } else {
             $resp = $this->redirectTo('root');
         }
         return $resp->addCookie('dreamer', '', time(), '/');
     });
 }
示例#5
0
 public function currentUserAction()
 {
     if ($this->currentUser) {
         return $this->respondTo(function ($format) {
             if (Request::isXhr()) {
                 return $this->jsonResponse(['id' => $this->currentUser->id, 'username' => $this->currentUser->username]);
             }
         });
     } else {
         return $this->show404();
     }
 }
示例#6
0
 public function __construct($path = '/', array $requestInfo = [])
 {
     $requestInfo = $requestInfo + ['method' => "GET", 'post' => [], 'get' => [], 'cookie' => []];
     $_SERVER['HTTP_HOST'] = "localhost";
     $_SERVER['REQUEST_METHOD'] = $requestInfo['method'];
     $_SERVER['REQUEST_URI'] = $path;
     $_SERVER['QUERY_STRING'] = '';
     $_POST = $requestInfo['post'];
     $_GET = $requestInfo['get'];
     $_REQUEST = array_merge($_GET, $_POST);
     $_COOKIE = $requestInfo['cookie'];
     Request::reset();
     Request::init();
 }
示例#7
0
 /**
  * Delete ticket update
  *
  * @param integer $id
  */
 public function action_delete($id)
 {
     // Get the ticket update
     $history = \traq\models\TicketHistory::find($id);
     // Delete the update
     $history->delete();
     // Is this an ajax request?
     if (Request::isAjax()) {
         // Render the view
         View::set('history', $history);
     } else {
         // Just redirect back to the ticket
         Request::redirectTo($history->ticket->href());
     }
 }
示例#8
0
 /**
  * Toggles the subscription.
  *
  * @param string  $type Subscription type (Project, Milestone, Ticket)
  * @param integer $id   Subscribed object ID
  */
 public function action_toggle($type, $id)
 {
     switch ($type) {
         // Project
         case 'project':
             // Delete subscription
             if (is_subscribed($this->user, $this->project)) {
                 $sub = Subscription::select()->where(array(array('project_id', $this->project->id), array('user_id', $this->user->id), array('type', 'project')))->exec()->fetch();
                 $sub->delete();
             } else {
                 $sub = new Subscription(array('type' => "project", 'project_id' => $this->project->id, 'user_id' => $this->user->id, 'object_id' => $this->project->id));
                 $sub->save();
             }
             Request::redirectTo($this->project->href());
             break;
             // Milestone
         // Milestone
         case 'milestone':
             // Get milestone
             $milestone = Milestone::select()->where(array(array('project_id', $this->project->id), array('slug', $id)))->exec()->fetch();
             // Delete subscription
             if (is_subscribed($this->user, $milestone)) {
                 $sub = Subscription::select()->where(array(array('project_id', $this->project->id), array('user_id', $this->user->id), array('type', 'milestone'), array('object_id', $milestone->id)))->exec()->fetch();
                 $sub->delete();
             } else {
                 $sub = new Subscription(array('type' => "milestone", 'project_id' => $this->project->id, 'user_id' => $this->user->id, 'object_id' => $milestone->id));
                 $sub->save();
             }
             Request::redirectTo($milestone->href());
             break;
             // Milestone
         // Milestone
         case 'ticket':
             // Get ticket
             $ticket = Ticket::select()->where(array(array('project_id', $this->project->id), array('ticket_id', $id)))->exec()->fetch();
             // Delete subscription
             if (is_subscribed($this->user, $ticket)) {
                 $sub = Subscription::select()->where(array(array('project_id', $this->project->id), array('user_id', $this->user->id), array('type', 'ticket'), array('object_id', $ticket->id)))->exec()->fetch();
                 $sub->delete();
             } else {
                 $sub = new Subscription(array('type' => "ticket", 'project_id' => $this->project->id, 'user_id' => $this->user->id, 'object_id' => $ticket->id));
                 $sub->save();
             }
             Request::redirectTo($ticket->href());
             break;
     }
 }
示例#9
0
 /**
  * Delete attachment
  *
  * @param integer $attachment_id
  */
 public function action_delete($attachment_id)
 {
     // Delete and redirect
     $this->attachment->delete();
     Request::redirectTo($this->attachment->ticket->href());
 }
示例#10
0
 /**
  * Delete field.
  */
 public function action_delete($id)
 {
     // Find field
     $field = CustomField::find($id);
     // Verify project
     if ($field->project_id != $this->project->id) {
         return $this->show_no_permission();
     }
     // Delete and redirect
     $field->delete();
     if ($this->is_api) {
         return \API::response(1);
     } else {
         Request::redirectTo($this->project->href('settings/custom_fields'));
     }
 }
示例#11
0
 /**
  * Easily respond to different request types.
  */
 protected function respondTo(callable $callback)
 {
     // Is this an XMLHttpRequest? If not, use the request extension or fallback to HTML.
     $format = Request::isXhr() ? 'js' : Request::$properties->get('extension', 'html');
     return $callback($format);
 }
示例#12
0
 /**
  * Handles the permissions listing and saving...
  *
  * Nice sexy DRY code right here, eh?
  */
 public function action_index($type)
 {
     // If the type of permissions is 'groups', set it to 'usergroups'.
     $type = $type == 'groups' ? 'usergroup' : 'role';
     // Has the form been submitted?
     if (Request::method() == 'post') {
         $global_defaults = Permission::defaults(0, 0, $type);
         // Loop over group/role and get id and permissions
         foreach (Request::$post['perm'] as $type_id => $permissions) {
             // Loop over permissions for id and value
             foreach ($permissions as $permission_id => $value) {
                 // Fetch permission
                 $perm = Permission::find($permission_id);
                 // Are we dealing with a default?
                 if ($type_id == 0) {
                     // Does it exist?
                     if ($perm->project_id > 0) {
                         // We we need to delete it?
                         if ($global_defaults[$perm->action]->value == $value) {
                             $perm->delete();
                         } elseif ($perm->value != $value) {
                             $perm->set('value', $value);
                             $perm->save();
                         }
                     } else {
                         // Should we create it?
                         if ($perm->value != $value) {
                             // Create the permission
                             $perm = new Permission(array('project_id' => $this->project->id, 'type' => $type, 'type_id' => $type_id, 'action' => $perm->action, 'value' => $value));
                             $perm->save();
                         }
                     }
                 } elseif ($perm and $perm->type_id == $type_id and $value == -1 and $type_id > 0) {
                     $perm->delete();
                 } elseif ($value == 0 or $value == 1) {
                     // Update
                     if ($perm and $perm->type_id == $type_id) {
                         $perm->value = $value;
                         $perm->save();
                     } else {
                         $perm = new Permission(array('project_id' => $this->project->id, 'type' => $type, 'type_id' => $type_id, 'action' => $perm->action, 'value' => $value));
                         $perm->save();
                     }
                 }
             }
         }
         Request::redirect(Request::requestUri());
     }
     // Setup the page
     $this->permissions_for($type);
 }
示例#13
0
 /**
  * Returns the code for a link unless the current request matches the URL.
  *
  * @param string $label   The label
  * @param string $url     The URL
  * @param array  $options Options for the URL code (class, title, etc)
  *
  * @return string
  */
 public static function linkToUnlessCurrent($label, $url, array $attributes = array())
 {
     if (Request::matches($url)) {
         return $label;
     } else {
         return static::link($label, $url, $attributes);
     }
 }
示例#14
0
 /**
  * Delete tab.
  *
  * @param integer $id Tab ID
  */
 public function action_delete($id)
 {
     CustomTab::find($id)->delete();
     Request::redirectTo('/admin/custom_tabs');
 }
示例#15
0
 /**
  * Returns the URL for sorting the provided ticket column.
  *
  * @param string $column
  *
  * @return string
  */
 public static function sortUrlFor($column)
 {
     // Get current order
     if (isset(Request::$request['order_by'])) {
         $order = explode('.', Request::$request['order_by']);
     } else {
         return Request::requestUri() . (strlen($_SERVER['QUERY_STRING']) ? '&amp;' : '?') . "order_by={$column}.asc";
     }
     // Are we flipping the current sort?
     if ($order[0] == $column) {
         $query = "{$column}." . (strtolower($order[1]) == 'asc' ? 'desc' : 'asc');
     } else {
         $query = "{$column}.{$order[1]}";
     }
     return str_replace("order_by=" . implode('.', $order), "order_by={$query}", Request::requestUri());
 }
示例#16
0
 /**
  * Process the request.
  *
  * @return Route
  */
 public static function process()
 {
     $requestPath = Request::pathInfo();
     if (Request::pathInfo() === '/') {
         return static::getRoute('root');
     }
     foreach (static::$routes as $route) {
         $pattern = static::regex($route->compiledPath());
         if (!in_array(Request::$method, array_map('strtoupper', $route->methods))) {
             continue;
         }
         // Match exact path and request method
         if ($route->path == $requestPath) {
             $route->params = $route->defaults;
             Request::$properties->set($route->params);
             return $route;
         } elseif (preg_match($pattern, $requestPath, $params)) {
             unset($params[0]);
             // Merge params
             $route->params = $params + $route->defaults;
             Request::$properties->set($route->params);
             return $route;
         }
     }
 }
示例#17
0
 /**
  * Set ticket filters.
  */
 public function setFiltersAction()
 {
     $queryString = [];
     $filters = Request::$post->get('filters', [], false);
     // Add filter
     if ($newFilter = Request::$post->get('new_filter') and $newFilter !== '') {
         if (!isset($filters[$newFilter])) {
             $filters[$newFilter] = ['prefix' => '', 'values' => []];
         } else {
             $filters[$newFilter]['values'][] = '';
         }
     }
     foreach ($filters as $name => $filter) {
         $filter['prefix'] = $filter['prefix'] == '-' ? '!' : '';
         // Is this a filter?
         if (!in_array($name, array_keys(TicketFilters::filtersFor($this->currentProject)))) {
             continue;
         }
         if (!isset($filter['values'])) {
             $filter['values'] = [];
         }
         if ($field = CustomField::find('slug', $name)) {
             $queryString[$name] = $filter['prefix'] . implode(',', $filter['values']);
         } else {
             $queryString[$name] = $filter['prefix'] . implode(',', $filter['values']);
         }
     }
     return $this->redirect($this->generateUrl('tickets', ['pslug' => $this->currentProject['slug']]) . '?' . Request::buildQueryString($queryString, false));
 }
示例#18
0
 /**
  * Creates the URI for the specified page.
  *
  * @param integer $page
  *
  * @return string
  */
 public function createUri($page)
 {
     $queryString = $this->query;
     $queryString[] = "page={$page}";
     $queryString = implode('&', $queryString);
     return Request::pathInfo() . "?{$queryString}";
 }