public function action_change() { //トークンの生成 $this->action_csrf(); //バリデーション定義 $val = Validation::forge(); $val->add('password', '「現在のパスワード」')->add_rule('required')->add_rule('min_length', 8)->add_rule('max_length', 12); $val->add('newpassword', '「新しいパスワード」または、「(新)パスワード再入力」')->add_rule('required')->add_rule('min_length', 8)->add_rule('max_length', 12); $this->action_category(); if (Input::post()) { if (Security::check_token()) { if ($val->run()) { $username = Auth::get_screen_name(); //現在のパスワード $old_password = Input::post('password'); //新しいパスワード $new_password = Input::post('newpassword'); //パスワードを変更するメソッド Auth::change_password($old_password, $new_password, $username); $this->message = 'パスワードが変更されました。'; $view = View::forge('changepass/ChangePass', $this->data); $view->set_global('message', $this->message, false); $view->set_global('error', $this->error, false); } else { $this->error = $val->error(); $view = View::forge('changepass/ChangePass', $this->data); $view->set_global('message', $this->message, false); $view->set_global('error', $this->error, false); } } else { Profiler::mark('CSRF攻撃'); } } return $view; }
public function serve($content, $modified = false) { $cache_last_modified = $modified ? time() : filemtime($this->path); $header_modified_since = strtotime(\Input::server('HTTP_IF_MODIFIED_SINCE', 0)); $status = 200; // Set the response headers for cache etc $headers = array('Cache-Control' => 'public', 'Last-Modified' => gmdate('D, d M Y H:i:s', $cache_last_modified) . ' GMT', 'Content-Type' => $this->content_type, 'X-UA-Compatible' => 'IE=edge'); // Still call the before method on the controller... is this a good idea? Perhaps not. /* if (isset($this->request) && $controller = $this->request->controller_instance) { if (method_exists($controller, 'before')) $controller->before($content); } */ // Return 304 not modified if the content hasn't changed, but only if the profiler isn't enabled. if (!\Fuel::$profiling) { $headers['Content-Length'] = strlen($content); if ($header_modified_since >= $cache_last_modified) { header('HTTP/1.1 304 Not Modified'); exit; } } // Send the response \Response::forge($content, $status, $headers)->send(true); if (\Fuel::$profiling) { \Profiler::mark('CMF Cache Served'); } exit; }
function __construct() { if (isset($_GET['debug_profile'])) { Profiler::mark("Director", "construct"); } Session::addToArray('history', substr($_SERVER['REQUEST_URI'], strlen(Director::baseURL()))); if (isset($_GET['debug_profile'])) { Profiler::unmark("Director", "construct"); } }
/** * runTask * * @param string $name * @param callable $callback * @param integer $times * * @return $this */ protected function run($name, $callback, $times) { $this->profiler->mark($name . '-start'); foreach (range(1, $times) as $row) { call_user_func($callback); } $this->profiler->mark($name . '-end'); $time = $this->profiler->getTimeBetween($name . '-start', $name . '-end'); $time = $time * $this->format; $this->results[$name] = $time; return $this; }
function FieldHolder() { $fieldName = $this->name . 'ID'; $relationName = $this->name; Profiler::mark("RelatedDataEditor.FieldHolder", "get data"); $record = $this->form->getRecord(); $relatedObject = $record->{$relationName}(); Profiler::unmark("RelatedDataEditor.FieldHolder", "get data"); $this->dropdownField->Name = $this->name . '[ID]'; $this->dropdownField->Value = $record->{$fieldName}; $extraclass = $this->IsNested() ? "nested" : ""; $result .= "<div id=\"{$this->name}\" class=\"{$this->class} groupfield {$extraclass}\" >"; $fieldholder = $this->dropdownField->FieldHolder(); if ($this->showkeydropdown) { $result .= "<div id=\"{$this->name}_keyholder\" class=\"keyholder\">{$fieldholder}</div>"; if ($this->children) { $result .= "<img id=\"{$this->name}_loading\" src=\"cms/images/network-save.gif\" style=\"display: none;\" />"; $result .= "<img id=\"{$this->name}_loaded\" src=\"cms/images/alert-good.gif\" style=\"display: none;\" />"; } } else { $result .= "<div id=\"{$this->name}_keyholder\" class=\"keyholder\" style=\"display: none\">{$fieldholder}</div>"; } if ($this->children) { $result .= "<div id= \"{$this->name}_childrenholder\" class=\"children_holder\">"; foreach ($this->children as $child) { if (!$child->isComposite()) { $childFieldName = $child->Name(); $child->Name = $this->name . '[' . $child->Name() . ']'; if ($this->dropdownField->isSelected()) { $child->Value = $relatedObject->{$childFieldName}; } $child->setForm($this->form); $result .= $child->FieldHolder(); } else { $fs = $child->FieldSet(); foreach ($fs as $subfield) { $childFieldName = $subfield->Name(); $subfield->Name = $this->name . '[' . $subfield->Name() . ']'; if ($this->dropdownField->isSelected()) { $subfield->Value = $relatedObject->{$childFieldName}; } $subfield->setForm($this->form); } $result .= $child->FieldHolder(); } } $result .= "<div class=\"clear\"> </div>"; $result .= "</div>"; } $result .= "</div>"; return $result; }
/** * updates database fields * @param Bool $force - run it, even if it has run already * @return void */ public function runUpdate($force = true) { if (isset($_GET['debug_profile'])) { Profiler::mark('OrderMaker::runUpdate'); } if (!$this->IsRemoved()) { $this->checkField("OrderFor"); parent::runUpdate($force); } if (isset($_GET['debug_profile'])) { Profiler::unmark('OrderMaker::runUpdate'); } }
/** * For all modifers with their own database fields, we need to include this... * It will update each of the fields. * Within this method, we need to create the methods * Live{functionName} * e.g LiveMyField() and LiveMyReduction() in this case... * The OrderModifier already updates the basic database fields. * @param Bool $force - run it, even if it has run already */ public function runUpdate($force = false) { if (isset($_GET['debug_profile'])) { Profiler::mark('ModifierExample::runUpdate'); } if (!$this->IsRemoved()) { $this->checkField("MyField"); $this->checkField("MyReduction"); } if (isset($_GET['debug_profile'])) { Profiler::unmark('ModifierExample::runUpdate'); } parent::runUpdate($force); }
public function action_index() { // 実行時間の計測ポイント Profiler::mark('indexアクションの開始'); $file = DOCROOT . 'show_file.php'; $content = file_get_contents($file); $title = 'ファイル表示プログラム'; $view = View::forge('showfile'); $view->set('title', $title); $view->set('content', $content); // 実行時間の計測ポイント Profiler::mark('indexアクションの終了'); return $view; }
/** * Load every call to the API with this method. * * @return void * @access public */ public function action_index() { // Profile the loader \Profiler::mark('Start of loader\'s action_index() function'); \Profiler::mark_memory($this, 'Start of loader\'s action_index() function'); // Make sure we aren't processing crap. if (in_array($this->format, array('csv', 'php', 'serialize'))) { $this->format = 'json'; } // For some reason this value is quoted when set to html. if (\Input::post('format') === '"html"') { $this->format = 'html'; } // Cleanse the session to keep things stable. \Session::destroy(); // For error handling \Session::set('response_format', $this->format); // External error processing through Apache if (\Uri::segment(1) === 'error' && is_numeric(\Uri::segment(2)) && strlen(\Uri::segment(2)) === 3) { return $this->response(\Utility::format_error(\Uri::segment(2))); } // /loader/index/error/404 style (Due to routing) if (substr_count(\Uri::current(), 'loader/index/error') === 1 && is_numeric(\Uri::segment(4)) && strlen(\Uri::segment(4)) === 3) { return $this->response(\Utility::format_error(\Uri::segment(4))); } // We need a version number if (empty(\Uri::segment(1)) || \Module::exists(\Uri::segment(1)) === false) { $error_data = \Utility::format_error(400, \Err::BAD_OR_NO_VERSION, \Lang::get('errors.bad_version')); return $this->response($error_data, 400); } // We need a request. if (empty(\Input::post()) || \Input::method() !== 'POST') { $error_data = \Utility::format_error(405, null, \Lang::get('errors.no_request')); return $this->response($error_data, 405); } // Pass the request to the proper API version request handler. (Module) if (!empty(\Input::post())) { \Module::load(\Uri::segment(1)); $response = \Request::forge(\Uri::segment(1) . '/index', false)->execute()->response->body; // HTML only Data Calls if (is_string($response)) { return $this->response($response, 200); } return $this->response($response[0], $response[1]); } }
public function get($url) { if (\Fuel::$profiling) { \Profiler::mark('CMF Cache Start (auto)'); } $this->request = \Request::active(); $this->path = APPPATH . 'cache/pages/' . \CMF\Cache::uriCacheKey($url) . '.cache'; if (file_exists($this->path)) { $contents = unserialize(file_get_contents($this->path)); // Check the files first $cache_modified = filemtime($this->path); foreach ($contents['files'] as $file) { $file = PROJECTROOT . $file; if (!file_exists($file) || filemtime($file) > $cache_modified) { $this->startListeners(); return false; } } // Now check the last modified / record counts from the DB if (!empty($contents['sql'])) { $result = \DB::query($contents['sql'])->execute()->as_array(); $result = $result[0]; if ($result['count'] !== $contents['count'] || strtotime($result['updated_at']) > $contents['updated_at']) { $this->startListeners(); return false; } } // See if the cache defines a content type if (isset($contents['content-type'])) { $this->content_type = $contents['content-type']; } // We are home and dry - the cache is completely valid. // Replicate any logs that were made in the original request \CMF\Log::addMultiple($contents['logs_made']); // Ok, now we can serve the cache, finally!! // We process the cached content to find and replace any areas that shouldn't be cached return \CMF\Cache::addNoCacheAreas($contents['nocache'], $contents['content'], array('template' => @$contents['template'], 'module' => @$contents['module'])); } // If we've arrived here, we need to start listening for queries and assets $this->startListeners(); return false; }
/** * Overridden to load all children from Cmis instead of this node * directly * * @param boolean $showAll * @return DataObjectSet */ public function stageChildren($showAll = false) { if (!$this->ID) { return DataObject::get('CmisContentSource'); } $repo = $this->source->getRemoteRepository(); $children = ArrayList::create(); if ($repo->isConnected()) { if (isset($_GET['debug_profile'])) { Profiler::mark("CmisContentItem", "getChildren"); } $childItems = $repo->getChildren($this->cmisObject); if ($childItems) { foreach ($childItems as $child) { $item = new CmisContentItem($this->source, $child); $children->push($item); } } if (isset($_GET['debug_profile'])) { Profiler::unmark("CmisContentItem", "getChildren"); } } return $children; }
/** * Update the given HTML content with the appropriate include tags for the registered * requirements. * @todo Calculate $prefix properly */ static function includeInHTML($templateFile, $content) { if (isset($_GET['debug_profile'])) { Profiler::mark("Requirements::includeInHTML"); } if (strpos($content, '</head') !== false && (Requirements::$javascript || Requirements::$css || Requirements::$customScript || Requirements::$customHeadTags)) { $prefix = ""; $requirements = ''; foreach (array_diff_key(self::$javascript, self::$blocked) as $file => $dummy) { if (substr($file, 0, 7) == 'http://' || Director::fileExists($file)) { $requirements .= "<script type=\"text/javascript\" src=\"{$prefix}{$file}\"></script>\n"; } } if (self::$customScript) { $requirements .= "<script type=\"text/javascript\">\n//<![CDATA[\n"; foreach (array_diff_key(self::$customScript, self::$blocked) as $script) { $requirements .= "{$script}\n"; } $requirements .= "\n//]]>\n</script>\n"; } foreach (array_diff_key(self::$css, self::$blocked) as $file => $params) { if (Director::fileExists($file)) { $media = isset($params['media']) ? " media=\"{$params['media']}\"" : ""; $requirements .= "<link rel=\"stylesheet\" type=\"text/css\"{$media} href=\"{$prefix}{$file}\" />\n"; } } foreach (array_diff_key(self::$customCSS, self::$blocked) as $css) { $requirements .= "<style type=\"text/css\">\n{$css}\n</style>\n"; } $requirements .= self::$customHeadTags; if (isset($_GET['debug_profile'])) { Profiler::unmark("Requirements::includeInHTML"); } return eregi_replace("(</head[^>]*>)", $requirements . "\\1", $content); } else { if (isset($_GET['debug_profile'])) { Profiler::unmark("Requirements::includeInHTML"); } return $content; } }
/** * The process() method handles the "meat" of the template processing. */ public function process($item) { SSViewer::$topLevel[] = $item; if(isset($this->chosenTemplates['main'])) { $template = $this->chosenTemplates['main']; } else { $template = $this->chosenTemplates[ reset($dummy = array_keys($this->chosenTemplates)) ]; } if(isset($_GET['debug_profile'])) Profiler::mark("SSViewer::process", " for $template"); $cacheFile = TEMP_FOLDER . "/.cache" . str_replace(array('\\','/',':'),'.',realpath($template)); $lastEdited = filemtime($template); if(!file_exists($cacheFile) || filemtime($cacheFile) < $lastEdited || isset($_GET['flush'])) { if(isset($_GET['debug_profile'])) Profiler::mark("SSViewer::process - compile", " for $template"); $content = file_get_contents($template); $content = SSViewer::parseTemplateContent($content, $template); $fh = fopen($cacheFile,'w'); fwrite($fh, $content); fclose($fh); if(isset($_GET['debug_profile'])) Profiler::unmark("SSViewer::process - compile", " for $template"); } if(isset($_GET['showtemplate']) && !Director::isLive()) { $lines = file($cacheFile); echo "<h2>Template: $cacheFile</h2>"; echo "<pre>"; foreach($lines as $num => $line) { echo str_pad($num+1,5) . htmlentities($line); } echo "</pre>"; } foreach(array('Content', 'Layout') as $subtemplate) { if(isset($this->chosenTemplates[$subtemplate])) { $subtemplateViewer = new SSViewer($this->chosenTemplates[$subtemplate]); $item = $item->customise(array( $subtemplate => $subtemplateViewer->process($item) )); } } $itemStack = array(); $val = ""; include($cacheFile); $output = $val; $output = Requirements::includeInHTML($template, $output); array_pop(SSViewer::$topLevel); if(isset($_GET['debug_profile'])) Profiler::unmark("SSViewer::process", " for $template"); // If we have our crazy base tag, then fix # links referencing the current page. if(strpos($output, '<base') !== false) { $thisURLRelativeToBase = Director::makeRelative(Director::absoluteURL($_SERVER['REQUEST_URI'])); $output = preg_replace('/(<a[^>+]href *= *")#/i', '\\1' . $thisURLRelativeToBase . '#', $output); } return $output; }
/** * Overridden to load all children from Matrix. For now we're ignoring * the $showAll param - we have a separate 'dependentChildren' method * to specifically handle dependent and non-dependent children * * @param boolean $showAll * @return ArrayList */ public function stageChildren($showAll = false) { if (!$this->ID) { return MatrixContentSource::get(); } if (!$this->objChildren) { $this->objChildren = new ArrayList(); // For the first batch, just get all the immediate children of the // top level $repo = $this->source->getRemoteRepository(); if ($repo->isConnected()) { if (isset($_GET['debug_profile'])) { Profiler::mark("MatrixContentItem", "getChildren"); } if (!isset($this->remoteProperties['id'])) { // for some reason the call failed! return $this->objChildren; } $childItems = $repo->getChildren(array('id' => $this->remoteProperties['id'], 'depth' => 1)); if (isset($_GET['debug_profile'])) { Profiler::unmark("MatrixContentItem", "getChildren"); } // make sure that there's no errors!! if (!isset($childItems->error)) { if (isset($_GET['debug_profile'])) { Profiler::mark("MatrixContentItem", "loadChildren"); } // means there weren't any children of this asset foreach ($childItems as $childId => $properties) { $item = $this->source->getObject($properties->id); if (isset($properties->LinkType)) { $item->ShowInMenus = true; } $this->objChildren->push($item); } if (isset($_GET['debug_profile'])) { Profiler::unmark("MatrixContentItem", "loadChildren"); } } } } return $this->objChildren; }
function silverstripe_main($chain) { global $token; if (isset($_GET['flush']) && !$token->tokenProvided()) { unset($_GET['flush']); } else { $chain->setSuppression(false); } /** * Include Sapphire's core code */ require_once "core/Core.php"; if (function_exists('mb_http_output')) { mb_http_output('UTF-8'); mb_internal_encoding('UTF-8'); } Session::start(); if (isset($_GET['debug_profile'])) { Profiler::init(); Profiler::mark('all_execution'); Profiler::mark('main.php init'); } // Connect to database require_once "core/model/DB.php"; global $databaseConfig; if (isset($_GET['debug_profile'])) { Profiler::mark('DB::connect'); } if ($databaseConfig) { DB::connect($databaseConfig); } if (isset($_GET['debug_profile'])) { Profiler::unmark('DB::connect'); } if ($token->parameterProvided() && !$token->tokenProvided()) { // First, check if we're in dev mode, or the database doesn't have any security data $canFlush = Director::isDev() || !Security::database_is_ready(); // Otherwise, we start up the session if needed, then check for admin if (!$canFlush) { if (!isset($_SESSION) && (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))) { Session::start(); } if (Permission::check('ADMIN')) { $canFlush = true; } else { $loginPage = Director::absoluteURL('Security/login'); $loginPage .= "?BackURL=" . urlencode($_SERVER['REQUEST_URI']); header('location: ' . $loginPage, true, 302); die; } } // And if we can flush, reload with an authority token if ($canFlush) { $token->reloadWithToken(); } } }
/** * The process() method handles the "meat" of the template processing. * It takes care of caching the output (via {@link SS_Cache}), * as well as replacing the special "$Content" and "$Layout" * placeholders with their respective subtemplates. * The method injects extra HTML in the header via {@link Requirements::includeInHTML()}. * * Note: You can call this method indirectly by {@link ViewableData->renderWith()}. * * @param ViewableData $item * @param SS_Cache $cache Optional cache backend * @return String Parsed template output. */ public function process($item, $cache = null) { SSViewer::$topLevel[] = $item; if (!$cache) { $cache = SS_Cache::factory('cacheblock'); } if (isset($this->chosenTemplates['main'])) { $template = $this->chosenTemplates['main']; } else { $template = $this->chosenTemplates[reset($dummy = array_keys($this->chosenTemplates))]; } if (isset($_GET['debug_profile'])) { Profiler::mark("SSViewer::process", " for {$template}"); } $cacheFile = TEMP_FOLDER . "/.cache" . str_replace(array('\\', '/', ':'), '.', realpath($template)); $lastEdited = filemtime($template); if (!file_exists($cacheFile) || filemtime($cacheFile) < $lastEdited || isset($_GET['flush'])) { if (isset($_GET['debug_profile'])) { Profiler::mark("SSViewer::process - compile", " for {$template}"); } $content = file_get_contents($template); $content = SSViewer::parseTemplateContent($content, $template); $fh = fopen($cacheFile, 'w'); fwrite($fh, $content); fclose($fh); if (isset($_GET['debug_profile'])) { Profiler::unmark("SSViewer::process - compile", " for {$template}"); } } if (isset($_GET['showtemplate']) && !Director::isLive()) { $lines = file($cacheFile); echo "<h2>Template: {$cacheFile}</h2>"; echo "<pre>"; foreach ($lines as $num => $line) { echo str_pad($num + 1, 5) . htmlentities($line); } echo "</pre>"; } // Makes the rendered sub-templates available on the parent item, // through $Content and $Layout placeholders. foreach (array('Content', 'Layout') as $subtemplate) { if (isset($this->chosenTemplates[$subtemplate])) { $subtemplateViewer = new SSViewer($this->chosenTemplates[$subtemplate]); $item = $item->customise(array($subtemplate => $subtemplateViewer->process($item, $cache))); } } $itemStack = array(); $val = ""; $valStack = array(); include $cacheFile; $output = $val; $output = Requirements::includeInHTML($template, $output); array_pop(SSViewer::$topLevel); if (isset($_GET['debug_profile'])) { Profiler::unmark("SSViewer::process", " for {$template}"); } // If we have our crazy base tag, then fix # links referencing the current page. if ($this->rewriteHashlinks && self::$options['rewriteHashlinks']) { if (strpos($output, '<base') !== false) { if (SSViewer::$options['rewriteHashlinks'] === 'php') { $thisURLRelativeToBase = "<?php echo \$_SERVER['REQUEST_URI']; ?>"; } else { $thisURLRelativeToBase = Director::makeRelative(Director::absoluteURL($_SERVER['REQUEST_URI'])); } $output = preg_replace('/(<a[^>]+href *= *)"#/i', '\\1"' . $thisURLRelativeToBase . '#', $output); } } return $output; }
/** * Update the given HTML content with the appropriate include tags for the registered * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter, * including a <head> tag. The requirements will insert before the closing <head> tag automatically. * * @todo Calculate $prefix properly * * @param string $templateFilePath Absolute path for the *.ss template file * @param string $content HTML content that has already been parsed from the $templateFilePath through {@link SSViewer}. * @return string HTML content thats augumented with the requirements before the closing <head> tag. */ function includeInHTML($templateFile, $content) { if (isset($_GET['debug_profile'])) { Profiler::mark("Requirements::includeInHTML"); } if (strpos($content, '</head') !== false && ($this->css || $this->javascript || $this->customCSS || $this->customScript || $this->customHeadTags)) { $requirements = ''; $jsRequirements = ''; // Combine files - updates $this->javascript and $this->css $this->process_combined_files(); foreach (array_diff_key($this->javascript, $this->blocked) as $file => $dummy) { $path = $this->path_for_file($file); if ($path) { $jsRequirements .= "<script type=\"text/javascript\" src=\"{$path}\"></script>\n"; } } // add all inline javascript *after* including external files which // they might rely on if ($this->customScript) { foreach (array_diff_key($this->customScript, $this->blocked) as $script) { $jsRequirements .= "<script type=\"text/javascript\">\n//<![CDATA[\n"; $jsRequirements .= "{$script}\n"; $jsRequirements .= "\n//]]>\n</script>\n"; } } foreach (array_diff_key($this->css, $this->blocked) as $file => $params) { $path = $this->path_for_file($file); if ($path) { $media = isset($params['media']) && !empty($params['media']) ? " media=\"{$params['media']}\"" : ""; $requirements .= "<link rel=\"stylesheet\" type=\"text/css\"{$media} href=\"{$path}\" />\n"; } } foreach (array_diff_key($this->customCSS, $this->blocked) as $css) { $requirements .= "<style type=\"text/css\">\n{$css}\n</style>\n"; } foreach (array_diff_key($this->customHeadTags, $this->blocked) as $customHeadTag) { $requirements .= "{$customHeadTag}\n"; } if ($this->write_js_to_body) { // Remove all newlines from code to preserve layout $jsRequirements = preg_replace('/>\\n*/', '>', $jsRequirements); // We put script tags into the body, for performance. // If your template already has script tags in the body, then we put our script // tags just before those. Otherwise, we put it at the bottom. $p1 = strripos($content, '<script'); $p2 = stripos($content, '<body'); if ($p1 !== false && $p1 > $p2) { $content = substr($content, 0, $p1) . $jsRequirements . substr($content, $p1); } else { $content = preg_replace("/(<\\/body[^>]*>)/i", $jsRequirements . "\\1", $content); } // Put CSS at the bottom of the head $content = preg_replace("/(<\\/head>)/i", $requirements . "\\1", $content); } else { $content = preg_replace("/(<\\/head>)/i", $requirements . "\\1", $content); $content = preg_replace("/(<\\/head>)/i", $jsRequirements . "\\1", $content); } } if (isset($_GET['debug_profile'])) { Profiler::unmark("Requirements::includeInHTML"); } return $content; }
/** * Construct takes a URI or detects it if none is given and generates * the segments. * * @param string The URI * @return void */ public function __construct($uri = null) { if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' Start'); } $this->uri = trim($uri ?: \Input::uri(), '/'); $this->segments = $this->uri === '' ? array() : explode('/', $this->uri); if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' End'); } }
/** * Cleans up Fuel execution, ends the output buffering, and outputs the * buffer contents. * * @access public * @return void */ public static function finish() { if (static::$caching && static::$paths_changed === true) { static::cache('Fuel::path_cache', static::$path_cache); } // Grab the output buffer $output = ob_get_clean(); if (static::$profiling) { \Profiler::mark('End of Fuel Execution'); if (preg_match("|</body>.*?</html>|is", $output)) { $output = preg_replace("|</body>.*?</html>|is", '', $output); $output .= \Profiler::output(); $output .= '</body></html>'; } else { $output .= \Profiler::output(); } } $bm = \Profiler::app_total(); // TODO: There is probably a better way of doing this, but this works for now. $output = \str_replace(array('{exec_time}', '{mem_usage}'), array(round($bm[0], 4), round($bm[1] / pow(1024, 2), 3)), $output); // Send the buffer to the browser. echo $output; }
/** * Construct takes a URI or detects it if none is given and generates * the segments. * * @param string The URI * @return void */ public function __construct($uri = null) { if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' Start'); } // if the route is a closure, an object will be passed here is_object($uri) and $uri = null; $this->uri = trim($uri ?: \Input::uri(), '/'); if (empty($this->uri)) { $this->segments = array(); } else { $this->segments = explode('/', $this->uri); } if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' End'); } }
/** * Run the controller (default action) * * @param array $requestParams Passed request parameters */ function index($requestParams) { if (isset($_GET['debug_profile'])) { Profiler::mark("OpenIDAuthenticator_Controller"); } $consumer = new Auth_OpenID_Consumer(new OpenIDStorage(), new SessionWrapper()); // Complete the authentication process using the server's response. $response = $consumer->complete(); if ($response->status == Auth_OpenID_CANCEL) { Session::set("Security.Message.message", _t('OpenIDAuthenticator.VERIFICATIONCANCELLED', 'The verification was cancelled. Please try again.')); Session::set("Security.Message.type", "bad"); if (isset($_GET['debug_profile'])) { Profiler::unmark("OpenIDAuthenticator_Controller"); } Director::redirect("Security/login"); } else { if ($response->status == Auth_OpenID_FAILURE) { Session::set("Security.Message.message", _t('OpenIDAuthenticator.AUTHFAILED', 'The OpenID/i-name authentication failed.')); Session::set("Security.Message.type", "bad"); if (isset($_GET['debug_profile'])) { Profiler::unmark("OpenIDAuthenticator_Controller"); } Director::redirect("Security/login"); } else { if ($response->status == Auth_OpenID_SUCCESS) { $openid = $response->identity_url; if ($response->endpoint->canonicalID) { $openid = $response->endpoint->canonicalID; } if (isset($_GET['debug_profile'])) { Profiler::unmark("OpenIDAuthenticator_Controller"); } $SQL_identity = Convert::raw2sql($openid); if ($member = DataObject::get_one("Member", "Member.IdentityURL = '{$SQL_identity}'")) { $firstname = Convert::raw2xml($member->FirstName); Session::set("Security.Message.message", sprintf(_t('Member.WELCOMEBACK'), $firstname)); Session::set("Security.Message.type", "good"); $member->LogIn(Session::get('SessionForms.OpenIDLoginForm.Remember')); Session::clear('SessionForms.OpenIDLoginForm.OpenIDURL'); Session::clear('SessionForms.OpenIDLoginForm.Remember'); if ($backURL = Session::get("BackURL")) { Session::clear("BackURL"); Director::redirect($backURL); } else { Director::redirectBack(); } } else { Session::set("Security.Message.message", _t('OpenIDAuthenticator.LOGINFAILED', 'Login failed. Please try again.')); Session::set("Security.Message.type", "bad"); if ($badLoginURL = Session::get("BadLoginURL")) { Director::redirect($badLoginURL); } else { Director::redirectBack(); } } } } } }
/** * Get the value of a field on this object, automatically inserting the value into any available casting objects * that have been specified. * * @param string $fieldName * @param array $arguments * @param bool $forceReturnedObject if TRUE, the value will ALWAYS be casted to an object before being returned, * even if there is no explicit casting information * @param string $cacheName a custom cache name */ public function obj($fieldName, $arguments = null, $forceReturnedObject = true, $cache = false, $cacheName = null) { if (isset($_REQUEST['debug_profile'])) { Profiler::mark("obj.{$fieldName}", "on a {$this->class} object"); } if (!$cacheName) { $cacheName = $arguments ? $fieldName . implode(',', $arguments) : $fieldName; } if (!isset($this->objCache[$cacheName])) { // HACK: Don't call the deprecated FormField::Name() method $methodIsAllowed = true; if ($this instanceof FormField && $fieldName == 'Name') { $methodIsAllowed = false; } if ($methodIsAllowed && $this->hasMethod($fieldName)) { $value = $arguments ? call_user_func_array(array($this, $fieldName), $arguments) : $this->{$fieldName}(); } else { $value = $this->{$fieldName}; } if (!is_object($value) && ($this->castingClass($fieldName) || $forceReturnedObject)) { if (!($castConstructor = $this->castingHelper($fieldName))) { $castConstructor = $this->stat('default_cast'); } $valueObject = Object::create_from_string($castConstructor, $fieldName); $valueObject->setValue($value, $this->hasMethod('toMap') ? $this->toMap() : null); $value = $valueObject; } if ($cache) { $this->objCache[$cacheName] = $value; } } else { $value = $this->objCache[$cacheName]; } if (isset($_REQUEST['debug_profile'])) { Profiler::unmark("obj.{$fieldName}", "on a {$this->class} object"); } if (!is_object($value) && $forceReturnedObject) { $default = Config::inst()->get('ViewableData', 'default_cast', Config::FIRST_SET); $value = new $default($fieldName); } return $value; }
/** * Generate the given field on the table, modifying whatever already exists as necessary. * @param string $table The table name. * @param string $field The field name. * @param array|string $spec The field specification. If passed in array syntax, the specific database * driver takes care of the ALTER TABLE syntax. If passed as a string, its assumed to * be prepared as a direct SQL framgment ready for insertion into ALTER TABLE. In this case you'll * need to take care of database abstraction in your DBField subclass. */ function requireField($table, $field, $spec) { //TODO: this is starting to get extremely fragmented. //There are two different versions of $spec floating around, and their content changes depending //on how they are structured. This needs to be tidied up. $fieldValue = null; $newTable = false; Profiler::mark('requireField'); // backwards compatibility patch for pre 2.4 requireField() calls $spec_orig=$spec; if(!is_string($spec)) { $spec['parts']['name'] = $field; $spec_orig['parts']['name'] = $field; //Convert the $spec array into a database-specific string $spec=DB::getConn()->$spec['type']($spec['parts'], true); } // Collations didn't come in until MySQL 4.1. Anything earlier will throw a syntax error if you try and use // collations. // TODO: move this to the MySQLDatabase file, or drop it altogether? if(!$this->supportsCollations()) { $spec = preg_replace('/ *character set [^ ]+( collate [^ ]+)?( |$)/', '\\2', $spec); } if(!isset($this->tableList[strtolower($table)])) $newTable = true; if(!$newTable && !isset($this->fieldList[$table])) { $this->fieldList[$table] = $this->fieldList($table); } if(is_array($spec)) { $specValue = DB::getConn()->$spec_orig['type']($spec_orig['parts']); } else { $specValue = $spec; } // We need to get db-specific versions of the ID column: if($spec_orig==DB::getConn()->IdColumn() || $spec_orig==DB::getConn()->IdColumn(true)) $specValue=DB::getConn()->IdColumn(true); if(!$newTable) { if(isset($this->fieldList[$table][$field])) { if(is_array($this->fieldList[$table][$field])) { $fieldValue = $this->fieldList[$table][$field]['data_type']; } else { $fieldValue = $this->fieldList[$table][$field]; } } } // Get the version of the field as we would create it. This is used for comparison purposes to see if the // existing field is different to what we now want if(is_array($spec_orig)) { $spec_orig=DB::getConn()->$spec_orig['type']($spec_orig['parts']); } if($newTable || $fieldValue=='') { Profiler::mark('createField'); $this->transCreateField($table, $field, $spec_orig); Profiler::unmark('createField'); $this->alterationMessage("Field $table.$field: created as $spec_orig","created"); } else if($fieldValue != $specValue) { // If enums/sets are being modified, then we need to fix existing data in the table. // Update any records where the enum is set to a legacy value to be set to the default. // One hard-coded exception is SiteTree - the default for this is Page. foreach(array('enum','set') as $enumtype) { if(preg_match("/^$enumtype/i",$specValue)) { $newStr = preg_replace("/(^$enumtype\s*\(')|('$\).*)/i","",$spec_orig); $new = preg_split("/'\s*,\s*'/", $newStr); $oldStr = preg_replace("/(^$enumtype\s*\(')|('$\).*)/i","", $fieldValue); $old = preg_split("/'\s*,\s*'/", $newStr); $holder = array(); foreach($old as $check) { if(!in_array($check, $new)) { $holder[] = $check; } } if(count($holder)) { $default = explode('default ', $spec_orig); $default = $default[1]; if($default == "'SiteTree'") $default = "'Page'"; $query = "UPDATE \"$table\" SET $field=$default WHERE $field IN ("; for($i=0;$i+1<count($holder);$i++) { $query .= "'{$holder[$i]}', "; } $query .= "'{$holder[$i]}')"; DB::query($query); $amount = DB::affectedRows(); $this->alterationMessage("Changed $amount rows to default value of field $field (Value: $default)"); } } } Profiler::mark('alterField'); $this->transAlterField($table, $field, $spec_orig); Profiler::unmark('alterField'); $this->alterationMessage("Field $table.$field: changed to $specValue <i style=\"color: #AAA\">(from {$fieldValue})</i>","changed"); } Profiler::unmark('requireField'); }
function run($requestParams) { if (isset($_GET['debug_profile'])) { Profiler::mark("Controller", "run"); } $this->pushCurrent(); $this->response = new HTTPResponse(); $this->requestParams = $requestParams; $this->action = isset($this->urlParams['Action']) ? str_replace("-", "_", $this->urlParams['Action']) : ""; if (!$this->action) { $this->action = 'index'; } // Check security on the controller if (!$this->checkAccessAction($this->action)) { user_error("Disallowed action: '{$this->action}' on controller '{$this->class}'", E_USER_ERROR); } // Init $this->baseInitCalled = false; $this->init(); if (!$this->baseInitCalled) { user_error("init() method on class '{$this->class}' doesn't call Controller::init(). Make sure that you have parent::init() included.", E_USER_WARNING); } // If we had a redirection or something, halt processing. if ($this->response->isFinished()) { $this->popCurrent(); return $this->response; } // Look at the action variables for forms $funcName = null; foreach ($this->requestParams as $paramName => $paramVal) { if (substr($paramName, 0, 7) == 'action_') { // Cleanup action_, _x and _y from image fields $funcName = preg_replace(array('/^action_/', '/_x$|_y$/'), '', $paramName); break; } } // Form handler if (isset($this->requestParams['executeForm']) && is_string($this->requestParams['executeForm'])) { if (isset($funcName)) { Form::set_current_action($funcName); } // Get the appropraite ocntroller: sometimes we want to get a form from another controller if (isset($this->requestParams['formController'])) { $formController = Director::getControllerForURL($this->requestParams['formController']); while (is_a($formController, 'NestedController')) { $formController = $formController->getNestedController(); } } else { $formController = $this; } // Create the form object $form = $formController; $formObjParts = explode('.', $this->requestParams['executeForm']); foreach ($formObjParts as $formMethod) { if (isset($_GET['debug_profile'])) { Profiler::mark("Calling {$formMethod}", "on {$form->class}"); } $form = $form->{$formMethod}(); if (isset($_GET['debug_profile'])) { Profiler::unmark("Calling {$formMethod}", "on {$form->class}"); } if (!$form) { break; } //user_error("Form method '" . $this->requestParams['executeForm'] . "' returns null in controller class '$this->class' ($_SERVER[REQUEST_URI])", E_USER_ERROR); } // Populate the form if (isset($_GET['debug_profile'])) { Profiler::mark("Controller", "populate form"); } if ($form) { $form->loadDataFrom($this->requestParams, true); // disregard validation if a single field is called if (!isset($_REQUEST['action_callfieldmethod'])) { $valid = $form->beforeProcessing(); if (!$valid) { $this->popCurrent(); return $this->response; } } else { $fieldcaller = $form->dataFieldByName($requestParams['fieldName']); if (is_a($fieldcaller, "TableListField")) { if ($fieldcaller->hasMethod('php')) { $valid = $fieldcaller->php($requestParams); if (!$valid) { exit; } } } } // If the action wasnt' set, choose the default on the form. if (!isset($funcName) && ($defaultAction = $form->defaultAction())) { $funcName = $defaultAction->actionName(); } if (isset($funcName)) { $form->setButtonClicked($funcName); } } else { user_error("No form (" . Session::get('CMSMain.currentPage') . ") returned by {$formController->class}->{$_REQUEST['executeForm']}", E_USER_WARNING); } if (isset($_GET['debug_profile'])) { Profiler::unmark("Controller", "populate form"); } if (!isset($funcName)) { user_error("No action button has been clicked in this form executon, and no default has been allowed", E_USER_ERROR); } // Protection against CSRF attacks if ($form->securityTokenEnabled()) { $securityID = Session::get('SecurityID'); if (!$securityID || !isset($this->requestParams['SecurityID']) || $securityID != $this->requestParams['SecurityID']) { // Don't show error on live sites, as spammers create a million of these if (!Director::isLive()) { trigger_error("Security ID doesn't match, possible CRSF attack.", E_USER_ERROR); } else { die; } } } // First, try a handler method on the controller if ($this->hasMethod($funcName) || !$form) { if (isset($_GET['debug_controller'])) { Debug::show("Found function {$funcName} on the controller"); } if (isset($_GET['debug_profile'])) { Profiler::mark("{$this->class}::{$funcName} (controller action)"); } $result = $this->{$funcName}($this->requestParams, $form); if (isset($_GET['debug_profile'])) { Profiler::unmark("{$this->class}::{$funcName} (controller action)"); } // Otherwise, try a handler method on the form object } else { if (isset($_GET['debug_controller'])) { Debug::show("Found function {$funcName} on the form object"); } if (isset($_GET['debug_profile'])) { Profiler::mark("{$form->class}::{$funcName} (form action)"); } $result = $form->{$funcName}($this->requestParams, $form); if (isset($_GET['debug_profile'])) { Profiler::unmark("{$form->class}::{$funcName} (form action)"); } } // Normal action } else { if (!isset($funcName)) { $funcName = $this->action; } if ($this->hasMethod($funcName)) { if (isset($_GET['debug_controller'])) { Debug::show("Found function {$funcName} on the {$this->class} controller"); } if (isset($_GET['debug_profile'])) { Profiler::mark("{$this->class}::{$funcName} (controller action)"); } $result = $this->{$funcName}($this->urlParams); if (isset($_GET['debug_profile'])) { Profiler::unmark("{$this->class}::{$funcName} (controller action)"); } } else { if (isset($_GET['debug_controller'])) { Debug::show("Running default action for {$funcName} on the {$this->class} controller"); } if (isset($_GET['debug_profile'])) { Profiler::mark("Controller::defaultAction({$funcName})"); } $result = $this->defaultAction($funcName, $this->urlParams); if (isset($_GET['debug_profile'])) { Profiler::unmark("Controller::defaultAction({$funcName})"); } } } // If your controller function returns an array, then add that data to the // default template if (is_array($result)) { $extended = $this->customise($result); $viewer = $this->getViewer($funcName); $result = $viewer->process($extended); } $this->response->setBody($result); if ($result) { ContentNegotiator::process($this->response); } // Set up HTTP cache headers HTTP::add_cache_headers($this->response); if (isset($_GET['debug_profile'])) { Profiler::unmark("Controller", "run"); } $this->popCurrent(); return $this->response; }
/** * 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; }
/** * 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) { if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' Start'); } 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(); } try { if ($this->route->callable !== null) { $response = call_user_func_array($this->route->callable, array($this)); } else { $method_prefix = 'action_'; $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, new \Response()); $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)) { $action = $class->getMethod($method); if (!$action->isPublic()) { throw new \HttpNotFoundException(); } $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); } else { throw new \HttpNotFoundException(); } } } catch (\Exception $e) { static::reset_request(); throw $e; } // Get the controller's output if (is_null($response)) { throw new \FuelException('The controller action called or it\'s after() method must return a Response object.'); } elseif ($response instanceof \Response) { $this->response = $response; } else { $this->response = \Response::forge($response, 200); } static::reset_request(); if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' End'); } return $this; }
/** * Cleans up Fuel execution, ends the output buffering, and outputs the * buffer contents. * * @access public * @return void */ public static function finish() { if (\Config::get('caching', false)) { \Finder::instance()->write_cache('FuelFileFinder'); } if (static::$profiling and !static::$is_cli and !\Input::is_ajax()) { // Grab the output buffer and flush it, we will rebuffer later $output = ob_get_clean(); $headers = headers_list(); $show = true; foreach ($headers as $header) { if (stripos($header, 'content-type') === 0 and stripos($header, 'text/html') === false) { $show = false; } } if ($show) { \Profiler::mark('End of Fuel Execution'); if (preg_match("|</body>.*?</html>|is", $output)) { $output = preg_replace("|</body>.*?</html>|is", '', $output); $output .= \Profiler::output(); $output .= '</body></html>'; } else { $output .= \Profiler::output(); } } // Restart the output buffer and send the new output ob_start(); echo $output; } }
/** * 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) { if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' Start'); } 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(); } try { if ($this->route->callable !== null) { $response = call_user_func_array($this->route->callable, array($this)); } else { $method_prefix = 'action_'; $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, new \Response()); $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)) { $action = $class->getMethod($method); if (!$action->isPublic()) { throw new \HttpNotFoundException(); } $class->getMethod('before')->invoke($this->controller_instance); $response = $action->invokeArgs($this->controller_instance, $this->method_params); $response_after = $class->getMethod('after')->invoke($this->controller_instance, $response); // @TODO let the after method set the response directly if (is_null($response_after)) { logger(\Fuel::L_WARNING, 'The ' . $class->getName() . '::after() method should accept and return the Controller\'s response, empty return for the after() method is deprecated.', __METHOD__); } else { $response = $response_after; } } else { throw new \HttpNotFoundException(); } } } catch (\Exception $e) { static::reset_request(); throw $e; } // Get the controller's output if (is_null($response)) { // @TODO remove this in a future version as we will get rid of it. logger(\Fuel::L_WARNING, 'The ' . $class->getName() . ' controller should return a string or a Response object, support for the $controller->response object is deprecated.', __METHOD__); $this->response = $this->controller_instance->response; } elseif ($response instanceof \Response) { $this->response = $response; } else { $this->response = \Response::forge($response, 200); } static::reset_request(); if (\Fuel::$profiling) { \Profiler::mark(__METHOD__ . ' End'); } return $this; }
Profiler::mark('main.php init'); } // Connect to database require_once "core/model/DB.php"; // Redirect to the installer if no database is selected if (!isset($databaseConfig) || !isset($databaseConfig['database']) || !$databaseConfig['database']) { $s = isset($_SERVER['SSL']) || isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 's' : ''; $installURL = "http{$s}://" . $_SERVER['HTTP_HOST'] . BASE_URL . '/install.php'; // The above dirname() will equate to "\" on Windows when installing directly from http://localhost (not using // a sub-directory), this really messes things up in some browsers. Let's get rid of the backslashes $installURL = str_replace('\\', '', $installURL); header("Location: {$installURL}"); die; } if (isset($_GET['debug_profile'])) { Profiler::mark('DB::connect'); } DB::connect($databaseConfig); if (isset($_GET['debug_profile'])) { Profiler::unmark('DB::connect'); } if (isset($_GET['debug_profile'])) { Profiler::unmark('main.php init'); } // Direct away - this is the "main" function, that hands control to the appropriate controller Director::direct($url); if (isset($_GET['debug_profile'])) { Profiler::unmark('all_execution'); if (!Director::isLive()) { Profiler::show(isset($_GET['profile_trace'])); }
function XML_val($fieldName, $args = null) { if (isset($this->extraData[$fieldName])) { if (isset($_GET['debug_profile'])) { Profiler::mark("template({$fieldName})", " on {$this->class} object"); } if (is_object($this->extraData[$fieldName])) { $val = $this->extraData[$fieldName]->forTemplate(); } else { $val = $this->extraData[$fieldName]; } if (isset($_GET['debug_profile'])) { Profiler::unmark("template({$fieldName})", " on {$this->class} object"); } return $val; } else { return $this->obj->XML_val($fieldName, $args); } }