Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

View.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. /**
  3. * Piwik - free/libre analytics platform
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. *
  8. */
  9. namespace Piwik;
  10. use Exception;
  11. use Piwik\Access;
  12. use Piwik\AssetManager\UIAssetCacheBuster;
  13. use Piwik\Common;
  14. use Piwik\Plugins\UsersManager\API as APIUsersManager;
  15. use Piwik\SettingsPiwik;
  16. use Piwik\Version;
  17. use Piwik\View\ViewInterface;
  18. use Twig_Environment;
  19. /**
  20. * Transition for pre-Piwik 0.4.4
  21. */
  22. if (!defined('PIWIK_USER_PATH')) {
  23. define('PIWIK_USER_PATH', PIWIK_INCLUDE_PATH);
  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. * - **userAlias**: The alias of the current user.
  47. *
  48. * ### Template Naming Convention
  49. *
  50. * Template files should be named after the controller method they are used in.
  51. * If they are used in more than one controller method or are included by another
  52. * template, they should describe the output they generate and be prefixed with
  53. * an underscore, eg, **_dataTable.twig**.
  54. *
  55. * ### Twig
  56. *
  57. * Twig templates must exist in the **templates** folder in a plugin's root
  58. * folder.
  59. *
  60. * The following filters are available to twig templates:
  61. *
  62. * - **translate**: Outputs internationalized text using a translation token, eg,
  63. * `{{ 'General_Date'|translate }}`. sprintf parameters can be passed
  64. * to the filter.
  65. * - **urlRewriteWithParameters**: Modifies the current query string with the given
  66. * set of parameters, eg,
  67. *
  68. * {{ {'module':'MyPlugin', 'action':'index'} | urlRewriteWithParameters }}
  69. *
  70. * - **sumTime**: Pretty formats an number of seconds.
  71. * - **money**: Formats a numerical value as a monetary value using the currency
  72. * of the supplied site (second arg is site ID).
  73. * eg, `{{ 23|money(site.idsite)|raw }}
  74. * - **truncate**: Truncates the text to certain length (determined by first arg.)
  75. * eg, `{{ myReallyLongText|truncate(80) }}`
  76. * - **implode**: Calls `implode`.
  77. * - **ucwords**: Calls `ucwords`.
  78. *
  79. * The following functions are available to twig templates:
  80. *
  81. * - **linkTo**: Modifies the current query string with the given set of parameters,
  82. * eg `{{ linkTo({'module':'MyPlugin', 'action':'index'}) }}`.
  83. * - **sparkline**: Outputs a sparkline image HTML element using the sparkline image
  84. * src link. eg, `{{ sparkline(sparklineUrl) }}`.
  85. * - **postEvent**: Posts an event that allows event observers to add text to a string
  86. * which is outputted in the template, eg, `{{ postEvent('MyPlugin.event') }}`
  87. * - **isPluginLoaded**: Returns true if the supplied plugin is loaded, false if otherwise.
  88. * `{% if isPluginLoaded('Goals') %}...{% endif %}`
  89. *
  90. * ### Examples
  91. *
  92. * **Basic usage**
  93. *
  94. * // a controller method
  95. * public function myView()
  96. * {
  97. * $view = new View("@MyPlugin/myView");
  98. * $view->property1 = "a view property";
  99. * $view->property2 = "another view property";
  100. * return $view->render();
  101. * }
  102. *
  103. *
  104. * @api
  105. */
  106. class View implements ViewInterface
  107. {
  108. private $template = '';
  109. /**
  110. * Instance
  111. * @var Twig_Environment
  112. */
  113. private $twig;
  114. protected $templateVars = array();
  115. private $contentType = 'text/html; charset=utf-8';
  116. private $xFrameOptions = null;
  117. /**
  118. * Constructor.
  119. *
  120. * @param string $templateFile The template file to load. Must be in the following format:
  121. * `"@MyPlugin/templateFileName"`. Note the absence of .twig
  122. * from the end of the name.
  123. */
  124. public function __construct($templateFile)
  125. {
  126. $templateExt = '.twig';
  127. if (substr($templateFile, -strlen($templateExt)) !== $templateExt) {
  128. $templateFile .= $templateExt;
  129. }
  130. $this->template = $templateFile;
  131. $this->initializeTwig();
  132. $this->piwik_version = Version::VERSION;
  133. $this->userLogin = Piwik::getCurrentUserLogin();
  134. $this->isSuperUser = Access::getInstance()->hasSuperUserAccess();
  135. try {
  136. $this->piwikUrl = SettingsPiwik::getPiwikUrl();
  137. } catch (Exception $ex) {
  138. // pass (occurs when DB cannot be connected to, perhaps piwik URL cache should be stored in config file...)
  139. }
  140. }
  141. /**
  142. * Returns the template filename.
  143. *
  144. * @return string
  145. */
  146. public function getTemplateFile()
  147. {
  148. return $this->template;
  149. }
  150. /**
  151. * Returns the variables to bind to the template when rendering.
  152. *
  153. * @param array $override Template variable override values. Mainly useful
  154. * when including View templates in other templates.
  155. * @return array
  156. */
  157. public function getTemplateVars($override = array())
  158. {
  159. return $override + $this->templateVars;
  160. }
  161. /**
  162. * Directly assigns a variable to the view script.
  163. * Variable names may not be prefixed with '_'.
  164. *
  165. * @param string $key The variable name.
  166. * @param mixed $val The variable value.
  167. */
  168. public function __set($key, $val)
  169. {
  170. $this->templateVars[$key] = $val;
  171. }
  172. /**
  173. * Retrieves an assigned variable.
  174. * Variable names may not be prefixed with '_'.
  175. *
  176. * @param string $key The variable name.
  177. * @return mixed The variable value.
  178. */
  179. public function &__get($key)
  180. {
  181. return $this->templateVars[$key];
  182. }
  183. /**
  184. * Returns true if a template variable has been set or not.
  185. *
  186. * @param $name The name of the template variable.
  187. * @return bool
  188. */
  189. public function __isset($name)
  190. {
  191. return isset($this->templateVars[$name]);
  192. }
  193. private function initializeTwig()
  194. {
  195. $piwikTwig = new Twig();
  196. $this->twig = $piwikTwig->getTwigEnvironment();
  197. }
  198. /**
  199. * Renders the current view. Also sends the stored 'Content-Type' HTML header.
  200. * See {@link setContentType()}.
  201. *
  202. * @return string Generated template.
  203. */
  204. public function render()
  205. {
  206. try {
  207. $this->currentModule = Piwik::getModule();
  208. $this->currentAction = Piwik::getAction();
  209. $this->url = Common::sanitizeInputValue(Url::getCurrentUrl());
  210. $this->token_auth = Piwik::getCurrentUserTokenAuth();
  211. $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess();
  212. $this->userIsSuperUser = Piwik::hasUserSuperUserAccess();
  213. $this->latest_version_available = UpdateCheck::isNewestVersionAvailable();
  214. $this->disableLink = Common::getRequestVar('disableLink', 0, 'int');
  215. $this->isWidget = Common::getRequestVar('widget', 0, 'int');
  216. $this->cacheBuster = UIAssetCacheBuster::getInstance()->piwikVersionBasedCacheBuster();
  217. $this->loginModule = Piwik::getLoginPluginName();
  218. $user = APIUsersManager::getInstance()->getUser($this->userLogin);
  219. $this->userAlias = $user['alias'];
  220. } catch (Exception $e) {
  221. Log::verbose($e);
  222. // can fail, for example at installation (no plugin loaded yet)
  223. }
  224. try {
  225. $this->totalTimeGeneration = Registry::get('timer')->getTime();
  226. $this->totalNumberOfQueries = Profiler::getQueryCount();
  227. } catch (Exception $e) {
  228. $this->totalNumberOfQueries = 0;
  229. }
  230. ProxyHttp::overrideCacheControlHeaders('no-store');
  231. Common::sendHeader('Content-Type: ' . $this->contentType);
  232. // always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail)
  233. Common::sendHeader('X-Frame-Options: ' . (string)$this->xFrameOptions);
  234. return $this->renderTwigTemplate();
  235. }
  236. protected function renderTwigTemplate()
  237. {
  238. try {
  239. $output = $this->twig->render($this->getTemplateFile(), $this->getTemplateVars());
  240. } catch (Exception $ex) {
  241. // twig does not rethrow exceptions, it wraps them so we log the cause if we can find it
  242. $cause = $ex->getPrevious();
  243. Log::debug($cause === null ? $ex : $cause);
  244. throw $ex;
  245. }
  246. $output = $this->applyFilter_cacheBuster($output);
  247. $helper = new Theme;
  248. $output = $helper->rewriteAssetsPathToTheme($output);
  249. return $output;
  250. }
  251. protected function applyFilter_cacheBuster($output)
  252. {
  253. $assetManager = AssetManager::getInstance();
  254. $stylesheet = $assetManager->getMergedStylesheetAsset();
  255. if ($stylesheet->exists()) {
  256. $content = $stylesheet->getContent();
  257. } else {
  258. $content = $assetManager->getMergedStylesheet()->getContent();
  259. }
  260. $cacheBuster = UIAssetCacheBuster::getInstance();
  261. $tagJs = 'cb=' . $cacheBuster->piwikVersionBasedCacheBuster();
  262. $tagCss = 'cb=' . $cacheBuster->md5BasedCacheBuster($content);
  263. $pattern = array(
  264. '~<script type=[\'"]text/javascript[\'"] src=[\'"]([^\'"]+)[\'"]>~',
  265. '~<script src=[\'"]([^\'"]+)[\'"] type=[\'"]text/javascript[\'"]>~',
  266. '~<link rel=[\'"]stylesheet[\'"] type=[\'"]text/css[\'"] href=[\'"]([^\'"]+)[\'"] ?/?>~',
  267. // removes the double ?cb= tag
  268. '~(src|href)=\"index.php\?module=([A-Za-z0-9_]+)&action=([A-Za-z0-9_]+)\?cb=~',
  269. );
  270. $replace = array(
  271. '<script type="text/javascript" src="$1?' . $tagJs . '">',
  272. '<script type="text/javascript" src="$1?' . $tagJs . '">',
  273. '<link rel="stylesheet" type="text/css" href="$1?' . $tagCss . '" />',
  274. '$1="index.php?module=$2&amp;action=$3&amp;cb=',
  275. );
  276. return preg_replace($pattern, $replace, $output);
  277. }
  278. /**
  279. * Set stored value used in the Content-Type HTTP header field. The header is
  280. * set just before rendering.
  281. *
  282. * @param string $contentType
  283. */
  284. public function setContentType($contentType)
  285. {
  286. $this->contentType = $contentType;
  287. }
  288. /**
  289. * Set X-Frame-Options field in the HTTP response. The header is set just
  290. * before rendering.
  291. *
  292. * _Note: setting this allows you to make sure the View **cannot** be
  293. * embedded in iframes. Learn more [here](https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options)._
  294. *
  295. * @param string $option ('deny' or 'sameorigin')
  296. */
  297. public function setXFrameOptions($option = 'deny')
  298. {
  299. if ($option === 'deny' || $option === 'sameorigin') {
  300. $this->xFrameOptions = $option;
  301. }
  302. if ($option == 'allow') {
  303. $this->xFrameOptions = null;
  304. }
  305. }
  306. /**
  307. * Add form to view
  308. *
  309. * @param QuickForm2 $form
  310. * @ignore
  311. */
  312. public function addForm(QuickForm2 $form)
  313. {
  314. // assign array with form data
  315. $this->assign('form_data', $form->getFormData());
  316. $this->assign('element_list', $form->getElementList());
  317. }
  318. /**
  319. * Assign value to a variable for use in a template
  320. * @param string|array $var
  321. * @param mixed $value
  322. * @ignore
  323. */
  324. public function assign($var, $value = null)
  325. {
  326. if (is_string($var)) {
  327. $this->$var = $value;
  328. } elseif (is_array($var)) {
  329. foreach ($var as $key => $value) {
  330. $this->$key = $value;
  331. }
  332. }
  333. }
  334. /**
  335. * Clear compiled Twig templates
  336. * @ignore
  337. */
  338. public static function clearCompiledTemplates()
  339. {
  340. $twig = new Twig();
  341. $twig->getTwigEnvironment()->clearTemplateCache();
  342. }
  343. /**
  344. * Creates a View for and then renders the single report template.
  345. *
  346. * Can be used for pages that display only one report to avoid having to create
  347. * a new template.
  348. *
  349. * @param string $title The report title.
  350. * @param string $reportHtml The report body HTML.
  351. * @return string|void The report contents if `$fetch` is true.
  352. */
  353. public static function singleReport($title, $reportHtml)
  354. {
  355. $view = new View('@CoreHome/_singleReport');
  356. $view->title = $title;
  357. $view->report = $reportHtml;
  358. return $view->render();
  359. }
  360. }