Elgg  Version 2.2
 All Classes Namespaces Files Functions Variables Pages
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  $view = 'output/excerpt';
74  $vars = [
75  'text' => $text,
76  'num_chars' => $num_chars,
77  ];
78  $viewtype = elgg_view_exists($view) ? '' : 'default';
79 
80  return _elgg_view_under_viewtype($view, $vars, $viewtype);
81 }
82 
91 function elgg_format_url($url) {
92  return preg_replace('/&(?!amp;)/', '&amp;', $url);
93 }
94 
105 function elgg_format_bytes($size, $precision = 2) {
106  if (!$size || $size < 0) {
107  return false;
108  }
109 
110  $base = log($size) / log(1024);
111  $suffixes = array('B', 'kB', 'MB', 'GB', 'TB');
112 
113  return round(pow(1024, $base - floor($base)), $precision) . ' ' . $suffixes[floor($base)];
114 }
115 
139 function elgg_format_attributes(array $attrs = array()) {
140  if (!is_array($attrs) || empty($attrs)) {
141  return '';
142  }
143 
144  $attributes = [];
145 
146  foreach ($attrs as $attr => $val) {
147  if (0 !== strpos($attr, 'data-') && false !== strpos($attr, '_')) {
148  // this is probably a view $vars variable not meant for output
149  continue;
150  }
151 
152  $attr = strtolower($attr);
153 
154  if (!isset($val) || $val === false) {
155  continue;
156  }
157 
158  if ($val === true) {
159  $val = $attr; //e.g. checked => true ==> checked="checked"
160  }
161 
162  if (is_scalar($val)) {
163  $val = [$val];
164  }
165 
166  if (!is_array($val)) {
167  continue;
168  }
169 
170  // Check if array contains non-scalar values and bail if so
171  $filtered_val = array_filter($val, function($e) {
172  return is_scalar($e);
173  });
174 
175  if (count($val) != count($filtered_val)) {
176  continue;
177  }
178 
179  $val = implode(' ', $val);
180 
181  $val = htmlspecialchars($val, ENT_QUOTES, 'UTF-8', false);
182  $attributes[] = "$attr=\"$val\"";
183  }
184 
185  return implode(' ', $attributes);
186 }
187 
218 function elgg_format_element($tag_name, array $attributes = array(), $text = '', array $options = array()) {
219  if (is_array($tag_name)) {
220  $args = $tag_name;
221 
222  if ($attributes !== [] || $text !== '' || $options !== []) {
223  throw new \InvalidArgumentException('If $tag_name is an array, the other arguments must not be set');
224  }
225 
226  if (isset($args['#tag_name'])) {
227  $tag_name = $args['#tag_name'];
228  }
229  if (isset($args['#text'])) {
230  $text = $args['#text'];
231  }
232  if (isset($args['#options'])) {
233  $options = $args['#options'];
234  }
235 
236  unset($args['#tag_name'], $args['#text'], $args['#options']);
237  $attributes = $args;
238  }
239 
240  if (!is_string($tag_name) || $tag_name === '') {
241  throw new \InvalidArgumentException('$tag_name is required');
242  }
243 
244  if (isset($options['is_void'])) {
245  $is_void = $options['is_void'];
246  } else {
247  // from http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
248  $is_void = in_array(strtolower($tag_name), array(
249  'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem',
250  'meta', 'param', 'source', 'track', 'wbr'
251  ));
252  }
253 
254  if (!empty($options['encode_text'])) {
255  $double_encode = empty($options['double_encode']) ? false : true;
256  $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8', $double_encode);
257  }
258 
259  if ($attributes) {
261  if ($attrs !== '') {
262  $attrs = " $attrs";
263  }
264  } else {
265  $attrs = '';
266  }
267 
268  if ($is_void) {
269  return empty($options['is_xml']) ? "<{$tag_name}{$attrs}>" : "<{$tag_name}{$attrs} />";
270  } else {
271  return "<{$tag_name}{$attrs}>$text</$tag_name>";
272  }
273 }
274 
291  // see https://bugs.php.net/bug.php?id=51192
292  // from the bookmarks save action.
293  $php_5_2_13_and_below = version_compare(PHP_VERSION, '5.2.14', '<');
294  $php_5_3_0_to_5_3_2 = version_compare(PHP_VERSION, '5.3.0', '>=') &&
295  version_compare(PHP_VERSION, '5.3.3', '<');
296 
297  if ($php_5_2_13_and_below || $php_5_3_0_to_5_3_2) {
298  $tmp_address = str_replace("-", "", $url);
299  $validated = filter_var($tmp_address, FILTER_VALIDATE_URL);
300  } else {
301  $validated = filter_var($url, FILTER_VALIDATE_URL);
302  }
303 
304  // work around for handling absoluate IRIs (RFC 3987) - see #4190
305  if (!$validated && (strpos($url, 'http:') === 0) || (strpos($url, 'https:') === 0)) {
306  $validated = true;
307  }
308 
309  if ($validated) {
310  // all normal URLs including mailto:
311  return $url;
312 
313  } elseif (preg_match("#^(\#|\?|//)#i", $url)) {
314  // '//example.com' (Shortcut for protocol.)
315  // '?query=test', #target
316  return $url;
317 
318  } elseif (stripos($url, 'javascript:') === 0 || stripos($url, 'mailto:') === 0) {
319  // 'javascript:' and 'mailto:'
320  // Not covered in FILTER_VALIDATE_URL
321  return $url;
322 
323  } elseif (preg_match("#^[^/]*\.php(\?.*)?$#i", $url)) {
324  // 'install.php', 'install.php?step=step'
325  return elgg_get_site_url() . $url;
326 
327  } elseif (preg_match("#^[^/?]*\.#i", $url)) {
328  // 'example.com', 'example.com/subpage'
329  return "http://$url";
330 
331  } else {
332  // 'page/handler', 'mod/plugin/file.php'
333 
334  // trim off any leading / because the site URL is stored
335  // with a trailing /
336  return elgg_get_site_url() . ltrim($url, '/');
337  }
338 }
339 
349 
350  // return a URL friendly title to short circuit normal title formatting
351  $params = array('title' => $title);
352  $result = elgg_trigger_plugin_hook('format', 'friendly:title', $params, null);
353  if ($result) {
354  return $result;
355  }
356 
357  // titles are often stored HTML encoded
358  $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
359 
361 
362  return $title;
363 }
364 
376 function elgg_get_friendly_time($time, $current_time = null) {
377 
378  if (!$current_time) {
379  $current_time = time();
380  }
381 
382  // return a time string to short circuit normal time formatting
383  $params = array('time' => $time, 'current_time' => $current_time);
384  $result = elgg_trigger_plugin_hook('format', 'friendly:time', $params, null);
385  if ($result) {
386  return $result;
387  }
388 
389  $diff = abs((int)$current_time - (int)$time);
390 
391  $minute = 60;
392  $hour = $minute * 60;
393  $day = $hour * 24;
394 
395  if ($diff < $minute) {
396  return elgg_echo("friendlytime:justnow");
397  }
398 
399  if ($diff < $hour) {
400  $granularity = ':minutes';
401  $diff = round($diff / $minute);
402  } else if ($diff < $day) {
403  $granularity = ':hours';
404  $diff = round($diff / $hour);
405  } else {
406  $granularity = ':days';
407  $diff = round($diff / $day);
408  }
409 
410  if ($diff == 0) {
411  $diff = 1;
412  }
413 
414  $future = ((int)$current_time - (int)$time < 0) ? ':future' : '';
415  $singular = ($diff == 1) ? ':singular' : '';
416 
417  return elgg_echo("friendlytime{$future}{$granularity}{$singular}", array($diff));
418 }
419 
426 function elgg_get_friendly_upload_error($error_code) {
427  switch ($error_code) {
428  case UPLOAD_ERR_OK:
429  return '';
430 
431  case UPLOAD_ERR_INI_SIZE:
432  $key = 'ini_size';
433  break;
434 
435  case UPLOAD_ERR_FORM_SIZE:
436  $key = 'form_size';
437  break;
438 
439  case UPLOAD_ERR_PARTIAL:
440  $key = 'partial';
441  break;
442 
443  case UPLOAD_ERR_NO_FILE:
444  $key = 'no_file';
445  break;
446 
447  case UPLOAD_ERR_NO_TMP_DIR:
448  $key = 'no_tmp_dir';
449  break;
450 
451  case UPLOAD_ERR_CANT_WRITE:
452  $key = 'cant_write';
453  break;
454 
455  case UPLOAD_ERR_EXTENSION:
456  $key = 'extension';
457  break;
458 
459  default:
460  $key = 'unknown';
461  break;
462  }
463 
464  return elgg_echo("upload:error:$key");
465 }
466 
467 
478 function elgg_strip_tags($string, $allowable_tags = null) {
479  $params['original_string'] = $string;
480  $params['allowable_tags'] = $allowable_tags;
481 
482  $string = strip_tags($string, $allowable_tags);
483  $string = elgg_trigger_plugin_hook('format', 'strip_tags', $params, $string);
484 
485  return $string;
486 }
487 
516  $string = str_replace(
517  array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'),
518  array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'),
519  $string
520  );
521  $string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8');
522  $string = str_replace(
523  array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'),
524  array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'),
525  $string
526  );
527  return $string;
528 }
529 
542  elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use elgg_html_decode()', '2.0');
543  return elgg_html_decode($string);
544 }
545 
555  //encode <,>,&, quotes and characters above 127
556  if (function_exists('mb_convert_encoding')) {
557  $display_query = mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8');
558  } else {
559  // if no mbstring extension, we just strip characters
560  $display_query = preg_replace("/[^\x01-\x7F]/", "", $string);
561  }
562  return htmlspecialchars($display_query, ENT_QUOTES, 'UTF-8', false);
563 }
564 
565 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
566 
567 };
elgg_view_exists($view, $viewtype= '', $recurse=true)
Returns whether the specified view exists.
Definition: views.php:299
$view
Definition: crop.php:34
$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:290
elgg_html_decode($string)
Decode HTML markup into a raw text string.
Definition: output.php:515
elgg_echo($message_key, $args=array(), $language="")
Given a message key, returns an appropriately translated full-text string.
Definition: languages.php:21
$e
Definition: metadata.php:12
elgg_strip_tags($string, $allowable_tags=null)
Strip tags and offer plugins the chance.
Definition: output.php:478
_elgg_get_display_query($string)
Prepares query string for output to prevent CSRF attacks.
Definition: output.php:554
$args
Some servers don't allow PHP to check the rewrite, so try via AJAX.
$num_chars
Definition: excerpt.php:16
$url
Definition: exceptions.php:24
$vars['entity']
$title
Definition: save.php:22
elgg_get_friendly_upload_error($error_code)
Returns a human-readable message for PHP's upload error codes.
Definition: output.php:426
$options
Elgg admin footer.
Definition: footer.php:6
elgg_format_element($tag_name, array $attributes=array(), $text= '', array $options=array())
Format an HTML element.
Definition: output.php:218
$string
$params
Definition: login.php:72
$text
Definition: default.php:25
elgg_autop($string)
Create paragraphs from text with line spacing.
Definition: output.php:56
$key
Definition: summary.php:34
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:801
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Log a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1070
elgg_format_bytes($size, $precision=2)
Format bytes to a human readable format.
Definition: output.php:105
elgg_get_site_url($site_guid=0)
Get the URL for the current (or specified) site.
_elgg_html_decode($string)
Alias of elgg_html_decode.
Definition: output.php:541
elgg_format_attributes(array $attrs=array())
Converts an associative array into a string of well-formed HTML/XML attributes Returns a concatenated...
Definition: output.php:139
_elgg_services(\Elgg\Di\ServiceProvider $services=null)
Get the global service provider.
Definition: autoloader.php:17
$attrs
Definition: ajax_loader.php:30
$size
Definition: default.php:20
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:376
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:91
elgg_get_friendly_title($title)
When given a title, returns a version suitable for inclusion in a URL.
Definition: output.php:348
_elgg_view_under_viewtype($view, $vars, $viewtype)
Render a view while the global viewtype is temporarily changed.
Definition: views.php:1928
$attributes
Definition: ajax_loader.php:13
if(!$limit) $attr
Definition: comments.php:22