コード例 #1
0
ファイル: ExceptionHandler.php プロジェクト: bossrabbit/piwik
 private static function getErrorResponse(Exception $ex)
 {
     $debugTrace = $ex->getTraceAsString();
     $message = $ex->getMessage();
     if (!method_exists($ex, 'isHtmlMessage') || !$ex->isHtmlMessage()) {
         $message = Common::sanitizeInputValue($message);
     }
     $logo = new CustomLogo();
     $logoHeaderUrl = false;
     $logoFaviconUrl = false;
     try {
         $logoHeaderUrl = $logo->getHeaderLogoUrl();
         $logoFaviconUrl = $logo->getPathUserFavicon();
     } catch (Exception $ex) {
         Log::debug($ex);
     }
     $result = Piwik_GetErrorMessagePage($message, $debugTrace, true, true, $logoHeaderUrl, $logoFaviconUrl);
     /**
      * Triggered before a Piwik error page is displayed to the user.
      *
      * This event can be used to modify the content of the error page that is displayed when
      * an exception is caught.
      *
      * @param string &$result The HTML of the error page.
      * @param Exception $ex The Exception displayed in the error page.
      */
     Piwik::postEvent('FrontController.modifyErrorPage', array(&$result, $ex));
     return $result;
 }
コード例 #2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Set memory limit to off
     @ini_set('memory_limit', -1);
     Piwik::doAsSuperUser(function () use($input, $output) {
         $settings = new MigratorSettings();
         $settings->idSite = $input->getArgument('idSite');
         $settings->site = $this->getSite($settings->idSite);
         $settings->dateFrom = $input->getOption('date-from') ? new \DateTime($input->getOption('date-from')) : null;
         $settings->dateTo = $input->getOption('date-to') ? new \DateTime($input->getOption('date-to')) : null;
         $settings->skipArchiveData = $input->getOption('skip-archive-data');
         $settings->skipLogData = $input->getOption('skip-log-data');
         $config = Db::getDatabaseConfig();
         $startTime = microtime(true);
         $this->createTargetDatabaseConfig($input, $output, $config);
         $tmpConfig = $config;
         $sourceDb = Db::get();
         try {
             $targetDb = @Db\Adapter::factory($config['adapter'], $tmpConfig);
         } catch (\Exception $e) {
             throw new \RuntimeException('Unable to connect to the target database: ' . $e->getMessage(), 0, $e);
         }
         $sourceDbHelper = new DBHelper($sourceDb, Db::getDatabaseConfig());
         $migratorFacade = new Migrator($sourceDbHelper, new DBHelper($targetDb, $config), GCHelper::getInstance(), $settings, new ArchiveLister($sourceDbHelper));
         $migratorFacade->migrate();
         $endTime = microtime(true);
         Log::debug(sprintf('Time taken: %01.2f sec', $endTime - $startTime));
         Log::debug(sprintf('Peak memory usage: %01.2f MB', memory_get_peak_usage(true) / 1048576));
     });
 }
コード例 #3
0
ファイル: ComponentFactory.php プロジェクト: a4tunado/piwik
 /**
  * Create a component instance that exists within a specific plugin. Uses the component's
  * unqualified class name and expected base type.
  *
  * This method will only create a class if it is located within the component type's
  * associated subdirectory.
  *
  * @param string $pluginName The name of the plugin the component is expected to belong to,
  *                           eg, `'UserSettings'`.
  * @param string $componentClassSimpleName The component's class name w/o namespace, eg,
  *                                         `"GetKeywords"`.
  * @param string $componentTypeClass The fully qualified class name of the component type, eg,
  *                                   `"Piwik\Plugin\Report"`.
  * @return mixed|null A new instance of the desired component or null if not found. If the
  *                    plugin is not loaded or activated or the component is not located in
  *                    in the sub-namespace specified by `$componentTypeClass::COMPONENT_SUBNAMESPACE`,
  *                    this method will return null.
  */
 public static function factory($pluginName, $componentClassSimpleName, $componentTypeClass)
 {
     if (empty($pluginName) || empty($componentClassSimpleName)) {
         return null;
     }
     $pluginManager = PluginManager::getInstance();
     try {
         if (!$pluginManager->isPluginActivated($pluginName)) {
             return null;
         }
         $plugin = $pluginManager->getLoadedPlugin($pluginName);
     } catch (Exception $e) {
         Log::debug($e);
         return null;
     }
     $subnamespace = $componentTypeClass::COMPONENT_SUBNAMESPACE;
     $desiredComponentClass = 'Piwik\\Plugins\\' . $pluginName . '\\' . $subnamespace . '\\' . $componentClassSimpleName;
     $components = $plugin->findMultipleComponents($subnamespace, $componentTypeClass);
     foreach ($components as $class) {
         if ($class == $desiredComponentClass) {
             return new $class();
         }
     }
     return null;
 }
コード例 #4
0
 protected static function deleteArchivesWithPeriodRange(Date $date)
 {
     $numericTable = ArchiveTableCreator::getNumericTable($date);
     $blobTable = ArchiveTableCreator::getBlobTable($date);
     $yesterday = Date::factory('yesterday')->getDateTime();
     Log::debug("Purging Custom Range archives: done [ purged archives older than %s from %s / blob ]", $yesterday, $numericTable);
     self::getModel()->deleteArchivesWithPeriodRange($numericTable, $blobTable, Piwik::$idPeriods['range'], $yesterday);
 }
コード例 #5
0
 public function testConnection()
 {
     try {
         $this->connectIfNeeded();
         return 'TEST' === $this->redis->echo('TEST');
     } catch (\Exception $e) {
         Log::debug($e->getMessage());
     }
     return false;
 }
コード例 #6
0
ファイル: SystemTestCase.php プロジェクト: mgou-net/piwik
 public static function tearDownAfterClass()
 {
     Log::debug("Tearing down " . get_called_class());
     if (!isset(static::$fixture)) {
         $fixture = new Fixture();
     } else {
         $fixture = static::$fixture;
     }
     $fixture->performTearDown();
 }
コード例 #7
0
 public function migrate($siteId, \DateTime $from = null, \DateTime $to = null)
 {
     $archives = $this->archiveLister->getArchiveList($from, $to);
     foreach ($archives as $archiveDate) {
         Log::debug('Migrating archive ' . $archiveDate);
         $this->migrateArchive($archiveDate, 'archive_numeric_' . $archiveDate, $siteId);
         try {
             $this->migrateArchive($archiveDate, 'archive_blob_' . $archiveDate, $siteId);
         } catch (\Exception $e) {
             // blob tables can be missing
         }
     }
 }
コード例 #8
0
ファイル: ArchivePurger.php プロジェクト: a4tunado/piwik
 protected static function deleteArchivesWithPeriodRange(Date $date)
 {
     $query = "DELETE FROM %s WHERE period = ? AND ts_archived < ?";
     $yesterday = Date::factory('yesterday')->getDateTime();
     $bind = array(Piwik::$idPeriods['range'], $yesterday);
     $numericTable = ArchiveTableCreator::getNumericTable($date);
     Db::query(sprintf($query, $numericTable), $bind);
     Log::debug("Purging Custom Range archives: done [ purged archives older than %s from %s / blob ]", $yesterday, $numericTable);
     try {
         Db::query(sprintf($query, ArchiveTableCreator::getBlobTable($date)), $bind);
     } catch (Exception $e) {
         // Individual blob tables could be missing
     }
 }
コード例 #9
0
 private static function getErrorResponse(Exception $ex)
 {
     $debugTrace = $ex->getTraceAsString();
     $message = $ex->getMessage();
     $isHtmlMessage = method_exists($ex, 'isHtmlMessage') && $ex->isHtmlMessage();
     if (!$isHtmlMessage && Request::isApiRequest($_GET)) {
         $outputFormat = strtolower(Common::getRequestVar('format', 'xml', 'string', $_GET + $_POST));
         $response = new ResponseBuilder($outputFormat);
         return $response->getResponseException($ex);
     } elseif (!$isHtmlMessage) {
         $message = Common::sanitizeInputValue($message);
     }
     $logo = new CustomLogo();
     $logoHeaderUrl = false;
     $logoFaviconUrl = false;
     try {
         $logoHeaderUrl = $logo->getHeaderLogoUrl();
         $logoFaviconUrl = $logo->getPathUserFavicon();
     } catch (Exception $ex) {
         try {
             Log::debug($ex);
         } catch (\Exception $otherEx) {
             // DI container may not be setup at this point
         }
     }
     $result = Piwik_GetErrorMessagePage($message, $debugTrace, true, true, $logoHeaderUrl, $logoFaviconUrl);
     try {
         /**
          * Triggered before a Piwik error page is displayed to the user.
          *
          * This event can be used to modify the content of the error page that is displayed when
          * an exception is caught.
          *
          * @param string &$result The HTML of the error page.
          * @param Exception $ex The Exception displayed in the error page.
          */
         Piwik::postEvent('FrontController.modifyErrorPage', array(&$result, $ex));
     } catch (ContainerDoesNotExistException $ex) {
         // this can happen when an error occurs before the Piwik environment is created
     }
     return $result;
 }
コード例 #10
0
 /**
  * Computes the total number of unique visitors who visited at least one site in,
  * a set of sites and the number of unique visitors that visited all of the sites
  * in the set.
  *
  * Comparison is done in dates for the UTC time, not for the site specific time.
  *
  * Performance: The SQL query this method executes was tested on a Piwik instance
  *              with 13 million visits total. Computing data for 4 sites with no
  *              date limit took 13s to complete.
  *
  * @param int[] $idSites The IDs of the sites for whom unique visitor counts should be
  *                       computed.
  * @param Date $startDate The lower bound of the date range of the visits to check.
  * @param Date $endDate The upper bound of the date range of the visits to check.
  * @param Segment $segment An optional segment to apply to the visits set before aggregation.
  *                         To supply no segment, use `new Segment()`.
  * @return int[] Returns two metrics: **nb_total_visitors** and **nb_shared_visitors**.
  *
  *               **nb_total_visitors** is the total number of unique visitors who visited
  *               at least one site in the list.
  *
  *               **nb_shared_visitors** is the total number of unique visitors who visited
  *               every site in the list.
  * @throws Exception if less than 2 site IDs are supplied,
  */
 public function getCommonVisitorCount($idSites, Date $startDate, Date $endDate, Segment $segment)
 {
     Log::debug("%s::%s('%s', '%s', '%s', '%s') called", "Model\\DistinctMetricsAggregator", __FUNCTION__, $idSites, $startDate, $endDate, $segment);
     if (count($idSites) == 1) {
         throw new Exception(Piwik::translate('InterSites_PleasSupplyAtLeastTwoDifferentSites'));
     }
     $select = "config_id, COUNT(DISTINCT idsite) AS sitecount";
     $from = array('log_visit');
     $where = 'visit_last_action_time >= ? AND visit_last_action_time <= ? AND idsite IN (' . Common::getSqlStringFieldsArray($idSites) . ')';
     $orderBy = false;
     $groupBy = 'config_id';
     $startDateTime = new \DateTime($startDate->toString());
     $endDateTime = new \DateTime($endDate->toString());
     $bind = array_merge(array($startDateTime->format("Y-m-d 00:00:00"), $endDateTime->format("Y-m-d 23:59:59")), $idSites);
     $innerQuery = $segment->getSelectQuery($select, $from, $where, $bind, $orderBy, $groupBy);
     $wholeQuery = "SELECT COUNT(sitecount_by_config.config_id) AS nb_total_visitors,\n                              SUM(IF(sitecount_by_config.sitecount >= " . count($idSites) . ", 1, 0)) AS nb_shared_visitors\n                         FROM ( {$innerQuery['sql']} ) AS sitecount_by_config";
     $result = Db::fetchRow($wholeQuery, $innerQuery['bind']);
     // nb_shared_visitors can be NULL if there are no visits
     if ($result['nb_shared_visitors'] === null) {
         $result['nb_shared_visitors'] = 0;
     }
     Log::debug("%s::%s() returned '%s'", "Model\\DistinctMetricsAggregator", __FUNCTION__, $result);
     return $result;
 }
コード例 #11
0
ファイル: Manager.php プロジェクト: 962464/piwik
 /**
  * Install loaded plugins
  *
  * @throws
  * @return array Error messages of plugin install fails
  */
 public function installLoadedPlugins()
 {
     Log::debug("Loaded plugins: " . implode(", ", array_keys($this->getLoadedPlugins())));
     $messages = array();
     foreach ($this->getLoadedPlugins() as $plugin) {
         try {
             $this->installPluginIfNecessary($plugin);
         } catch (\Exception $e) {
             $messages[] = $e->getMessage();
         }
     }
     return $messages;
 }
コード例 #12
0
ファイル: Fixture.php プロジェクト: igorclark/piwik
 public static function loadAllPlugins($testEnvironment = null, $testCaseClass = false, $extraPluginsToLoad = array())
 {
     if (empty($testEnvironment)) {
         $testEnvironment = new Piwik_TestingEnvironment();
     }
     DbHelper::createTables();
     $pluginsManager = \Piwik\Plugin\Manager::getInstance();
     $plugins = $testEnvironment->getCoreAndSupportedPlugins();
     // make sure the plugin that executed this method is included in the plugins to load
     $extraPlugins = array_merge($extraPluginsToLoad, array(\Piwik\Plugin::getPluginNameFromBacktrace(debug_backtrace()), \Piwik\Plugin::getPluginNameFromNamespace($testCaseClass), \Piwik\Plugin::getPluginNameFromNamespace(get_called_class())));
     foreach ($extraPlugins as $pluginName) {
         if (empty($pluginName)) {
             continue;
         }
         if (in_array($pluginName, $plugins)) {
             continue;
         }
         $plugins[] = $pluginName;
         if ($testEnvironment) {
             $testEnvironment->pluginsToLoad = array_merge($testEnvironment->pluginsToLoad ?: array(), array($pluginName));
         }
     }
     Log::debug("Plugins to load during tests: " . implode(', ', $plugins));
     $pluginsManager->loadPlugins($plugins);
 }
コード例 #13
0
ファイル: Db.php プロジェクト: FluentDevelopment/piwik
 private static function logSql($functionName, $sql, $parameters = array())
 {
     if (self::$logQueries === false || @Config::getInstance()->Debug['log_sql_queries'] != 1) {
         return;
     }
     // NOTE: at the moment we don't log parameters in order to avoid sensitive information leaks
     Log::debug("Db::%s() executing SQL: %s", $functionName, $sql);
 }
コード例 #14
0
ファイル: View.php プロジェクト: diosmosis/piwik
 protected function renderTwigTemplate()
 {
     try {
         $output = $this->twig->render($this->getTemplateFile(), $this->getTemplateVars());
     } catch (Exception $ex) {
         // twig does not rethrow exceptions, it wraps them so we log the cause if we can find it
         $cause = $ex->getPrevious();
         Log::debug($cause === null ? $ex : $cause);
         throw $ex;
     }
     $output = $this->applyFilter_cacheBuster($output);
     $helper = new Theme();
     $output = $helper->rewriteAssetsPathToTheme($output);
     return $output;
 }
コード例 #15
0
ファイル: Request.php プロジェクト: josl/CGE-File-Sharing
 /**
  * Dispatches the API request to the appropriate API method and returns the result
  * after post-processing.
  *
  * Post-processing includes:
  *
  * - flattening if **flat** is 0
  * - running generic filters unless **disable_generic_filters** is set to 1
  * - URL decoding label column values
  * - running queued filters unless **disable_queued_filters** is set to 1
  * - removing columns based on the values of the **hideColumns** and **showColumns** query parameters
  * - filtering rows if the **label** query parameter is set
  * - converting the result to the appropriate format (ie, XML, JSON, etc.)
  *
  * If `'original'` is supplied for the output format, the result is returned as a PHP
  * object.
  *
  * @throws PluginDeactivatedException if the module plugin is not activated.
  * @throws Exception if the requested API method cannot be called, if required parameters for the
  *                   API method are missing or if the API method throws an exception and the **format**
  *                   query parameter is **original**.
  * @return DataTable|Map|string The data resulting from the API call.
  */
 public function process()
 {
     // read the format requested for the output data
     $outputFormat = strtolower(Common::getRequestVar('format', 'xml', 'string', $this->request));
     // create the response
     $response = new ResponseBuilder($outputFormat, $this->request);
     $corsHandler = new CORSHandler();
     $corsHandler->handle();
     try {
         // read parameters
         $moduleMethod = Common::getRequestVar('method', null, 'string', $this->request);
         list($module, $method) = $this->extractModuleAndMethod($moduleMethod);
         $module = $this->renameModule($module);
         if (!\Piwik\Plugin\Manager::getInstance()->isPluginActivated($module)) {
             throw new PluginDeactivatedException($module);
         }
         $apiClassName = $this->getClassNameAPI($module);
         self::reloadAuthUsingTokenAuth($this->request);
         // call the method
         $returnedValue = Proxy::getInstance()->call($apiClassName, $method, $this->request);
         $toReturn = $response->getResponse($returnedValue, $module, $method);
     } catch (Exception $e) {
         Log::debug($e);
         $toReturn = $response->getResponseException($e);
     }
     return $toReturn;
 }
コード例 #16
0
ファイル: Rules.php プロジェクト: diosmosis/piwik
 public static function isArchivingDisabledFor(array $idSites, Segment $segment, $periodLabel)
 {
     $generalConfig = Config::getInstance()->General;
     if ($periodLabel == 'range') {
         if (!isset($generalConfig['archiving_range_force_on_browser_request']) || $generalConfig['archiving_range_force_on_browser_request'] != false) {
             return false;
         }
         Log::debug("Not forcing archiving for range period.");
         $processOneReportOnly = false;
     } else {
         $processOneReportOnly = !self::shouldProcessReportsAllPlugins($idSites, $segment, $periodLabel);
     }
     $isArchivingEnabled = self::isRequestAuthorizedToArchive() && !self::$archivingDisabledByTests;
     if ($processOneReportOnly) {
         // When there is a segment, we disable archiving when browser_archiving_disabled_enforce applies
         if (!$segment->isEmpty() && !$isArchivingEnabled && !self::isBrowserArchivingAvailableForSegments() && !SettingsServer::isArchivePhpTriggered()) {
             Log::debug("Archiving is disabled because of config setting browser_archiving_disabled_enforce=1");
             return true;
         }
         // Always allow processing one report
         return false;
     }
     return !$isArchivingEnabled;
 }
コード例 #17
0
 /**
  * Instantiates the Archiver class in each plugin that defines it,
  * and triggers Aggregation processing on these plugins.
  */
 public function callAggregateAllPlugins($visits, $visitsConverted)
 {
     Log::debug("PluginsArchiver::%s: Initializing archiving process for all plugins [visits = %s, visits converted = %s]", __FUNCTION__, $visits, $visitsConverted);
     $this->archiveProcessor->setNumberOfVisits($visits, $visitsConverted);
     $archivers = $this->getPluginArchivers();
     foreach ($archivers as $pluginName => $archiverClass) {
         // We clean up below all tables created during this function call (and recursive calls)
         $latestUsedTableId = Manager::getInstance()->getMostRecentTableId();
         /** @var Archiver $archiver */
         $archiver = new $archiverClass($this->archiveProcessor);
         if (!$archiver->isEnabled()) {
             Log::debug("PluginsArchiver::%s: Skipping archiving for plugin '%s'.", __FUNCTION__, $pluginName);
             continue;
         }
         if ($this->shouldProcessReportsForPlugin($pluginName)) {
             $this->logAggregator->setQueryOriginHint($pluginName);
             try {
                 $timer = new Timer();
                 if ($this->isSingleSiteDayArchive) {
                     Log::debug("PluginsArchiver::%s: Archiving day reports for plugin '%s'.", __FUNCTION__, $pluginName);
                     $archiver->aggregateDayReport();
                 } else {
                     Log::debug("PluginsArchiver::%s: Archiving period reports for plugin '%s'.", __FUNCTION__, $pluginName);
                     $archiver->aggregateMultipleReports();
                 }
                 $this->logAggregator->setQueryOriginHint('');
                 Log::debug("PluginsArchiver::%s: %s while archiving %s reports for plugin '%s'.", __FUNCTION__, $timer->getMemoryLeak(), $this->params->getPeriod()->getLabel(), $pluginName);
             } catch (Exception $e) {
                 $className = get_class($e);
                 $exception = new $className($e->getMessage() . " - caused by plugin {$pluginName}", $e->getCode(), $e);
                 throw $exception;
             }
         } else {
             Log::debug("PluginsArchiver::%s: Not archiving reports for plugin '%s'.", __FUNCTION__, $pluginName);
         }
         Manager::getInstance()->deleteAll($latestUsedTableId);
         unset($archiver);
     }
 }
コード例 #18
0
 /**
  * @param string $function
  * @param string $pluginName
  * @return null|\Piwik\Plugin
  */
 private static function getActivatedPlugin($function, $pluginName)
 {
     $pluginManager = PluginManager::getInstance();
     try {
         if (!$pluginManager->isPluginActivated($pluginName)) {
             Log::debug("ComponentFactory::%s: component for deactivated plugin ('%s') requested.", $function, $pluginName);
             return null;
         }
         return $pluginManager->getLoadedPlugin($pluginName);
     } catch (Exception $e) {
         Log::debug($e);
         return null;
     }
 }
コード例 #19
0
ファイル: PivotByDimension.php プロジェクト: bossrabbit/piwik
 private function fetchIntersectedWithThisBySegment(DataTable $table, $segmentValue)
 {
     $segmentStr = $this->thisReportDimensionSegment->getSegment() . "==" . urlencode($segmentValue);
     // TODO: segment + report API method query params should be stored in DataTable metadata so we don't have to access it here
     $originalSegment = Common::getRequestVar('segment', false);
     if (!empty($originalSegment)) {
         $segmentStr = $originalSegment . ';' . $segmentStr;
     }
     Log::debug("PivotByDimension: Fetching intersected with segment '%s'", $segmentStr);
     $params = array('segment' => $segmentStr) + $this->getRequestParamOverride($table);
     return $this->pivotDimensionReport->fetch($params);
 }
コード例 #20
0
ファイル: Common.php プロジェクト: emersonmatsumoto/piwik
 public static function printDebug($info = '')
 {
     if (isset($GLOBALS['PIWIK_TRACKER_DEBUG']) && $GLOBALS['PIWIK_TRACKER_DEBUG']) {
         if (is_object($info)) {
             $info = var_export($info, true);
         }
         Log::getInstance()->setLogLevel(Log::DEBUG);
         if (is_array($info) || is_object($info)) {
             $info = Common::sanitizeInputValues($info);
             $out = var_export($info, true);
             foreach (explode("\n", $out) as $line) {
                 Log::debug($line);
             }
         } else {
             foreach (explode("\n", $info) as $line) {
                 Log::debug(htmlspecialchars($line, ENT_QUOTES));
             }
         }
     }
 }
コード例 #21
0
 /**
  * Must be called before dispatch()
  * - checks that directories are writable,
  * - loads the configuration file,
  * - loads the plugin,
  * - inits the DB connection,
  * - etc.
  *
  * @throws Exception
  * @return void
  */
 public function init()
 {
     static $initialized = false;
     if ($initialized) {
         return;
     }
     $initialized = true;
     $tmpPath = StaticContainer::get('path.tmp');
     $directoriesToCheck = array($tmpPath, $tmpPath . '/assets/', $tmpPath . '/cache/', $tmpPath . '/logs/', $tmpPath . '/tcpdf/', $tmpPath . '/templates_c/');
     Filechecks::dieIfDirectoriesNotWritable($directoriesToCheck);
     $this->handleMaintenanceMode();
     $this->handleProfiler();
     $this->handleSSLRedirection();
     Plugin\Manager::getInstance()->loadPluginTranslations();
     Plugin\Manager::getInstance()->loadActivatedPlugins();
     // try to connect to the database
     try {
         Db::createDatabaseObject();
         Db::fetchAll("SELECT DATABASE()");
     } catch (Exception $exception) {
         if (self::shouldRethrowException()) {
             throw $exception;
         }
         Log::debug($exception);
         /**
          * Triggered when Piwik cannot connect to the database.
          *
          * This event can be used to start the installation process or to display a custom error
          * message.
          *
          * @param Exception $exception The exception thrown from creating and testing the database
          *                             connection.
          */
         Piwik::postEvent('Db.cannotConnectToDb', array($exception), $pending = true);
         throw $exception;
     }
     // try to get an option (to check if data can be queried)
     try {
         Option::get('TestingIfDatabaseConnectionWorked');
     } catch (Exception $exception) {
         if (self::shouldRethrowException()) {
             throw $exception;
         }
         Log::debug($exception);
         /**
          * Triggered when Piwik cannot access database data.
          *
          * This event can be used to start the installation process or to display a custom error
          * message.
          *
          * @param Exception $exception The exception thrown from trying to get an option value.
          */
         Piwik::postEvent('Config.badConfigurationFile', array($exception), $pending = true);
         throw $exception;
     }
     // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs
     Access::getInstance();
     /**
      * Triggered just after the platform is initialized and plugins are loaded.
      *
      * This event can be used to do early initialization.
      *
      * _Note: At this point the user is not authenticated yet._
      */
     Piwik::postEvent('Request.dispatchCoreAndPluginUpdatesScreen');
     $this->throwIfPiwikVersionIsOlderThanDBSchema();
     \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
     // ensure the current Piwik URL is known for later use
     if (method_exists('Piwik\\SettingsPiwik', 'getPiwikUrl')) {
         SettingsPiwik::getPiwikUrl();
     }
     /**
      * Triggered before the user is authenticated, when the global authentication object
      * should be created.
      *
      * Plugins that provide their own authentication implementation should use this event
      * to set the global authentication object (which must derive from {@link Piwik\Auth}).
      *
      * **Example**
      *
      *     Piwik::addAction('Request.initAuthenticationObject', function() {
      *         StaticContainer::getContainer()->set('Piwik\Auth', new MyAuthImplementation());
      *     });
      */
     Piwik::postEvent('Request.initAuthenticationObject');
     try {
         $authAdapter = StaticContainer::get('Piwik\\Auth');
     } catch (Exception $e) {
         $message = "Authentication object cannot be found in the container. Maybe the Login plugin is not activated?\n                        <br />You can activate the plugin by adding:<br />\n                        <code>Plugins[] = Login</code><br />\n                        under the <code>[Plugins]</code> section in your config/config.ini.php";
         $ex = new AuthenticationFailedException($message);
         $ex->setIsHtmlMessage();
         throw $ex;
     }
     Access::getInstance()->reloadAccess($authAdapter);
     // Force the auth to use the token_auth if specified, so that embed dashboard
     // and all other non widgetized controller methods works fine
     if (Common::getRequestVar('token_auth', false, 'string') !== false) {
         Request::reloadAuthUsingTokenAuth();
     }
     SettingsServer::raiseMemoryLimitIfNecessary();
     \Piwik\Plugin\Manager::getInstance()->postLoadPlugins();
     /**
      * Triggered after the platform is initialized and after the user has been authenticated, but
      * before the platform has handled the request.
      *
      * Piwik uses this event to check for updates to Piwik.
      */
     Piwik::postEvent('Platform.initialized');
 }
コード例 #22
0
ファイル: Profiler.php プロジェクト: bossrabbit/piwik
 /**
  * Log a breakdown by query
  *
  * @param array $infoIndexedByQuery
  */
 private static function getSqlProfilingQueryBreakdownOutput($infoIndexedByQuery)
 {
     $output = '<hr /><strong>Breakdown by query</strong><br/>';
     foreach ($infoIndexedByQuery as $query => $queryInfo) {
         $timeMs = round($queryInfo['sumTimeMs'], 1);
         $count = $queryInfo['count'];
         $avgTimeString = '';
         if ($count > 1) {
             $avgTimeMs = $timeMs / $count;
             $avgTimeString = " (average = <b>" . round($avgTimeMs, 1) . "ms</b>)";
         }
         $query = preg_replace('/([\\t\\n\\r ]+)/', ' ', $query);
         $output .= "Executed <b>{$count}</b> time" . ($count == 1 ? '' : 's') . " in <b>" . $timeMs . "ms</b> {$avgTimeString} <pre>\t{$query}</pre>";
     }
     Log::debug($output);
 }
コード例 #23
0
ファイル: Manager.php プロジェクト: mgou-net/piwik
 /**
  * Install loaded plugins
  *
  * @throws
  * @return array Error messages of plugin install fails
  */
 public function installLoadedPlugins()
 {
     Log::debug("Loaded plugins: " . implode(", ", array_keys($this->getLoadedPlugins())));
     foreach ($this->getLoadedPlugins() as $plugin) {
         $this->installPluginIfNecessary($plugin);
     }
 }
コード例 #24
0
ファイル: Config.php プロジェクト: polytan02/dev_piwik_ynh
 /**
  * Returns a list of {@link ServerInfo} instances describing the LDAP servers
  * that should be connected to.
  *
  * @return ServerInfo[]
  */
 public static function getConfiguredLdapServers()
 {
     $serverNameList = self::getServerNameList();
     if (empty($serverNameList)) {
         $server = ServerInfo::makeFromOldConfig();
         $serverHost = $server->getServerHostname();
         if (empty($serverHost)) {
             return array();
         } else {
             return array($server);
         }
     } else {
         if (is_string($serverNameList)) {
             $serverNameList = explode(',', $serverNameList);
         }
         $servers = array();
         foreach ($serverNameList as $name) {
             try {
                 $servers[] = ServerInfo::makeConfigured($name);
             } catch (Exception $ex) {
                 Log::debug("LoginLdap\\Config::%s: LDAP server info '%s' is configured incorrectly: %s", __FUNCTION__, $name, $ex->getMessage());
             }
         }
         return $servers;
     }
 }
コード例 #25
0
ファイル: Controller.php プロジェクト: TensorWrenchOSS/piwik
 /**
  * Password reset confirmation action. Finishes the password reset process.
  * Users visit this action from a link supplied in an email.
  */
 public function confirmResetPassword()
 {
     $errorMessage = null;
     $login = Common::getRequestVar('login', '');
     $resetToken = Common::getRequestVar('resetToken', '');
     try {
         $this->passwordResetter->confirmNewPassword($login, $resetToken);
     } catch (Exception $ex) {
         Log::debug($ex);
         $errorMessage = $ex->getMessage();
     }
     if (is_null($errorMessage)) {
         // if success, show login w/ success message
         // have to do this as super user since redirectToIndex checks if there's a default website ID for
         // the current user and if not, doesn't redirect to the requested action. TODO: this behavior is wrong. somehow.
         $self = $this;
         Access::doAsSuperUser(function () use($self) {
             $self->redirectToIndex(Piwik::getLoginPluginName(), 'resetPasswordSuccess');
         });
         return null;
     } else {
         // show login page w/ error. this will keep the token in the URL
         return $this->login($errorMessage);
     }
 }
コード例 #26
0
 protected function acquireLock()
 {
     $lockName = $this->getArchiveProcessorLockName();
     $result = Db::getDbLock($lockName, $maxRetries = 30);
     if (!$result) {
         Log::debug("SELECT GET_LOCK failed to acquire lock. Proceeding anyway.");
     }
 }
コード例 #27
0
ファイル: IntegrationTestCase.php プロジェクト: Abine/piwik
 /**
  * Drops all archive tables.
  */
 public static function deleteArchiveTables()
 {
     foreach (ArchiveTableCreator::getTablesArchivesInstalled() as $table) {
         Log::debug("Dropping table {$table}");
         Db::query("DROP TABLE IF EXISTS `{$table}`");
     }
     ArchiveTableCreator::refreshTableList($forceReload = true);
 }
コード例 #28
0
 public function logStatusDebug($isTemporary)
 {
     $temporary = 'definitive archive';
     if ($isTemporary) {
         $temporary = 'temporary archive';
     }
     Log::debug("%s archive, idSite = %d (%s), segment '%s', report = '%s', UTC datetime [%s -> %s]", $this->getPeriod()->getLabel(), $this->getSite()->getId(), $temporary, $this->getSegment()->getString(), $this->getRequestedPlugin(), $this->getDateStart()->getDateStartUTC(), $this->getDateEnd()->getDateEndUTC());
 }
コード例 #29
0
ファイル: Controller.php プロジェクト: signalshare/piwik
 /**
  * Password reset confirmation action. Finishes the password reset process.
  * Users visit this action from a link supplied in an email.
  */
 public function confirmResetPassword()
 {
     $errorMessage = null;
     $login = Common::getRequestVar('login', '');
     $resetToken = Common::getRequestVar('resetToken', '');
     try {
         $this->passwordResetter->confirmNewPassword($login, $resetToken);
     } catch (Exception $ex) {
         Log::debug($ex);
         $errorMessage = $ex->getMessage();
     }
     if (is_null($errorMessage)) {
         // if success, show login w/ success message
         return $this->resetPasswordSuccess();
     } else {
         // show login page w/ error. this will keep the token in the URL
         return $this->login($errorMessage);
     }
 }
コード例 #30
0
ファイル: Rules.php プロジェクト: josl/CGE-File-Sharing
 public static function isArchivingDisabledFor(array $idSites, Segment $segment, $periodLabel)
 {
     if ($periodLabel == 'range') {
         return false;
     }
     $processOneReportOnly = !self::shouldProcessReportsAllPlugins($idSites, $segment, $periodLabel);
     $isArchivingDisabled = !self::isRequestAuthorizedToArchive() || self::$archivingDisabledByTests;
     if ($processOneReportOnly) {
         // When there is a segment, we disable archiving when browser_archiving_disabled_enforce applies
         if (!$segment->isEmpty() && $isArchivingDisabled && Config::getInstance()->General['browser_archiving_disabled_enforce'] && !SettingsServer::isArchivePhpTriggered()) {
             Log::debug("Archiving is disabled because of config setting browser_archiving_disabled_enforce=1");
             return true;
         }
         // Always allow processing one report
         return false;
     }
     return $isArchivingDisabled;
 }