Elgg  Version 1.11
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 
371  // return a URL friendly title to short circuit normal title formatting
372  $params = array('title' => $title);
373  $result = elgg_trigger_plugin_hook('format', 'friendly:title', $params, null);
374  if ($result) {
375  return $result;
376  }
377 
378  // titles are often stored HTML encoded
379  $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
380 
382 
383  return $title;
384 }
385 
397 function elgg_get_friendly_time($time, $current_time = null) {
398 
399  if (!$current_time) {
400  $current_time = time();
401  }
402 
403  // return a time string to short circuit normal time formatting
404  $params = array('time' => $time, 'current_time' => $current_time);
405  $result = elgg_trigger_plugin_hook('format', 'friendly:time', $params, null);
406  if ($result) {
407  return $result;
408  }
409 
410  $diff = abs((int)$current_time - (int)$time);
411 
412  $minute = 60;
413  $hour = $minute * 60;
414  $day = $hour * 24;
415 
416  if ($diff < $minute) {
417  return elgg_echo("friendlytime:justnow");
418  }
419 
420  if ($diff < $hour) {
421  $granularity = ':minutes';
422  $diff = round($diff / $minute);
423  } else if ($diff < $day) {
424  $granularity = ':hours';
425  $diff = round($diff / $hour);
426  } else {
427  $granularity = ':days';
428  $diff = round($diff / $day);
429  }
430 
431  if ($diff == 0) {
432  $diff = 1;
433  }
434 
435  $future = ((int)$current_time - (int)$time < 0) ? ':future' : '';
436  $singular = ($diff == 1) ? ':singular' : '';
437 
438  return elgg_echo("friendlytime{$future}{$granularity}{$singular}", array($diff));
439 }
440 
447 function elgg_get_friendly_upload_error($error_code) {
448  switch ($error_code) {
449  case UPLOAD_ERR_OK:
450  return '';
451 
452  case UPLOAD_ERR_INI_SIZE:
453  $key = 'ini_size';
454  break;
455 
456  case UPLOAD_ERR_FORM_SIZE:
457  $key = 'form_size';
458  break;
459 
460  case UPLOAD_ERR_PARTIAL:
461  $key = 'partial';
462  break;
463 
464  case UPLOAD_ERR_NO_FILE:
465  $key = 'no_file';
466  break;
467 
468  case UPLOAD_ERR_NO_TMP_DIR:
469  $key = 'no_tmp_dir';
470  break;
471 
472  case UPLOAD_ERR_CANT_WRITE:
473  $key = 'cant_write';
474  break;
475 
476  case UPLOAD_ERR_EXTENSION:
477  $key = 'extension';
478  break;
479 
480  default:
481  $key = 'unknown';
482  break;
483  }
484 
485  return elgg_echo("upload:error:$key");
486 }
487 
488 
499 function elgg_strip_tags($string, $allowable_tags = null) {
500  $params['original_string'] = $string;
501  $params['allowable_tags'] = $allowable_tags;
502 
503  $string = strip_tags($string, $allowable_tags);
504  $string = elgg_trigger_plugin_hook('format', 'strip_tags', $params, $string);
505 
506  return $string;
507 }
508 
537  $string = str_replace(
538  array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'),
539  array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'),
540  $string
541  );
542  $string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8');
543  $string = str_replace(
544  array('&amp;gt;', '&amp;lt;', '&amp;amp;', '&amp;quot;', '&amp;#039;'),
545  array('&gt;', '&lt;', '&amp;', '&quot;', '&#039;'),
546  $string
547  );
548  return $string;
549 }
550 
560  //encode <,>,&, quotes and characters above 127
561  if (function_exists('mb_convert_encoding')) {
562  $display_query = mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8');
563  } else {
564  // if no mbstring extension, we just strip characters
565  $display_query = preg_replace("/[^\x01-\x7F]/", "", $string);
566  }
567  return htmlspecialchars($display_query, ENT_QUOTES, 'UTF-8', false);
568 }
569 
582  global $CONFIG;
583  $value[] = "{$CONFIG->path}engine/tests/ElggCoreOutputAutoPTest.php";
584  return $value;
585 }
586 
593 function _elgg_output_init() {
594  elgg_register_plugin_hook_handler('unit_test', 'system', '_elgg_output_unit_test');
595 }
596 
597 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
598  $events->registerHandler('init', 'system', '_elgg_output_init');
599 };
$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:499
_elgg_get_display_query($string)
Prepares query string for output to prevent CSRF attacks.
Definition: output.php:559
$value
Definition: longtext.php:26
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Definition: elgglib.php:703
$url
Definition: exceptions.php:24
$title
Definition: save.php:24
_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:447
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
global $CONFIG
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:775
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Log a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1006
elgg global
Pointer to the global context.
Definition: elgglib.js:12
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:536
$type
Definition: add.php:8
elgg_format_attributes(array $attrs=array())
Converts an associative array into a string of well-formed attributes.
Definition: output.php:139
_elgg_output_unit_test($hook, $type, $value, $params)
Unit tests for Output.
Definition: output.php:581
$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:397
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:369
$attributes
Definition: ajax_loader.php:13
if(file_exists($welcome)) $vars
Definition: upgrade.php:93
_elgg_output_init()
Initialize the output subsystem.
Definition: output.php:593