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