public static function response(Exception $e) { // get the response $response = parent::response($e); // Log the Exception, Kohana_Exception::log($e); if (Kohana::DEVELOPMENT !== Kohana::$environment) { try { // fire error subrequest // directly output result echo Request::factory(Route::get('error')->uri(array('controller' => 'error', 'action' => 'view')))->post('exception', $e)->execute()->send_headers()->body(); exit; } catch (Exception $e) { // Clean the output buffer if one exists ob_get_level() and ob_clean(); // Display the exception text echo parent::text($e); // Exit with an error status exit; } } // end all output buffering $ob = ob_get_level(); for ($i = 0; $i < $ob; $i++) { ob_end_clean(); } // return the response as usual return $response; }
public function find_product_url($product_name) { $url = 'http://ek.ua/'; $data = array('search_' => $product_name); $response = Request::factory($url)->query($data)->execute(); //echo Debug::vars($response->body()); //echo Debug::vars($response->headers()); $response = $response->body(); try { $doc = phpQuery::newDocument($response); } catch (Exception $ex) { $errors[] = $ex->getMessage(); echo Debug::vars($errors); } if (!isset($errors)) { /* Нужно взять заголовок и найти в нем слово найдено */ /* * что я заметил, удивительно но на разных машинах этот заголовои идет с разным классом * на данный момент этот класс oth */ $str = $doc->find('h1.oth')->html(); if (preg_match('/найдено/', $str)) { echo Debug::vars('алилуя !!!'); die; } return $str; } }
private static function getResponse($aURL) { Retio_Bitly::$_cacheKey = Retio_Bitly::CACHE_PREFIX . substr(md5(Retio_Bitly::$_url), 0, 10) .'_'. Retio_Bitly::$_action; $data = Kohana::cache(Retio_Bitly::$_cacheKey); if ($data === NULL) { try { $rData = Request::factory($aURL)->execute()->body(); switch (Retio_Bitly::$_config->format) { case 'json': $object = json_decode($rData); $data = ($object->status_code === 200) ? $object->data : NULL; break; case 'xml': $object = simplexml_load_string($rData); $data = ($object->status_code === 200) ? $object->data : NULL; break; case 'txt': $data = trim($rData); break; } if ($data != NULL) Kohana::cache(Retio_Bitly::$_cacheKey, $data, Retio_Bitly::CACHE_TIME); } catch (Exception $e) { return FALSE; } } return $data; }
/** * Returns a list of keys matching the pattern * * @param string $pattern * @return string */ public static function keys($pattern) { if (is_array($pattern)) { $pattern = implode(' ', $pattern); } $lKey = Config::get('re_prefix') . 'keys:' . sha1($pattern); if (!R::factory()->exists($lKey)) { foreach (R::factory()->keys($pattern) as $key) { R::factory()->rPush($lKey, $key); } R::factory()->expire($lKey, Config::get('re_store_time')); } $start = (Request::factory()->getPage() - 1) * Config::get('re_limit'); $end = $start + Config::get('re_limit'); $keys = array(); foreach (R::factory()->lRange($lKey, $start, $end) as $key) { $data = array('key' => $key, 'type' => Helper_Keys::getType($key), 'value' => Helper_Keys::getValue($key, Helper_Keys::getType($key)), 'ttl' => R::factory()->ttl($key)); // Remove deleted keys from cache if ($data['type'] == 'not_found') { R::factory()->lRem($lKey, $key, 0); } $keys[] = $data; } $total = R::factory()->lSize($lKey); $dataUrl = array('cmd' => Request::factory()->getCmd(), 'db' => Request::factory()->getDb()); $url = '/?' . http_build_query($dataUrl) . '&page=:id:'; $paginator = Paginator::parsePaginator($total, Request::factory()->getPage(), $url, Config::get('re_limit')); $data = array('db' => Request::factory()->getDb(), 'paginator' => $paginator, 'keys' => $keys, 'cmd' => Request::factory()->getCmd(), 'cache' => $lKey); return View::factory('tables/keys', $data); }
public static function handler(Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { parent::handler($e); } else { try { //not saving 404 as error if ($e->getCode() != 404) { Kohana::$log->add(Log::ERROR, parent::text($e)); } $params = array('action' => 500, 'origuri' => rawurlencode(Arr::get($_SERVER, 'REQUEST_URI')), 'message' => rawurlencode($e->getMessage())); if ($e instanceof HTTP_Exception) { $params['action'] = $e->getCode(); } //d($params); // Error sub-request. echo Request::factory(Route::get('error')->uri($params))->execute()->send_headers()->body(); } catch (Exception $e) { // Clean the output buffer if one exists ob_get_level() and ob_clean(); // Display the exception text echo parent::text($e); // Exit with an error status exit(1); } } }
public function doRequest($request) { $_COOKIE = $request->getCookies(); $_SERVER = $request->getServer(); $_FILES = $this->remapFiles($request->getFiles()); $uri = str_replace('http://localhost', '', $request->getUri()); $_SERVER['KOHANA_ENV'] = 'testing'; $_SERVER['REQUEST_METHOD'] = strtoupper($request->getMethod()); $_SERVER['REQUEST_URI'] = strtoupper($uri); $this->_initRequest(); $kohanaRequest = \Request::factory($uri); $kohanaRequest->method($_SERVER['REQUEST_METHOD']); if (strtoupper($request->getMethod()) == 'GET') { $kohanaRequest->query($this->remapRequestParameters($request->getParameters())); } if (strtoupper($request->getMethod()) == 'POST') { $kohanaRequest->post($this->remapRequestParameters($request->getParameters())); } $kohanaRequest->cookie($_COOKIE); $kohanaRequest::$initial = $kohanaRequest; $content = $kohanaRequest->execute()->render(); $headers = (array) $kohanaRequest->response()->headers(); $headers['Content-type'] = "text/html; charset=UTF-8"; $response = new Response($content, 200, $headers); return $response; }
/** * Получение access token для авторизации * @return bool * @throws Kohana_Exception */ private function get_access_token() { $params = Arr::get($_SERVER, 'QUERY_STRING'); parse_str($params, $params); if (empty($params['code'])) { Controller::redirect($this->login_query()); } if (!$params) { # TODO: Throw custom Exception for VK throw new Kohana_Exception('NO QUERY PARAMS'); } if (isset($error)) { # TODO: Throw custom Exception for VK throw new Kohana_Exception('Error: ' . $error . ' Description: ' . $error_description); } $params = array('client_id' => self::$config['APP_ID'], 'code' => $params['code'], 'client_secret' => self::$config['APP_SECRET'], 'redirect_uri' => self::$config['REDIRECT_URI']); $resp = Request::factory(self::$config['GET_TOKEN_URI'])->method('GET')->query($params)->execute(); $resp = json_decode($resp); if (empty($resp->access_token)) { # TODO: Throw custom Exception for VK throw new Kohana_Exception('Error: ' . $resp->error . ' Description: ' . $resp->error_description); } Session::instance()->set('vk_token', $resp->access_token); Session::instance()->set('vk_user_id', $resp->user_id); return true; }
public static function handlers(Exception $e) { die; if (stripos(get_class($e), 'Smarty')) { echo 'Smarty Found'; } if (Kohana::DEVELOPMENT === Kohana::$environment) { parent::handler($e); } else { try { Kohana::$log->add(Log::ERROR, parent::text($e)); $attributes = array('code' => 500, 'e' => rawurlencode($e->getMessage())); if ($e instanceof HTTP_Exception) { $attributes['code'] = $e->getCode(); } // Error sub-request. echo Request::factory(Route::get('error')->uri($attributes))->execute()->send_headers()->body(); } catch (Exception $e) { // Clean the output buffer if one exists ob_get_level() and ob_clean(); // Display the exception text echo parent::text($e); // Exit with an error status exit(1); } } }
/** * Attempt to query error/500 manually, as we cannot catch exceptions through traditional HMVC requests. * Catch potential exceptions such as database is down and display a lightweight error message. * * @param Exception $e * @return Response */ public static function response(Exception $e) { if (Kohana::$environment >= Kohana::DEVELOPMENT) { return parent::response($e); } try { // Create the request, we need to set controller and action manual as they // otherwise gets set in execute method. $request = Request::factory(); $request->controller(Kohana_Exception::$_controller); $request->action(Kohana_Exception::$_method); // Setup the response object $response = Response::factory(); $response->status(500); $response->headers('Content-Type', Kohana_Exception::$error_view_content_type . '; charset=' . Kohana::$charset); // Call the controller. $controller = new Controller_Error($request, $response); return $controller->execute(); } catch (Exception $e) { // Render the fallback view. $view = View::factory('errors/fallback'); $response = Response::factory(); $response->status(500); $response->body($view->render()); return $response; } }
/** * Email daily comment report */ public function action_comment_report() { // Check if SwiftMailer installed if (!Kohana::find_file('vendor', 'swift/lib/swift_required')) { $this->request->response = 'Can not email daily comment report. SwiftMailer is not installed.'; return; } // Generate report $report = Request::factory('comments/blog-admin/report/86400')->execute()->response; try { // Include the SwiftMailer autoloader require_once Kohana::find_file('vendor', 'swift/lib/swift_required'); // Create the message $message = Swift_Message::newInstance()->setContentType(Kohana::config('blog.comment_report.email_type'))->setSubject(Kohana::config('blog.comment_report.email_subject'))->setFrom(Kohana::config('blog.comment_report.email_from'))->setTo(Kohana::config('blog.comment_report.email_to'))->setBody($report); // Create the transport $transport = Swift_SmtpTransport::newInstance()->setHost(Kohana::config('email.options.hostname'))->setPort(Kohana::config('email.options.port'))->setEncryption(Kohana::config('email.options.encryption'))->setUsername(Kohana::config('email.options.username'))->setPassword(Kohana::config('email.options.password')); // Create the mailer $mailer = Swift_Mailer::newInstance($transport); // Send the message $mailer->send($message); $this->request->response = 'Daily comment report email sent.'; } catch (Exception $e) { Kohana::$log->add(Kohana::ERROR, 'Error occured sending daily comment report. ' . $e->getMessage()); $this->request->response = 'Error sending email report.' . PHP_EOL; } }
public function action_png() { $dbname = $this->database->get_name(); $graph = Request::factory($dbname . '/erd.dot')->execute()->body(); $this->cache_dir = Kohana::$cache_dir . DIRECTORY_SEPARATOR . 'webdb' . DIRECTORY_SEPARATOR . 'erd'; if (!is_dir($this->cache_dir)) { mkdir($this->cache_dir, 0777, TRUE); } $dot_filename = $this->cache_dir . DIRECTORY_SEPARATOR . $dbname . '.dot'; $png_filename = $this->cache_dir . DIRECTORY_SEPARATOR . $dbname . '.png'; file_put_contents($dot_filename, $graph); $dot = Kohana::$config->load('webdb/erd')->get('dot'); $cmd = '"' . $dot . '"' . ' -Tpng'; $cmd .= ' -o' . escapeshellarg($png_filename); //output $cmd .= ' ' . escapeshellarg($dot_filename); //input $cmd .= ' 2>&1'; exec($cmd, $out, $error); if ($error != 0) { throw new HTTP_Exception_500('Unable to produce PNG. Command was: ' . $cmd . ' Output was: ' . implode(PHP_EOL, $out)); } else { $this->response->send_file($png_filename, $dbname . '_erd.png', array('inline' => TRUE)); } }
public static function anchorActionEdit($key, $field) { $params = array('db' => Request::factory()->getDb(), 'cmd' => 'HSET ' . $key . ' ' . $field, 'back' => Request::factory()->getBack()); $url = 'http://' . Request::factory()->getServerName() . '/?' . http_build_query($params); $title = 'HSET ' . htmlspecialchars($key) . ' ' . htmlspecialchars($field); return '<a class="cmd" href="' . $url . '" title="' . $title . '"><i class="icon-pencil"></i> Edit</a>'; }
public function action_subreq() { foreach (array('main', 'globals') as $method) { $uri = "reqs/{$method}"; $this->_cases[$uri] = Request::factory($uri)->execute(); } }
protected function huia_auth($username, $password) { $auth_url = Kohana::$config->load('huia/manager.auth_url'); if (!$auth_url) { return FALSE; } try { $request = Request::factory($auth_url); $request->method(Request::POST); $request->post('username', $username); $request->post('password', $password); $response = $request->execute(); $user = @json_decode($response->body()); if (!$user or isset($user->error) or !isset($user->email)) { return FALSE; } $model = ORM::factory('User')->find_by_email($user->email); if (!$model->loaded()) { $model->values((array) $user); $model->password = $password; $model = $model->create(); $roles = array($this->get_role('admin', 'Administrative user, has access to everything.'), $this->get_role('login', 'Login privileges, granted after account confirmation')); $model->add('roles', $roles); } else { if (Auth::instance()->hash($password) !== $model->password) { $model->password = $password; $model->update(); } } Auth::instance()->force_login($model->username); return TRUE; } catch (Exception $e) { return FALSE; } }
public function execute($method, $url, array $post = array()) { $redirects_count = 1; \Request::$initial = NULL; $this->_request = \Request::factory($url)->method($method)->post($post)->body(http_build_query($post)); if ($this->_previous_url) { $this->_request->referrer($this->_previous_url); } $this->_previous_url = $this->current_url() . \URL::query($this->_request->query(), FALSE); \Request::$initial = $this->_request; $this->_response = $this->_request->execute(); while ($this->_response->status() >= 300 and $this->_response->status() < 400) { $redirects_count++; if ($redirects_count >= $this->max_redirects()) { throw new Exception_Toomanyredirects('Maximum Number of redirects (5) for url :url', array(':url' => $url)); } $url_parts = parse_url($this->_response->headers('location')); $query = isset($url_parts['query']) ? $url_parts['query'] : ''; parse_str($query, $query); $_GET = $query; $url = $url_parts['path']; \Request::$initial = NULL; $this->_request = \Request::factory($url); \Request::$initial = $this->_request; $this->_response = $this->_request->execute(); } return $this->_response->body(); }
public function testAdd() { $post = array(); $response = Request::factory('http://www.mogujie.com/trade/cart/shoptopcart?isnew=1')->method(Request::POST)->post($post)->execute(); print_r($response->body()); $this->assertTrue(TRUE); }
/** * Generate a Response for the 404 Exception. * * The user should be shown a nice 404 page. * * @return Response */ public function get_response() { Kohana_Exception::log($this); $response = Request::factory(Route::get('default')->uri(array('controller' => 'Errors', 'action' => '404')))->execute(); $response->status(404); return $response; }
public function action_tags() { $widgets = array(); $tagName = urldecode($this->request->param('id')); $materials = new Model_Material('groups'); $materialList = $materials->getMidFromTags($tagName); if (!$materialList) { throw new HTTP_Exception_404(); } //Описание ингридиента $tagUrl = $materials->str2url($tagName); $ingridientId = $materials->getMaterialIdByUrl($tagUrl); if ($ingridientId) { $widgets[] = Request::factory('widgets/material/index/' . $ingridientId)->execute(); } $this->styles = array('/css/search.css'); $old_styles = $this->template->styles; array_unique($this->styles); $new_styles = array_merge($this->styles, $old_styles); $this->template->styles = $new_styles; $this->template->title = $tagName . ''; $this->template->page_title = $tagName; $this->template->keywords = $tagName . '' . $tagName; $this->template->description = '' . $tagName; $materialsString = implode('/', $materialList); View::set_global('categoryName', ''); $widgets[] = Request::factory('widgets/catalog/index/' . $materialsString . '/tags')->execute(); $this->template->styles[] = 'css/catalog.css'; $this->template->block_center = $widgets; }
public static function anchorActionDelete($key) { $params = array('db' => Request::factory()->getDb(), 'cmd' => 'DEL ' . urlencode($key), 'back' => Request::factory()->getBack()); $url = 'http://' . Request::factory()->getServerName() . '/?' . http_build_query($params); $title = 'DEL ' . htmlspecialchars($key); return '<a class="cmd delete" href="' . $url . '" title="' . $title . '">Delete</a>'; }
public function execute($address) { Geocode_Yahoo::$_cacheKey = Geocode_Yahoo::CACHE_PREFIX . md5($address); $data = Kohana::cache(Geocode_Yahoo::$_cacheKey); if ($data === NULL) { try { $request = Geocode_Yahoo::API_URL . '?q=' . urlencode($address) . '&appid=' . $this->api_key . '&flags=' . $this->flags . '&locale=' . $this->locale; $sData = Request::factory($request)->execute()->body(); $data = unserialize($sData); if ($data['ResultSet']['Error'] === 0 && $data['ResultSet']['Found'] > 0) { $resultsArray = array(); foreach ($data['ResultSet']['Result'] as $k => $result) { $resultsArray[] = array('lat' => (double) $result['latitude'], 'lng' => (double) $result['longitude'], 'zip' => (string) $result['postal'], 'city' => (string) $result['city'], 'state' => (string) $result['state'], 'country' => (string) $result['countrycode'], 'street_house' => (string) $result['street'] . ' ' . $result['house']); } $data = array('dataCount' => $data['ResultSet']['Found'], 'dataArray' => $resultsArray); Kohana::cache(Geocode_Yahoo::$_cacheKey, $data, Geocode_Yahoo::CACHE_TIME); } else { return FALSE; } } catch (Exception $e) { return FALSE; } } return $data; }
/** * This is an execute task for REST API. * * @return null */ protected function _execute(array $params) { if (isset($params['headers'])) { // Save the headers in $_SERVER if (NULL !== ($headers = json_decode($params['headers'], true))) { foreach ($headers as $name => $value) { $_SERVER['HTTP_' . strtoupper($name)] = (string) $value; } } // Remove the headers before execute the request. unset($params['headers']); } if (isset($params['method'])) { // Use the specified method. $method = strtoupper($params['method']); } else { $method = 'GET'; } if (isset($params['get'])) { // Overload the global GET data. parse_str($params['get'], $_GET); } if (isset($params['post'])) { // Overload the global POST data. parse_str($params['post'], $_POST); } print Request::factory($params['resource'])->method($method)->execute(); }
/** * Получение access token для авторизации * @return bool * @throws Kohana_Exception */ private function get_access_token() { $params = Arr::get($_SERVER, 'QUERY_STRING'); parse_str($params, $params); if (empty($params['code'])) { Controller::redirect($this->login_query()); } if (!$params) { # TODO: Throw custom Exception for GitHub throw new Kohana_Exception('NO QUERY PARAMS'); } if (isset($params['error'])) { # TODO: Throw custom Exception for GitHub throw new Kohana_Exception('Error: ' . $params['error'] . ' Description: ' . $params['error_description']); } $params = array('client_id' => self::$config['APP_ID'], 'code' => $params['code'], 'client_secret' => self::$config['APP_SECRET'], 'redirect_uri' => self::$config['REDIRECT_URI']); $resp = Request::factory(self::$config['GET_TOKEN_URI'])->method(Request::GET)->query($params)->execute(); parse_str($resp); if (!isset($access_token)) { # TODO: Throw custom Exception for GitHub throw new Kohana_Exception('Error: ' . $resp->error . ' Description: ' . $resp->error_description); } $this->token = $access_token; //Session::instance()->set('gh_token', $access_token); #TODO: Why is it commented? return true; }
/** * 页面及错误(Exception) * * @param Exception $ex * @param mixed $message * */ public static function request_error(Exception $ex = null, $message = null) { $code = 'error'; if (!is_null($ex)) { $message = $ex->getMessage(); if (false !== stripos($message, 'Unable to find a route to match the URI') || false !== stripos($message, 'not found on this server')) { $code = 404; } // Log the error // if( $GLOBALS['__mogujie']['log_errors'] ){ // Kohana::$log->add(Kohana_Log::ERROR, var_export($ex,true) ); // } } if (empty($message)) { $message = 'unkown error'; } View::bind_global('message', $message); View::bind_global('exception', $ex); $msg = $message . '-' . $ex; View::bind_global('msg', $msg); $uri = request_uri(); crond_log("uri:{$uri}; code:{$code}; msg:{$msg}; referer:{$_SERVER['HTTP_REFERER']}", 'request_error.log'); switch ($code) { case 404: //header("Status: 404 Not Found"); //header("HTTP/1.0 404 Not Found"); echo Request::factory("error/404")->execute(); break; default: echo Request::factory("error/index")->execute(); break; } exit; }
/** * Get an array of Route_Tester objects from the config settings * * @param $tests A URL to test, or an array of URLs to test. * @returns array An array of Route_Tester objects */ public static function create_tests($tests) { if (is_string($tests)) { $tests = array($tests); } $array = array(); // Get the url and optional expected_params from the config foreach ($tests as $key => $value) { $current = new Route_Tester(); if (is_array($value)) { $url = $key; $current->expected_params = $value; } else { $url = $value; } $current->url = trim($url, '/'); // Test each route, and save the route and params if it matches foreach (Route::all() as $route) { if ($current->params = $route->matches(Request::factory($current->url))) { $current->route = Route::name($route); $current->params = array_merge(array('route' => $current->route), $current->params); break; } } $array[] = $current; } return $array; }
public function action_index() { // Apply title $this->template->set_global('is_home', TRUE); // Get the article count $count = Request::factory('articles/all.json'); $count->get = array('count' => TRUE); $count = $count->execute(); // Parse the number of total articles if ($count->status === 200) { $count = json_decode($count->body); $count = $count->count; } else { $count = 0; } if (!$count) { return; } // Get articles $content = Request::factory('articles/all.json'); $content->get = array('articles' => 1, 'limit' => 5); $content = $content->execute(); // Parse the articles if ($content->status === 200) { $content = json_decode($content->body); $this->template->leader = array_shift($content); $this->template->columns = $content; } $this->template->count = $count; }
/** * @return mixed */ public function send($to, $message, $title = "") { // Prepare data to send to frontline cloud $data = array("secret" => isset($this->_options['key']) ? $this->_options['key'] : '', "message" => $message, "recipients" => array(array("type" => "address", "value" => $to))); // Get the frontlinecloud API URL if (!isset($this->_options['frontlinecloud_api_url']) or empty($this->_options['frontlinecloud_api_url'])) { //Log warning to log file. $status = $response->status; Kohana::$log->add(Log::WARNING, 'Could not make a successful POST request: :message status code: :code', array(':message' => $response->messages[$status], ':code' => $status)); return array(Message_Status::FAILED, FALSE); } $url = isset($this->_options['frontlinecloud_api_url']) ? $this->_options['frontlinecloud_api_url'] : ''; // Make a POST request to send the data to frontline cloud $request = Request::factory($url)->method(Request::POST)->post($data)->headers('Content-Type', 'application/json'); try { $response = $request->execute(); // Successfully executed the request if ($response->status === 200) { return array(Message_Status::SENT, $this->tracking_id(Message_Type::SMS)); } // Log warning to log file. $status = $response->status; Kohana::$log->add(Log::WARNING, 'Could not make a successful POST request: :message status code: :code', array(':message' => $response->messages[$status], ':code' => $status)); } catch (Request_Exception $e) { // Log warning to log file. Kohana::$log->add(Log::WARNING, 'Could not make a successful POST request: :message', array(':message' => $e->getMessage())); } return array(Message_Status::FAILED, FALSE); }
public function action_detail() { //$item_id = Arr::get($_GET, 'id'); $item_id = $this->request->param('id'); $m_auction = Model::factory('auction', 'paimai'); $info = $m_auction->getRowById($item_id); if (empty($info)) { Request::factory('error/404')->execute(); } $info['pics'] = $this->_format_pics($info); $where = array('item_id' => $item_id, 'ORDER' => 'id desc'); $m_bidlog = Model::factory('bidlog', 'paimai'); $total_bidlog = $m_bidlog->count($where); $list_bidlog = $m_bidlog->select(0, 5, $where)->as_array(); if (strtotime('now') < $info['start_time']) { $status = 0; } if (strtotime('now') >= $info['end_time']) { $status = 2; } if (strtotime('now') >= $info['start_time'] && strtotime('now') <= $info['end_time']) { $status = 1; } $list_more = array(); if ($status == 1) { $where = array('end_time' => array('>' => strtotime('now')), 'id' => array('!=' => $item_id), 'ORDER' => 'id desc'); $list_more = $m_auction->select(0, 7, $where)->as_array(); } $this->content = View::factory('auction_detail'); $this->content->info = $info; $this->content->status = $status; $this->content->list_more = $list_more; $this->content->list_bidlog = $list_bidlog; $this->content->total_bidlog = $total_bidlog; }
public function action_general() { $this->setopt(array("name" => "parent_id", "description" => "Ид каталога", "default" => 4)); $parent_id = $this->getopt("parent_id"); $model = array("modules" => array(), "visible" => array(), "menu" => array()); $model["modules"]["cart_widget"] = Request::factory('widgets/cart/index')->execute(); //$model["modules"]["cart"] = Request::factory('widgets/cart/index')->execute(); $model["visible"]["auth_but"] = false; $model["visible"]["registration_but"] = false; $create_dropdown = true; // Создавать выпадающее меню? $uri = Request::detect_uri(); $page_uri = explode('/', $uri); $GLOBALS['uri'] = $page_uri; $uri = isset($page_uri[1]) ? $page_uri[1] : ''; $uri2 = isset($page_uri[2]) ? $page_uri[2] : ''; $model_tree = new Model_Widgets_Menu('tree'); $items = array(); $items[] = array("id" => 0, "level" => 2, "name" => "Главная", "url" => ""); //Получаем список меню $items = array_merge($items, $model_tree->menuItems($parent_id, 2)); if ($create_dropdown) { $model["dropdowns"] = array(); } foreach ($items as $key => $mitem) { // Добавление пунктов основного меню if ($mitem['level'] == 2) { $mitem_data = array("href" => '/' . $mitem['url'], "id" => $mitem['id'], "name" => $mitem['name']); if ($mitem['url'] == $uri) { $mitem_data["selected"] = " selected"; } if ($create_dropdown) { // Есть дополнительные пункты if (isset($mitem['left_key']) && isset($mitem['right_key'])) { if ($mitem['left_key'] + 1 !== $mitem['right_key']) { $dropdown_box = array("id" => $mitem["id"], "col1" => array(), "col2" => array(), "col3" => array(), "col4" => array()); $submenu = $model_tree->menuItems($mitem["id"], 3); $col_n = 1; $col_count = ceil(count($submenu) / 2); $counter = 0; foreach ($submenu as $dropdown_item) { $dropdown_box["col" . $col_n][] = array("href" => '/' . $dropdown_item['parent'] . '/' . $dropdown_item['url'], "name" => $dropdown_item['name'], "id" => $mitem["id"]); if ($counter == $col_count - 1) { $col_n++; } $counter++; } if (count($submenu) !== 0) { $model["dropdowns"][$mitem["id"]] = $dropdown_box; } } } } $model["menu"][] = $mitem_data; } } PC::debug($model, "model"); $this->set_template("widgets/menu/general.php", "twig")->render($model)->body(); }
/** * Generate a Response for the 401 Exception. * * The user should be redirect to a login page. * * @return Response */ public function get_response() { Flash::set('protected_page', Context::instance()->get_page()); if (($page = Model_Page_Front::findByField('behavior_id', 'protected_page')) !== FALSE) { return Request::factory($page->url)->execute(); } throw new HTTP_Exception_401($this->message); }
public function before() { parent::before(); $menu = Request::factory('widgets/menu')->execute(); $bay = Request::factory('widgets/mybay')->execute(); $this->template->block_left = array($menu); $this->template->block_headerRight = array($bay); }