Base for a static organization website

View.php 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. <?php
  2. /**
  3. * Methods for displaying presentation data in the view.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.View
  15. * @since CakePHP(tm) v 0.10.0.1076
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('HelperCollection', 'View');
  19. App::uses('AppHelper', 'View/Helper');
  20. App::uses('Router', 'Routing');
  21. App::uses('ViewBlock', 'View');
  22. App::uses('CakeEvent', 'Event');
  23. App::uses('CakeEventManager', 'Event');
  24. App::uses('CakeResponse', 'Network');
  25. /**
  26. * View, the V in the MVC triad. View interacts with Helpers and view variables passed
  27. * in from the controller to render the results of the controller action. Often this is HTML,
  28. * but can also take the form of JSON, XML, PDF's or streaming files.
  29. *
  30. * CakePHP uses a two-step-view pattern. This means that the view content is rendered first,
  31. * and then inserted into the selected layout. This also means you can pass data from the view to the
  32. * layout using `$this->set()`
  33. *
  34. * Since 2.1, the base View class also includes support for themes by default. Theme views are regular
  35. * view files that can provide unique HTML and static assets. If theme views are not found for the
  36. * current view the default app view files will be used. You can set `$this->theme = 'mytheme'`
  37. * in your Controller to use the Themes.
  38. *
  39. * Example of theme path with `$this->theme = 'SuperHot';` Would be `app/View/Themed/SuperHot/Posts`
  40. *
  41. * @package Cake.View
  42. * @property CacheHelper $Cache
  43. * @property FormHelper $Form
  44. * @property HtmlHelper $Html
  45. * @property JsHelper $Js
  46. * @property NumberHelper $Number
  47. * @property PaginatorHelper $Paginator
  48. * @property RssHelper $Rss
  49. * @property SessionHelper $Session
  50. * @property TextHelper $Text
  51. * @property TimeHelper $Time
  52. * @property ViewBlock $Blocks
  53. */
  54. class View extends Object {
  55. /**
  56. * Helpers collection
  57. *
  58. * @var HelperCollection
  59. */
  60. public $Helpers;
  61. /**
  62. * ViewBlock instance.
  63. *
  64. * @var ViewBlock
  65. */
  66. public $Blocks;
  67. /**
  68. * Name of the plugin.
  69. *
  70. * @link http://manual.cakephp.org/chapter/plugins
  71. * @var string
  72. */
  73. public $plugin = null;
  74. /**
  75. * Name of the controller.
  76. *
  77. * @var string
  78. */
  79. public $name = null;
  80. /**
  81. * Current passed params
  82. *
  83. * @var mixed
  84. */
  85. public $passedArgs = array();
  86. /**
  87. * An array of names of built-in helpers to include.
  88. *
  89. * @var mixed
  90. */
  91. public $helpers = array();
  92. /**
  93. * Path to View.
  94. *
  95. * @var string
  96. */
  97. public $viewPath = null;
  98. /**
  99. * Variables for the view
  100. *
  101. * @var array
  102. */
  103. public $viewVars = array();
  104. /**
  105. * Name of view to use with this View.
  106. *
  107. * @var string
  108. */
  109. public $view = null;
  110. /**
  111. * Name of layout to use with this View.
  112. *
  113. * @var string
  114. */
  115. public $layout = 'default';
  116. /**
  117. * Path to Layout.
  118. *
  119. * @var string
  120. */
  121. public $layoutPath = null;
  122. /**
  123. * Turns on or off CakePHP's conventional mode of applying layout files. On by default.
  124. * Setting to off means that layouts will not be automatically applied to rendered views.
  125. *
  126. * @var bool
  127. */
  128. public $autoLayout = true;
  129. /**
  130. * File extension. Defaults to CakePHP's template ".ctp".
  131. *
  132. * @var string
  133. */
  134. public $ext = '.ctp';
  135. /**
  136. * Sub-directory for this view file. This is often used for extension based routing.
  137. * Eg. With an `xml` extension, $subDir would be `xml/`
  138. *
  139. * @var string
  140. */
  141. public $subDir = null;
  142. /**
  143. * Theme name.
  144. *
  145. * @var string
  146. */
  147. public $theme = null;
  148. /**
  149. * Used to define methods a controller that will be cached.
  150. *
  151. * @see Controller::$cacheAction
  152. * @var mixed
  153. */
  154. public $cacheAction = false;
  155. /**
  156. * Holds current errors for the model validation.
  157. *
  158. * @var array
  159. */
  160. public $validationErrors = array();
  161. /**
  162. * True when the view has been rendered.
  163. *
  164. * @var bool
  165. */
  166. public $hasRendered = false;
  167. /**
  168. * List of generated DOM UUIDs.
  169. *
  170. * @var array
  171. */
  172. public $uuids = array();
  173. /**
  174. * An instance of a CakeRequest object that contains information about the current request.
  175. * This object contains all the information about a request and several methods for reading
  176. * additional information about the request.
  177. *
  178. * @var CakeRequest
  179. */
  180. public $request;
  181. /**
  182. * Reference to the Response object
  183. *
  184. * @var CakeResponse
  185. */
  186. public $response;
  187. /**
  188. * The Cache configuration View will use to store cached elements. Changing this will change
  189. * the default configuration elements are stored under. You can also choose a cache config
  190. * per element.
  191. *
  192. * @var string
  193. * @see View::element()
  194. */
  195. public $elementCache = 'default';
  196. /**
  197. * Element cache settings
  198. *
  199. * @var array
  200. * @see View::_elementCache();
  201. * @see View::_renderElement
  202. */
  203. public $elementCacheSettings = array();
  204. /**
  205. * List of variables to collect from the associated controller.
  206. *
  207. * @var array
  208. */
  209. protected $_passedVars = array(
  210. 'viewVars', 'autoLayout', 'ext', 'helpers', 'view', 'layout', 'name', 'theme',
  211. 'layoutPath', 'viewPath', 'request', 'plugin', 'passedArgs', 'cacheAction'
  212. );
  213. /**
  214. * Scripts (and/or other <head /> tags) for the layout.
  215. *
  216. * @var array
  217. */
  218. protected $_scripts = array();
  219. /**
  220. * Holds an array of paths.
  221. *
  222. * @var array
  223. */
  224. protected $_paths = array();
  225. /**
  226. * Holds an array of plugin paths.
  227. *
  228. * @var array
  229. */
  230. protected $_pathsForPlugin = array();
  231. /**
  232. * The names of views and their parents used with View::extend();
  233. *
  234. * @var array
  235. */
  236. protected $_parents = array();
  237. /**
  238. * The currently rendering view file. Used for resolving parent files.
  239. *
  240. * @var string
  241. */
  242. protected $_current = null;
  243. /**
  244. * Currently rendering an element. Used for finding parent fragments
  245. * for elements.
  246. *
  247. * @var string
  248. */
  249. protected $_currentType = '';
  250. /**
  251. * Content stack, used for nested templates that all use View::extend();
  252. *
  253. * @var array
  254. */
  255. protected $_stack = array();
  256. /**
  257. * Instance of the CakeEventManager this View object is using
  258. * to dispatch inner events. Usually the manager is shared with
  259. * the controller, so it it possible to register view events in
  260. * the controller layer.
  261. *
  262. * @var CakeEventManager
  263. */
  264. protected $_eventManager = null;
  265. /**
  266. * Whether the event manager was already configured for this object
  267. *
  268. * @var bool
  269. */
  270. protected $_eventManagerConfigured = false;
  271. /**
  272. * Constant for view file type 'view'
  273. *
  274. * @var string
  275. */
  276. const TYPE_VIEW = 'view';
  277. /**
  278. * Constant for view file type 'element'
  279. *
  280. * @var string
  281. */
  282. const TYPE_ELEMENT = 'element';
  283. /**
  284. * Constant for view file type 'layout'
  285. *
  286. * @var string
  287. */
  288. const TYPE_LAYOUT = 'layout';
  289. /**
  290. * Constructor
  291. *
  292. * @param Controller $controller A controller object to pull View::_passedVars from.
  293. */
  294. public function __construct(Controller $controller = null) {
  295. if (is_object($controller)) {
  296. $count = count($this->_passedVars);
  297. for ($j = 0; $j < $count; $j++) {
  298. $var = $this->_passedVars[$j];
  299. $this->{$var} = $controller->{$var};
  300. }
  301. $this->_eventManager = $controller->getEventManager();
  302. }
  303. if (empty($this->request) && !($this->request = Router::getRequest(true))) {
  304. $this->request = new CakeRequest(null, false);
  305. $this->request->base = '';
  306. $this->request->here = $this->request->webroot = '/';
  307. }
  308. if (is_object($controller) && isset($controller->response)) {
  309. $this->response = $controller->response;
  310. } else {
  311. $this->response = new CakeResponse();
  312. }
  313. $this->Helpers = new HelperCollection($this);
  314. $this->Blocks = new ViewBlock();
  315. $this->loadHelpers();
  316. parent::__construct();
  317. }
  318. /**
  319. * Returns the CakeEventManager manager instance that is handling any callbacks.
  320. * You can use this instance to register any new listeners or callbacks to the
  321. * controller events, or create your own events and trigger them at will.
  322. *
  323. * @return CakeEventManager
  324. */
  325. public function getEventManager() {
  326. if (empty($this->_eventManager)) {
  327. $this->_eventManager = new CakeEventManager();
  328. }
  329. if (!$this->_eventManagerConfigured) {
  330. $this->_eventManager->attach($this->Helpers);
  331. $this->_eventManagerConfigured = true;
  332. }
  333. return $this->_eventManager;
  334. }
  335. /**
  336. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  337. *
  338. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  339. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  340. *
  341. * @param string $name Name of template file in the/app/View/Elements/ folder,
  342. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  343. * is not found in the plugin, the normal view path cascade will be searched.
  344. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  345. * @param array $options Array of options. Possible keys are:
  346. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  347. * If an array, the following keys can be used:
  348. * - `config` - Used to store the cached element in a custom cache configuration.
  349. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  350. * - `plugin` - (deprecated!) Load an element from a specific plugin. This option is deprecated, and
  351. * will be removed in CakePHP 3.0. Use `Plugin.element_name` instead.
  352. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  353. * Defaults to false.
  354. * - `ignoreMissing` - Used to allow missing elements. Set to true to not trigger notices.
  355. * @return string Rendered Element
  356. */
  357. public function element($name, $data = array(), $options = array()) {
  358. $file = $plugin = null;
  359. if (isset($options['plugin'])) {
  360. $name = Inflector::camelize($options['plugin']) . '.' . $name;
  361. }
  362. if (!isset($options['callbacks'])) {
  363. $options['callbacks'] = false;
  364. }
  365. if (isset($options['cache'])) {
  366. $contents = $this->_elementCache($name, $data, $options);
  367. if ($contents !== false) {
  368. return $contents;
  369. }
  370. }
  371. $file = $this->_getElementFilename($name);
  372. if ($file) {
  373. return $this->_renderElement($file, $data, $options);
  374. }
  375. if (empty($options['ignoreMissing'])) {
  376. list ($plugin, $name) = pluginSplit($name, true);
  377. $name = str_replace('/', DS, $name);
  378. $file = $plugin . 'Elements' . DS . $name . $this->ext;
  379. trigger_error(__d('cake_dev', 'Element Not Found: %s', $file), E_USER_NOTICE);
  380. }
  381. }
  382. /**
  383. * Checks if an element exists
  384. *
  385. * @param string $name Name of template file in the /app/View/Elements/ folder,
  386. * or `MyPlugin.template` to check the template element from MyPlugin. If the element
  387. * is not found in the plugin, the normal view path cascade will be searched.
  388. * @return bool Success
  389. */
  390. public function elementExists($name) {
  391. return (bool)$this->_getElementFilename($name);
  392. }
  393. /**
  394. * Renders view for given view file and layout.
  395. *
  396. * Render triggers helper callbacks, which are fired before and after the view are rendered,
  397. * as well as before and after the layout. The helper callbacks are called:
  398. *
  399. * - `beforeRender`
  400. * - `afterRender`
  401. * - `beforeLayout`
  402. * - `afterLayout`
  403. *
  404. * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
  405. *
  406. * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
  407. * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
  408. * the view will be located along the regular view path cascade.
  409. *
  410. * @param string $view Name of view file to use
  411. * @param string $layout Layout to use.
  412. * @return string|null Rendered content or null if content already rendered and returned earlier.
  413. * @triggers View.beforeRender $this, array($viewFileName)
  414. * @triggers View.afterRender $this, array($viewFileName)
  415. * @throws CakeException If there is an error in the view.
  416. */
  417. public function render($view = null, $layout = null) {
  418. if ($this->hasRendered) {
  419. return null;
  420. }
  421. if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
  422. $this->_currentType = static::TYPE_VIEW;
  423. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($viewFileName)));
  424. $this->Blocks->set('content', $this->_render($viewFileName));
  425. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($viewFileName)));
  426. }
  427. if ($layout === null) {
  428. $layout = $this->layout;
  429. }
  430. if ($layout && $this->autoLayout) {
  431. $this->Blocks->set('content', $this->renderLayout('', $layout));
  432. }
  433. $this->hasRendered = true;
  434. return $this->Blocks->get('content');
  435. }
  436. /**
  437. * Renders a layout. Returns output from _render(). Returns false on error.
  438. * Several variables are created for use in layout.
  439. *
  440. * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
  441. * - `content_for_layout` - contains rendered view file
  442. * - `scripts_for_layout` - Contains content added with addScript() as well as any content in
  443. * the 'meta', 'css', and 'script' blocks. They are appended in that order.
  444. *
  445. * Deprecated features:
  446. *
  447. * - `$scripts_for_layout` is deprecated and will be removed in CakePHP 3.0.
  448. * Use the block features instead. `meta`, `css` and `script` will be populated
  449. * by the matching methods on HtmlHelper.
  450. * - `$title_for_layout` is deprecated and will be removed in CakePHP 3.0.
  451. * Use the `title` block instead.
  452. * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
  453. * Use the `content` block instead.
  454. *
  455. * @param string $content Content to render in a view, wrapped by the surrounding layout.
  456. * @param string $layout Layout name
  457. * @return mixed Rendered output, or false on error
  458. * @triggers View.beforeLayout $this, array($layoutFileName)
  459. * @triggers View.afterLayout $this, array($layoutFileName)
  460. * @throws CakeException if there is an error in the view.
  461. */
  462. public function renderLayout($content, $layout = null) {
  463. $layoutFileName = $this->_getLayoutFileName($layout);
  464. if (empty($layoutFileName)) {
  465. return $this->Blocks->get('content');
  466. }
  467. if (empty($content)) {
  468. $content = $this->Blocks->get('content');
  469. } else {
  470. $this->Blocks->set('content', $content);
  471. }
  472. $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
  473. $scripts = implode("\n\t", $this->_scripts);
  474. $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
  475. $this->viewVars = array_merge($this->viewVars, array(
  476. 'content_for_layout' => $content,
  477. 'scripts_for_layout' => $scripts,
  478. ));
  479. $title = $this->Blocks->get('title');
  480. if ($title === '') {
  481. if (isset($this->viewVars['title_for_layout'])) {
  482. $title = $this->viewVars['title_for_layout'];
  483. } else {
  484. $title = Inflector::humanize($this->viewPath);
  485. }
  486. }
  487. $this->viewVars['title_for_layout'] = $title;
  488. $this->Blocks->set('title', $title);
  489. $this->_currentType = static::TYPE_LAYOUT;
  490. $this->Blocks->set('content', $this->_render($layoutFileName));
  491. $this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
  492. return $this->Blocks->get('content');
  493. }
  494. /**
  495. * Render cached view. Works in concert with CacheHelper and Dispatcher to
  496. * render cached view files.
  497. *
  498. * @param string $filename the cache file to include
  499. * @param string $timeStart the page render start time
  500. * @return bool Success of rendering the cached file.
  501. */
  502. public function renderCache($filename, $timeStart) {
  503. $response = $this->response;
  504. ob_start();
  505. include $filename;
  506. $type = $response->mapType($response->type());
  507. if (Configure::read('debug') > 0 && $type === 'html') {
  508. echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
  509. }
  510. $out = ob_get_clean();
  511. if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
  512. if (time() >= $match['1']) {
  513. //@codingStandardsIgnoreStart
  514. @unlink($filename);
  515. //@codingStandardsIgnoreEnd
  516. unset($out);
  517. return false;
  518. }
  519. return substr($out, strlen($match[0]));
  520. }
  521. }
  522. /**
  523. * Returns a list of variables available in the current View context
  524. *
  525. * @return array Array of the set view variable names.
  526. */
  527. public function getVars() {
  528. return array_keys($this->viewVars);
  529. }
  530. /**
  531. * Returns the contents of the given View variable(s)
  532. *
  533. * @param string $var The view var you want the contents of.
  534. * @return mixed The content of the named var if its set, otherwise null.
  535. * @deprecated 3.0.0 Will be removed in 3.0. Use View::get() instead.
  536. */
  537. public function getVar($var) {
  538. return $this->get($var);
  539. }
  540. /**
  541. * Returns the contents of the given View variable.
  542. *
  543. * @param string $var The view var you want the contents of.
  544. * @param mixed $default The default/fallback content of $var.
  545. * @return mixed The content of the named var if its set, otherwise $default.
  546. */
  547. public function get($var, $default = null) {
  548. if (!isset($this->viewVars[$var])) {
  549. return $default;
  550. }
  551. return $this->viewVars[$var];
  552. }
  553. /**
  554. * Get the names of all the existing blocks.
  555. *
  556. * @return array An array containing the blocks.
  557. * @see ViewBlock::keys()
  558. */
  559. public function blocks() {
  560. return $this->Blocks->keys();
  561. }
  562. /**
  563. * Start capturing output for a 'block'
  564. *
  565. * @param string $name The name of the block to capture for.
  566. * @return void
  567. * @see ViewBlock::start()
  568. */
  569. public function start($name) {
  570. $this->Blocks->start($name);
  571. }
  572. /**
  573. * Start capturing output for a 'block' if it has no content
  574. *
  575. * @param string $name The name of the block to capture for.
  576. * @return void
  577. * @see ViewBlock::startIfEmpty()
  578. */
  579. public function startIfEmpty($name) {
  580. $this->Blocks->startIfEmpty($name);
  581. }
  582. /**
  583. * Append to an existing or new block. Appending to a new
  584. * block will create the block.
  585. *
  586. * @param string $name Name of the block
  587. * @param mixed $value The content for the block.
  588. * @return void
  589. * @see ViewBlock::concat()
  590. */
  591. public function append($name, $value = null) {
  592. $this->Blocks->concat($name, $value);
  593. }
  594. /**
  595. * Prepend to an existing or new block. Prepending to a new
  596. * block will create the block.
  597. *
  598. * @param string $name Name of the block
  599. * @param mixed $value The content for the block.
  600. * @return void
  601. * @see ViewBlock::concat()
  602. */
  603. public function prepend($name, $value = null) {
  604. $this->Blocks->concat($name, $value, ViewBlock::PREPEND);
  605. }
  606. /**
  607. * Set the content for a block. This will overwrite any
  608. * existing content.
  609. *
  610. * @param string $name Name of the block
  611. * @param mixed $value The content for the block.
  612. * @return void
  613. * @see ViewBlock::set()
  614. */
  615. public function assign($name, $value) {
  616. $this->Blocks->set($name, $value);
  617. }
  618. /**
  619. * Fetch the content for a block. If a block is
  620. * empty or undefined '' will be returned.
  621. *
  622. * @param string $name Name of the block
  623. * @param string $default Default text
  624. * @return string default The block content or $default if the block does not exist.
  625. * @see ViewBlock::get()
  626. */
  627. public function fetch($name, $default = '') {
  628. return $this->Blocks->get($name, $default);
  629. }
  630. /**
  631. * Check if a block exists
  632. *
  633. * @param string $name Name of the block
  634. * @return bool
  635. */
  636. public function exists($name) {
  637. return $this->Blocks->exists($name);
  638. }
  639. /**
  640. * End a capturing block. The compliment to View::start()
  641. *
  642. * @return void
  643. * @see ViewBlock::end()
  644. */
  645. public function end() {
  646. $this->Blocks->end();
  647. }
  648. /**
  649. * Provides view or element extension/inheritance. Views can extends a
  650. * parent view and populate blocks in the parent template.
  651. *
  652. * @param string $name The view or element to 'extend' the current one with.
  653. * @return void
  654. * @throws LogicException when you extend a view with itself or make extend loops.
  655. * @throws LogicException when you extend an element which doesn't exist
  656. */
  657. public function extend($name) {
  658. if ($name[0] === '/' || $this->_currentType === static::TYPE_VIEW) {
  659. $parent = $this->_getViewFileName($name);
  660. } else {
  661. switch ($this->_currentType) {
  662. case static::TYPE_ELEMENT:
  663. $parent = $this->_getElementFileName($name);
  664. if (!$parent) {
  665. list($plugin, $name) = $this->pluginSplit($name);
  666. $paths = $this->_paths($plugin);
  667. $defaultPath = $paths[0] . 'Elements' . DS;
  668. throw new LogicException(__d(
  669. 'cake_dev',
  670. 'You cannot extend an element which does not exist (%s).',
  671. $defaultPath . $name . $this->ext
  672. ));
  673. }
  674. break;
  675. case static::TYPE_LAYOUT:
  676. $parent = $this->_getLayoutFileName($name);
  677. break;
  678. default:
  679. $parent = $this->_getViewFileName($name);
  680. }
  681. }
  682. if ($parent == $this->_current) {
  683. throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
  684. }
  685. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  686. throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
  687. }
  688. $this->_parents[$this->_current] = $parent;
  689. }
  690. /**
  691. * Adds a script block or other element to be inserted in $scripts_for_layout in
  692. * the `<head />` of a document layout
  693. *
  694. * @param string $name Either the key name for the script, or the script content. Name can be used to
  695. * update/replace a script element.
  696. * @param string $content The content of the script being added, optional.
  697. * @return void
  698. * @deprecated 3.0.0 Will be removed in 3.0. Superseded by blocks functionality.
  699. * @see View::start()
  700. */
  701. public function addScript($name, $content = null) {
  702. if (empty($content)) {
  703. if (!in_array($name, array_values($this->_scripts))) {
  704. $this->_scripts[] = $name;
  705. }
  706. } else {
  707. $this->_scripts[$name] = $content;
  708. }
  709. }
  710. /**
  711. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  712. *
  713. * @param string $object Type of object, i.e. 'form' or 'link'
  714. * @param string $url The object's target URL
  715. * @return string
  716. */
  717. public function uuid($object, $url) {
  718. $c = 1;
  719. $url = Router::url($url);
  720. $hash = $object . substr(md5($object . $url), 0, 10);
  721. while (in_array($hash, $this->uuids)) {
  722. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  723. $c++;
  724. }
  725. $this->uuids[] = $hash;
  726. return $hash;
  727. }
  728. /**
  729. * Allows a template or element to set a variable that will be available in
  730. * a layout or other element. Analogous to Controller::set().
  731. *
  732. * @param string|array $one A string or an array of data.
  733. * @param string|array $two Value in case $one is a string (which then works as the key).
  734. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  735. * @return void
  736. */
  737. public function set($one, $two = null) {
  738. $data = null;
  739. if (is_array($one)) {
  740. if (is_array($two)) {
  741. $data = array_combine($one, $two);
  742. } else {
  743. $data = $one;
  744. }
  745. } else {
  746. $data = array($one => $two);
  747. }
  748. if (!$data) {
  749. return false;
  750. }
  751. $this->viewVars = $data + $this->viewVars;
  752. }
  753. /**
  754. * Retrieve the current view type
  755. *
  756. * @return string
  757. */
  758. public function getCurrentType() {
  759. return $this->_currentType;
  760. }
  761. /**
  762. * Magic accessor for helpers. Provides access to attributes that were deprecated.
  763. *
  764. * @param string $name Name of the attribute to get.
  765. * @return mixed
  766. */
  767. public function __get($name) {
  768. switch ($name) {
  769. case 'base':
  770. case 'here':
  771. case 'webroot':
  772. case 'data':
  773. return $this->request->{$name};
  774. case 'action':
  775. return $this->request->params['action'];
  776. case 'params':
  777. return $this->request;
  778. case 'output':
  779. return $this->Blocks->get('content');
  780. }
  781. if (isset($this->Helpers->{$name})) {
  782. $this->{$name} = $this->Helpers->{$name};
  783. return $this->Helpers->{$name};
  784. }
  785. return $this->{$name};
  786. }
  787. /**
  788. * Magic accessor for deprecated attributes.
  789. *
  790. * @param string $name Name of the attribute to set.
  791. * @param mixed $value Value of the attribute to set.
  792. * @return mixed
  793. */
  794. public function __set($name, $value) {
  795. switch ($name) {
  796. case 'output':
  797. return $this->Blocks->set('content', $value);
  798. default:
  799. $this->{$name} = $value;
  800. }
  801. }
  802. /**
  803. * Magic isset check for deprecated attributes.
  804. *
  805. * @param string $name Name of the attribute to check.
  806. * @return bool
  807. */
  808. public function __isset($name) {
  809. if (isset($this->{$name})) {
  810. return true;
  811. }
  812. $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
  813. if (in_array($name, $magicGet)) {
  814. return $this->__get($name) !== null;
  815. }
  816. return false;
  817. }
  818. /**
  819. * Interact with the HelperCollection to load all the helpers.
  820. *
  821. * @return void
  822. */
  823. public function loadHelpers() {
  824. $helpers = HelperCollection::normalizeObjectArray($this->helpers);
  825. foreach ($helpers as $properties) {
  826. list(, $class) = pluginSplit($properties['class']);
  827. $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
  828. }
  829. }
  830. /**
  831. * Renders and returns output for given view filename with its
  832. * array of data. Handles parent/extended views.
  833. *
  834. * @param string $viewFile Filename of the view
  835. * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
  836. * @return string Rendered output
  837. * @triggers View.beforeRenderFile $this, array($viewFile)
  838. * @triggers View.afterRenderFile $this, array($viewFile, $content)
  839. * @throws CakeException when a block is left open.
  840. */
  841. protected function _render($viewFile, $data = array()) {
  842. if (empty($data)) {
  843. $data = $this->viewVars;
  844. }
  845. $this->_current = $viewFile;
  846. $initialBlocks = count($this->Blocks->unclosed());
  847. $eventManager = $this->getEventManager();
  848. $beforeEvent = new CakeEvent('View.beforeRenderFile', $this, array($viewFile));
  849. $eventManager->dispatch($beforeEvent);
  850. $content = $this->_evaluate($viewFile, $data);
  851. $afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
  852. $afterEvent->modParams = 1;
  853. $eventManager->dispatch($afterEvent);
  854. $content = $afterEvent->data[1];
  855. if (isset($this->_parents[$viewFile])) {
  856. $this->_stack[] = $this->fetch('content');
  857. $this->assign('content', $content);
  858. $content = $this->_render($this->_parents[$viewFile]);
  859. $this->assign('content', array_pop($this->_stack));
  860. }
  861. $remainingBlocks = count($this->Blocks->unclosed());
  862. if ($initialBlocks !== $remainingBlocks) {
  863. throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
  864. }
  865. return $content;
  866. }
  867. /**
  868. * Sandbox method to evaluate a template / view script in.
  869. *
  870. * @param string $viewFile Filename of the view
  871. * @param array $dataForView Data to include in rendered view.
  872. * If empty the current View::$viewVars will be used.
  873. * @return string Rendered output
  874. */
  875. protected function _evaluate($viewFile, $dataForView) {
  876. $this->__viewFile = $viewFile;
  877. extract($dataForView);
  878. ob_start();
  879. include $this->__viewFile;
  880. unset($this->__viewFile);
  881. return ob_get_clean();
  882. }
  883. /**
  884. * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
  885. *
  886. * @param string $helperName Name of the helper to load.
  887. * @param array $settings Settings for the helper
  888. * @return Helper a constructed helper object.
  889. * @see HelperCollection::load()
  890. */
  891. public function loadHelper($helperName, $settings = array()) {
  892. return $this->Helpers->load($helperName, $settings);
  893. }
  894. /**
  895. * Returns filename of given action's template file (.ctp) as a string.
  896. * CamelCased action names will be under_scored! This means that you can have
  897. * LongActionNames that refer to long_action_names.ctp views.
  898. *
  899. * @param string $name Controller action to find template filename for
  900. * @return string Template filename
  901. * @throws MissingViewException when a view file could not be found.
  902. */
  903. protected function _getViewFileName($name = null) {
  904. $subDir = null;
  905. if ($this->subDir !== null) {
  906. $subDir = $this->subDir . DS;
  907. }
  908. if ($name === null) {
  909. $name = $this->view;
  910. }
  911. $name = str_replace('/', DS, $name);
  912. list($plugin, $name) = $this->pluginSplit($name);
  913. if (strpos($name, DS) === false && $name[0] !== '.') {
  914. $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
  915. } elseif (strpos($name, DS) !== false) {
  916. if ($name[0] === DS || $name[1] === ':') {
  917. $name = trim($name, DS);
  918. } elseif ($name[0] === '.') {
  919. $name = substr($name, 3);
  920. } elseif (!$plugin || $this->viewPath !== $this->name) {
  921. $name = $this->viewPath . DS . $subDir . $name;
  922. }
  923. }
  924. $paths = $this->_paths($plugin);
  925. $exts = $this->_getExtensions();
  926. foreach ($exts as $ext) {
  927. foreach ($paths as $path) {
  928. if (file_exists($path . $name . $ext)) {
  929. return $path . $name . $ext;
  930. }
  931. }
  932. }
  933. throw new MissingViewException(array('file' => $name . $this->ext));
  934. }
  935. /**
  936. * Splits a dot syntax plugin name into its plugin and filename.
  937. * If $name does not have a dot, then index 0 will be null.
  938. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  939. *
  940. * @param string $name The name you want to plugin split.
  941. * @param bool $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
  942. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  943. */
  944. public function pluginSplit($name, $fallback = true) {
  945. $plugin = null;
  946. list($first, $second) = pluginSplit($name);
  947. if (CakePlugin::loaded($first) === true) {
  948. $name = $second;
  949. $plugin = $first;
  950. }
  951. if (isset($this->plugin) && !$plugin && $fallback) {
  952. $plugin = $this->plugin;
  953. }
  954. return array($plugin, $name);
  955. }
  956. /**
  957. * Returns layout filename for this template as a string.
  958. *
  959. * @param string $name The name of the layout to find.
  960. * @return string Filename for layout file (.ctp).
  961. * @throws MissingLayoutException when a layout cannot be located
  962. */
  963. protected function _getLayoutFileName($name = null) {
  964. if ($name === null) {
  965. $name = $this->layout;
  966. }
  967. $subDir = null;
  968. if ($this->layoutPath !== null) {
  969. $subDir = $this->layoutPath . DS;
  970. }
  971. list($plugin, $name) = $this->pluginSplit($name);
  972. $paths = $this->_paths($plugin);
  973. $file = 'Layouts' . DS . $subDir . $name;
  974. $exts = $this->_getExtensions();
  975. foreach ($exts as $ext) {
  976. foreach ($paths as $path) {
  977. if (file_exists($path . $file . $ext)) {
  978. return $path . $file . $ext;
  979. }
  980. }
  981. }
  982. throw new MissingLayoutException(array('file' => $file . $this->ext));
  983. }
  984. /**
  985. * Get the extensions that view files can use.
  986. *
  987. * @return array Array of extensions view files use.
  988. */
  989. protected function _getExtensions() {
  990. $exts = array($this->ext);
  991. if ($this->ext !== '.ctp') {
  992. $exts[] = '.ctp';
  993. }
  994. return $exts;
  995. }
  996. /**
  997. * Finds an element filename, returns false on failure.
  998. *
  999. * @param string $name The name of the element to find.
  1000. * @return mixed Either a string to the element filename or false when one can't be found.
  1001. */
  1002. protected function _getElementFileName($name) {
  1003. list($plugin, $name) = $this->pluginSplit($name);
  1004. $paths = $this->_paths($plugin);
  1005. $exts = $this->_getExtensions();
  1006. foreach ($exts as $ext) {
  1007. foreach ($paths as $path) {
  1008. if (file_exists($path . 'Elements' . DS . $name . $ext)) {
  1009. return $path . 'Elements' . DS . $name . $ext;
  1010. }
  1011. }
  1012. }
  1013. return false;
  1014. }
  1015. /**
  1016. * Return all possible paths to find view files in order
  1017. *
  1018. * @param string $plugin Optional plugin name to scan for view files.
  1019. * @param bool $cached Set to false to force a refresh of view paths. Default true.
  1020. * @return array paths
  1021. */
  1022. protected function _paths($plugin = null, $cached = true) {
  1023. if ($cached === true) {
  1024. if ($plugin === null && !empty($this->_paths)) {
  1025. return $this->_paths;
  1026. }
  1027. if ($plugin !== null && isset($this->_pathsForPlugin[$plugin])) {
  1028. return $this->_pathsForPlugin[$plugin];
  1029. }
  1030. }
  1031. $paths = array();
  1032. $viewPaths = App::path('View');
  1033. $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
  1034. if (!empty($plugin)) {
  1035. $count = count($viewPaths);
  1036. for ($i = 0; $i < $count; $i++) {
  1037. if (!in_array($viewPaths[$i], $corePaths)) {
  1038. $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
  1039. }
  1040. }
  1041. $paths = array_merge($paths, App::path('View', $plugin));
  1042. }
  1043. $paths = array_unique(array_merge($paths, $viewPaths));
  1044. if (!empty($this->theme)) {
  1045. $theme = Inflector::camelize($this->theme);
  1046. $themePaths = array();
  1047. foreach ($paths as $path) {
  1048. if (strpos($path, DS . 'Plugin' . DS) === false) {
  1049. if ($plugin) {
  1050. $themePaths[] = $path . 'Themed' . DS . $theme . DS . 'Plugin' . DS . $plugin . DS;
  1051. }
  1052. $themePaths[] = $path . 'Themed' . DS . $theme . DS;
  1053. }
  1054. }
  1055. $paths = array_merge($themePaths, $paths);
  1056. }
  1057. $paths = array_merge($paths, $corePaths);
  1058. if ($plugin !== null) {
  1059. return $this->_pathsForPlugin[$plugin] = $paths;
  1060. }
  1061. return $this->_paths = $paths;
  1062. }
  1063. /**
  1064. * Checks if an element is cached and returns the cached data if present
  1065. *
  1066. * @param string $name Element name
  1067. * @param string $data Data
  1068. * @param array $options Element options
  1069. * @return string|null
  1070. */
  1071. protected function _elementCache($name, $data, $options) {
  1072. $plugin = null;
  1073. list($plugin, $name) = $this->pluginSplit($name);
  1074. $underscored = null;
  1075. if ($plugin) {
  1076. $underscored = Inflector::underscore($plugin);
  1077. }
  1078. $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
  1079. $this->elementCacheSettings = array(
  1080. 'config' => $this->elementCache,
  1081. 'key' => implode('_', $keys)
  1082. );
  1083. if (is_array($options['cache'])) {
  1084. $defaults = array(
  1085. 'config' => $this->elementCache,
  1086. 'key' => $this->elementCacheSettings['key']
  1087. );
  1088. $this->elementCacheSettings = array_merge($defaults, $options['cache']);
  1089. }
  1090. $this->elementCacheSettings['key'] = 'element_' . $this->elementCacheSettings['key'];
  1091. return Cache::read($this->elementCacheSettings['key'], $this->elementCacheSettings['config']);
  1092. }
  1093. /**
  1094. * Renders an element and fires the before and afterRender callbacks for it
  1095. * and writes to the cache if a cache is used
  1096. *
  1097. * @param string $file Element file path
  1098. * @param array $data Data to render
  1099. * @param array $options Element options
  1100. * @return string
  1101. * @triggers View.beforeRender $this, array($file)
  1102. * @triggers View.afterRender $this, array($file, $element)
  1103. */
  1104. protected function _renderElement($file, $data, $options) {
  1105. $current = $this->_current;
  1106. $restore = $this->_currentType;
  1107. $this->_currentType = static::TYPE_ELEMENT;
  1108. if ($options['callbacks']) {
  1109. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
  1110. }
  1111. $element = $this->_render($file, array_merge($this->viewVars, $data));
  1112. if ($options['callbacks']) {
  1113. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
  1114. }
  1115. $this->_currentType = $restore;
  1116. $this->_current = $current;
  1117. if (isset($options['cache'])) {
  1118. Cache::write($this->elementCacheSettings['key'], $element, $this->elementCacheSettings['config']);
  1119. }
  1120. return $element;
  1121. }
  1122. }