Helper.php 26 KB

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