PageRenderTime 1676ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/View/Helper.php

https://bitbucket.org/daveschwan/ronin-group
PHP | 951 lines | 471 code | 78 blank | 402 comment | 102 complexity | d1a6c3d508516cd01a5f23b914ad274a MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, MIT, BSD-3-Clause, Apache-2.0
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @package Cake.View
  13. * @since CakePHP(tm) v 0.2.9
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. App::uses('Router', 'Routing');
  17. App::uses('Hash', 'Utility');
  18. App::uses('Inflector', 'Utility');
  19. /**
  20. * Abstract base class for all other Helpers in CakePHP.
  21. * Provides common methods and features.
  22. *
  23. * @package Cake.View
  24. */
  25. class Helper extends Object {
  26. /**
  27. * Settings for this helper.
  28. *
  29. * @var array
  30. */
  31. public $settings = array();
  32. /**
  33. * List of helpers used by this helper
  34. *
  35. * @var array
  36. */
  37. public $helpers = array();
  38. /**
  39. * A helper lookup table used to lazy load helper objects.
  40. *
  41. * @var array
  42. */
  43. protected $_helperMap = array();
  44. /**
  45. * The current theme name if any.
  46. *
  47. * @var string
  48. */
  49. public $theme = null;
  50. /**
  51. * Request object
  52. *
  53. * @var CakeRequest
  54. */
  55. public $request = null;
  56. /**
  57. * Plugin path
  58. *
  59. * @var string
  60. */
  61. public $plugin = null;
  62. /**
  63. * Holds the fields array('field_name' => array('type' => 'string', 'length' => 100),
  64. * primaryKey and validates array('field_name')
  65. *
  66. * @var array
  67. */
  68. public $fieldset = array();
  69. /**
  70. * Holds tag templates.
  71. *
  72. * @var array
  73. */
  74. public $tags = array();
  75. /**
  76. * Holds the content to be cleaned.
  77. *
  78. * @var mixed
  79. */
  80. protected $_tainted = null;
  81. /**
  82. * Holds the cleaned content.
  83. *
  84. * @var mixed
  85. */
  86. protected $_cleaned = null;
  87. /**
  88. * The View instance this helper is attached to
  89. *
  90. * @var View
  91. */
  92. protected $_View;
  93. /**
  94. * A list of strings that should be treated as suffixes, or
  95. * sub inputs for a parent input. This is used for date/time
  96. * inputs primarily.
  97. *
  98. * @var array
  99. */
  100. protected $_fieldSuffixes = array(
  101. 'year', 'month', 'day', 'hour', 'min', 'second', 'meridian'
  102. );
  103. /**
  104. * The name of the current model entities are in scope of.
  105. *
  106. * @see Helper::setEntity()
  107. * @var string
  108. */
  109. protected $_modelScope;
  110. /**
  111. * The name of the current model association entities are in scope of.
  112. *
  113. * @see Helper::setEntity()
  114. * @var string
  115. */
  116. protected $_association;
  117. /**
  118. * The dot separated list of elements the current field entity is for.
  119. *
  120. * @see Helper::setEntity()
  121. * @var string
  122. */
  123. protected $_entityPath;
  124. /**
  125. * Minimized attributes
  126. *
  127. * @var array
  128. */
  129. protected $_minimizedAttributes = array(
  130. 'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected',
  131. 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize',
  132. 'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate'
  133. );
  134. /**
  135. * Format to attribute
  136. *
  137. * @var string
  138. */
  139. protected $_attributeFormat = '%s="%s"';
  140. /**
  141. * Format to attribute
  142. *
  143. * @var string
  144. */
  145. protected $_minimizedAttributeFormat = '%s="%s"';
  146. /**
  147. * Default Constructor
  148. *
  149. * @param View $View The View this helper is being attached to.
  150. * @param array $settings Configuration settings for the helper.
  151. */
  152. public function __construct(View $View, $settings = array()) {
  153. $this->_View = $View;
  154. $this->request = $View->request;
  155. if ($settings) {
  156. $this->settings = Hash::merge($this->settings, $settings);
  157. }
  158. if (!empty($this->helpers)) {
  159. $this->_helperMap = ObjectCollection::normalizeObjectArray($this->helpers);
  160. }
  161. }
  162. /**
  163. * Provide non fatal errors on missing method calls.
  164. *
  165. * @param string $method Method to invoke
  166. * @param array $params Array of params for the method.
  167. * @return void
  168. */
  169. public function __call($method, $params) {
  170. trigger_error(__d('cake_dev', 'Method %1$s::%2$s does not exist', get_class($this), $method), E_USER_WARNING);
  171. }
  172. /**
  173. * Lazy loads helpers. Provides access to deprecated request properties as well.
  174. *
  175. * @param string $name Name of the property being accessed.
  176. * @return mixed Helper or property found at $name
  177. * @deprecated Accessing request properties through this method is deprecated and will be removed in 3.0.
  178. */
  179. public function __get($name) {
  180. if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
  181. $settings = array_merge((array)$this->_helperMap[$name]['settings'], array('enabled' => false));
  182. $this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $settings);
  183. }
  184. if (isset($this->{$name})) {
  185. return $this->{$name};
  186. }
  187. switch ($name) {
  188. case 'base':
  189. case 'here':
  190. case 'webroot':
  191. case 'data':
  192. return $this->request->{$name};
  193. case 'action':
  194. return isset($this->request->params['action']) ? $this->request->params['action'] : '';
  195. case 'params':
  196. return $this->request;
  197. }
  198. }
  199. /**
  200. * Provides backwards compatibility access for setting values to the request object.
  201. *
  202. * @param string $name Name of the property being accessed.
  203. * @param mixed $value
  204. * @return void
  205. * @deprecated This method will be removed in 3.0
  206. */
  207. public function __set($name, $value) {
  208. switch ($name) {
  209. case 'base':
  210. case 'here':
  211. case 'webroot':
  212. case 'data':
  213. $this->request->{$name} = $value;
  214. return;
  215. case 'action':
  216. $this->request->params['action'] = $value;
  217. return;
  218. }
  219. $this->{$name} = $value;
  220. }
  221. /**
  222. * Finds URL for specified action.
  223. *
  224. * Returns a URL pointing at the provided parameters.
  225. *
  226. * @param string|array $url Either a relative string url like `/products/view/23` or
  227. * an array of URL parameters. Using an array for URLs will allow you to leverage
  228. * the reverse routing features of CakePHP.
  229. * @param boolean $full If true, the full base URL will be prepended to the result
  230. * @return string Full translated URL with base path.
  231. * @link http://book.cakephp.org/2.0/en/views/helpers.html
  232. */
  233. public function url($url = null, $full = false) {
  234. return h(Router::url($url, $full));
  235. }
  236. /**
  237. * Checks if a file exists when theme is used, if no file is found default location is returned
  238. *
  239. * @param string $file The file to create a webroot path to.
  240. * @return string Web accessible path to file.
  241. */
  242. public function webroot($file) {
  243. $asset = explode('?', $file);
  244. $asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
  245. $webPath = "{$this->request->webroot}" . $asset[0];
  246. $file = $asset[0];
  247. if (!empty($this->theme)) {
  248. $file = trim($file, '/');
  249. $theme = $this->theme . '/';
  250. if (DS === '\\') {
  251. $file = str_replace('/', '\\', $file);
  252. }
  253. if (file_exists(Configure::read('App.www_root') . 'theme' . DS . $this->theme . DS . $file)) {
  254. $webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
  255. } else {
  256. $themePath = App::themePath($this->theme);
  257. $path = $themePath . 'webroot' . DS . $file;
  258. if (file_exists($path)) {
  259. $webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
  260. }
  261. }
  262. }
  263. if (strpos($webPath, '//') !== false) {
  264. return str_replace('//', '/', $webPath . $asset[1]);
  265. }
  266. return $webPath . $asset[1];
  267. }
  268. /**
  269. * Generate URL for given asset file. Depending on options passed provides full URL with domain name.
  270. * Also calls Helper::assetTimestamp() to add timestamp to local files
  271. *
  272. * @param string|array Path string or URL array
  273. * @param array $options Options array. Possible keys:
  274. * `fullBase` Return full URL with domain name
  275. * `pathPrefix` Path prefix for relative URLs
  276. * `ext` Asset extension to append
  277. * `plugin` False value will prevent parsing path as a plugin
  278. * @return string Generated URL
  279. */
  280. public function assetUrl($path, $options = array()) {
  281. if (is_array($path)) {
  282. return $this->url($path, !empty($options['fullBase']));
  283. }
  284. if (strpos($path, '://') !== false) {
  285. return $path;
  286. }
  287. if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
  288. list($plugin, $path) = $this->_View->pluginSplit($path, false);
  289. }
  290. if (!empty($options['pathPrefix']) && $path[0] !== '/') {
  291. $path = $options['pathPrefix'] . $path;
  292. }
  293. if (
  294. !empty($options['ext']) &&
  295. strpos($path, '?') === false &&
  296. substr($path, -strlen($options['ext'])) !== $options['ext']
  297. ) {
  298. $path .= $options['ext'];
  299. }
  300. if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
  301. return $path;
  302. }
  303. if (isset($plugin)) {
  304. $path = Inflector::underscore($plugin) . '/' . $path;
  305. }
  306. $path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
  307. if (!empty($options['fullBase'])) {
  308. $path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
  309. }
  310. return $path;
  311. }
  312. /**
  313. * Encodes a URL for use in HTML attributes.
  314. *
  315. * @param string $url The URL to encode.
  316. * @return string The URL encoded for both URL & HTML contexts.
  317. */
  318. protected function _encodeUrl($url) {
  319. $path = parse_url($url, PHP_URL_PATH);
  320. $parts = array_map('rawurldecode', explode('/', $path));
  321. $parts = array_map('rawurlencode', $parts);
  322. $encoded = implode('/', $parts);
  323. return h(str_replace($path, $encoded, $url));
  324. }
  325. /**
  326. * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
  327. * Configure. If Asset.timestamp is true and debug > 0, or Asset.timestamp === 'force'
  328. * a timestamp will be added.
  329. *
  330. * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
  331. * @return string Path with a timestamp added, or not.
  332. */
  333. public function assetTimestamp($path) {
  334. $stamp = Configure::read('Asset.timestamp');
  335. $timestampEnabled = $stamp === 'force' || ($stamp === true && Configure::read('debug') > 0);
  336. if ($timestampEnabled && strpos($path, '?') === false) {
  337. $filepath = preg_replace(
  338. '/^' . preg_quote($this->request->webroot, '/') . '/',
  339. '',
  340. urldecode($path)
  341. );
  342. $webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
  343. if (file_exists($webrootPath)) {
  344. //@codingStandardsIgnoreStart
  345. return $path . '?' . @filemtime($webrootPath);
  346. //@codingStandardsIgnoreEnd
  347. }
  348. $segments = explode('/', ltrim($filepath, '/'));
  349. if ($segments[0] === 'theme') {
  350. $theme = $segments[1];
  351. unset($segments[0], $segments[1]);
  352. $themePath = App::themePath($theme) . 'webroot' . DS . implode(DS, $segments);
  353. //@codingStandardsIgnoreStart
  354. return $path . '?' . @filemtime($themePath);
  355. //@codingStandardsIgnoreEnd
  356. } else {
  357. $plugin = Inflector::camelize($segments[0]);
  358. if (CakePlugin::loaded($plugin)) {
  359. unset($segments[0]);
  360. $pluginPath = CakePlugin::path($plugin) . 'webroot' . DS . implode(DS, $segments);
  361. //@codingStandardsIgnoreStart
  362. return $path . '?' . @filemtime($pluginPath);
  363. //@codingStandardsIgnoreEnd
  364. }
  365. }
  366. }
  367. return $path;
  368. }
  369. /**
  370. * Used to remove harmful tags from content. Removes a number of well known XSS attacks
  371. * from content. However, is not guaranteed to remove all possibilities. Escaping
  372. * content is the best way to prevent all possible attacks.
  373. *
  374. * @param string|array $output Either an array of strings to clean or a single string to clean.
  375. * @return string|array cleaned content for output
  376. * @deprecated This method will be removed in 3.0
  377. */
  378. public function clean($output) {
  379. $this->_reset();
  380. if (empty($output)) {
  381. return null;
  382. }
  383. if (is_array($output)) {
  384. foreach ($output as $key => $value) {
  385. $return[$key] = $this->clean($value);
  386. }
  387. return $return;
  388. }
  389. $this->_tainted = $output;
  390. $this->_clean();
  391. return $this->_cleaned;
  392. }
  393. /**
  394. * Returns a space-delimited string with items of the $options array. If a key
  395. * of $options array happens to be one of those listed in `Helper::$_minimizedAttributes`
  396. *
  397. * And its value is one of:
  398. *
  399. * - '1' (string)
  400. * - 1 (integer)
  401. * - true (boolean)
  402. * - 'true' (string)
  403. *
  404. * Then the value will be reset to be identical with key's name.
  405. * If the value is not one of these 3, the parameter is not output.
  406. *
  407. * 'escape' is a special option in that it controls the conversion of
  408. * attributes to their html-entity encoded equivalents. Set to false to disable html-encoding.
  409. *
  410. * If value for any option key is set to `null` or `false`, that option will be excluded from output.
  411. *
  412. * @param array $options Array of options.
  413. * @param array $exclude Array of options to be excluded, the options here will not be part of the return.
  414. * @param string $insertBefore String to be inserted before options.
  415. * @param string $insertAfter String to be inserted after options.
  416. * @return string Composed attributes.
  417. * @deprecated This method will be moved to HtmlHelper in 3.0
  418. */
  419. protected function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
  420. if (!is_string($options)) {
  421. $options = (array)$options + array('escape' => true);
  422. if (!is_array($exclude)) {
  423. $exclude = array();
  424. }
  425. $exclude = array('escape' => true) + array_flip($exclude);
  426. $escape = $options['escape'];
  427. $attributes = array();
  428. foreach ($options as $key => $value) {
  429. if (!isset($exclude[$key]) && $value !== false && $value !== null) {
  430. $attributes[] = $this->_formatAttribute($key, $value, $escape);
  431. }
  432. }
  433. $out = implode(' ', $attributes);
  434. } else {
  435. $out = $options;
  436. }
  437. return $out ? $insertBefore . $out . $insertAfter : '';
  438. }
  439. /**
  440. * Formats an individual attribute, and returns the string value of the composed attribute.
  441. * Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
  442. *
  443. * @param string $key The name of the attribute to create
  444. * @param string $value The value of the attribute to create.
  445. * @param boolean $escape Define if the value must be escaped
  446. * @return string The composed attribute.
  447. * @deprecated This method will be moved to HtmlHelper in 3.0
  448. */
  449. protected function _formatAttribute($key, $value, $escape = true) {
  450. if (is_array($value)) {
  451. $value = implode(' ', $value);
  452. }
  453. if (is_numeric($key)) {
  454. return sprintf($this->_minimizedAttributeFormat, $value, $value);
  455. }
  456. $truthy = array(1, '1', true, 'true', $key);
  457. $isMinimized = in_array($key, $this->_minimizedAttributes);
  458. if ($isMinimized && in_array($value, $truthy, true)) {
  459. return sprintf($this->_minimizedAttributeFormat, $key, $key);
  460. }
  461. if ($isMinimized) {
  462. return '';
  463. }
  464. return sprintf($this->_attributeFormat, $key, ($escape ? h($value) : $value));
  465. }
  466. /**
  467. * Returns a string to be used as onclick handler for confirm dialogs.
  468. *
  469. * @param string $message Message to be displayed
  470. * @param string $okCode Code to be executed after user chose 'OK'
  471. * @param string $cancelCode Code to be executed after user chose 'Cancel'
  472. * @param array $options Array of options
  473. * @return string onclick JS code
  474. */
  475. protected function _confirm($message, $okCode, $cancelCode = '', $options = array()) {
  476. $message = json_encode($message);
  477. $confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
  478. if (isset($options['escape']) && $options['escape'] === false) {
  479. $confirm = h($confirm);
  480. }
  481. return $confirm;
  482. }
  483. /**
  484. * Sets this helper's model and field properties to the dot-separated value-pair in $entity.
  485. *
  486. * @param string $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
  487. * @param boolean $setScope Sets the view scope to the model specified in $tagValue
  488. * @return void
  489. */
  490. public function setEntity($entity, $setScope = false) {
  491. if ($entity === null) {
  492. $this->_modelScope = false;
  493. }
  494. if ($setScope === true) {
  495. $this->_modelScope = $entity;
  496. }
  497. $parts = array_values(Hash::filter(explode('.', $entity)));
  498. if (empty($parts)) {
  499. return;
  500. }
  501. $count = count($parts);
  502. $lastPart = isset($parts[$count - 1]) ? $parts[$count - 1] : null;
  503. // Either 'body' or 'date.month' type inputs.
  504. if (
  505. ($count === 1 && $this->_modelScope && !$setScope) ||
  506. (
  507. $count === 2 &&
  508. in_array($lastPart, $this->_fieldSuffixes) &&
  509. $this->_modelScope &&
  510. $parts[0] !== $this->_modelScope
  511. )
  512. ) {
  513. $entity = $this->_modelScope . '.' . $entity;
  514. }
  515. // 0.name, 0.created.month style inputs. Excludes inputs with the modelScope in them.
  516. if (
  517. $count >= 2 &&
  518. is_numeric($parts[0]) &&
  519. !is_numeric($parts[1]) &&
  520. $this->_modelScope &&
  521. strpos($entity, $this->_modelScope) === false
  522. ) {
  523. $entity = $this->_modelScope . '.' . $entity;
  524. }
  525. $this->_association = null;
  526. $isHabtm = (
  527. isset($this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type']) &&
  528. $this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type'] === 'multiple'
  529. );
  530. // habtm models are special
  531. if ($count === 1 && $isHabtm) {
  532. $this->_association = $parts[0];
  533. $entity = $parts[0] . '.' . $parts[0];
  534. } else {
  535. // check for associated model.
  536. $reversed = array_reverse($parts);
  537. foreach ($reversed as $i => $part) {
  538. if ($i > 0 && preg_match('/^[A-Z]/', $part)) {
  539. $this->_association = $part;
  540. break;
  541. }
  542. }
  543. }
  544. $this->_entityPath = $entity;
  545. }
  546. /**
  547. * Returns the entity reference of the current context as an array of identity parts
  548. *
  549. * @return array An array containing the identity elements of an entity
  550. */
  551. public function entity() {
  552. return explode('.', $this->_entityPath);
  553. }
  554. /**
  555. * Gets the currently-used model of the rendering context.
  556. *
  557. * @return string
  558. */
  559. public function model() {
  560. if ($this->_association) {
  561. return $this->_association;
  562. }
  563. return $this->_modelScope;
  564. }
  565. /**
  566. * Gets the currently-used model field of the rendering context.
  567. * Strips off field suffixes such as year, month, day, hour, min, meridian
  568. * when the current entity is longer than 2 elements.
  569. *
  570. * @return string
  571. */
  572. public function field() {
  573. $entity = $this->entity();
  574. $count = count($entity);
  575. $last = $entity[$count - 1];
  576. if ($count > 2 && in_array($last, $this->_fieldSuffixes)) {
  577. $last = isset($entity[$count - 2]) ? $entity[$count - 2] : null;
  578. }
  579. return $last;
  580. }
  581. /**
  582. * Generates a DOM ID for the selected element, if one is not set.
  583. * Uses the current View::entity() settings to generate a CamelCased id attribute.
  584. *
  585. * @param array|string $options Either an array of html attributes to add $id into, or a string
  586. * with a view entity path to get a domId for.
  587. * @param string $id The name of the 'id' attribute.
  588. * @return mixed If $options was an array, an array will be returned with $id set. If a string
  589. * was supplied, a string will be returned.
  590. */
  591. public function domId($options = null, $id = 'id') {
  592. if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
  593. unset($options[$id]);
  594. return $options;
  595. } elseif (!is_array($options) && $options !== null) {
  596. $this->setEntity($options);
  597. return $this->domId();
  598. }
  599. $entity = $this->entity();
  600. $model = array_shift($entity);
  601. $dom = $model . implode('', array_map(array('Inflector', 'camelize'), $entity));
  602. if (is_array($options) && !array_key_exists($id, $options)) {
  603. $options[$id] = $dom;
  604. } elseif ($options === null) {
  605. return $dom;
  606. }
  607. return $options;
  608. }
  609. /**
  610. * Gets the input field name for the current tag. Creates input name attributes
  611. * using CakePHP's data[Model][field] formatting.
  612. *
  613. * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
  614. * If a string or null, will be used as the View entity.
  615. * @param string $field
  616. * @param string $key The name of the attribute to be set, defaults to 'name'
  617. * @return mixed If an array was given for $options, an array with $key set will be returned.
  618. * If a string was supplied a string will be returned.
  619. */
  620. protected function _name($options = array(), $field = null, $key = 'name') {
  621. if ($options === null) {
  622. $options = array();
  623. } elseif (is_string($options)) {
  624. $field = $options;
  625. $options = 0;
  626. }
  627. if (!empty($field)) {
  628. $this->setEntity($field);
  629. }
  630. if (is_array($options) && array_key_exists($key, $options)) {
  631. return $options;
  632. }
  633. switch ($field) {
  634. case '_method':
  635. $name = $field;
  636. break;
  637. default:
  638. $name = 'data[' . implode('][', $this->entity()) . ']';
  639. }
  640. if (is_array($options)) {
  641. $options[$key] = $name;
  642. return $options;
  643. }
  644. return $name;
  645. }
  646. /**
  647. * Gets the data for the current tag
  648. *
  649. * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
  650. * If a string or null, will be used as the View entity.
  651. * @param string $field
  652. * @param string $key The name of the attribute to be set, defaults to 'value'
  653. * @return mixed If an array was given for $options, an array with $key set will be returned.
  654. * If a string was supplied a string will be returned.
  655. */
  656. public function value($options = array(), $field = null, $key = 'value') {
  657. if ($options === null) {
  658. $options = array();
  659. } elseif (is_string($options)) {
  660. $field = $options;
  661. $options = 0;
  662. }
  663. if (is_array($options) && isset($options[$key])) {
  664. return $options;
  665. }
  666. if (!empty($field)) {
  667. $this->setEntity($field);
  668. }
  669. $result = null;
  670. $data = $this->request->data;
  671. $entity = $this->entity();
  672. if (!empty($data) && is_array($data) && !empty($entity)) {
  673. $result = Hash::get($data, implode('.', $entity));
  674. }
  675. $habtmKey = $this->field();
  676. if (empty($result) && isset($data[$habtmKey][$habtmKey]) && is_array($data[$habtmKey])) {
  677. $result = $data[$habtmKey][$habtmKey];
  678. } elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) {
  679. if (ClassRegistry::isKeySet($habtmKey)) {
  680. $model = ClassRegistry::getObject($habtmKey);
  681. $result = $this->_selectedArray($data[$habtmKey], $model->primaryKey);
  682. }
  683. }
  684. if (is_array($options)) {
  685. if ($result === null && isset($options['default'])) {
  686. $result = $options['default'];
  687. }
  688. unset($options['default']);
  689. }
  690. if (is_array($options)) {
  691. $options[$key] = $result;
  692. return $options;
  693. }
  694. return $result;
  695. }
  696. /**
  697. * Sets the defaults for an input tag. Will set the
  698. * name, value, and id attributes for an array of html attributes.
  699. *
  700. * @param string $field The field name to initialize.
  701. * @param array $options Array of options to use while initializing an input field.
  702. * @return array Array options for the form input.
  703. */
  704. protected function _initInputField($field, $options = array()) {
  705. if ($field !== null) {
  706. $this->setEntity($field);
  707. }
  708. $options = (array)$options;
  709. $options = $this->_name($options);
  710. $options = $this->value($options);
  711. $options = $this->domId($options);
  712. return $options;
  713. }
  714. /**
  715. * Adds the given class to the element options
  716. *
  717. * @param array $options Array options/attributes to add a class to
  718. * @param string $class The class name being added.
  719. * @param string $key the key to use for class.
  720. * @return array Array of options with $key set.
  721. */
  722. public function addClass($options = array(), $class = null, $key = 'class') {
  723. if (isset($options[$key]) && trim($options[$key])) {
  724. $options[$key] .= ' ' . $class;
  725. } else {
  726. $options[$key] = $class;
  727. }
  728. return $options;
  729. }
  730. /**
  731. * Returns a string generated by a helper method
  732. *
  733. * This method can be overridden in subclasses to do generalized output post-processing
  734. *
  735. * @param string $str String to be output.
  736. * @return string
  737. * @deprecated This method will be removed in future versions.
  738. */
  739. public function output($str) {
  740. return $str;
  741. }
  742. /**
  743. * Before render callback. beforeRender is called before the view file is rendered.
  744. *
  745. * Overridden in subclasses.
  746. *
  747. * @param string $viewFile The view file that is going to be rendered
  748. * @return void
  749. */
  750. public function beforeRender($viewFile) {
  751. }
  752. /**
  753. * After render callback. afterRender is called after the view file is rendered
  754. * but before the layout has been rendered.
  755. *
  756. * Overridden in subclasses.
  757. *
  758. * @param string $viewFile The view file that was rendered.
  759. * @return void
  760. */
  761. public function afterRender($viewFile) {
  762. }
  763. /**
  764. * Before layout callback. beforeLayout is called before the layout is rendered.
  765. *
  766. * Overridden in subclasses.
  767. *
  768. * @param string $layoutFile The layout about to be rendered.
  769. * @return void
  770. */
  771. public function beforeLayout($layoutFile) {
  772. }
  773. /**
  774. * After layout callback. afterLayout is called after the layout has rendered.
  775. *
  776. * Overridden in subclasses.
  777. *
  778. * @param string $layoutFile The layout file that was rendered.
  779. * @return void
  780. */
  781. public function afterLayout($layoutFile) {
  782. }
  783. /**
  784. * Before render file callback.
  785. * Called before any view fragment is rendered.
  786. *
  787. * Overridden in subclasses.
  788. *
  789. * @param string $viewFile The file about to be rendered.
  790. * @return void
  791. */
  792. public function beforeRenderFile($viewFile) {
  793. }
  794. /**
  795. * After render file callback.
  796. * Called after any view fragment is rendered.
  797. *
  798. * Overridden in subclasses.
  799. *
  800. * @param string $viewFile The file just be rendered.
  801. * @param string $content The content that was rendered.
  802. * @return void
  803. */
  804. public function afterRenderFile($viewFile, $content) {
  805. }
  806. /**
  807. * Transforms a recordset from a hasAndBelongsToMany association to a list of selected
  808. * options for a multiple select element
  809. *
  810. * @param string|array $data
  811. * @param string $key
  812. * @return array
  813. */
  814. protected function _selectedArray($data, $key = 'id') {
  815. if (!is_array($data)) {
  816. $model = $data;
  817. if (!empty($this->request->data[$model][$model])) {
  818. return $this->request->data[$model][$model];
  819. }
  820. if (!empty($this->request->data[$model])) {
  821. $data = $this->request->data[$model];
  822. }
  823. }
  824. $array = array();
  825. if (!empty($data)) {
  826. foreach ($data as $row) {
  827. if (isset($row[$key])) {
  828. $array[$row[$key]] = $row[$key];
  829. }
  830. }
  831. }
  832. return empty($array) ? null : $array;
  833. }
  834. /**
  835. * Resets the vars used by Helper::clean() to null
  836. *
  837. * @return void
  838. */
  839. protected function _reset() {
  840. $this->_tainted = null;
  841. $this->_cleaned = null;
  842. }
  843. /**
  844. * Removes harmful content from output
  845. *
  846. * @return void
  847. */
  848. protected function _clean() {
  849. if (get_magic_quotes_gpc()) {
  850. $this->_cleaned = stripslashes($this->_tainted);
  851. } else {
  852. $this->_cleaned = $this->_tainted;
  853. }
  854. $this->_cleaned = str_replace(array("&amp;", "&lt;", "&gt;"), array("&amp;amp;", "&amp;lt;", "&amp;gt;"), $this->_cleaned);
  855. $this->_cleaned = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u', "$1;", $this->_cleaned);
  856. $this->_cleaned = preg_replace('#(&\#x*)([0-9A-F]+);*#iu', "$1$2;", $this->_cleaned);
  857. $this->_cleaned = html_entity_decode($this->_cleaned, ENT_COMPAT, "UTF-8");
  858. $this->_cleaned = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>#iUu', "$1>", $this->_cleaned);
  859. $this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*)[\\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2nojavascript...', $this->_cleaned);
  860. $this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2novbscript...', $this->_cleaned);
  861. $this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=*([\'\"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#iUu', '$1=$2nomozbinding...', $this->_cleaned);
  862. $this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*data[\x00-\x20]*:#Uu', '$1=$2nodata...', $this->_cleaned);
  863. $this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*expression[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
  864. $this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*behaviour[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
  865. $this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*>#iUu', "$1>", $this->_cleaned);
  866. $this->_cleaned = preg_replace('#</*\w+:\w[^>]*>#i', "", $this->_cleaned);
  867. do {
  868. $oldstring = $this->_cleaned;
  869. $this->_cleaned = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $this->_cleaned);
  870. } while ($oldstring !== $this->_cleaned);
  871. $this->_cleaned = str_replace(array("&amp;", "&lt;", "&gt;"), array("&amp;amp;", "&amp;lt;", "&amp;gt;"), $this->_cleaned);
  872. }
  873. }