Elgg  Version 1.12
output.php
Go to the documentation of this file.
1 <?php
17 function parse_urls($text) {
18 
19  // URI specification: http://www.ietf.org/rfc/rfc3986.txt
20  // This varies from the specification in the following ways:
21  // * Supports non-ascii characters
22  // * Does not allow parentheses and single quotes
23  // * Cuts off commas, exclamation points, and periods off as last character
24 
25  // @todo this causes problems with <attr = "val">
26  // must be in <attr="val"> format (no space).
27  // By default htmlawed rewrites tags to this format.
28  // if PHP supported conditional negative lookbehinds we could use this:
29  // $r = preg_replace_callback('/(?<!=)(?<![ ])?(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i',
30  $r = preg_replace_callback('/(?<![=\/"\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\']+)/i',
31  create_function(
32  '$matches',
33  '
34  $url = $matches[1];
35  $punc = "";
36  $last = substr($url, -1, 1);
37  if (in_array($last, array(".", "!", ",", "(", ")"))) {
38  $punc = $last;
39  $url = rtrim($url, ".!,()");
40  }
41  $urltext = str_replace("/", "/<wbr />", $url);
42  return "<a href=\"$url\" rel=\"nofollow\">$urltext</a>$punc";
43  '
44  ), $text);
45 
46  return $r;
47 }
48 
56 function elgg_autop($string) {
57  return _elgg_services()->autoP->process($string);
58 }
59 
72 function elgg_get_excerpt($text, $num_chars = 250) {
73  $text = trim(elgg_strip_tags($text));
74  $string_length = elgg_strlen($text);
75 
76  if ($string_length <= $num_chars) {
77  return $text;
78  }
79 
80  // handle cases
81  $excerpt = elgg_substr($text, 0, $num_chars);
82  $space = elgg_strrpos($excerpt, ' ', 0);
83 
84  // don't crop if can't find a space.
85  if ($space === false) {
86  $space = $num_chars;
87  }
88  $excerpt = trim(elgg_substr($excerpt, 0, $space));
89 
90  if ($string_length != elgg_strlen($excerpt)) {
91  $excerpt .= '...';
92  }
93 
94  return $excerpt;
95 }
96 
106  return preg_replace('/&(?!amp;)/', '&amp;', $url);
107 }
108 
119 function elgg_format_bytes($size, $precision = 2) {
120  if (!$size || $size < 0) {
121  return false;
122  }
123 
124  $base = log($size) / log(1024);
125  $suffixes = array('B', 'kB', 'MB', 'GB', 'TB');
126 
127  return round(pow(1024, $base - floor($base)), $precision) . ' ' . $suffixes[floor($base)];
128 }
129 
139 function elgg_format_attributes(array $attrs = array()) {
140  if (!is_array($attrs) || !count($attrs)) {
141  return '';
142  }
143 
145  $attributes = array();
146 
147  if (isset($attrs['js'])) {
148  elgg_deprecated_notice('Use associative array of attr => val pairs instead of $vars[\'js\']', 1.8);
149 
150  if (!empty($attrs['js'])) {
151  $attributes[] = $attrs['js'];
152  }
153 
154  unset($attrs['js']);
155  }
156 
157  foreach ($attrs as $attr => $val) {
158  $attr = strtolower($attr);
159 
160  if ($val === true) {
161  $val = $attr; //e.g. checked => true ==> checked="checked"
162  }
163 
175  if ($val !== NULL && $val !== false && (is_array($val) || !is_object($val))) {
176  if (is_array($val)) {
177  $val = implode(' ', $val);
178  }
179 
180  $val = htmlspecialchars($val, ENT_QUOTES, 'UTF-8', false);
181  $attributes[] = "$attr=\"$val\"";
182  }
183  }
184 
185  return implode(' ', $attributes);
186 }
187 
215 function elgg_format_element($tag_name, array $attributes = array(), $text = '', array $options = array()) {
216  if (!is_string($tag_name)) {
217  throw new \InvalidArgumentException('$tag_name is required');
218  }
219 
220  if (isset($options['is_void'])) {
221  $is_void = $options['is_void'];
222  } else {
223  // from http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
224  $is_void = in_array(strtolower($tag_name), array(
225  'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem',
226  'meta', 'param', 'source', 'track', 'wbr'
227  ));
228  }
229 
230  if (!empty($options['encode_text'])) {
231  $double_encode = empty($options['double_encode']) ? false : true;
232  $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8', $double_encode);
233  }
234 
235  if ($attributes) {
237  if ($attrs !== '') {
238  $attrs = " $attrs";
239  }
240  } else {
241  $attrs = '';
242  }
243 
244  if ($is_void) {
245  return empty($options['is_xml']) ? "<{$tag_name}{$attrs}>" : "<{$tag_name}{$attrs} />";
246  } else {
247  return "<{$tag_name}{$attrs}>$text</$tag_name>";
248  }
249 }
250 
265 function _elgg_clean_vars(array $vars = array()) {
266  unset($vars['config']);
267  unset($vars['url']);
268  unset($vars['user']);
269 
270  // backwards compatibility code
271  if (isset($vars['internalname'])) {
272  if (!isset($vars['__ignoreInternalname'])) {
273  $vars['name'] = $vars['internalname'];
274  }
275  unset($vars['internalname']);
276  }
277 
278  if (isset($vars['internalid'])) {
279  if (!isset($vars['__ignoreInternalid'])) {
280  $vars['id'] = $vars['internalid'];
281  }
282  unset($vars['internalid']);
283  }
284 
285  if (isset($vars['__ignoreInternalid'])) {
286  unset($vars['__ignoreInternalid']);
287  }
288 
289  if (isset($vars['__ignoreInternalname'])) {
290  unset($vars['__ignoreInternalname']);
291  }
292 
293  return $vars;
294 }
295 
312  // see https://bugs.php.net/bug.php?id=51192
313  // from the bookmarks save action.
314  $php_5_2_13_and_below = version_compare(PHP_VERSION, '5.2.14', '<');
315  $php_5_3_0_to_5_3_2 = version_compare(PHP_VERSION, '5.3.0', '>=') &&
316  version_compare(PHP_VERSION, '5.3.3', '<');
317 
318  if ($php_5_2_13_and_below || $php_5_3_0_to_5_3_2) {
319  $tmp_address = str_replace("-", "", $url);
320  $validated = filter_var($tmp_address, FILTER_VALIDATE_URL);
321  } else {
322  $validated = filter_var($url, FILTER_VALIDATE_URL);
323  }
324 
325  // work around for handling absoluate IRIs (RFC 3987) - see #4190
326  if (!$validated && (strpos($url, 'http:') === 0) || (strpos($url, 'https:') === 0)) {
327  $validated = true;
328  }
329 
330  if ($validated) {
331  // all normal URLs including mailto:
332  return $url;
333 
334  } elseif (preg_match("#^(\#|\?|//)#i", $url)) {
335  // '//example.com' (Shortcut for protocol.)
336  // '?query=test', #target
337  return $url;
338 
339  } elseif (stripos($url, 'javascript:') === 0 || stripos($url, 'mailto:') === 0) {
340  // 'javascript:' and 'mailto:'
341  // Not covered in FILTER_VALIDATE_URL
342  return $url;
343 
344  } elseif (preg_match("#^[^/]*\.php(\?.*)?$#i", $url)) {
345  // 'install.php', 'install.php?step=step'
346  return elgg_get_site_url() . $url;
347 
348  } elseif (preg_match("#^[^/?]*\.#i", $url)) {
349  // 'example.com', 'example.com/subpage'
350  return "http://$url";
351 
352  } else {
353  // 'page/handler', 'mod/plugin/file.php'
354 
355  // trim off any leading / because the site URL is stored
356  // with a trailing /
357  return elgg_get_site_url() . ltrim($url, '/');
358  }
359 }
360 
370 function elgg_normalize_site_url($unsafe_url) {
371  if (!is_string($unsafe_url)) {
372  return false;
373  }
374 
375  $unsafe_url = elgg_normalize_url($unsafe_url);
376  if (0 === strpos($unsafe_url, elgg_get_site_url())) {
377  return $unsafe_url;
378  }
379 
380  return false;
381 }
382 
392 
393  // return a URL friendly title to short circuit normal title formatting
394  $params = array('title' => $title);
395  $result = elgg_trigger_plugin_hook('format', 'friendly:title', $params, null);
396  if ($result) {
397  return $result;
398  }
399 
400  // titles are often stored HTML encoded
401  $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
402 
404 
405  return $title;
406 }
407 
419 function elgg_get_friendly_time($time, $current_time = null) {
420 
421  if (!$current_time) {
422  $current_time = time();
423  }
424 
425  // return a time string to short circuit normal time formatting
426  $params = array('time' => $time, 'current_time' => $current_time);
427  $result = elgg_trigger_plugin_hook('format', 'friendly:time', $params, null);
428  if ($result) {
429  return $result;
430  }
431 
432  $diff = abs((int)$current_time - (int)$time);
433 
434  $minute = 60;
435  $hour = $minute * 60;
436  $day = $hour * 24;
437 
438  if ($diff < $minute) {
439  return elgg_echo("friendlytime:justnow");
440  }
441 
442  if ($diff < $hour) {
443  $granularity = ':minutes';
444  $diff = round($diff / $minute);
445  } else if ($diff < $day) {
446  $granularity = ':hours';
447  $diff = round($diff / $hour);
448  } else {
449  $granularity = ':days';
450  $diff = round($diff / $day);
451  }
452 
453  if ($diff == 0) {
454  $diff = 1;
455  }
456 
457  $future = ((int)$current_time - (int)$time < 0) ? ':future' : '';
458  $singular = ($diff == 1) ? ':singular' : '';
459 
460  return elgg_echo("friendlytime{$future}{$granularity}{$singular}", array($diff));
461 }
462 
469 function elgg_get_friendly_upload_error($error_code) {
470  switch ($error_code) {
471  case UPLOAD_ERR_OK:
472  return '';
473 
474  case UPLOAD_ERR_INI_SIZE:
475  $key = 'ini_size';
476  break;
477 
478  case UPLOAD_ERR_FORM_SIZE:
479  $key = 'form_size';
480  break;
481 
482  case UPLOAD_ERR_PARTIAL:
483  $key = 'partial';
484  break;
485 
486  case UPLOAD_ERR_NO_FILE:
487  $key = 'no_file';
488  break;
489 
490  case UPLOAD_ERR_NO_TMP_DIR:
491  $key = 'no_tmp_dir';
492  break;
493 
494  case UPLOAD_ERR_CANT_WRITE:
495  $key = 'cant_write';
496  break;
497 
498  case UPLOAD_ERR_EXTENSION:
499  $key = 'extension';
500  break;
501 
502  default:
503  $key = 'unknown';
504  break;
505  }
506 
507  return elgg_echo("upload:error:$key");
508 }
509 
510 
521 function elgg_strip_tags($string, $allowable_tags = null) {
522  $params['original_string'] = $string;
523  $params['allowable_tags'] = $allowable_tags;
524 
525  $string = strip_tags($string, $allowable_tags);
526  $string = elgg_trigger_plugin_hook('format', 'strip_tags', $params, $string);
527 
528  return $string;
529 }
530 
559  $string = str_replace(
560  array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'),
561  array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'),
562  $string
563  );
564  $string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8');
565  $string = str_replace(
566  array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'),
567  array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'),
568  $string
569  );
570  return $string;
571 }
572 
582  //encode <,>,&, quotes and characters above 127
583  if (function_exists('mb_convert_encoding')) {
584  $display_query = mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8');
585  } else {
586  // if no mbstring extension, we just strip characters
587  $display_query = preg_replace("/[^\x01-\x7F]/", "", $string);
588  }
589  return htmlspecialchars($display_query, ENT_QUOTES, 'UTF-8', false);
590 }
591 
592 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
593 
594 };
$r
parse_urls($text)
Takes a string and turns any URLs into formatted links.
Definition: output.php:17
elgg_normalize_url($url)
Definition: output.php:311
$size
Definition: view.php:10
elgg_strip_tags($string, $allowable_tags=null)
Strip tags and offer plugins the chance.
Definition: output.php:521
elgg_normalize_site_url($unsafe_url)
From untrusted input, get a site URL safe for forwarding.
Definition: output.php:370
_elgg_get_display_query($string)
Prepares query string for output to prevent CSRF attacks.
Definition: output.php:581
$url
Definition: exceptions.php:24
$title
Definition: save.php:22
_elgg_clean_vars(array $vars=array())
Preps an associative array for use in elgg_format_attributes().
Definition: output.php:265
elgg_get_friendly_upload_error($error_code)
Returns a human-readable message for PHP&#39;s upload error codes.
Definition: output.php:469
elgg_format_element($tag_name, array $attributes=array(), $text= '', array $options=array())
Format an HTML element.
Definition: output.php:215
$string
elgg_strlen()
Wrapper function for mb_strlen().
Definition: mb_wrapper.php:72
elgg_strrpos()
Wrapper function for mb_strrpos().
Definition: mb_wrapper.php:140
$params
Definition: login.php:72
$options
Definition: index.php:14
$text
Definition: default.php:25
elgg_echo($message_key, $args=array(), $language="")
Given a message key, returns an appropriately translated full-text string.
Definition: languages.php:21
elgg_autop($string)
Create paragraphs from text with line spacing.
Definition: output.php:56
$key
Definition: summary.php:34
_elgg_services()
Definition: autoloader.php:14
static urlize($string, $separator= '-')
Create a version of a string for embedding in a URL.
Definition: Translit.php:40
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Definition: elgglib.php:790
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Log a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1031
elgg_format_bytes($size, $precision=2)
Format bytes to a human readable format.
Definition: output.php:119
elgg_get_site_url($site_guid=0)
Get the URL for the current (or specified) site.
_elgg_html_decode($string)
Apply html_entity_decode() to a string while re-entitising HTML special char entities to prevent them...
Definition: output.php:558
elgg_format_attributes(array $attrs=array())
Converts an associative array into a string of well-formed attributes.
Definition: output.php:139
$attrs
Definition: ajax_loader.php:30
elgg_substr()
Wrapper function for mb_substr().
Definition: mb_wrapper.php:225
elgg_get_friendly_time($time, $current_time=null)
Formats a UNIX timestamp in a friendly way (eg "less than a minute ago")
Definition: output.php:419
elgg_get_excerpt($text, $num_chars=250)
Returns an excerpt.
Definition: output.php:72
elgg_format_url($url)
Handles formatting of ampersands in urls.
Definition: output.php:105
elgg_get_friendly_title($title)
When given a title, returns a version suitable for inclusion in a URL.
Definition: output.php:391
$attributes
Definition: ajax_loader.php:13
if(!$limit) $attr
Definition: comments.php:22
if(file_exists($welcome)) $vars
Definition: upgrade.php:93