PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.6.0
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.6.0
5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / View.php
matomo / app / core Last commit date
API 4 years ago Access 5 years ago Application 4 years ago Archive 4 years ago ArchiveProcessor 4 years ago Archiver 5 years ago AssetManager 4 years ago Auth 5 years ago Category 5 years ago CliMulti 4 years ago Columns 5 years ago Concurrency 4 years ago Config 5 years ago Container 4 years ago CronArchive 4 years ago DataAccess 4 years ago DataFiles 5 years ago DataTable 4 years ago Db 4 years ago DeviceDetector 4 years ago Email 5 years ago Exception 4 years ago Http 5 years ago Intl 4 years ago Mail 5 years ago Measurable 5 years ago Menu 5 years ago Metrics 4 years ago Notification 4 years ago Period 4 years ago Plugin 4 years ago ProfessionalServices 5 years ago Report 5 years ago ReportRenderer 5 years ago Scheduler 4 years ago Segment 5 years ago Session 4 years ago Settings 5 years ago Tracker 4 years ago Translation 4 years ago UpdateCheck 5 years ago Updater 4 years ago Updates 4 years ago Validators 4 years ago View 4 years ago ViewDataTable 5 years ago Visualization 5 years ago Widget 5 years ago .htaccess 6 years ago Access.php 4 years ago Archive.php 4 years ago ArchiveProcessor.php 4 years ago AssetManager.php 5 years ago Auth.php 5 years ago AuthResult.php 5 years ago BaseFactory.php 5 years ago Cache.php 5 years ago CacheId.php 5 years ago CliMulti.php 4 years ago Common.php 4 years ago Config.php 4 years ago Console.php 5 years ago Context.php 5 years ago Cookie.php 4 years ago CronArchive.php 4 years ago DataArray.php 4 years ago DataTable.php 4 years ago Date.php 4 years ago Db.php 4 years ago DbHelper.php 4 years ago Development.php 5 years ago ErrorHandler.php 5 years ago EventDispatcher.php 4 years ago ExceptionHandler.php 4 years ago FileIntegrity.php 5 years ago Filechecks.php 5 years ago Filesystem.php 4 years ago FrontController.php 4 years ago Http.php 4 years ago IP.php 4 years ago Log.php 4 years ago LogDeleter.php 4 years ago Mail.php 4 years ago Metrics.php 5 years ago NoAccessException.php 5 years ago Nonce.php 4 years ago Notification.php 5 years ago NumberFormatter.php 5 years ago Option.php 4 years ago Period.php 5 years ago Piwik.php 4 years ago Plugin.php 4 years ago Profiler.php 4 years ago ProxyHeaders.php 5 years ago ProxyHttp.php 4 years ago QuickForm2.php 5 years ago RankingQuery.php 5 years ago ReportRenderer.php 5 years ago Segment.php 5 years ago Sequence.php 5 years ago Session.php 4 years ago SettingsPiwik.php 5 years ago SettingsServer.php 5 years ago Singleton.php 5 years ago Site.php 4 years ago SupportedBrowser.php 4 years ago TCPDF.php 5 years ago Theme.php 5 years ago Timer.php 5 years ago Tracker.php 4 years ago Twig.php 4 years ago Unzip.php 5 years ago UpdateCheck.php 5 years ago Updater.php 5 years ago UpdaterErrorException.php 5 years ago Updates.php 5 years ago Url.php 4 years ago UrlHelper.php 4 years ago Version.php 4 years ago View.php 4 years ago bootstrap.php 5 years ago dispatch.php 5 years ago testMinimumPhpVersion.php 5 years ago
View.php
514 lines
1 <?php
2 /**
3 * Matomo - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 *
8 */
9 namespace Piwik;
10
11 use Exception;
12 use Piwik\AssetManager\UIAssetCacheBuster;
13 use Piwik\Container\StaticContainer;
14 use Piwik\Plugins\CoreAdminHome\Controller;
15 use Piwik\Plugins\CorePluginsAdmin\CorePluginsAdmin;
16 use Piwik\View\ViewInterface;
17 use Piwik\View\SecurityPolicy;
18 use Twig\Environment;
19
20 /**
21 * Transition for pre-Piwik 0.4.4
22 */
23 if (!defined('PIWIK_USER_PATH')) {
24 define('PIWIK_USER_PATH', PIWIK_INCLUDE_PATH);
25 }
26
27 /**
28 * Encapsulates and manages a [Twig](http://twig.sensiolabs.org/) template.
29 *
30 * View lets you set properties that will be passed on to a Twig template.
31 * View will also set several properties that will be available in all Twig
32 * templates, including:
33 *
34 * - **currentModule**: The value of the **module** query parameter.
35 * - **currentAction**: The value of the **action** query parameter.
36 * - **userLogin**: The current user login name.
37 * - **sites**: List of site data for every site the current user has at least
38 * view access for.
39 * - **url**: The current URL (sanitized).
40 * - **token_auth**: The current user's token auth.
41 * - **userHasSomeAdminAccess**: True if the user has admin access to at least
42 * one site, false if otherwise.
43 * - **userIsSuperUser**: True if the user is the superuser, false if otherwise.
44 * - **latest_version_available**: The latest version of Piwik available.
45 * - **isWidget**: The value of the 'widget' query parameter.
46 * - **show_autocompleter**: Whether the site selector should be shown or not.
47 * - **loginModule**: The name of the currently used authentication module.
48 * - **isInternetEnabled**: Whether the matomo server is allowed to connect to
49 * external networks.
50 *
51 * ### Template Naming Convention
52 *
53 * Template files should be named after the controller method they are used in.
54 * If they are used in more than one controller method or are included by another
55 * template, they should describe the output they generate and be prefixed with
56 * an underscore, eg, **_dataTable.twig**.
57 *
58 * ### Twig
59 *
60 * Twig templates must exist in the **templates** folder in a plugin's root
61 * folder.
62 *
63 * The following filters are available to twig templates:
64 *
65 * - **translate**: Outputs internationalized text using a translation token, eg,
66 * `{{ 'General_Date'|translate }}`. sprintf parameters can be passed
67 * to the filter.
68 * - **urlRewriteWithParameters**: Modifies the current query string with the given
69 * set of parameters, eg,
70 *
71 * {{ {'module':'MyPlugin', 'action':'index'} | urlRewriteWithParameters }}
72 *
73 * - **sumTime**: Pretty formats an number of seconds.
74 * - **money**: Formats a numerical value as a monetary value using the currency
75 * of the supplied site (second arg is site ID).
76 * eg, `{{ 23|money(site.idsite)|raw }}
77 * - **truncate**: Truncates the text to certain length (determined by first arg.)
78 * eg, `{{ myReallyLongText|truncate(80) }}`
79 * - **implode**: Calls `implode`.
80 * - **ucwords**: Calls `ucwords`.
81 *
82 * The following functions are available to twig templates:
83 *
84 * - **linkTo**: Modifies the current query string with the given set of parameters,
85 * eg `{{ linkTo({'module':'MyPlugin', 'action':'index'}) }}`.
86 * - **sparkline**: Outputs a sparkline image HTML element using the sparkline image
87 * src link. eg, `{{ sparkline(sparklineUrl) }}`.
88 * - **postEvent**: Posts an event that allows event observers to add text to a string
89 * which is outputted in the template, eg, `{{ postEvent('MyPlugin.event') }}`
90 * - **isPluginLoaded**: Returns true if the supplied plugin is loaded, false if otherwise.
91 * `{% if isPluginLoaded('Goals') %}...{% endif %}`
92 * - **areAdsForProfessionalServicesEnabled**: Returns true if it is ok to show some advertising in the UI for providers of Professional Support for Piwik (from Piwik 2.16.0)
93 * - **isMultiServerEnvironment**: Returns true if Piwik is used on more than one server (since Piwik 2.16.1)
94 *
95 * ### Examples
96 *
97 * **Basic usage**
98 *
99 * // a controller method
100 * public function myView()
101 * {
102 * $view = new View("@MyPlugin/myView");
103 * $view->property1 = "a view property";
104 * $view->property2 = "another view property";
105 * return $view->render();
106 * }
107 *
108 *
109 * @api
110 */
111 class View implements ViewInterface
112 {
113 private $template = '';
114
115 /**
116 * Instance
117 * @var Environment
118 */
119 private $twig;
120 protected $templateVars = array();
121 private $contentType = 'text/html; charset=utf-8';
122 private $xFrameOptions = null;
123 private $enableCacheBuster = true;
124
125 private $useStrictReferrerPolicy = true;
126
127 /**
128 * Can be disabled to not send headers when rendering a view. This can be useful if heaps of views are being
129 * rendered during one request to possibly prevent a segmentation fault see eg #15307 . It should not be disabled
130 * for a main view, but could be disabled for views that are being rendered eg during a twig event as a "subview" which
131 * is part of the "main view".
132 * @var bool
133 */
134 public $sendHeadersWhenRendering = true;
135
136 /**
137 * Constructor.
138 *
139 * @param string $templateFile The template file to load. Must be in the following format:
140 * `"@MyPlugin/templateFileName"`. Note the absence of .twig
141 * from the end of the name.
142 */
143 public function __construct($templateFile)
144 {
145 $templateExt = '.twig';
146 if (substr($templateFile, -strlen($templateExt)) !== $templateExt) {
147 $templateFile .= $templateExt;
148 }
149 $this->template = $templateFile;
150
151 $this->initializeTwig();
152
153 $this->piwik_version = Version::VERSION;
154 $this->userLogin = Piwik::getCurrentUserLogin();
155 $this->isSuperUser = Access::getInstance()->hasSuperUserAccess();
156 // following is used in ajaxMacros called macro (showMoreHelp as passed in other templates) - requestErrorDiv
157 $isGeneralSettingsAdminEnabled = Controller::isGeneralSettingsAdminEnabled();
158 $isPluginsAdminEnabled = CorePluginsAdmin::isPluginsAdminEnabled();
159 // simplify template usage
160 $this->showMoreFaqInfo = $this->isSuperUser && ($isGeneralSettingsAdminEnabled || $isPluginsAdminEnabled);
161
162 try {
163 $this->piwikUrl = SettingsPiwik::getPiwikUrl();
164 } catch (Exception $ex) {
165 // pass (occurs when DB cannot be connected to, perhaps piwik URL cache should be stored in config file...)
166 }
167 }
168
169 /**
170 * Disables the cache buster (adding of ?cb=...) to JavaScript and stylesheet files
171 */
172 public function disableCacheBuster()
173 {
174 $this->enableCacheBuster = false;
175 }
176
177 /**
178 * Returns the template filename.
179 *
180 * @return string
181 */
182 public function getTemplateFile()
183 {
184 return $this->template;
185 }
186
187 /**
188 * Returns the variables to bind to the template when rendering.
189 *
190 * @param array $override Template variable override values. Mainly useful
191 * when including View templates in other templates.
192 * @return array
193 */
194 public function getTemplateVars($override = array())
195 {
196 return $override + $this->templateVars;
197 }
198
199 /**
200 * Directly assigns a variable to the view script.
201 * Variable names may not be prefixed with '_'.
202 *
203 * @param string $key The variable name.
204 * @param mixed $val The variable value.
205 */
206 public function __set($key, $val)
207 {
208 $this->templateVars[$key] = $val;
209 }
210
211 /**
212 * Retrieves an assigned variable.
213 * Variable names may not be prefixed with '_'.
214 *
215 * @param string $key The variable name.
216 * @return mixed The variable value.
217 */
218 public function &__get($key)
219 {
220 return $this->templateVars[$key];
221 }
222
223 /**
224 * Returns true if a template variable has been set or not.
225 *
226 * @param string $name The name of the template variable.
227 * @return bool
228 */
229 public function __isset($name)
230 {
231 return isset($this->templateVars[$name]);
232 }
233
234 /**
235 * Unsets a template variable.
236 *
237 * @param string $name The name of the template variable.
238 */
239 public function __unset($name)
240 {
241 unset($this->templateVars[$name]);
242 }
243
244 private function initializeTwig()
245 {
246 $this->twig = StaticContainer::get(Twig::class)->getTwigEnvironment();
247 }
248
249 /**
250 * Renders the current view. Also sends the stored 'Content-Type' HTML header.
251 * See {@link setContentType()}.
252 *
253 * @return string Generated template.
254 */
255 public function render()
256 {
257 try {
258 $this->currentModule = Piwik::getModule();
259 $this->currentAction = Piwik::getAction();
260
261 $this->url = Common::sanitizeInputValue(Url::getCurrentUrl());
262 $this->token_auth = Piwik::getCurrentUserTokenAuth();
263 $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess();
264 $this->userIsAnonymous = Piwik::isUserIsAnonymous();
265 $this->userIsSuperUser = Piwik::hasUserSuperUserAccess();
266 $this->latest_version_available = UpdateCheck::isNewestVersionAvailable();
267 $this->showUpdateNotificationToUser = !SettingsPiwik::isShowUpdateNotificationToSuperUsersOnlyEnabled() || Piwik::hasUserSuperUserAccess();
268 $this->disableLink = Common::getRequestVar('disableLink', 0, 'int');
269 $this->isWidget = Common::getRequestVar('widget', 0, 'int');
270 $this->isMultiServerEnvironment = SettingsPiwik::isMultiServerEnvironment();
271 $this->isInternetEnabled = SettingsPiwik::isInternetEnabled();
272 $this->shouldPropagateTokenAuth = $this->shouldPropagateTokenAuthInAjaxRequests();
273
274 $piwikAds = StaticContainer::get('Piwik\ProfessionalServices\Advertising');
275 $this->areAdsForProfessionalServicesEnabled = $piwikAds->areAdsForProfessionalServicesEnabled();
276
277 if (Development::isEnabled()) {
278 $cacheBuster = rand(0, 10000);
279 } else {
280 $cacheBuster = UIAssetCacheBuster::getInstance()->piwikVersionBasedCacheBuster();
281 }
282 $this->cacheBuster = $cacheBuster;
283
284 $this->loginModule = Piwik::getLoginPluginName();
285 } catch (Exception $e) {
286 Log::debug($e);
287
288 // can fail, for example at installation (no plugin loaded yet)
289 }
290
291 if ($this->sendHeadersWhenRendering) {
292 ProxyHttp::overrideCacheControlHeaders('no-store');
293
294 Common::sendHeader('Content-Type: ' . $this->contentType);
295 // always sending this header, sometimes empty, to ensure that Dashboard embed loads
296 // - when calling sendHeader() multiple times, the last one prevails
297 if(!empty($this->xFrameOptions)) {
298 Common::sendHeader('X-Frame-Options: ' . (string)$this->xFrameOptions);
299 }
300
301 // don't send Referer-Header for outgoing links
302 if (!empty($this->useStrictReferrerPolicy)) {
303 Common::sendHeader('Referrer-Policy: same-origin');
304 } else {
305 // always send explicit default header
306 Common::sendHeader('Referrer-Policy: no-referrer-when-downgrade');
307 }
308
309 // this will be an empty string if CSP is disabled
310 $cspHeader = StaticContainer::get(SecurityPolicy::class)->createHeaderString();
311 if ('' !== $cspHeader) {
312 Common::sendHeader($cspHeader);
313 }
314 }
315
316 return $this->renderTwigTemplate();
317 }
318
319 /**
320 * @internal
321 * @ignore
322 * @return Environment
323 */
324 public function getTwig()
325 {
326 return $this->twig;
327 }
328
329 protected function renderTwigTemplate()
330 {
331 $output = $this->twig->render($this->getTemplateFile(), $this->getTemplateVars());
332
333 if ($this->enableCacheBuster) {
334 $output = $this->applyFilter_cacheBuster($output);
335 }
336
337 $helper = new Theme;
338 $output = $helper->rewriteAssetsPathToTheme($output);
339 return $output;
340 }
341
342 protected function applyFilter_cacheBuster($output)
343 {
344 $cacheBuster = UIAssetCacheBuster::getInstance();
345 $cache = Cache::getTransientCache();
346
347 $cssCacheBusterId = $cache->fetch('cssCacheBusterId');
348 if (empty($cssCacheBusterId)) {
349 $assetManager = AssetManager::getInstance();
350 $stylesheet = $assetManager->getMergedStylesheetAsset();
351 if ($stylesheet->exists()) {
352 $content = $stylesheet->getContent();
353 } else {
354 $content = $assetManager->getMergedStylesheet()->getContent();
355 }
356 $cssCacheBusterId = $cacheBuster->md5BasedCacheBuster($content);
357 $cache->save('cssCacheBusterId', $cssCacheBusterId);
358 }
359
360 $tagJs = 'cb=' . $cacheBuster->piwikVersionBasedCacheBuster();
361 $tagCss = 'cb=' . $cssCacheBusterId;
362
363 $pattern = array(
364 '~<script type=[\'"]text/javascript[\'"] src=[\'"]([^\'"]+)[\'"]>~',
365 '~<script src=[\'"]([^\'"]+)[\'"] type=[\'"]text/javascript[\'"]>~',
366 '~<link rel=[\'"]stylesheet[\'"] type=[\'"]text/css[\'"] href=[\'"]([^\'"]+)[\'"] ?/?>~',
367 // removes the double ?cb= tag
368 '~(src|href)=\"index.php\?module=([A-Za-z0-9_]+)&action=([A-Za-z0-9_]+)\?cb=~',
369 );
370
371 $replace = array(
372 '<script type="text/javascript" src="$1?' . $tagJs . '">',
373 '<script type="text/javascript" src="$1?' . $tagJs . '">',
374 '<link rel="stylesheet" type="text/css" href="$1?' . $tagCss . '" />',
375 '$1="index.php?module=$2&amp;action=$3&amp;cb=',
376 );
377
378 return preg_replace($pattern, $replace, $output);
379 }
380
381 /**
382 * Set stored value used in the Content-Type HTTP header field. The header is
383 * set just before rendering.
384 *
385 * @param string $contentType
386 */
387 public function setContentType($contentType)
388 {
389 $this->contentType = $contentType;
390 }
391
392 /**
393 * Set X-Frame-Options field in the HTTP response. The header is set just
394 * before rendering.
395 *
396 * _Note: setting this allows you to make sure the View **cannot** be
397 * embedded in iframes. Learn more [here](https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options)._
398 *
399 * @param string $option ('deny' or 'sameorigin')
400 */
401 public function setXFrameOptions($option = 'deny')
402 {
403
404 if ($option === 'deny' || $option === 'sameorigin') {
405 $this->xFrameOptions = $option;
406 }
407 if ($option == 'allow') {
408 $this->xFrameOptions = null;
409 }
410 }
411
412 /**
413 * Add form to view
414 *
415 * @param QuickForm2 $form
416 * @ignore
417 */
418 public function addForm(QuickForm2 $form)
419 {
420
421 // assign array with form data
422 $this->assign('form_data', $form->getFormData());
423 $this->assign('element_list', $form->getElementList());
424 }
425
426 /**
427 * Assign value to a variable for use in a template
428 * @param string|array $var
429 * @param mixed $value
430 * @ignore
431 */
432 public function assign($var, $value = null)
433 {
434 if (is_string($var)) {
435 $this->$var = $value;
436 } elseif (is_array($var)) {
437 foreach ($var as $key => $value) {
438 $this->$key = $value;
439 }
440 }
441 }
442
443 /**
444 * Clear compiled Twig templates
445 * @ignore
446 */
447 public static function clearCompiledTemplates()
448 {
449 $enable = StaticContainer::get('view.clearcompiledtemplates.enable');
450 if ($enable) {
451 // some high performance systems that run many Matomo instances may never want to clear this template cache
452 // if they use eg a blue/green deployment
453 $templatesCompiledPath = StaticContainer::get('path.tmp.templates');
454 Filesystem::unlinkRecursive($templatesCompiledPath, false);
455 }
456 }
457
458 /**
459 * Creates a View for and then renders the single report template.
460 *
461 * Can be used for pages that display only one report to avoid having to create
462 * a new template.
463 *
464 * @param string $title The report title.
465 * @param string $reportHtml The report body HTML.
466 * @return string|void The report contents if `$fetch` is true.
467 */
468 public static function singleReport($title, $reportHtml)
469 {
470 $view = new View('@CoreHome/_singleReport');
471 $view->title = $title;
472 $view->report = $reportHtml;
473 return $view->render();
474 }
475
476 private function shouldPropagateTokenAuthInAjaxRequests()
477 {
478 $generalConfig = Config::getInstance()->General;
479 return Common::getRequestVar('module', false) == 'Widgetize' ||
480 $generalConfig['enable_framed_pages'] == '1' ||
481 $this->validTokenAuthInUrl();
482 }
483
484 /**
485 * @return bool
486 * @throws Exception
487 */
488 private function validTokenAuthInUrl()
489 {
490 $tokenAuth = Common::getRequestVar('token_auth', '', 'string', $_GET);
491 return ($tokenAuth && $tokenAuth === Piwik::getCurrentUserTokenAuth());
492 }
493
494 /**
495 * Returns whether a strict Referrer-Policy header will be sent. Generally this should be set to 'true'.
496 *
497 * @return bool
498 */
499 public function getUseStrictReferrerPolicy()
500 {
501 return $this->useStrictReferrerPolicy;
502 }
503
504 /**
505 * Sets whether a strict Referrer-Policy header will be sent (if not, nothing is sent).
506 *
507 * @param bool $useStrictReferrerPolicy
508 */
509 public function setUseStrictReferrerPolicy($useStrictReferrerPolicy)
510 {
511 $this->useStrictReferrerPolicy = $useStrictReferrerPolicy;
512 }
513 }
514