PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.0.3
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.0.3
5.12.1 5.12.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 2 years ago Access 2 years ago Application 2 years ago Archive 2 years ago ArchiveProcessor 2 years ago Archiver 2 years ago AssetManager 2 years ago Auth 2 years ago Category 2 years ago Changes 2 years ago CliMulti 2 years ago Columns 2 years ago Concurrency 2 years ago Config 2 years ago Container 2 years ago CronArchive 2 years ago DataAccess 2 years ago DataFiles 2 years ago DataTable 2 years ago Db 2 years ago DeviceDetector 2 years ago Email 2 years ago Exception 2 years ago Http 2 years ago Intl 2 years ago Log 2 years ago Mail 2 years ago Measurable 2 years ago Menu 2 years ago Metrics 2 years ago Notification 2 years ago Period 2 years ago Plugin 2 years ago ProfessionalServices 2 years ago Report 2 years ago ReportRenderer 2 years ago Scheduler 2 years ago Segment 2 years ago Session 2 years ago Settings 2 years ago Tracker 2 years ago Translation 2 years ago Twig 2 years ago UpdateCheck 2 years ago Updater 2 years ago Updates 2 years ago Validators 2 years ago View 2 years ago ViewDataTable 2 years ago Visualization 2 years ago Widget 2 years ago .htaccess 2 years ago Access.php 2 years ago Archive.php 2 years ago ArchiveProcessor.php 2 years ago AssetManager.php 2 years ago Auth.php 2 years ago AuthResult.php 2 years ago BaseFactory.php 2 years ago Cache.php 2 years ago CacheId.php 2 years ago CliMulti.php 2 years ago Common.php 2 years ago Config.php 2 years ago Console.php 2 years ago Context.php 2 years ago Cookie.php 2 years ago CronArchive.php 2 years ago DI.php 2 years ago DataArray.php 2 years ago DataTable.php 2 years ago Date.php 2 years ago Db.php 2 years ago DbHelper.php 2 years ago Development.php 2 years ago ErrorHandler.php 2 years ago EventDispatcher.php 2 years ago ExceptionHandler.php 2 years ago FileIntegrity.php 2 years ago Filechecks.php 2 years ago Filesystem.php 2 years ago FrontController.php 2 years ago Http.php 2 years ago IP.php 2 years ago Log.php 2 years ago LogDeleter.php 2 years ago Mail.php 2 years ago Metrics.php 2 years ago NoAccessException.php 2 years ago Nonce.php 2 years ago Notification.php 2 years ago NumberFormatter.php 2 years ago Option.php 2 years ago Period.php 2 years ago Piwik.php 2 years ago Plugin.php 2 years ago Profiler.php 2 years ago ProxyHeaders.php 2 years ago ProxyHttp.php 2 years ago QuickForm2.php 2 years ago RankingQuery.php 2 years ago ReportRenderer.php 2 years ago Request.php 2 years ago Segment.php 2 years ago Sequence.php 2 years ago Session.php 2 years ago SettingsPiwik.php 2 years ago SettingsServer.php 2 years ago Singleton.php 2 years ago Site.php 2 years ago SiteContentDetector.php 2 years ago SupportedBrowser.php 2 years ago TCPDF.php 2 years ago Theme.php 2 years ago Timer.php 2 years ago Tracker.php 2 years ago Twig.php 2 years ago Unzip.php 2 years ago UpdateCheck.php 2 years ago Updater.php 2 years ago UpdaterErrorException.php 2 years ago Updates.php 2 years ago Url.php 2 years ago UrlHelper.php 2 years ago Version.php 2 years ago View.php 2 years ago bootstrap.php 2 years ago dispatch.php 2 years ago testMinimumPhpVersion.php 2 years ago
View.php
462 lines
1 <?php
2
3 /**
4 * Matomo - free/libre analytics platform
5 *
6 * @link https://matomo.org
7 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8 *
9 */
10 namespace Piwik;
11
12 use Exception;
13 use Piwik\AssetManager\UIAssetCacheBuster;
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](http://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 * @param QuickForm2 $form
374 * @ignore
375 */
376 public function addForm(\Piwik\QuickForm2 $form)
377 {
378 // assign array with form data
379 $this->assign('form_data', $form->getFormData());
380 $this->assign('element_list', $form->getElementList());
381 }
382 /**
383 * Assign value to a variable for use in a template
384 * @param string|array $var
385 * @param mixed $value
386 * @ignore
387 */
388 public function assign($var, $value = null)
389 {
390 if (is_string($var)) {
391 $this->{$var} = $value;
392 } elseif (is_array($var)) {
393 foreach ($var as $key => $value) {
394 $this->{$key} = $value;
395 }
396 }
397 }
398 /**
399 * Clear compiled Twig templates
400 * @ignore
401 */
402 public static function clearCompiledTemplates()
403 {
404 $enable = StaticContainer::get('view.clearcompiledtemplates.enable');
405 if ($enable) {
406 // some high performance systems that run many Matomo instances may never want to clear this template cache
407 // if they use eg a blue/green deployment
408 $templatesCompiledPath = StaticContainer::get('path.tmp.templates');
409 \Piwik\Filesystem::unlinkRecursive($templatesCompiledPath, false);
410 }
411 }
412 /**
413 * Creates a View for and then renders the single report template.
414 *
415 * Can be used for pages that display only one report to avoid having to create
416 * a new template.
417 *
418 * @param string $title The report title.
419 * @param string $reportHtml The report body HTML.
420 * @return string|void The report contents if `$fetch` is true.
421 */
422 public static function singleReport($title, $reportHtml)
423 {
424 $view = new \Piwik\View('@CoreHome/_singleReport');
425 $view->title = $title;
426 $view->report = $reportHtml;
427 return $view->render();
428 }
429 private function shouldPropagateTokenAuthInAjaxRequests()
430 {
431 $generalConfig = \Piwik\Config::getInstance()->General;
432 return \Piwik\Common::getRequestVar('module', false) == 'Widgetize' || $generalConfig['enable_framed_pages'] == '1' || $this->validTokenAuthInUrl();
433 }
434 /**
435 * @return bool
436 * @throws Exception
437 */
438 private function validTokenAuthInUrl()
439 {
440 $tokenAuth = \Piwik\Common::getRequestVar('token_auth', '', 'string', $_GET);
441 return $tokenAuth && $tokenAuth === \Piwik\Piwik::getCurrentUserTokenAuth();
442 }
443 /**
444 * Returns whether a strict Referrer-Policy header will be sent. Generally this should be set to 'true'.
445 *
446 * @return bool
447 */
448 public function getUseStrictReferrerPolicy()
449 {
450 return $this->useStrictReferrerPolicy;
451 }
452 /**
453 * Sets whether a strict Referrer-Policy header will be sent (if not, nothing is sent).
454 *
455 * @param bool $useStrictReferrerPolicy
456 */
457 public function setUseStrictReferrerPolicy($useStrictReferrerPolicy)
458 {
459 $this->useStrictReferrerPolicy = $useStrictReferrerPolicy;
460 }
461 }
462