update Piwik to version 2.16 (fixes #91)

This commit is contained in:
oliver 2016-04-10 18:55:57 +02:00
commit 47263617c5
87 changed files with 418860 additions and 226988 deletions

View file

@ -0,0 +1,22 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater;
use Exception;
/**
* Error while downloading the archive.
*/
class ArchiveDownloadException extends UpdaterException
{
public function __construct(Exception $exception)
{
parent::__construct($exception, array());
}
}

View file

@ -1,6 +1,6 @@
<?php
/**
* Piwik - Open source web analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -8,55 +8,330 @@
*/
namespace Piwik\Plugins\CoreUpdater\Commands;
use Piwik\Version;
use Piwik\Config;
use Piwik\DbHelper;
use Piwik\Filesystem;
use Piwik\Piwik;
use Piwik\Plugin\ConsoleCommand;
use Piwik\Plugins\CoreUpdater\Controller;
use Piwik\Plugins\CoreUpdater\Commands\Update\CliUpdateObserver;
use Piwik\Plugins\CoreUpdater\NoUpdatesFoundException;
use Piwik\Plugins\UserCountry\LocationProvider;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Piwik\Updater;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
/**
* @package CloudAdmin
* @package CoreUpdater
*/
class Update extends ConsoleCommand
{
/**
* @var string[]
*/
private $migrationQueries;
protected function configure()
{
$this->setName('core:update');
$this->setDescription('Triggers upgrades. Use it after Piwik core or any plugin files have been updated.');
$this->addOption('dry-run', null, InputOption::VALUE_NONE, 'Only prints out the SQL requests that would be executed during the upgrade');
$this->addOption('yes', null, InputOption::VALUE_NONE, 'Directly execute the update without asking for confirmation');
}
/**
* Execute command like: ./console core:update --dry-run
* Execute command like: ./console core:update --yes
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$doDryRun = $input->getOption('dry-run');
$this->executeClearCaches();
$yes = $input->getOption('yes');
try {
$this->makeUpdate($input, $output, $doDryRun);
$this->makeUpdate($input, $output, true);
if (!$yes) {
$yes = $this->askForUpdateConfirmation($input, $output);
}
if ($yes) {
$output->writeln("\nStarting the database upgrade process now. This may take a while, so please be patient.");
$this->makeUpdate($input, $output, false);
$this->writeSuccessMessage($output, array("Piwik has been successfully updated!"));
} else {
$this->writeSuccessMessage($output, array('Database upgrade not executed.'));
}
} catch(NoUpdatesFoundException $e) {
// Do not fail if no updates were found
$output->writeln("<info>".$e->getMessage()."</info>");
} catch (\Exception $e) {
// Fail in case of any other error during upgrade
$output->writeln("<error>" . $e->getMessage() . "</error>");
throw $e;
$this->writeSuccessMessage($output, array($e->getMessage()));
}
}
private function askForUpdateConfirmation(InputInterface $input, OutputInterface $output)
{
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion('<comment>A database upgrade is required. Execute update? (y/N) </comment>', false);
return $helper->ask($input, $output, $question);
}
protected function executeClearCaches()
{
Filesystem::deleteAllCacheOnUpdate();
}
protected function makeUpdate(InputInterface $input, OutputInterface $output, $doDryRun)
{
$this->checkAllRequiredOptionsAreNotEmpty($input);
$updateController = new Controller();
echo $updateController->runUpdaterAndExit($doDryRun);
$updater = $this->makeUpdaterInstance($output);
$componentsWithUpdateFile = $updater->getComponentUpdates();
if (empty($componentsWithUpdateFile)) {
throw new NoUpdatesFoundException("Everything is already up to date.");
}
$output->writeln(array(
"",
" *** " . Piwik::translate('CoreUpdater_UpdateTitle') . " ***"
));
// handle case of existing database with no tables
if (!DbHelper::isInstalled()) {
$this->handleCoreError($output, Piwik::translate('CoreUpdater_EmptyDatabaseError', Config::getInstance()->database['dbname']));
return;
}
$output->writeln(array(
"",
" " . Piwik::translate('CoreUpdater_DatabaseUpgradeRequired'),
"",
" " . Piwik::translate('CoreUpdater_YourDatabaseIsOutOfDate')
));
if ($this->isUpdatingCore($componentsWithUpdateFile)) {
$currentVersion = $this->getCurrentVersionForCore($updater);
$output->writeln(array(
"",
" " . Piwik::translate('CoreUpdater_PiwikWillBeUpgradedFromVersionXToVersionY', array($currentVersion, Version::VERSION))
));
}
$pluginsToUpdate = $this->getPluginsToUpdate($componentsWithUpdateFile);
if (!empty($pluginsToUpdate)) {
$output->writeln(array(
"",
" " . Piwik::translate('CoreUpdater_TheFollowingPluginsWillBeUpgradedX', implode(', ', $pluginsToUpdate))
));
}
$dimensionsToUpdate = $this->getDimensionsToUpdate($componentsWithUpdateFile);
if (!empty($dimensionsToUpdate)) {
$output->writeln(array(
"",
" " . Piwik::translate('CoreUpdater_TheFollowingDimensionsWillBeUpgradedX', implode(', ', $dimensionsToUpdate))
));
}
$output->writeln("");
if ($doDryRun) {
$this->doDryRun($updater, $output);
} else {
$this->doRealUpdate($updater, $componentsWithUpdateFile, $output);
}
}
}
private function doDryRun(Updater $updater, OutputInterface $output)
{
$migrationQueries = $this->getMigrationQueriesToExecute($updater);
$output->writeln(array(" *** Note: this is a Dry Run ***", ""));
foreach ($migrationQueries as $query) {
$output->writeln(" " . $query);
}
$output->writeln(array("", " *** End of Dry Run ***", ""));
}
private function doRealUpdate(Updater $updater, $componentsWithUpdateFile, OutputInterface $output)
{
$output->writeln(array(" " . Piwik::translate('CoreUpdater_TheUpgradeProcessMayTakeAWhilePleaseBePatient'), ""));
$updaterResult = $updater->updateComponents($componentsWithUpdateFile);
if (@$updaterResult['coreError']) {
$this->handleCoreError($output, $updaterResult['errors'], $includeDiyHelp = true);
return;
}
if (!empty($updaterResult['warnings'])) {
$this->outputUpdaterWarnings($output, $updaterResult['warnings']);
}
if (!empty($updaterResult['errors'])) {
$this->outputUpdaterErrors($output, $updaterResult['errors'], $updaterResult['deactivatedPlugins']);
}
if (!empty($updaterResult['warnings'])
|| !empty($updaterResult['errors'])
) {
$output->writeln(array(
" " . Piwik::translate('CoreUpdater_HelpMessageIntroductionWhenWarning'),
"",
" * " . $this->getUpdateHelpMessage()
));
}
}
private function handleCoreError(OutputInterface $output, $errors, $includeDiyHelp = false)
{
if (!is_array($errors)) {
$errors = array($errors);
}
$output->writeln(array(
"",
" [X] " . Piwik::translate('CoreUpdater_CriticalErrorDuringTheUpgradeProcess'),
"",
));
foreach ($errors as $errorMessage) {
$errorMessage = trim($errorMessage);
$errorMessage = str_replace("\n", "\n ", $errorMessage);
$output->writeln(" * $errorMessage");
}
$output->writeln(array(
"",
" " . Piwik::translate('CoreUpdater_HelpMessageIntroductionWhenError'),
"",
" * " . $this->getUpdateHelpMessage()
));
if ($includeDiyHelp) {
$output->writeln(array(
"",
" " . Piwik::translate('CoreUpdater_ErrorDIYHelp'),
"",
" * " . Piwik::translate('CoreUpdater_ErrorDIYHelp_1'),
" * " . Piwik::translate('CoreUpdater_ErrorDIYHelp_2'),
" * " . Piwik::translate('CoreUpdater_ErrorDIYHelp_3'),
" * " . Piwik::translate('CoreUpdater_ErrorDIYHelp_4'),
" * " . Piwik::translate('CoreUpdater_ErrorDIYHelp_5')
));
}
throw new \RuntimeException("Piwik could not be updated! See above for more information.");
}
private function outputUpdaterWarnings(OutputInterface $output, $warnings)
{
$output->writeln(array(
"",
" [!] " . Piwik::translate('CoreUpdater_WarningMessages'),
""
));
foreach ($warnings as $message) {
$output->writeln(" * $message");
}
}
private function outputUpdaterErrors(OutputInterface $output, $errors, $deactivatedPlugins)
{
$output->writeln(array(
"",
" [X] " . Piwik::translate('CoreUpdater_ErrorDuringPluginsUpdates'),
""
));
foreach ($errors as $message) {
$output->writeln(" * $message");
}
if (!empty($deactivatedPlugins)) {
$output->writeln(array(
"",
" [!] " . Piwik::translate('CoreUpdater_WeAutomaticallyDeactivatedTheFollowingPlugins', implode(', ', $deactivatedPlugins))
));
}
}
private function getUpdateHelpMessage()
{
return Piwik::translate('CoreUpdater_HelpMessageContent', array('[',']',"\n *"));
}
private function isUpdatingCore($componentsWithUpdateFile)
{
foreach ($componentsWithUpdateFile as $componentName => $updates) {
if ($componentName == 'core') {
return true;
}
}
return false;
}
private function getCurrentVersionForCore(Updater $updater)
{
$currentVersion = $updater->getCurrentComponentVersion('core');
if ($currentVersion === false) {
$currentVersion = "<= 0.2.9";
}
return $currentVersion;
}
private function getPluginsToUpdate($componentsWithUpdateFile)
{
$plugins = array();
foreach ($componentsWithUpdateFile as $componentName => $updates) {
if ($componentName !== 'core'
&& 0 !== strpos($componentName, 'log_')
) {
$plugins[] = $componentName;
}
}
return $plugins;
}
private function getDimensionsToUpdate($componentsWithUpdateFile)
{
$dimensions = array();
foreach ($componentsWithUpdateFile as $componentName => $updates) {
if (0 === strpos($componentName, 'log_')) {
$dimensions[] = $componentName;
}
}
sort($dimensions);
return $dimensions;
}
private function getMigrationQueriesToExecute(Updater $updater)
{
if (empty($this->migrationQueries)) {
$this->migrationQueries = $updater->getSqlQueriesToExecute();
}
return $this->migrationQueries;
}
private function makeUpdaterInstance(OutputInterface $output)
{
$updater = new Updater();
$migrationQueryCount = count($this->getMigrationQueriesToExecute($updater));
$updater->addUpdateObserver(new CliUpdateObserver($output, $migrationQueryCount));
return $updater;
}
}

View file

@ -0,0 +1,54 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater\Commands\Update;
use Piwik\Updater\UpdateObserver;
use Symfony\Component\Console\Output\OutputInterface;
/**
* UpdateObserver used to output progress of an update initiated on the command line. Prints the currently
* executing query and the total number of queries to run.
*
* @package CoreUpdater
*/
class CliUpdateObserver extends UpdateObserver
{
/**
* @var OutputInterface
*/
private $output;
/**
* @var int
*/
private $totalMigrationQueryCount;
/**
* @var int
*/
private $currentMigrationQueryExecutionCount = 0;
public function __construct(OutputInterface $output, $totalMigrationQueryCount)
{
$this->output = $output;
$this->totalMigrationQueryCount = $totalMigrationQueryCount;
}
public function onStartExecutingMigrationQuery($updateFile, $sql)
{
$this->output->write(" Executing <comment>$sql</comment>... ");
++$this->currentMigrationQueryExecutionCount;
}
public function onFinishedExecutingMigrationQuery($updateFile, $sql)
{
$this->output->writeln("Done. <info>[{$this->currentMigrationQueryExecutionCount} / {$this->totalMigrationQueryCount}]</info>");
}
}

View file

@ -1,6 +1,6 @@
<?php
/**
* Piwik - Open source web analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -9,7 +9,6 @@
namespace Piwik\Plugins\CoreUpdater;
use Exception;
use Piwik\ArchiveProcessor\Rules;
use Piwik\Common;
use Piwik\Config;
use Piwik\DbHelper;
@ -18,49 +17,45 @@ use Piwik\Filesystem;
use Piwik\Http;
use Piwik\Option;
use Piwik\Piwik;
use Piwik\Plugin\Manager as PluginManager;
use Piwik\Plugin;
use Piwik\Plugins\CorePluginsAdmin\Marketplace;
use Piwik\Plugins\LanguagesManager\LanguagesManager;
use Piwik\SettingsPiwik;
use Piwik\SettingsServer;
use Piwik\Unzip;
use Piwik\UpdateCheck;
use Piwik\Updater;
use Piwik\Updater as DbUpdater;
use Piwik\Version;
use Piwik\View;
use Piwik\View\OneClickDone;
use Piwik\Plugin\Manager as PluginManager;
use Piwik\View;
/**
*
*/
class Controller extends \Piwik\Plugin\Controller
{
const CONFIG_FILE_BACKUP = '/config/global.ini.auto-backup-before-update.php';
const PATH_TO_EXTRACT_LATEST_VERSION = '/tmp/latest/';
private $coreError = false;
private $warningMessages = array();
private $errorMessages = array();
private $deactivatedPlugins = array();
private $pathPiwikZip = false;
private $newVersion;
static protected function getLatestZipUrl($newVersion)
/**
* @var Updater
*/
private $updater;
public function __construct(Updater $updater)
{
if (@Config::getInstance()->Debug['allow_upgrades_to_beta']) {
return 'http://builds.piwik.org/piwik-' . $newVersion . '.zip';
}
return Config::getInstance()->General['latest_version_url'];
$this->updater = $updater;
parent::__construct();
}
public function newVersionAvailable()
{
Piwik::checkUserHasSuperUserAccess();
$this->checkNewVersionIsAvailableOrDie();
$newVersion = $this->checkNewVersionIsAvailableOrDie();
$newVersion = $this->updater->getLatestVersion();
$view = new View('@CoreUpdater/newVersionAvailable');
$this->addCustomLogoInfo($view);
$this->setBasicVariablesView($view);
$view->piwik_version = Version::VERSION;
$view->piwik_new_version = $newVersion;
@ -77,7 +72,7 @@ class Controller extends \Piwik\Plugin\Controller
$view->marketplacePlugins = $marketplacePlugins;
$view->incompatiblePlugins = $incompatiblePlugins;
$view->piwik_latest_version_url = self::getLatestZipUrl($newVersion);
$view->piwik_latest_version_url = $this->updater->getArchiveUrl($newVersion);
$view->can_auto_update = Filechecks::canAutoUpdate();
$view->makeWritableCommands = Filechecks::getAutoUpdateMakeWritableMessage();
@ -87,58 +82,49 @@ class Controller extends \Piwik\Plugin\Controller
public function oneClickUpdate()
{
Piwik::checkUserHasSuperUserAccess();
$this->newVersion = $this->checkNewVersionIsAvailableOrDie();
SettingsServer::setMaxExecutionTime(0);
$url = self::getLatestZipUrl($this->newVersion);
$steps = array(
array('oneClick_Download', Piwik::translate('CoreUpdater_DownloadingUpdateFromX', $url)),
array('oneClick_Unpack', Piwik::translate('CoreUpdater_UnpackingTheUpdate')),
array('oneClick_Verify', Piwik::translate('CoreUpdater_VerifyingUnpackedFiles')),
array('oneClick_CreateConfigFileBackup', Piwik::translate('CoreUpdater_CreatingBackupOfConfigurationFile', self::CONFIG_FILE_BACKUP))
);
$incompatiblePlugins = $this->getIncompatiblePlugins($this->newVersion);
if (!empty($incompatiblePlugins)) {
$namesToDisable = array();
foreach ($incompatiblePlugins as $incompatiblePlugin) {
$namesToDisable[] = $incompatiblePlugin->getPluginName();
}
$steps[] = array('oneClick_DisableIncompatiblePlugins', Piwik::translate('CoreUpdater_DisablingIncompatiblePlugins', implode(', ', $namesToDisable)));
}
$steps[] = array('oneClick_Copy', Piwik::translate('CoreUpdater_InstallingTheLatestVersion'));
$steps[] = array('oneClick_Finished', Piwik::translate('CoreUpdater_PiwikUpdatedSuccessfully'));
$errorMessage = false;
$messages = array();
foreach ($steps as $step) {
try {
$method = $step[0];
$message = $step[1];
$this->$method();
$messages[] = $message;
} catch (Exception $e) {
$errorMessage = $e->getMessage();
break;
}
}
$view = new OneClickDone(Piwik::getCurrentUserTokenAuth());
$view->coreError = $errorMessage;
$useHttps = Common::getRequestVar('https', 1, 'int');
try {
$messages = $this->updater->updatePiwik($useHttps);
} catch (ArchiveDownloadException $e) {
$view->httpsFail = $useHttps;
$view->error = $e->getMessage();
$messages = $e->getUpdateLogMessages();
} catch (UpdaterException $e) {
$view->error = $e->getMessage();
$messages = $e->getUpdateLogMessages();
}
$view->feedbackMessages = $messages;
$this->addCustomLogoInfo($view);
return $view->render();
}
public function oneClickResults()
{
$view = new View('@CoreUpdater/oneClickResults');
$view->coreError = Common::getRequestVar('error', '', 'string', $_POST);
$view->feedbackMessages = safe_unserialize(Common::unsanitizeInputValue(Common::getRequestVar('messages', '', 'string', $_POST)));
$httpsFail = (bool) Common::getRequestVar('httpsFail', 0, 'int', $_POST);
$error = Common::getRequestVar('error', '', 'string', $_POST);
if ($httpsFail) {
$view = new View('@CoreUpdater/updateHttpsError');
$view->error = $error;
} elseif ($error) {
$view = new View('@CoreUpdater/updateHttpError');
$view->error = $error;
$view->feedbackMessages = safe_unserialize(Common::unsanitizeInputValue(Common::getRequestVar('messages', '', 'string', $_POST)));
} else {
$view = new View('@CoreUpdater/updateSuccess');
}
$this->addCustomLogoInfo($view);
$this->setBasicVariablesView($view);
return $view->render();
}
protected function redirectToDashboardWhenNoError($updater)
protected function redirectToDashboardWhenNoError(DbUpdater $updater)
{
if (count($updater->getSqlQueriesToExecute()) == 1
&& !$this->coreError
@ -150,147 +136,11 @@ class Controller extends \Piwik\Plugin\Controller
}
}
protected static function clearPhpCaches()
{
if (function_exists('apc_clear_cache')) {
apc_clear_cache(); // clear the system (aka 'opcode') cache
}
if (function_exists('opcache_reset')) {
opcache_reset(); // reset the opcode cache (php 5.5.0+)
}
}
private function checkNewVersionIsAvailableOrDie()
{
$newVersion = UpdateCheck::isNewestVersionAvailable();
if (!$newVersion) {
if (!$this->updater->isNewVersionAvailable()) {
throw new Exception(Piwik::translate('CoreUpdater_ExceptionAlreadyLatestVersion', Version::VERSION));
}
return $newVersion;
}
private function oneClick_Download()
{
$pathPiwikZip = PIWIK_USER_PATH . self::PATH_TO_EXTRACT_LATEST_VERSION . 'latest.zip';
$this->pathPiwikZip = SettingsPiwik::rewriteTmpPathWithHostname($pathPiwikZip);
Filechecks::dieIfDirectoriesNotWritable(array(self::PATH_TO_EXTRACT_LATEST_VERSION));
// we catch exceptions in the caller (i.e., oneClickUpdate)
$url = self::getLatestZipUrl($this->newVersion) . '?cb=' . $this->newVersion;
Http::fetchRemoteFile($url, $this->pathPiwikZip);
}
private function oneClick_Unpack()
{
$pathExtracted = PIWIK_USER_PATH . self::PATH_TO_EXTRACT_LATEST_VERSION;
$pathExtracted = SettingsPiwik::rewriteTmpPathWithHostname($pathExtracted);
$this->pathRootExtractedPiwik = $pathExtracted . 'piwik';
if (file_exists($this->pathRootExtractedPiwik)) {
Filesystem::unlinkRecursive($this->pathRootExtractedPiwik, true);
}
$archive = Unzip::factory('PclZip', $this->pathPiwikZip);
if (0 == ($archive_files = $archive->extract($pathExtracted))) {
throw new Exception(Piwik::translate('CoreUpdater_ExceptionArchiveIncompatible', $archive->errorInfo()));
}
if (0 == count($archive_files)) {
throw new Exception(Piwik::translate('CoreUpdater_ExceptionArchiveEmpty'));
}
unlink($this->pathPiwikZip);
}
private function oneClick_Verify()
{
$someExpectedFiles = array(
'/config/global.ini.php',
'/index.php',
'/core/Piwik.php',
'/piwik.php',
'/plugins/API/API.php'
);
foreach ($someExpectedFiles as $file) {
if (!is_file($this->pathRootExtractedPiwik . $file)) {
throw new Exception(Piwik::translate('CoreUpdater_ExceptionArchiveIncomplete', $file));
}
}
}
private function oneClick_CreateConfigFileBackup()
{
$configFileBefore = PIWIK_USER_PATH . '/config/global.ini.php';
$configFileAfter = PIWIK_USER_PATH . self::CONFIG_FILE_BACKUP;
Filesystem::copy($configFileBefore, $configFileAfter);
}
private function oneClick_DisableIncompatiblePlugins()
{
$plugins = $this->getIncompatiblePlugins($this->newVersion);
foreach ($plugins as $plugin) {
PluginManager::getInstance()->deactivatePlugin($plugin->getPluginName());
}
}
private function oneClick_Copy()
{
/*
* Make sure the execute bit is set for this shell script
*/
if (!Rules::isBrowserTriggerEnabled()) {
@chmod($this->pathRootExtractedPiwik . '/misc/cron/archive.sh', 0755);
}
/*
* Copy all files to PIWIK_INCLUDE_PATH.
* These files are accessed through the dispatcher.
*/
Filesystem::copyRecursive($this->pathRootExtractedPiwik, PIWIK_INCLUDE_PATH);
/*
* These files are visible in the web root and are generally
* served directly by the web server. May be shared.
*/
if (PIWIK_INCLUDE_PATH !== PIWIK_DOCUMENT_ROOT) {
/*
* Copy PHP files that expect to be in the document root
*/
$specialCases = array(
'/index.php',
'/piwik.php',
'/js/index.php',
);
foreach ($specialCases as $file) {
Filesystem::copy($this->pathRootExtractedPiwik . $file, PIWIK_DOCUMENT_ROOT . $file);
}
/*
* Copy the non-PHP files (e.g., images, css, javascript)
*/
Filesystem::copyRecursive($this->pathRootExtractedPiwik, PIWIK_DOCUMENT_ROOT, true);
}
/*
* Config files may be user (account) specific
*/
if (PIWIK_INCLUDE_PATH !== PIWIK_USER_PATH) {
Filesystem::copyRecursive($this->pathRootExtractedPiwik . '/config', PIWIK_USER_PATH . '/config');
}
Filesystem::unlinkRecursive($this->pathRootExtractedPiwik, true);
self::clearPhpCaches();
}
private function oneClick_Finished()
{
}
public function index()
@ -309,47 +159,38 @@ class Controller extends \Piwik\Plugin\Controller
public function runUpdaterAndExit($doDryRun = null)
{
$updater = new Updater();
$componentsWithUpdateFile = CoreUpdater::getComponentUpdates($updater);
$updater = new DbUpdater();
$componentsWithUpdateFile = $updater->getComponentUpdates();
if (empty($componentsWithUpdateFile)) {
throw new NoUpdatesFoundException("Everything is already up to date.");
}
SettingsServer::setMaxExecutionTime(0);
$cli = Common::isPhpCliMode() ? '_cli' : '';
$welcomeTemplate = '@CoreUpdater/runUpdaterAndExit_welcome' . $cli;
$doneTemplate = '@CoreUpdater/runUpdaterAndExit_done' . $cli;
$welcomeTemplate = '@CoreUpdater/runUpdaterAndExit_welcome';
$doneTemplate = '@CoreUpdater/runUpdaterAndExit_done';
$viewWelcome = new View($welcomeTemplate);
$this->addCustomLogoInfo($viewWelcome);
$this->setBasicVariablesView($viewWelcome);
$viewDone = new View($doneTemplate);
$this->addCustomLogoInfo($viewDone);
$this->setBasicVariablesView($viewDone);
$doExecuteUpdates = Common::getRequestVar('updateCorePlugins', 0, 'integer') == 1;
if(is_null($doDryRun)) {
if (is_null($doDryRun)) {
$doDryRun = !$doExecuteUpdates;
}
if($doDryRun) {
if ($doDryRun) {
$viewWelcome->queries = $updater->getSqlQueriesToExecute();
$viewWelcome->isMajor = $updater->hasMajorDbUpdate();
$this->doWelcomeUpdates($viewWelcome, $componentsWithUpdateFile);
return $viewWelcome->render();
}
// CLI
if (Common::isPhpCliMode()) {
$this->doWelcomeUpdates($viewWelcome, $componentsWithUpdateFile);
$output = $viewWelcome->render();
// Proceed with upgrade in CLI only if user specifically asked for it, or if running console command
$isUpdateRequested = Common::isRunningConsoleCommand() || Piwik::getModule() == 'CoreUpdater';
if (!$this->coreError && $isUpdateRequested) {
$this->doExecuteUpdates($viewDone, $updater, $componentsWithUpdateFile);
$output .= $viewDone->render();
}
return $output;
}
// Web
if ($doExecuteUpdates) {
$this->warningMessages = array();
@ -366,8 +207,9 @@ class Controller extends \Piwik\Plugin\Controller
private function doWelcomeUpdates($view, $componentsWithUpdateFile)
{
$view->new_piwik_version = Version::VERSION;
$view->commandUpgradePiwik = "<br /><code>php " . Filesystem::getPathToPiwikRoot() . "/console core:update </code>";
$view->commandUpgradePiwik = "php " . Filesystem::getPathToPiwikRoot() . "/console core:update";
$pluginNamesToUpdate = array();
$dimensionsToUpdate = array();
$coreToUpdate = false;
// handle case of existing database with no tables
@ -386,6 +228,8 @@ class Controller extends \Piwik\Plugin\Controller
foreach ($componentsWithUpdateFile as $name => $filenames) {
if ($name == 'core') {
$coreToUpdate = true;
} elseif (0 === strpos($name, 'log_')) {
$dimensionsToUpdate[] = $name;
} else {
$pluginNamesToUpdate[] = $name;
}
@ -402,17 +246,20 @@ class Controller extends \Piwik\Plugin\Controller
}
Filesystem::deleteAllCacheOnUpdate();
sort($dimensionsToUpdate);
$view->coreError = $this->coreError;
$view->warningMessages = $this->warningMessages;
$view->errorMessages = $this->errorMessages;
$view->current_piwik_version = $currentVersion;
$view->pluginNamesToUpdate = $pluginNamesToUpdate;
$view->dimensionsToUpdate = $dimensionsToUpdate;
$view->coreToUpdate = $coreToUpdate;
}
private function doExecuteUpdates($view, $updater, $componentsWithUpdateFile)
private function doExecuteUpdates($view, DbUpdater $updater, $componentsWithUpdateFile)
{
$result = CoreUpdater::updateComponents($updater, $componentsWithUpdateFile);
$result = $updater->updateComponents($componentsWithUpdateFile);
$this->coreError = $result['coreError'];
$this->warningMessages = $result['warnings'];
@ -429,4 +276,11 @@ class Controller extends \Piwik\Plugin\Controller
return PluginManager::getInstance()->getIncompatiblePlugins($piwikVersion);
}
public static function isUpdatingOverHttps()
{
$openSslEnabled = extension_loaded('openssl');
$usingMethodSupportingHttps = (Http::getTransportMethod() !== 'socket');
return $openSslEnabled && $usingMethodSupportingHttps;
}
}

View file

@ -1,6 +1,6 @@
<?php
/**
* Piwik - Open source web analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -9,17 +9,14 @@
namespace Piwik\Plugins\CoreUpdater;
use Exception;
use Piwik\API\ResponseBuilder;
use Piwik\Common;
use Piwik\Filesystem;
use Piwik\FrontController;
use Piwik\Piwik;
use Piwik\ScheduledTask;
use Piwik\ScheduledTime;
use Piwik\UpdateCheck;
use Piwik\Updater;
use Piwik\UpdaterErrorException;
use Piwik\Updater as PiwikCoreUpdater;
use Piwik\Version;
use Piwik\Access;
/**
*
@ -27,101 +24,30 @@ use Piwik\Access;
class CoreUpdater extends \Piwik\Plugin
{
/**
* @see Piwik\Plugin::getListHooksRegistered
* @see Piwik\Plugin::registerEvents
*/
public function getListHooksRegistered()
public function registerEvents()
{
$hooks = array(
return array(
'Request.dispatchCoreAndPluginUpdatesScreen' => 'dispatch',
'Platform.initialized' => 'updateCheck',
'TaskScheduler.getScheduledTasks' => 'getScheduledTasks',
);
return $hooks;
}
public function getScheduledTasks(&$tasks)
/**
* @deprecated
*/
public static function updateComponents(PiwikCoreUpdater $updater, $componentsWithUpdateFile)
{
$sendUpdateNotification = new ScheduledTask($this,
'sendNotificationIfUpdateAvailable',
null,
ScheduledTime::factory('daily'),
ScheduledTask::LOWEST_PRIORITY);
$tasks[] = $sendUpdateNotification;
return $updater->updateComponents($componentsWithUpdateFile);
}
public function sendNotificationIfUpdateAvailable()
/**
* @deprecated
*/
public static function getComponentUpdates(PiwikCoreUpdater $updater)
{
$coreUpdateCommunication = new UpdateCommunication();
if ($coreUpdateCommunication->isEnabled()) {
$coreUpdateCommunication->sendNotificationIfUpdateAvailable();
}
}
public static function updateComponents(Updater $updater, $componentsWithUpdateFile)
{
$warnings = array();
$errors = array();
$deactivatedPlugins = array();
$coreError = false;
if (!empty($componentsWithUpdateFile)) {
$currentAccess = Access::getInstance();
$hasSuperUserAccess = $currentAccess->hasSuperUserAccess();
if (!$hasSuperUserAccess) {
$currentAccess->setSuperUserAccess(true);
}
// if error in any core update, show message + help message + EXIT
// if errors in any plugins updates, show them on screen, disable plugins that errored + CONTINUE
// if warning in any core update or in any plugins update, show message + CONTINUE
// if no error or warning, success message + CONTINUE
foreach ($componentsWithUpdateFile as $name => $filenames) {
try {
$warnings = array_merge($warnings, $updater->update($name));
} catch (UpdaterErrorException $e) {
$errors[] = $e->getMessage();
if ($name == 'core') {
$coreError = true;
break;
} else {
\Piwik\Plugin\Manager::getInstance()->deactivatePlugin($name);
$deactivatedPlugins[] = $name;
}
}
}
if (!$hasSuperUserAccess) {
$currentAccess->setSuperUserAccess(false);
}
}
Filesystem::deleteAllCacheOnUpdate();
$result = array(
'warnings' => $warnings,
'errors' => $errors,
'coreError' => $coreError,
'deactivatedPlugins' => $deactivatedPlugins
);
return $result;
}
public static function getComponentUpdates(Updater $updater)
{
$updater->addComponentToCheck('core', Version::VERSION);
$plugins = \Piwik\Plugin\Manager::getInstance()->getLoadedPlugins();
foreach ($plugins as $pluginName => $plugin) {
$updater->addComponentToCheck($pluginName, $plugin->getVersion());
}
$componentsWithUpdateFile = $updater->getComponentsWithUpdateFile();
if (count($componentsWithUpdateFile) == 0 && !$updater->hasNewVersion('core')) {
return null;
}
return $componentsWithUpdateFile;
return $updater->getComponentUpdates();
}
public function dispatch()
@ -129,13 +55,12 @@ class CoreUpdater extends \Piwik\Plugin
$module = Common::getRequestVar('module', '', 'string');
$action = Common::getRequestVar('action', '', 'string');
$updater = new Updater();
$updater->addComponentToCheck('core', Version::VERSION);
$updates = $updater->getComponentsWithNewVersion();
$updater = new PiwikCoreUpdater();
$updates = $updater->getComponentsWithNewVersion(array('core' => Version::VERSION));
if (!empty($updates)) {
Filesystem::deleteAllCacheOnUpdate();
}
if (self::getComponentUpdates($updater) !== null
if ($updater->getComponentUpdates() !== null
&& $module != 'CoreUpdater'
// Proxy module is used to redirect users to piwik.org, should still work when Piwik must be updated
&& $module != 'Proxy'
@ -147,6 +72,15 @@ class CoreUpdater extends \Piwik\Plugin
if (FrontController::shouldRethrowException()) {
throw new Exception("Piwik and/or some plugins have been upgraded to a new version. \n" .
"--> Please run the update process first. See documentation: http://piwik.org/docs/update/ \n");
} elseif ($module === 'API') {
$outputFormat = strtolower(Common::getRequestVar('format', 'xml', 'string', $_GET + $_POST));
$response = new ResponseBuilder($outputFormat);
$e = new Exception('Database Upgrade Required. Your Piwik database is out-of-date, and must be upgraded before you can continue.');
echo $response->getResponseException($e);
Common::sendResponseCode(503);
exit;
} else {
Piwik::redirectToModule('CoreUpdater');
}

View file

@ -0,0 +1,43 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater\Diagnostic;
use Piwik\Config;
use Piwik\Plugins\CoreUpdater;
use Piwik\Plugins\Diagnostics\Diagnostic\Diagnostic;
use Piwik\Plugins\Diagnostics\Diagnostic\DiagnosticResult;
use Piwik\Translation\Translator;
/**
* Check the HTTPS update.
*/
class HttpsUpdateCheck implements Diagnostic
{
/**
* @var Translator
*/
private $translator;
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
public function execute()
{
$label = $this->translator->translate('Installation_SystemCheckUpdateHttps');
if (CoreUpdater\Controller::isUpdatingOverHttps()) {
return array(DiagnosticResult::singleResult($label, DiagnosticResult::STATUS_OK));
}
$comment = $this->translator->translate('Installation_SystemCheckUpdateHttpsNotSupported');
return array(DiagnosticResult::singleResult($label, DiagnosticResult::STATUS_WARNING, $comment));
}
}

View file

@ -0,0 +1,34 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater;
use Piwik\Filesystem;
class Model
{
public function getPluginsFromDirectoy($directoryToLook)
{
$directories = _glob($directoryToLook . '/plugins/' . '*', GLOB_ONLYDIR);
$directories = array_map(function ($directory) use ($directoryToLook) {
return str_replace($directoryToLook, '', $directory);
}, $directories);
return $directories;
}
public function removeGoneFiles($source, $target)
{
Filesystem::unlinkTargetFilesNotPresentInSource($source . '/core', $target . '/core');
foreach ($this->getPluginsFromDirectoy($source) as $pluginDir) {
Filesystem::unlinkTargetFilesNotPresentInSource($source . $pluginDir, $target . $pluginDir);
}
}
}

View file

@ -1,6 +1,6 @@
<?php
/**
* Piwik - Open source web analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later

View file

@ -0,0 +1,43 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater;
use Piwik\Common;
use Piwik\Config;
use Piwik\Http;
use Piwik\Plugins\SitesManager\API;
use Piwik\Url;
use Piwik\Version;
use Piwik\UpdateCheck\ReleaseChannel as BaseReleaseChannel;
abstract class ReleaseChannel extends BaseReleaseChannel
{
public function getUrlToCheckForLatestAvailableVersion()
{
$parameters = array(
'piwik_version' => Version::VERSION,
'php_version' => PHP_VERSION,
'release_channel' => $this->getId(),
'url' => Url::getCurrentUrlWithoutQueryString(),
'trigger' => Common::getRequestVar('module', '', 'string'),
'timezone' => API::getInstance()->getDefaultTimezone(),
);
$url = Config::getInstance()->General['api_service_url']
. '/1.0/getLatestVersion/'
. '?' . http_build_query($parameters, '', '&');
return $url;
}
public function getDownloadUrlWithoutScheme($version)
{
return sprintf('://builds.piwik.org/piwik-%s.zip', $version);
}
}

View file

@ -0,0 +1,35 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater\ReleaseChannel;
use Piwik\Piwik;
use Piwik\Plugins\CoreUpdater\ReleaseChannel;
class Latest2XBeta extends ReleaseChannel
{
public function getId()
{
return 'latest_2x_beta';
}
public function getName()
{
return Piwik::translate('CoreUpdater_Latest2XBetaRelease');
}
public function getDescription()
{
return Piwik::translate('CoreUpdater_LtsSupportVersion');
}
public function getOrder()
{
return 21;
}
}

View file

@ -0,0 +1,35 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater\ReleaseChannel;
use Piwik\Piwik;
use Piwik\Plugins\CoreUpdater\ReleaseChannel;
class Latest2XStable extends ReleaseChannel
{
public function getId()
{
return 'latest_2x_stable';
}
public function getName()
{
return Piwik::translate('CoreUpdater_Latest2XStableRelease');
}
public function getDescription()
{
return Piwik::translate('CoreUpdater_LtsSupportVersion');
}
public function getOrder()
{
return 20;
}
}

View file

@ -0,0 +1,30 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater\ReleaseChannel;
use Piwik\Piwik;
use Piwik\Plugins\CoreUpdater\ReleaseChannel;
class LatestBeta extends ReleaseChannel
{
public function getId()
{
return 'latest_beta';
}
public function getName()
{
return Piwik::translate('CoreUpdater_LatestBetaRelease');
}
public function getOrder()
{
return 11;
}
}

View file

@ -0,0 +1,40 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater\ReleaseChannel;
use Piwik\Piwik;
use Piwik\Plugins\CoreUpdater\ReleaseChannel;
class LatestStable extends ReleaseChannel
{
public function getId()
{
return 'latest_stable';
}
public function getName()
{
return Piwik::translate('CoreUpdater_LatestStableRelease');
}
public function getDescription()
{
return Piwik::translate('General_Recommended');
}
public function getDownloadUrlWithoutScheme($version)
{
return '://builds.piwik.org/piwik.zip';
}
public function getOrder()
{
return 10;
}
}

View file

@ -0,0 +1,25 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\CoreUpdater;
class Tasks extends \Piwik\Plugin\Tasks
{
public function schedule()
{
$this->daily('sendNotificationIfUpdateAvailable', null, self::LOWEST_PRIORITY);
}
public function sendNotificationIfUpdateAvailable()
{
$coreUpdateCommunication = new UpdateCommunication();
if ($coreUpdateCommunication->isEnabled()) {
$coreUpdateCommunication->sendNotificationIfUpdateAvailable();
}
}
}

View file

@ -0,0 +1,23 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater\Test\Fixtures;
use Piwik\Tests\Fixtures\SqlDump;
class DbUpdaterTestFixture extends SqlDump
{
public function performSetUp($setupEnvironmentOnly = false)
{
$this->dumpUrl = PIWIK_INCLUDE_PATH . "/tests/UI/resources/piwik1.0.sql.gz";
$this->dropDatabaseInSetUp = true;
$this->resetPersistedFixture = true;
parent::performSetUp($setupEnvironmentOnly);
}
}

View file

@ -0,0 +1,24 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater\Test\Fixtures;
use Piwik\Tests\Framework\Fixture;
/**
* Fixture that makes the update over HTTPS fail to be able to test that users can still update over HTTP.
*/
class FailUpdateHttpsFixture extends Fixture
{
public function provideContainerConfig()
{
return array(
'Piwik\Plugins\CoreUpdater\Updater' => \DI\object('Piwik\Plugins\CoreUpdater\Test\Mock\UpdaterMock'),
);
}
}

View file

@ -0,0 +1,123 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater\Test\Integration\Commands;
use Piwik\Config;
use Piwik\DataAccess\ArchiveTableCreator;
use Piwik\Date;
use Piwik\Db;
use Piwik\DbHelper;
use Piwik\Option;
use Piwik\Tests\Framework\TestCase\ConsoleCommandTestCase;
use Piwik\Updates\Updates_2_10_0_b5;
use Piwik\Version;
use Symfony\Component\Console\Helper\QuestionHelper;
require_once PIWIK_INCLUDE_PATH . '/core/Updates/2.10.0-b5.php';
/**
* @group CoreUpdater
*/
class UpdateTest extends ConsoleCommandTestCase
{
const VERSION_TO_UPDATE_FROM = '2.9.0';
const EXPECTED_SQL_FROM_2_10 = "UPDATE report SET reports = REPLACE(reports, 'UserSettings_getBrowserVersion', 'DevicesDetection_getBrowserVersions');";
private $oldScriptName = null;
public function setUp()
{
parent::setUp();
Option::set('version_core', self::VERSION_TO_UPDATE_FROM);
$this->oldScriptName = $_SERVER['SCRIPT_NAME'];
$_SERVER['SCRIPT_NAME'] = $_SERVER['SCRIPT_NAME'] . " console"; // update won't execute w/o this, see Common::isRunningConsoleCommand()
ArchiveTableCreator::clear();
DbHelper::getTablesInstalled($forceReload = true); // force reload so internal cache in Mysql.php is refreshed
Updates_2_10_0_b5::$archiveBlobTables = null;
}
public function tearDown()
{
$_SERVER['SCRIPT_NAME'] = $this->oldScriptName;
parent::tearDown();
}
public function test_UpdateCommand_SuccessfullyExecutesUpdate()
{
$result = $this->applicationTester->run(array(
'command' => 'core:update',
'--yes' => true
));
$this->assertEquals(0, $result, $this->getCommandDisplayOutputErrorMessage());
$this->assertDryRunExecuted($this->applicationTester->getDisplay());
// make sure update went through
$this->assertEquals(Version::VERSION, Option::get('version_core'));
}
public function test_UpdateCommand_DoesntExecuteSql_WhenUserSaysNo()
{
/** @var QuestionHelper $dialog */
$dialog = $this->application->getHelperSet()->get('question');
$dialog->setInputStream($this->getInputStream("N\n"));
$result = $this->applicationTester->run(array(
'command' => 'core:update'
));
$this->assertEquals(0, $result, $this->getCommandDisplayOutputErrorMessage());
$this->assertDryRunExecuted($this->applicationTester->getDisplay());
// make sure update did not go through
$this->assertEquals(self::VERSION_TO_UPDATE_FROM, Option::get('version_core'));
}
public function test_UpdateCommand_DoesNotExecuteUpdate_IfPiwikUpToDate()
{
Option::set('version_core', Version::VERSION);
$result = $this->applicationTester->run(array(
'command' => 'core:update',
'--yes' => true
));
$this->assertEquals(0, $result, $this->getCommandDisplayOutputErrorMessage());
// check no update occurred
$this->assertContains("Everything is already up to date.", $this->applicationTester->getDisplay());
$this->assertEquals(Version::VERSION, Option::get('version_core'));
}
public function test_UpdateCommand_ReturnsCorrectExitCode_WhenErrorOccurs()
{
// create a blob table, then drop it manually so update 2.10.0-b10 will fail
$tableName = ArchiveTableCreator::getBlobTable(Date::factory('2015-01-01'));
Db::exec("DROP TABLE $tableName");
$result = $this->applicationTester->run(array(
'command' => 'core:update',
'--yes' => true
));
$this->assertEquals(1, $result, $this->getCommandDisplayOutputErrorMessage());
$this->assertContains("Piwik could not be updated! See above for more information.", $this->applicationTester->getDisplay());
}
private function assertDryRunExecuted($output)
{
$this->assertContains("Note: this is a Dry Run", $output);
$this->assertContains(self::EXPECTED_SQL_FROM_2_10, $output);
}
}

View file

@ -0,0 +1,66 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater\Test\ReleaseChannel;
use Piwik\Config;
use Piwik\Plugins\CoreUpdater\ReleaseChannel;
use Piwik\UpdateCheck;
use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
use Piwik\Url;
use Piwik\Version;
class MyReleaseChannel extends ReleaseChannel
{
public function getId()
{
return 'my_channel';
}
public function getName()
{
return 'My Special Channel';
}
}
/**
* @group Plugins
* @group ReleaseChannel
* @group ReleaseChannelTest
*/
class ReleaseChannelTest extends IntegrationTestCase
{
/**
* @var MyReleaseChannel
*/
private $channel;
public function setUp()
{
parent::setUp();
$this->channel = new MyReleaseChannel();
}
public function test_getDownloadUrlWithoutScheme_shouldReturnUrlWithVersionNumberButWithoutScheme()
{
$this->assertSame('://builds.piwik.org/piwik-2.15.0-b5.zip', $this->channel->getDownloadUrlWithoutScheme('2.15.0-b5'));
}
public function test_getUrlToCheckForLatestAvailableVersion()
{
$version = Version::VERSION;
$phpVersion = urlencode(PHP_VERSION);
$url = urlencode(Url::getCurrentUrlWithoutQueryString());
$urlToCheck = $this->channel->getUrlToCheckForLatestAvailableVersion();
$this->assertStringStartsWith("http://api.piwik.org/1.0/getLatestVersion/?piwik_version=$version&php_version=$phpVersion&release_channel=my_channel&url=$url&trigger=&timezone=", $urlToCheck);
}
}

View file

@ -0,0 +1,146 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater\Test;
use Piwik\Config;
use Piwik\Option;
use Piwik\Plugins\CoreUpdater\UpdateCommunication;
use Piwik\Tests\Framework\Fixture;
use Piwik\UpdateCheck;
use Piwik\Version;
use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
/**
* @group Plugins
*/
class UpdateCommunicationTest extends IntegrationTestCase
{
public function setUp()
{
parent::setUp();
}
public function test_isEnabled()
{
$updateCommunication = new UpdateCommunication();
$this->assertTrue($updateCommunication->isEnabled());
Config::getInstance()->General['enable_update_communication'] = 0;
$this->assertFalse($updateCommunication->isEnabled());
Config::getInstance()->General['enable_update_communication'] = 1;
$this->assertTrue($updateCommunication->isEnabled());
}
/**
* @dataProvider provideSendNotificationData
*/
public function test_sendNotificationIfUpdateAvailable($latestVersion, $lastSentVersion, $expects, $expectedLastSentVersion)
{
$this->setLatestVersion($latestVersion);
$this->setLastSentVersion($lastSentVersion);
$mock = $this->getCommunicationMock(array('sendNotifications'));
$mock->expects($expects)->method('sendNotifications');
$mock->sendNotificationIfUpdateAvailable();
$this->assertEquals($expectedLastSentVersion, $this->getLastSentVersion());
}
public function provideSendNotificationData()
{
return array(
array(Version::VERSION, false, $this->never(), false), // shouldNotSend_IfNoUpdateAvailable
array('33.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotified
array('31.0.0', '33.0.0', $this->never(), '33.0.0'), // shouldNotSend_IfAlreadyNotifiedAboutLaterRelease
array('3333.3333.3333-bbeta10', '31.0.0', $this->never(), '31.0.0'), // shouldNotSend_IfLatestVersionIsNotVersionLike,
array('33.0.0', false, $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailableAndNeverSentAnyBefore
array('33.0.0', '31.0.0', $this->once(), '33.0.0'), // shouldSend_IfUpdateAvailable
);
}
public function test_sendNotifications_shouldSentCorrectEmail()
{
$rootUrl = Fixture::getTestRootUrl();
$message = "ScheduledReports_EmailHello
CoreUpdater_ThereIsNewVersionAvailableForUpdate
CoreUpdater_YouCanUpgradeAutomaticallyOrDownloadPackage
{$rootUrl}index.php?module=CoreUpdater&action=newVersionAvailable
CoreUpdater_ViewVersionChangelog
http://piwik.org/changelog/piwik-33-0-0/
CoreUpdater_FeedbackRequest
http://piwik.org/contact/";
$this->assertEmailForVersion('33.0.0', $message);
}
public function test_sendNotifications_shouldNotIncludeChangelogIfNotMajorVersionUpdate()
{
$rootUrl = Fixture::getTestRootUrl();
$message = "ScheduledReports_EmailHello
CoreUpdater_ThereIsNewVersionAvailableForUpdate
CoreUpdater_YouCanUpgradeAutomaticallyOrDownloadPackage
{$rootUrl}index.php?module=CoreUpdater&action=newVersionAvailable
CoreUpdater_FeedbackRequest
http://piwik.org/contact/";
$this->assertEmailForVersion('33.0.0-b1', $message);
}
private function assertEmailForVersion($version, $expectedMessage)
{
$this->setLatestVersion($version);
$subject = 'CoreUpdater_NotificationSubjectAvailableCoreUpdate';
$mock = $this->getCommunicationMock(array('sendEmailNotification'));
$mock->expects($this->once())
->method('sendEmailNotification')
->with($this->equalTo($subject), $this->equalTo($expectedMessage));
$mock->sendNotificationIfUpdateAvailable();
}
private function setLastSentVersion($value)
{
Option::set('last_update_communication_sent_core', $value);
}
private function getLastSentVersion()
{
return Option::get('last_update_communication_sent_core');
}
private function setLatestVersion($value)
{
$this->preventVersionIsOverwrittenByActualVersionCheck();
Option::set(UpdateCheck::LATEST_VERSION, $value);
}
private function preventVersionIsOverwrittenByActualVersionCheck()
{
Config::getInstance()->General['enable_auto_update'] = false;
}
/**
* @param array $methodsToOverwrite
* @return UpdateCommunication
*/
private function getCommunicationMock($methodsToOverwrite)
{
return $this->getMock('\Piwik\Plugins\CoreUpdater\UpdateCommunication', $methodsToOverwrite);
}
}

View file

@ -0,0 +1,59 @@
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\CoreUpdater\Test\Mock;
use Piwik\Plugins\CoreUpdater\ArchiveDownloadException;
use Piwik\Plugins\CoreUpdater\Updater;
use Piwik\Translation\Translator;
class UpdaterMock extends Updater
{
/**
* @var Translator
*/
private $translator;
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
public function getLatestVersion()
{
return '4.0.0';
}
public function isNewVersionAvailable()
{
return true;
}
public function getArchiveUrl($version, $https = true)
{
return 'http://builds.piwik.org/piwik.zip';
}
public function updatePiwik($https = true)
{
// Simulate that the update over HTTPS fails
if ($https) {
// The actual error message depends on the OS, the HTTP method etc.
// This is what I get on my machine, but it doesn't really matter
throw new ArchiveDownloadException(new \Exception('curl_exec: SSL certificate problem: Invalid certificate chain. Hostname requested was: piwik.org'), array());
}
// Simulate that the update over HTTP succeeds
return array(
$this->translator->translate('CoreUpdater_DownloadingUpdateFromX', ''),
$this->translator->translate('CoreUpdater_UnpackingTheUpdate'),
$this->translator->translate('CoreUpdater_VerifyingUnpackedFiles'),
$this->translator->translate('CoreUpdater_InstallingTheLatestVersion'),
);
}
}

Some files were not shown because too many files have changed in this diff Show more