3 * @file include/text.php
6 use Friendica\Content\Feature;
7 use Friendica\Content\Smilies;
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
12 use Friendica\Util\Map;
14 require_once "include/friendica_smarty.php";
15 require_once "mod/proxy.php";
16 require_once "include/conversation.php";
19 * This is our template processor
21 * @param string|FriendicaSmarty $s the string requiring macro substitution,
22 * or an instance of FriendicaSmarty
23 * @param array $r key value pairs (search => replace)
24 * @return string substituted string
26 function replace_macros($s, $r) {
28 $stamp1 = microtime(true);
32 // pass $baseurl to all templates
33 $r['$baseurl'] = System::baseUrl();
35 $t = $a->template_engine();
37 $output = $t->replaceMacros($s, $r);
38 } catch (Exception $e) {
39 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
43 $a->save_timestamp($stamp1, "rendering");
49 * @brief Generates a pseudo-random string of hexadecimal characters
54 function random_string($size = 64)
56 $byte_size = ceil($size / 2);
58 $bytes = random_bytes($byte_size);
60 $return = substr(bin2hex($bytes), 0, $size);
66 * This is our primary input filter.
68 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
69 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
70 * after cleansing, and angle chars with the high bit set could get through as markup.
72 * This is now disabled because it was interfering with some legitimate unicode sequences
73 * and hopefully there aren't a lot of those browsers left.
75 * Use this on any text input where angle chars are not valid or permitted
76 * They will be replaced with safer brackets. This may be filtered further
77 * if these are not allowed either.
79 * @param string $string Input string
80 * @return string Filtered string
82 function notags($string) {
83 return str_replace(array("<", ">"), array('[', ']'), $string);
85 // High-bit filter no longer used
86 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
91 * use this on "body" or "content" input where angle chars shouldn't be removed,
92 * and allow them to be safely displayed.
93 * @param string $string
96 function escape_tags($string) {
97 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
102 * generate a string that's random, but usually pronounceable.
103 * used to generate initial passwords
107 function autoname($len) {
113 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
114 if (mt_rand(0, 5) == 4) {
133 's','sc','sh','sm','sp','st',
141 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
142 'nd','ng','nk','nt','rn','rp','rt');
144 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
145 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
147 $start = mt_rand(0,2);
156 for ($x = 0; $x < $len; $x ++) {
157 $r = mt_rand(0,count($table) - 1);
160 if ($table == $vowels) {
161 $table = array_merge($cons,$midcons);
168 $word = substr($word,0,$len);
170 foreach ($noend as $noe) {
171 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
172 $word = substr($word, 0, -1);
176 if (substr($word, -1) == 'q') {
177 $word = substr($word, 0, -1);
184 * escape text ($str) for XML transport
186 * @return string Escaped text.
188 function xmlify($str) {
189 /// @TODO deprecated code found?
192 $len = mb_strlen($str);
193 for ($x = 0; $x < $len; $x ++) {
194 $char = mb_substr($str,$x,1);
224 $buffer = mb_ereg_replace("&", "&", $str);
225 $buffer = mb_ereg_replace("'", "'", $buffer);
226 $buffer = mb_ereg_replace('"', """, $buffer);
227 $buffer = mb_ereg_replace("<", "<", $buffer);
228 $buffer = mb_ereg_replace(">", ">", $buffer);
230 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
231 $buffer = trim($buffer);
239 * @param string $s xml escaped text
240 * @return string unescaped text
242 function unxmlify($s) {
243 /// @TODO deprecated code found?
244 // $ret = str_replace('&','&', $s);
245 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
246 /*$ret = mb_ereg_replace('&', '&', $s);
247 $ret = mb_ereg_replace(''', "'", $ret);
248 $ret = mb_ereg_replace('"', '"', $ret);
249 $ret = mb_ereg_replace('<', "<", $ret);
250 $ret = mb_ereg_replace('>', ">", $ret);
252 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
258 * @brief Paginator function. Pushes relevant links in a pager array structure.
260 * Links are generated depending on the current page and the total number of items.
261 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
262 * Current page link is given the "active" CSS class
264 * @param App $a App instance
265 * @param int $count [optional] item count (used with minimal pager)
266 * @return Array data for pagination template
268 function paginate_data(App $a, $count = null) {
269 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
271 $stripped = str_replace('q=', '', $stripped);
272 $stripped = trim($stripped, '/');
273 $pagenum = $a->pager['page'];
275 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
276 $stripped .= '&offset=' . urlencode($a->page_offset);
282 function _l(&$d, $name, $url, $text, $class = '') {
283 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
284 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
287 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
290 if (!is_null($count)) {
291 // minimal pager (newer / older)
292 $data['class'] = 'pager';
293 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
294 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
296 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
297 $data['class'] = 'pagination';
298 if ($a->pager['total'] > $a->pager['itemspage']) {
299 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
300 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
302 $numpages = $a->pager['total'] / $a->pager['itemspage'];
305 $numstop = $numpages;
307 // Limit the number of displayed page number buttons.
309 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
310 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
315 for ($i = $numstart; $i <= $numstop; $i++) {
316 if ($i == $a->pager['page']) {
317 _l($pages, $i, '#', $i, 'current active');
319 _l($pages, $i, $url . '&page='. $i, $i, 'n');
323 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
324 if ($i == $a->pager['page']) {
325 _l($pages, $i, '#', $i, 'current active');
327 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
331 $data['pages'] = $pages;
333 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
334 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
335 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
344 * Automatic pagination.
346 * To use, get the count of total items.
347 * Then call $a->set_pager_total($number_items);
348 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
349 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
350 * (assuming there are enough items to paginate).
351 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
352 * will limit the results to the correct items for the current page.
353 * The actual page handling is then accomplished at the application layer.
355 * @param App $a App instance
356 * @return string html for pagination #FIXME remove html
358 function paginate(App $a) {
360 $data = paginate_data($a);
361 $tpl = get_markup_template("paginate.tpl");
362 return replace_macros($tpl, array("pager" => $data));
369 * @param App $a App instance
371 * @return string html for pagination #FIXME remove html
373 function alt_pager(App $a, $i) {
375 $data = paginate_data($a, $i);
376 $tpl = get_markup_template("paginate.tpl");
377 return replace_macros($tpl, array('pager' => $data));
383 * Loader for infinite scrolling
384 * @return string html for loader
386 function scroll_loader() {
387 $tpl = get_markup_template("scroll_loader.tpl");
388 return replace_macros($tpl, array(
389 'wait' => t('Loading more entries...'),
390 'end' => t('The end')
396 * Turn user/group ACLs stored as angle bracketed text into arrays
401 function expand_acl($s) {
402 // turn string array of angle-bracketed elements into numeric array
403 // e.g. "<1><2><3>" => array(1,2,3);
407 $t = str_replace('<', '', $s);
408 $a = explode('>', $t);
409 foreach ($a as $aa) {
411 $ret[] = intval($aa);
420 * Wrap ACL elements in angle brackets for storage
421 * @param string $item
423 function sanitise_acl(&$item) {
425 $item = '<' . intval(notags(trim($item))) . '>';
433 * Convert an ACL array to a storable string
435 * Normally ACL permissions will be an array.
436 * We'll also allow a comma-separated string.
438 * @param string|array $p
441 function perms2str($p) {
446 $tmp = explode(',',$p);
449 if (is_array($tmp)) {
450 array_walk($tmp, 'sanitise_acl');
451 $ret = implode('', $tmp);
458 * generate a guaranteed unique (for this domain) item ID for ATOM
459 * safe from birthday paradox
461 * @param string $hostname
465 function item_new_uri($hostname, $uid, $guid = "") {
469 $hash = get_guid(32);
475 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
477 $dups = dba::exists('item', array('uri' => $uri));
478 } while ($dups == true);
485 * Generate a guaranteed unique photo ID.
486 * safe from birthday paradox
490 function photo_new_resource() {
494 $resource = hash('md5',uniqid(mt_rand(),true));
495 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
499 if (DBM::is_result($r)) {
502 } while ($found == true);
510 * wrapper to load a view template, checking for alternate
511 * languages before falling back to the default
513 * @global string $lang
515 * @param string $s view name
518 function load_view_file($s) {
520 if (! isset($lang)) {
525 if (file_exists("$d/$lang/$b")) {
526 $stamp1 = microtime(true);
527 $content = file_get_contents("$d/$lang/$b");
528 $a->save_timestamp($stamp1, "file");
532 $theme = current_theme();
534 if (file_exists("$d/theme/$theme/$b")) {
535 $stamp1 = microtime(true);
536 $content = file_get_contents("$d/theme/$theme/$b");
537 $a->save_timestamp($stamp1, "file");
541 $stamp1 = microtime(true);
542 $content = file_get_contents($s);
543 $a->save_timestamp($stamp1, "file");
549 * load a view template, checking for alternate
550 * languages before falling back to the default
552 * @global string $lang
553 * @param string $s view path
556 function get_intltext_template($s) {
561 if ($a->theme['template_engine'] === 'smarty3') {
562 $engine = "/smarty3";
565 if (! isset($lang)) {
569 if (file_exists("view/lang/$lang$engine/$s")) {
570 $stamp1 = microtime(true);
571 $content = file_get_contents("view/lang/$lang$engine/$s");
572 $a->save_timestamp($stamp1, "file");
574 } elseif (file_exists("view/lang/en$engine/$s")) {
575 $stamp1 = microtime(true);
576 $content = file_get_contents("view/lang/en$engine/$s");
577 $a->save_timestamp($stamp1, "file");
580 $stamp1 = microtime(true);
581 $content = file_get_contents("view$engine/$s");
582 $a->save_timestamp($stamp1, "file");
592 * @param string $root
595 function get_markup_template($s, $root = '') {
596 $stamp1 = microtime(true);
599 $t = $a->template_engine();
601 $template = $t->getTemplateFile($s, $root);
602 } catch (Exception $e) {
603 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
607 $a->save_timestamp($stamp1, "file");
616 * @param string $filename
617 * @param string $root
620 function get_template_file($a, $filename, $root = '') {
621 $theme = current_theme();
623 // Make sure $root ends with a slash /
624 if ($root !== '' && substr($root, -1, 1) !== '/') {
628 if (file_exists("{$root}view/theme/$theme/$filename")) {
629 $template_file = "{$root}view/theme/$theme/$filename";
630 } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
631 $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
632 } elseif (file_exists("{$root}/$filename")) {
633 $template_file = "{$root}/$filename";
635 $template_file = "{$root}view/$filename";
638 return $template_file;
643 * for html,xml parsing - let's say you've got
644 * an attribute foobar="class1 class2 class3"
645 * and you want to find out if it contains 'class3'.
646 * you can't use a normal sub string search because you
647 * might match 'notclass3' and a regex to do the job is
648 * possible but a bit complicated.
649 * pass the attribute string as $attr and the attribute you
650 * are looking for as $s - returns true if found, otherwise false
652 * @param string $attr attribute value
653 * @param string $s string to search
654 * @return boolean True if found, False otherwise
656 function attribute_contains($attr, $s) {
657 $a = explode(' ', $attr);
658 return (count($a) && in_array($s,$a));
662 /* setup int->string log level map */
663 $LOGGER_LEVELS = array();
666 * @brief Logs the given message at the given log level
669 * LOGGER_NORMAL (default)
676 * @global array $LOGGER_LEVELS
680 function logger($msg, $level = 0) {
682 global $LOGGER_LEVELS;
684 // turn off logger in install mode
686 $a->module == 'install'
692 $debugging = Config::get('system','debugging');
693 $logfile = Config::get('system','logfile');
694 $loglevel = intval(Config::get('system','loglevel'));
699 || $level > $loglevel
704 if (count($LOGGER_LEVELS) == 0) {
705 foreach (get_defined_constants() as $k => $v) {
706 if (substr($k, 0, 7) == "LOGGER_") {
707 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
712 $process_id = session_id();
714 if ($process_id == '') {
715 $process_id = get_app()->process_id;
718 $callers = debug_backtrace();
719 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
720 datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
722 $LOGGER_LEVELS[$level],
723 basename($callers[0]['file']),
725 $callers[1]['function'],
729 $stamp1 = microtime(true);
730 @file_put_contents($logfile, $logline, FILE_APPEND);
731 $a->save_timestamp($stamp1, "file");
735 * @brief An alternative logger for development.
736 * Works largely as logger() but allows developers
737 * to isolate particular elements they are targetting
738 * personally without background noise
741 * LOGGER_NORMAL (default)
748 * @global array $LOGGER_LEVELS
753 function dlogger($msg, $level = 0) {
756 // turn off logger in install mode
758 $a->module == 'install'
764 $logfile = Config::get('system','dlogfile');
770 if (count($LOGGER_LEVELS) == 0) {
771 foreach (get_defined_constants() as $k => $v) {
772 if (substr($k, 0, 7) == "LOGGER_") {
773 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
778 $process_id = session_id();
780 if ($process_id == '') {
781 $process_id = get_app()->process_id;
784 $callers = debug_backtrace();
785 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
788 basename($callers[0]['file']),
790 $callers[1]['function'],
794 $stamp1 = microtime(true);
795 @file_put_contents($logfile, $logline, FILE_APPEND);
796 $a->save_timestamp($stamp1, "file");
801 * Compare activity uri. Knows about activity namespace.
803 * @param string $haystack
804 * @param string $needle
807 function activity_match($haystack,$needle) {
808 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
813 * @brief Pull out all #hashtags and @person tags from $string.
815 * We also get @person@domain.com - which would make
816 * the regex quite complicated as tags can also
817 * end a sentence. So we'll run through our results
818 * and strip the period from any tags which end with one.
819 * Returns array of tags found, or empty array.
821 * @param string $string Post content
822 * @return array List of tag and person names
824 function get_tags($string) {
827 // Convert hashtag links to hashtags
828 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
830 // ignore anything in a code block
831 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
833 // Force line feeds at bbtags
834 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
836 // ignore anything in a bbtag
837 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
839 // Match full names against @tags including the space between first and last
840 // We will look these up afterward to see if they are full names or not recognisable.
842 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
843 foreach ($matches[1] as $match) {
844 if (strstr($match, ']')) {
845 // we might be inside a bbcode color tag - leave it alone
848 if (substr($match, -1, 1) === '.') {
849 $ret[] = substr($match, 0, -1);
856 // Otherwise pull out single word tags. These can be @nickname, @first_last
859 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
860 foreach ($matches[1] as $match) {
861 if (strstr($match, ']')) {
862 // we might be inside a bbcode color tag - leave it alone
865 if (substr($match, -1, 1) === '.') {
866 $match = substr($match,0,-1);
868 // ignore strictly numeric tags like #1
869 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
872 // try not to catch url fragments
873 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
884 * quick and dirty quoted_printable encoding
890 return str_replace("%", "=", rawurlencode($s));
895 * Get html for contact block.
897 * @template contact_block.tpl
898 * @hook contact_block_end (contacts=>array, output=>string)
901 function contact_block() {
905 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
910 if (!is_array($a->profile) || $a->profile['hide-friends']) {
913 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
914 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
915 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
916 AND `network` IN ('%s', '%s', '%s')",
917 intval($a->profile['uid']),
919 dbesc(NETWORK_OSTATUS),
920 dbesc(NETWORK_DIASPORA)
922 if (DBM::is_result($r)) {
923 $total = intval($r[0]['total']);
926 $contacts = t('No contacts');
929 // Splitting the query in two parts makes it much faster
930 $r = q("SELECT `id` FROM `contact`
931 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
932 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
933 AND `network` IN ('%s', '%s', '%s')
934 ORDER BY RAND() LIMIT %d",
935 intval($a->profile['uid']),
937 dbesc(NETWORK_OSTATUS),
938 dbesc(NETWORK_DIASPORA),
941 if (DBM::is_result($r)) {
943 foreach ($r AS $contact) {
944 $contacts[] = $contact["id"];
946 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
947 dbesc(implode(",", $contacts)));
949 if (DBM::is_result($r)) {
950 $contacts = sprintf(tt('%d Contact','%d Contacts', $total),$total);
952 foreach ($r as $rr) {
953 $micropro[] = micropro($rr,true,'mpfriend');
959 $tpl = get_markup_template('contact_block.tpl');
960 $o = replace_macros($tpl, array(
961 '$contacts' => $contacts,
962 '$nickname' => $a->profile['nickname'],
963 '$viewcontacts' => t('View Contacts'),
964 '$micropro' => $micropro,
967 $arr = array('contacts' => $r, 'output' => $o);
969 call_hooks('contact_block_end', $arr);
976 * @brief Format contacts as picture links or as texxt links
978 * @param array $contact Array with contacts which contains an array with
979 * int 'id' => The ID of the contact
980 * int 'uid' => The user ID of the user who owns this data
981 * string 'name' => The name of the contact
982 * string 'url' => The url to the profile page of the contact
983 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
984 * string 'network' => The network to which the contact belongs to
985 * string 'thumb' => The contact picture
986 * string 'click' => js code which is performed when clicking on the contact
987 * @param boolean $redirect If true try to use the redir url if it's possible
988 * @param string $class CSS class for the
989 * @param boolean $textmode If true display the contacts as text links
990 * if false display the contacts as picture links
992 * @return string Formatted html
994 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
996 // Use the contact URL if no address is available
997 if (!x($contact, "addr")) {
998 $contact["addr"] = $contact["url"];
1001 $url = $contact['url'];
1007 $redirect_url = 'redir/' . $contact['id'];
1008 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1010 $url = $redirect_url;
1011 $sparkle = ' sparkle';
1017 // If there is some js available we don't need the url
1018 if (x($contact, 'click')) {
1022 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1023 '$click' => defaults($contact, 'click', ''),
1026 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1027 '$name' => $contact['name'],
1028 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1029 '$parkle' => $sparkle,
1038 * @param string $s search query
1039 * @param string $id html id
1040 * @param string $url search url
1041 * @param boolean $savedsearch show save search button
1043 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true) {
1047 '$s' => htmlspecialchars($s),
1049 '$action_url' => $url,
1050 '$search_label' => t('Search'),
1051 '$save_label' => t('Save'),
1052 '$savedsearch' => Feature::isEnabled(local_user(),'savedsearch'),
1053 '$search_hint' => t('@name, !forum, #tags, content'),
1057 $values['$searchoption'] = array(
1062 if (Config::get('system','poco_local_search')) {
1063 $values['$searchoption'][] = t("Forums");
1067 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1071 * @brief Check for a valid email string
1073 * @param string $email_address
1076 function valid_email($email_address)
1078 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
1083 * Replace naked text hyperlink with HTML formatted hyperlink
1087 function linkify($s) {
1088 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1089 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1097 * @return array index is present tense verb
1098 value is array containing past tense verb, translation of present, translation of past
1099 * @hook poke_verbs pokes array
1101 function get_poke_verbs() {
1103 // index is present tense verb
1104 // value is array containing past tense verb, translation of present, translation of past
1107 'poke' => array('poked', t('poke'), t('poked')),
1108 'ping' => array('pinged', t('ping'), t('pinged')),
1109 'prod' => array('prodded', t('prod'), t('prodded')),
1110 'slap' => array('slapped', t('slap'), t('slapped')),
1111 'finger' => array('fingered', t('finger'), t('fingered')),
1112 'rebuff' => array('rebuffed', t('rebuff'), t('rebuffed')),
1114 call_hooks('poke_verbs', $arr);
1119 * @brief Translate days and months names.
1121 * @param string $s String with day or month name.
1122 * @return string Translated string.
1124 function day_translate($s) {
1125 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1126 array(t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1129 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1130 array(t('January'), t('February'), t('March'), t('April'), t('May'), t('June'), t('July'), t('August'), t('September'), t('October'), t('November'), t('December')),
1137 * @brief Translate short days and months names.
1139 * @param string $s String with short day or month name.
1140 * @return string Translated string.
1142 function day_short_translate($s) {
1143 $ret = str_replace(array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'),
1144 array(t('Mon'), t('Tue'), t('Wed'), t('Thu'), t('Fri'), t('Sat'), t('Sun')),
1146 $ret = str_replace(array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'),
1147 array(t('Jan'), t('Feb'), t('Mar'), t('Apr'), t('May'), ('Jun'), t('Jul'), t('Aug'), t('Sep'), t('Oct'), t('Nov'), t('Dec')),
1156 * @param string $url
1159 function normalise_link($url) {
1160 $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
1161 return rtrim($ret,'/');
1166 * Compare two URLs to see if they are the same, but ignore
1167 * slight but hopefully insignificant differences such as if one
1168 * is https and the other isn't, or if one is www.something and
1169 * the other isn't - and also ignore case differences.
1171 * @param string $a first url
1172 * @param string $b second url
1173 * @return boolean True if the URLs match, otherwise False
1176 function link_compare($a, $b) {
1177 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1182 * @brief Find any non-embedded images in private items and add redir links to them
1185 * @param array &$item The field array of an item row
1187 function redir_private_images($a, &$item)
1190 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1192 foreach ($matches as $mtch) {
1193 if (strpos($mtch[1], '/redir') !== false) {
1197 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1198 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1199 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1205 function put_item_in_cache(&$item, $update = false)
1207 $rendered_hash = defaults($item, 'rendered-hash', '');
1209 if ($rendered_hash == ''
1210 || $item["rendered-html"] == ""
1211 || $rendered_hash != hash("md5", $item["body"])
1212 || Config::get("system", "ignore_cache")
1214 // The function "redir_private_images" changes the body.
1215 // I'm not sure if we should store it permanently, so we save the old value.
1216 $body = $item["body"];
1219 redir_private_images($a, $item);
1221 $item["rendered-html"] = prepare_text($item["body"]);
1222 $item["rendered-hash"] = hash("md5", $item["body"]);
1223 $item["body"] = $body;
1225 if ($update && ($item["id"] > 0)) {
1226 dba::update('item', array('rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]),
1227 array('id' => $item["id"]), false);
1233 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1234 * If attach is true, also add icons for item attachments.
1236 * @param array $item
1237 * @param boolean $attach
1238 * @return string item body html
1239 * @hook prepare_body_init item array before any work
1240 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1241 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1243 function prepare_body(&$item, $attach = false, $preview = false) {
1246 call_hooks('prepare_body_init', $item);
1248 $searchpath = System::baseUrl() . "/search?tag=";
1251 $hashtags = array();
1252 $mentions = array();
1254 // In order to provide theme developers more possibilities, event items
1255 // are treated differently.
1256 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1257 $ev = format_event_item($item);
1261 if (!Config::get('system','suppress_tags')) {
1262 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1263 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1265 while ($tag = dba::fetch($taglist)) {
1266 if ($tag["url"] == "") {
1267 $tag["url"] = $searchpath.strtolower($tag["term"]);
1270 $orig_tag = $tag["url"];
1272 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1274 if ($tag["type"] == TERM_HASHTAG) {
1275 if ($orig_tag != $tag["url"]) {
1276 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1278 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1280 } elseif ($tag["type"] == TERM_MENTION) {
1281 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1284 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1286 dba::close($taglist);
1289 $item['tags'] = $tags;
1290 $item['hashtags'] = $hashtags;
1291 $item['mentions'] = $mentions;
1293 // Update the cached values if there is no "zrl=..." on the links.
1294 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1296 // Or update it if the current viewer is the intented viewer.
1297 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1301 put_item_in_cache($item, $update);
1302 $s = $item["rendered-html"];
1304 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1305 call_hooks('prepare_body', $prep_arr);
1306 $s = $prep_arr['html'];
1309 // Replace the blockquotes with quotes that are used in mails.
1310 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1311 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1317 $arr = explode('[/attach],', $item['attach']);
1319 foreach ($arr as $r) {
1322 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1324 foreach ($matches as $mtch) {
1327 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1328 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1330 $the_url = $mtch[1];
1333 if (strpos($mime, 'video') !== false) {
1336 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1337 '$baseurl' => System::baseUrl(),
1339 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1340 '$baseurl' => System::baseUrl(),
1344 $id = end(explode('/', $the_url));
1345 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1348 'title' => t('View Video'),
1355 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1357 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1358 $filesubtype = str_replace('.', '-', $filesubtype);
1361 $filesubtype = 'unkn';
1364 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1365 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1367 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1368 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1374 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1378 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1379 $x = Map::byCoordinates(trim($item['coord']));
1381 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1386 // Look for spoiler.
1387 $spoilersearch = '<blockquote class="spoiler">';
1389 // Remove line breaks before the spoiler.
1390 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1391 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1393 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1394 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1397 while ((strpos($s, $spoilersearch) !== false)) {
1398 $pos = strpos($s, $spoilersearch);
1399 $rnd = random_string(8);
1400 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1401 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1402 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1405 // Look for quote with author.
1406 $authorsearch = '<blockquote class="author">';
1408 while ((strpos($s, $authorsearch) !== false)) {
1409 $pos = strpos($s, $authorsearch);
1410 $rnd = random_string(8);
1411 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1412 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1413 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1416 // Replace friendica image url size with theme preference.
1417 if (x($a->theme_info, 'item_image_size')){
1418 $ps = $a->theme_info['item_image_size'];
1419 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1422 $prep_arr = array('item' => $item, 'html' => $s);
1423 call_hooks('prepare_body_final', $prep_arr);
1425 return $prep_arr['html'];
1429 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1431 * @param string $text String with bbcode.
1432 * @return string Formattet HTML.
1434 function prepare_text($text) {
1436 require_once 'include/bbcode.php';
1438 if (stristr($text, '[nosmile]')) {
1441 $s = Smilies::replace(bbcode($text));
1448 * return array with details for categories and folders for an item
1450 * @param array $item
1454 * [ // categories array
1456 * 'name': 'category name',
1457 * 'removeurl': 'url to remove this category',
1458 * 'first': 'is the first in this array? true/false',
1459 * 'last': 'is the last in this array? true/false',
1465 * 'name': 'folder name',
1466 * 'removeurl': 'url to remove this folder',
1467 * 'first': 'is the first in this array? true/false',
1468 * 'last': 'is the last in this array? true/false',
1474 function get_cats_and_terms($item) {
1477 $categories = array();
1482 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1484 foreach ($matches as $mtch) {
1485 $categories[] = array(
1486 'name' => xmlify(file_tag_decode($mtch[1])),
1488 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1496 if (count($categories)) {
1497 $categories[count($categories) - 1]['last'] = true;
1500 if (local_user() == $item['uid']) {
1503 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1505 foreach ($matches as $mtch) {
1507 'name' => xmlify(file_tag_decode($mtch[1])),
1509 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1518 if (count($folders)) {
1519 $folders[count($folders) - 1]['last'] = true;
1522 return array($categories, $folders);
1527 * get private link for item
1528 * @param array $item
1529 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1531 function get_plink($item) {
1534 if ($a->user['nickname'] != "") {
1536 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1537 'href' => "display/" . $item['guid'],
1538 'orig' => "display/" . $item['guid'],
1539 'title' => t('View on separate page'),
1540 'orig_title' => t('view on separate page'),
1543 if (x($item, 'plink')) {
1544 $ret["href"] = $a->remove_baseurl($item['plink']);
1545 $ret["title"] = t('link to source');
1548 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1550 'href' => $item['plink'],
1551 'orig' => $item['plink'],
1552 'title' => t('link to source'),
1563 * replace html amp entity with amp char
1567 function unamp($s) {
1568 return str_replace('&', '&', $s);
1573 * return number of bytes in size (K, M, G)
1574 * @param string $size_str
1577 function return_bytes($size_str) {
1578 switch (substr ($size_str, -1)) {
1579 case 'M': case 'm': return (int)$size_str * 1048576;
1580 case 'K': case 'k': return (int)$size_str * 1024;
1581 case 'G': case 'g': return (int)$size_str * 1073741824;
1582 default: return $size_str;
1590 function generate_user_guid() {
1593 $guid = get_guid(32);
1594 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1597 if (! DBM::is_result($x)) {
1600 } while ($found == true);
1608 * @param boolean $strip_padding
1611 function base64url_encode($s, $strip_padding = false) {
1613 $s = strtr(base64_encode($s), '+/', '-_');
1615 if ($strip_padding) {
1616 $s = str_replace('=','',$s);
1626 function base64url_decode($s) {
1629 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1634 * // Placeholder for new rev of salmon which strips base64 padding.
1635 * // PHP base64_decode handles the un-padded input without requiring this step
1636 * // Uncomment if you find you need it.
1639 * if (! strpos($s,'=')) {
1649 return base64_decode(strtr($s,'-_','+/'));
1654 * return div element with class 'clear'
1658 function cleardiv() {
1659 return '<div class="clear"></div>';
1663 function bb_translate_video($s) {
1666 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1668 foreach ($matches as $mtch) {
1669 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1670 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1671 elseif (stristr($mtch[1],'vimeo'))
1672 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1678 function html2bb_video($s) {
1680 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1681 '[youtube]$2[/youtube]', $s);
1683 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1684 '[youtube]$2[/youtube]', $s);
1686 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1687 '[vimeo]$2[/vimeo]', $s);
1693 * apply xmlify() to all values of array $val, recursively
1697 function array_xmlify($val){
1698 if (is_bool($val)) {
1699 return $val?"true":"false";
1700 } elseif (is_array($val)) {
1701 return array_map('array_xmlify', $val);
1703 return xmlify((string) $val);
1708 * transform link href and img src from relative to absolute
1710 * @param string $text
1711 * @param string $base base url
1714 function reltoabs($text, $base) {
1719 $base = rtrim($base,'/');
1721 $base2 = $base . "/";
1724 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1725 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1726 $text = preg_replace($pattern, $replace, $text);
1728 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1729 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1730 $text = preg_replace($pattern, $replace, $text);
1733 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1734 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1735 $text = preg_replace($pattern, $replace, $text);
1737 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1738 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1739 $text = preg_replace($pattern, $replace, $text);
1747 * get translated item type
1749 * @param array $itme
1752 function item_post_type($item) {
1753 if (intval($item['event-id'])) {
1755 } elseif (strlen($item['resource-id'])) {
1757 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1758 return t('activity');
1759 } elseif ($item['id'] != $item['parent']) {
1760 return t('comment');
1766 // post categories and "save to file" use the same item.file table for storage.
1767 // We will differentiate the different uses by wrapping categories in angle brackets
1768 // and save to file categories in square brackets.
1769 // To do this we need to escape these characters if they appear in our tag.
1771 function file_tag_encode($s) {
1772 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1775 function file_tag_decode($s) {
1776 return str_replace(array('%3c', '%3e', '%5b', '%5d'), array('<', '>', '[', ']'), $s);
1779 function file_tag_file_query($table,$s,$type = 'file') {
1781 if ($type == 'file') {
1782 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1784 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1786 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1789 // ex. given music,video return <music><video> or [music][video]
1790 function file_tag_list_to_file($list,$type = 'file') {
1792 if (strlen($list)) {
1793 $list_array = explode(",",$list);
1794 if ($type == 'file') {
1802 foreach ($list_array as $item) {
1803 if (strlen($item)) {
1804 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1811 // ex. given <music><video>[friends], return music,video or friends
1812 function file_tag_file_to_list($file,$type = 'file') {
1815 if ($type == 'file') {
1816 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1818 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1821 foreach ($matches as $mtch) {
1822 if (strlen($list)) {
1825 $list .= file_tag_decode($mtch[1]);
1832 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1833 // $file_old - categories previously associated with an item
1834 // $file_new - new list of categories for an item
1836 if (!intval($uid)) {
1839 if ($file_old == $file_new) {
1843 $saved = PConfig::get($uid, 'system', 'filetags');
1844 if (strlen($saved)) {
1845 if ($type == 'file') {
1848 $termtype = TERM_FILE;
1852 $termtype = TERM_CATEGORY;
1855 $filetags_updated = $saved;
1857 // check for new tags to be added as filetags in pconfig
1858 $new_tags = array();
1859 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1861 foreach ($check_new_tags as $tag) {
1862 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1866 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1868 // check for deleted tags to be removed from filetags in pconfig
1869 $deleted_tags = array();
1870 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1872 foreach ($check_deleted_tags as $tag) {
1873 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1874 $deleted_tags[] = $tag;
1877 foreach ($deleted_tags as $key => $tag) {
1878 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1880 intval(TERM_OBJ_POST),
1884 if (DBM::is_result($r)) {
1885 unset($deleted_tags[$key]);
1887 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1891 if ($saved != $filetags_updated) {
1892 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1895 } elseif (strlen($file_new)) {
1896 PConfig::set($uid, 'system', 'filetags', $file_new);
1901 function file_tag_save_file($uid, $item, $file) {
1902 require_once "include/files.php";
1907 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1911 if (DBM::is_result($r)) {
1912 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1913 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1914 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1920 create_files_from_item($item);
1922 $saved = PConfig::get($uid, 'system', 'filetags');
1923 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1924 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1926 info(t('Item filed'));
1931 function file_tag_unsave_file($uid, $item, $file, $cat = false) {
1932 require_once "include/files.php";
1939 $pattern = '<' . file_tag_encode($file) . '>' ;
1940 $termtype = TERM_CATEGORY;
1942 $pattern = '[' . file_tag_encode($file) . ']' ;
1943 $termtype = TERM_FILE;
1947 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1951 if (! DBM::is_result($r)) {
1955 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1956 dbesc(str_replace($pattern,'',$r[0]['file'])),
1961 create_files_from_item($item);
1963 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1965 intval(TERM_OBJ_POST),
1969 if (!DBM::is_result($r)) {
1970 $saved = PConfig::get($uid, 'system', 'filetags');
1971 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1977 function normalise_openid($s) {
1978 return trim(str_replace(array('http://', 'https://'), array('', ''), $s), '/');
1982 function undo_post_tagging($s) {
1984 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1986 foreach ($matches as $mtch) {
1987 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1993 function protect_sprintf($s) {
1994 return str_replace('%', '%%', $s);
1998 function is_a_date_arg($s) {
2002 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2003 $m = intval(substr($s,5));
2004 if ($m > 0 && $m <= 12)
2012 * remove intentation from a text
2014 function deindent($text, $chr = "[\t ]", $count = NULL) {
2015 $lines = explode("\n", $text);
2016 if (is_null($count)) {
2019 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2022 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2023 $count = strlen($m[0]);
2025 for ($k = 0; $k < count($lines); $k++) {
2026 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2029 return implode("\n", $lines);
2032 function formatBytes($bytes, $precision = 2) {
2033 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2035 $bytes = max($bytes, 0);
2036 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2037 $pow = min($pow, count($units) - 1);
2039 $bytes /= pow(1024, $pow);
2041 return round($bytes, $precision) . ' ' . $units[$pow];
2045 * @brief translate and format the networkname of a contact
2047 * @param string $network
2048 * Networkname of the contact (e.g. dfrn, rss and so on)
2053 function format_network_name($network, $url = 0) {
2054 if ($network != "") {
2055 require_once 'include/contact_selectors.php';
2057 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2059 $network_name = network_to_name($network);
2062 return $network_name;
2068 * @brief Syntax based code highlighting for popular languages.
2069 * @param string $s Code block
2070 * @param string $lang Programming language
2071 * @return string Formated html
2073 function text_highlight($s, $lang) {
2074 if ($lang === 'js') {
2075 $lang = 'javascript';
2078 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2080 // Autoload the library to make constants available
2081 class_exists('Text_Highlighter_Renderer_Html');
2084 'numbers' => HL_NUMBERS_LI,
2089 $s = trim(html_entity_decode($s, ENT_COMPAT));
2090 $s = str_replace(' ', "\t", $s);
2093 * The highlighter library insists on an opening php tag for php code blocks. If
2094 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2095 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2097 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2098 $s = '<?php' . "\n" . $s;
2102 $renderer = new Text_Highlighter_Renderer_Html($options);
2103 $hl = Text_Highlighter::factory($lang);
2104 $hl->setRenderer($renderer);
2105 $o = $hl->highlight($s);
2106 $o = str_replace("\n", '', $o);
2109 $b = substr($o, 0, strpos($o, '<li>'));
2110 $e = substr($o, strpos($o, '</li>'));
2114 return '<code>' . $o . '</code>';