CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs