Exemplo n.º 1
1
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Replace this with dependency injection once available
     /** @var DiagnosticService $diagnosticService */
     $diagnosticService = StaticContainer::get('Piwik\\Plugins\\Diagnostics\\DiagnosticService');
     $showAll = $input->getOption('all');
     $report = $diagnosticService->runDiagnostics();
     foreach ($report->getAllResults() as $result) {
         $items = $result->getItems();
         if (!$showAll && $result->getStatus() === DiagnosticResult::STATUS_OK) {
             continue;
         }
         if (count($items) === 1) {
             $output->writeln($result->getLabel() . ': ' . $this->formatItem($items[0]), OutputInterface::OUTPUT_PLAIN);
             continue;
         }
         $output->writeln($result->getLabel() . ':');
         foreach ($items as $item) {
             $output->writeln("\t- " . $this->formatItem($item), OutputInterface::OUTPUT_PLAIN);
         }
     }
     if ($report->hasWarnings()) {
         $output->writeln(sprintf('<comment>%d warnings detected</comment>', $report->getWarningCount()));
     }
     if ($report->hasErrors()) {
         $output->writeln(sprintf('<error>%d errors detected</error>', $report->getErrorCount()));
         return 1;
     }
     return 0;
 }
 protected function configureSegments()
 {
     $idSite = Common::getRequestVar('idSite', 0, 'int');
     if (empty($idSite)) {
         return array();
     }
     $configuration = StaticContainer::get('Piwik\\Plugins\\CustomDimensions\\Dao\\Configuration');
     $dimensions = $configuration->getCustomDimensionsForSite($idSite);
     foreach ($dimensions as $dimension) {
         if (!$dimension['active']) {
             continue;
         }
         $segment = new Segment();
         $segment->setSegment(CustomDimensionsRequestProcessor::buildCustomDimensionTrackingApiName($dimension));
         $segment->setType(Segment::TYPE_DIMENSION);
         $segment->setName($dimension['name']);
         $columnName = LogTable::buildCustomDimensionColumnName($dimension);
         if ($dimension['scope'] === CustomDimensions::SCOPE_ACTION) {
             $segment->setSqlSegment('log_link_visit_action. ' . $columnName);
             $segment->setCategory('General_Actions');
             $segment->setSuggestedValuesCallback(function ($idSite, $maxValuesToReturn) use($dimension) {
                 $autoSuggest = new AutoSuggest();
                 return $autoSuggest->getMostUsedActionDimensionValues($dimension, $idSite, $maxValuesToReturn);
             });
         } elseif ($dimension['scope'] === CustomDimensions::SCOPE_VISIT) {
             $segment->setSqlSegment('log_visit. ' . $columnName);
             $segment->setCategory('General_Visit');
         } else {
             continue;
         }
         $this->addSegment($segment);
     }
 }
Exemplo n.º 3
0
 /**
  * Constructor.
  *
  * @param string|null $serverHostName The hostname of the LDAP server. If not null, an attempt
  *                                    to connect is made.
  * @param int $port The server port to use.
  * @throws Exception if a connection is attempted and it fails.
  */
 public function __construct($serverHostName = null, $port = ServerInfo::DEFAULT_LDAP_PORT, $timeout = self::DEFAULT_TIMEOUT_SECS, LoggerInterface $logger = null)
 {
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
     if (!empty($serverHostName)) {
         $this->connect($serverHostName, $port, $timeout);
     }
 }
 public function setUp()
 {
     parent::setUp();
     /** @var PluginManager $manager */
     $manager = StaticContainer::get('Piwik\\Plugin\\Manager');
     $manager->loadPlugins(array('Events', 'Contents'));
 }
Exemplo n.º 5
0
 /**
  * Constructor.
  *
  * @param string $name The persisted name of the setting.
  * @param mixed $defaultValue  Default value for this setting if no value was specified.
  * @param string $type Eg an array, int, ... see TYPE_* constants
  * @param string $pluginName The name of the plugin the setting belongs to
  * @param int $idSite The idSite this setting belongs to.
  */
 public function __construct($name, $defaultValue, $type, $pluginName, $idSite)
 {
     parent::__construct($name, $defaultValue, $type, $pluginName);
     $this->idSite = $idSite;
     $storageFactory = StaticContainer::get('Piwik\\Settings\\Storage\\Factory');
     $this->storage = $storageFactory->getMeasurableSettingsStorage($idSite, $this->pluginName);
 }
Exemplo n.º 6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = StaticContainer::get('path.tmp') . '/logs/';
     $cmd = sprintf('tail -f %s*.log', $path);
     $output->writeln('Executing command: ' . $cmd);
     passthru($cmd);
 }
Exemplo n.º 7
0
 public function hasKey($key)
 {
     if ($key === 'auth') {
         $key = 'Piwik\\Auth';
     }
     return StaticContainer::getContainer()->has($key);
 }
Exemplo n.º 8
0
 function init()
 {
     HTML_QuickForm2_Factory::registerRule('checkLogin', 'Piwik\\Plugins\\Installation\\Rule_isValidLoginString');
     HTML_QuickForm2_Factory::registerRule('checkEmail', 'Piwik\\Plugins\\Installation\\Rule_isValidEmailString');
     $login = $this->addElement('text', 'login')->setLabel(Piwik::translate('Installation_SuperUserLogin'));
     $login->addRule('required', Piwik::translate('General_Required', Piwik::translate('Installation_SuperUserLogin')));
     $login->addRule('checkLogin');
     $password = $this->addElement('password', 'password')->setLabel(Piwik::translate('Installation_Password'));
     $password->addRule('required', Piwik::translate('General_Required', Piwik::translate('Installation_Password')));
     $pwMinLen = UsersManager::PASSWORD_MIN_LENGTH;
     $pwLenInvalidMessage = Piwik::translate('UsersManager_ExceptionInvalidPassword', array($pwMinLen));
     $password->addRule('length', $pwLenInvalidMessage, array('min' => $pwMinLen));
     $passwordBis = $this->addElement('password', 'password_bis')->setLabel(Piwik::translate('Installation_PasswordRepeat'));
     $passwordBis->addRule('required', Piwik::translate('General_Required', Piwik::translate('Installation_PasswordRepeat')));
     $passwordBis->addRule('eq', Piwik::translate('Installation_PasswordDoNotMatch'), $password);
     $email = $this->addElement('text', 'email')->setLabel(Piwik::translate('Installation_Email'));
     $email->addRule('required', Piwik::translate('General_Required', Piwik::translate('Installation_Email')));
     $email->addRule('checkEmail', Piwik::translate('UsersManager_ExceptionInvalidEmail'));
     $this->addElement('checkbox', 'subscribe_newsletter_piwikorg', null, array('content' => '&nbsp;&nbsp;' . Piwik::translate('Installation_PiwikOrgNewsletter')));
     $professionalServicesNewsletter = Piwik::translate('Installation_ProfessionalServicesNewsletter', array("<a href='http://piwik.org/consulting/?pk_medium=App_Newsletter_link&pk_source=Piwik_App&pk_campaign=App_Installation' style='color:#444;' rel='noreferrer' target='_blank'>", "</a>"));
     $currentLanguage = StaticContainer::get('Piwik\\Translation\\Translator')->getCurrentLanguage();
     $this->addElement('checkbox', 'subscribe_newsletter_professionalservices', null, array('content' => '&nbsp;&nbsp;' . $professionalServicesNewsletter));
     $this->addElement('submit', 'submit', array('value' => Piwik::translate('General_Next') . ' »', 'class' => 'btn'));
     // default values
     $this->addDataSource(new HTML_QuickForm2_DataSource_Array(array('subscribe_newsletter_piwikorg' => 1, 'subscribe_newsletter_professionalservices' => $currentLanguage == 'de' ? 0 : 1)));
 }
Exemplo n.º 9
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $invalidator = StaticContainer::get('Piwik\\Archive\\ArchiveInvalidator');
     $cascade = $input->getOption('cascade');
     $dryRun = $input->getOption('dry-run');
     $sites = $this->getSitesToInvalidateFor($input);
     $periodTypes = $this->getPeriodTypesToInvalidateFor($input);
     $dateRanges = $this->getDateRangesToInvalidateFor($input);
     $segments = $this->getSegmentsToInvalidateFor($input, $sites);
     foreach ($periodTypes as $periodType) {
         foreach ($dateRanges as $dateRange) {
             foreach ($segments as $segment) {
                 $segmentStr = $segment ? $segment->getString() : '';
                 $output->writeln("Invalidating {$periodType} periods in {$dateRange} [segment = {$segmentStr}]...");
                 $dates = $this->getPeriodDates($periodType, $dateRange);
                 if ($dryRun) {
                     $output->writeln("[Dry-run] invalidating archives for site = [ " . implode(', ', $sites) . " ], dates = [ " . implode(', ', $dates) . " ], period = [ {$periodType} ], segment = [ " . "{$segmentStr} ], cascade = [ " . (int) $cascade . " ]");
                 } else {
                     $invalidationResult = $invalidator->markArchivesAsInvalidated($sites, $dates, $periodType, $segment, $cascade);
                     if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
                         $output->writeln($invalidationResult->makeOutputLogs());
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 10
0
 public static function configure(WidgetConfig $config)
 {
     $config->setCategoryId('About Piwik');
     $config->setName('ProfessionalServices_WidgetProfessionalServicesForPiwik');
     $advertising = StaticContainer::get('Piwik\\ProfessionalServices\\Advertising');
     $config->setIsEnabled($advertising->areAdsForProfessionalServicesEnabled());
 }
Exemplo n.º 11
0
 public function initAuthenticationObject($activateCookieAuth = false)
 {
     $auth = new Auth();
     StaticContainer::getContainer()->set('Piwik\\Auth', $auth);
     $login = new Login();
     return $login->initAuthenticationFromCookie($auth, $activateCookieAuth);
 }
Exemplo n.º 12
0
 /**
  * Performs a batch insert into a specific table using either LOAD DATA INFILE or plain INSERTs,
  * as a fallback. On MySQL, LOAD DATA INFILE is 20x faster than a series of plain INSERTs.
  *
  * @param string $tableName PREFIXED table name! you must call Common::prefixTable() before passing the table name
  * @param array $fields array of unquoted field names
  * @param array $values array of data to be inserted
  * @param bool $throwException Whether to throw an exception that was caught while trying
  *                                LOAD DATA INFILE, or not.
  * @throws Exception
  * @return bool  True if the bulk LOAD was used, false if we fallback to plain INSERTs
  */
 public static function tableInsertBatch($tableName, $fields, $values, $throwException = false)
 {
     $filePath = StaticContainer::get('path.tmp') . '/assets/' . $tableName . '-' . Common::generateUniqId() . '.csv';
     $loadDataInfileEnabled = Config::getInstance()->General['enable_load_data_infile'];
     if ($loadDataInfileEnabled && Db::get()->hasBulkLoader()) {
         try {
             $fileSpec = array('delim' => "\t", 'quote' => '"', 'escape' => '\\\\', 'escapespecial_cb' => function ($str) {
                 return str_replace(array(chr(92), chr(34)), array(chr(92) . chr(92), chr(92) . chr(34)), $str);
             }, 'eol' => "\r\n", 'null' => 'NULL');
             // hack for charset mismatch
             if (!DbHelper::isDatabaseConnectionUTF8() && !isset(Config::getInstance()->database['charset'])) {
                 $fileSpec['charset'] = 'latin1';
             }
             self::createCSVFile($filePath, $fileSpec, $values);
             if (!is_readable($filePath)) {
                 throw new Exception("File {$filePath} could not be read.");
             }
             $rc = self::createTableFromCSVFile($tableName, $fields, $filePath, $fileSpec);
             if ($rc) {
                 unlink($filePath);
                 return true;
             }
         } catch (Exception $e) {
             if ($throwException) {
                 throw $e;
             }
         }
     }
     // if all else fails, fallback to a series of INSERTs
     @unlink($filePath);
     self::tableInsertBatchIterate($tableName, $fields, $values);
     return false;
 }
Exemplo n.º 13
0
 public function __construct()
 {
     $this->requestProcessors = StaticContainer::get('tracker.request.processors');
     $this->visitorRecognizer = StaticContainer::get('Piwik\\Tracker\\VisitorRecognizer');
     $this->visitProperties = null;
     $this->userSettings = StaticContainer::get('Piwik\\Tracker\\Settings');
 }
Exemplo n.º 14
0
 public function test_removeFile_shouldRemoveFile()
 {
     $tmpFile = StaticContainer::get('path.tmp') . '/filesystem-test-file';
     touch($tmpFile);
     Filesystem::remove($tmpFile);
     $this->assertFileNotExists($tmpFile);
 }
Exemplo n.º 15
0
 public function triggerWebtreesAdminTasks()
 {
     $settings = new Settings();
     $this->logger = \Piwik\Container\StaticContainer::get('Psr\\Log\\LoggerInterface');
     $this->logger->info('Webtrees Admin Task triggered');
     $rooturl = $settings->getSetting('webtreesRootUrl');
     if (!$rooturl || strlen($rooturl->getValue()) === 0) {
         return;
     }
     $token = $settings->getSetting('webtreesToken');
     if (!$token || strlen($token->getValue()) === 0) {
         return;
     }
     $taskname = $settings->getSetting('webtreesTaskName');
     if (!$taskname || strlen($taskname->getValue()) === 0) {
         return;
     }
     $url = sprintf('%1$s/module.php?mod=perso_admintasks&mod_action=trigger&force=%2$s&task=%3$s', $rooturl->getValue(), $token->getValue(), $taskname->getValue());
     $this->logger->info('webtrees url : {url}', array('url' => $url));
     try {
         \Piwik\Http::sendHttpRequest($url, Webtrees::SOCKET_TIMEOUT);
     } catch (Exception $e) {
         $this->logger->warning('an error occured', array('exception' => $e));
     }
 }
Exemplo n.º 16
0
 /**
  * Validates the given translations
  *  * There need to be more than 250 translations present
  *  * Locale and TranslatorName needs to be set in plugin General
  *  * Locale must be valid (format, language & country)
  *
  * @param array $translations
  *
  * @return boolean
  */
 public function isValid($translations)
 {
     $this->message = null;
     if (empty($translations['General']['Locale'])) {
         $this->message = self::ERRORSTATE_LOCALEREQUIRED;
         return false;
     }
     if (empty($translations['General']['TranslatorName'])) {
         $this->message = self::ERRORSTATE_TRANSLATORINFOREQUIRED;
         return false;
     }
     /** @var LanguageDataProvider $languageDataProvider */
     $languageDataProvider = StaticContainer::get('Piwik\\Intl\\Data\\Provider\\LanguageDataProvider');
     /** @var RegionDataProvider $regionDataProvider */
     $regionDataProvider = StaticContainer::get('Piwik\\Intl\\Data\\Provider\\RegionDataProvider');
     $allLanguages = $languageDataProvider->getLanguageList();
     $allCountries = $regionDataProvider->getCountryList();
     if (!preg_match('/^([a-z]{2})_([A-Z]{2})\\.UTF-8$/', $translations['General']['Locale'], $matches)) {
         $this->message = self::ERRORSTATE_LOCALEINVALID;
         return false;
     } else {
         if (!array_key_exists($matches[1], $allLanguages)) {
             $this->message = self::ERRORSTATE_LOCALEINVALIDLANGUAGE;
             return false;
         } else {
             if (!array_key_exists(strtolower($matches[2]), $allCountries)) {
                 $this->message = self::ERRORSTATE_LOCALEINVALIDCOUNTRY;
                 return false;
             }
         }
     }
     return true;
 }
Exemplo n.º 17
0
 /**
  * @throws \Exception
  */
 public function addOptOutStyles()
 {
     /** @var \Piwik\Plugins\CoreAdminHome\OptOutManager $manager */
     $manager = StaticContainer::get('Piwik\\Plugins\\CoreAdminHome\\OptOutManager');
     // See Issue #33
     $siteId = Common::getRequestVar('idsite', 0, 'integer');
     // Is still available for BC
     if (!$siteId) {
         $siteId = Common::getRequestVar('idSite', 0, 'integer');
     }
     // Try to find siteId in Session
     if (!$siteId) {
         return;
     }
     $site = API::getInstance()->getSiteDataId($siteId);
     if (!$site) {
         return;
     }
     $manager->addQueryParameter('idsite', $siteId);
     // Add CSS file if set
     if (!empty($site['custom_css_file'])) {
         $manager->addStylesheet($site['custom_css_file'], false);
     }
     // Add CSS Inline Styles if set
     if (!empty($site['custom_css'])) {
         $manager->addStylesheet($site['custom_css'], true);
     }
 }
Exemplo n.º 18
0
 public function setUp()
 {
     parent::setUp();
     if (!Fixture::siteCreated(1)) {
         Fixture::createWebsite('2015-01-01 00:00:00');
     }
     $this->channels = new Plugin\ReleaseChannels(StaticContainer::get('Piwik\\Plugin\\Manager'));
 }
Exemplo n.º 19
0
 public function onSiteDeleted($idSite)
 {
     // we do not delete logs here on purpose (you can run these queries on the log_ tables to delete all data)
     Cache::deleteCacheWebsiteAttributes($idSite);
     $archiveInvalidator = StaticContainer::get('Piwik\\Archive\\ArchiveInvalidator');
     $archiveInvalidator->forgetRememberedArchivedReportsToInvalidateForSite($idSite);
     MeasurableSettingsTable::removeAllSettingsForSite($idSite);
 }
Exemplo n.º 20
0
 public function __construct($logger = null, $config = null)
 {
     $config = $config ?: Config::getInstance();
     $this->isEnabled = (bool) $config->General['enable_segments_subquery_cache'];
     $this->limitActionIds = $config->General['segments_subquery_cache_limit'];
     $this->lifetime = $config->General['segments_subquery_cache_ttl'];
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }
 public function __construct($processNewSegmentsFrom, Model $segmentEditorModel = null, Cache $segmentListCache = null, Date $now = null, LoggerInterface $logger = null)
 {
     $this->processNewSegmentsFrom = $processNewSegmentsFrom;
     $this->segmentEditorModel = $segmentEditorModel ?: Factory::getModel('Piwik\\Plugins\\SegmentEditor');
     $this->segmentListCache = $segmentListCache ?: new Transient();
     $this->now = $now ?: Date::factory('now');
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }
Exemplo n.º 22
0
 /**
  * @param array $widget
  *
  * @dataProvider availableWidgetsProvider
  */
 public function test_WidgetIsRenderable_ToPreventBreakingTheAPI($widget)
 {
     $params = $widget['parameters'];
     $parameters = array();
     $resolver = new ControllerResolver(StaticContainer::getContainer());
     $controller = $resolver->getController($params['module'], $params['action'], $parameters);
     $this->assertNotEmpty($controller, $widget['name'] . ' is not renderable with following params: ' . json_encode($params) . '. This breaks the API, please make sure to keep the URL working');
 }
Exemplo n.º 23
0
 /**
  * Constructor.
  *
  * @param ArchiveInvalidator $invalidator
  * @param DuplicateActionRemover $duplicateActionRemover
  * @param Actions $actionsAccess
  * @param LoggerInterface $logger
  */
 public function __construct(ArchiveInvalidator $invalidator = null, DuplicateActionRemover $duplicateActionRemover = null, Actions $actionsAccess = null, LoggerInterface $logger = null)
 {
     parent::__construct();
     $this->archiveInvalidator = $invalidator ?: StaticContainer::get('Piwik\\Archive\\ArchiveInvalidator');
     $this->duplicateActionRemover = $duplicateActionRemover ?: new DuplicateActionRemover();
     $this->actionsAccess = $actionsAccess ?: new Actions();
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }
Exemplo n.º 24
0
 public static function getDownloadPath()
 {
     $path = StaticContainer::get('path.tmp') . self::DOWNLOAD_PATH;
     if (!is_dir($path)) {
         mkdir($path);
     }
     return $path;
 }
 /**
  * Set login name and authentication token for API request.
  * Listens to API.Request.authenticate hook.
  */
 public function ApiRequestAuthenticate($tokenAuth)
 {
     /** @var \Piwik\Auth $auth */
     $auth = StaticContainer::get('Piwik\\Auth');
     $auth->setLogin($login = null);
     $auth->setTokenAuth($tokenAuth);
     $auth->setAuthCode(Common::getRequestVar('auth_code', '', 'string'));
 }
 /**
  * Constructor.
  *
  * @param ArchiveInvalidator $invalidator
  * @param DuplicateActionRemover $duplicateActionRemover
  * @param Actions $actionsAccess
  * @param LoggerInterface $logger
  */
 public function __construct(ArchiveInvalidator $invalidator = null, DuplicateActionRemover $duplicateActionRemover = null, Actions $actionsAccess = null, LoggerInterface $logger = null)
 {
     parent::__construct();
     $this->archiveInvalidator = $invalidator ?: new ArchiveInvalidator();
     $this->duplicateActionRemover = $duplicateActionRemover ?: Factory::getModel('Piwik\\Plugins\\CoreAdminHome\\Model', 'DuplicateActionRemover');
     $this->actionsAccess = $actionsAccess ?: new Actions();
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }
Exemplo n.º 27
0
 /**
  * Constructor.
  *
  * @param string[] $options The string options applied to the generate:travis-yml command.
  */
 public function __construct($options)
 {
     $this->options = $options;
     if (class_exists('\\Piwik\\Container\\StaticContainer')) {
         $this->logger = \Piwik\Container\StaticContainer::getContainer()->get('Psr\\Log\\LoggerInterface');
     }
     $this->view = new TravisYmlView();
 }
Exemplo n.º 28
0
Arquivo: Menu.php Projeto: piwik/piwik
 /**
  * Menu constructor.
  * @param Plugins $marketplacePlugins
  */
 public function __construct($marketplacePlugins = null)
 {
     if (!empty($marketplacePlugins)) {
         $this->marketplacePlugins = $marketplacePlugins;
     } elseif (Marketplace::isMarketplaceEnabled()) {
         // we load it manually as marketplace plugin might not be loaded
         $this->marketplacePlugins = StaticContainer::get('Piwik\\Plugins\\Marketplace\\Plugins');
     }
 }
Exemplo n.º 29
0
 private function migratePluginEmailUpdateSetting()
 {
     $isEnabled = Option::get('enableUpdateCommunicationPlugins');
     Access::doAsSuperUser(function () use($isEnabled) {
         $settings = StaticContainer::get('Piwik\\Plugins\\CoreUpdater\\SystemSettings');
         $settings->sendPluginUpdateEmail->setValue(!empty($isEnabled));
         $settings->save();
     });
 }
Exemplo n.º 30
0
 public function __construct(Model $model = null, Date $purgeCustomRangesOlderThan = null, LoggerInterface $logger = null)
 {
     $this->model = $model ?: new Model();
     $this->purgeCustomRangesOlderThan = $purgeCustomRangesOlderThan ?: self::getDefaultCustomRangeToPurgeAgeThreshold();
     $this->yesterday = Date::factory('yesterday');
     $this->today = Date::factory('today');
     $this->now = time();
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }