Helper.php 27 KB

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