1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\Marketplace;
use Exception;
use Piwik\Common;
use Piwik\Config\GeneralConfig;
use Piwik\Container\StaticContainer;
use Piwik\DataTable\Renderer\Json;
use Piwik\Date;
use Piwik\Filesystem;
use Piwik\Log;
use Piwik\Nonce;
use Piwik\Notification;
use Piwik\Piwik;
use Piwik\Plugin;
use Piwik\Plugins\CorePluginsAdmin\Controller as PluginsController;
use Piwik\Plugins\CorePluginsAdmin\CorePluginsAdmin;
use Piwik\Plugins\CorePluginsAdmin\PluginInstaller;
use Piwik\Plugins\Login\PasswordVerifier;
use Piwik\Plugins\Marketplace\Input\PluginName;
use Piwik\Plugins\Marketplace\Input\PurchaseType;
use Piwik\Plugins\Marketplace\Input\Sort;
use Piwik\Plugins\Marketplace\PluginTrial\Service as PluginTrialService;
use Piwik\ProxyHttp;
use Piwik\Request;
use Piwik\SettingsPiwik;
use Piwik\SettingsServer;
use Piwik\Url;
use Piwik\View;
class Controller extends \Piwik\Plugin\ControllerAdmin
{
public const UPDATE_NONCE = 'Marketplace.updatePlugin';
public const INSTALL_NONCE = 'Marketplace.installPlugin';
public const DOWNLOAD_NONCE_PREFIX = 'Marketplace.downloadPlugin.';
/**
* @var LicenseKey
*/
private $licenseKey;
/**
* @var Plugins
*/
private $plugins;
/**
* @var Api\Client
*/
private $marketplaceApi;
/**
* @var Consumer
*/
private $consumer;
/**
* @var PluginInstaller
*/
private $pluginInstaller;
/**
* @var Plugin\Manager
*/
private $pluginManager;
/**
* @var Environment
*/
private $environment;
/**
* @var PasswordVerifier
*/
private $passwordVerify;
/**
* @var array<int, array<string, mixed>>|null
*/
private $paidPlugins;
public function __construct(
LicenseKey $licenseKey,
Plugins $plugins,
Api\Client $marketplaceApi,
Consumer $consumer,
PluginInstaller $pluginInstaller,
Environment $environment,
PasswordVerifier $passwordVerify
) {
$this->licenseKey = $licenseKey;
$this->plugins = $plugins;
$this->marketplaceApi = $marketplaceApi;
$this->consumer = $consumer;
$this->pluginInstaller = $pluginInstaller;
$this->pluginManager = Plugin\Manager::getInstance();
$this->environment = $environment;
$this->passwordVerify = $passwordVerify;
$this->paidPlugins = null;
parent::__construct();
}
public function subscriptionOverview()
{
Piwik::checkUserHasSuperUserAccess();
// we want to make sure to fetch the latest results, eg in case user has purchased a subscription meanwhile
// this is also like a self-repair to clear the caches :)
$this->marketplaceApi->clearAllCacheEntries();
$this->consumer->clearCache();
// invalidate cache for plugin/manager
Plugin\Manager::getLicenseCache()->flushAll();
$hasLicenseKey = $this->licenseKey->has();
$consumer = $this->consumer->getConsumer();
$subscriptions = array();
$loginUrl = '';
if (!empty($consumer['loginUrl'])) {
$loginUrl = $consumer['loginUrl'];
}
if (!empty($consumer['licenses'])) {
foreach ($consumer['licenses'] as $subscription) {
$subscription['start'] = $this->getPrettyLongDate($subscription['startDate']);
$subscription['end'] = $this->getPrettyLongDate($subscription['endDate']);
$subscription['nextPayment'] = $this->getPrettyLongDate($subscription['nextPaymentDate']);
$subscriptions[] = $subscription;
}
}
return $this->renderTemplate('@Marketplace/subscription-overview', array(
'hasLicenseKey' => $hasLicenseKey,
'subscriptions' => $subscriptions,
'loginUrl' => $loginUrl,
'numUsers' => $this->environment->getNumUsers(),
));
}
public function manageLicenseKey()
{
Piwik::checkUserHasSuperUserAccess();
return $this->renderTemplate('@Marketplace/manageLicenseKey', array(
'hasValidLicenseKey' => $this->licenseKey->has() && $this->consumer->isValidConsumer(),
));
}
public function getPaidPluginsToInstallAtOnceParams()
{
Piwik::checkUserHasSuperUserAccess();
Json::sendHeaderJSON();
if (!$this->isInstallAllPaidPluginsVisible()) {
return json_encode([]);
}
return json_encode([
'paidPluginsToInstallAtOnce' => $this->getAllPaidPluginsToInstallAtOnce(),
'installAllPluginsNonce' => Nonce::getNonce(self::INSTALL_NONCE),
], JSON_HEX_APOS);
}
private function getPrettyLongDate($date)
{
if (empty($date)) {
return '';
}
return Date::factory($date)->getLocalized(Date::DATE_FORMAT_LONG);
}
public function pluginDetails()
{
$view = $this->configureViewAndCheckPermission('@Marketplace/plugin-details');
$pluginName = new PluginName();
$pluginName = $pluginName->getPluginName();
$activeTab = Common::getRequestVar('activeTab', '', 'string');
if ('changelog' !== $activeTab) {
$activeTab = '';
}
try {
$plugin = $this->plugins->getPluginInfo($pluginName);
if (empty($plugin['name'])) {
throw new Exception('Plugin does not exist');
}
} catch (Exception $e) {
$plugin = null;
$view->errorMessage = $e->getMessage();
}
$view->plugin = $plugin;
$view->isSuperUser = Piwik::hasUserSuperUserAccess();
$view->installNonce = Nonce::getNonce(static::INSTALL_NONCE);
$view->updateNonce = Nonce::getNonce(static::UPDATE_NONCE);
$view->activeTab = $activeTab;
$view->isAutoUpdatePossible = SettingsPiwik::isAutoUpdatePossible();
$view->isAutoUpdateEnabled = SettingsPiwik::isAutoUpdateEnabled();
return $view->render();
}
public function download()
{
Piwik::checkUserHasSuperUserAccess();
$this->dieIfPluginsAdminIsDisabled();
$pluginName = new PluginName();
$pluginName = $pluginName->getPluginName();
Nonce::checkNonce(static::DOWNLOAD_NONCE_PREFIX . $pluginName);
$filename = $pluginName . '.zip';
try {
$pathToPlugin = $this->marketplaceApi->download($pluginName);
ProxyHttp::serverStaticFile($pathToPlugin, 'application/zip', $expire = 0, $start = false, $end = false, $filename);
} catch (Exception $e) {
Common::sendResponseCode(500);
Log::warning('Could not download file . ' . $e->getMessage());
}
if (!empty($pathToPlugin)) {
Filesystem::deleteFileIfExists($pathToPlugin);
}
}
private function getPaidPluginsToInstallAtOnceData(array $paidPlugins): array
{
$paidPluginsToInstallAtOnce = [];
if (SettingsPiwik::isAutoUpdatePossible()) {
foreach ($paidPlugins as $paidPlugin) {
if (
$this->canPluginBeInstalled($paidPlugin)
|| ($this->pluginManager->isPluginInstalled($paidPlugin['name'], true)
&& !$this->pluginManager->isPluginActivated($paidPlugin['name']))
) {
$paidPluginsToInstallAtOnce[] = $paidPlugin['displayName'];
}
}
}
return $paidPluginsToInstallAtOnce;
}
public function overview()
{
$view = $this->configureViewAndCheckPermission('@Marketplace/overview');
$view->paidPluginsToInstallAtOnce = $this->getAllPaidPluginsToInstallAtOnce();
$view->isValidConsumer = $this->consumer->isValidConsumer();
$view->pluginTypeOptions = array(
'plugins' => Piwik::translate('General_Plugins'),
'premium' => Piwik::translate('Marketplace_PaidPlugins'),
'themes' => Piwik::translate('CorePluginsAdmin_Themes'),
);
$view->pluginSortOptions = array(
Sort::METHOD_LAST_UPDATED => Piwik::translate('Marketplace_SortByLastUpdated'),
Sort::METHOD_POPULAR => Piwik::translate('Marketplace_SortByPopular'),
Sort::METHOD_NEWEST => Piwik::translate('Marketplace_SortByNewest'),
Sort::METHOD_ALPHA => Piwik::translate('Marketplace_SortByAlpha'),
);
$view->defaultSort = Sort::DEFAULT_SORT;
$view->installNonce = Nonce::getNonce(static::INSTALL_NONCE);
$view->updateNonce = Nonce::getNonce(static::UPDATE_NONCE);
$view->deactivateNonce = Nonce::getNonce(PluginsController::DEACTIVATE_NONCE);
$view->activateNonce = Nonce::getNonce(PluginsController::ACTIVATE_NONCE);
$view->currentUserEmail = Piwik::getCurrentUserEmail();
$view->isSuperUser = Piwik::hasUserSuperUserAccess();
$view->isPluginsAdminEnabled = CorePluginsAdmin::isPluginsAdminEnabled();
$view->isAutoUpdatePossible = SettingsPiwik::isAutoUpdatePossible();
$view->isAutoUpdateEnabled = SettingsPiwik::isAutoUpdateEnabled();
$view->isPluginUploadEnabled = CorePluginsAdmin::isPluginUploadEnabled();
$view->uploadLimit = SettingsServer::getPostMaxUploadSize();
$view->inReportingMenu = (bool) Common::getRequestVar('embed', 0, 'int');
$view->numUsers = $this->environment->getNumUsers();
return $view->render();
}
public function updateOverview(): string
{
Piwik::checkUserIsNotAnonymous();
$paidPlugins = $this->getPaidPlugins();
$updateData = [
'isValidConsumer' => $this->consumer->isValidConsumer(),
];
Json::sendHeaderJSON();
return json_encode($updateData);
}
public function searchPlugins(): string
{
Piwik::checkUserIsNotAnonymous();
$request = Request::fromRequest();
$query = $request->getStringParameter('query', '');
$themesOnly = $request->getBoolParameter('themesOnly', false);
$purchaseType = $request->getStringParameter('purchaseType', '');
$sort = $request->getStringParameter('sort', '');
$purchaseType = (new PurchaseType())->getPurchaseType($purchaseType);
$sort = (new Sort())->getSort($sort);
$plugins = $this->plugins->searchPlugins($query, $sort, $themesOnly, $purchaseType);
foreach ($plugins as &$plugin) {
if ($plugin['isDownloadable']) {
$plugin['downloadNonce'] = Nonce::getNonce(static::DOWNLOAD_NONCE_PREFIX . $plugin['name']);
}
$plugin['isTrialRequested'] = false;
$plugin['canTrialBeRequested'] = false;
if ($plugin['isEligibleForFreeTrial']) {
$plugin['isTrialRequested'] = StaticContainer::get(PluginTrialService::class)->wasRequested($plugin['name']);
$plugin['canTrialBeRequested'] = (int) GeneralConfig::getConfigValue('plugin_trial_request_expiration_in_days') !== -1;
}
}
Json::sendHeaderJSON();
return json_encode($plugins);
}
public function installAllPaidPlugins()
{
Piwik::checkUserHasSuperUserAccess();
$this->dieIfPluginsAdminIsDisabled();
Plugin\ControllerAdmin::displayWarningIfConfigFileNotWritable();
$params = array(
'module' => 'Marketplace',
'action' => 'installAllPaidPlugins',
'nonce' => Common::getRequestVar('nonce'),
);
if ($this->passwordVerify->requirePasswordVerifiedRecently($params)) {
Nonce::checkNonce(static::INSTALL_NONCE);
$paidPlugins = $this->getPaidPlugins();
$hasErrors = false;
foreach ($paidPlugins as $paidPlugin) {
if (!$this->canPluginBeInstalled($paidPlugin)) {
continue;
}
$pluginName = $paidPlugin['name'];
try {
$this->pluginInstaller->installOrUpdatePluginFromMarketplace($pluginName);
} catch (\Exception $e) {
$notification = new Notification($e->getMessage());
$notification->context = Notification::CONTEXT_ERROR;
if (method_exists($e, 'isHtmlMessage') && $e->isHtmlMessage()) {
$notification->raw = true;
}
Notification\Manager::notify('Marketplace_Install' . $pluginName, $notification);
$hasErrors = true;
}
}
if ($hasErrors) {
Url::redirectToReferrer();
return;
}
$dependency = new Plugin\Dependency();
for ($i = 0; $i <= 10; $i++) {
foreach ($paidPlugins as $index => $paidPlugin) {
if (empty($paidPlugin)) {
continue;
}
$pluginName = $paidPlugin['name'];
if ($this->pluginManager->isPluginActivated($pluginName)) {
// we do not use unset since it might skip a plugin afterwards when removing index
$paidPlugins[$index] = null;
continue;
}
if (!$this->pluginManager->isPluginInFilesystem($pluginName)) {
$paidPlugins[$index] = null;
continue;
}
if (
empty($paidPlugin['require'])
|| !$dependency->hasDependencyToDisabledPlugin($paidPlugin['require'])
) {
$paidPlugins[$index] = null;
try {
$this->pluginManager->activatePlugin($pluginName);
} catch (Exception $e) {
$hasErrors = true;
$notification = new Notification($e->getMessage());
$notification->context = Notification::CONTEXT_ERROR;
Notification\Manager::notify('Marketplace_Install' . $pluginName, $notification);
}
}
}
$paidPlugins = array_filter($paidPlugins);
}
if ($hasErrors) {
$notification = new Notification(Piwik::translate('Marketplace_OnlySomePaidPluginsInstalledAndActivated'));
$notification->context = Notification::CONTEXT_INFO;
} else {
$notification = new Notification(Piwik::translate('Marketplace_AllPaidPluginsInstalledAndActivated'));
$notification->context = Notification::CONTEXT_SUCCESS;
}
Notification\Manager::notify('Marketplace_InstallAll', $notification);
Url::redirectToUrl(Url::getCurrentUrlWithoutQueryString() . Url::getCurrentQueryStringWithParametersModified([
'action' => 'overview',
'nonce' => null,
]));
}
}
public function updatePlugin()
{
$view = $this->createUpdateOrInstallView('updatePlugin', static::UPDATE_NONCE);
return $view->render();
}
public function installPlugin()
{
$params = array(
'module' => 'Marketplace',
'action' => 'installPlugin',
'mode' => 'admin',
'pluginName' => Common::getRequestVar('pluginName'),
'nonce' => Common::getRequestVar('nonce'),
);
if ($this->passwordVerify->requirePasswordVerifiedRecently($params)) {
$view = $this->createUpdateOrInstallView('installPlugin', static::INSTALL_NONCE);
$view->nonce = Nonce::getNonce(PluginsController::ACTIVATE_NONCE);
return $view->render();
}
}
private function createUpdateOrInstallView($template, $nonceName)
{
Piwik::checkUserHasSuperUserAccess();
$this->dieIfPluginsAdminIsDisabled();
$this->displayWarningIfConfigFileNotWritable();
$plugins = $this->getPluginNameIfNonceValid($nonceName);
$view = new View('@Marketplace/' . $template);
$this->setBasicVariablesView($view);
$view->errorMessage = '';
$pluginInfos = [];
foreach ($plugins as $pluginName) {
$currentPluginInfo = $this->plugins->getPluginInfo($pluginName);
$pluginInfos[] = $currentPluginInfo;
try {
$this->pluginInstaller->installOrUpdatePluginFromMarketplace($pluginName);
} catch (\Exception $e) {
$message = $e->getMessage();
$isRaw = false;
if (stripos($message, 'PCLZIP_ERR_BAD_FORMAT') !== false) {
$faqLink = Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/plugins/faq_21/');
if (!empty($currentPluginInfo['isPaid'])) {
$downloadLink = Url::addCampaignParametersToMatomoLink('https://shop.matomo.org/my-account/downloads');
$translateKey = 'Marketplace_PluginDownloadLinkMissingPremium';
} else {
$downloadLink = Url::addCampaignParametersToMatomoLink('https://plugins.matomo.org/' . $pluginName);
$translateKey = 'Marketplace_PluginDownloadLinkMissingFree';
}
$message = Piwik::translate($translateKey, [$pluginName, Url::getExternalLinkTag($downloadLink), '</a>', Url::getExternalLinkTag($faqLink), '</a>']);
$isRaw = true;
}
$notification = new Notification($message);
$notification->context = Notification::CONTEXT_ERROR;
$notification->type = Notification::TYPE_PERSISTENT;
$notification->flags = Notification::FLAG_CLEAR;
if ((method_exists($e, 'isHtmlMessage') && $e->isHtmlMessage()) || $isRaw) {
$notification->raw = true;
}
Notification\Manager::notify('CorePluginsAdmin_InstallPlugin', $notification);
Url::redirectToReferrer();
return;
}
}
$view->plugins = $pluginInfos;
return $view;
}
private function getPluginNameIfNonceValid($nonceName)
{
Nonce::checkNonce($nonceName);
$pluginName = Common::getRequestVar('pluginName', null, 'string');
$plugins = explode(',', $pluginName);
$plugins = array_map('trim', $plugins);
foreach ($plugins as $name) {
if (!$this->pluginManager->isValidPluginName($name)) {
throw new Exception('Invalid plugin name: ' . $name);
}
}
return $plugins;
}
private function dieIfPluginsAdminIsDisabled()
{
if (!CorePluginsAdmin::isPluginsAdminEnabled()) {
throw new \Exception('Enabling, disabling and uninstalling plugins has been disabled by Matomo admins.
Please contact your Matomo admins with your request so they can assist you.');
}
}
private function canPluginBeInstalled($plugin)
{
if (empty($plugin['isDownloadable'])) {
return false;
}
$pluginName = $plugin['name'];
$isAlreadyInstalled = $this->pluginManager->isPluginInstalled($pluginName, true)
|| $this->pluginManager->isPluginLoaded($pluginName)
|| $this->pluginManager->isPluginActivated($pluginName);
return !$isAlreadyInstalled && $plugin['hasDownloadLink'];
}
protected function configureViewAndCheckPermission($template)
{
Piwik::checkUserIsNotAnonymous();
$view = new View($template);
$this->setBasicVariablesView($view);
$this->displayWarningIfConfigFileNotWritable();
$this->securityPolicy->addPolicy('img-src', '*.matomo.org');
$this->securityPolicy->addPolicy('default-src', '*.matomo.org');
$view->errorMessage = '';
return $view;
}
private function isInstallAllPaidPluginsVisible(): bool
{
return (
$this->consumer->isValidConsumer() &&
Piwik::hasUserSuperUserAccess() &&
SettingsPiwik::isAutoUpdatePossible() &&
CorePluginsAdmin::isPluginsAdminEnabled() &&
count($this->getAllPaidPluginsToInstallAtOnce()) > 0
);
}
private function getAllPaidPluginsToInstallAtOnce()
{
$paidPlugins = $this->getPaidPlugins();
return $this->getPaidPluginsToInstallAtOnceData($paidPlugins);
}
/**
* @return array<int, array<string, mixed>>
*/
private function getPaidPlugins(): array
{
if ($this->paidPlugins === null) {
$this->paidPlugins = $this->plugins->getAllPaidPlugins();
}
return $this->paidPlugins;
}
}
|