function plgSh404sefAnalyticsCustomVars(&$customVars, $sefConfig)
{
    // add custom variable : page creation time
    if ($sefConfig->analyticsEnableTimeCollection) {
        $profiler =& JProfiler::getInstance('sh404sef_profiler');
        $profiler->mark('');
        $pageCreationTime = $profiler->getBuffer();
        //extract Data
        $pageCreationTime = str_replace('sh404sef_profiler : ', '', $pageCreationTime[0]);
        $tmp = explode(', ', $pageCreationTime);
        // we may have memory report attached
        $time = str_replace(' seconds', '', $tmp[0]);
        // classify exact time into predefined categories for encoding
        $time = Sh404sefHelperAnalytics::classifyTime($time);
        // same for memory used
        $memory = empty($tmp[1]) ? 0 : sh404sefHelperAnalytics::classifyMemory(str_replace(' MB', '', trim($tmp[1])));
        // store results into incoming array
        $customVars[SH404SEF_ANALYTICS_TIME_CUSTOM_VAR]->name = 'Page creation time and ram';
        $customVars[SH404SEF_ANALYTICS_TIME_CUSTOM_VAR]->value = ($time << 4) + $memory;
    }
    // add custom variable : user logged in
    if ($sefConfig->analyticsEnableUserCollection) {
        $user = JFactory::getUser();
        $customVars[SH404SEF_ANALYTICS_USER_CUSTOM_VAR]->name = 'Logged-in user';
        $userType = empty($user->usertype) ? 'anonymous' : $user->usertype;
        $customVars[SH404SEF_ANALYTICS_USER_CUSTOM_VAR]->value = htmlentities($userType, ENT_QUOTES, 'UTF-8');
    }
    return true;
}
Exemple #2
0
 /**
  * Display the template list.
  *
  * @return void
  */
 private function templates()
 {
     $input = JFactory::getApplication()->input;
     $profiling = false;
     if ($profiling) {
         //            jimport('joomla.error.profiler');
         $this->profiler = JProfiler::getInstance('EasyCreator');
     }
     $this->task = $input->get('task');
     $this->ecr_project = $input->get('ecr_project');
     $this->path = ECRPATH_EXTENSIONTEMPLATES;
     $this->file_path = $input->getPath('file_path');
     $this->file_name = $input->getPath('file_name');
     $this->com_type = $input->get('com_type');
     $this->template = $input->get('template');
     $this->comTypes = EcrProjectHelper::getProjectTypes();
     $cache = JFactory::getCache();
     $cache->setCaching(1);
     if ($profiling) {
         $this->profiler->mark('start get templates');
     }
     $this->templates = EcrProjectTemplateHelper::getTemplateList();
     if ($profiling) {
         $this->profiler->mark('end get cached templates');
     }
     if ($profiling) {
         echo '<pre>' . print_r($this->profiler->getBuffer(), true) . '</pre>';
     }
     $this->setLayout('templates');
 }
Exemple #3
0
 public static function _doCheck()
 {
     jimport('joomla.error.profiler');
     // creating the profiler object will start the counter
     $profiler = JProfiler::getInstance('sh404sef_analytics_profiler');
     // if not set to auto check and not forced to do so
     // when user click on "check updates" button
     // we don't actually try to get updates info
     $sefConfig =& Sh404sefFactory::getConfig();
     // check if allowed to auto check, w/o user clicking on button
     if (!$sefConfig->autoCheckNewAnalytics && !self::$_options['forced']) {
         // prepare a default response object
         $response = new stdClass();
         $response->status = true;
         $response->statusMessage = JText::_('COM_SH404SEF_CLICK_TO_CHECK_ANALYTICS');
         $response->note = '';
         return $response;
     }
     // calculate adapted class name
     $className = 'Sh404sefAdapterAnalytics' . strtolower($sefConfig->analyticsType);
     $handler = new $className();
     // ask specialized class to fetch analytics data
     $response = $handler->fetchAnalytics($sefConfig, self::$_options);
     // done; send response back
     return $response;
 }
Exemple #4
0
 /**
  * Retrieve the storage content.
  *
  * @param   string  $lang       E.g. de-DE, es-ES etc.
  * @param   string  $extension  E.g. joomla, com_weblinks, com_easycreator etc.
  * @param   string  $domain     Must be 'admin' or 'site'.
  *
  * @throws G11nException
  * @return \g11n\Support\Store
  */
 public function retrieve($lang, $extension, $domain = '')
 {
     if (self::$storage == 'off') {
         return false;
     }
     $profiler = JProfiler::getInstance('LangDebug');
     $profiler->mark('start: ' . $extension);
     $this->query->clear('where');
     $this->query->where('extension = ' . $this->db->quote($extension));
     $this->query->where('lang = ' . $this->db->quote($lang));
     $this->query->where('scope = ' . $this->db->quote($this->scope));
     $this->db->setQuery($this->query);
     $e = $this->db->loadObject();
     if (empty($e->strings)) {
         $profiler->mark('<span style="color: red;">langload db failed ****</span>' . $this->query);
         $this->setError($this->db->getError());
         return false;
     }
     $strings = json_decode($e->strings, true);
     $profiler->mark('<span style="color: green;">*Loaded db*</span>');
     $this->strings = array_merge($this->strings, $strings);
     // Language overrides
     $this->strings = array_merge($this->strings, $this->override);
     $this->paths[$extension][$fileName] = true;
     return true;
 }
Exemple #5
0
 public function __construct($context)
 {
     $this->context = $context;
     if (JvrelInit::getCfg('debug')) {
         $this->profiler = JProfiler::getInstance('Application');
     }
     $this->eopsob = new JvrelativesEopsob();
 }
 /**
  * Called after any type of action
  *
  * @param     string              $route      Which action is happening (install|uninstall|discover_install)
  * @param     jadapterinstance    $adapter    The object responsible for running this script
  *
  * @return    boolean                         True on success
  */
 public function postflight($route, JAdapterInstance $adapter)
 {
     if (JDEBUG) {
         JProfiler::getInstance('Application')->mark('after' . ucfirst($route) . 'Projectfork');
         $buffer = JProfiler::getInstance('Application')->getBuffer();
         $app = JFactory::getApplication();
         foreach ($buffer as $mark) {
             $app->enqueueMessage($mark, 'debug');
         }
     }
     return true;
 }
 /**
  * Adds application response time and memory usage to Chrome Inspector with ChromeLogger extension
  *
  * See: https://chrome.google.com/webstore/detail/chrome-logger/noaneddfkdjfnfdakjjmocngnfkfehhd
  */
 public function __destruct()
 {
     if (JDEBUG && !headers_sent()) {
         $buffer = JProfiler::getInstance('Application')->getBuffer();
         if ($buffer) {
             $data = strip_tags(end($buffer));
             $row = array(array($data), null, 'info');
             $header = array('version' => '4.1.0', 'columns' => array('log', 'backtrace', 'type'), 'rows' => array($row));
             header('X-ChromeLogger-Data: ' . base64_encode(utf8_encode(json_encode($header))));
         }
     }
 }
 /**
  * Returns a Joomla application with a root user logged in
  *
  * @param string $base Base path for the Joomla installation
  * @param int    $client_id Application client id to spoof. Defaults to admin.
  *
  * @return Application
  */
 public static function getApplication($base, $client_id = self::ADMIN)
 {
     $_SERVER['SERVER_PORT'] = 80;
     if (!self::$_application) {
         self::bootstrap($base);
         $options = array('root_user' => 'root', 'client_id' => $client_id);
         self::$_application = new Application($options);
         $credentials = array('name' => 'root', 'username' => 'root', 'groups' => array(8), 'email' => '*****@*****.**');
         self::$_application->authenticate($credentials);
         // If there are no marks in JProfiler debug plugin performs a division by zero using count($marks)
         \JProfiler::getInstance('Application')->mark('Hello world');
     }
     return self::$_application;
 }
Exemple #9
0
 /**
  * @param Application $app
  */
 public function __construct($app)
 {
     parent::__construct($app);
     return;
     // for debug only
     if (self::$_jbdump === null) {
         // Joomla standart profiler
         if (JDEBUG) {
             self::$_jbdump = JProfiler::getInstance('Application');
         }
         // jbdump plugin
         if (class_exists('jbdump')) {
             self::$_jbdump = JBDump::i($this->_jbdumpParams);
         }
     }
 }
Exemple #10
0
 /**
  * Stores the strings into a storage.
  *
  * @param   string  $lang       E.g. de-DE, es-ES etc.
  * @param   string  $extension  E.g. joomla, com_weblinks, com_easycreator etc.
  * @param   string  $domain     Must be 'admin' or 'site'.
  *
  * @throws G11nException
  * @return boolean
  */
 public function store($lang, $extension, $domain = '')
 {
     if (self::$storage == 'off') {
         return false;
     }
     $profiler = JProfiler::getInstance('LangDebug');
     $profiler->mark('store: ' . $extension);
     //        #		$fileNames = JFolder::files(JPATH_ADMINISTRATOR, '.sys.ini', false, true);
     $strings = self::parseFile($fileName);
     $path = self::$cacheDir . '/' . $lang . '.' . $extension . '.txt';
     $jsonString = json_encode($strings);
     if (!JFile::write($path, $jsonString)) {
         throw new G11nException('Unable to write language storage file');
     }
     $profiler->mark('<span style="color: blue;">wrote file</span>: ' . str_replace(JPATH_ROOT, 'J', $path));
     $profiler->mark('store SUCCESS ++++: ' . $extension);
     return true;
 }
 /**
  * Returns a Joomla application with a root user logged in
  *
  * @param string $base Base path for the Joomla installation
  * @return Application
  */
 public static function getApplication($base)
 {
     $_SERVER['SERVER_PORT'] = 80;
     if (!defined('_JEXEC')) {
         $_SERVER['HTTP_HOST'] = 'localhost';
         $_SERVER['HTTP_USER_AGENT'] = 'joomla-cli/1.0.0';
         define('_JEXEC', 1);
         define('DS', DIRECTORY_SEPARATOR);
         define('JPATH_BASE', realpath($base));
         require_once JPATH_BASE . '/includes/defines.php';
         require_once JPATH_BASE . '/includes/framework.php';
         require_once JPATH_LIBRARIES . '/import.php';
         require_once JPATH_LIBRARIES . '/cms.php';
     }
     $credentials = array('name' => 'root', 'username' => 'root', 'groups' => array(8), 'email' => '*****@*****.**');
     $application = new Application(array('root_user' => 'root'));
     $application->authenticate($credentials);
     // If there are no marks in JProfiler debug plugin performs a division by zero using count($marks)
     \JProfiler::getInstance('Application')->mark('Hello world');
     return $application;
 }
 /**
  * Converting the site URL to fit to the HTTP request.
  *
  * @return  void
  *
  * @since   1.5
  */
 public function onAfterInitialise()
 {
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     if ($app->isAdmin()) {
         return;
     }
     if (count($app->getMessageQueue())) {
         return;
     }
     if ($user->get('guest') && $app->input->getMethod() == 'GET') {
         $this->_cache->setCaching(true);
     }
     $data = $this->_cache->get($this->_cache_key);
     if ($data !== false) {
         // Set cached body.
         $app->setBody($data);
         echo $app->toString();
         if (JDEBUG) {
             JProfiler::getInstance('Application')->mark('afterCache');
         }
         $app->close();
     }
 }
 /**
  * Render the module.
  *
  * @param   object  $module   A module object.
  * @param   array   $attribs  An array of attributes for the module (probably from the XML).
  *
  * @return  string  The HTML content of the module output.
  *
  * @since   11.1
  */
 public static function renderModule($module, $attribs = array())
 {
     static $chrome;
     if (constant('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('beforeRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     $app = JFactory::getApplication();
     // Record the scope.
     $scope = $app->scope;
     // Set scope to component name
     $app->scope = $module->module;
     // Get module parameters
     $params = new JRegistry();
     $params->loadString($module->params);
     // Get module path
     $module->module = preg_replace('/[^A-Z0-9_\\.-]/i', '', $module->module);
     $path = JPATH_BASE . '/modules/' . $module->module . '/' . $module->module . '.php';
     // Load the module
     if (file_exists($path)) {
         $lang = JFactory::getLanguage();
         // 1.5 or Core then 1.6 3PD
         $lang->load($module->module, JPATH_BASE, null, false, false) || $lang->load($module->module, dirname($path), null, false, false) || $lang->load($module->module, JPATH_BASE, $lang->getDefault(), false, false) || $lang->load($module->module, dirname($path), $lang->getDefault(), false, false);
         $content = '';
         ob_start();
         include $path;
         $module->content = ob_get_contents() . $content;
         ob_end_clean();
     }
     // Load the module chrome functions
     if (!$chrome) {
         $chrome = array();
     }
     include_once JPATH_THEMES . '/system/html/modules.php';
     $chromePath = JPATH_THEMES . '/' . $app->getTemplate() . '/html/modules.php';
     if (!isset($chrome[$chromePath])) {
         if (file_exists($chromePath)) {
             include_once $chromePath;
         }
         $chrome[$chromePath] = true;
     }
     // Make sure a style is set
     if (!isset($attribs['style'])) {
         $attribs['style'] = 'none';
     }
     // Dynamically add outline style
     if ($app->input->getBool('tp') && JComponentHelper::getParams('com_templates')->get('template_positions_display')) {
         $attribs['style'] .= ' outline';
     }
     foreach (explode(' ', $attribs['style']) as $style) {
         $chromeMethod = 'modChrome_' . $style;
         // Apply chrome and render module
         if (function_exists($chromeMethod)) {
             $module->style = $attribs['style'];
             ob_start();
             $chromeMethod($module, $params, $attribs);
             $module->content = ob_get_contents();
             ob_end_clean();
         }
     }
     // Revert the scope
     $app->scope = $scope;
     if (constant('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('afterRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     return $module->content;
 }
Exemple #14
0
 /**
  * Class constructor.
  *
  * @param   mixed  $input   An optional argument to provide dependency injection for the application's
  *                          input object.  If the argument is a JInput object that object will become
  *                          the application's input object, otherwise a default input object is created.
  * @param   mixed  $config  An optional argument to provide dependency injection for the application's
  *                          config object.  If the argument is a JRegistry object that object will become
  *                          the application's config object, otherwise a default config object is created.
  * @param   mixed  $client  An optional argument to provide dependency injection for the application's
  *                          client object.  If the argument is a JApplicationWebClient object that object will become
  *                          the application's client object, otherwise a default client object is created.
  *
  * @since   3.2
  */
 public function __construct(JInput $input = null, JRegistry $config = null, JApplicationWebClient $client = null)
 {
     parent::__construct($input, $config, $client);
     // Load and set the dispatcher
     $this->loadDispatcher();
     // If JDEBUG is defined, load the profiler instance
     if (defined('JDEBUG') && JDEBUG) {
         $this->profiler = JProfiler::getInstance('Application');
     }
     // Enable sessions by default.
     if (is_null($this->config->get('session'))) {
         $this->config->set('session', true);
     }
     // Set the session default name.
     if (is_null($this->config->get('session_name'))) {
         $this->config->set('session_name', $this->getName());
     }
 }
Exemple #15
0
/**
 * NOTE: This file should remain compatible with PHP 5.2 to allow us to run our PHP minimum check and show a friendly error message
 */
/**
 * Define the application's minimum supported PHP version as a constant so it can be referenced within the application.
 */
define('JOOMLA_MINIMUM_PHP', '5.5.9');
if (version_compare(PHP_VERSION, JOOMLA_MINIMUM_PHP, '<')) {
    die('Your host needs to use PHP ' . JOOMLA_MINIMUM_PHP . ' or higher to run this version of Joomla!');
}
// Saves the start time and memory usage.
$startTime = microtime(1);
$startMem = memory_get_usage();
/**
 * Constant that is checked in included files to prevent direct access.
 */
define('_JEXEC', 1);
if (file_exists(__DIR__ . '/defines.php')) {
    include_once __DIR__ . '/defines.php';
}
if (!defined('_JDEFINES')) {
    define('JPATH_BASE', __DIR__);
    require_once JPATH_BASE . '/includes/defines.php';
}
require_once JPATH_BASE . '/includes/framework.php';
// Set profiler start time and memory usage and mark afterLoad in the profiler.
JDEBUG ? JProfiler::getInstance('Application')->setStart($startTime, $startMem)->mark('afterLoad') : null;
// Instantiate the application.
$app = JFactory::getApplication('administrator');
// Execute the application.
$app->execute();
Exemple #16
0
 /**
  * Actually load the template and echo the view html
  * will process jplugins if required.
  *
  * @return  void
  */
 protected function output()
 {
     $app = JFactory::getApplication();
     $input = $app->input;
     $profiler = JProfiler::getInstance('Application');
     $text = $this->loadTemplate();
     JDEBUG ? $profiler->mark('template loaded') : null;
     $model = $this->getModel();
     $params = $model->getParams();
     if ($params->get('process-jplugins')) {
         FabrikHelperHTML::runConentPlugins($text);
     }
     JDEBUG ? $profiler->mark('end fabrik display') : null;
     // $$$ rob 09/06/2011 no need for isMambot test? should use ob_start() in module / plugin to capture the output
     echo $text;
 }
Exemple #17
0
function KunenaParseRoute($segments)
{
    // If Kunena Forum isn't installed do nothing
    if (!class_exists('KunenaForum') || !KunenaForum::isCompatible('3.0') || !KunenaForum::installed()) {
        return array();
    }
    $profiler = JProfiler::getInstance('Application');
    KUNENA_PROFILER ? $profiler->mark('kunenaRoute') : null;
    $starttime = $profiler->getmicrotime();
    // Get current menu item and get query variables from it
    $active = JFactory::getApplication()->getMenu()->getActive();
    $vars = isset($active->query) ? $active->query : array('view' => 'home');
    if (empty($vars['view']) || $vars['view'] == 'home' || $vars['view'] == 'entrypage') {
        $vars['view'] = '';
    }
    // Use category SEF feature?
    $sefcats = isset(KunenaRoute::$sefviews[$vars['view']]) && empty($vars['id']);
    // Handle all segments
    while (($segment = array_shift($segments)) !== null) {
        // Skip //
        if (!$segment) {
            continue;
        }
        if ($sefcats && class_exists('KunenaRoute') && method_exists('KunenaRoute', 'resolveAlias')) {
            // Find out if we have SEF alias (category, view or layout)
            $alias = strtr($segment, ':', '-');
            $variables = KunenaRoute::resolveAlias($alias);
            if ($variables) {
                $sefcats = false;
                $vars = $variables + $vars;
                continue;
            }
        }
        $sefcats = false;
        // Generate variable and value
        $seg = explode(':', $segment);
        $var = array_shift($seg);
        $value = array_shift($seg);
        if (empty($var) && empty($value)) {
            // Skip /-/
            continue;
        }
        if (is_numeric($var)) {
            // Handle variables starting by number
            $value = (int) $var;
            if ($vars['view'] == 'user') {
                // Special case: User view
                $var = 'userid';
            } elseif (empty($vars['catid'])) {
                // First number is always category
                $var = 'catid';
                $vars['view'] = 'category';
            } elseif (empty($vars['id'])) {
                // Second number is always topic
                $var = 'id';
                $vars['view'] = 'topic';
                $sefcats = false;
            } elseif (empty($vars['mesid'])) {
                // Third number is always message
                $var = 'mesid';
                $vars['view'] = 'topic';
            } else {
                // Invalid parameter, skip it
                continue;
            }
        } elseif ($value === null) {
            // Simple variable without value is always either view or layout
            $value = $var;
            if (empty($vars['view']) || $value == 'topic' && $vars['view'] == 'category') {
                // View
                $var = 'view';
            } elseif (empty($vars['layout'])) {
                // Layout
                $var = 'layout';
            } elseif (!empty($vars['view'])) {
                // Unknown parameter: skip
                if (!empty($vars['view'])) {
                    continue;
                }
            } else {
                // Unknown view or non-existing category
                $var = 'view';
            }
        }
        $vars[$var] = $value;
    }
    if (empty($vars['layout'])) {
        $vars['layout'] = 'default';
    }
    KunenaRoute::$time = $profiler->getmicrotime() - $starttime;
    foreach ($vars as $var => $value) {
        KunenaRoute::$current->setVar($var, $value);
    }
    return $vars;
}
Exemple #18
0
 /**
  * Method to return the JAccessRules object for an asset.  The returned object can optionally hold
  * only the rules explicitly set for the asset or the summation of all inherited rules from
  * parent assets and explicit rules.
  *
  * @param   mixed    $asset                 Integer asset id or the name of the asset as a string.
  * @param   boolean  $recursive             True to return the rules object with inherited rules.
  * @param   boolean  $recursiveParentAsset  True to calculate the rule also based on inherited component/extension rules.
  *
  * @return  JAccessRules   JAccessRules object for the asset.
  *
  * @since   11.1
  */
 public static function getAssetRules($asset, $recursive = false, $recursiveParentAsset = true)
 {
     // Get instance of the Profiler:
     $_PROFILER = JProfiler::getInstance('Application');
     $extensionName = self::getExtensionNameFromAsset($asset);
     // Almost all calls should have recursive set to true
     // so we'll get to take advantage of preloading:
     if ($recursive && $recursiveParentAsset && isset(self::$assetPermissionsByName[$extensionName]) && isset(self::$assetPermissionsByName[$extensionName][$asset])) {
         // Mark in the profiler.
         JDEBUG ? $_PROFILER->mark('Start JAccess::getAssetRules New (' . $asset . ')') : null;
         $assetType = self::getAssetType($asset);
         $assetId = self::$assetPermissionsByName[$extensionName][$asset]->id;
         $ancestors = array_reverse(self::getAssetAncestors($assetType, $assetId));
         // Collects permissions for each $asset
         $collected = array();
         foreach ($ancestors as $id) {
             $collected[] = self::$assetPermissionsById[$extensionName][$id]->rules;
         }
         /**
          * Hashing the collected rules allows us to store
          * only one instance of the JAccessRules object for
          * Assets that have the same exact permissions...
          * it's a great way to save some memory.
          */
         $hash = md5(implode(',', $collected));
         if (!isset(self::$assetRulesIdentities[$hash])) {
             $rules = new JAccessRules();
             $rules->mergeCollection($collected);
             self::$assetRulesIdentities[$hash] = $rules;
         }
         // Mark in the profiler.
         JDEBUG ? $_PROFILER->mark('Finish JAccess::getAssetRules New (' . $asset . ')') : null;
         return self::$assetRulesIdentities[$hash];
     } else {
         // Mark in the profiler.
         JDEBUG ? $_PROFILER->mark('Start JAccess::getAssetRules Old (' . $asset . ')') : null;
         if ($asset === "1") {
             // There's no need to process it with the
             // recursive method for the Root Asset ID.
             $recursive = false;
         }
         // Get the database connection object.
         $db = JFactory::getDbo();
         // Build the database query to get the rules for the asset.
         $query = $db->getQuery(true)->select($recursive ? 'b.rules' : 'a.rules')->from('#__assets AS a');
         $extensionString = '';
         if ($recursiveParentAsset && ($extensionName !== $asset || is_numeric($asset))) {
             $extensionString = ' OR a.name = ' . $db->quote($extensionName);
         }
         $recursiveString = '';
         if ($recursive) {
             $recursiveString = ' OR a.parent_id=0';
         }
         // If the asset identifier is numeric assume it is a primary key, else lookup by name.
         if (is_numeric($asset)) {
             $query->where('(a.id = ' . (int) $asset . $extensionString . $recursiveString . ')');
         } else {
             $query->where('(a.name = ' . $db->quote($asset) . $extensionString . $recursiveString . ')');
         }
         // If we want the rules cascading up to the global asset node we need a self-join.
         if ($recursive) {
             $query->join('LEFT', '#__assets AS b ON b.lft <= a.lft AND b.rgt >= a.rgt')->order('b.lft');
         }
         // Execute the query and load the rules from the result.
         $db->setQuery($query);
         $result = $db->loadColumn();
         // Get the root even if the asset is not found and in recursive mode
         if (empty($result)) {
             $db = JFactory::getDbo();
             $assets = JTable::getInstance('Asset', 'JTable', array('dbo' => $db));
             $rootId = $assets->getRootId();
             $query->clear()->select('rules')->from('#__assets')->where('id = ' . $db->quote($rootId));
             $db->setQuery($query);
             $result = $db->loadResult();
             $result = array($result);
         }
         // Instantiate and return the JAccessRules object for the asset rules.
         $rules = new JAccessRules();
         $rules->mergeCollection($result);
         JDEBUG ? $_PROFILER->mark('Finish JAccess::getAssetRules Old (' . $asset . ')') : null;
         return $rules;
     }
 }
Exemple #19
0
 /**
  * Render the module.
  *
  * @param   object  $module   A module object.
  * @param   array   $attribs  An array of attributes for the module (probably from the XML).
  *
  * @return  string  The HTML content of the module output.
  *
  * @since   11.1
  */
 public static function renderModule($module, $attribs = array())
 {
     static $chrome;
     if (constant('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('beforeRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     $option = JRequest::getCmd('option');
     $app = JFactory::getApplication();
     // Record the scope.
     $scope = $app->scope;
     // Set scope to component name
     $app->scope = $module->module;
     // Get module parameters
     $params = new JRegistry();
     $params->loadString($module->params);
     // Get module path
     $module->module = preg_replace('/[^A-Z0-9_\\.-]/i', '', $module->module);
     $path = JPATH_BASE . '/modules/' . $module->module . '/' . $module->module . '.php';
     // Load the module
     if (!$module->user && file_exists($path)) {
         $lang = JFactory::getLanguage();
         // 1.5 or Core then 1.6 3PD
         $lang->load($module->module, JPATH_BASE, null, false, false) || $lang->load($module->module, dirname($path), null, false, false) || $lang->load($module->module, JPATH_BASE, $lang->getDefault(), false, false) || $lang->load($module->module, dirname($path), $lang->getDefault(), false, false);
         $content = '';
         ob_start();
         require $path;
         $module->content = ob_get_contents() . $content;
         ob_end_clean();
     }
     // Load the module chrome functions
     if (!$chrome) {
         $chrome = array();
     }
     require_once JPATH_THEMES . '/system/html/modules.php';
     $chromePath = JPATH_THEMES . '/' . $app->getTemplate() . '/html/modules.php';
     if (!isset($chrome[$chromePath])) {
         if (file_exists($chromePath)) {
             require_once $chromePath;
         }
         $chrome[$chromePath] = true;
     }
     // Make sure a style is set
     if (!isset($attribs['style'])) {
         $attribs['style'] = 'none';
     }
     // Dynamically add outline style
     if (JRequest::getBool('tp') && JComponentHelper::getParams('com_templates')->get('template_positions_display')) {
         $attribs['style'] .= ' outline';
     }
     // Do 3rd party stuff to manipulate module content
     // onRenderModule is allowed to alter the $module, $attribs
     // and may return a boolean.
     // true=remove, any other value = keep.
     // $result holds an array of booleans, 1 from each plugin.
     // we ditch the module if any of them = true.
     $result = $app->triggerEvent('onRenderModule', array(&$module, &$attribs));
     if (array_search(true, $result, true) !== false) {
         return '';
     }
     foreach (explode(' ', $attribs['style']) as $style) {
         $chromeMethod = 'modChrome_' . $style;
         // Apply chrome and render module
         if (function_exists($chromeMethod)) {
             $module->style = $attribs['style'];
             ob_start();
             $chromeMethod($module, $params, $attribs);
             $module->content = ob_get_contents();
             ob_end_clean();
         }
     }
     //revert the scope
     $app->scope = $scope;
     if (constant('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('afterRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     return $module->content;
 }
 /**
  * Render the component.
  *
  * @param   string  $option  The component option.
  * @param   array   $params  The component parameters
  *
  * @return  string
  *
  * @since   1.5
  * @throws  Exception
  */
 public static function renderComponent($option, $params = array())
 {
     $app = JFactory::getApplication();
     // Load template language files.
     $template = $app->getTemplate(true)->template;
     $lang = JFactory::getLanguage();
     $lang->load('tpl_' . $template, JPATH_BASE, null, false, true) || $lang->load('tpl_' . $template, JPATH_THEMES . "/{$template}", null, false, true);
     if (empty($option)) {
         throw new Exception(JText::_('JLIB_APPLICATION_ERROR_COMPONENT_NOT_FOUND'), 404);
     }
     if (JDEBUG) {
         JProfiler::getInstance('Application')->mark('beforeRenderComponent ' . $option);
     }
     // Record the scope
     $scope = $app->scope;
     // Set scope to component name
     $app->scope = $option;
     // Build the component path.
     $option = preg_replace('/[^A-Z0-9_\\.-]/i', '', $option);
     $file = substr($option, 4);
     // Define component path.
     if (!defined('JPATH_COMPONENT')) {
         define('JPATH_COMPONENT', JPATH_BASE . '/components/' . $option);
     }
     if (!defined('JPATH_COMPONENT_SITE')) {
         define('JPATH_COMPONENT_SITE', JPATH_SITE . '/components/' . $option);
     }
     if (!defined('JPATH_COMPONENT_ADMINISTRATOR')) {
         define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_ADMINISTRATOR . '/components/' . $option);
     }
     $path = JPATH_COMPONENT . '/' . $file . '.php';
     // If component is disabled throw error
     if (!static::isEnabled($option) || !file_exists($path)) {
         throw new Exception(JText::_('JLIB_APPLICATION_ERROR_COMPONENT_NOT_FOUND'), 404);
     }
     // Load common and local language files.
     $lang->load($option, JPATH_BASE, null, false, true) || $lang->load($option, JPATH_COMPONENT, null, false, true);
     // Handle template preview outlining.
     $contents = null;
     // Execute the component.
     $contents = static::executeComponent($path);
     // Revert the scope
     $app->scope = $scope;
     if (JDEBUG) {
         JProfiler::getInstance('Application')->mark('afterRenderComponent ' . $option);
     }
     return $contents;
 }
Exemple #21
0
 /**
  * Display logged queries.
  *
  * @return  string
  *
  * @since   2.5
  */
 protected function displayQueries()
 {
     $db = JFactory::getDbo();
     $log = $db->getLog();
     if (!$log) {
         return null;
     }
     $timings = $db->getTimings();
     $callStacks = $db->getCallStacks();
     $db->setDebug(false);
     $selectQueryTypeTicker = array();
     $otherQueryTypeTicker = array();
     $timing = array();
     $maxtime = 0;
     if (isset($timings[0])) {
         $startTime = $timings[0];
         $endTime = $timings[count($timings) - 1];
         $totalBargraphTime = $endTime - $startTime;
         if ($totalBargraphTime > 0) {
             foreach ($log as $id => $query) {
                 if (isset($timings[$id * 2 + 1])) {
                     // Compute the query time: $timing[$k] = array( queryTime, timeBetweenQueries ).
                     $timing[$id] = array(($timings[$id * 2 + 1] - $timings[$id * 2]) * 1000, $id > 0 ? ($timings[$id * 2] - $timings[$id * 2 - 1]) * 1000 : 0);
                     $maxtime = max($maxtime, $timing[$id]['0']);
                 }
             }
         }
     } else {
         $startTime = null;
         $totalBargraphTime = 1;
     }
     $bars = array();
     $info = array();
     $totalQueryTime = 0;
     $duplicates = array();
     foreach ($log as $id => $query) {
         $did = md5($query);
         if (!isset($duplicates[$did])) {
             $duplicates[$did] = array();
         }
         $duplicates[$did][] = $id;
         if ($timings && isset($timings[$id * 2 + 1])) {
             // Compute the query time.
             $queryTime = ($timings[$id * 2 + 1] - $timings[$id * 2]) * 1000;
             $totalQueryTime += $queryTime;
             // Run an EXPLAIN EXTENDED query on the SQL query if possible.
             $hasWarnings = false;
             $hasWarningsInProfile = false;
             if (isset($this->explains[$id])) {
                 $explain = $this->tableToHtml($this->explains[$id], $hasWarnings);
             } else {
                 $explain = JText::sprintf('PLG_DEBUG_QUERY_EXPLAIN_NOT_POSSIBLE', htmlspecialchars($query));
             }
             // Run a SHOW PROFILE query.
             $profile = '';
             if (in_array($db->name, array('mysqli', 'mysql', 'pdomysql'))) {
                 if (isset($this->sqlShowProfileEach[$id])) {
                     $profileTable = $this->sqlShowProfileEach[$id];
                     $profile = $this->tableToHtml($profileTable, $hasWarningsInProfile);
                 }
             }
             // How heavy should the string length count: 0 - 1.
             $ratio = 0.5;
             $timeScore = $queryTime / ((strlen($query) + 1) * $ratio) * 200;
             // Determine color of bargraph depending on query speed and presence of warnings in EXPLAIN.
             if ($timeScore > 10) {
                 $barClass = 'bar-danger';
                 $labelClass = 'label-important';
             } elseif ($hasWarnings || $timeScore > 5) {
                 $barClass = 'bar-warning';
                 $labelClass = 'label-warning';
             } else {
                 $barClass = 'bar-success';
                 $labelClass = 'label-success';
             }
             // Computes bargraph as follows: Position begin and end of the bar relatively to whole execution time.
             $prevBar = $id && isset($bars[$id - 1]) ? $bars[$id - 1] : 0;
             $barPre = round($timing[$id][1] / ($totalBargraphTime * 10), 4);
             $barWidth = round($timing[$id][0] / ($totalBargraphTime * 10), 4);
             $minWidth = 0.3;
             if ($barWidth < $minWidth) {
                 $barPre -= $minWidth - $barWidth;
                 if ($barPre < 0) {
                     $minWidth += $barPre;
                     $barPre = 0;
                 }
                 $barWidth = $minWidth;
             }
             $bars[$id] = (object) array('class' => $barClass, 'width' => $barWidth, 'pre' => $barPre, 'tip' => sprintf('%.2f&nbsp;ms', $queryTime));
             $info[$id] = (object) array('class' => $labelClass, 'explain' => $explain, 'profile' => $profile, 'hasWarnings' => $hasWarnings);
         }
     }
     // Remove single queries from $duplicates.
     $total_duplicates = 0;
     foreach ($duplicates as $did => $dups) {
         if (count($dups) < 2) {
             unset($duplicates[$did]);
         } else {
             $total_duplicates += count($dups);
         }
     }
     // Fix first bar width.
     $minWidth = 0.3;
     if ($bars[0]->width < $minWidth && isset($bars[1])) {
         $bars[1]->pre -= $minWidth - $bars[0]->width;
         if ($bars[1]->pre < 0) {
             $minWidth += $bars[1]->pre;
             $bars[1]->pre = 0;
         }
         $bars[0]->width = $minWidth;
     }
     $memoryUsageNow = memory_get_usage();
     $list = array();
     foreach ($log as $id => $query) {
         // Start query type ticker additions.
         $fromStart = stripos($query, 'from');
         $whereStart = stripos($query, 'where', $fromStart);
         if ($whereStart === false) {
             $whereStart = stripos($query, 'order by', $fromStart);
         }
         if ($whereStart === false) {
             $whereStart = strlen($query) - 1;
         }
         $fromString = substr($query, 0, $whereStart);
         $fromString = str_replace("\t", " ", $fromString);
         $fromString = str_replace("\n", " ", $fromString);
         $fromString = trim($fromString);
         // Initialise the select/other query type counts the first time.
         if (!isset($selectQueryTypeTicker[$fromString])) {
             $selectQueryTypeTicker[$fromString] = 0;
         }
         if (!isset($otherQueryTypeTicker[$fromString])) {
             $otherQueryTypeTicker[$fromString] = 0;
         }
         // Increment the count.
         if (stripos($query, 'select') === 0) {
             $selectQueryTypeTicker[$fromString] = $selectQueryTypeTicker[$fromString] + 1;
             unset($otherQueryTypeTicker[$fromString]);
         } else {
             $otherQueryTypeTicker[$fromString] = $otherQueryTypeTicker[$fromString] + 1;
             unset($selectQueryTypeTicker[$fromString]);
         }
         $text = $this->highlightQuery($query);
         if ($timings && isset($timings[$id * 2 + 1])) {
             // Compute the query time.
             $queryTime = ($timings[$id * 2 + 1] - $timings[$id * 2]) * 1000;
             // Timing
             // Formats the output for the query time with EXPLAIN query results as tooltip:
             $htmlTiming = '<div style="margin: 0px 0 5px;"><span class="dbg-query-time">';
             $htmlTiming .= JText::sprintf('PLG_DEBUG_QUERY_TIME', sprintf('<span class="label %s">%.2f&nbsp;ms</span>', $info[$id]->class, $timing[$id]['0']));
             if ($timing[$id]['1']) {
                 $htmlTiming .= ' ' . JText::sprintf('PLG_DEBUG_QUERY_AFTER_LAST', sprintf('<span class="label label-default">%.2f&nbsp;ms</span>', $timing[$id]['1']));
             }
             $htmlTiming .= '</span>';
             if (isset($callStacks[$id][0]['memory'])) {
                 $memoryUsed = $callStacks[$id][0]['memory'][1] - $callStacks[$id][0]['memory'][0];
                 $memoryBeforeQuery = $callStacks[$id][0]['memory'][0];
                 // Determine colour of query memory usage.
                 if ($memoryUsed > 0.1 * $memoryUsageNow) {
                     $labelClass = 'label-important';
                 } elseif ($memoryUsed > 0.05 * $memoryUsageNow) {
                     $labelClass = 'label-warning';
                 } else {
                     $labelClass = 'label-success';
                 }
                 $htmlTiming .= ' ' . '<span class="dbg-query-memory">' . JText::sprintf('PLG_DEBUG_MEMORY_USED_FOR_QUERY', sprintf('<span class="label ' . $labelClass . '">%.3f&nbsp;MB</span>', $memoryUsed / 1048576), sprintf('<span class="label label-default">%.3f&nbsp;MB</span>', $memoryBeforeQuery / 1048576)) . '</span>';
                 if ($callStacks[$id][0]['memory'][2] !== null) {
                     // Determine colour of number or results.
                     $resultsReturned = $callStacks[$id][0]['memory'][2];
                     if ($resultsReturned > 3000) {
                         $labelClass = 'label-important';
                     } elseif ($resultsReturned > 1000) {
                         $labelClass = 'label-warning';
                     } elseif ($resultsReturned == 0) {
                         $labelClass = '';
                     } else {
                         $labelClass = 'label-success';
                     }
                     $htmlResultsReturned = '<span class="label ' . $labelClass . '">' . (int) $resultsReturned . '</span>';
                     $htmlTiming .= ' <span class="dbg-query-rowsnumber">' . JText::sprintf('PLG_DEBUG_ROWS_RETURNED_BY_QUERY', $htmlResultsReturned) . '</span>';
                 }
             }
             $htmlTiming .= '</div>';
             // Bar.
             $htmlBar = $this->renderBars($bars, 'query', $id);
             // Profile query.
             $title = JText::_('PLG_DEBUG_PROFILE');
             if (!$info[$id]->profile) {
                 $title = '<span class="dbg-noprofile">' . $title . '</span>';
             }
             $htmlProfile = $info[$id]->profile ? $info[$id]->profile : JText::_('PLG_DEBUG_NO_PROFILE');
             // Backtrace and call stack.
             $htmlCallStack = '';
             if (isset($callStacks[$id])) {
                 $htmlCallStackElements = array();
                 foreach ($callStacks[$id] as $functionCall) {
                     if (isset($functionCall['file']) && isset($functionCall['line']) && strpos($functionCall['file'], '/libraries/joomla/database/') === false) {
                         $htmlFile = htmlspecialchars($functionCall['file']);
                         $htmlLine = htmlspecialchars($functionCall['line']);
                         $htmlCallStackElements[] = '<span class="dbg-log-called-from">' . $this->formatLink($htmlFile, $htmlLine) . '</span>';
                     }
                 }
                 $htmlCallStack = '<div class="dbg-query-table"><div>' . implode('</div><div>', $htmlCallStackElements) . '</div></div>';
                 if (!$this->linkFormat) {
                     $htmlCallStack .= '<div>[<a href="http://xdebug.org/docs/all_settings#file_link_format" target="_blank">';
                     $htmlCallStack .= JText::_('PLG_DEBUG_LINK_FORMAT') . '</a>]</div>';
                 }
             }
             $htmlAccordions = JHtml::_('bootstrap.startAccordion', 'dbg_query_' . $id, array('active' => $info[$id]->hasWarnings ? 'dbg_query_explain_' . $id : ''));
             $htmlAccordions .= JHtml::_('bootstrap.addSlide', 'dbg_query_' . $id, JText::_('PLG_DEBUG_EXPLAIN'), 'dbg_query_explain_' . $id) . $info[$id]->explain . JHtml::_('bootstrap.endSlide');
             $htmlAccordions .= JHtml::_('bootstrap.addSlide', 'dbg_query_' . $id, $title, 'dbg_query_profile_' . $id) . $htmlProfile . JHtml::_('bootstrap.endSlide');
             if ($htmlCallStack) {
                 $htmlAccordions .= JHtml::_('bootstrap.addSlide', 'dbg_query_' . $id, JText::_('PLG_DEBUG_CALL_STACK'), 'dbg_query_callstack_' . $id) . $htmlCallStack . JHtml::_('bootstrap.endSlide');
             }
             $htmlAccordions .= JHtml::_('bootstrap.endAccordion');
             $did = md5($query);
             if (isset($duplicates[$did])) {
                 $dups = array();
                 foreach ($duplicates[$did] as $dup) {
                     if ($dup != $id) {
                         $dups[] = '<a href="#dbg-query-' . ($dup + 1) . '">#' . ($dup + 1) . '</a>';
                     }
                 }
                 $htmlQuery = '<div class="alert alert-error">' . JText::_('PLG_DEBUG_QUERY_DUPLICATES') . ': ' . implode('&nbsp; ', $dups) . '</div>' . '<pre class="alert hasTooltip" title="' . JHtml::tooltipText('PLG_DEBUG_QUERY_DUPLICATES_FOUND') . '">' . $text . '</pre>';
             } else {
                 $htmlQuery = '<pre>' . $text . '</pre>';
             }
             $list[] = '<a name="dbg-query-' . ($id + 1) . '"></a>' . $htmlTiming . $htmlBar . $htmlQuery . $htmlAccordions;
         } else {
             $list[] = '<pre>' . $text . '</pre>';
         }
     }
     $totalTime = 0;
     foreach (JProfiler::getInstance('Application')->getMarks() as $mark) {
         $totalTime += $mark->time;
     }
     if ($totalQueryTime > $totalTime * 0.25) {
         $labelClass = 'label-important';
     } elseif ($totalQueryTime < $totalTime * 0.15) {
         $labelClass = 'label-success';
     } else {
         $labelClass = 'label-warning';
     }
     if ($this->totalQueries == 0) {
         $this->totalQueries = $db->getCount();
     }
     $html = array();
     $html[] = '<h4>' . JText::sprintf('PLG_DEBUG_QUERIES_LOGGED', $this->totalQueries) . sprintf(' <span class="label ' . $labelClass . '">%.1f&nbsp;ms</span>', $totalQueryTime) . '</h4><br />';
     if ($total_duplicates) {
         $html[] = '<div class="alert alert-error">' . '<h4>' . JText::sprintf('PLG_DEBUG_QUERY_DUPLICATES_TOTAL_NUMBER', $total_duplicates) . '</h4>';
         foreach ($duplicates as $dups) {
             $links = array();
             foreach ($dups as $dup) {
                 $links[] = '<a href="#dbg-query-' . ($dup + 1) . '">#' . ($dup + 1) . '</a>';
             }
             $html[] = '<div>' . JText::sprintf('PLG_DEBUG_QUERY_DUPLICATES_NUMBER', count($links)) . ': ' . implode('&nbsp; ', $links) . '</div>';
         }
         $html[] = '</div>';
     }
     $html[] = '<ol><li>' . implode('<hr /></li><li>', $list) . '<hr /></li></ol>';
     if (!$this->params->get('query_types', 1)) {
         return implode('', $html);
     }
     // Get the totals for the query types.
     $totalSelectQueryTypes = count($selectQueryTypeTicker);
     $totalOtherQueryTypes = count($otherQueryTypeTicker);
     $totalQueryTypes = $totalSelectQueryTypes + $totalOtherQueryTypes;
     $html[] = '<h4>' . JText::sprintf('PLG_DEBUG_QUERY_TYPES_LOGGED', $totalQueryTypes) . '</h4>';
     if ($totalSelectQueryTypes) {
         $html[] = '<h5>' . JText::_('PLG_DEBUG_SELECT_QUERIES') . '</h5>';
         arsort($selectQueryTypeTicker);
         $list = array();
         foreach ($selectQueryTypeTicker as $query => $occurrences) {
             $list[] = '<pre>' . JText::sprintf('PLG_DEBUG_QUERY_TYPE_AND_OCCURRENCES', $this->highlightQuery($query), $occurrences) . '</pre>';
         }
         $html[] = '<ol><li>' . implode('</li><li>', $list) . '</li></ol>';
     }
     if ($totalOtherQueryTypes) {
         $html[] = '<h5>' . JText::_('PLG_DEBUG_OTHER_QUERIES') . '</h5>';
         arsort($otherQueryTypeTicker);
         $list = array();
         foreach ($otherQueryTypeTicker as $query => $occurrences) {
             $list[] = '<pre>' . JText::sprintf('PLG_DEBUG_QUERY_TYPE_AND_OCCURRENCES', $this->highlightQuery($query), $occurrences) . '</pre>';
         }
         $html[] = '<ol><li>' . implode('</li><li>', $list) . '</li></ol>';
     }
     return implode('', $html);
 }
Exemple #22
0
function KunenaParseRoute($segments) {
	$profiler = JProfiler::getInstance('Application');
	KUNENA_PROFILER ? $profiler->mark('kunenaRoute') : null;
	$starttime = $profiler->getmicrotime();

	// Get current menu item and get query variables from it
	$active = JFactory::getApplication()->getMenu ()->getActive ();
	$vars = isset ( $active->query ) ? $active->query : array ('view'=>'home');
	if (empty($vars['view']) || $vars['view']=='home' || $vars['view']=='entrypage') {
		$vars['view'] = '';
	}

	// Fix bug in Joomla 1.5 when using /components/kunena instead /component/kunena
	if (!$active && $segments[0] == 'kunena') array_shift ( $segments );

	// Enable SEF category feature
	$sefcats = KunenaRoute::$config->sefcats && isset(KunenaRouter::$sefviews[$vars['view']]) && empty($vars ['id']);

	// Handle all segments
	while ( ($segment = array_shift ( $segments )) !== null ) {
		$seg = explode ( ':', $segment );
		$var = array_shift ( $seg );
		$value = array_shift ( $seg );

		if (is_numeric ( $var )) {
			$value = (int) $var;
			if ($vars['view'] == 'user') {
				$var = 'userid';
			} else {
				// Numeric variable is always catid or id
				if (empty($vars ['catid'])
					|| (empty($vars ['id']) && KunenaForumCategoryHelper::get($value)->exists() && KunenaForumTopicHelper::get($value)->category_id != $vars ['catid'])) {
					// First numbers are always categories
					// FIXME: what if $topic->catid == catid
					$var = 'catid';
					$vars ['view'] = 'category';
				} elseif (empty($vars ['id'])) {
					// Next number is always topic
					$var = 'id';
					$vars ['view'] = 'topic';
					$sefcats = false;
				} elseif (empty($vars ['mesid'])) {
					// Next number is always message
					$var = 'mesid';
					$vars ['view'] = 'topic';
				} else {
					// Invalid parameter, skip it
					continue;
				}
			}
		} elseif (empty ( $var ) && empty ( $value )) {
			// Empty parameter, skip it
			continue;
		} elseif ($sefcats && (($value !== null && ! isset ( KunenaRouter::$parsevars[$var] ))
		|| ($value === null && ! isset ( KunenaRouter::$views[$var] ) && ! isset ( KunenaRouter::$layouts[$var] ) && ! isset ( KunenaRouter::$functions[$var] )))) {
			// We have SEF category: translate category name into catid=123
			// TODO: cache filtered values to gain some speed -- I would like to start using category names instead of catids if it gets fast enough
			$var = 'catid';
			$value = -1;
			$catname = strtr ( $segment, ':', '-' );
			$categories = empty($vars ['catid']) ? KunenaForumCategoryHelper::getCategories() : KunenaForumCategoryHelper::getChildren($vars ['catid']);
			foreach ( $categories as $category ) {
				if ($catname == KunenaRouter::filterOutput ( $category->name ) || $catname == JFilterOutput::stringURLSafe ( $category->name )) {
					$value = (int) $category->id;
					break;
				}
			}
			$vars ['view'] = 'category';
		} elseif ($value === null) {
			// Variable must be either view or layout
			$sefcats = false;
			$value = $var;
			if (empty($vars ['view']) || ($value=='topic' && $vars ['view'] == 'category')) {
				$var = 'view';
			} elseif (empty($vars ['layout'])) {
				$var = 'layout';
			} else {
				// Unknown parameter: continue
				if (!empty($vars ['view'])) continue;
				// Oops: unknown view or non-existing category
				$var = 'view';
			}
		}
		$vars [$var] = $value;
	}
	if (empty($vars ['layout'])) $vars ['layout'] = 'default';
	KunenaRouter::$time = $profiler->getmicrotime() - $starttime;
	return $vars;
}
Exemple #23
0
 /**
  * Main setup routine for displaying the form/detail view
  *
  * @param   string $tpl template
  *
  * @return  void
  */
 public function display($tpl = null)
 {
     $profiler = JProfiler::getInstance('Application');
     $input = $this->app->input;
     $w = new FabrikWorker();
     /** @var FabrikFEModelForm $model */
     $model = $this->getModel('form');
     if (!$model) {
         // Dodgy URL - can't find the form name see https://github.com/Fabrik/fabrik/issues/1248
         return;
     }
     $model->isMambot = $this->isMambot;
     $form = $model->getForm();
     if ($model->render() === false) {
         return false;
     }
     $this->isMultiPage = $model->isMultiPage();
     list($this->plugintop, $this->pluginbottom, $this->pluginend) = $model->getFormPluginHTML();
     $listModel = $model->getlistModel();
     if (!$model->canPublish()) {
         if (!$this->app->isAdmin()) {
             echo FText::_('COM_FABRIK_FORM_NOT_PUBLISHED');
             return false;
         }
     }
     $this->rowid = $model->getRowId();
     $this->access = $model->checkAccessFromListSettings();
     if ($this->access == 0) {
         $this->app->enqueueMessage(FText::_('JERROR_ALERTNOAUTHOR'), 'error');
         return false;
     }
     JDEBUG ? $profiler->mark('form view before join group ids got') : null;
     if (!$listModel->noTable()) {
         $joins = $listModel->getJoins();
         $model->getJoinGroupIds($joins);
     }
     $params = $model->getParams();
     $this->setTitle($w, $params);
     $this->setCanonicalLink($model);
     FabrikHelperHTML::debug($params->get('note'), 'note');
     $params->def('icons', $this->app->get('icons'));
     $params->set('popup', $input->get('tmpl') == 'component' ? 1 : 0);
     $this->editable = $model->isEditable();
     $form->label = FText::_($model->getLabel());
     $form->intro = FText::_($model->getIntro());
     $form->outro = FText::_($model->getOutro());
     $form->action = $model->getAction();
     $form->class = $model->getFormClass();
     $form->formid = $model->isEditable() ? 'form_' . $model->getId() : 'details_' . $model->getId();
     $form->name = 'form_' . $model->getId();
     if ((string) $this->rowid !== '') {
         $form->formid .= '_' . $this->rowid;
     }
     $form->error = $form->error === '' ? FText::_('COM_FABRIK_FAILED_VALIDATION') : FText::_($form->error);
     if (!empty($model->formErrorMsg)) {
         $form->error .= '<br />' . $model->formErrorMsg;
     }
     $form->origerror = $form->error;
     $clearErrors = false;
     // Module rendered without ajax, we need to assign the session errors back into the model
     if ($model->isMambot) {
         $this->package = $this->app->getUserState('com_fabrik.package', 'fabrik');
         $context = 'com_' . $this->package . '.form.' . $form->id . '.' . $this->rowid . '.';
         $model->errors = $this->session->get($context . 'errors', array());
         $clearErrors = true;
     }
     $form->error = $model->hasErrors() ? $form->error : '';
     JDEBUG ? $profiler->mark('form view before validation classes loaded') : null;
     $tmpl = $model->getTmpl();
     $this->tmpl = $tmpl;
     $this->_addButtons();
     JDEBUG ? $profiler->mark('form view before group view got') : null;
     $this->groups = $model->getGroupView($tmpl);
     $btnData = new stdClass();
     $l = FabrikHelperHTML::getLayout('form.fabrik-repeat-group-delete');
     $this->removeRepeatGroupButton = $l->render($btnData);
     $l = FabrikHelperHTML::getLayout('form.fabrik-repeat-group-add');
     $this->addRepeatGroupButton = $l->render($btnData);
     JDEBUG ? $profiler->mark('form view after group view got') : null;
     $this->data = $model->tmplData;
     $this->params = $params;
     $this->tipLocation = $params->get('tiplocation');
     FabrikHelperHTML::debug($this->groups, 'form:view:groups');
     // Force front end templates
     $this->_basePath = COM_FABRIK_FRONTEND . '/views';
     $this->_addJavascript($listModel->getId());
     JDEBUG ? $profiler->mark('form view: after add js') : null;
     $this->_loadTmplBottom($form);
     JDEBUG ? $profiler->mark('form view: after tmpl bottom loaded') : null;
     $form->attribs = ' class="' . $form->class . '" name="' . $form->name . '" id="' . $form->formid . '" enctype="' . $model->getFormEncType() . '"';
     $this->form = $form;
     JDEBUG ? $profiler->mark('form view: form assigned as ref') : null;
     $list = new stdClass();
     $list->id = $form->record_in_database ? $model->getListModel()->getTable()->id : 0;
     $this->list = $list;
     JDEBUG ? $profiler->mark('form view: before getRelatedTables()') : null;
     $this->linkedTables = $model->getRelatedTables();
     JDEBUG ? $profiler->mark('form view: after getRelatedTables()') : null;
     $this->setMessage();
     $jTmplFolder = FabrikWorker::j3() ? 'tmpl' : 'tmpl25';
     $folder = $model->isEditable() ? 'form' : 'details';
     $this->addTemplatePath($this->_basePath . '/' . $folder . '/' . $jTmplFolder . '/' . $tmpl);
     $root = $this->app->isAdmin() ? JPATH_ADMINISTRATOR : JPATH_SITE;
     $this->addTemplatePath($root . '/templates/' . $this->app->getTemplate() . '/html/com_fabrik/' . $folder . '/' . $tmpl);
     // If rendered as a module (non ajax) and we have inserted the session errors, clear them from the session.
     if ($clearErrors) {
         $model->clearErrors();
     }
     JDEBUG ? $profiler->mark('form view before template load') : null;
 }
 /**
  * Render the module.
  *
  * @param   object  $module   A module object.
  * @param   array   $attribs  An array of attributes for the module (probably from the XML).
  *
  * @return  string  The HTML content of the module output.
  *
  * @since   11.1
  */
 public static function renderModule($module, $attribs = array())
 {
     static $chrome;
     if (constant('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('beforeRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     $app = JFactory::getApplication();
     // Record the scope.
     $scope = $app->scope;
     // Set scope to component name
     $app->scope = $module->module;
     // Get module parameters
     $params = new JRegistry();
     $params->loadString($module->params);
     // Get module path
     $module->module = preg_replace('/[^A-Z0-9_\\.-]/i', '', $module->module);
     $path = JPATH_BASE . '/modules/' . $module->module . '/' . $module->module . '.php';
     // Load the module
     // $module->user is a check for 1.0 custom modules and is deprecated refactoring
     if (empty($module->user) && file_exists($path)) {
         $lang = JFactory::getLanguage();
         // 1.5 or Core then 1.6 3PD
         $lang->load($module->module, JPATH_BASE, null, false, true) || $lang->load($module->module, dirname($path), null, false, true);
         $content = '';
         ob_start();
         include $path;
         $module->content = ob_get_contents() . $content;
         ob_end_clean();
     }
     // Load the module chrome functions
     if (!$chrome) {
         $chrome = array();
     }
     include_once JPATH_THEMES . '/system/html/modules.php';
     $chromePath = JPATH_THEMES . '/' . $app->getTemplate() . '/html/modules.php';
     if (!isset($chrome[$chromePath])) {
         if (file_exists($chromePath)) {
             // Read module chrome function name from definition file
             if (preg_match_all('/function\\s+(modChrome_[a-z0-9_]+)/i', file_get_contents($chromePath), $matches, PREG_SET_ORDER)) {
                 $module_chrome_loaded = false;
                 // Make sure module chrome is loaded only 1 time
                 foreach ($matches as $match) {
                     if (function_exists($match[1])) {
                         $module_chrome_loaded = true;
                         break;
                     }
                 }
                 // Include module chrome definition file
                 if (!$module_chrome_loaded) {
                     include_once $chromePath;
                 }
             }
         }
         $chrome[$chromePath] = true;
     }
     /* Trigger onJSNTPLRenderModule to overide Chrome module */
     if (!file_exists($chromePath)) {
         $result = $app->triggerEvent('onJSNTPLRenderModule', array(&$module, &$attribs));
         if (!is_array($result)) {
             $result = array($result);
         }
         if (array_search(true, $result, true) !== false) {
             return '';
         }
         $chrome[$chromePath] = true;
     }
     /* Trigger onJSNTPLRenderModule to overide Chrome module */
     // Make sure a style is set
     if (!isset($attribs['style'])) {
         $attribs['style'] = 'none';
     }
     // Dynamically add outline style
     if (JRequest::getBool('tp') && JComponentHelper::getParams('com_templates')->get('template_positions_display')) {
         $attribs['style'] .= ' outline';
     }
     foreach (explode(' ', $attribs['style']) as $style) {
         $chromeMethod = 'modChrome_' . $style;
         // Apply chrome and render module
         if (function_exists($chromeMethod)) {
             $module->style = $attribs['style'];
             ob_start();
             $chromeMethod($module, $params, $attribs);
             $module->content = ob_get_contents();
             ob_end_clean();
         }
     }
     //revert the scope
     $app->scope = $scope;
     if (constant('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('afterRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     return $module->content;
 }
Exemple #25
0
 /**
  * Process the form
  * Inline edit save routed here (not in raw)
  *
  * @return  null
  */
 public function process()
 {
     $profiler = JProfiler::getInstance('Application');
     JDEBUG ? $profiler->mark('controller process: start') : null;
     $app = JFactory::getApplication();
     $package = $app->getUserState('com_fabrik.package', 'fabrik');
     $input = $app->input;
     if ($input->get('format', '') == 'raw') {
         error_reporting(error_reporting() ^ (E_WARNING | E_NOTICE));
     }
     $viewName = $input->get('view', 'form');
     $view = $this->getView($viewName, JFactory::getDocument()->getType());
     if ($model = $this->getModel('form', 'FabrikFEModel')) {
         $view->setModel($model, true);
     }
     $model->setId($input->getInt('formid', 0));
     $model->packageId = $input->getInt('packageId');
     $this->isMambot = $input->get('isMambot', 0);
     $form = $model->getForm();
     $model->rowId = $input->get('rowid', '', 'string');
     /**
      * $$$ hugh - need this in plugin manager to be able to treat a "Copy" form submission
      * as 'new' for purposes of running plugins.  Rob's comment in model process() seems to
      * indicate that origRowId was for this purposes, but it doesn't work, 'cos always has a value.
      */
     if ($input->get('Copy', 'no') !== 'no') {
         $model->copyingRow(true);
     }
     // Check for request forgeries
     if ($model->spoofCheck()) {
         JSession::checkToken() or die('Invalid Token');
     }
     JDEBUG ? $profiler->mark('controller process validate: start') : null;
     if (!$model->validate()) {
         $this->handleError($view, $model);
         return;
     }
     JDEBUG ? $profiler->mark('controller process validate: end') : null;
     // Reset errors as validate() now returns ok validations as empty arrays
     $model->clearErrors();
     try {
         $model->process();
     } catch (Exception $e) {
         $model->errors['process_error'] = true;
         JError::raiseWarning(500, $e->getMessage());
     }
     if ($input->getInt('elid', 0) !== 0) {
         // Inline edit show the edited element - ignores validations for now
         $inlineModel = $this->getModel('forminlineedit', 'FabrikFEModel');
         $inlineModel->setFormModel($model);
         echo $inlineModel->showResults();
         return;
     }
     // Check if any plugin has created a new validation error
     if ($model->hasErrors()) {
         FabrikWorker::getPluginManager()->runPlugins('onError', $model);
         $this->handleError($view, $model);
         return;
     }
     /**
      * If debug submit is requested (&fabrikdebug=2, and J! debug on, and Fabrik debug allowed),
      * bypass any and all redirects, so we can see the profile for the submit
      */
     if (FabrikHelperHTML::isDebugSubmit()) {
         return;
     }
     $listModel = $model->getListModel();
     $listModel->set('_table', null);
     $url = $this->getRedirectURL($model);
     $msg = $this->getRedirectMessage($model);
     // @todo -should get handed off to the json view to do this
     if ($input->getInt('fabrik_ajax') == 1) {
         // $$$ hugh - adding some options for what to do with redirect when in content plugin
         // Should probably do this elsewhere, but for now ...
         $redirect_opts = array('msg' => $msg, 'url' => $url, 'baseRedirect' => $this->baseRedirect, 'rowid' => $input->get('rowid', '', 'string'), 'suppressMsg' => !$model->showSuccessMsg());
         if (!$this->baseRedirect && $this->isMambot) {
             $session = JFactory::getSession();
             $context = $model->getRedirectContext();
             $redirect_opts['redirect_how'] = $session->get($context . 'redirect_content_how', 'popup');
             $redirect_opts['width'] = (int) $session->get($context . 'redirect_content_popup_width', '300');
             $redirect_opts['height'] = (int) $session->get($context . 'redirect_content_popup_height', '300');
             $redirect_opts['x_offset'] = (int) $session->get($context . 'redirect_content_popup_x_offset', '0');
             $redirect_opts['y_offset'] = (int) $session->get($context . 'redirect_content_popup_y_offset', '0');
             $redirect_opts['title'] = $session->get($context . 'redirect_content_popup_title', '');
             $redirect_opts['reset_form'] = $session->get($context . 'redirect_content_reset_form', '1') == '1';
         } elseif (!$this->baseRedirect && !$this->isMambot) {
             /**
              * $$$ hugh - I think this case only happens when we're a popup form from a list
              * in which case I don't think "popup" is realy a valid option.  Anyway, need to set something,
              * so for now just do the same as we do for isMambot, but default redirect_how to 'samepage'
              */
             $session = JFactory::getSession();
             $context = $model->getRedirectContext();
             $redirect_opts['redirect_how'] = $session->get($context . 'redirect_content_how', 'samepage');
             $redirect_opts['width'] = (int) $session->get($context . 'redirect_content_popup_width', '300');
             $redirect_opts['height'] = (int) $session->get($context . 'redirect_content_popup_height', '300');
             $redirect_opts['x_offset'] = (int) $session->get($context . 'redirect_content_popup_x_offset', '0');
             $redirect_opts['y_offset'] = (int) $session->get($context . 'redirect_content_popup_y_offset', '0');
             $redirect_opts['title'] = $session->get($context . 'redirect_content_popup_title', '');
             $redirect_opts['reset_form'] = $session->get($context . 'redirect_content_reset_form', '1') == '1';
         } elseif ($this->isMambot) {
             // $$$ hugh - special case to allow custom code to specify that
             // the form should not be cleared after a failed AJAX submit
             $session = JFactory::getSession();
             $context = 'com_fabrik.form.' . $model->get('id') . '.redirect.';
             $redirect_opts['reset_form'] = $session->get($context . 'redirect_content_reset_form', '1') == '1';
         }
         // Let form.js handle the redirect logic
         echo json_encode($redirect_opts);
         // Stop require.js being added to output
         exit;
     }
     if ($input->get('format') == 'raw') {
         $input->set('view', 'list');
         $this->display();
         return;
     } else {
         // If no msg, set to null, so J! doesn't create an empty "Message" area
         if (empty($msg)) {
             $msg = null;
         }
         $this->setRedirect($url, $msg);
     }
 }
Exemple #26
0
 /**
  * Render the module.
  *
  * @param   object  $module   A module object.
  * @param   array   $attribs  An array of attributes for the module (probably from the XML).
  *
  * @return  string  The HTML content of the module output.
  *
  * @since   1.5
  */
 public static function renderModule($module, $attribs = array())
 {
     static $chrome;
     // Check that $module is a valid module object
     if (!is_object($module) || !isset($module->module) || !isset($module->params)) {
         if (defined('JDEBUG') && JDEBUG) {
             JLog::addLogger(array('text_file' => 'jmodulehelper.log.php'), JLog::ALL, array('modulehelper'));
             JLog::add('JModuleHelper::renderModule($module) expects a module object', JLog::DEBUG, 'modulehelper');
         }
         return;
     }
     if (defined('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('beforeRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     $app = JFactory::getApplication();
     // Record the scope.
     $scope = $app->scope;
     // Set scope to component name
     $app->scope = $module->module;
     // Get module parameters
     $params = new JRegistry();
     $params->loadString($module->params);
     // Get the template
     $template = $app->getTemplate();
     // Get module path
     $module->module = preg_replace('/[^A-Z0-9_\\.-]/i', '', $module->module);
     $path = JPATH_BASE . '/modules/' . $module->module . '/' . $module->module . '.php';
     // Load the module
     if (file_exists($path)) {
         $lang = JFactory::getLanguage();
         // 1.5 or Core then 1.6 3PD
         $lang->load($module->module, JPATH_BASE, null, false, true) || $lang->load($module->module, dirname($path), null, false, true);
         $content = '';
         ob_start();
         include $path;
         $module->content = ob_get_contents() . $content;
         ob_end_clean();
     }
     // Load the module chrome functions
     if (!$chrome) {
         $chrome = array();
     }
     include_once JPATH_THEMES . '/system/html/modules.php';
     $chromePath = JPATH_THEMES . '/' . $template . '/html/modules.php';
     if (!isset($chrome[$chromePath])) {
         if (file_exists($chromePath)) {
             include_once $chromePath;
         }
         $chrome[$chromePath] = true;
     }
     // Check if the current module has a style param to override template module style
     $paramsChromeStyle = $params->get('style');
     if ($paramsChromeStyle) {
         $attribs['style'] = preg_replace('/^(system|' . $template . ')\\-/i', '', $paramsChromeStyle);
     }
     // Make sure a style is set
     if (!isset($attribs['style'])) {
         $attribs['style'] = 'none';
     }
     // Dynamically add outline style
     if ($app->input->getBool('tp') && JComponentHelper::getParams('com_templates')->get('template_positions_display')) {
         $attribs['style'] .= ' outline';
     }
     foreach (explode(' ', $attribs['style']) as $style) {
         $chromeMethod = 'modChrome_' . $style;
         // Apply chrome and render module
         if (function_exists($chromeMethod)) {
             $module->style = $attribs['style'];
             ob_start();
             $chromeMethod($module, $params, $attribs);
             $module->content = ob_get_contents();
             ob_end_clean();
         }
     }
     // Revert the scope
     $app->scope = $scope;
     if (defined('JDEBUG')) {
         JProfiler::getInstance('Application')->mark('afterRenderModule ' . $module->module . ' (' . $module->title . ')');
     }
     return $module->content;
 }
Exemple #27
0
<?php

/**
 * @package ᅧ Gantry Template Framework - RocketTheme
 * @version ᅧ 1.1 November 11, 2011
 * @author ᅧ ᅧRocketTheme http://www.rockettheme.com
 * @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC
 * @license ᅧ http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
 *
 * Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system
 *
 */
// no direct access
defined('_JEXEC') or die('Restricted index access');
// load and inititialize gantry class
jimport('joomla.error.profiler');
$profile = JProfiler::getInstance('Gantry Global Init');
$profile->mark('Start');
require_once 'lib/gantry/gantry.php';
$gantry->init();
$profile->mark('Stop');
$gantry->finalize();
             $ids .= (int) $items[$i]->pid . ',';
             $pks .= (int) $items[$i]->pk . ',';
         }
         $ids = substr($ids, 0, -1);
         $pks = substr($pks, 0, -1);
     }
     $config['ids'] = $ids;
     $config['pks'] = $pks;
 }
 // Pagination
 if ($limitstart != -1 && $limitend > 0 && !($preconfig['limit2'] > 0)) {
     $items = array_splice($items, $limitstart, $limitend);
 }
 // -------- -------- -------- -------- -------- -------- -------- -------- // Do List
 if ($doDebug) {
     $profiler = JProfiler::getInstance();
 }
 if ($preconfig['show_list']) {
     $config['infinite'] = $isInfinite;
     $target = 'search';
     if (isset($preconfig['search2']) && $preconfig['search2'] != '') {
         $target = 'search2';
         $search2 = CCK_List::getSearch($preconfig['search2'], $id);
         $search->content = $search2->content;
     }
     if ($total) {
         if (isset($preconfig['idx'])) {
             $config['idx'] = $preconfig['idx'];
             if (!isset($app->cck_idx)) {
                 $app->cck_idx = array();
             }
    //$currentlang = current($langActive);
    $registry = JFactory::getConfig();
    $deflang = $registry->getValue("config.defaultlang");
    JFactory::getApplication()->redirect(JRoute::_("index.php?lang=" . $deflang));
    JError::raiseError('0', JText::_('NOT AUTHORISED') . ' ' . $curLanguage->getTag());
    exit;
}
$db->_profile("langmod");
$db->_profile("langlayout", true);
if (JDEBUG) {
    $_PROFILER = JProfiler::getInstance('Application');
    $_PROFILER->mark('lang mod start');
}
require $layout;
if (JDEBUG) {
    $_PROFILER = JProfiler::getInstance('Application');
    $_PROFILER->mark('lang mod end');
}
$db->_profile("langlayout");
$version = new JoomFishVersion();
?>
<!--JoomFish <?php 
echo $version->getVersion();
?>
-->
<!-- <?php 
echo $version->getCopyright();
?>
 Think Network, released under the GPL. -->
<!-- More information: at http://www.joomfish.net -->
 /**
  * Method to get the indexer state.
  *
  * @return  object  The indexer state object.
  *
  * @since   2.5
  */
 public static function getState()
 {
     // First, try to load from the internal state.
     if (!empty(self::$state)) {
         return self::$state;
     }
     // If we couldn't load from the internal state, try the session.
     $session = JFactory::getSession();
     $data = $session->get('_finder.state', null);
     // If the state is empty, load the values for the first time.
     if (empty($data)) {
         $data = new JObject();
         // Load the default configuration options.
         $data->options = JComponentHelper::getParams('com_finder');
         // Setup the weight lookup information.
         $data->weights = array(self::TITLE_CONTEXT => round($data->options->get('title_multiplier', 1.7), 2), self::TEXT_CONTEXT => round($data->options->get('text_multiplier', 0.7), 2), self::META_CONTEXT => round($data->options->get('meta_multiplier', 1.2), 2), self::PATH_CONTEXT => round($data->options->get('path_multiplier', 2.0), 2), self::MISC_CONTEXT => round($data->options->get('misc_multiplier', 0.3), 2));
         // Set the current time as the start time.
         $data->startTime = JFactory::getDate()->toSql();
         // Set the remaining default values.
         $data->batchSize = (int) $data->options->get('batch_size', 50);
         $data->batchOffset = 0;
         $data->totalItems = 0;
         $data->pluginState = array();
     }
     // Setup the profiler if debugging is enabled.
     if (JFactory::getApplication()->get('debug')) {
         self::$profiler = JProfiler::getInstance('FinderIndexer');
     }
     // Setup the stemmer.
     if ($data->options->get('stem', 1) && $data->options->get('stemmer', 'porter_en')) {
         FinderIndexerHelper::$stemmer = FinderIndexerStemmer::getInstance($data->options->get('stemmer', 'porter_en'));
     }
     // Set the state.
     self::$state = $data;
     return self::$state;
 }