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