Base for a static organization website

Helper.php 28KB

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