Helper.php 26 KB

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