private function init() { $this->session = Session::getInstance(); $this->request = Request::getInstance(); $this->router = Router::getInstance(); $this->view = View::getInstance(); }
/** * Construct */ public function __construct() { parent::__construct(); $this->JSRMS = new JSRMS(); $this->JSRMS->requireResource('system'); $this->muteExpectedErrors(); $this->setCacheDir(SYSTEM_ROOT . '/classes/smarty/cache/'); $this->setCompileDir(SYSTEM_ROOT . '/classes/smarty/templates_c/'); $this->setTemplateDir(SYSTEM_ROOT . '/view/'); $this->registerObject('Router', Router::getInstance(), array('build'), false); $this->registerObject('L10N', System::getLanguage(), array('_'), false); $this->assign('LoggedIn', System::getUser() != NULL); $this->assign('User', System::getUser()); $this->assign('Navigation', Navigation::$elements); $this->assign('LangStrings', System::getLanguage()->getAllStrings()); // Configuration $this->assign('HTTP_BASEDIR', System::getBaseURL()); $this->assign('MOD_REWRITE', MOD_REWRITE); $this->assign('MAX_UPLOAD_SIZE', Utils::maxUploadSize()); if (System::getSession()->getData('successMsg', '') != '') { $this->assign('successMsg', System::getSession()->getData('successMsg', '')); System::getSession()->setData('successMsg', ''); } if (System::getSession()->getData('errorMsg', '') != '') { $this->assign('errorMsg', System::getSession()->getData('errorMsg', '')); System::getSession()->setData('errorMsg', ''); } if (System::getSession()->getData('infoMsg', '') != '') { $this->assign('infoMsg', System::getSession()->getData('infoMsg', '')); System::getSession()->setData('infoMsg', ''); } }
/** * Start the application */ public function start() { //match the current route $route = Router::getInstance()->matchRoute(); if ($route) { //rewrite the GET $_GET = array('Module' => $route['route']['Module'], 'Controller' => $route['route']['Controller'], 'Action' => $route['route']['Action']); if (!empty($route['params'])) { $_GET = array_merge($_GET, $route['params']); } switch ($this->renderAction($route)) { default: case View::HTML: //check if layout is not disabled if (!Layout::getInstance()->isDisabled($route['route']['Module'], $route['route']['Controller'], $route['route']['Action'])) { Layout::getInstance()->loadLayout($route); } else { //if disabled just show html echo self::$action; } break; case View::JSON: //serve the json value header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 08 Jul 1985 19:15:00 GMT'); header('Content-type: application/json'); exit(self::$action); break; } } }
function parse($url) { // Get an instance of the Router $router =& Router::getInstance(); // Get an array of all defined prefixes $prefixes = $router->prefixes(); // Only proceed if prefixes have been defined... if (is_array($prefixes) && count($prefixes, COUNT_RECURSIVE) > 0) { // Get the sub-domain from the current URL, and convert to lower-case $url_parts = explode('.', env('HTTP_HOST')); $subdomain = strtolower(trim($url_parts[0])); // Assuming all routing prefixes are lower-case, check for a match between a prefix and the current URL sub-domain if (in_array($subdomain, $prefixes)) { // Iterate each defined route... foreach ($router->routes as $route) { // Check to make sure we are not trying to modify our own route definition... if (!$route instanceof SubDomainPrefixRoute) { // Check, just in case... if (isset($route->defaults)) { // If a prefix has not been defined for this particular route, then we can add a prefix using the current URL sub-domain... if (!isset($route->defaults['prefix'])) { $route->defaults['prefix'] = $subdomain; $route->defaults[$subdomain] = true; } } } } } } return false; // We do not want this route to be matched, so we return false in order that Cake can continue checking routes for a match }
/** * Create new request and sends email to user * @static * @param string Mail adress * @throws MailFailureException, UserNotFoundException */ public static function createRequest($mail) { LostPW::cleanUp(); $user = User::find('email', $mail); if ($user == NULL) { throw new UserNotFoundException(); } // Delete old requests $sql = System::getDatabase()->prepare('DELETE FROM lostpw WHERE user_ID = :uid'); $sql->execute(array(':uid' => $user->uid)); // Create new request $hash = LostPW::createHash(); $sql = System::getDatabase()->prepare('INSERT INTO lostpw (user_ID, hash, time) VALUES (:uid, :hash, :time)'); $sql->execute(array(':uid' => $user->uid, ':hash' => $hash, ':time' => time())); // Send Mail $content = new Template(); $content->assign('link', Router::getInstance()->build('AuthController', 'lostpw_check', array('hash' => $hash))); $content->assign('user', $user); $content->assign('title', System::getLanguage()->_('LostPW')); // Determine template file $tpl = 'mails/lostpw.' . LANGUAGE . '.tpl'; foreach ($content->getTemplateDir() as $dir) { $file = 'mails/lostpw.' . $user->lang . '.tpl'; if (file_exists($dir . $file)) { $tpl = $file; break; } } $mail = new Mail(System::getLanguage()->_('LostPW'), $content->fetch($tpl), $user); $mail->send(); }
private function loadFile() { if ($this->file != NULL) { return; } $this->file = File::find('alias', $this->getParam('alias', '')); if ($this->file == NULL) { System::displayError(System::getLanguage()->_('ErrorFileNotFound'), '404 Not Found'); } if (System::getUser() != NULL) { $user_id = System::getUser()->uid; } else { $user_id = -1; } if ($user_id != $this->file->uid) { if ($this->file->permission == FilePermissions::PRIVATE_ACCESS) { System::displayError(System::getLanguage()->_('PermissionDenied'), '403 Forbidden'); exit; } elseif ($this->file->permission == FilePermissions::RESTRICTED_ACCESS) { if (is_array(System::getSession()->getData("authenticatedFiles"))) { if (!in_array($this->file->alias, System::getSession()->getData("authenticatedFiles"))) { System::forwardToRoute(Router::getInstance()->build('AuthController', 'authenticateFile', $this->file)); exit; } } else { System::forwardToRoute(Router::getInstance()->build('AuthController', 'authenticateFile', $this->file)); exit; } } } }
public function __construct() { $fc = Router::getInstance(); $this->params = $fc->getParams(); $this->format = $fc->getFormat(); $this->makeObj(); }
public function testNegotiatesPlaceholders() { $router = Router::getInstance(true); $router->register('abc/:id', 'test'); $result = $router->negotiate('abc/1'); $this->assertEquals($result, array('actions' => array('test'), 'args' => array('id' => 1))); }
/** * Setups basic components * @return boolean */ function setup() { $this->ini = ParserINI::getConfig('site'); $this->router = Router::getInstance(); $this->sAction = $this->router->getData(); $this->user = User::loadFromSession(); return true; }
public function index() { $user = System::getUser(); $form = new Form('form-profile'); $form->setAttribute('data-noajax', 'true'); $form->binding = $user; $fieldset = new Fieldset(System::getLanguage()->_('General')); $firstname = new Text('firstname', System::getLanguage()->_('Firstname')); $firstname->binding = new Databinding('firstname'); $lastname = new Text('lastname', System::getLanguage()->_('Lastname')); $lastname->binding = new Databinding('lastname'); $email = new Text('email', System::getLanguage()->_('EMail'), true); $email->binding = new Databinding('email'); $email->blacklist = $this->getListOfMailAdresses($user); $email->error_msg[4] = System::getLanguage()->_('ErrorMailAdressAlreadyExists'); $language = new Radiobox('lang', System::getLanguage()->_('Language'), L10N::getLanguages()); $language->binding = new Databinding('lang'); $fieldset->addElements($firstname, $lastname, $email, $language); $form->addElements($fieldset); $fieldset = new Fieldset(System::getLanguage()->_('Password')); $password = new Password('password', System::getLanguage()->_('Password')); $password->minlength = PASSWORD_MIN_LENGTH; $password->binding = new Databinding('password'); $password2 = new Password('password2', System::getLanguage()->_('ReenterPassword')); $fieldset->addElements($password, $password2); $form->addElements($fieldset); $fieldset = new Fieldset(System::getLanguage()->_('Settings')); $quota = new Text('quota', System::getLanguage()->_('Quota')); if ($user->quota > 0) { $quota->value = System::getLanguage()->_('QuotaAvailabe', Utils::formatBytes($user->getFreeSpace()), Utils::formatBytes($user->quota)); } else { $quota->value = System::getLanguage()->_('Unlimited'); } $quota->readonly = true; $fieldset->addElements($quota); $form->addElements($fieldset); if (Utils::getPOST('submit', false) !== false) { if (!empty($password->value) && $password->value != $password2->value) { $password2->error = System::getLanguage()->_('ErrorInvalidPasswords'); } else { if ($form->validate()) { $form->save(); System::getUser()->save(); System::getSession()->setData('successMsg', System::getLanguage()->_('ProfileUpdated')); System::forwardToRoute(Router::getInstance()->build('ProfileController', 'index')); exit; } } } else { $form->fill(); } $form->setSubmit(new Button(System::getLanguage()->_('Save'), 'floppy-disk')); $smarty = new Template(); $smarty->assign('title', System::getLanguage()->_('MyProfile')); $smarty->assign('heading', System::getLanguage()->_('MyProfile')); $smarty->assign('form', $form->__toString()); $smarty->display('form.tpl'); }
public function run() { $this->init(); if (!Router::getInstance()->route($_SERVER['REQUEST_METHOD'], Uri::detectPath())) { // No valid route found http_response_code(404); echo '<h1>Page not found.</h1>'; } }
public function Load() { $module = Router::getInstance()->getModule(); $file = $this->ent['CONF_FILE'] = $this->ent['CONF_FILE'] ?: 'Conf.php'; $filep = $this->ent['APP_PATH'] . 'Modules/' . $this->app['modulelist'][$module] . '/' . $file; $this->moduleConfig = G($filep); //configmix $this->mixConfig($module); return true; }
/** * Checks if user is authentificated * if not - user is redirected to login page */ public final function checkAuthentification() { if (System::getUser() == NULL) { if (System::$isXHR) { System::displayError(System::getLanguage()->_('PermissionDenied'), '403 Forbidden'); } else { System::forwardToRoute(Router::getInstance()->build('AuthController', 'login')); exit; } } }
public static function get($name = null, $default = null) { if (!static::$params) { static::$params = Router::getInstance()->request()->params(); } if ($name) { return isset(static::$params[$name]) ? static::$params[$name] : $default; } else { return static::$params; } }
/** * Singleton * @return app */ public static function getInstance() { if (self::$self != NULL) { return self::$self; } self::$self = new self(); /// Получение параметров конфигурации из файла self::$config = (include __NGN__ . '/config.inc'); /// Подключение простого модуля кэширования с помощью APC # include(__SYSTEM__.'/aeon.cache.php'); # self::$cache = new SimpleCache(); /// Если есть APC храним в нём список helper'ов /* if(__APC__){ if(apc_exists('helpers-list')) $ext = json_decode(apc_fetch('helpers-list'), true); else { $ext = glob(__HELPERS__.'/*.php'); apc_add('helpers-list', json_encode($ext), 2); } } else { $ext = glob(__HELPERS__.'/*.php'); }; */ /// Модуль авторизации # self::$extensions['auth'] = \Auth::getInstance(); /* /// Подключаем Helper'ы foreach($ext as $v) { include($v); $ext_name = substr(basename($v), 0, -4); $ext_class_name = '\Helper\\'.$ext_name; self::$extensions[$ext_name] = $ext_class_name::getInstance(self::$self); }; unset($ext); */ include __SYSTEM__ . '/aeon.local.php'; \Eva\Local::getInstance(self::$self); /// Сайт работает с БД? if (self::getParam('db:enabled')) { try { /// Пытаемся подключится self::$db = new PDO('mysql:host=' . self::getParam('db:server') . '; dbname=' . self::getParam('db:name'), self::getParam('db:user'), self::getParam('db:password'), array(PDO::ATTR_PERSISTENT => true)); self::$db->query('SET character_set_client="utf8", character_set_results="utf8", collation_connection="cp1251_general_ci"'); } catch (Exception $e) { /// Падаем и ложим весь сайт error_log('PDO is not supported on this OS! Please, contact your administrator!', 0); msg503(); } } /// Роутер self::$router = \Router::getInstance(); /// Возвращаем экземпляр класса движка return self::$self; }
protected function __construct() { Loader::registerNamespace('MVCFramework', dirname(__FILE__) . DIRECTORY_SEPARATOR); Loader::registerAutoLoad(); $this->_config = Config::getInstance(); //if config folder is not set, use default one if ($this->_config->getConfigFolder() == null) { $this->setConfigFolder('../config'); } $this->registerRootNamespace(); $this->_router = Router::getInstance(); }
public function render($strApplicationName) { if (!empty($this->strForceCssFile)) { $strCssFile = $this->strForceCssFile; } else { $objRouter = Router::getInstance(); $objCurrentRoute = $objRouter->getCurrentRoute(); $strCssFile = $objCurrentRoute->strRouteName . '_' . $objCurrentRoute->strMethodName; } $strApplicationBaseUrl = \webcitron\Subframe\Application::url(); $strCssHhtml = sprintf('<link rel="stylesheet" href="%s/%s/css/%s.css?%s" />', $strApplicationBaseUrl, $strApplicationName, $strCssFile, $this->strCurrentCommit); return $strCssHhtml; }
/** * The constructor of FWRestServer * * @return void */ public function __construct() { $this->_config = Config::getInstance(); $this->_baseURL = $this->_config->getParam("baseurl"); $router = Router::getInstance(); $routes = $router->getRestRoutes(); if (count($routes) > 0) { foreach ($routes as $route) { $this->_addService($route); } } $this->serve(); $this->_process(); }
protected function invokeHandler() { $error = array(); if (Utils::isLocalhostServer()) { $error[] = System::getLanguage()->_('NoLocalhost'); } if ($this->file->permission != FilePermissions::PUBLIC_ACCESS) { $error[] = System::getLanguage()->_('OnlyPublicFiles'); } $router = Router::getInstance(); $link = $router->build('DownloadController', 'raw', $this->file); $link = "http://view.officeapps.live.com/op/view.aspx?src=" . urlencode($link); $this->smarty->assign('error', join('<br>', $error)); $this->smarty->assign('link', $link); $this->smarty->display('handler/office.tpl'); }
public function __construct() { $this->_server = new SOAP_Server(); $this->_server->setDefaultNamespace($this->_namespace); $router = Router::getInstance(); $this->_soapRoutes = $router->getSoapRoutes(); if (count($this->_soapRoutes) > 0) { foreach ($this->_soapRoutes as $route) { $this->_addService($route[0], $route[1], $route[2], $route[3]); } } $soapLogin = new FWSoapLogin(); $loginAdapter = new FWSoapAdapter($soapLogin, array("login")); $logoutAdapter = new FWSoapAdapter($soapLogin, array("logout")); $this->_addService($loginAdapter, "http://schemas.xmlsoap.org/soap/envelope/", "login", "Login functionalities"); $this->_addService($logoutAdapter, "http://schemas.xmlsoap.org/soap/envelope/", "logout", "Logout functionalities"); }
public static function dispatch($url = null) { $request = new \ephFrame\HTTP\Request(); try { if ($result = Router::getInstance()->parse($request)) { $controller = new $result['controller']($request, $result); $response = $controller->action($result['action'], $result); if ($response instanceof \ephFrame\core\Controller) { $controller = $response; } return $controller->getResponse()->send(); } } catch (\Exception $exception) { $controller = new \ephFrame\core\ErrorController($request); $controller->handleException($exception); return $controller->getResponse()->send(); } return false; }
/** * Initialize the application */ public function init() { // Load the application configuration $this->singleton('conf', Conf::getInstance()); // Load the application error Handler $this->singleton('errorHandler', ErrorHandler::getInstance()); // Load the application logger $this->singleton('logger', Logger::getInstance()); // Load the filesystem library $this->singleton('fs', FileSystem::getInstance()); // Load the application session $this->singleton('session', Session::getInstance()); // Load the application router $this->singleton('router', Router::getInstance()); // Load the application HTTP request $this->singleton('request', Request::getInstance()); // Load the application HTTP response $this->singleton('response', Response::getInstance()); // Load the application cache $this->singleton('cache', Cache::getInstance()); }
/** * Метод запуска приложения * @throws Exception */ public static function run() { try { // Загрузка и объединение конфигов if (!file_exists(PSR4_ROOT . '/config.local.php')) { throw new Exception('You have to create file config.local.php with your settings'); } self::$config = (array) (require PSR4_ROOT . '/config.local.php') + (array) (require PSR4_ROOT . '/config.php'); // Маршрутизация запроса $router = Router::getInstance(); $route = $router->route($_SERVER['REQUEST_URI']); // Вызов обработчика self::_runAction($route['controller'], $route['action'], $route['params']); } catch (HttpException $e) { if ($e->getCode() === 404) { self::_runAction('error', '404', []); } else { self::_runAction('error', '500', ['message' => $e->getMessage()]); } } catch (\Exception $e) { self::_runAction('error', '500', ['message' => $e->getMessage()]); } }
/** * testNamedArgsUrlParsing method * * @access public * @return void */ function testNamedArgsUrlParsing() { $Router =& Router::getInstance(); Router::reload(); $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param:value'); $expected = array('pass' => array(), 'named' => array('param1' => 'value1:1', 'param2' => 'value2:3', 'param' => 'value'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); $this->assertEqual($result, $expected); Router::reload(); $result = Router::connectNamed(false); $this->assertEqual(array_keys($result['rules']), array()); $this->assertFalse($result['greedy']); $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param:value'); $expected = array('pass' => array('param1:value1:1', 'param2:value2:3', 'param:value'), 'named' => array(), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); $this->assertEqual($result, $expected); Router::reload(); $result = Router::connectNamed(true); $this->assertEqual(array_keys($result['rules']), $Router->named['default']); $this->assertTrue($result['greedy']); Router::reload(); Router::connectNamed(array('param1' => 'not-matching')); $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param:value'); $expected = array('pass' => array('param1:value1:1'), 'named' => array('param2' => 'value2:3', 'param' => 'value'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); $this->assertEqual($result, $expected); Router::reload(); Router::connect('/foo/:action/*', array('controller' => 'bar'), array('named' => array('param1' => array('action' => 'index')), 'greedy' => true)); $result = Router::parse('/foo/index/param1:value1:1/param2:value2:3/param:value'); $expected = array('pass' => array(), 'named' => array('param1' => 'value1:1', 'param2' => 'value2:3', 'param' => 'value'), 'controller' => 'bar', 'action' => 'index', 'plugin' => null); $this->assertEqual($result, $expected); $result = Router::parse('/foo/view/param1:value1:1/param2:value2:3/param:value'); $expected = array('pass' => array('param1:value1:1'), 'named' => array('param2' => 'value2:3', 'param' => 'value'), 'controller' => 'bar', 'action' => 'view', 'plugin' => null); $this->assertEqual($result, $expected); Router::reload(); Router::connectNamed(array('param1' => '[\\d]', 'param2' => '[a-z]', 'param3' => '[\\d]')); $result = Router::parse('/controller/action/param1:1/param2:2/param3:3'); $expected = array('pass' => array('param2:2'), 'named' => array('param1' => '1', 'param3' => '3'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); $this->assertEqual($result, $expected); Router::reload(); Router::connectNamed(array('param1' => '[\\d]', 'param2' => true, 'param3' => '[\\d]')); $result = Router::parse('/controller/action/param1:1/param2:2/param3:3'); $expected = array('pass' => array(), 'named' => array('param1' => '1', 'param2' => '2', 'param3' => '3'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); $this->assertEqual($result, $expected); Router::reload(); Router::connectNamed(array('param1' => 'value[\\d]+:[\\d]+'), array('greedy' => false)); $result = Router::parse('/controller/action/param1:value1:1/param2:value2:3/param3:value'); $expected = array('pass' => array('param2:value2:3', 'param3:value'), 'named' => array('param1' => 'value1:1'), 'controller' => 'controller', 'action' => 'action', 'plugin' => null); $this->assertEqual($result, $expected); Router::reload(); Router::connect('/foo/*', array('controller' => 'bar', 'action' => 'fubar'), array('named' => array('param1' => 'value[\\d]:[\\d]'))); Router::connectNamed(array(), array('greedy' => false)); $result = Router::parse('/foo/param1:value1:1/param2:value2:3/param3:value'); $expected = array('pass' => array('param2:value2:3', 'param3:value'), 'named' => array('param1' => 'value1:1'), 'controller' => 'bar', 'action' => 'fubar', 'plugin' => null); $this->assertEqual($result, $expected); }
public function testToURLInvalid() { $router = Router::getInstance(); $url = $router->toURL("frontend", "noExistant", "noExiste"); $this->assertNull($url); }
<?php $router = Router::getInstance(); //Home $router->addRoute('/', 'HomeController', 'index'); //Auth $router->addRoute('/auth/login', 'AuthController', 'login'); $router->addRoute('/auth/logout', 'AuthController', 'logout'); $router->addRoute('/auth/lostpw', 'AuthController', 'lostpw'); $router->addRoute('/auth/lostpw/:hash:', 'AuthController', 'lostpw_check'); $router->addRoute('/auth/file/:alias:', 'AuthController', 'authenticateFile'); //Download $router->addRoute('/show/:alias:', 'DownloadController', 'show'); $router->addRoute('/download/:alias:/force', 'DownloadController', 'force'); $router->addRoute('/download/:alias:/raw', 'DownloadController', 'raw'); $router->addRoute('/download/:alias:/embed', 'DownloadController', 'embed'); $router->addRoute('/download/:alias:/resize', 'DownloadController', 'resize'); $router->addRoute('/download/folder/:id:', 'DownloadController', 'folder'); //Upload $router->addRoute('/upload', 'UploadController', 'upload'); //Browser $router->addRoute('/browser', 'BrowserController', 'index'); $router->addRoute('/browser/folders/add', 'BrowserController', 'addFolder'); $router->addRoute('/browser/folders/:id:/:path:', 'BrowserController', 'show'); //Profile $router->addRoute('/profile', 'ProfileController', 'index'); //Log $router->addRoute('/log', 'LogController', 'index'); $router->addRoute('/log/clear', 'LogController', 'clear'); $router->addRoute('/log/php', 'LogController', 'php'); // Users
/** * Converts a matching route array into a url string. Composes the string url using the template * used to create the route. * * @param array $params The params to convert to a string url. * @return string Composed route string. * @access protected */ function _writeUrl($params) { if (isset($params['prefix'], $params['action'])) { $params['action'] = str_replace($params['prefix'] . '_', '', $params['action']); unset($params['prefix']); } if (is_array($params['pass'])) { $params['pass'] = implode('/', $params['pass']); } $instance =& Router::getInstance(); $separator = $instance->named['separator']; if (!empty($params['named']) && is_array($params['named'])) { $named = array(); foreach ($params['named'] as $key => $value) { $named[] = $key . $separator . $value; } $params['pass'] = $params['pass'] . '/' . implode('/', $named); } $out = $this->template; $search = $replace = array(); foreach ($this->keys as $key) { $string = null; if (isset($params[$key])) { $string = $params[$key]; } elseif (strpos($out, $key) != strlen($out) - strlen($key)) { $key .= '/'; } $search[] = ':' . $key; $replace[] = $string; } $out = str_replace($search, $replace, $out); if (strpos($this->template, '*')) { $out = str_replace('*', $params['pass'], $out); } $out = str_replace('//', '/', $out); return $out; }
function startup(&$controller = null) { /** * AUTHAKE CONFIGURATION * All these changes can be overrided in AppController->beforeFilter action */ /** * Base URL, used to insert the application URL in mails. */ if (Configure::read('Authake.baseUrl') == null) { Configure::write('Authake.baseUrl', Router::getInstance()->url('/', true)); // set the full application url } if (Configure::read('Authake.service') == null) { Configure::write('Authake.service', 'Authake'); //Name of the service i.e. "Super Authake" } /** * Default login action */ if (Configure::read('Authake.loginAction') == null) { Configure::write('Authake.loginAction', array('plugin' => 'authake', 'controller' => 'user', 'action' => 'login')); } /** * Used to redirect the users if the current user is logged out. Basically, this * is used in case when The login page is the home page. If this is not set to different location, then it's going into recursion. */ if (Configure::read('Authake.loggedAction') == null) { Configure::write('Authake.loggedAction', array('plugin' => 'authake', 'controller' => 'users', 'action' => 'index')); } /** * Session timeout in seconds, if managed by Authake (or null to disable) */ if (Configure::read('Authake.sessionTimeout') == null) { Configure::write('Authake.sessionTimeout', 3600 * 24 * 7); } /** * Default page when access is denied (should be allowed by ACLs...) */ if (Configure::read('Authake.defaultDeniedAction') == null) { Configure::write('Authake.defaultDeniedAction', array('plugin' => 'authake', 'controller' => 'user', 'action' => 'denied')); } /** * Reload all rules every x seconds */ if (Configure::read('Authake.rulesCacheTimeout') == null) { Configure::write('Authake.rulesCacheTimeout', 300); } /** * Email which sends the system mails */ if (Configure::read('Authake.systemEmail') == null) { Configure::write('Authake.systemEmail', 'Cake Test Account <*****@*****.**>'); } if (Configure::read('Authake.systemReplyTo') == null) { Configure::write('Authake.systemReplyTo', '*****@*****.**'); } /** * User need to authenticate that he requested the password change * (by receiving the confirmation link at his e-mail) */ if (Configure::read('Authake.passwordVerify') == null) { Configure::write('Authake.passwordVerify', true); } /** * Users can register */ if (Configure::read('Authake.registration') == null) { Configure::write('Authake.registration', true); //or false } /** * Default group for registered users * If set registered user will be inserted into specified group */ if (Configure::read('Authake.defaultGroup') == null) { Configure::write('Authake.defaultGroup', false); //could be array or single number } /** * Skip using authake layout for User controller. * This is used to display default layout of the application to actions * like login, register, change password etc. */ if (Configure::read('Authake.useDefaultLayout') == null) { Configure::write('Authake.useDefaultLayout', false); //could be true or false } }
public static function initREST($debug = false) { try { include "framework" . DS . "bootstrap.php"; $config = Config::getInstance(); $baseURL = $config->getbaseurl(); if (!defined("BASE_URL")) { define("BASE_URL", $baseURL); } $filter = BaseFilter::getInstance(); $router = Router::getInstance(); $router->_loadRoutes(); } catch (Exception $ex) { trigger_error("CORE | There has been an exception at the core of the Framework {$ex->getMessage()} ", E_USER_ERROR); } }
/** * Override main() to handle action * * @access public */ function main($command = null) { while (true) { if (empty($command)) { $command = trim($this->in('')); } switch ($command) { case 'help': $this->out('Console help:'); $this->out('-------------'); $this->out('The interactive console is a tool for testing parts of your app before you commit code'); $this->out(''); $this->out('Model testing:'); $this->out('To test model results, use the name of your model without a leading $'); $this->out('e.g. Foo->find("all")'); $this->out(''); $this->out('To dynamically set associations, you can do the following:'); $this->out("\tModelA bind <association> ModelB"); $this->out("where the supported assocations are hasOne, hasMany, belongsTo, hasAndBelongsToMany"); $this->out(''); $this->out('To dynamically remove associations, you can do the following:'); $this->out("\t ModelA unbind <association> ModelB"); $this->out("where the supported associations are the same as above"); $this->out(''); $this->out("To save a new field in a model, you can do the following:"); $this->out("\tModelA->save(array('foo' => 'bar', 'baz' => 0))"); $this->out("where you are passing a hash of data to be saved in the format"); $this->out("of field => value pairs"); $this->out(''); $this->out("To get column information for a model, use the following:"); $this->out("\tModelA columns"); $this->out("which returns a list of columns and their type"); $this->out(''); $this->out('Route testing:'); $this->out('To test URLs against your app\'s route configuration, type:'); $this->out("\tRoute <url>"); $this->out("where url is the path to your your action plus any query parameters, minus the"); $this->out("application's base path"); $this->out(''); $this->out('To reload your routes config (config/routes.php), do the following:'); $this->out("\tRoute reload"); $this->out(''); break; case 'quit': case 'exit': return true; break; case 'models': $this->out('Model classes:'); $this->hr(); foreach ($this->models as $model) { $this->out(" - {$model}"); } break; case preg_match("/^(\\w+) bind (\\w+) (\\w+)/", $command, $tmp) == true: foreach ($tmp as $data) { $data = strip_tags($data); $data = str_replace($this->badCommandChars, "", $data); } $modelA = $tmp[1]; $association = $tmp[2]; $modelB = $tmp[3]; if ($this->__isValidModel($modelA) && $this->__isValidModel($modelB) && in_array($association, $this->associations)) { $this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false); $this->out("Created {$association} association between {$modelA} and {$modelB}"); } else { $this->out("Please verify you are using valid models and association types"); } break; case preg_match("/^(\\w+) unbind (\\w+) (\\w+)/", $command, $tmp) == true: foreach ($tmp as $data) { $data = strip_tags($data); $data = str_replace($this->badCommandChars, "", $data); } $modelA = $tmp[1]; $association = $tmp[2]; $modelB = $tmp[3]; // Verify that there is actually an association to unbind $currentAssociations = $this->{$modelA}->getAssociated(); $validCurrentAssociation = false; foreach ($currentAssociations as $model => $currentAssociation) { if ($model == $modelB && $association == $currentAssociation) { $validCurrentAssociation = true; } } if ($this->__isValidModel($modelA) && $this->__isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) { $this->{$modelA}->unbindModel(array($association => array($modelB))); $this->out("Removed {$association} association between {$modelA} and {$modelB}"); } else { $this->out("Please verify you are using valid models, valid current association, and valid association types"); } break; case strpos($command, "->find") > 0: // Remove any bad info $command = strip_tags($command); $command = str_replace($this->badCommandChars, "", $command); // Do we have a valid model? list($modelToCheck, $tmp) = explode('->', $command); if ($this->__isValidModel($modelToCheck)) { $findCommand = "\$data = \$this->{$command};"; @eval($findCommand); if (is_array($data)) { foreach ($data as $idx => $results) { if (is_numeric($idx)) { // findAll() output foreach ($results as $modelName => $result) { $this->out("{$modelName}"); foreach ($result as $field => $value) { if (is_array($value)) { foreach ($value as $field2 => $value2) { $this->out("\t{$field2}: {$value2}"); } $this->out(""); } else { $this->out("\t{$field}: {$value}"); } } } } else { // find() output $this->out($idx); foreach ($results as $field => $value) { if (is_array($value)) { foreach ($value as $field2 => $value2) { $this->out("\t{$field2}: {$value2}"); } $this->out(""); } else { $this->out("\t{$field}: {$value}"); } } } } } else { $this->out("\nNo result set found"); } } else { $this->out("{$modelToCheck} is not a valid model"); } break; case strpos($command, '->save') > 0: // Validate the model we're trying to save here $command = strip_tags($command); $command = str_replace($this->badCommandChars, "", $command); list($modelToSave, $tmp) = explode("->", $command); if ($this->__isValidModel($modelToSave)) { // Extract the array of data we are trying to build list($foo, $data) = explode("->save", $command); $badChars = array("(", ")"); $data = str_replace($badChars, "", $data); $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));"; @eval($saveCommand); $this->out('Saved record for ' . $modelToSave); } break; case preg_match("/^(\\w+) columns/", $command, $tmp) == true: $modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1])); if ($this->__isValidModel($modelToCheck)) { // Get the column info for this model $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();"; @eval($fieldsCommand); if (is_array($data)) { foreach ($data as $field => $type) { $this->out("\t{$field}: {$type}"); } } } else { $this->out("Please verify that you selected a valid model"); } break; case preg_match("/^routes\\s+reload/i", $command, $tmp) == true: $router =& Router::getInstance(); $router->reload(); if (config('routes') && $router->parse('/')) { $this->out("Routes configuration reloaded, " . count($router->routes) . " routes connected"); } break; case preg_match("/^route\\s+(.*)/i", $command, $tmp) == true: $this->out(Debugger::exportVar(Router::parse($tmp[1]))); break; default: $this->out("Invalid command\n"); break; } $command = ''; } }