Exemplo n.º 1
0
 /**
  * Listens to the response.filter_content event.
  *
  * @param  sfEvent $event   The sfEvent instance
  * @param  string  $context The response content
  *
  * @return string  The filtered response content
  */
 public function filterResponseContent(sfEvent $event, $content)
 {
     if (!sfConfig::get('sf_web_debug')) {
         return $content;
     }
     // log timers information
     $messages = array();
     foreach (sfTimerManager::getTimers() as $name => $timer) {
         $messages[] = sprintf('%s %.2f ms (%d)', $name, $timer->getElapsedTime() * 1000, $timer->getCalls());
     }
     $this->dispatcher->notify(new sfEvent($this, 'application.log', $messages));
     // don't add debug toolbar:
     // * for XHR requests
     // * if 304
     // * if not rendering to the client
     // * if HTTP headers only
     $response = $event->getSubject();
     if (!$this->context->has('request') || !$this->context->has('response') || !$this->context->has('controller') || $this->context->getRequest()->isXmlHttpRequest() || strpos($response->getContentType(), 'html') === false || $response->getStatusCode() == 304 || $this->context->getController()->getRenderMode() != sfView::RENDER_CLIENT || $response->isHeaderOnly()) {
         return $content;
     }
     // add needed assets for the web debug toolbar
     $root = $this->context->getRequest()->getRelativeUrlRoot();
     $assets = sprintf('
   <script type="text/javascript" src="%s"></script>
   <link rel="stylesheet" type="text/css" media="screen" href="%s" />', $root . sfConfig::get('sf_web_debug_web_dir') . '/js/main.js', $root . sfConfig::get('sf_web_debug_web_dir') . '/css/main.css');
     $content = str_ireplace('</head>', $assets . '</head>', $content);
     // add web debug information to response content
     $webDebugContent = $this->webDebug->getResults();
     $count = 0;
     $content = str_ireplace('</body>', $webDebugContent . '</body>', $content, $count);
     if (!$count) {
         $content .= $webDebugContent;
     }
     return $content;
 }
 /**
  * Executes the filter
  */
 public function execute($filterChain)
 {
     $filterChain->execute();
     $response = $this->getContext()->getResponse();
     $request = $this->getContext()->getRequest();
     $controller = $this->getContext()->getController();
     // don't highlight:
     // * for XHR requests
     // * if 304
     // * if not rendering to the client
     // * if HTTP headers only
     if ($request->isXmlHttpRequest() || strpos($response->getContentType(), 'html') === false || $response->getStatusCode() == 304 || $controller->getRenderMode() != sfView::RENDER_CLIENT || $response->isHeaderOnly()) {
         return;
     }
     $timer = sfTimerManager::getTimer('Highlight Filter');
     try {
         $this->highlight();
     } catch (sfLuceneHighlighterException $e) {
         $timer->addTime();
         $this->getContext()->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array($e->getMessage(), 'priority' => sfLogger::WARNING)));
         if ($e instanceof sfLuceneHighlighterXMLException) {
             $errors = $e->getProblems();
             $errors['priority'] = sfLogger::ERR;
             $this->getContext()->getEventDispatcher()->notify(new sfEvent($this, 'application.log', $errors));
         }
     } catch (Exception $e) {
         $timer->addTime();
         throw $e;
     }
     $timer->addTime();
 }
 protected function execute($arguments = array(), $options = array())
 {
     if (!$this->safeToRun()) {
         print "Process already running!\n";
         die;
     }
     $timer = sfTimerManager::getTimer('execute');
     $databaseManager = new sfDatabaseManager($this->configuration);
     $databaseManager->initialize($this->configuration);
     //set up index
     $index = EntityTable::getLuceneIndex();
     //delete deleted entities
     $q = LsDoctrineQuery::create()->from('Entity e')->where('e.is_deleted = ?', true)->setHydrationMode(Doctrine::HYDRATE_ARRAY);
     foreach ($q->execute() as $entity) {
         if ($hits = $index->find('key:' . $entity['id'])) {
             if ($options['debug_mode']) {
                 printf("Deleting index for Entity %s\n", $entity['id']);
             }
             foreach ($hits as $hit) {
                 $index->delete($hit->id);
             }
         }
     }
     printf("Memory used: %s\n", LsNumber::makeBytesReadable(memory_get_usage()));
     printf("Index size: %s\n", $index->count());
     $timer->addTime();
     printf("Run time: %s\n", $timer->getElapsedTime());
     sfTimerManager::clearTimers();
 }
Exemplo n.º 4
0
 /**
  * Renders the presentation.
  *
  * @return string Current template content
  */
 public function render()
 {
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('Partial "%s/%s"', $this->moduleName, $this->actionName));
     }
     if (sfConfig::get('sf_cache')) {
         $viewCache = $this->context->getViewCacheManager();
         $viewCache->registerConfiguration($this->moduleName);
         $cacheKey = $viewCache->computeCacheKey($this->partialVars);
         if ($retval = $viewCache->getPartialCache($this->moduleName, $this->actionName, $cacheKey)) {
             return $retval;
         } else {
             $mainResponse = $this->context->getResponse();
             $responseClass = get_class($mainResponse);
             $this->context->setResponse($response = new $responseClass($this->context->getEventDispatcher(), $mainResponse->getOptions()));
         }
     }
     // execute pre-render check
     $this->preRenderCheck();
     $this->getAttributeHolder()->set('sf_type', 'partial');
     // render template
     $retval = $this->renderFile($this->getDirectory() . '/' . $this->getTemplate());
     if (sfConfig::get('sf_cache')) {
         $retval = $viewCache->setPartialCache($this->moduleName, $this->actionName, $cacheKey, $retval);
         $this->context->setResponse($mainResponse);
         $mainResponse->merge($response);
     }
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     return $retval;
 }
 public function execute($filterChain)
 {
     $filterChain->execute();
     $response = $this->getContext()->getResponse();
     $request = $this->getContext()->getRequest();
     $controller = $this->getContext()->getController();
     // don't highlight:
     // * for XHR requests
     // * if 304
     // * if not rendering to the client
     // * if HTTP headers only
     if ($request->isXmlHttpRequest() || strpos($response->getContentType(), 'html') === false || $response->getStatusCode() == 304 || $controller->getRenderMode() != sfView::RENDER_CLIENT || $response->isHeaderOnly()) {
         return;
     }
     $timer = sfTimerManager::getTimer('Highlight Filter');
     try {
         if (!$this->highlight()) {
             $this->removeNotice();
         }
     } catch (sfSolrHighlighterException $e) {
         sfLogger::getInstance()->err('{sfSolrHighlightFilter} silently ignoring exception: ' . $e->getMessage());
         if ($this->testMode) {
             $timer->addTime();
             throw $e;
         }
     } catch (Exception $e) {
         $timer->addTime();
         throw $e;
     }
     $timer->addTime();
 }
Exemplo n.º 6
0
 public function getPanelContent()
 {
     if (sfTimerManager::getTimers()) {
         $totalTime = $this->getTotalTime();
         $panel = '<table class="sfWebDebugLogs" style="width: 300px"><tr><th>type</th><th>calls</th><th>time (ms)</th><th>time (%)</th></tr>';
         foreach (sfTimerManager::getTimers() as $name => $timer) {
             $panel .= sprintf('<tr><td class="sfWebDebugLogType">%s</td><td class="sfWebDebugLogNumber" style="text-align: right">%d</td><td style="text-align: right">%.2f</td><td style="text-align: right">%d</td></tr>', $name, $timer->getCalls(), $timer->getElapsedTime() * 1000, $totalTime ? $timer->getElapsedTime() * 1000 * 100 / $totalTime : 'N/A');
         }
         $panel .= '</table>';
         return $panel;
     }
 }
Exemplo n.º 7
0
 /**
  * Listens to the routing.load_configuration event. Finds & compiles LESS files to CSS
  *
  * @param   sfEvent $event  an sfEvent instance
  */
 public static function findAndCompile(sfEvent $event)
 {
     // Start compilation timer for debug info
     $timer = sfTimerManager::getTimer('Less compilation');
     // Create new helper object & compile LESS stylesheets with it
     $less = new sfLESS();
     foreach ($less->findLessFiles() as $lessFile) {
         $less->compile($lessFile);
     }
     // Stop timer
     $timer->addTime();
 }
 /**
  * Compile the source files and fix permissions
  *
  * @param string $in      Input directory containing sass files
  * @param string $out     Output directory where to write the css files
  * @param string $cache   Cache folder (null if cache is not used)
  * @param array  $params  Sass compiler parameters
  */
 public function compile($in, $out, $cache, array $params = array())
 {
     $timer = sfTimerManager::getTimer('Sass compilation');
     $this->createFolderIfNeeded($out);
     if (!empty($cache)) {
         $this->createFolderIfNeeded($cache);
     }
     $this->driver->compile($in, $out, $params);
     $this->fixPermissions($out);
     if (!empty($cache)) {
         $this->fixPermissions($cache);
     }
     $timer->addTime();
 }
 /**
  * Renders the presentation.
  *
  * @return string Current template content
  */
 public function render()
 {
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('Partial "%s/%s"', $this->moduleName, $this->actionName));
     }
     if ($retval = $this->getCache()) {
         return $retval;
     } else {
         if ($this->checkCache) {
             $mainResponse = $this->context->getResponse();
             $responseClass = get_class($mainResponse);
             $this->context->setResponse($response = new $responseClass($this->context->getEventDispatcher(), array_merge($mainResponse->getOptions(), array('content_type' => $mainResponse->getContentType()))));
         }
     }
     try {
         // PHP FALLBACK
         try {
             // execute pre-render check
             $this->preRenderCheck();
         } catch (sfRenderException $e) {
             if (null === $this->template) {
                 throw new sfRenderException('A template has not been set.');
             }
             $view = new sfPartialView($this->context, $this->moduleName, $this->actionName, $this->viewName);
             return $view->render();
         } catch (Exception $e) {
             throw $e;
         }
         $this->getAttributeHolder()->set('sf_type', 'partial');
         // render template
         $retval = $this->renderFile($this->getDirectory(), $this->getTemplate());
     } catch (Exception $e) {
         if ($this->checkCache) {
             $this->context->setResponse($mainResponse);
             $mainResponse->merge($response);
         }
         throw $e;
     }
     if ($this->checkCache) {
         $retval = $this->viewCache->setPartialCache($this->moduleName, $this->actionName, $this->cacheKey, $retval);
         $this->context->setResponse($mainResponse);
         $mainResponse->merge($response);
     }
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     return $retval;
 }
 protected function execute($arguments = array(), $options = array())
 {
     if (!$this->safeToRun()) {
         print "Process already running!\n";
         die;
     }
     $timer = sfTimerManager::getTimer('execute');
     //get index and optimize
     $index = EntityTable::getLuceneIndex();
     $index->optimize();
     printf("Memory used: %s\n", LsNumber::makeBytesReadable(memory_get_usage()));
     printf("Index size: %s\n", $index->count());
     $timer->addTime();
     printf("Run time: %s\n", $timer->getElapsedTime());
     sfTimerManager::clearTimers();
 }
 public function getPanelContent()
 {
     $panel = array();
     $timers = sfTimerManager::getTimers();
     if (sfConfig::get('sf_debug') && $timers) {
         $totalTime = $this->getTotalTime();
         $timer_nb = 1;
         foreach ($timers as $name => $timer) {
             array_push($panel, array('number' => $timer_nb, 'name' => $name, 'calls' => $timer->getCalls(), 'time' => $timer->getElapsedTime() * 1000, 'percent' => $totalTime ? $timer->getElapsedTime() * 1000 * 100 / $totalTime : 'N/A'));
             $timer_nb++;
         }
         $panel['total'] = 'Total time: ' . $this->getTotalTime() . ' ms';
     } else {
         $panel['total'] = 'No info available';
     }
     return $panel;
 }
Exemplo n.º 12
0
 /**
  * Executes this filter.
  *
  * @param sfFilterChain $filterChain The filter chain
  *
  * @throws <b>sfInitializeException</b> If an error occurs during view initialization.
  * @throws <b>sfViewException</b>       If an error occurs while executing the view.
  */
 public function execute($filterChain)
 {
     // get the current action instance
     $actionInstance = $this->context->getController()->getActionStack()->getLastEntry()->getActionInstance();
     // execute the action, execute and render the view
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('Action "%s/%s"', $actionInstance->getModuleName(), $actionInstance->getActionName()));
         $viewName = $this->handleAction($filterChain, $actionInstance);
         $timer->addTime();
         $timer = sfTimerManager::getTimer(sprintf('View "%s" for "%s/%s"', $viewName, $actionInstance->getModuleName(), $actionInstance->getActionName()));
         $this->handleView($filterChain, $actionInstance, $viewName);
         $timer->addTime();
     } else {
         $viewName = $this->handleAction($filterChain, $actionInstance);
         $this->handleView($filterChain, $actionInstance, $viewName);
     }
 }
 /**
  * Renders the presentation.
  *
  * @param array Template attributes
  *
  * @return string Current template content
  */
 public function render($templateVars = array())
 {
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('Partial "%s/%s"', $this->moduleName, $this->actionName));
     }
     // execute pre-render check
     $this->preRenderCheck();
     // assigns some variables to the template
     $this->attributeHolder->add($this->getGlobalVars());
     $this->attributeHolder->add($templateVars);
     // render template
     $retval = $this->renderFile($this->getDirectory() . '/' . $this->getTemplate());
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     return $retval;
 }
 private function init()
 {
     if (sfContext::getInstance()->has('profiler')) {
         $timer = sfTimerManager::getTimer('afRead');
         // this time will be stopeed inside XmlParser constructor
     }
     $parser = new XmlParser();
     $this->type = $parser->getType();
     $this->layout = $parser->getLayout();
     if (method_exists($this->layout, 'beforeEnd')) {
         $this->layout->beforeEnd();
     }
     if (sfContext::getInstance()->has('profiler')) {
         $timer = sfTimerManager::getTimer('afRender');
         $timer->addTime();
         // this one closes afRender timer that was started inside XmlParser constructor
     }
 }
Exemplo n.º 15
0
 /**
  * Renders the presentation.
  *
  * @return string Current template content
  */
 public function render()
 {
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('Partial "%s/%s"', $this->moduleName, $this->actionName));
     }
     if ($retval = $this->getCache()) {
         if ($this->isFlavorPartial(ncFlavorFlavors::getModulePath($module_name) . '/templates', $this->getTemplate())) {
             $retval = $this->renderFile($this->getFlavorDirectory($this->getModuleName(), $this->getTemplate()) . '/' . $this->getTemplate());
         }
         return $retval;
     } else {
         if ($this->checkCache) {
             $mainResponse = $this->context->getResponse();
             $responseClass = get_class($mainResponse);
             $this->context->setResponse($response = new $responseClass($this->context->getEventDispatcher(), array_merge($mainResponse->getOptions(), array('content_type' => $mainResponse->getContentType()))));
         }
     }
     try {
         // execute pre-render check
         $this->preRenderCheck();
         $this->getAttributeHolder()->set('sf_type', 'partial');
         // render template
         $retval = $this->renderFile($this->getFlavorDirectory($this->getModuleName(), $this->getTemplate()) . '/' . $this->getTemplate());
     } catch (Exception $e) {
         if ($this->checkCache) {
             $this->context->setResponse($mainResponse);
             $mainResponse->merge($response);
         }
         throw $e;
     }
     if ($this->checkCache) {
         if ($this->isFlavorPartial(ncFlavorFlavors::getModulePath($module_name) . '/templates', $this->getTemplate())) {
             $retval = $this->renderFile($this->getFlavorDirectory($this->getModuleName(), $this->getTemplate()) . '/' . $this->getTemplate());
         } else {
             $retval = $this->viewCache->setPartialCache($this->moduleName, $this->actionName, $this->cacheKey, $retval);
         }
         $this->context->setResponse($mainResponse);
         $mainResponse->merge($response);
     }
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     return $retval;
 }
Exemplo n.º 16
0
 protected function sendTimers()
 {
     $timers = sfTimerManager::getTimers();
     $totalTime = $this->getTotalTime();
     $panel = array();
     $timer_nb = 1;
     foreach ($timers as $name => $timer) {
         array_push($panel, array('number' => $timer_nb, 'name' => $name, 'calls' => $timer->getCalls(), 'time' => $timer->getElapsedTime() * 1000, 'percent' => $totalTime ? $timer->getElapsedTime() * 1000 * 100 / $totalTime : 'N/A'));
         $timer_nb++;
     }
     if (count($panel)) {
         array_unshift($panel, array('', 'Type', 'Calls', 'Time(ms)', 'Time(%)'));
         $this->sfFire->table('Timers ' . $this->getTotalTime() . ' ms', $panel);
     } else {
         $this->sfFire->group('Timers ' . $this->getTotalTime() . ' ms');
         $this->sfFire->info('No info available');
         $this->sfFire->groupEnd();
     }
 }
Exemplo n.º 17
0
 /**
  * Renders the presentation.
  *
  * @return string Current template content
  */
 public function render()
 {
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('Partial "%s/%s"', $this->moduleName, $this->actionName));
     }
     if ($retval = $this->getCache()) {
         return $retval;
     }
     if ($this->checkCache) {
         $mainResponse = $this->context->getResponse();
         $responseClass = get_class($mainResponse);
         $response = new $responseClass($this->context->getEventDispatcher(), $mainResponse->getOptions());
         // the inner response has access to different properties, depending on whether it is marked as contextual in cache.yml
         if ($this->viewCache->isContextual($this->viewCache->getPartialUri($this->moduleName, $this->actionName, $this->cacheKey))) {
             $response->copyProperties($mainResponse);
         } else {
             $response->setContentType($mainResponse->getContentType());
         }
         $this->context->setResponse($response);
     }
     try {
         // execute pre-render check
         $this->preRenderCheck();
         $this->getAttributeHolder()->set('sf_type', 'partial');
         // render template
         $retval = $this->renderFile($this->getDirectory() . '/' . $this->getTemplate());
     } catch (Exception $e) {
         if ($this->checkCache) {
             $this->context->setResponse($mainResponse);
             $mainResponse->merge($response);
         }
         throw $e;
     }
     if ($this->checkCache) {
         $retval = $this->viewCache->setPartialCache($this->moduleName, $this->actionName, $this->cacheKey, $retval);
         $this->context->setResponse($mainResponse);
         $mainResponse->merge($response);
     }
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     return $retval;
 }
 protected function execute($arguments = array(), $options = array())
 {
     if (!$this->safeToRun()) {
         print "Process already running!\n";
         die;
     }
     $timer = sfTimerManager::getTimer('execute');
     $databaseManager = new sfDatabaseManager($this->configuration);
     $databaseManager->initialize($this->configuration);
     //get id of last-indexed entity
     $index = EntityTable::getLuceneIndex($options['index_file']);
     $index->setMergeFactor(200);
     $index->setMaxBufferedDocs(20);
     if ($count = $index->count()) {
         if (!($lastDoc = $index->getDocument($count - 1))) {
             throw new Exception("Can't find last document in index");
         }
         $maxEntityId = $lastDoc->key;
     } else {
         $maxEntityId = 0;
     }
     //find non-deleted entities with greater IDs
     $q = LsDoctrineQuery::create()->from('Entity e')->leftJoin('e.Alias a')->where('e.id > ? AND e.is_deleted = ?', array($maxEntityId, false))->andWhere('a.context IS NULL')->offset($options['offset'])->limit($options['limit'])->orderBy('e.id ASC');
     //index entities
     $optimize = 0;
     foreach ($q->fetchArray() as $entity) {
         if (EntityTable::updateLuceneIndex($entity, $index, $batchMode = true)) {
             if ($options['debug_mode']) {
                 printf("Indexed entity with ID %s\n", $entity['id']);
             }
         } else {
             if ($options['debug_mode']) {
                 printf("Skipped entity with ID %s\n", $entity['id']);
             }
         }
     }
     printf("Memory used: %s\n", LsNumber::makeBytesReadable(memory_get_usage()));
     printf("Index size: %s\n", $index->count());
     $timer->addTime();
     printf("Run time: %s\n", $timer->getElapsedTime());
     sfTimerManager::clearTimers();
 }
 /**
  * Listens to the response.filter_content event.
  *
  * @param  sfEvent $event   The sfEvent instance
  * @param  string  $context The response content
  *
  * @return string  The filtered response content
  */
 public function filterResponseContent(sfEvent $event, $content)
 {
     // log timers information
     $messages = array();
     foreach (sfTimerManager::getTimers() as $name => $timer) {
         $messages[] = sprintf('%s %.2f ms (%d)', $name, $timer->getElapsedTime() * 1000, $timer->getCalls());
     }
     $this->dispatcher->notify(new sfEvent($this, 'application.log', $messages));
     // don't add debug toolbar:
     // * for XHR requests
     // * if 304
     // * if not rendering to the client
     // * if HTTP headers only
     $response = $event->getSubject();
     $request = $this->context->getRequest();
     if (!$this->context->has('request') || !$this->context->has('response') || !$this->context->has('controller') || $request->isXmlHttpRequest() || strpos($response->getContentType(), 'html') === false || $response->getStatusCode() == 304 || $this->context->getController()->getRenderMode() != sfView::RENDER_CLIENT || $response->isHeaderOnly()) {
         return $content;
     }
     $webDebug = new $this->webDebugClass($this->dispatcher, $this, array('image_root_path' => ($request->getRelativeUrlRoot() ? $request->getRelativeUrlRoot() . '/' : '') . sfConfig::get('sf_web_debug_web_dir') . '/images'));
     return $webDebug->injectToolbar($content);
 }
Exemplo n.º 20
0
 /**
  * Executes this filter.
  *
  * @param sfFilterChain The filter chain.
  *
  * @throws <b>sfInitializeException</b> If an error occurs during view initialization
  * @throws <b>sfViewException</b>       If an error occurs while executing the view
  */
 public function execute($filterChain)
 {
     // execute next filter
     $filterChain->execute();
     if (sfConfig::get('sf_logging_enabled')) {
         $this->getContext()->getLogger()->info('{sfFilter} render to client');
     }
     // get response object
     $response = $this->getContext()->getResponse();
     // send headers
     $response->sendHttpHeaders();
     // send content
     $response->sendContent();
     // log timers information
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $logger = $this->getContext()->getLogger();
         foreach (sfTimerManager::getTimers() as $name => $timer) {
             $logger->info(sprintf('{sfTimerManager} %s %.2f ms (%d)', $name, $timer->getElapsedTime() * 1000, $timer->getCalls()));
         }
     }
 }
 /**
  * Executes this filter.
  *
  * @param sfFilterChain The filter chain
  *
  * @throws <b>sfInitializeException</b> If an error occurs during view initialization.
  * @throws <b>sfViewException</b>       If an error occurs while executing the view.
  */
 public function execute($filterChain)
 {
     // get the current action instance
     $actionInstance = $this->context->getController()->getActionStack()->getLastEntry()->getActionInstance();
     // validate and execute the action
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('Action "%s/%s"', $actionInstance->getModuleName(), $actionInstance->getActionName()));
     }
     $viewName = $this->handleAction($filterChain, $actionInstance);
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     // execute and render the view
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer(sprintf('View "%s" for "%s/%s"', $viewName, $actionInstance->getModuleName(), $actionInstance->getActionName()));
     }
     $this->handleView($filterChain, $actionInstance, $viewName);
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     // execute the filter chain (needed if fill-in filter is activated by the validation system)
     $filterChain->execute();
 }
/**
 * Evaluates and returns a component.
 * The syntax is similar to the one of include_component.
 *
 * <b>Example:</b>
 * <code>
 *  echo get_component('mymodule', 'mypartial', array('myvar' => 12345));
 * </code>
 *
 * @param  string module name
 * @param  string component name
 * @param  array variables to be made accessible to the component
 * @return string result of the component execution
 * @see    include_component
 */
function get_component($moduleName, $componentName, $vars = array())
{
    $context = sfContext::getInstance();
    $actionName = '_' . $componentName;
    // check cache
    if ($cacheManager = $context->getViewCacheManager()) {
        if ($retval = _get_cache($cacheManager, $moduleName, $actionName, $vars)) {
            return $retval;
        }
    }
    $controller = $context->getController();
    if (!$controller->componentExists($moduleName, $componentName)) {
        // cannot find component
        $error = 'The component does not exist: "%s", "%s"';
        $error = sprintf($error, $moduleName, $componentName);
        throw new sfConfigurationException($error);
    }
    // create an instance of the action
    $componentInstance = $controller->getComponent($moduleName, $componentName);
    // initialize the action
    if (!$componentInstance->initialize($context)) {
        // component failed to initialize
        $error = 'Component initialization failed for module "%s", component "%s"';
        $error = sprintf($error, $moduleName, $componentName);
        throw new sfInitializationException($error);
    }
    // load component's module config file
    require sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name') . '/' . $moduleName . '/' . sfConfig::get('sf_app_module_config_dir_name') . '/module.yml');
    $componentInstance->getVarHolder()->add($vars);
    // dispatch component
    $componentToRun = 'execute' . ucfirst($componentName);
    if (!method_exists($componentInstance, $componentToRun)) {
        if (!method_exists($componentInstance, 'execute')) {
            // component not found
            $error = 'sfComponent initialization failed for module "%s", component "%s"';
            $error = sprintf($error, $moduleName, $componentName);
            throw new sfInitializationException($error);
        }
        $componentToRun = 'execute';
    }
    if (sfConfig::get('sf_logging_enabled')) {
        $context->getLogger()->info('{PartialHelper} call "' . $moduleName . '->' . $componentToRun . '()' . '"');
    }
    // run component
    if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
        $timer = sfTimerManager::getTimer(sprintf('Component "%s/%s"', $moduleName, $componentName));
    }
    $retval = $componentInstance->{$componentToRun}();
    if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
        $timer->addTime();
    }
    if ($retval != sfView::NONE) {
        // render
        $view = new sfPartialView();
        $view->initialize($context, $moduleName, $actionName, '');
        $retval = $view->render($componentInstance->getVarHolder()->getAll());
        if ($cacheManager && (!sfConfig::get('sf_lazy_cache_key') || $cacheManager->isActionCacheable($moduleName, $actionName))) {
            $uri = _get_cache_uri($moduleName, $actionName, $vars);
            $retval = _set_cache($cacheManager, $uri, $retval);
        }
        return $retval;
    }
}
Exemplo n.º 23
0
 public function execute($filterChain)
 {
     $filterChain->execute();
     if (sfConfig::get('sf_logging_enabled')) {
         $this->getContext()->getLogger()->info('{sfFilter} render to client');
     }
     $response = $this->getContext()->getResponse();
     if (method_exists($response, 'sendHttpHeaders')) {
         $response->sendHttpHeaders();
     }
     $response->sendContent();
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $logger = $this->getContext()->getLogger();
         foreach (sfTimerManager::getTimers() as $name => $timer) {
             $logger->info(sprintf('{sfTimerManager} %s %.2f ms (%d)', $name, $timer->getElapsedTime() * 1000, $timer->getCalls()));
         }
     }
 }
Exemplo n.º 24
0
 /**
  * Listens to the response.filter_content event.
  *
  * @param  sfEvent $event   The sfEvent instance
  * @param  string  $content The response content
  *
  * @return string  The filtered response content
  */
 public function filterResponseContent(sfEvent $event, $content)
 {
     if (!sfConfig::get('sf_web_debug')) {
         return $content;
     }
     // log timers information
     $messages = array();
     foreach (sfTimerManager::getTimers() as $name => $timer) {
         $messages[] = sprintf('%s %.2f ms (%d)', $name, $timer->getElapsedTime() * 1000, $timer->getCalls());
     }
     $this->dispatcher->notify(new sfEvent($this, 'application.log', $messages));
     // don't add debug toolbar:
     // * for XHR requests
     // * if response status code is in the 3xx range
     // * if not rendering to the client
     // * if HTTP headers only
     $response = $event->getSubject();
     $request = $this->context->getRequest();
     if (null === $this->webDebug || !$this->context->has('request') || !$this->context->has('response') || !$this->context->has('controller') || $request->isXmlHttpRequest() || strpos($response->getContentType(), 'html') === false || '3' == substr($response->getStatusCode(), 0, 1) || $this->context->getController()->getRenderMode() != sfView::RENDER_CLIENT || $response->isHeaderOnly()) {
         return $content;
     }
     return $this->webDebug->injectToolbar($content);
 }
Exemplo n.º 25
0
 /**
  * Checks to see if a configuration file has been modified and if so
  * recompile the cache file associated with it.
  *
  * The recompilation only occurs in a non debug environment.
  *
  * If the configuration file path is relative, symfony will look in directories 
  * defined in the sfConfiguration::getConfigPaths() method.
  *
  * @param string  $configPath A filesystem path to a configuration file
  * @param boolean $optional   If true, config path does not need to exist
  *
  * @return string An absolute filesystem path to the cache filename associated with this specified configuration file
  *
  * @throws <b>sfConfigurationException</b> If a requested configuration file does not exist
  *
  * @see sfConfiguration::getConfigPaths()
  */
 public function checkConfig($configPath, $optional = false)
 {
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer('Configuration');
     }
     // the cache filename we'll be using
     $cache = $this->getCacheName($configPath);
     if (!sfConfig::get('sf_debug') && !sfConfig::get('sf_test') && is_readable($cache)) {
         return $cache;
     }
     if (!sfToolkit::isPathAbsolute($configPath)) {
         $files = $this->configuration->getConfigPaths($configPath);
     } else {
         $files = is_readable($configPath) ? array($configPath) : array();
     }
     if (!isset($files[0])) {
         if ($optional) {
             return null;
         }
         // configuration does not exist
         throw new sfConfigurationException(sprintf('Configuration "%s" does not exist or is unreadable.', $configPath));
     }
     // find the more recent configuration file last modification time
     $mtime = 0;
     foreach ($files as $file) {
         if (filemtime($file) > $mtime) {
             $mtime = filemtime($file);
         }
     }
     if (!is_readable($cache) || $mtime > filemtime($cache)) {
         // configuration has changed so we need to reparse it
         $this->callHandler($configPath, $files, $cache);
     }
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     return $cache;
 }
Exemplo n.º 26
0
<?php

/*
 * This file is part of the symfony package.
 * (c) 2004-2006 Fabien Potencier <*****@*****.**>
 * 
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
require_once __DIR__ . '/../../bootstrap/unit.php';
$t = new lime_test(6);
$t->diag('sfTimer starting and stopping');
$timer = new sfTimer();
$timer->addTime();
sleep(1);
$timer->addTime();
$t->is($timer->getCalls(), 2, '->getCalls() returns the amount of addTime() calls');
$t->ok($timer->getElapsedTime() > 0, '->getElapsedTime() returns a value greater than zero. No precision is tested by the unit test to avoid false alarms');
$t->diag('sfTimerManager');
$timerA = sfTimerManager::getTimer('timerA');
$timerB = sfTimerManager::getTimer('timerB');
$t->isa_ok($timerA, 'sfTimer', '::getTimer() returns an sfTimer instance');
$timers = sfTimerManager::getTimers();
$t->is(count($timers), 2, '::getTimers() returns an array with the timers created by the timer manager');
$t->is($timers['timerA'], $timerA, '::getTimers() returns an array with keys being the timer name');
sfTimerManager::clearTimers();
$t->is(count(sfTimerManager::getTimers()), 0, '::clearTimers() empties the list of the timer instances');
Exemplo n.º 27
0
function _call_component($moduleName, $componentName, $vars)
{
    $context = sfContext::getInstance();
    $controller = $context->getController();
    if (!$controller->componentExists($moduleName, $componentName)) {
        // cannot find component
        throw new sfConfigurationException(sprintf('The component does not exist: "%s", "%s".', $moduleName, $componentName));
    }
    // create an instance of the action
    $componentInstance = $controller->getComponent($moduleName, $componentName);
    // load component's module config file
    require $context->getConfigCache()->checkConfig('modules/' . $moduleName . '/config/module.yml');
    $componentInstance->getVarHolder()->add($vars);
    // dispatch component
    $componentToRun = 'execute' . ucfirst($componentName);
    if (!method_exists($componentInstance, $componentToRun)) {
        if (!method_exists($componentInstance, 'execute')) {
            // component not found
            throw new sfInitializationException(sprintf('sfComponent initialization failed for module "%s", component "%s".', $moduleName, $componentName));
        }
        $componentToRun = 'execute';
    }
    if (sfConfig::get('sf_logging_enabled')) {
        $context->getEventDispatcher()->notify(new sfEvent(null, 'application.log', array(sprintf('Call "%s->%s()' . '"', $moduleName, $componentToRun))));
    }
    // run component
    if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
        $timer = sfTimerManager::getTimer(sprintf('Component "%s/%s"', $moduleName, $componentName));
    }
    $retval = $componentInstance->{$componentToRun}($context->getRequest());
    if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
        $timer->addTime();
    }
    return sfView::NONE == $retval ? null : $componentInstance->getVarHolder()->getAll();
}
 /**
  * Checks to see if a configuration file has been modified and if so
  * recompile the cache file associated with it.
  *
  * The recompilation only occurs in a non debug environment.
  *
  * If the configuration file path is relative, symfony will look in directories 
  * defined in the sfLoader::getConfigPaths() method.
  *
  * @param string A filesystem path to a configuration file
  *
  * @return string An absolute filesystem path to the cache filename associated with this specified configuration file
  *
  * @throws <b>sfConfigurationException</b> If a requested configuration file does not exist
  *
  * @see sfLoader::getConfigPaths()
  */
 public function checkConfig($configPath, $optional = false)
 {
     static $process_cache_cleared = false;
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer = sfTimerManager::getTimer('Configuration');
     }
     // the cache filename we'll be using
     $cache = $this->getCacheName($configPath);
     if (sfConfig::get('sf_in_bootstrap') && is_readable($cache)) {
         if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
             $timer->addTime();
         }
         return $cache;
     }
     if (!sfToolkit::isPathAbsolute($configPath)) {
         $files = sfLoader::getConfigPaths($configPath);
     } else {
         $files = is_readable($configPath) ? array($configPath) : array();
     }
     if (!isset($files[0])) {
         if ($optional) {
             return null;
         }
         // configuration does not exist
         $error = sprintf('Configuration "%s" does not exist or is unreadable', $configPath);
         throw new sfConfigurationException($error);
     }
     // find the more recent configuration file last modification time
     $mtime = 0;
     foreach ($files as $file) {
         if (filemtime($file) > $mtime) {
             $mtime = filemtime($file);
         }
     }
     if (!is_readable($cache) || $mtime > filemtime($cache)) {
         // configuration has changed so we need to reparse it
         $this->callHandler($configPath, $files, $cache);
         // clear process cache
         if ('config/config_handlers.yml' != $configPath && sfConfig::get('sf_use_process_cache') && !$process_cache_cleared) {
             sfProcessCache::clear();
             $process_cache_cleared = true;
         }
     }
     if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled')) {
         $timer->addTime();
     }
     return $cache;
 }
Exemplo n.º 29
0
    /**
     * Returns the web debug toolbar as HTML.
     *
     * @return string The web debug toolbar HTML
     */
    public function getResults()
    {
        if (!sfConfig::get('sf_web_debug')) {
            return '';
        }
        $this->loadHelpers();
        $result = '';
        // max priority
        $maxPriority = '';
        if (sfConfig::get('sf_logging_enabled')) {
            $maxPriority = $this->getPriority($this->maxPriority);
        }
        $logs = '';
        $sqlLogs = array();
        if (sfConfig::get('sf_logging_enabled')) {
            $logs = '<table class="sfWebDebugLogs">
        <tr>
          <th>#</th>
          <th>type</th>
          <th>message</th>
        </tr>' . "\n";
            $line_nb = 0;
            foreach ($this->log as $logEntry) {
                $log = $logEntry['message'];
                $priority = $this->getPriority($logEntry['priority']);
                if (strpos($type = $logEntry['type'], 'sf') === 0) {
                    $type = substr($type, 2);
                }
                // xdebug information
                $debug_info = '';
                if ($logEntry['debugStack']) {
                    $debug_info .= '&nbsp;<a href="#" onclick="sfWebDebugToggle(\'debug_' . $line_nb . '\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/toggle.gif') . '</a><div class="sfWebDebugDebugInfo" id="debug_' . $line_nb . '" style="display:none">';
                    foreach ($logEntry['debugStack'] as $i => $logLine) {
                        $debug_info .= '#' . $i . ' &raquo; ' . $this->formatLogLine($logLine) . '<br/>';
                    }
                    $debug_info .= "</div>\n";
                }
                // format log
                $log = $this->formatLogLine($log);
                // sql queries log
                if (preg_match('/execute(?:Query|Update).+?\\:\\s+(.+)$/', $log, $match)) {
                    $sqlLogs[] .= $match[1];
                }
                ++$line_nb;
                $logs .= sprintf("<tr class='sfWebDebugLogLine sfWebDebug%s %s'><td class=\"sfWebDebugLogNumber\">%s</td><td class=\"sfWebDebugLogType\">%s&nbsp;%s</td><td>%s%s</td></tr>\n", ucfirst($priority), $logEntry['type'], $line_nb, image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/' . $priority . '.png'), $type, $log, $debug_info);
            }
            $logs .= '</table>';
            ksort($this->types);
            $types = array();
            foreach ($this->types as $type => $nb) {
                $types[] = '<a href="#" onclick="sfWebDebugToggleMessages(\'' . $type . '\'); return false;">' . $type . '</a>';
            }
        }
        // ignore cache link
        $cacheLink = '';
        if (sfConfig::get('sf_debug') && sfConfig::get('sf_cache')) {
            $selfUrl = $_SERVER['PHP_SELF'] . (strpos($_SERVER['PHP_SELF'], '_sf_ignore_cache') === false ? '?_sf_ignore_cache=1' : '');
            $cacheLink = '<li><a href="' . $selfUrl . '" title="reload and ignore cache">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/reload.png') . '</a></li>';
        }
        // logging information
        $logLink = '';
        if (sfConfig::get('sf_logging_enabled')) {
            $logLink = '<li><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugLog\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/comment.png') . ' logs &amp; msgs</a></li>';
        }
        // database information
        $dbInfo = '';
        $dbInfoDetails = '';
        if ($sqlLogs) {
            $dbInfo = '<li><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugDatabaseDetails\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/database.png') . ' ' . count($sqlLogs) . '</a></li>';
            $dbInfoDetails = '
        <div id="sfWebDebugDatabaseLogs">
        <ol><li>' . implode("</li>\n<li>", $sqlLogs) . '</li></ol>
        </div>
      ';
        }
        // memory used
        $memoryInfo = '';
        if (sfConfig::get('sf_debug') && function_exists('memory_get_usage')) {
            $totalMemory = sprintf('%.1f', memory_get_usage() / 1024);
            $memoryInfo = '<li>' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/memory.png') . ' ' . $totalMemory . ' KB</li>';
        }
        // total time elapsed
        $timeInfo = '';
        if (sfConfig::get('sf_debug')) {
            $totalTime = (microtime(true) - sfConfig::get('sf_timer_start')) * 1000;
            $totalTime = sprintf($totalTime <= 1 ? '%.2f' : '%.0f', $totalTime);
            $timeInfo = '<li class="last"><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugTimeDetails\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/time.png') . ' ' . $totalTime . ' ms</a></li>';
        }
        // timers
        $timeInfoDetails = '<table class="sfWebDebugLogs" style="width: 300px"><tr><th>type</th><th>calls</th><th>time (ms)</th><th>time (%)</th></tr>';
        foreach (sfTimerManager::getTimers() as $name => $timer) {
            $timeInfoDetails .= sprintf('<tr><td class="sfWebDebugLogType">%s</td><td class="sfWebDebugLogNumber" style="text-align: right">%d</td><td style="text-align: right">%.2f</td><td style="text-align: right">%d</td></tr>', $name, $timer->getCalls(), $timer->getElapsedTime() * 1000, $timer->getElapsedTime() * 1000 * 100 / $totalTime);
        }
        $timeInfoDetails .= '</table>';
        // logs
        $logInfo = '';
        if (sfConfig::get('sf_logging_enabled')) {
            $logInfo .= '
        <ul id="sfWebDebugLogMenu">
          <li><a href="#" onclick="sfWebDebugToggleAllLogLines(true, \'sfWebDebugLogLine\'); return false;">[all]</a></li>
          <li><a href="#" onclick="sfWebDebugToggleAllLogLines(false, \'sfWebDebugLogLine\'); return false;">[none]</a></li>
          <li><a href="#" onclick="sfWebDebugShowOnlyLogLines(\'info\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/info.png') . '</a></li>
          <li><a href="#" onclick="sfWebDebugShowOnlyLogLines(\'warning\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/warning.png') . '</a></li>
          <li><a href="#" onclick="sfWebDebugShowOnlyLogLines(\'error\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/error.png') . '</a></li>
          <li>' . implode("</li>\n<li>", $types) . '</li>
        </ul>
        <div id="sfWebDebugLogLines">' . $logs . '</div>
      ';
        }
        $result .= '
    <div id="sfWebDebug">
      <div id="sfWebDebugBar" class="sfWebDebug' . ucfirst($maxPriority) . '">
        <a href="#" onclick="sfWebDebugToggleMenu(); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/sf.png') . '</a>
        <ul id="sfWebDebugDetails" class="menu">
          <li>' . SYMFONY_VERSION . '</li>
          <li><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugConfig\'); return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/config.png') . ' vars &amp; config</a></li>
          ' . $cacheLink . '
          ' . $logLink . '
          ' . $dbInfo . '
          ' . $memoryInfo . '
          ' . $timeInfo . '
        </ul>
        <a href="#" onclick="document.getElementById(\'sfWebDebug\').style.display=\'none\'; return false;">' . image_tag(sfConfig::get('sf_web_debug_web_dir') . '/images/close.png') . '</a>
      </div>

      <div id="sfWebDebugLog" class="sfWebDebugTop" style="display: none"><h1>Log and debug messages</h1>' . $logInfo . '</div>
      <div id="sfWebDebugConfig" class="sfWebDebugTop" style="display: none"><h1>Configuration and request variables</h1>' . $this->getCurrentConfigAsHtml() . '</div>
      <div id="sfWebDebugDatabaseDetails" class="sfWebDebugTop" style="display: none"><h1>SQL queries</h1>' . $dbInfoDetails . '</div>
      <div id="sfWebDebugTimeDetails" class="sfWebDebugTop" style="display: none"><h1>Timers</h1>' . $timeInfoDetails . '</div>

      </div>
    ';
        return $result;
    }
 /**
  * Clears all sfTimer instances stored in sfTimerManager.
  */
 public static function clearTimers()
 {
     self::$timers = array();
 }