/** * Creates an instance of the Response class * * @param string $body The response body * @param int $status The HTTP response status for this response * @param array $headers Array of HTTP headers for this reponse * * @return Response */ public static function forge($body = null, $status = 200, array $headers = array()) { $response = new static($body, $status, $headers); // fire any response created events \Event::instance()->has_events('response_created') and \Event::instance()->trigger('response_created', '', 'none'); return $response; }
public function __construct() { $this->wi3 = $this->app = APPPATH; //site and pagefiller location can only be known after site has been loaded by Engine or View //we therefore register an hook on the wi3.siteandpageloaded event Event::instance("wi3.init.sitearea.site.loaded")->callback(array("Wi3_pathof", "fill_site_paths")); Event::instance("wi3.init.page.loaded")->callback(array("Wi3_pathof", "fill_page_paths")); }
public static function set_auto_render() { //add a hook to the system.display Event. This event is called just before flushing content to the browser //only add the hook if we didn't set the hook already sometime earlier if (self::$will_already_be_auto_rendered == false) { //add before the page is cached, so that css files are cached as well Event::instance('wi3.afterexecution.addcontent.css')->callback(array('Wi3_Css', 'render_in_head')); self::$will_already_be_auto_rendered = true; } }
/** * When this type of exception isn't caught this method is called by * Error::exception_handler() to deal with the problem. */ public function handle() { // get the exception response $response = $this->response(); // fire any app shutdown events \Event::instance()->trigger('shutdown', '', 'none', true); // fire any framework shutdown events \Event::instance()->trigger('fuel-shutdown', '', 'none', true); // send the response out $response->send(true); }
function __construct() { //register this Plugin parent::__construct(); //------------------------------------------------------------- // this function ensures that some Wi3 information is always sent to the client for use in javascript files (ie kohana.js) // //set up the event to pass information to the clientside //add this event before the javascript event, so that javascript always have this information available when they load Event::instance('wi3.afterexecution.addcontent.javascript.variables')->callback(array("Plugin_clientjavascriptvars", "addclientjavascriptvars")); //------------------------------------------------------------- }
public function execute($job, $data) { // Trigger price update/change event and modify data $data = \Event::instance('supplier')->trigger('update', $data, 'array'); $data = call_user_func_array('\\Arr::merge_assoc', $data); // This is all about update $data = $data[0]; // Do not update some fields $set = \Arr::filter_keys($data, array('external_id', 'supplier_id'), true); $data['updated_at'] = time(); return Model_Price::query()->set($set)->where('external_id', $data['external_id'])->where('supplier_id', $data['supplier_id'])->update(); }
public function action_editpagetemplatesettings($pageid) { $page = Wi3::inst()->model->factory("Site_Page")->set("id", $pageid)->load(); Wi3::inst()->sitearea->page = $page; // Now notify other entities that use this->page that the page has been loaded Event::instance("wi3.init.sitearea.page.loaded")->execute(); // Save the template for this page $templatename = $_POST["pagefiller_templatename"]; $page->templatename = $templatename; $page->update(); echo json_encode(array("alert" => "template is geupdate")); }
/** * Method for registering callback methods for a particular action and a particular * @param String $action underscore separated string 'exam_add' * @param String $handlerClass - Name of the class in which the static callback methods are grouped per module * @return Notice $this */ public function register_callbacks($mod, $handlerClass) { foreach ($this->_config[$mod] as $conf) { $action = $mod . '_' . $conf; $event = Event::instance($action); foreach (self::$MEDIA as $m) { $callback = $m . '_' . $conf; if ($this->check_preference($action, $m) && method_exists($handlerClass, $callback)) { $event->callback(array($handlerClass, $callback)); } } } }
public function setpage($pageorpagename) { if (is_object($pageorpagename)) { $this->page = $pageorpagename; } else { if (is_string($pageorpagename)) { $this->page = $this->getpage($pageorpagename); } else { $this->page = $this->getpage(NULL); } } // Now notify other entities that use this->page that the page has been loaded Event::instance("wi3.init.sitearea.page.loaded")->execute(); return $this->page; }
/** * Queue job * * @param mixed $id Supplier id * @param string $method Method to run * @param integer $delay * @param integer $ttr Time limit * @return null */ public function execute($id, $method, $delay = 0, $ttr = 300) { // Cast id is_numeric($id) and $id = (int) $id; // Job data $data = array('id' => $id, 'cached' => (bool) \Cli::option('cached', \Cli::option('c', false)), 'force' => (bool) \Cli::option('force', \Cli::option('f', false)), 'method' => $method); // Execute job immediately $execute = (bool) \Cli::option('execute', \Cli::option('e', false)); // Use Queue if available (greater performance) if (\Package::loaded('queue')) { // Create queue data if ($execute) { // Initialize logger $logger = clone \Log::instance(); // Get original handler $handler = $logger->popHandler(); $handler->pushProcessor(new \Monolog\Processor\PsrLogMessageProcessor()); $logger->pushHandler($handler); // Console handler $handler = new \Monolog\Handler\ConsoleHandler(\Monolog\Logger::NOTICE); $formatter = new \Monolog\Formatter\LineFormatter("%message% - %context%" . PHP_EOL, "Y-m-d H:i:s"); $handler->setFormatter($formatter); $logger->pushHandler($handler); // Add other handlers to logger through Event trigger \Event::instance('queue')->trigger('logger', $logger); $queue = array('supplier', array('driver' => 'direct', 'logger' => $logger)); } else { $queue = 'supplier'; } $options = array('delay' => $delay, 'ttr' => $ttr); // Push job and data to queue \Queue::push($queue, 'Indigo\\Erp\\Stock\\Job_Supplier', $data, $options); } else { try { $job = new Job_Supplier(); return $job->execute(null, $data); } catch (\Exception $e) { // TODO: process exceptions } } }
<?php defined('SYSPATH') or die('No direct access allowed.'); /** * @package YurikoCMS * @author Lorenzo Pisani - Zeelot * @copyright (c) 2008-2009 Lorenzo Pisani * @license http://yurikocms.com/license */ // Add all the enabled plugins to the modules $enabled = Sprig::factory('plugin', array('status' => 'enabled'))->load(NULL, FALSE); $modules = Kohana::modules(); // Start with the default template at the top $array = array('default_theme' => DOCROOT . 'yurikocms/themes/default'); foreach ($enabled as $plugin) { $array[$plugin->name] = DOCROOT . 'yurikocms/plugins/' . $plugin->name; } Event::instance('yuriko_core.init.loading_plugins')->bind('modules', $modules)->execute(); Kohana::modules($array + $modules); // Clean up unset($modules, $enabled); /** * Setup the YurikoCMS page route, this is a catch all route that any * custom routes need to preceed. */ Route::set('page', '(<uri>)', array('uri' => '.*'))->defaults(array('controller' => 'page', 'action' => 'index', 'directory' => 'yuriko'));
public function action_edit() { $id = $this->request->param('id'); if (!$id) { Request::current()->redirect('exam'); } $submitted = FALSE; if ($this->request->method() === 'POST' && $this->request->post()) { if (Arr::get($this->request->post(), 'save') !== null) { $submitted = true; $exam = ORM::factory('exam'); $validator = $exam->validator($this->request->post()); $validator->bind(':to', $this->request->post('to')); $validator->bind(':total_marks', $this->request->post('total_marks')); if ($validator->check()) { $from = strtotime($this->request->post('date')) + $this->request->post('from') * 60; $to = strtotime($this->request->post('date')) + $this->request->post('to') * 60; $exam = ORM::factory('exam', $id); $exam->values($this->request->post()); $exam->save(); $event_exam = Event_Abstract::factory('exam', $exam->event_id); $event_exam->set_values($this->request->post()); $event_exam->set_value('eventstart', $from); $event_exam->set_value('eventend', $to); $event_exam->update($exam->event_id); // dispatch events for sending the notices and feeds (TODO to be refactored later) if ($event_exam->is_rescheduled()) { Event::instance('exam_reschedule')->set('exam', $exam)->execute(); } if ($event_exam->is_relocated()) { Event::instance('exam_relocate')->set('exam', $exam)->execute(); } $feed = new Feed_Exam(); $feed->set_action('edit'); $feed->set_course_id($this->request->post('course_id')); $feed->set_respective_id($exam->id); $feed->set_actor_id(Auth::instance()->get_user()->id); $feed->streams(array('course_id' => (int) $this->request->post('course_id'))); $feed->save(); Session::instance()->set('success', 'Exam edited successfully.'); Request::current()->redirect('exam'); exit; } else { $this->_errors = $validator->errors('exam'); } } } $exam = ORM::factory('exam', $id); $event = ORM::factory('event', $exam->event_id); $saved_data = array('name' => $exam->name, 'examgroup_id' => $exam->examgroup_id, 'course_id' => $exam->course_id, 'total_marks' => $exam->total_marks, 'passing_marks' => $exam->passing_marks, 'reminder' => $exam->reminder, 'reminder_days' => $exam->reminder_days, 'date' => date('Y-m-d', $event->eventstart), 'from' => date('H:i', $event->eventstart), 'to' => date('H:i', $event->eventend), 'room_id' => $event->room_id); $silder['start'] = ($event->eventstart - strtotime($saved_data['date'])) / 60; $silder['end'] = ($event->eventend - strtotime($saved_data['date'])) / 60; $form = $this->form('exam/edit/id/' . $id, $submitted, $saved_data); $event_id = $exam->event_id; $links = array('rooms' => Html::anchor('/room/', 'Add Rooms', array('target' => '_blank'))); $view = View::factory('exam/form')->bind('form', $form)->bind('event_id', $event_id)->bind('links', $links)->bind('slider', $silder); Breadcrumbs::add(array('Exams', Url::site('exam'))); Breadcrumbs::add(array('Edit', Url::site('exam/edit/id/' . $id))); $this->content = $view; }
public function init() { // Load session handler $this->session = Session::instance(); // Set cache handler $this->cache = Wi3TikoCache::instance(); // Define APPRELATIVEPATH, which is the path to the application relative to the web root // We can retrieve this by using the SCRIPT_NAME from the front-controller ({pathfromroot}/app/index.php), and extracting the path-from-root define("APPRELATIVEPATH", substr($_SERVER["SCRIPT_NAME"], 0, strpos($_SERVER["SCRIPT_NAME"], "/app/index.php")) . "/app/latest/"); // Define document root // TODO: Add support for ISS (see http://www.helicron.net/php/) define("DOCUMENTROOT", $_SERVER["DOCUMENT_ROOT"] . "/"); // Determine language $lang = Cookie::get('lang'); if ($lang !== NULL) { if (!in_array($lang, array('nl-nl', 'en-us'))) { // Check the allowed languages, and force the default $lang = 'nl-nl'; } } else { // Language not set in cookie. Get default language from i18n file. $i18nfiles = Kohana::find_file("config", "i18n"); if (!empty($i18nfiles)) { $i18nsettings = Kohana::load($i18nfiles[0]); $lang = $i18nsettings["lang"]; } else { $lang = 'nl-nl'; // Fall back to default } // Save loaded language in cookie Cookie::set('lang', $lang); } // Set the target language i18n::lang($lang); // Set the source language to some non-existing language to prevent Kohana skipping translation lookup if source and target language are identical i18n::$source = "bb-bb"; // See http://unicode.org/cldr/utility/languageid.jsp?a=bb&l=en for valid tags // Load wi3-kohana-specific functions $this->kohana = new Wi3_Kohana(); // XSS Clean all user input! // TODO: only do this if the user is not an admin... $this->originalpost = $_POST; // Save original $_POST foreach ($_POST as $key => $val) { $_POST[$key] = Security::xss_clean($val); } $this->originalget = $_GET; // Save original $_GET foreach ($_GET as $key => $val) { $_GET[$key] = Security::xss_clean($val); } // Load some Wi3 classes // Load a global database configuration $this->database = new Wi3_Database(); // Helper functions to create databases etc $this->globaldatabase = Wi3_Database::instance("global"); Event::instance("wi3.init.globaldatabase.loaded")->execute(); // Get routing, url and path information // These classes in turn add a callback to the wi3.init.site.loaded Event, after which they will update with path and urls to the site $this->routing = Wi3_Routing::instance(); Event::instance("wi3.init.routing.loaded")->execute(); $this->pathof = Wi3_Pathof::instance(); Event::instance("wi3.init.pathof.loaded")->execute(); $this->urlof = Wi3_Urlof::instance(); Event::instance("wi3.init.urlof.loaded")->execute(); // Load CSS and Javascript 'injectors' $this->css = Wi3_Css::instance(); $this->javascript = Wi3_Javascript::instance(); // Instantiate the Model class, that is an interface to the 'factory' method for any underlying model-systems $this->model = Wi3_Model::inst(); Event::instance("wi3.init.model.loaded")->execute(); // Instantiate the form-builder $this->formbuilder = Wi3_Formbuilder::inst(); Event::instance("wi3.init.formbuilder.loaded")->execute(); // Now find out what is the scope of this request // It most often is a site-scope (i.e. the admin or view of a site), but might also be a global scope (i.e. superadmin) // This depends on the controller. // Pagefiller-specific controllers are always for the the sitearea $this->scope = (substr(Request::instance()->controller, 0, 9) == "adminarea" or substr(Request::instance()->controller, 0, 10) == "pagefiller" or Request::instance()->controller == "sitearea") ? "site" : "global"; if ($this->scope == "site") { $this->sitearea = Wi3_Sitearea::inst(); // Find out what site we are working with // Both the admin controller and the site controller need to know this in order to work properly // Find the site by apache 'sitename' variable if (isset($_SERVER['REDIRECT_SITENAME'])) { $sitename = $_SERVER['REDIRECT_SITENAME']; // With correct loading, $_SERVER['REDIRECT_SITENAME'] should always be present, as it is set in the vhosts .htaccess that redirect here // Global site is the site in the global space, i.e. the Site model in the 'list of sites' that is always accesible // ( In the per-site database, there can only exist one Site model ) $this->sitearea->globalsite = $this->model->factory("site")->set('name', $sitename)->load(); Event::instance("wi3.init.sitearea.globalsite.loaded")->execute(); $this->sitearea->site = $this->sitearea->globalsite; // This site instance will be replaced by the local user site. The ->name will be added to that local site, since it does not store that in the local db } // If the sitename not present, the page request came here via some illegal method. // If the site was not loaded correctly or is not active, we cannot show the site either if (!isset($_SERVER['REDIRECT_SITENAME']) or empty($sitename) or !$this->sitearea->globalsite->loaded() or $this->sitearea->globalsite->active == FALSE) { // Site does not exist. Quit. throw new Kohana_Exception("site does not exist"); } // Global site has been loaded and it was found to be active // Now we load the local site and requested page from within the user Database // This requires the inclusion of the site as a module and an init on its database-config // // First, Include the whole site-tree in the find_file() function Kohana::modules(Kohana::modules() + array("site" => APPPATH . "../../sites/" . $sitename . "/")); // Because Kohana uses include_once() this will only init the new module, without double-including the others // Load the sitedatabase config. It will be fetched from the sites/sitename/config folder since the sites/sitename is now in the Kohana find_file paths $siteconfig = Kohana::config('sitedatabase')->site; // Set up a site database connection, to be used by the site-based-models like Site_Page, Site_User, File etc $this->sitearea->database = Wi3_Database::instance("site", $siteconfig); Event::instance("wi3.init.sitearea.database.loaded")->execute(); // Load the user-site $this->sitearea->site = $this->model->factory("site_site")->set('id', 1)->load(); $this->sitearea->site->name = $sitename; // Add name, since this is not stored in the local site tables, but only in the global ones Event::instance("wi3.init.sitearea.site.loaded")->execute(); // Load the pageposition, page and file manager, all within the sitearea $this->sitearea->pagepositions = Wi3_Sitearea_Pagepositions::inst(); $this->sitearea->pages = Wi3_Sitearea_Pages::inst(); $this->sitearea->files = Wi3_Sitearea_Files::inst(); $this->sitearea->users = Wi3_Sitearea_Users::inst(); } // Load baseviews that are passed as $this into views in order to enable some in-view functions // Different setups are possible with the different parameters supplied // An instance is created, so that they can also be referenced simply from again loading e.g. Wi3_Baseview::instance('superadminarea'); // These instances are used as 'object scope' for the $this variables in views. See i.e. the superadminarea-controller's ->view function and the Baseview->capture() for more details $this->baseview_superadminarea = Wi3_Baseview::instance('superadminarea', array('javascript_url' => $this->urlof->appfiles . 'static/javascript/', 'javascript_path' => $this->pathof->app . 'static/javascript/', 'css_url' => $this->urlof->appfiles . 'static/css/', 'css_path' => $this->pathof->app . 'static/css/')); //Maybe just define the asset-path(s), from which the URLs are deduced, based on the Wi3::inst()->urlof ? $this->baseview_adminarea = Wi3_Baseview::instance('adminarea', array('javascript_url' => $this->urlof->appfiles . 'static/javascript/', 'javascript_path' => $this->pathof->app . 'static/javascript/', 'css_url' => $this->urlof->appfiles . 'static/css/', 'css_path' => $this->pathof->app . 'static/css/')); $this->baseview_sitearea = Wi3_Baseview::instance('sitearea', array('javascript_url' => $this->urlof->site . 'static/javascript/', 'javascript_path' => $this->pathof->site . 'static/javascript/', 'css_url' => $this->urlof->site . 'static/css/', 'css_path' => $this->pathof->site . 'static/css/')); Event::instance("wi3.init.baseviews.loaded")->execute(); // Set up an config loader $this->configof = Wi3_Configof::instance(); // Set up auth. This will try to login the current user from either the site db or the global db, based on the scope if ($this->scope == "site") { $this->sitearea->auth = Wi3_Auth_Site::instance(); } else { // If user is in setup, then don't yet load Auth and Database instances, since they most probably don't yet exist if (Request::instance()->controller != "setup") { $this->globalauth = Wi3_Auth_Global::instance(); } } $this->acl = Wi3_ACL::instance(); // Load the plugin-manager. The manager will also include the paths to the plugins in the modules-system $this->plugins = new Wi3_Plugins(); if ($this->scope == "site") { // Make all the pageversion-plugins to load // The versionplugins should respond to this event call, and add them to the $this->versionplugins array Event::instance('wi3.sitearea.pages.versionplugins.load')->execute(); } }
} require VENDORPATH . 'autoload.php'; /** * Register all the error/shutdown handlers */ register_shutdown_function(function () { // reset the autoloader \Autoloader::_reset(); // make sure we're having an output filter so we can display errors // occuring before the main config file is loaded \Config::get('security.output_filter', null) or \Config::set('security.output_filter', 'Security::htmlentities'); try { // fire any app shutdown events \Event::instance()->trigger('shutdown', '', 'none', true); // fire any framework shutdown events \Event::instance()->trigger('fuel-shutdown', '', 'none', true); } catch (\Exception $e) { if (\Fuel::$is_cli) { \Cli::error("Error: " . $e->getMessage() . " in " . $e->getFile() . " on " . $e->getLine()); \Cli::beep(); exit(1); } } return \Error::shutdown_handler(); }); set_exception_handler(function (\Exception $e) { // reset the autoloader \Autoloader::_reset(); // deal with PHP bugs #42098/#54054 if (!class_exists('Error')) { include COREPATH . 'classes/error.php';
* - string cache_dir set the internal cache directory APPPATH/cache * - boolean errors enable or disable error handling TRUE * - boolean profile enable or disable internal profiling TRUE * - boolean caching enable or disable internal caching FALSE */ Kohana::init(array('base_url' => '/', 'index_file' => FALSE)); /** * Attach the file write to logging. Multiple writers are supported. */ Kohana::$log->attach(new Kohana_Log_File(APPPATH . 'logs')); /** * Attach a file reader to config. Multiple readers are supported. */ Kohana::$config->attach(new Kohana_Config_File()); /** * Enable modules. Modules are referenced by a relative or absolute path. */ Kohana::modules(array(MODPATH . 'zeelot-event', MODPATH . 'zeelot-orm', MODPATH . 'yuriko_dev', MODPATH . 'yuriko_admin', MODPATH . 'assets', MODPATH . 'yuriko_core')); /** * Execute the main request using PATH_INFO. If no URI source is specified, * the URI will be automatically detected. */ $request = Request::instance(); Event::run('yuriko.bootstrap.request.pre_execute', $request); $request = $request->execute(); Event::instance('yuriko.bootstrap.request.pre_send_headers', $request); $request = $request->send_headers(); Event::instance('yuriko.bootstrap.request.pre_render', $request); echo $request->response; // Clean up unset($request);
<?php // Create a callback so that the multilanguage pageversion-class will be loaded once Wi3::inst()->sitearea->pages asks all pageversion-classes to do so Event::instance('wi3.sitearea.pages.versionplugins.load')->callback(array("Wi3_plugins", "load"), "plugin_multilanguage");
Event::instance('wi3.afterexecution.addcontent.javascript.first')->execute(); Event::instance('wi3.afterexecution.addcontent.javascript.second')->execute(); Event::instance('wi3.afterexecution.addcontent.javascript')->execute(); Event::instance('wi3.afterexecution.addcontent.html')->execute(); // Add html // Change content Event::instance('wi3.afterexecution.changecontent.first')->execute(); // Change final html Event::instance('wi3.afterexecution.changecontent.second')->execute(); // Change final html Event::instance('wi3.afterexecution.changecontent.third')->execute(); // Change final html // Internal: Change ID links to 'normal' links // Wi3::inst()->linkconverter->execute(); // Content is ready for output. Last change to process the data (but not change it) Event::instance('wi3.afterexecution.processcontent')->execute(); // Used by e.g. caching-mechanisms } catch (ACL_Exception_401 $e) { // Redirect to the same controller, but the login action // Controller should allow access to that function, and deal with the login and authentication Wi3::inst()->session->set("previously_requested_url", Wi3::inst()->routing->url); $request->redirect(Wi3::inst()->urlof->action("login")); } catch (Exception_Continue $e) { // Just continue with execution // ... } catch (Exception $e) { if (Kohana::$environment === Kohana::DEVELOPMENT) { // Just re-throw the exception throw $e; } // Log the error
public function action_startEditPagepositionSettings() { $pageid = substr($_POST["pagepositionname"], 9); // For now, just redirect immediately to the first page under this pageposition $pageposition = Wi3::inst()->model->factory("site_pageposition", array("id" => $pageid))->load(); Wi3::inst()->sitearea->pageposition = $pageposition; Event::instance("wi3.init.sitearea.pageposition.loaded")->execute(); foreach ($pageposition->pages as $page) { $_POST["pageid"] = $page->id; break; } return $this->action_startEditPageSettings(); // TODO: proper UI etc for multiple pages under one pageposition /* $editview = View::factory("adminarea/menu/ajax/pagepositionsettings"); $editview->site = Wi3::inst()->sitearea->site; if (is_numeric($pageid) AND !empty($pageid)) { $page = Wi3::inst()->model->factory("site_pageposition", Array("id" => $pageid))->load(); Wi3::inst()->sitearea->pageposition = $page; Event::instance("wi3.init.sitearea.pageposition.loaded")->execute(); if ($page->loaded()) { $editview->page = $page; echo json_encode( Array( "scriptsbefore" => Array("$('#menu_pagesettings_tabs').hide();"), "dom" => Array( "fill" => Array("#menu_pagesettings_tabs" => $editview->render() ) ), "scriptsafter" => Array("adminarea.menu_pagesettings_enable();", "$('#menu_pagesettings_tabs').show();", "$('#pagetitle').focus()"), ) ); } }*/ }
public function __construct() { $this->request = Wi3::instance()->routing->url; // Url of request, as found in routing // base URL determination of the *unrewritten* site URL // First get the part of the *rewritten* url that comes after $controller/$action (e.g. "pagename/arg1/arg2" after "sitearea/view") // Rewritten URL might be: .../sitearea/view/pagename/arg1 OR .../adminarea/ // (There is NOT NECESSARILY an action after the controller: Do a check for that!) if (strpos(Wi3::inst()->routing->filename, "app/index.php/" . Wi3::inst()->routing->controller . "/" . Wi3::inst()->routing->action) !== FALSE) { // There is an action part present $pagepart = substr(Wi3::inst()->routing->filename, strpos(Wi3::inst()->routing->filename, "app/index.php/" . Wi3::inst()->routing->controller . "/" . Wi3::inst()->routing->action) + strlen("app/index.php/" . Wi3::inst()->routing->controller . "/" . Wi3::inst()->routing->action)); } else { // There is only the controller and NOT an action part $pagepart = substr(Wi3::inst()->routing->filename, strpos(Wi3::inst()->routing->filename, "app/index.php/" . Wi3::inst()->routing->controller) + strlen("app/index.php/" . Wi3::inst()->routing->controller)); } if (!empty($pagepart)) { // That pagepart is also available in the *unrewritten* URL, at the very end of the URL // The part before it is our 'base' that we want to fetch $baseurl = substr(Wi3::inst()->routing->url, 0, strlen(Wi3::inst()->routing->url) - strlen($pagepart)) . "/"; // OR alternatively: $basepart = substr(Wi3::inst()->routing->url, 0, strrpos(Wi3::inst()->routing->url, $pagepart)); } else { // There is no pagepart, so only a baseurl (should in reality not occur, but anyways) $baseurl = Wi3::inst()->routing->url; } // Ensure a slash at the end of the baseurl $baseurl = trim($baseurl, "/") . "/"; // The baseurl is now something like http://domain.com/(folder/)adminarea/ or http://domain.com/(folder/)_wi3controller/somecontroller or http://comain.com/(folder/)pagename // We however do not want parts like adminarea or _wi3controller in the base url // Mind: we do not need to check for things like _wi3files because these URLs will/should not resolve here, but get a file directly if (strpos($baseurl, "/_wi3controllers/") !== FALSE) { $this->baseurl = substr($baseurl, 0, strpos($baseurl, "/_wi3controllers/") + 1); } else { if (strpos($baseurl, "/adminarea/") !== FALSE) { $this->baseurl = substr($baseurl, 0, strpos($baseurl, "/adminarea/") + 1); } else { if (strpos($baseurl, "/superadminarea/") !== FALSE) { $this->baseurl = substr($baseurl, 0, strpos($baseurl, "/superadminarea/") + 1); } else { $this->baseurl = $baseurl; //substr($baseurl, 0, -1); } } } // Now set the different 'urlof' variables $this->appfiles = $this->wi3files = $this->baseurl . "_wi3files/"; $this->appcontrollers = $this->wi3controllers = $this->baseurl . "_wi3controllers/"; // Adminarea can shorthandedly be accessed like domain.com/something/adminarea/action // This also goes for /adminarea_menu_ajax etc // Take that into account if (strpos(Wi3::inst()->routing->controller, "adminarea") === 0 or strpos(Wi3::inst()->routing->controller, "superadminarea") === 0) { $this->controller = $this->baseurl . Wi3::inst()->routing->controller . "/"; } else { $this->controller = $this->controller(Wi3::inst()->routing->controller); } $this->action = $this->action(Wi3::inst()->routing->action); //site and pagefiller location can only be known after site and page have been loaded by Engine or View //we therefore register an hook on the wi3.siteandpageloaded event Event::instance("wi3.init.sitearea.site.loaded")->callback(array("Wi3_urlof", "fillsite")); Event::instance("wi3.init.sitearea.page.loaded")->callback(array("Wi3_urlof", "fillpageandpagefiller")); }
/** * Initializes the framework. * This can only be called once. * * @access public * @return void */ public static function init($config) { if (static::$initialized) { throw new \FuelException("You can't initialize Fuel more than once."); } // BC FIX FOR APPLICATIONS <= 1.6.1, makes Redis_Db available as Redis, // like it was in versions before 1.7 class_exists('Redis', false) or class_alias('Redis_Db', 'Redis'); static::$_paths = array(APPPATH, COREPATH); // Is Fuel running on the command line? static::$is_cli = (bool) defined('STDIN'); \Config::load($config); // Start up output buffering static::$is_cli or ob_start(\Config::get('ob_callback', null)); if (\Config::get('caching', false)) { \Finder::instance()->read_cache('FuelFileFinder'); } static::$profiling = \Config::get('profiling', false); static::$profiling and \Profiler::init(); // set a default timezone if one is defined try { static::$timezone = \Config::get('default_timezone') ?: date_default_timezone_get(); date_default_timezone_set(static::$timezone); } catch (\Exception $e) { date_default_timezone_set('UTC'); throw new \PHPErrorException($e->getMessage()); } static::$encoding = \Config::get('encoding', static::$encoding); MBSTRING and mb_internal_encoding(static::$encoding); static::$locale = \Config::get('locale', static::$locale); if (!static::$is_cli) { if (\Config::get('base_url') === null) { \Config::set('base_url', static::generate_base_url()); } } // Run Input Filtering \Security::clean_input(); \Event::register('fuel-shutdown', 'Fuel::finish'); // Always load classes, config & language set in always_load.php config static::always_load(); // Load in the routes \Config::load('routes', true); \Router::add(\Config::get('routes')); // Set locale, log warning when it fails if (static::$locale) { setlocale(LC_ALL, static::$locale) or logger(\Fuel::L_WARNING, 'The configured locale ' . static::$locale . ' is not installed on your system.', __METHOD__); } static::$initialized = true; // fire any app created events \Event::instance()->has_events('app_created') and \Event::instance()->trigger('app_created', '', 'none'); if (static::$profiling) { \Profiler::mark(__METHOD__ . ' End'); } }
/** * Initializes the framework. This can only be called once. * * @access public * @return void */ public static function init($config) { if (static::$initialized) { throw new \FuelException("You can't initialize Fuel more than once."); } static::$_paths = array(APPPATH, COREPATH); // Is Fuel running on the command line? static::$is_cli = (bool) defined('STDIN'); \Config::load($config); // Start up output buffering ob_start(\Config::get('ob_callback', null)); static::$profiling = \Config::get('profiling', false); if (static::$profiling) { \Profiler::init(); \Profiler::mark(__METHOD__ . ' Start'); } static::$cache_dir = \Config::get('cache_dir', APPPATH . 'cache/'); static::$caching = \Config::get('caching', false); static::$cache_lifetime = \Config::get('cache_lifetime', 3600); if (static::$caching) { \Finder::instance()->read_cache('Fuel::paths'); } // set a default timezone if one is defined static::$timezone = \Config::get('default_timezone') ?: date_default_timezone_get(); date_default_timezone_set(static::$timezone); static::$encoding = \Config::get('encoding', static::$encoding); MBSTRING and mb_internal_encoding(static::$encoding); static::$locale = \Config::get('locale', static::$locale); if (!static::$is_cli) { if (\Config::get('base_url') === null) { \Config::set('base_url', static::generate_base_url()); } } // Run Input Filtering \Security::clean_input(); \Event::register('shutdown', 'Fuel::finish'); // Always load classes, config & language set in always_load.php config static::always_load(); // Load in the routes \Config::load('routes', true); \Router::add(\Config::get('routes')); // Set locale, log warning when it fails if (static::$locale) { setlocale(LC_ALL, static::$locale) or logger(\Fuel::L_WARNING, 'The configured locale ' . static::$locale . ' is not installed on your system.', __METHOD__); } static::$initialized = true; // fire any app created events \Event::instance()->has_events('app_created') and \Event::instance()->trigger('app_created', '', 'none'); if (static::$profiling) { \Profiler::mark(__METHOD__ . ' End'); } }
/** * This executes the request and sets the output to be used later. * * Usage: * * $request = Request::forge('hello/world')->execute(); * * @param array|null $method_params An array of parameters to pass to the method being executed * @return Request This request object */ public function execute($method_params = null) { // fire any request started events \Event::instance()->has_events('request_started') and \Event::instance()->trigger('request_started', '', 'none'); if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ': Start of ' . $this->uri->get()); } logger(\Fuel::L_INFO, 'Called', __METHOD__); // Make the current request active static::$active = $this; // First request called is also the main request if (!static::$main) { logger(\Fuel::L_INFO, 'Setting main Request', __METHOD__); static::$main = $this; } if (!$this->route) { static::reset_request(); throw new \HttpNotFoundException(); } // save the current language so we can restore it after the call $current_language = \Config::get('language', 'en'); try { if ($this->route->callable !== null) { $response = call_fuel_func_array($this->route->callable, array($this)); if (!$response instanceof Response) { $response = new \Response($response); } } else { $method_prefix = $this->method . '_'; $class = $this->controller; // Allow override of method params from execute if (is_array($method_params)) { $this->method_params = array_merge($this->method_params, $method_params); } // If the class doesn't exist then 404 if (!class_exists($class)) { throw new \HttpNotFoundException(); } // Load the controller using reflection $class = new \ReflectionClass($class); if ($class->isAbstract()) { throw new \HttpNotFoundException(); } // Create a new instance of the controller $this->controller_instance = $class->newInstance($this); $this->action = $this->action ?: ($class->hasProperty('default_action') ? $class->getProperty('default_action')->getValue($this->controller_instance) : 'index'); $method = $method_prefix . $this->action; // Allow to do in controller routing if method router(action, params) exists if ($class->hasMethod('router')) { $method = 'router'; $this->method_params = array($this->action, $this->method_params); } if (!$class->hasMethod($method)) { // If they call user, go to $this->post_user(); $method = strtolower(\Input::method()) . '_' . $this->action; // Fall back to action_ if no HTTP request method based method exists if (!$class->hasMethod($method)) { $method = 'action_' . $this->action; } } if ($class->hasMethod($method)) { $action = $class->getMethod($method); if (!$action->isPublic()) { throw new \HttpNotFoundException(); } if (count($this->method_params) < $action->getNumberOfRequiredParameters()) { throw new \HttpNotFoundException(); } // fire any controller started events \Event::instance()->has_events('controller_started') and \Event::instance()->trigger('controller_started', '', 'none'); $class->hasMethod('before') and $class->getMethod('before')->invoke($this->controller_instance); $response = $action->invokeArgs($this->controller_instance, $this->method_params); $class->hasMethod('after') and $response = $class->getMethod('after')->invoke($this->controller_instance, $response); // fire any controller finished events \Event::instance()->has_events('controller_finished') and \Event::instance()->trigger('controller_finished', '', 'none'); } else { throw new \HttpNotFoundException(); } } // restore the language setting \Config::set('language', $current_language); } catch (\Exception $e) { static::reset_request(); // restore the language setting \Config::set('language', $current_language); throw $e; } // Get the controller's output if ($response instanceof Response) { $this->response = $response; } else { throw new \FuelException(get_class($this->controller_instance) . '::' . $method . '() or the controller after() method must return a Response object.'); } // fire any request finished events \Event::instance()->has_events('request_finished') and \Event::instance()->trigger('request_finished', '', 'none'); if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ': End of ' . $this->uri->get()); } static::reset_request(); return $this; }
* Date: 26.05.2015 * Time: 7:06 * Входная точка */ error_reporting(E_ALL); /** * Устанавливаем корневую директорию */ define('ROOT_PATH', dirname(__FILE__) . '/'); define('EXT', '.php'); /** * Подключаем и регистрируем автозагрузчик */ require_once ROOT_PATH . 'vendor/autoload' . EXT; //Инициализация событийной модели Event::instance(); Event::fire('App.beforeAppStart', null); //Запуск приложения App::start(); /** * Ограничивает доступ к файлу напрямую из адресной строки * todo:: перенести все эту функцию в отдельный файл с такими же функциами-помошниками */ function restrictAccess() { if (!defined('ROOT_PATH')) { header('HTTP/1.0 404 Not Found'); die("<h1>404 Not Found</h1>The page that you have requested could not be found."); } } /**
<?php // Listen for events Event::instance('wi3.beforeinit')->callback(array('Wi3TikoCache', 'beforeInit')); Event::instance('wi3.afterexecution.processcontent')->callback(array('Wi3TikoCache', 'afterExecution'));
public function setUp() { $this->Event = \Event::instance(); }