public function query($sql, $errorLevel = E_USER_ERROR) { if (isset($_REQUEST['previewwrite']) && in_array(strtolower(substr($sql, 0, strpos($sql, ' '))), array('insert', 'update', 'delete', 'replace'))) { Debug::message("Will execute: {$sql}"); return; } if (isset($_REQUEST['showqueries'])) { $starttime = microtime(true); } // @todo This is a very ugly hack to rewrite the update statement of SiteTree::doPublish() // @see SiteTree::doPublish() There is a hack for MySQL already, maybe it's worth moving this to SiteTree or that other hack to Database... if (preg_replace('/[\\W\\d]*/i', '', $sql) == 'UPDATESiteTree_LiveSETSortSiteTreeSortFROMSiteTreeWHERESiteTree_LiveIDSiteTreeIDANDSiteTree_LiveParentID') { preg_match('/\\d+/i', $sql, $matches); $sql = 'UPDATE "SiteTree_Live" SET "Sort" = (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID") WHERE "ParentID" = ' . $matches[0]; } @($handle = $this->dbConn->query($sql)); if (isset($_REQUEST['showqueries'])) { $endtime = round(microtime(true) - $starttime, 4); Debug::message("\n{$sql}\n{$endtime}ms\n", false); } DB::$lastQuery = $handle; if (!$handle && $errorLevel) { $msg = $this->dbConn->errorInfo(); $this->databaseError("Couldn't run query: {$sql} | " . $msg[2], $errorLevel); } return new SQLitePDOQuery($this, $handle); }
public function getNestedController() { if ($this->urlParams['URLSegment']) { $SQL_URLSegment = Convert::raw2sql($this->urlParams['URLSegment']); if (Translatable::is_enabled()) { $child = Translatable::get_one("SiteTree", "URLSegment = '{$SQL_URLSegment}'"); } else { $child = DataObject::get_one("SiteTree", "URLSegment = '{$SQL_URLSegment}'"); } if (!$child) { $child = $this->get404Page(); } if ($child) { if (isset($_REQUEST['debug'])) { Debug::message("Using record #{$child->ID} of type {$child->class} with URL {$this->urlParams['URLSegment']}"); } $controllerClass = "{$child->class}_Controller"; if ($this->urlParams['Action'] && ClassInfo::exists($controllerClass . '_' . $this->urlParams['Action'])) { $controllerClass = $controllerClass . '_' . $this->urlParams['Action']; } if (ClassInfo::exists($controllerClass)) { $controller = new $controllerClass($child); } else { $controller = $child; } $controller->setURLParams($this->urlParams); return $controller; } else { die("The requested page couldn't be found."); } } else { user_error("ModelAsController not geting a URLSegment. It looks like the site isn't redirecting to home", E_USER_ERROR); } }
public function run($request) { // Are there members with a clear text password? $posts = DataObject::get("BlogEntry"); $count = 0; $commentCount = 0; foreach ($posts as $post) { // Delete comments if (class_exists('Comments')) { $comments = $post->Comments(); foreach ($comments as $comment) { $comment->Delete(); $commentCount++; } } $count++; $post->deleteFromStage('Live'); $post->delete(); } if ($count) { Debug::message("Deleted {$count} posts"); } else { Debug::message("No posts deleted"); } if ($commentCount) { Debug::message("Deleted {$commentCount} comments"); } }
function updateInfo($percent, $infoText, $debug = true) { global $command_line; if ($debug) { Debug::message($infoText, Debug::WARNING); } $percentageText = ($percent == 1)? '100': sprintf('%2.0f', $percent * 100); if (isset($command_line) and $command_line) { if ($percent < 0) { $percentageText = ' * '; } else { $percentageText .= '%'; } echo $percentageText, ' ', $infoText, "\n"; } else { echo '<script>'; if ($percent >= 0) { echo 'document.getElementById("progress-bar").style="width:' . ($percent * 100) . '%;";', "\n", 'document.getElementById("progress-bar").innerHTML ="' . $percentageText . '%";', "\n"; } if ($percent == 1) { echo 'document.getElementById("progress-bar").className = "progress-bar progress-bar-striped";'; } echo 'document.getElementById("progressbar-info").innerHTML="' . addslashes($infoText) . '";</script>'; } // This is for the buffer achieve the minimum size in order to flush data // echo str_repeat(' ', 1024 * 64); // Send output to browser immediately flush(); }
/** * 静态方法 启用框架的入口方法 */ public static function run() { self::debug(); //启用Debug模块 self::pathinfo(); //启用pathinfo self::initfile(); //检测并初始化系统 $controler_src = C('APP_PATH') . '/Action/' . $_GET['m'] . 'Action.class.php'; $runfile = C('RUN_PATH') . '/Action/' . $_GET['m'] . 'Action.class.php'; if (file_exists($controler_src)) { self::touch($runfile, strip_whitespace(file_get_contents($controler_src)), C('DEBUG')); $m = $_GET['m'] . 'Action'; $tmp = new $m(); Debug::addmsg("当前访问的控制器类: {$controler_src}"); method_exists($tmp, 'init') ? $tmp->init() : ''; method_exists($tmp, $_GET['a']) ? $tmp->{$_GET}['a']() : Debug::addmsg('<font color="red">当前访问的控制器类: ' . $controler_src . ' 不存在 ' . $_GET['a'] . ' 操作</font>'); } else { Debug::addmsg("<font color='red'>当前访问的控制器类: {$controler_src} 不存在!</font>"); } if (C('DEBUG')) { //DEBGU检测输出 Debug::message(); } }
/** * * @param string $sql * @param integer $errorLevel * @return SS_Query */ public function query($sql, $errorLevel = E_USER_ERROR) { $query = parent::query($sql, $errorLevel); if (isset($_REQUEST['showqueries']) && Director::isDev()) { $count = 1 + (int) Config::inst()->get('MySQLDebuggableDatabase', 'queries_count'); Config::inst()->update('MySQLDebuggableDatabase', 'queries_count', $count); Debug::message(PHP_EOL . 'Query Counts: ' . $count . PHP_EOL, false); } return $query; }
/** * Output a message * * @param string $message * @param int $verbosity Verbosity required to display this message (1 is default) */ public function message($message, $verbosity = 1) { if ($this->quiet) { return; } if ($this->verbosity >= 0 && $this->verbosity < $verbosity) { return; } Debug::message(date('Y-m-d H:i:s') . ': ' . $message, false); }
public function run($request) { $result = $this->validateConfig(); if ($result->valid()) { Debug::message("Fluent config is valid!", false); } else { Debug::message(sprintf("Fluent config invalid: %d errors found!", count($result->messageList())), false); foreach ($result->messageList() as $message) { Debug::message($message, false); } } }
public function transform($item, $parentObject, $duplicateStrategy) { if (Director::is_cli()) { Debug::message("Parent: #{$parentObject->ID}, {$parentObject->Title}"); Debug::message($item->AbsoluteURL); } // Sleep for 100ms to reduce load on the remote server usleep(100 * 1000); // Extract content from the page $contentFields = $this->getContentFieldsAndSelectors($item); // Default value for Title if (empty($contentFields['Title'])) { $contentFields['Title'] = array('content' => $item->Name); } // Default value for URL segment if (empty($contentFields['URLSegment'])) { $urlSegment = str_replace('/', '', $item->Name); $urlSegment = preg_replace('/\\.[^.]*$/', '', $urlSegment); $urlSegment = str_replace('.', '-', $item->Name); $contentFields['URLSegment'] = array('content' => $urlSegment); } $schema = $item->getSource()->getSchemaForURL($item->AbsoluteURL); $pageType = $schema->DataType; if (!$pageType) { throw new Exception('Pagetype for migration schema is empty!'); } // Create a page with the appropriate fields $page = new $pageType(array()); $existingPage = SiteTree::get_by_link($item->getExternalId()); if ($existingPage && $duplicateStrategy === 'Overwrite') { if (get_class($existingPage) !== $pageType) { $existingPage->ClassName = $pageType; $existingPage->write(); } if ($existingPage) { $page = $existingPage; } } $page->StaticSiteContentSourceID = $item->getSource()->ID; $page->StaticSiteURL = $item->AbsoluteURL; $page->ParentID = $parentObject ? $parentObject->ID : 0; foreach ($contentFields as $k => $v) { $page->{$k} = $v['content']; } $page->write(); if (Director::is_cli()) { Debug::message("#{$page->Title}"); Debug::message("#{$page->ID} child of #{$page->ID}"); } return new TransformResult($page, $item->stageChildren()); }
function run($request) { if ($this->isFreeToLock()) { if ($this->getLock()) { //try to get the lock, but do nothing if someone else is quicker and gets it first //do stuff $this->releaseLock(); } else { Debug::message('Aborting because another process acquired lock before this process could.', false); } } else { Debug::message('Aborting because of existing lock.', false); } }
/** * This is the main method to build the master string tables with the original strings. * It will search for existent modules that use the i18n feature, parse the _t() calls * and write the resultant files in the lang folder of each module. * * @uses DataObject->collectI18nStatics() * * @param SS_HTTPRequest $request */ public function run($request) { increase_time_limit_to(); $collector = i18nTextCollector::create($request->getVar('locale')); $merge = $this->getIsMerge($request); // Custom writer $writerName = $request->getVar('writer'); if ($writerName) { $writer = Injector::inst()->get($writerName); $collector->setWriter($writer); } // Get restrictions $restrictModules = $request->getVar('module') ? explode(',', $request->getVar('module')) : null; $collector->run($restrictModules, $merge); Debug::message(__CLASS__ . " completed!", false); }
function updateInfo($percent, $infoText, $debug = true) { if ($debug) { Debug::message($infoText, Debug::WARNING); } echo '<script language="javascript">'; if ($percent >= 0) { echo 'document.getElementById("progressbar-inner").style="width:' . $percent * 100 . '%;";'; } echo 'document.getElementById("progressbar-info").innerHTML="' . addslashes($infoText) . '";</script> '; // This is for the buffer achieve the minimum size in order to flush data // echo str_repeat(' ', 1024 * 64); // Send output to browser immediately flush(); }
public function getNestedController() { if($this->urlParams['URLSegment']) { $SQL_URLSegment = Convert::raw2sql($this->urlParams['URLSegment']); $child = SiteTree::get_by_url($SQL_URLSegment); if(!$child) { if($child = $this->findOldPage($SQL_URLSegment)) { $url = Controller::join_links( Director::baseURL(), $child->URLSegment, $this->urlParams['Action'], $this->urlParams['ID'], $this->urlParams['OtherID'] ); $response = new HTTPResponse(); $response->redirect($url, 301); return $response; } $child = $this->get404Page(); } if($child) { if(isset($_REQUEST['debug'])) Debug::message("Using record #$child->ID of type $child->class with URL {$this->urlParams['URLSegment']}"); $controllerClass = "{$child->class}_Controller"; if($this->urlParams['Action'] && ClassInfo::exists($controllerClass.'_'.$this->urlParams['Action'])) { $controllerClass = $controllerClass.'_'.$this->urlParams['Action']; } if(ClassInfo::exists($controllerClass)) { $controller = new $controllerClass($child); } else { $controller = $child; } return $controller; } else { return new HTTPResponse("The requested page couldn't be found.",404); } } else { user_error("ModelAsController not geting a URLSegment. It looks like the site isn't redirecting to home", E_USER_ERROR); } }
public function init() { parent::init(); $canAccess = Director::isDev() || Director::is_cli() || Permission::check("ADMIN"); if (!$canAccess) { return Security::permissionFailure($this); } if (!self::$default_reporter) { self::set_reporter(Director::is_cli() ? 'CliDebugView' : 'DebugView'); } if (!PhpUnitWrapper::has_php_unit()) { die("Please install PHPUnit using pear"); } if (!isset($_GET['flush']) || !$_GET['flush']) { Debug::message("WARNING: Manifest not flushed. " . "Add flush=1 as an argument to discover new classes or files.\n", false); } }
/** * Registers all cached routes with silverstripe */ public function RegisterRoutes() { $cachePath = $this->getCacheFilePath(); if (!file_exists($cachePath)) { return Debug::message('DateLink route cache file could not be found. This can be generated by using /dev/build'); } $document = new DOMDocument(); $document->load($cachePath); foreach ($document->getElementsByTagName('route') as $route) { $link = $route->getElementsByTagName('link')->item(0)->nodeValue; $parentID = $route->getElementsByTagName('page_id')->item(0)->nodeValue; $years = $route->getElementsByTagName('year'); foreach ($years as $year) { $this->registerRoute($link, $parentID, $year->nodeValue); } } }
function handleAction($request) { // This method can't be called without ajax. if (!Director::is_ajax()) { Director::redirectBack(); return; } $actions = Object::get_static($this->class, 'batch_actions'); $actionClass = $actions[$request->param('BatchAction')]; $actionHandler = new $actionClass(); // Sanitise ID list and query the database for apges $ids = split(' *, *', trim($request->requestVar('csvIDs'))); foreach ($ids as $k => $v) { if (!is_numeric($v)) { unset($ids[$k]); } } if ($ids) { $pages = DataObject::get('SiteTree', "`SiteTree`.ID IN (" . implode(", ", $ids) . ")"); // If we didn't query all the pages, then find the rest on the live site if (!$pages || $pages->Count() < sizeof($ids)) { foreach ($ids as $id) { $idsFromLive[$id] = true; } if ($pages) { foreach ($pages as $page) { unset($idsFromLive[$page->ID]); } } $idsFromLive = array_keys($idsFromLive); Debug::message("`SiteTree`.ID IN (" . implode(", ", $idsFromLive) . ")"); $livePages = Versioned::get_by_stage('SiteTree', 'Live', "`SiteTree`.ID IN (" . implode(", ", $idsFromLive) . ")"); if ($pages) { $pages->merge($livePages); } else { $pages = $livePages; } } } else { $pages = new DataObjectSet(); } return $actionHandler->run($pages); }
/** * Define custom methods for this object. Called once per class. * Implements failover and cached methods. */ function defineMethods() { // Set up failover if ($this->failover) { $this->addMethodsFrom('failover'); } if (isset($_GET['debugfailover'])) { Debug::message("{$this->class} / {$this->failover}"); } // Set up cached methods $methodNames = $this->allMethodNames(); foreach ($methodNames as $methodName) { if ($methodName[0] == "_") { $trimmedName = substr($methodName, 1); $this->createMethod($trimmedName, "return \$obj->cachedCall('{$methodName}', '{$trimmedName}', \$args);"); } } parent::defineMethods(); }
public function run($request) { // Migrate old ImageGalleryImage class to use Image object DB::query('UPDATE "File" SET "File"."ClassName" = \'Image\' WHERE "File"."ClassName" = \'ImageGalleryImage\''); // check that galleries exist $galleries = DataObject::get('MagnificGalleryPage'); if (!$galleries || $galleries->count() === 0) { user_error('No image gallery pages found', E_USER_ERROR); return; } // check each gallery $count = 0; Debug::message("Importing, please wait...."); foreach ($galleries as $gallery) { $albums = $gallery->Albums(); if (!$albums || $albums->count() === 0) { Debug::message("Warning: no album found in gallery '{$gallery->Title}'"); continue; } // Check each album in each gallery foreach ($albums as $album) { $album->write(); // Ensures folder, URLSegment, etc are all prepared $folder = $album->Folder(); $existing = $album->GalleryItems()->column('ImageID'); foreach ($folder->Children() as $image) { if (in_array($image->ID, $existing)) { continue; } //Add to the album $item = MagnificGalleryItem::create(); $item->GalleryPageID = $gallery->ID; $item->AlbumID = $album->ID; $item->ImageID = $image->ID; $item->write(); $count++; } } } Debug::message("Imported {$count} images into galleries"); }
/** * Replace the existing filter (ON clause) on a join */ public function setJoinFilter($tableAlias, $filter) { if(is_string($this->from[$tableAlias])) {Debug::message($tableAlias); Debug::dump($this->from);} $this->from[$tableAlias]['filter'] = array($filter); }
/** * Allows the display and benchmarking of queries as they are being run * * @param string $sql Query to run, and single parameter to callback * @param callable $callback Callback to execute code * @return mixed Result of query */ protected function benchmarkQuery($sql, $callback) { if (isset($_REQUEST['showqueries']) && Director::isDev()) { $starttime = microtime(true); $result = $callback($sql); $endtime = round(microtime(true) - $starttime, 4); Debug::message("\n{$sql}\n{$endtime}s\n", false); return $result; } else { return $callback($sql); } }
/** * Handles URL requests. * * - ViewableData::handleRequest() iterates through each rule in {@link self::$url_handlers}. * - If the rule matches, the named method will be called. * - If there is still more URL to be processed, then handleRequest() * is called on the object that that method returns. * * Once all of the URL has been processed, the final result is returned. * However, if the final result is an array, this * array is interpreted as being additional template data to customise the * 2nd to last result with, rather than an object * in its own right. This is most frequently used when a Controller's * action will return an array of data with which to * customise the controller. * * @param $request The {@link SS_HTTPRequest} object that is reponsible for distributing URL parsing * @uses SS_HTTPRequest * @uses SS_HTTPRequest->match() * @return SS_HTTPResponse|RequestHandler|string|array */ function handleRequest(SS_HTTPRequest $request, DataModel $model) { // $handlerClass is used to step up the class hierarchy to implement url_handlers inheritance $handlerClass = ($this->class) ? $this->class : get_class($this); if($this->brokenOnConstruct) { user_error("parent::__construct() needs to be called on {$handlerClass}::__construct()", E_USER_WARNING); } $this->request = $request; $this->setModel($model); // We stop after RequestHandler; in other words, at ViewableData while($handlerClass && $handlerClass != 'ViewableData') { $urlHandlers = Config::inst()->get($handlerClass, 'url_handlers', Config::FIRST_SET); if($urlHandlers) foreach($urlHandlers as $rule => $action) { if(isset($_REQUEST['debug_request'])) Debug::message("Testing '$rule' with '" . $request->remaining() . "' on $this->class"); if($params = $request->match($rule, true)) { // Backwards compatible setting of url parameters, please use SS_HTTPRequest->latestParam() instead //Director::setUrlParams($request->latestParams()); if(isset($_REQUEST['debug_request'])) { Debug::message("Rule '$rule' matched to action '$action' on $this->class. Latest request params: " . var_export($request->latestParams(), true)); } // Actions can reference URL parameters, eg, '$Action/$ID/$OtherID' => '$Action', if($action[0] == '$') $action = $params[substr($action,1)]; if($this->checkAccessAction($action)) { if(!$action) { if(isset($_REQUEST['debug_request'])) Debug::message("Action not set; using default action method name 'index'"); $action = "index"; } else if(!is_string($action)) { user_error("Non-string method name: " . var_export($action, true), E_USER_ERROR); } try { if(!$this->hasMethod($action)) { return $this->httpError(404, "Action '$action' isn't available on class " . get_class($this) . "."); } $result = $this->$action($request); } catch(SS_HTTPResponse_Exception $responseException) { $result = $responseException->getResponse(); } } else { return $this->httpError(403, "Action '$action' isn't allowed on class " . get_class($this) . "."); } if($result instanceof SS_HTTPResponse && $result->isError()) { if(isset($_REQUEST['debug_request'])) Debug::message("Rule resulted in HTTP error; breaking"); return $result; } // If we return a RequestHandler, call handleRequest() on that, even if there is no more URL to parse. // It might have its own handler. However, we only do this if we haven't just parsed an empty rule ourselves, // to prevent infinite loops. Also prevent further handling of controller actions which return themselves // to avoid infinite loops. if($this !== $result && !$request->isEmptyPattern($rule) && is_object($result) && $result instanceof RequestHandler) { $returnValue = $result->handleRequest($request, $model); // Array results can be used to handle if(is_array($returnValue)) $returnValue = $this->customise($returnValue); return $returnValue; // If we return some other data, and all the URL is parsed, then return that } else if($request->allParsed()) { return $result; // But if we have more content on the URL and we don't know what to do with it, return an error. } else { return $this->httpError(404, "I can't handle sub-URLs of a $this->class object."); } return $this; } } $handlerClass = get_parent_class($handlerClass); } // If nothing matches, return this object return $this; }
/** * Allows the display and benchmarking of queries as they are being run * * @param string $sql Query to run, and single parameter to callback * @param callable $callback Callback to execute code * @param array $parameters Parameters to display * @return mixed Result of query */ protected function benchmarkQuery($sql, $callback, $parameters = null) { if (isset($_REQUEST['showqueries']) && Director::isDev()) { $starttime = microtime(true); $result = $callback($sql); $endtime = round(microtime(true) - $starttime, 4); $message = $sql; if ($parameters) { $message .= "\nparams: \"" . implode('", "', $parameters) . '"'; } Debug::message("\n{$message}\n{$endtime}s\n", false); return $result; } else { return $callback($sql); } }
/** * Add methods from the {@link ViewableData::$failover} object, as well as wrapping any methods prefixed with an * underscore into a {@link ViewableData::cachedCall()}. * * @throws LogicException */ public function defineMethods() { if ($this->failover && !is_object($this->failover)) { throw new LogicException("ViewableData::\$failover set to a non-object"); } if ($this->failover) { $this->addMethodsFrom('failover'); if (isset($_REQUEST['debugfailover'])) { Debug::message("{$this->class} created with a failover class of {$this->failover->class}"); } } parent::defineMethods(); }
/** * Writes all changes to this object to the database. * - It will insert a record whenever ID isn't set, otherwise update. * - All relevant tables will be updated. * - $this->onBeforeWrite() gets called beforehand. * - Extensions such as Versioned will ammend the database-write to ensure that a version is saved. * * @uses DataExtension->augmentWrite() * * @param boolean $showDebug Show debugging information * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists * @param boolean $forceWrite Write to database even if there are no changes * @param boolean $writeComponents Call write() on all associated component instances which were previously * retrieved through {@link getComponent()}, {@link getComponents()} or * {@link getManyManyComponents()} (Default: false) * @return int The ID of the record * @throws ValidationException Exception that can be caught and handled by the calling function */ public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) { $now = SS_Datetime::now()->Rfc2822(); // Execute pre-write tasks $this->preWrite(); // Check if we are doing an update or an insert $isNewRecord = !$this->isInDB() || $forceInsert; // Check changes exist, abort if there are none $hasChanges = $this->updateChanges($forceInsert); if ($hasChanges || $forceWrite || $isNewRecord) { // New records have their insert into the base data table done first, so that they can pass the // generated primary key on to the rest of the manipulation $baseTable = ClassInfo::baseDataClass($this->class); $this->writeBaseRecord($baseTable, $now); // Write the DB manipulation for all changed fields $this->writeManipulation($baseTable, $now, $isNewRecord); // If there's any relations that couldn't be saved before, save them now (we have an ID here) $this->writeRelations(); $this->onAfterWrite(); $this->changed = array(); } else { if ($showDebug) { Debug::message("no changes for DataObject"); } // Used by DODs to clean up after themselves, eg, Versioned $this->invokeWithExtensions('onAfterSkippedWrite'); } // Ensure Created and LastEdited are populated if (!isset($this->record['Created'])) { $this->record['Created'] = $now; } $this->record['LastEdited'] = $now; // Write relations as necessary if ($writeComponents) { $this->writeComponents(true); } // Clears the cache for this object so get_one returns the correct object. $this->flushCache(); return $this->record['ID']; }
/** * Handles HTTP requests. * * If you are going to overload handleRequest, make sure that you start the method with $this->pushCurrent() * and end the method with $this->popCurrent(). Failure to do this will create weird session errors. * * @param $request The {@link HTTPRequest} object that is responsible for distributing request parsing. */ function handleRequest(HTTPRequest $request) { if(!$request) user_error("Controller::handleRequest() not passed a request!", E_USER_ERROR); $this->pushCurrent(); $this->urlParams = $request->allParams(); $this->request = $request; $this->response = new HTTPResponse(); // 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; } $body = parent::handleRequest($request); if($body instanceof HTTPResponse) { if(isset($_REQUEST['debug_request'])) Debug::message("Request handler returned HTTPResponse object to $this->class controller; returning it without modification."); $this->response = $body; } else { if(is_object($body)) { if(isset($_REQUEST['debug_request'])) Debug::message("Request handler $body->class object to $this->class controller;, rendering with template returned by $body->class::getViewer()"); $body = $body->getViewer($request->latestParam('Action'))->process($body); } $this->response->setBody($body); } ContentNegotiator::process($this->response); HTTP::add_cache_headers($this->response); $this->popCurrent(); return $this->response; }
/** * @param SS_HTTPRequest $request * @return array */ protected function findAction($request) { $handlerClass = $this->class ? $this->class : get_class($this); // We stop after RequestHandler; in other words, at ViewableData while ($handlerClass && $handlerClass != 'ViewableData') { $urlHandlers = Config::inst()->get($handlerClass, 'url_handlers', Config::UNINHERITED); if ($urlHandlers) { foreach ($urlHandlers as $rule => $action) { if (isset($_REQUEST['debug_request'])) { Debug::message("Testing '{$rule}' with '" . $request->remaining() . "' on {$this->class}"); } if ($request->match($rule, true)) { if (isset($_REQUEST['debug_request'])) { Debug::message("Rule '{$rule}' matched to action '{$action}' on {$this->class}. " . "Latest request params: " . var_export($request->latestParams(), true)); } return array('rule' => $rule, 'action' => $action); } } } $handlerClass = get_parent_class($handlerClass); } }
/** * @return ContentController * @throws Exception If URLSegment not passed in as a request parameter. */ public function getNestedController() { $request = $this->getRequest(); if (!($URLSegment = $request->param('URLSegment'))) { throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.'); } // Find page by link, regardless of current locale settings if (class_exists('Translatable')) { Translatable::disable_locale_filter(); } // Select child page $conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment)); if (SiteTree::config()->nested_urls) { $conditions[] = array('"SiteTree"."ParentID"' => 0); } $sitetree = DataObject::get_one('SiteTree', $conditions); // Check translation module // @todo Refactor out module specific code if (class_exists('Translatable')) { Translatable::enable_locale_filter(); } if (!$sitetree) { $response = ErrorPage::response_for(404); $this->httpError(404, $response ? $response : 'The requested page could not be found.'); } // Enforce current locale setting to the loaded SiteTree object if (class_exists('Translatable') && $sitetree->Locale) { Translatable::set_current_locale($sitetree->Locale); } if (isset($_REQUEST['debug'])) { Debug::message("Using record #{$sitetree->ID} of type {$sitetree->class} with link {$sitetree->Link()}"); } return self::controller_for($sitetree, $this->getRequest()->param('Action')); }
/** * @todo This should really be taken care of by the testing framework */ protected function debugMessage($msg) { if (class_exists('SapphireTest', false) && !SapphireTest::is_running_test()) { Debug::message($msg); } }
public function requireDefaultRecords() { foreach (StaticSiteContentSource::get() as $source) { if (!$source->Schemas()->count()) { Debug::message("Making a schema for {$source->ID}"); $defaultSchema = new StaticSiteContentSource_ImportSchema(); $defaultSchema->Order = 1000000; $defaultSchema->AppliesTo = ".*"; $defaultSchema->DataType = "Page"; $defaultSchema->ContentSourceID = $source->ID; $defaultSchema->write(); foreach (StaticSiteContentSource_ImportRule::get()->filter(array('SchemaID' => 0)) as $rule) { $rule->SchemaID = $defaultSchema->ID; $rule->write(); } } } }
/** * Pass the SilverStripe template to be used. * * @param string|array $templateList * If passed as a string with .ss extension, used as the "main" template */ public function __construct($templateList) { global $_TEMPLATE_MANIFEST; // flush template manifest cache if requested if (isset($_GET['flush']) && $_GET['flush'] == 'all') { self::flush_template_cache(); } if(substr((string) $templateList,-3) == '.ss') { $this->chosenTemplates['main'] = $templateList; } else { if(!is_array($templateList)) $templateList = array($templateList); if(isset($_GET['debug_request'])) Debug::message("Selecting templates from the following list: " . implode(", ", $templateList)); foreach($templateList as $template) { // if passed as a partial directory (e.g. "Layout/Page"), split into folder and template components if(strpos($template,'/') !== false) list($templateFolder, $template) = explode('/', $template, 2); else $templateFolder = null; // Use the theme template if available if(self::$current_theme && isset($_TEMPLATE_MANIFEST[$template]['themes'][self::$current_theme])) { $this->chosenTemplates = array_merge( $_TEMPLATE_MANIFEST[$template]['themes'][self::$current_theme], $this->chosenTemplates ); if(isset($_GET['debug_request'])) Debug::message("Found template '$template' from main theme '" . self::$current_theme . "': " . var_export($_TEMPLATE_MANIFEST[$template]['themes'][self::$current_theme], true)); } // Fall back to unthemed base templates if(isset($_TEMPLATE_MANIFEST[$template]) && (array_keys($_TEMPLATE_MANIFEST[$template]) != array('themes'))) { $this->chosenTemplates = array_merge( $_TEMPLATE_MANIFEST[$template], $this->chosenTemplates ); if(isset($_GET['debug_request'])) Debug::message("Found template '$template' from main template archive, containing the following items: " . var_export($_TEMPLATE_MANIFEST[$template], true)); unset($this->chosenTemplates['themes']); } if($templateFolder) { $this->chosenTemplates['main'] = $this->chosenTemplates[$templateFolder]; unset($this->chosenTemplates[$templateFolder]); } } if(isset($_GET['debug_request'])) Debug::message("Final template selections made: " . var_export($this->chosenTemplates, true)); } if(!$this->chosenTemplates) user_error("None of these templates can be found: ". implode(".ss, ", $templateList) . ".ss", E_USER_WARNING); parent::__construct(); }