PageRenderTime 71ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/View/View.php

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