Packages

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • FileTemplate
  • Template
  • TemplateHelpers

Interfaces

  • IFileTemplate
  • ITemplate

Exceptions

  • TemplateException
  • Overview
  • Package
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://nette.org)
  5:  *
  6:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  7:  *
  8:  * For the full copyright and license information, please view
  9:  * the file license.txt that was distributed with this source code.
 10:  * @package Nette\Templating
 11:  */
 12: 
 13: 
 14: 
 15: /**
 16:  * Template helpers.
 17:  *
 18:  * @author     David Grudl
 19:  * @package Nette\Templating
 20:  */
 21: final class TemplateHelpers
 22: {
 23:     private static $helpers = array(
 24:         'normalize' => 'Strings::normalize',
 25:         'toascii' => 'Strings::toAscii',
 26:         'webalize' => 'Strings::webalize',
 27:         'truncate' => 'Strings::truncate',
 28:         'lower' => 'Strings::lower',
 29:         'upper' => 'Strings::upper',
 30:         'firstupper' => 'Strings::firstUpper',
 31:         'capitalize' => 'Strings::capitalize',
 32:         'trim' => 'Strings::trim',
 33:         'padleft' => 'Strings::padLeft',
 34:         'padright' => 'Strings::padRight',
 35:         'reverse' =>  'Strings::reverse',
 36:         'replacere' => 'Strings::replace',
 37:         'url' => 'rawurlencode',
 38:         'striptags' => 'strip_tags',
 39:         'nl2br' => 'nl2br',
 40:         'substr' => 'Strings::substring',
 41:         'repeat' => 'str_repeat',
 42:         'implode' => 'implode',
 43:         'number' => 'number_format',
 44:     );
 45: 
 46:     /** @var string default date format */
 47:     public static $dateFormat = '%x';
 48: 
 49: 
 50: 
 51:     /**
 52:      * Try to load the requested helper.
 53:      * @param  string  helper name
 54:      * @return callable
 55:      */
 56:     public static function loader($helper)
 57:     {
 58:         if (method_exists(__CLASS__, $helper)) {
 59:             return new Callback(__CLASS__, $helper);
 60:         } elseif (isset(self::$helpers[$helper])) {
 61:             return self::$helpers[$helper];
 62:         }
 63:     }
 64: 
 65: 
 66: 
 67:     /**
 68:      * Escapes string for use inside HTML template.
 69:      * @param  mixed  UTF-8 encoding
 70:      * @param  int    optional attribute quotes
 71:      * @return string
 72:      */
 73:     public static function escapeHtml($s, $quotes = ENT_QUOTES)
 74:     {
 75:         if (is_object($s) && ($s instanceof ITemplate || $s instanceof Html || $s instanceof Form)) {
 76:             return $s->__toString(TRUE);
 77:         }
 78:         return htmlSpecialChars($s, $quotes);
 79:     }
 80: 
 81: 
 82: 
 83:     /**
 84:      * Escapes string for use inside HTML comments.
 85:      * @param  string  UTF-8 encoding
 86:      * @return string
 87:      */
 88:     public static function escapeHtmlComment($s)
 89:     {
 90:         // -- has special meaning in different browsers
 91:         return str_replace('--', '--><!-- ', $s); // HTML tags have no meaning inside comments
 92:     }
 93: 
 94: 
 95: 
 96:     /**
 97:      * Escapes string for use inside XML 1.0 template.
 98:      * @param  string UTF-8 encoding
 99:      * @return string
100:      */
101:     public static function escapeXML($s)
102:     {
103:         // XML 1.0: \x09 \x0A \x0D and C1 allowed directly, C0 forbidden
104:         // XML 1.1: \x00 forbidden directly and as a character reference,
105:         //   \x09 \x0A \x0D \x85 allowed directly, C0, C1 and \x7F allowed as character references
106:         return htmlSpecialChars(preg_replace('#[\x00-\x08\x0B\x0C\x0E-\x1F]+#', '', $s), ENT_QUOTES);
107:     }
108: 
109: 
110: 
111:     /**
112:      * Escapes string for use inside CSS template.
113:      * @param  string UTF-8 encoding
114:      * @return string
115:      */
116:     public static function escapeCss($s)
117:     {
118:         // http://www.w3.org/TR/2006/WD-CSS21-20060411/syndata.html#q6
119:         return addcslashes($s, "\x00..\x1F!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~");
120:     }
121: 
122: 
123: 
124:     /**
125:      * Escapes string for use inside JavaScript template.
126:      * @param  mixed  UTF-8 encoding
127:      * @return string
128:      */
129:     public static function escapeJs($s)
130:     {
131:         if (is_object($s) && ($s instanceof ITemplate || $s instanceof Html || $s instanceof Form)) {
132:             $s = $s->__toString(TRUE);
133:         }
134:         return str_replace(']]>', ']]\x3E', Json::encode($s));
135:     }
136: 
137: 
138: 
139:     /**
140:      * Escapes string for use inside iCal template.
141:      * @param  mixed  UTF-8 encoding
142:      * @return string
143:      */
144:     public static function escapeICal($s)
145:     {
146:         // http://www.ietf.org/rfc/rfc5545.txt
147:         return addcslashes(preg_replace('#[\x00-\x08\x0B\x0C-\x1F]+#', '', $s), "\";\\,:\n");
148:     }
149: 
150: 
151: 
152:     /**
153:      * Replaces all repeated white spaces with a single space.
154:      * @param  string UTF-8 encoding or 8-bit
155:      * @return string
156:      */
157:     public static function strip($s)
158:     {
159:         return Strings::replace(
160:             $s,
161:             '#(</textarea|</pre|</script|^).*?(?=<textarea|<pre|<script|\z)#si',
162:             new Callback(create_function('$m', '
163:                 return trim(preg_replace(\'#[ \\t\\r\\n]+#\', " ", $m[0]));
164:             ')));
165:     }
166: 
167: 
168: 
169:     /**
170:      * Indents the HTML content from the left.
171:      * @param  string UTF-8 encoding or 8-bit
172:      * @param  int
173:      * @param  string
174:      * @return string
175:      */
176:     public static function indent($s, $level = 1, $chars = "\t")
177:     {
178:         if ($level >= 1) {
179:             $s = Strings::replace($s, '#<(textarea|pre).*?</\\1#si', new Callback(create_function('$m', '
180:                 return strtr($m[0], " \\t\\r\\n", "\\x1F\\x1E\\x1D\\x1A");
181:             ')));
182:             $s = Strings::indent($s, $level, $chars);
183:             $s = strtr($s, "\x1F\x1E\x1D\x1A", " \t\r\n");
184:         }
185:         return $s;
186:     }
187: 
188: 
189: 
190:     /**
191:      * Date/time formatting.
192:      * @param  string|int|DateTime
193:      * @param  string
194:      * @return string
195:      */
196:     public static function date($time, $format = NULL)
197:     {
198:         if ($time == NULL) { // intentionally ==
199:             return NULL;
200:         }
201: 
202:         if (!isset($format)) {
203:             $format = self::$dateFormat;
204:         }
205: 
206:         $time = DateTime53::from($time);
207:         return Strings::contains($format, '%')
208:             ? strftime($format, $time->format('U')) // formats according to locales
209:             : $time->format($format); // formats using date()
210:     }
211: 
212: 
213: 
214:     /**
215:      * Converts to human readable file size.
216:      * @param  int
217:      * @param  int
218:      * @return string
219:      */
220:     public static function bytes($bytes, $precision = 2)
221:     {
222:         $bytes = round($bytes);
223:         $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
224:         foreach ($units as $unit) {
225:             if (abs($bytes) < 1024 || $unit === end($units)) {
226:                 break;
227:             }
228:             $bytes = $bytes / 1024;
229:         }
230:         return round($bytes, $precision) . ' ' . $unit;
231:     }
232: 
233: 
234: 
235:     /**
236:      * Returns array of string length.
237:      * @param  mixed
238:      * @return int
239:      */
240:     public static function length($var)
241:     {
242:         return is_string($var) ? Strings::length($var) : count($var);
243:     }
244: 
245: 
246: 
247:     /**
248:      * Performs a search and replace.
249:      * @param  string
250:      * @param  string
251:      * @param  string
252:      * @return string
253:      */
254:     public static function replace($subject, $search, $replacement = '')
255:     {
256:         return str_replace($search, $replacement, $subject);
257:     }
258: 
259: 
260: 
261:     /**
262:      * The data: URI generator.
263:      * @param  string
264:      * @param  string
265:      * @return string
266:      */
267:     public static function dataStream($data, $type = NULL)
268:     {
269:         if ($type === NULL) {
270:             $type = MimeTypeDetector::fromString($data);
271:         }
272:         return 'data:' . ($type ? "$type;" : '') . 'base64,' . base64_encode($data);
273:     }
274: 
275: 
276: 
277:     /**
278:      * /dev/null.
279:      * @param  mixed
280:      * @return string
281:      */
282:     public static function null($value)
283:     {
284:         return '';
285:     }
286: 
287: 
288: 
289:     /********************* Template tools ****************d*g**/
290: 
291: 
292: 
293:     /**
294:      * Removes unnecessary blocks of PHP code.
295:      * @param  string
296:      * @return string
297:      */
298:     public static function optimizePhp($source, $lineLength = 80, $existenceOfThisParameterSolvesDamnBugInPHP535 = NULL)
299:     {
300:         $res = $php = '';
301:         $lastChar = ';';
302:         $tokens = new ArrayIterator(token_get_all($source));
303:         foreach ($tokens as $key => $token) {
304:             if (is_array($token)) {
305:                 if ($token[0] === T_INLINE_HTML) {
306:                     $lastChar = '';
307:                     $res .= $token[1];
308: 
309:                 } elseif ($token[0] === T_CLOSE_TAG) {
310:                     $next = isset($tokens[$key + 1]) ? $tokens[$key + 1] : NULL;
311:                     if (substr($res, -1) !== '<' && preg_match('#^<\?php\s*\z#', $php)) {
312:                         $php = ''; // removes empty (?php ?), but retains ((?php ?)?php
313: 
314:                     } elseif (is_array($next) && $next[0] === T_OPEN_TAG) { // remove ?)(?php
315:                         if (!strspn($lastChar, ';{}:/')) {
316:                             $php .= $lastChar = ';';
317:                         }
318:                         if (substr($next[1], -1) === "\n") {
319:                             $php .= "\n";
320:                         }
321:                         $tokens->next();
322: 
323:                     } elseif ($next) {
324:                         $res .= preg_replace('#;?(\s)*\z#', '$1', $php) . $token[1]; // remove last semicolon before ?)
325:                         if (strlen($res) - strrpos($res, "\n") > $lineLength
326:                             && (!is_array($next) || strpos($next[1], "\n") === FALSE)
327:                         ) {
328:                             $res .= "\n";
329:                         }
330:                         $php = '';
331: 
332:                     } else { // remove last ?)
333:                         if (!strspn($lastChar, '};')) {
334:                             $php .= ';';
335:                         }
336:                     }
337: 
338:                 } elseif ($token[0] === T_ELSE || $token[0] === T_ELSEIF) {
339:                     if ($tokens[$key + 1] === ':' && $lastChar === '}') {
340:                         $php .= ';'; // semicolon needed in if(): ... if() ... else:
341:                     }
342:                     $lastChar = '';
343:                     $php .= $token[1];
344: 
345:                 } else {
346:                     if (!in_array($token[0], array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG))) {
347:                         $lastChar = '';
348:                     }
349:                     $php .= $token[1];
350:                 }
351:             } else {
352:                 $php .= $lastChar = $token;
353:             }
354:         }
355:         return $res . $php;
356:     }
357: 
358: }
359: 
Nette Framework 2.0.7 (for PHP 5.2, un-prefixed) API API documentation generated by ApiGen 2.8.0