Helper.php 27 KB

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