protected function execute(InputInterface $input, OutputInterface $output) { $piwikLanguages = \Piwik\Plugins\LanguagesManager\API::getInstance()->getAvailableLanguages(); $aliasesUrl = 'https://raw.githubusercontent.com/unicode-cldr/cldr-core/master/supplemental/aliases.json'; $aliasesData = Http::fetchRemoteFile($aliasesUrl); $aliasesData = json_decode($aliasesData, true); $aliasesData = $aliasesData['supplemental']['metadata']['alias']['languageAlias']; $writePath = Filesystem::getPathToPiwikRoot() . '/plugins/Intl/lang/%s.json'; foreach ($piwikLanguages as $langCode) { if ($langCode == 'dev') { continue; } $requestLangCode = $transformedLangCode = $this->transformLangCode($langCode); if (array_key_exists($requestLangCode, $aliasesData)) { $requestLangCode = $aliasesData[$requestLangCode]['_replacement']; } // fix some locales $localFixes = array('pt' => 'pt-PT', 'pt-br' => 'pt', 'zh-cn' => 'zh-Hans', 'zh-tw' => 'zh-Hant'); if (array_key_exists($langCode, $localFixes)) { $requestLangCode = $localFixes[$langCode]; } setlocale(LC_ALL, $langCode); $translations = array(); $this->fetchLanguageData($output, $transformedLangCode, $requestLangCode, $translations); $this->fetchTerritoryData($output, $transformedLangCode, $requestLangCode, $translations); $this->fetchCalendarData($output, $transformedLangCode, $requestLangCode, $translations); $this->fetchLayoutDirection($output, $transformedLangCode, $requestLangCode, $translations); $this->fetchUnitData($output, $transformedLangCode, $requestLangCode, $translations); $this->fetchNumberFormattingData($output, $transformedLangCode, $requestLangCode, $translations); ksort($translations['Intl']); file_put_contents(sprintf($writePath, $langCode), json_encode($translations, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); } }
protected function execute(InputInterface $input, OutputInterface $output) { $output->setDecorated(true); $username = $input->getOption('username'); $password = $input->getOption('password'); $plugin = $input->getOption('plugin'); $lastUpdate = $input->getOption('lastupdate'); $resource = 'piwik-' . ($plugin ? 'plugin-' . strtolower($plugin) : 'base'); $transifexApi = new API($username, $password); // remove all existing translation files in download path $files = glob($this->getDownloadPath() . DIRECTORY_SEPARATOR . '*.json'); array_map('unlink', $files); if (!$transifexApi->resourceExists($resource)) { $output->writeln("Skipping resource {$resource} as it doesn't exist on Transifex"); return; } $output->writeln("Fetching translations from Transifex for resource {$resource}"); $availableLanguages = LanguagesManagerApi::getInstance()->getAvailableLanguageNames(); $languageCodes = array(); foreach ($availableLanguages as $languageInfo) { $languageCodes[] = $languageInfo['code']; } $languageCodes = array_filter($languageCodes, function ($code) { return !in_array($code, array('en', 'dev')); }); try { $languages = $transifexApi->getAvailableLanguageCodes(); if (!empty($plugin)) { $languages = array_filter($languages, function ($language) { return LanguagesManagerApi::getInstance()->isLanguageAvailable(str_replace('_', '-', strtolower($language))); }); } } catch (AuthenticationFailedException $e) { $languages = $languageCodes; } /** @var ProgressBar $progress */ $progress = new ProgressBar($output, count($languages)); $progress->start(); $statistics = $transifexApi->getStatistics($resource); foreach ($languages as $language) { try { // if we have modification date given from statistics api compare it with given last update time to ignore not update resources if (LanguagesManagerApi::getInstance()->isLanguageAvailable(str_replace('_', '-', strtolower($language))) && isset($statistics->{$language})) { $lastupdated = strtotime($statistics->{$language}->last_update); if ($lastUpdate > $lastupdated) { $progress->advance(); continue; } } $translations = $transifexApi->getTranslations($resource, $language, true); file_put_contents($this->getDownloadPath() . DIRECTORY_SEPARATOR . str_replace('_', '-', strtolower($language)) . '.json', $translations); } catch (\Exception $e) { $output->writeln("Error fetching language file {$language}: " . $e->getMessage()); } $progress->advance(); } $progress->finish(); $output->writeln(''); }
protected function execute(InputInterface $input, OutputInterface $output) { $languages = API::getInstance()->getAvailableLanguageNames(); $languageNames = array(); foreach ($languages as $languageInfo) { $languageNames[] = $languageInfo['english_name']; } sort($languageNames); $output->writeln("Currently available languages:"); $output->writeln(implode("\n", $languageNames)); }
protected function execute(InputInterface $input, OutputInterface $output) { /** @var DialogHelper $dialog */ $dialog = $this->getHelperSet()->get('dialog'); $languageCode = $input->getOption('code'); $filename = $input->getOption('file'); $languageCodes = API::getInstance()->getAvailableLanguages(); if (empty($languageCode) || !in_array($languageCode, $languageCodes)) { $languageCode = $dialog->askAndValidate($output, 'Please provide a valid language code: ', function ($code) use($languageCodes) { if (!in_array($code, array_values($languageCodes))) { throw new \InvalidArgumentException(sprintf('Language code "%s" is invalid.', $code)); } return $code; }); } if (empty($filename) || !file_exists($filename)) { $filename = $dialog->askAndValidate($output, 'Please provide a file to load translations from: ', function ($file) { if (!file_exists($file)) { throw new \InvalidArgumentException(sprintf('File "%s" does not exist.', $file)); } return $file; }); } $output->writeln("Starting to import data from '{$filename}' to language '{$languageCode}'"); $plugin = $input->getOption('plugin'); $translationWriter = new Writer($languageCode, $plugin); $baseTranslations = $translationWriter->getTranslations("en"); $translationWriter->addValidator(new NoScripts()); if (empty($plugin)) { $translationWriter->addValidator(new CoreTranslations($baseTranslations)); } $translationWriter->addFilter(new ByBaseTranslations($baseTranslations)); $translationWriter->addFilter(new EmptyTranslations()); $translationWriter->addFilter(new ByParameterCount($baseTranslations)); $translationWriter->addFilter(new UnnecassaryWhitespaces($baseTranslations)); $translationWriter->addFilter(new EncodedEntities()); $translationData = file_get_contents($filename); $translations = json_decode($translationData, true); $translationWriter->setTranslations($translations); if (!$translationWriter->isValid()) { $output->writeln("Failed setting translations:" . $translationWriter->getValidationMessage()); return; } if (!$translationWriter->hasTranslations()) { $output->writeln("No translations available"); return; } $translationWriter->save(); $output->writeln("Finished."); }
/** * anonymous = in the session * authenticated user = in the session and in DB */ public function saveLanguage() { $language = Common::getRequestVar('language'); // Prevent CSRF only when piwik is not installed yet (During install user can change language) if (DbHelper::isInstalled()) { $this->checkTokenInUrl(); } LanguagesManager::setLanguageForSession($language); if (\Piwik\Registry::isRegistered('access')) { $currentUser = Piwik::getCurrentUserLogin(); if ($currentUser && $currentUser !== 'anonymous') { API::getInstance()->setLanguageForUser($currentUser, $language); } } Url::redirectToReferrer(); }
/** * Shows the "Track Visits" checkbox. */ public function optOut() { $trackVisits = !IgnoreCookie::isIgnoreCookieFound(); $nonce = Common::getRequestVar('nonce', false); $language = Common::getRequestVar('language', ''); if ($nonce !== false && Nonce::verifyNonce('Piwik_OptOut', $nonce)) { Nonce::discardNonce('Piwik_OptOut'); IgnoreCookie::setIgnoreCookie(); $trackVisits = !$trackVisits; } $view = new View('@CoreAdminHome/optOut'); $view->trackVisits = $trackVisits; $view->nonce = Nonce::getNonce('Piwik_OptOut', 3600); $view->language = APILanguagesManager::getInstance()->isLanguageAvailable($language) ? $language : LanguagesManager::getLanguageCodeForCurrentUser(); return $view->render(); }
/** * test English short name for language * * @group Plugins */ function testGetLanguageNamesInEnglish() { $languages = API::getInstance()->getAvailableLanguages(); foreach ($languages as $language) { $data = file_get_contents(PIWIK_INCLUDE_PATH . "/lang/{$language}.json"); $translations = json_decode($data, true); $name = $translations['General']['EnglishLanguageName']; if ($language != 'en') { $this->assertFalse($name == 'English', "for {$language}"); } $languageCode = substr($language, 0, 2); $this->assertTrue(isset($GLOBALS['Piwik_LanguageList'][$languageCode])); $names = $GLOBALS['Piwik_LanguageList'][$languageCode]; if (isset($GLOBALS['Piwik_LanguageList'][$language])) { if (is_array($names)) { $this->assertTrue(in_array($name, $names), "{$language}: failed because {$name} not a known language name"); } else { $this->assertTrue($name == $names, "{$language}: failed because {$name} == {$names}"); } } else { if (is_array($names)) { $this->assertTrue(strpos($name, $names[0]) !== false); } else { $this->fail("{$language}: expected an array of language names"); } } } }
/** * Shows the "Track Visits" checkbox. */ public function optOut() { $trackVisits = !IgnoreCookie::isIgnoreCookieFound(); $dntChecker = new DoNotTrackHeaderChecker(); $dntFound = $dntChecker->isDoNotTrackFound(); $setCookieInNewWindow = Common::getRequestVar('setCookieInNewWindow', false, 'int'); if ($setCookieInNewWindow) { $reloadUrl = Url::getCurrentQueryStringWithParametersModified(array( 'showConfirmOnly' => 1, 'setCookieInNewWindow' => 0, )); } else { $reloadUrl = false; $nonce = Common::getRequestVar('nonce', false); if ($nonce !== false && Nonce::verifyNonce('Piwik_OptOut', $nonce)) { Nonce::discardNonce('Piwik_OptOut'); IgnoreCookie::setIgnoreCookie(); $trackVisits = !$trackVisits; } } $language = Common::getRequestVar('language', ''); $lang = APILanguagesManager::getInstance()->isLanguageAvailable($language) ? $language : LanguagesManager::getLanguageCodeForCurrentUser(); // should not use self::renderTemplate since that uses setBasicVariablesView. this will cause // an error when setBasicVariablesAdminView is called, and MenuTop is requested (the idSite query // parameter is required) $view = new View("@CoreAdminHome/optOut"); $view->setXFrameOptions('allow'); $view->dntFound = $dntFound; $view->trackVisits = $trackVisits; $view->nonce = Nonce::getNonce('Piwik_OptOut', 3600); $view->language = $lang; $view->isSafari = $this->isUserAgentSafari(); $view->showConfirmOnly = Common::getRequestVar('showConfirmOnly', false, 'int'); $view->reloadUrl = $reloadUrl; return $view->render(); }
private function getLanguageInfoByIsoCode($isoCode) { $languages = API::getInstance()->getAvailableLanguagesInfo(); foreach ($languages as $languageInfo) { if ($languageInfo['code'] == $isoCode) { return $languageInfo; } } return array(); }
/** * Records settings from the "User Settings" page * @throws Exception */ public function recordUserSettings() { $response = new ResponseBuilder(Common::getRequestVar('format')); try { $this->checkTokenInUrl(); $defaultReport = Common::getRequestVar('defaultReport'); $defaultDate = Common::getRequestVar('defaultDate'); $language = Common::getRequestVar('language'); $userLogin = Piwik::getCurrentUserLogin(); $this->processPasswordChange($userLogin); LanguagesManager::setLanguageForSession($language); APILanguagesManager::getInstance()->setLanguageForUser($userLogin, $language); APIUsersManager::getInstance()->setUserPreference($userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT, $defaultReport); APIUsersManager::getInstance()->setUserPreference($userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT_DATE, $defaultDate); $toReturn = $response->getResponse(); } catch (Exception $e) { $toReturn = $response->getResponseException($e); } return $toReturn; }
public function performSetUp($setupEnvironmentOnly = false) { // TODO: don't use static var, use test env var for this TestingEnvironmentManipulator::$extraPluginsToLoad = $this->extraPluginsToLoad; $this->dbName = $this->getDbName(); if ($this->persistFixtureData) { $this->dropDatabaseInSetUp = false; $this->dropDatabaseInTearDown = false; $this->overwriteExisting = false; $this->removeExistingSuperUser = false; } $testEnv = $this->getTestEnvironment(); $testEnv->testCaseClass = $this->testCaseClass; $testEnv->fixtureClass = get_class($this); $testEnv->dbName = $this->dbName; $testEnv->extraDiEnvironments = $this->extraDiEnvironments; foreach ($this->extraTestEnvVars as $name => $value) { $testEnv->{$name} = $value; } $testEnv->save(); $this->createEnvironmentInstance(); if ($this->dbName === false) { // must be after test config is created $this->dbName = self::getConfig()->database['dbname']; } try { static::connectWithoutDatabase(); if ($this->dropDatabaseInSetUp || $this->resetPersistedFixture) { $this->dropDatabase(); } DbHelper::createDatabase($this->dbName); DbHelper::disconnectDatabase(); Tracker::disconnectCachedDbConnection(); // reconnect once we're sure the database exists self::getConfig()->database['dbname'] = $this->dbName; Db::createDatabaseObject(); Db::get()->query("SET wait_timeout=28800;"); DbHelper::createTables(); self::getPluginManager()->unloadPlugins(); } catch (Exception $e) { static::fail("TEST INITIALIZATION FAILED: " . $e->getMessage() . "\n" . $e->getTraceAsString()); } include "DataFiles/Providers.php"; if (!$this->isFixtureSetUp()) { DbHelper::truncateAllTables(); } // We need to be SU to create websites for tests Access::getInstance()->setSuperUserAccess(); Cache::deleteTrackerCache(); self::resetPluginsInstalledConfig(); $testEnvironment = $this->getTestEnvironment(); static::loadAllPlugins($testEnvironment, $this->testCaseClass, $this->extraPluginsToLoad); self::updateDatabase(); self::installAndActivatePlugins($testEnvironment); $_GET = $_REQUEST = array(); $_SERVER['HTTP_REFERER'] = ''; FakeAccess::$superUserLogin = '******'; File::$invalidateOpCacheBeforeRead = true; if ($this->configureComponents) { IPAnonymizer::deactivate(); $dntChecker = new DoNotTrackHeaderChecker(); $dntChecker->deactivate(); } if ($this->createSuperUser) { self::createSuperUser($this->removeExistingSuperUser); if (!Access::getInstance() instanceof FakeAccess) { $this->loginAsSuperUser(); } APILanguageManager::getInstance()->setLanguageForUser('superUserLogin', 'en'); } SettingsPiwik::overwritePiwikUrl(self::getTestRootUrl()); if ($setupEnvironmentOnly) { return; } PiwikCache::getTransientCache()->flushAll(); if ($this->overwriteExisting || !$this->isFixtureSetUp()) { $this->setUp(); $this->markFixtureSetUp(); $this->log("Database {$this->dbName} marked as successfully set up."); } else { $this->log("Using existing database {$this->dbName}."); } }
public function performSetUp($setupEnvironmentOnly = false) { try { if ($this->createConfig) { Config::getInstance()->setTestEnvironment(); } $this->dbName = $this->getDbName(); if ($this->persistFixtureData) { $this->dropDatabaseInSetUp = false; $this->dropDatabaseInTearDown = false; $this->overwriteExisting = false; $this->removeExistingSuperUser = false; Config::getInstance()->database_tests['dbname'] = Config::getInstance()->database['dbname'] = $this->dbName; $this->getTestEnvironment()->dbName = $this->dbName; } if ($this->dbName === false) { // must be after test config is created $this->dbName = Config::getInstance()->database['dbname']; } static::connectWithoutDatabase(); if ($this->dropDatabaseInSetUp || $this->resetPersistedFixture) { $this->dropDatabase(); } DbHelper::createDatabase($this->dbName); DbHelper::disconnectDatabase(); // reconnect once we're sure the database exists Config::getInstance()->database['dbname'] = $this->dbName; Db::createDatabaseObject(); Db::get()->query("SET wait_timeout=28800;"); DbHelper::createTables(); \Piwik\Plugin\Manager::getInstance()->unloadPlugins(); } catch (Exception $e) { static::fail("TEST INITIALIZATION FAILED: " . $e->getMessage() . "\n" . $e->getTraceAsString()); } include "DataFiles/SearchEngines.php"; include "DataFiles/Socials.php"; include "DataFiles/Languages.php"; include "DataFiles/Countries.php"; include "DataFiles/Currencies.php"; include "DataFiles/LanguageToCountry.php"; include "DataFiles/Providers.php"; if (!$this->isFixtureSetUp()) { DbHelper::truncateAllTables(); } static::createAccessInstance(); // We need to be SU to create websites for tests Piwik::setUserHasSuperUserAccess(); Cache::deleteTrackerCache(); static::loadAllPlugins($this->getTestEnvironment(), $this->testCaseClass, $this->extraPluginsToLoad); self::updateDatabase(); self::installAndActivatePlugins(); $_GET = $_REQUEST = array(); $_SERVER['HTTP_REFERER'] = ''; // Make sure translations are loaded to check messages in English if ($this->loadTranslations) { Translate::reloadLanguage('en'); APILanguageManager::getInstance()->setLanguageForUser('superUserLogin', 'en'); } FakeAccess::$superUserLogin = '******'; \Piwik\SettingsPiwik::$cachedKnownSegmentsToArchive = null; \Piwik\CacheFile::$invalidateOpCacheBeforeRead = true; if ($this->configureComponents) { \Piwik\Plugins\PrivacyManager\IPAnonymizer::deactivate(); \Piwik\Plugins\PrivacyManager\DoNotTrackHeaderChecker::deactivate(); } if ($this->createSuperUser) { self::createSuperUser($this->removeExistingSuperUser); } if ($setupEnvironmentOnly) { return; } $this->getTestEnvironment()->save(); $this->getTestEnvironment()->executeSetupTestEnvHook(); Piwik_TestingEnvironment::addSendMailHook(); if ($this->overwriteExisting || !$this->isFixtureSetUp()) { $this->setUp(); $this->markFixtureSetUp(); $this->log("Database {$this->dbName} marked as successfully set up."); } else { $this->log("Using existing database {$this->dbName}."); } }
/** * Set the language for the session * * @param string $languageCode ISO language code * @return bool */ public static function setLanguageForSession($languageCode) { if (!API::getInstance()->isLanguageAvailable($languageCode)) { return false; } $cookieName = Config::getInstance()->General['language_cookie_name']; $cookie = new Cookie($cookieName, 0); $cookie->set('language', $languageCode); $cookie->save(); return true; }
/** * @return View * @throws \Exception */ public function getOptOutView() { if ($this->view) { return $this->view; } $trackVisits = !IgnoreCookie::isIgnoreCookieFound(); $dntFound = $this->getDoNotTrackHeaderChecker()->isDoNotTrackFound(); $setCookieInNewWindow = Common::getRequestVar('setCookieInNewWindow', false, 'int'); if ($setCookieInNewWindow) { $reloadUrl = Url::getCurrentQueryStringWithParametersModified(array('showConfirmOnly' => 1, 'setCookieInNewWindow' => 0)); } else { $reloadUrl = false; $nonce = Common::getRequestVar('nonce', false); if ($nonce !== false && Nonce::verifyNonce('Piwik_OptOut', $nonce)) { Nonce::discardNonce('Piwik_OptOut'); IgnoreCookie::setIgnoreCookie(); $trackVisits = !$trackVisits; } } $language = Common::getRequestVar('language', ''); $lang = APILanguagesManager::getInstance()->isLanguageAvailable($language) ? $language : LanguagesManager::getLanguageCodeForCurrentUser(); $this->addQueryParameters(array('module' => 'CoreAdminHome', 'action' => 'optOut', 'language' => $lang, 'setCookieInNewWindow' => 1), false); $this->view = new View("@CoreAdminHome/optOut"); $this->view->setXFrameOptions('allow'); $this->view->dntFound = $dntFound; $this->view->trackVisits = $trackVisits; $this->view->nonce = Nonce::getNonce('Piwik_OptOut', 3600); $this->view->language = $lang; $this->view->showConfirmOnly = Common::getRequestVar('showConfirmOnly', false, 'int'); $this->view->reloadUrl = $reloadUrl; $this->view->javascripts = $this->getJavascripts(); $this->view->stylesheets = $this->getStylesheets(); $this->view->title = $this->getTitle(); $this->view->queryParameters = $this->getQueryParameters(); return $this->view; }
/** * Shows the "Track Visits" checkbox. */ public function optOut() { $trackVisits = !IgnoreCookie::isIgnoreCookieFound(); $nonce = Common::getRequestVar('nonce', false); $language = Common::getRequestVar('language', ''); if ($nonce !== false && Nonce::verifyNonce('Piwik_OptOut', $nonce)) { Nonce::discardNonce('Piwik_OptOut'); IgnoreCookie::setIgnoreCookie(); $trackVisits = !$trackVisits; } $lang = APILanguagesManager::getInstance()->isLanguageAvailable($language) ? $language : LanguagesManager::getLanguageCodeForCurrentUser(); return $this->renderTemplate('optOut', array('trackVisits' => $trackVisits, 'nonce' => Nonce::getNonce('Piwik_OptOut', 3600), 'language' => $lang)); }
/** * test English short name for language * * @group Plugins */ function testGetLanguageNamesInEnglish() { $languages = API::getInstance()->getAvailableLanguages(); /** @var LanguageDataProvider $dataProvider */ $dataProvider = StaticContainer::get('Piwik\\Intl\\Data\\Provider\\LanguageDataProvider'); $languagesReference = $dataProvider->getLanguageList(); foreach ($languages as $language) { $data = file_get_contents(PIWIK_INCLUDE_PATH . "/plugins/Intl/lang/{$language}.json"); $translations = json_decode($data, true); $name = $translations['Intl']['EnglishLanguageName']; if ($language != 'en') { $this->assertFalse($name == 'English', "for {$language}"); } $languageCode = substr($language, 0, 2); $this->assertTrue(isset($languagesReference[$languageCode])); $names = $languagesReference[$languageCode]; if (isset($languagesReference[$language])) { if (is_array($names)) { $this->assertTrue(in_array($name, $names), "{$language}: failed because {$name} not a known language name"); } else { $this->assertTrue($name == $names, "{$language}: failed because {$name} == {$names}"); } } else { if (is_array($names)) { $this->assertTrue(strpos($name, $names[0]) !== false); } else { $this->fail("{$language}: expected an array of language names"); } } } }
public function sendReport($idReport, $period = false, $date = false, $force = false) { Piwik::checkUserIsNotAnonymous(); $reports = $this->getReports($idSite = false, false, $idReport); $report = reset($reports); if ($report['period'] == 'never') { $report['period'] = 'day'; } if (!empty($period)) { $report['period'] = $period; } if (empty($date)) { $date = Date::now()->subPeriod(1, $report['period'])->toString(); } $language = \Piwik\Plugins\LanguagesManager\API::getInstance()->getLanguageForUser($report['login']); // generate report list($outputFilename, $prettyDate, $reportSubject, $reportTitle, $additionalFiles) = $this->generateReport($idReport, $date, $language, self::OUTPUT_SAVE_ON_DISK, $report['period']); if (!file_exists($outputFilename)) { throw new Exception("The report file wasn't found in {$outputFilename}"); } $contents = file_get_contents($outputFilename); if (empty($contents)) { Log::warning("Scheduled report file '%s' exists but is empty!", $outputFilename); } /** * Triggered when sending scheduled reports. * * Plugins that provide new scheduled report transport mediums should use this event to * send the scheduled report. * * @param string $reportType A string ID describing how the report is sent, eg, * `'sms'` or `'email'`. * @param array $report An array describing the scheduled report that is being * generated. * @param string $contents The contents of the scheduled report that was generated * and now should be sent. * @param string $filename The path to the file where the scheduled report has * been saved. * @param string $prettyDate A prettified date string for the data within the * scheduled report. * @param string $reportSubject A string describing what's in the scheduled * report. * @param string $reportTitle The scheduled report's given title (given by a Piwik user). * @param array $additionalFiles The list of additional files that should be * sent with this report. * @param \Piwik\Period $period The period for which the report has been generated. * @param boolean $force A report can only be sent once per period. Setting this to true * will force to send the report even if it has already been sent. */ Piwik::postEvent(self::SEND_REPORT_EVENT, array($report['type'], $report, $contents, $filename = basename($outputFilename), $prettyDate, $reportSubject, $reportTitle, $additionalFiles, \Piwik\Period\Factory::build($report['period'], $date), $force)); // Update flag in DB $now = Date::now()->getDatetime(); $this->getModel()->updateReport($report['idreport'], array('ts_last_sent' => $now)); // If running from piwik.php with debug, do not delete the PDF after sending the email $tracker = new Tracker(); if (!$tracker->isDebugModeEnabled()) { @chmod($outputFilename, 0600); } }
public function sendReport($idReport, $period = false, $date = false) { Piwik::checkUserIsNotAnonymous(); $reports = $this->getReports($idSite = false, false, $idReport); $report = reset($reports); if ($report['period'] == 'never') { $report['period'] = 'day'; } if (!empty($period)) { $report['period'] = $period; } if (empty($date)) { $date = Date::now()->subPeriod(1, $report['period'])->toString(); } $language = \Piwik\Plugins\LanguagesManager\API::getInstance()->getLanguageForUser($report['login']); // generate report list($outputFilename, $prettyDate, $reportSubject, $reportTitle, $additionalFiles) = $this->generateReport($idReport, $date, $language, self::OUTPUT_SAVE_ON_DISK, $report['period']); if (!file_exists($outputFilename)) { throw new Exception("The report file wasn't found in {$outputFilename}"); } $filename = basename($outputFilename); $handle = fopen($outputFilename, "r"); $contents = fread($handle, filesize($outputFilename)); fclose($handle); /** * Triggered when sending scheduled reports. * * Plugins that provide new scheduled report transport mediums should use this event to * send the scheduled report. * * @param string $reportType A string ID describing how the report is sent, eg, * `'sms'` or `'email'`. * @param array $report An array describing the scheduled report that is being * generated. * @param string $contents The contents of the scheduled report that was generated * and now should be sent. * @param string $filename The path to the file where the scheduled report has * been saved. * @param string $prettyDate A prettified date string for the data within the * scheduled report. * @param string $reportSubject A string describing what's in the scheduled * report. * @param string $reportTitle The scheduled report's given title (given by a Piwik user). * @param array $additionalFiles The list of additional files that should be * sent with this report. */ Piwik::postEvent(self::SEND_REPORT_EVENT, array($report['type'], $report, $contents, $filename, $prettyDate, $reportSubject, $reportTitle, $additionalFiles)); // Update flag in DB Db::get()->update(Common::prefixTable('report'), array('ts_last_sent' => Date::now()->getDatetime()), "idreport = " . $report['idreport']); // If running from piwik.php with debug, do not delete the PDF after sending the email if (!isset($GLOBALS['PIWIK_TRACKER_DEBUG']) || !$GLOBALS['PIWIK_TRACKER_DEBUG']) { @chmod($outputFilename, 0600); } }
/** * Shows the "Track Visits" checkbox. */ public function optOut() { $trackVisits = !IgnoreCookie::isIgnoreCookieFound(); $nonce = Common::getRequestVar('nonce', false); $language = Common::getRequestVar('language', ''); if ($nonce !== false && Nonce::verifyNonce('Piwik_OptOut', $nonce)) { Nonce::discardNonce('Piwik_OptOut'); IgnoreCookie::setIgnoreCookie(); $trackVisits = !$trackVisits; } $lang = APILanguagesManager::getInstance()->isLanguageAvailable($language) ? $language : LanguagesManager::getLanguageCodeForCurrentUser(); // should not use self::renderTemplate since that uses setBasicVariablesView. this will cause // an error when setBasicVariablesAdminView is called, and MenuTop is requested (the idSite query // parameter is required) $view = new View("@CoreAdminHome/optOut"); $view->setXFrameOptions('allow'); $view->trackVisits = $trackVisits; $view->nonce = Nonce::getNonce('Piwik_OptOut', 3600); $view->language = $lang; return $view->render(); }
protected function execute(InputInterface $input, OutputInterface $output) { $dialog = $this->getHelperSet()->get('dialog'); $command = $this->getApplication()->find('translations:fetch'); $arguments = array('command' => 'translations:fetch', '--username' => $input->getOption('username'), '--password' => $input->getOption('password')); $inputObject = new ArrayInput($arguments); $inputObject->setInteractive($input->isInteractive()); $command->run($inputObject, $output); $languages = API::getInstance()->getAvailableLanguageNames(); $languageCodes = array(); foreach ($languages as $languageInfo) { $languageCodes[] = $languageInfo['code']; } $plugin = $input->getOption('plugin'); $files = _glob(FetchFromOTrance::getDownloadPath() . DIRECTORY_SEPARATOR . '*.json'); $output->writeln("Starting to import new language files"); if (!$input->isInteractive()) { $output->writeln("(!) Non interactive mode: New languages will be skipped"); } $progress = $this->getHelperSet()->get('progress'); $progress->start($output, count($files)); foreach ($files as $filename) { $progress->advance(); $code = basename($filename, '.json'); if (!in_array($code, $languageCodes)) { if (!empty($plugin)) { continue; # never create a new language for plugin only } $createNewFile = false; if ($input->isInteractive()) { $createNewFile = $dialog->askConfirmation($output, "\nLanguage {$code} does not exist. Should it be added? ", false); } if (!$createNewFile) { continue; # do not create a new file for the language } @touch(PIWIK_DOCUMENT_ROOT . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . $code . '.json'); API::unsetInstance(); // unset language manager instance, so valid names are refetched } $command = $this->getApplication()->find('translations:set'); $arguments = array('command' => 'translations:set', '--code' => $code, '--file' => $filename, '--plugin' => $plugin); $inputObject = new ArrayInput($arguments); $inputObject->setInteractive($input->isInteractive()); $command->run($inputObject, new NullOutput()); // update core modules that aren't in their own repo if (empty($plugin)) { foreach (self::getPluginsInCore() as $pluginName) { // update translation files $command = $this->getApplication()->find('translations:set'); $arguments = array('command' => 'translations:set', '--code' => $code, '--file' => $filename, '--plugin' => $pluginName); $inputObject = new ArrayInput($arguments); $inputObject->setInteractive($input->isInteractive()); $command->run($inputObject, new NullOutput()); } } } $progress->finish(); $output->writeln("Finished."); }
protected function execute(InputInterface $input, OutputInterface $output) { $start = microtime(true); /** @var DialogHelper $dialog */ $dialog = $this->getHelperSet()->get('dialog'); $languages = API::getInstance()->getAvailableLanguageNames(); $languageCodes = array(); foreach ($languages as $languageInfo) { $languageCodes[] = $languageInfo['code']; } $plugin = $input->getOption('plugin'); if (!$input->isInteractive()) { $output->writeln("(!) Non interactive mode: New languages will be skipped"); } $pluginList = array($plugin); if (empty($plugin)) { $pluginList = self::getPluginsInCore(); array_unshift($pluginList, ''); } foreach ($pluginList as $plugin) { $output->writeln(""); // fetch base or specific plugin $this->fetchTranslations($input, $output, $plugin); $files = _glob(FetchTranslations::getDownloadPath() . DIRECTORY_SEPARATOR . '*.json'); if (count($files) == 0) { $output->writeln("No translation updates available! Skipped."); continue; } $output->writeln("Starting to import new language files"); /** @var ProgressHelper $progress */ $progress = $this->getHelperSet()->get('progress'); $progress->start($output, count($files)); foreach ($files as $filename) { $progress->advance(); $code = basename($filename, '.json'); if (!in_array($code, $languageCodes)) { if (!empty($plugin)) { continue; # never create a new language for plugin only } $createNewFile = false; if ($input->isInteractive()) { $createNewFile = $dialog->askConfirmation($output, "\nLanguage {$code} does not exist. Should it be added? ", false); } if (!$createNewFile) { continue; # do not create a new file for the language } @touch(PIWIK_DOCUMENT_ROOT . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . $code . '.json'); API::unsetInstance(); // unset language manager instance, so valid names are refetched } $command = $this->getApplication()->find('translations:set'); $arguments = array('command' => 'translations:set', '--code' => $code, '--file' => $filename, '--plugin' => $plugin); $inputObject = new ArrayInput($arguments); $inputObject->setInteractive($input->isInteractive()); $command->run($inputObject, new NullOutput()); } $progress->finish(); } $output->writeln("Finished in " . round(microtime(true) - $start, 3) . "s"); }