Elgg  Version 1.9
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 
118 function elgg_format_attributes(array $attrs = array()) {
119  if (!is_array($attrs) || !count($attrs)) {
120  return '';
121  }
122 
124  $attributes = array();
125 
126  if (isset($attrs['js'])) {
127  elgg_deprecated_notice('Use associative array of attr => val pairs instead of $vars[\'js\']', 1.8);
128 
129  if (!empty($attrs['js'])) {
130  $attributes[] = $attrs['js'];
131  }
132 
133  unset($attrs['js']);
134  }
135 
136  foreach ($attrs as $attr => $val) {
137  $attr = strtolower($attr);
138 
139  if ($val === true) {
140  $val = $attr; //e.g. checked => true ==> checked="checked"
141  }
142 
154  if ($val !== NULL && $val !== false && (is_array($val) || !is_object($val))) {
155  if (is_array($val)) {
156  $val = implode(' ', $val);
157  }
158 
159  $val = htmlspecialchars($val, ENT_QUOTES, 'UTF-8', false);
160  $attributes[] = "$attr=\"$val\"";
161  }
162  }
163 
164  return implode(' ', $attributes);
165 }
166 
194 function elgg_format_element($tag_name, array $attributes = array(), $text = '', array $options = array()) {
195  if (!is_string($tag_name)) {
196  throw new InvalidArgumentException('$tag_name is required');
197  }
198 
199  if (isset($options['is_void'])) {
200  $is_void = $options['is_void'];
201  } else {
202  // from http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
203  $is_void = in_array(strtolower($tag_name), array(
204  'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem',
205  'meta', 'param', 'source', 'track', 'wbr'
206  ));
207  }
208 
209  if (!empty($options['encode_text'])) {
210  $double_encode = empty($options['double_encode']) ? false : true;
211  $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8', $double_encode);
212  }
213 
214  if ($attributes) {
216  if ($attrs !== '') {
217  $attrs = " $attrs";
218  }
219  } else {
220  $attrs = '';
221  }
222 
223  if ($is_void) {
224  return empty($options['is_xml']) ? "<{$tag_name}{$attrs}>" : "<{$tag_name}{$attrs} />";
225  } else {
226  return "<{$tag_name}{$attrs}>$text</$tag_name>";
227  }
228 }
229 
244 function _elgg_clean_vars(array $vars = array()) {
245  unset($vars['config']);
246  unset($vars['url']);
247  unset($vars['user']);
248 
249  // backwards compatibility code
250  if (isset($vars['internalname'])) {
251  if (!isset($vars['__ignoreInternalname'])) {
252  $vars['name'] = $vars['internalname'];
253  }
254  unset($vars['internalname']);
255  }
256 
257  if (isset($vars['internalid'])) {
258  if (!isset($vars['__ignoreInternalid'])) {
259  $vars['id'] = $vars['internalid'];
260  }
261  unset($vars['internalid']);
262  }
263 
264  if (isset($vars['__ignoreInternalid'])) {
265  unset($vars['__ignoreInternalid']);
266  }
267 
268  if (isset($vars['__ignoreInternalname'])) {
269  unset($vars['__ignoreInternalname']);
270  }
271 
272  return $vars;
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 
539  //encode <,>,&, quotes and characters above 127
540  if (function_exists('mb_convert_encoding')) {
541  $display_query = mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8');
542  } else {
543  // if no mbstring extension, we just strip characters
544  $display_query = preg_replace("/[^\x01-\x7F]/", "", $string);
545  }
546  return htmlspecialchars($display_query, ENT_QUOTES, 'UTF-8', false);
547 }
548 
561  global $CONFIG;
562  $value[] = "{$CONFIG->path}engine/tests/ElggCoreOutputAutoPTest.php";
563  return $value;
564 }
565 
572 function _elgg_output_init() {
573  elgg_register_plugin_hook_handler('unit_test', 'system', '_elgg_output_unit_test');
574 }
575 
576 elgg_register_event_handler('init', 'system', '_elgg_output_init');
$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_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:538
$value
Definition: longtext.php:29
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Register a callback as a plugin hook handler.
Definition: elgglib.php:853
$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:244
elgg_get_friendly_upload_error($error_code)
Returns a human-readable message for PHP&#39;s upload error codes.
Definition: output.php:426
elgg_format_element($tag_name, array $attributes=array(), $text= '', array $options=array())
Format an HTML element.
Definition: output.php:194
$string
elgg_strlen()
Wrapper function for mb_strlen().
Definition: mb_wrapper.php:76
elgg_strrpos()
Wrapper function for mb_strrpos().
Definition: mb_wrapper.php:144
$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
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Trigger a Plugin Hook and run all handler callbacks registered to that hook:type. ...
Definition: elgglib.php:925
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Sends a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1171
elgg global
Pointer to the global context.
Definition: elgglib.js:12
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:515
$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:118
_elgg_output_unit_test($hook, $type, $value, $params)
Unit tests for Output.
Definition: output.php:560
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Register a callback as an Elgg event handler.
Definition: elgglib.php:669
$attrs
Definition: ajax_loader.php:30
elgg_substr()
Wrapper function for mb_substr().
Definition: mb_wrapper.php:229
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:105
elgg_get_friendly_title($title)
When given a title, returns a version suitable for inclusion in a URL.
Definition: output.php:348
$attributes
Definition: ajax_loader.php:13
static urlize($string, $separator= '-')
Create a version of a string for embedding in a URL.
Definition: Translit.php:39
if(file_exists($welcome)) $vars
Definition: upgrade.php:93
_elgg_output_init()
Initialize the output subsystem.
Definition: output.php:572