Helper.php 28 KB

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