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

  • NFileTemplate
  • NTemplate
  • NTemplateHelpers

Interfaces

  • IFileTemplate
  • ITemplate

Exceptions

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