3 * @file include/text.php
6 use Friendica\Content\ContactSelector;
7 use Friendica\Content\Feature;
8 use Friendica\Content\Smilies;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\System;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Profile;
16 use Friendica\Model\Term;
17 use Friendica\Util\Map;
19 require_once "mod/proxy.php";
20 require_once "include/conversation.php";
23 * This is our template processor
25 * @param string|FriendicaSmarty $s the string requiring macro substitution,
26 * or an instance of FriendicaSmarty
27 * @param array $r key value pairs (search => replace)
28 * @return string substituted string
30 function replace_macros($s, $r) {
32 $stamp1 = microtime(true);
36 // pass $baseurl to all templates
37 $r['$baseurl'] = System::baseUrl();
39 $t = $a->template_engine();
41 $output = $t->replaceMacros($s, $r);
42 } catch (Exception $e) {
43 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
47 $a->save_timestamp($stamp1, "rendering");
53 * @brief Generates a pseudo-random string of hexadecimal characters
58 function random_string($size = 64)
60 $byte_size = ceil($size / 2);
62 $bytes = random_bytes($byte_size);
64 $return = substr(bin2hex($bytes), 0, $size);
70 * This is our primary input filter.
72 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
73 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
74 * after cleansing, and angle chars with the high bit set could get through as markup.
76 * This is now disabled because it was interfering with some legitimate unicode sequences
77 * and hopefully there aren't a lot of those browsers left.
79 * Use this on any text input where angle chars are not valid or permitted
80 * They will be replaced with safer brackets. This may be filtered further
81 * if these are not allowed either.
83 * @param string $string Input string
84 * @return string Filtered string
86 function notags($string) {
87 return str_replace(["<", ">"], ['[', ']'], $string);
89 // High-bit filter no longer used
90 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
95 * use this on "body" or "content" input where angle chars shouldn't be removed,
96 * and allow them to be safely displayed.
97 * @param string $string
100 function escape_tags($string) {
101 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
106 * generate a string that's random, but usually pronounceable.
107 * used to generate initial passwords
111 function autoname($len) {
117 $vowels = ['a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'];
118 if (mt_rand(0, 5) == 4) {
137 's','sc','sh','sm','sp','st',
145 $midcons = ['ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
146 'nd','ng','nk','nt','rn','rp','rt'];
148 $noend = ['bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
149 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh'];
151 $start = mt_rand(0,2);
160 for ($x = 0; $x < $len; $x ++) {
161 $r = mt_rand(0,count($table) - 1);
164 if ($table == $vowels) {
165 $table = array_merge($cons,$midcons);
172 $word = substr($word,0,$len);
174 foreach ($noend as $noe) {
175 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
176 $word = substr($word, 0, -1);
180 if (substr($word, -1) == 'q') {
181 $word = substr($word, 0, -1);
188 * escape text ($str) for XML transport
190 * @return string Escaped text.
192 function xmlify($str) {
193 /// @TODO deprecated code found?
196 $len = mb_strlen($str);
197 for ($x = 0; $x < $len; $x ++) {
198 $char = mb_substr($str,$x,1);
228 $buffer = mb_ereg_replace("&", "&", $str);
229 $buffer = mb_ereg_replace("'", "'", $buffer);
230 $buffer = mb_ereg_replace('"', """, $buffer);
231 $buffer = mb_ereg_replace("<", "<", $buffer);
232 $buffer = mb_ereg_replace(">", ">", $buffer);
234 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
235 $buffer = trim($buffer);
243 * @param string $s xml escaped text
244 * @return string unescaped text
246 function unxmlify($s) {
247 /// @TODO deprecated code found?
248 // $ret = str_replace('&','&', $s);
249 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
250 /*$ret = mb_ereg_replace('&', '&', $s);
251 $ret = mb_ereg_replace(''', "'", $ret);
252 $ret = mb_ereg_replace('"', '"', $ret);
253 $ret = mb_ereg_replace('<', "<", $ret);
254 $ret = mb_ereg_replace('>', ">", $ret);
256 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
262 * @brief Paginator function. Pushes relevant links in a pager array structure.
264 * Links are generated depending on the current page and the total number of items.
265 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
266 * Current page link is given the "active" CSS class
268 * @param App $a App instance
269 * @param int $count [optional] item count (used with minimal pager)
270 * @return Array data for pagination template
272 function paginate_data(App $a, $count = null) {
273 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
275 $stripped = str_replace('q=', '', $stripped);
276 $stripped = trim($stripped, '/');
277 $pagenum = $a->pager['page'];
279 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
280 $stripped .= '&offset=' . urlencode($a->page_offset);
286 function _l(&$d, $name, $url, $text, $class = '') {
287 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
288 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
291 $d[$name] = ['url' => $url, 'text' => $text, 'class' => $class];
294 if (!is_null($count)) {
295 // minimal pager (newer / older)
296 $data['class'] = 'pager';
297 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
298 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
300 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
301 $data['class'] = 'pagination';
302 if ($a->pager['total'] > $a->pager['itemspage']) {
303 _l($data, 'first', $url . '&page=1', L10n::t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
304 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
306 $numpages = $a->pager['total'] / $a->pager['itemspage'];
309 $numstop = $numpages;
311 // Limit the number of displayed page number buttons.
313 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
314 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
319 for ($i = $numstart; $i <= $numstop; $i++) {
320 if ($i == $a->pager['page']) {
321 _l($pages, $i, '#', $i, 'current active');
323 _l($pages, $i, $url . '&page='. $i, $i, 'n');
327 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
328 if ($i == $a->pager['page']) {
329 _l($pages, $i, '#', $i, 'current active');
331 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
335 $data['pages'] = $pages;
337 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
338 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
339 _l($data, 'last', $url . '&page=' . $lastpage, L10n::t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
348 * Automatic pagination.
350 * To use, get the count of total items.
351 * Then call $a->set_pager_total($number_items);
352 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
353 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
354 * (assuming there are enough items to paginate).
355 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
356 * will limit the results to the correct items for the current page.
357 * The actual page handling is then accomplished at the application layer.
359 * @param App $a App instance
360 * @return string html for pagination #FIXME remove html
362 function paginate(App $a) {
364 $data = paginate_data($a);
365 $tpl = get_markup_template("paginate.tpl");
366 return replace_macros($tpl, ["pager" => $data]);
373 * @param App $a App instance
375 * @return string html for pagination #FIXME remove html
377 function alt_pager(App $a, $i) {
379 $data = paginate_data($a, $i);
380 $tpl = get_markup_template("paginate.tpl");
381 return replace_macros($tpl, ['pager' => $data]);
387 * Loader for infinite scrolling
388 * @return string html for loader
390 function scroll_loader() {
391 $tpl = get_markup_template("scroll_loader.tpl");
392 return replace_macros($tpl, [
393 'wait' => L10n::t('Loading more entries...'),
394 'end' => L10n::t('The end')
400 * Turn user/group ACLs stored as angle bracketed text into arrays
405 function expand_acl($s) {
406 // turn string array of angle-bracketed elements into numeric array
407 // e.g. "<1><2><3>" => array(1,2,3);
411 $t = str_replace('<', '', $s);
412 $a = explode('>', $t);
413 foreach ($a as $aa) {
415 $ret[] = intval($aa);
424 * Wrap ACL elements in angle brackets for storage
425 * @param string $item
427 function sanitise_acl(&$item) {
429 $item = '<' . intval(notags(trim($item))) . '>';
437 * Convert an ACL array to a storable string
439 * Normally ACL permissions will be an array.
440 * We'll also allow a comma-separated string.
442 * @param string|array $p
445 function perms2str($p) {
450 $tmp = explode(',',$p);
453 if (is_array($tmp)) {
454 array_walk($tmp, 'sanitise_acl');
455 $ret = implode('', $tmp);
462 * generate a guaranteed unique (for this domain) item ID for ATOM
463 * safe from birthday paradox
465 * @param string $hostname
469 function item_new_uri($hostname, $uid, $guid = "") {
473 $hash = get_guid(32);
479 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
481 $dups = dba::exists('item', ['uri' => $uri]);
482 } while ($dups == true);
489 * Generate a guaranteed unique photo ID.
490 * safe from birthday paradox
494 function photo_new_resource() {
498 $resource = hash('md5',uniqid(mt_rand(),true));
499 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
503 if (DBM::is_result($r)) {
506 } while ($found == true);
514 * wrapper to load a view template, checking for alternate
515 * languages before falling back to the default
517 * @global string $lang
519 * @param string $s view name
522 function load_view_file($s) {
524 if (! isset($lang)) {
529 if (file_exists("$d/$lang/$b")) {
530 $stamp1 = microtime(true);
531 $content = file_get_contents("$d/$lang/$b");
532 $a->save_timestamp($stamp1, "file");
536 $theme = current_theme();
538 if (file_exists("$d/theme/$theme/$b")) {
539 $stamp1 = microtime(true);
540 $content = file_get_contents("$d/theme/$theme/$b");
541 $a->save_timestamp($stamp1, "file");
545 $stamp1 = microtime(true);
546 $content = file_get_contents($s);
547 $a->save_timestamp($stamp1, "file");
553 * load a view template, checking for alternate
554 * languages before falling back to the default
556 * @global string $lang
557 * @param string $s view path
560 function get_intltext_template($s) {
565 if ($a->theme['template_engine'] === 'smarty3') {
566 $engine = "/smarty3";
569 if (! isset($lang)) {
573 if (file_exists("view/lang/$lang$engine/$s")) {
574 $stamp1 = microtime(true);
575 $content = file_get_contents("view/lang/$lang$engine/$s");
576 $a->save_timestamp($stamp1, "file");
578 } elseif (file_exists("view/lang/en$engine/$s")) {
579 $stamp1 = microtime(true);
580 $content = file_get_contents("view/lang/en$engine/$s");
581 $a->save_timestamp($stamp1, "file");
584 $stamp1 = microtime(true);
585 $content = file_get_contents("view$engine/$s");
586 $a->save_timestamp($stamp1, "file");
596 * @param string $root
599 function get_markup_template($s, $root = '') {
600 $stamp1 = microtime(true);
603 $t = $a->template_engine();
605 $template = $t->getTemplateFile($s, $root);
606 } catch (Exception $e) {
607 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
611 $a->save_timestamp($stamp1, "file");
617 * for html,xml parsing - let's say you've got
618 * an attribute foobar="class1 class2 class3"
619 * and you want to find out if it contains 'class3'.
620 * you can't use a normal sub string search because you
621 * might match 'notclass3' and a regex to do the job is
622 * possible but a bit complicated.
623 * pass the attribute string as $attr and the attribute you
624 * are looking for as $s - returns true if found, otherwise false
626 * @param string $attr attribute value
627 * @param string $s string to search
628 * @return boolean True if found, False otherwise
630 function attribute_contains($attr, $s) {
631 $a = explode(' ', $attr);
632 return (count($a) && in_array($s,$a));
636 /* setup int->string log level map */
640 * @brief Logs the given message at the given log level
643 * LOGGER_NORMAL (default)
650 * @global array $LOGGER_LEVELS
654 function logger($msg, $level = 0) {
656 global $LOGGER_LEVELS;
658 // turn off logger in install mode
660 $a->module == 'install'
666 $debugging = Config::get('system','debugging');
667 $logfile = Config::get('system','logfile');
668 $loglevel = intval(Config::get('system','loglevel'));
673 || $level > $loglevel
678 if (count($LOGGER_LEVELS) == 0) {
679 foreach (get_defined_constants() as $k => $v) {
680 if (substr($k, 0, 7) == "LOGGER_") {
681 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
686 $process_id = session_id();
688 if ($process_id == '') {
689 $process_id = get_app()->process_id;
692 $callers = debug_backtrace();
693 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
694 datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
696 $LOGGER_LEVELS[$level],
697 basename($callers[0]['file']),
699 $callers[1]['function'],
703 $stamp1 = microtime(true);
704 @file_put_contents($logfile, $logline, FILE_APPEND);
705 $a->save_timestamp($stamp1, "file");
709 * @brief An alternative logger for development.
710 * Works largely as logger() but allows developers
711 * to isolate particular elements they are targetting
712 * personally without background noise
715 * LOGGER_NORMAL (default)
722 * @global array $LOGGER_LEVELS
727 function dlogger($msg, $level = 0) {
730 // turn off logger in install mode
732 $a->module == 'install'
738 $logfile = Config::get('system','dlogfile');
744 if (count($LOGGER_LEVELS) == 0) {
745 foreach (get_defined_constants() as $k => $v) {
746 if (substr($k, 0, 7) == "LOGGER_") {
747 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
752 $process_id = session_id();
754 if ($process_id == '') {
755 $process_id = get_app()->process_id;
758 $callers = debug_backtrace();
759 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
762 basename($callers[0]['file']),
764 $callers[1]['function'],
768 $stamp1 = microtime(true);
769 @file_put_contents($logfile, $logline, FILE_APPEND);
770 $a->save_timestamp($stamp1, "file");
775 * Compare activity uri. Knows about activity namespace.
777 * @param string $haystack
778 * @param string $needle
781 function activity_match($haystack,$needle) {
782 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
787 * @brief Pull out all #hashtags and @person tags from $string.
789 * We also get @person@domain.com - which would make
790 * the regex quite complicated as tags can also
791 * end a sentence. So we'll run through our results
792 * and strip the period from any tags which end with one.
793 * Returns array of tags found, or empty array.
795 * @param string $string Post content
796 * @return array List of tag and person names
798 function get_tags($string) {
801 // Convert hashtag links to hashtags
802 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
804 // ignore anything in a code block
805 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
807 // Force line feeds at bbtags
808 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
810 // ignore anything in a bbtag
811 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
813 // Match full names against @tags including the space between first and last
814 // We will look these up afterward to see if they are full names or not recognisable.
816 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
817 foreach ($matches[1] as $match) {
818 if (strstr($match, ']')) {
819 // we might be inside a bbcode color tag - leave it alone
822 if (substr($match, -1, 1) === '.') {
823 $ret[] = substr($match, 0, -1);
830 // Otherwise pull out single word tags. These can be @nickname, @first_last
833 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
834 foreach ($matches[1] as $match) {
835 if (strstr($match, ']')) {
836 // we might be inside a bbcode color tag - leave it alone
839 if (substr($match, -1, 1) === '.') {
840 $match = substr($match,0,-1);
842 // ignore strictly numeric tags like #1
843 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
846 // try not to catch url fragments
847 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
858 * quick and dirty quoted_printable encoding
864 return str_replace("%", "=", rawurlencode($s));
869 * Get html for contact block.
871 * @template contact_block.tpl
872 * @hook contact_block_end (contacts=>array, output=>string)
875 function contact_block() {
879 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
884 if (!is_array($a->profile) || $a->profile['hide-friends']) {
887 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
888 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
889 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
890 AND `network` IN ('%s', '%s', '%s')",
891 intval($a->profile['uid']),
893 dbesc(NETWORK_OSTATUS),
894 dbesc(NETWORK_DIASPORA)
896 if (DBM::is_result($r)) {
897 $total = intval($r[0]['total']);
900 $contacts = L10n::t('No contacts');
903 // Splitting the query in two parts makes it much faster
904 $r = q("SELECT `id` FROM `contact`
905 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
906 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
907 AND `network` IN ('%s', '%s', '%s')
908 ORDER BY RAND() LIMIT %d",
909 intval($a->profile['uid']),
911 dbesc(NETWORK_OSTATUS),
912 dbesc(NETWORK_DIASPORA),
915 if (DBM::is_result($r)) {
917 foreach ($r AS $contact) {
918 $contacts[] = $contact["id"];
920 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
921 dbesc(implode(",", $contacts)));
923 if (DBM::is_result($r)) {
924 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
926 foreach ($r as $rr) {
927 $micropro[] = micropro($rr, true, 'mpfriend');
933 $tpl = get_markup_template('contact_block.tpl');
934 $o = replace_macros($tpl, [
935 '$contacts' => $contacts,
936 '$nickname' => $a->profile['nickname'],
937 '$viewcontacts' => L10n::t('View Contacts'),
938 '$micropro' => $micropro,
941 $arr = ['contacts' => $r, 'output' => $o];
943 Addon::callHooks('contact_block_end', $arr);
950 * @brief Format contacts as picture links or as texxt links
952 * @param array $contact Array with contacts which contains an array with
953 * int 'id' => The ID of the contact
954 * int 'uid' => The user ID of the user who owns this data
955 * string 'name' => The name of the contact
956 * string 'url' => The url to the profile page of the contact
957 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
958 * string 'network' => The network to which the contact belongs to
959 * string 'thumb' => The contact picture
960 * string 'click' => js code which is performed when clicking on the contact
961 * @param boolean $redirect If true try to use the redir url if it's possible
962 * @param string $class CSS class for the
963 * @param boolean $textmode If true display the contacts as text links
964 * if false display the contacts as picture links
966 * @return string Formatted html
968 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
970 // Use the contact URL if no address is available
971 if (!x($contact, "addr")) {
972 $contact["addr"] = $contact["url"];
975 $url = $contact['url'];
980 $redirect_url = 'redir/' . $contact['id'];
981 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
983 $url = $redirect_url;
984 $sparkle = ' sparkle';
986 $url = Profile::zrl($url);
990 // If there is some js available we don't need the url
991 if (x($contact, 'click')) {
995 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),[
996 '$click' => defaults($contact, 'click', ''),
999 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1000 '$name' => $contact['name'],
1001 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1002 '$parkle' => $sparkle,
1011 * @param string $s Search query.
1012 * @param string $id HTML id
1013 * @param string $url Search url.
1014 * @param bool $save Show save search button.
1015 * @param bool $aside Display the search widgit aside.
1017 * @return string Formatted HTML.
1019 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
1023 if (strpos($s, '#') === 0) {
1026 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
1029 '$s' => htmlspecialchars($s),
1031 '$action_url' => $url,
1032 '$search_label' => L10n::t('Search'),
1033 '$save_label' => $save_label,
1034 '$savedsearch' => Feature::isEnabled(local_user(),'savedsearch'),
1035 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
1040 $values['$searchoption'] = [
1041 L10n::t("Full Text"),
1043 L10n::t("Contacts")];
1045 if (Config::get('system','poco_local_search')) {
1046 $values['$searchoption'][] = L10n::t("Forums");
1050 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1054 * @brief Check for a valid email string
1056 * @param string $email_address
1059 function valid_email($email_address)
1061 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
1066 * Replace naked text hyperlink with HTML formatted hyperlink
1070 function linkify($s) {
1071 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1072 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1080 * @return array index is present tense verb
1081 value is array containing past tense verb, translation of present, translation of past
1082 * @hook poke_verbs pokes array
1084 function get_poke_verbs() {
1086 // index is present tense verb
1087 // value is array containing past tense verb, translation of present, translation of past
1090 'poke' => ['poked', L10n::t('poke'), L10n::t('poked')],
1091 'ping' => ['pinged', L10n::t('ping'), L10n::t('pinged')],
1092 'prod' => ['prodded', L10n::t('prod'), L10n::t('prodded')],
1093 'slap' => ['slapped', L10n::t('slap'), L10n::t('slapped')],
1094 'finger' => ['fingered', L10n::t('finger'), L10n::t('fingered')],
1095 'rebuff' => ['rebuffed', L10n::t('rebuff'), L10n::t('rebuffed')],
1097 Addon::callHooks('poke_verbs', $arr);
1102 * @brief Translate days and months names.
1104 * @param string $s String with day or month name.
1105 * @return string Translated string.
1107 function day_translate($s) {
1108 $ret = str_replace(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
1109 [L10n::t('Monday'), L10n::t('Tuesday'), L10n::t('Wednesday'), L10n::t('Thursday'), L10n::t('Friday'), L10n::t('Saturday'), L10n::t('Sunday')],
1112 $ret = str_replace(['January','February','March','April','May','June','July','August','September','October','November','December'],
1113 [L10n::t('January'), L10n::t('February'), L10n::t('March'), L10n::t('April'), L10n::t('May'), L10n::t('June'), L10n::t('July'), L10n::t('August'), L10n::t('September'), L10n::t('October'), L10n::t('November'), L10n::t('December')],
1120 * @brief Translate short days and months names.
1122 * @param string $s String with short day or month name.
1123 * @return string Translated string.
1125 function day_short_translate($s) {
1126 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
1127 [L10n::t('Mon'), L10n::t('Tue'), L10n::t('Wed'), L10n::t('Thu'), L10n::t('Fri'), L10n::t('Sat'), L10n::t('Sun')],
1129 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'],
1130 [L10n::t('Jan'), L10n::t('Feb'), L10n::t('Mar'), L10n::t('Apr'), L10n::t('May'), ('Jun'), L10n::t('Jul'), L10n::t('Aug'), L10n::t('Sep'), L10n::t('Oct'), L10n::t('Nov'), L10n::t('Dec')],
1139 * @param string $url
1142 function normalise_link($url) {
1143 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
1144 return rtrim($ret,'/');
1149 * Compare two URLs to see if they are the same, but ignore
1150 * slight but hopefully insignificant differences such as if one
1151 * is https and the other isn't, or if one is www.something and
1152 * the other isn't - and also ignore case differences.
1154 * @param string $a first url
1155 * @param string $b second url
1156 * @return boolean True if the URLs match, otherwise False
1159 function link_compare($a, $b) {
1160 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1165 * @brief Find any non-embedded images in private items and add redir links to them
1168 * @param array &$item The field array of an item row
1170 function redir_private_images($a, &$item)
1173 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1175 foreach ($matches as $mtch) {
1176 if (strpos($mtch[1], '/redir') !== false) {
1180 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1181 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1182 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1188 function put_item_in_cache(&$item, $update = false)
1190 $rendered_hash = defaults($item, 'rendered-hash', '');
1192 if ($rendered_hash == ''
1193 || $item["rendered-html"] == ""
1194 || $rendered_hash != hash("md5", $item["body"])
1195 || Config::get("system", "ignore_cache")
1197 // The function "redir_private_images" changes the body.
1198 // I'm not sure if we should store it permanently, so we save the old value.
1199 $body = $item["body"];
1202 redir_private_images($a, $item);
1204 $item["rendered-html"] = prepare_text($item["body"]);
1205 $item["rendered-hash"] = hash("md5", $item["body"]);
1206 $item["body"] = $body;
1208 if ($update && ($item["id"] > 0)) {
1209 dba::update('item', ['rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]],
1210 ['id' => $item["id"]], false);
1216 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1217 * If attach is true, also add icons for item attachments.
1219 * @param array $item
1220 * @param boolean $attach
1221 * @return string item body html
1222 * @hook prepare_body_init item array before any work
1223 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1224 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1226 function prepare_body(&$item, $attach = false, $preview = false) {
1229 Addon::callHooks('prepare_body_init', $item);
1231 $searchpath = System::baseUrl() . "/search?tag=";
1237 // In order to provide theme developers more possibilities, event items
1238 // are treated differently.
1239 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1240 $ev = format_event_item($item);
1244 if (!Config::get('system','suppress_tags')) {
1245 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1246 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1248 while ($tag = dba::fetch($taglist)) {
1249 if ($tag["url"] == "") {
1250 $tag["url"] = $searchpath.strtolower($tag["term"]);
1253 $orig_tag = $tag["url"];
1255 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1257 if ($tag["type"] == TERM_HASHTAG) {
1258 if ($orig_tag != $tag["url"]) {
1259 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1261 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1263 } elseif ($tag["type"] == TERM_MENTION) {
1264 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1267 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1269 dba::close($taglist);
1272 $item['tags'] = $tags;
1273 $item['hashtags'] = $hashtags;
1274 $item['mentions'] = $mentions;
1276 // Update the cached values if there is no "zrl=..." on the links.
1277 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1279 // Or update it if the current viewer is the intented viewer.
1280 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1284 put_item_in_cache($item, $update);
1285 $s = $item["rendered-html"];
1287 $prep_arr = ['item' => $item, 'html' => $s, 'preview' => $preview];
1288 Addon::callHooks('prepare_body', $prep_arr);
1289 $s = $prep_arr['html'];
1292 // Replace the blockquotes with quotes that are used in mails.
1293 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1294 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
1300 $arr = explode('[/attach],', $item['attach']);
1302 foreach ($arr as $r) {
1305 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1307 foreach ($matches as $mtch) {
1310 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1311 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1313 $the_url = $mtch[1];
1316 if (strpos($mime, 'video') !== false) {
1319 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), [
1320 '$baseurl' => System::baseUrl(),
1322 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), [
1323 '$baseurl' => System::baseUrl(),
1327 $id = end(explode('/', $the_url));
1328 $as .= replace_macros(get_markup_template('video_top.tpl'), [
1331 'title' => L10n::t('View Video'),
1338 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1340 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1341 $filesubtype = str_replace('.', '-', $filesubtype);
1344 $filesubtype = 'unkn';
1347 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1348 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
1350 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1351 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1357 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1361 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1362 $x = Map::byCoordinates(trim($item['coord']));
1364 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1369 // Look for spoiler.
1370 $spoilersearch = '<blockquote class="spoiler">';
1372 // Remove line breaks before the spoiler.
1373 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1374 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1376 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1377 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1380 while ((strpos($s, $spoilersearch) !== false)) {
1381 $pos = strpos($s, $spoilersearch);
1382 $rnd = random_string(8);
1383 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1384 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1385 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1388 // Look for quote with author.
1389 $authorsearch = '<blockquote class="author">';
1391 while ((strpos($s, $authorsearch) !== false)) {
1392 $pos = strpos($s, $authorsearch);
1393 $rnd = random_string(8);
1394 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1395 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1396 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1399 // Replace friendica image url size with theme preference.
1400 if (x($a->theme_info, 'item_image_size')){
1401 $ps = $a->theme_info['item_image_size'];
1402 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1405 $prep_arr = ['item' => $item, 'html' => $s];
1406 Addon::callHooks('prepare_body_final', $prep_arr);
1408 return $prep_arr['html'];
1412 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1414 * @param string $text String with bbcode.
1415 * @return string Formattet HTML.
1417 function prepare_text($text) {
1419 require_once 'include/bbcode.php';
1421 if (stristr($text, '[nosmile]')) {
1424 $s = Smilies::replace(bbcode($text));
1431 * return array with details for categories and folders for an item
1433 * @param array $item
1437 * [ // categories array
1439 * 'name': 'category name',
1440 * 'removeurl': 'url to remove this category',
1441 * 'first': 'is the first in this array? true/false',
1442 * 'last': 'is the last in this array? true/false',
1448 * 'name': 'folder name',
1449 * 'removeurl': 'url to remove this folder',
1450 * 'first': 'is the first in this array? true/false',
1451 * 'last': 'is the last in this array? true/false',
1457 function get_cats_and_terms($item)
1464 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1466 foreach ($matches as $mtch) {
1468 'name' => xmlify(file_tag_decode($mtch[1])),
1470 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1478 if (count($categories)) {
1479 $categories[count($categories) - 1]['last'] = true;
1482 if (local_user() == $item['uid']) {
1485 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1487 foreach ($matches as $mtch) {
1489 'name' => xmlify(file_tag_decode($mtch[1])),
1491 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1500 if (count($folders)) {
1501 $folders[count($folders) - 1]['last'] = true;
1504 return [$categories, $folders];
1509 * get private link for item
1510 * @param array $item
1511 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1513 function get_plink($item) {
1516 if ($a->user['nickname'] != "") {
1518 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1519 'href' => "display/" . $item['guid'],
1520 'orig' => "display/" . $item['guid'],
1521 'title' => L10n::t('View on separate page'),
1522 'orig_title' => L10n::t('view on separate page'),
1525 if (x($item, 'plink')) {
1526 $ret["href"] = $a->remove_baseurl($item['plink']);
1527 $ret["title"] = L10n::t('link to source');
1530 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1532 'href' => $item['plink'],
1533 'orig' => $item['plink'],
1534 'title' => L10n::t('link to source'),
1545 * replace html amp entity with amp char
1549 function unamp($s) {
1550 return str_replace('&', '&', $s);
1555 * return number of bytes in size (K, M, G)
1556 * @param string $size_str
1559 function return_bytes($size_str) {
1560 switch (substr ($size_str, -1)) {
1561 case 'M': case 'm': return (int)$size_str * 1048576;
1562 case 'K': case 'k': return (int)$size_str * 1024;
1563 case 'G': case 'g': return (int)$size_str * 1073741824;
1564 default: return $size_str;
1572 function generate_user_guid() {
1575 $guid = get_guid(32);
1576 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1579 if (! DBM::is_result($x)) {
1582 } while ($found == true);
1590 * @param boolean $strip_padding
1593 function base64url_encode($s, $strip_padding = false) {
1595 $s = strtr(base64_encode($s), '+/', '-_');
1597 if ($strip_padding) {
1598 $s = str_replace('=','',$s);
1608 function base64url_decode($s) {
1611 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1616 * // Placeholder for new rev of salmon which strips base64 padding.
1617 * // PHP base64_decode handles the un-padded input without requiring this step
1618 * // Uncomment if you find you need it.
1621 * if (! strpos($s,'=')) {
1631 return base64_decode(strtr($s,'-_','+/'));
1636 * return div element with class 'clear'
1640 function cleardiv() {
1641 return '<div class="clear"></div>';
1645 function bb_translate_video($s) {
1648 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1650 foreach ($matches as $mtch) {
1651 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1652 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1653 elseif (stristr($mtch[1],'vimeo'))
1654 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1660 function html2bb_video($s) {
1662 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1663 '[youtube]$2[/youtube]', $s);
1665 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1666 '[youtube]$2[/youtube]', $s);
1668 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1669 '[vimeo]$2[/vimeo]', $s);
1675 * apply xmlify() to all values of array $val, recursively
1679 function array_xmlify($val){
1680 if (is_bool($val)) {
1681 return $val?"true":"false";
1682 } elseif (is_array($val)) {
1683 return array_map('array_xmlify', $val);
1685 return xmlify((string) $val);
1690 * transform link href and img src from relative to absolute
1692 * @param string $text
1693 * @param string $base base url
1696 function reltoabs($text, $base) {
1701 $base = rtrim($base,'/');
1703 $base2 = $base . "/";
1706 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1707 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1708 $text = preg_replace($pattern, $replace, $text);
1710 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1711 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1712 $text = preg_replace($pattern, $replace, $text);
1715 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1716 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1717 $text = preg_replace($pattern, $replace, $text);
1719 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1720 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1721 $text = preg_replace($pattern, $replace, $text);
1729 * get translated item type
1731 * @param array $itme
1734 function item_post_type($item) {
1735 if (intval($item['event-id'])) {
1736 return L10n::t('event');
1737 } elseif (strlen($item['resource-id'])) {
1738 return L10n::t('photo');
1739 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1740 return L10n::t('activity');
1741 } elseif ($item['id'] != $item['parent']) {
1742 return L10n::t('comment');
1745 return L10n::t('post');
1748 // post categories and "save to file" use the same item.file table for storage.
1749 // We will differentiate the different uses by wrapping categories in angle brackets
1750 // and save to file categories in square brackets.
1751 // To do this we need to escape these characters if they appear in our tag.
1753 function file_tag_encode($s) {
1754 return str_replace(['<','>','[',']'],['%3c','%3e','%5b','%5d'],$s);
1757 function file_tag_decode($s) {
1758 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
1761 function file_tag_file_query($table,$s,$type = 'file') {
1763 if ($type == 'file') {
1764 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1766 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1768 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1771 // ex. given music,video return <music><video> or [music][video]
1772 function file_tag_list_to_file($list,$type = 'file') {
1774 if (strlen($list)) {
1775 $list_array = explode(",",$list);
1776 if ($type == 'file') {
1784 foreach ($list_array as $item) {
1785 if (strlen($item)) {
1786 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1793 // ex. given <music><video>[friends], return music,video or friends
1794 function file_tag_file_to_list($file,$type = 'file') {
1797 if ($type == 'file') {
1798 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1800 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1803 foreach ($matches as $mtch) {
1804 if (strlen($list)) {
1807 $list .= file_tag_decode($mtch[1]);
1814 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1815 // $file_old - categories previously associated with an item
1816 // $file_new - new list of categories for an item
1818 if (!intval($uid)) {
1821 if ($file_old == $file_new) {
1825 $saved = PConfig::get($uid, 'system', 'filetags');
1826 if (strlen($saved)) {
1827 if ($type == 'file') {
1830 $termtype = TERM_FILE;
1834 $termtype = TERM_CATEGORY;
1837 $filetags_updated = $saved;
1839 // check for new tags to be added as filetags in pconfig
1841 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1843 foreach ($check_new_tags as $tag) {
1844 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1848 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1850 // check for deleted tags to be removed from filetags in pconfig
1852 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1854 foreach ($check_deleted_tags as $tag) {
1855 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1856 $deleted_tags[] = $tag;
1859 foreach ($deleted_tags as $key => $tag) {
1860 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1862 intval(TERM_OBJ_POST),
1866 if (DBM::is_result($r)) {
1867 unset($deleted_tags[$key]);
1869 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1873 if ($saved != $filetags_updated) {
1874 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1877 } elseif (strlen($file_new)) {
1878 PConfig::set($uid, 'system', 'filetags', $file_new);
1883 function file_tag_save_file($uid, $item, $file)
1885 if (! intval($uid)) {
1889 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1893 if (DBM::is_result($r)) {
1894 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1895 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1896 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1902 Term::createFromItem($item);
1904 $saved = PConfig::get($uid, 'system', 'filetags');
1905 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1906 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1908 info(L10n::t('Item filed'));
1913 function file_tag_unsave_file($uid, $item, $file, $cat = false)
1915 if (! intval($uid)) {
1920 $pattern = '<' . file_tag_encode($file) . '>' ;
1921 $termtype = TERM_CATEGORY;
1923 $pattern = '[' . file_tag_encode($file) . ']' ;
1924 $termtype = TERM_FILE;
1927 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1931 if (! DBM::is_result($r)) {
1935 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1936 dbesc(str_replace($pattern,'',$r[0]['file'])),
1941 Term::createFromItem($item);
1943 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1945 intval(TERM_OBJ_POST),
1949 if (!DBM::is_result($r)) {
1950 $saved = PConfig::get($uid, 'system', 'filetags');
1951 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1957 function normalise_openid($s) {
1958 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
1962 function undo_post_tagging($s) {
1964 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1966 foreach ($matches as $mtch) {
1967 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1973 function protect_sprintf($s) {
1974 return str_replace('%', '%%', $s);
1978 function is_a_date_arg($s) {
1982 if ($i <= $y + 1 && strpos($s, '-') == 4) {
1983 $m = intval(substr($s,5));
1984 if ($m > 0 && $m <= 12)
1992 * remove intentation from a text
1994 function deindent($text, $chr = "[\t ]", $count = NULL) {
1995 $lines = explode("\n", $text);
1996 if (is_null($count)) {
1999 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2002 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2003 $count = strlen($m[0]);
2005 for ($k = 0; $k < count($lines); $k++) {
2006 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2009 return implode("\n", $lines);
2012 function formatBytes($bytes, $precision = 2) {
2013 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
2015 $bytes = max($bytes, 0);
2016 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2017 $pow = min($pow, count($units) - 1);
2019 $bytes /= pow(1024, $pow);
2021 return round($bytes, $precision) . ' ' . $units[$pow];
2025 * @brief translate and format the networkname of a contact
2027 * @param string $network
2028 * Networkname of the contact (e.g. dfrn, rss and so on)
2033 function format_network_name($network, $url = 0) {
2034 if ($network != "") {
2036 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
2038 $network_name = ContactSelector::networkToName($network);
2041 return $network_name;
2046 * @brief Syntax based code highlighting for popular languages.
2047 * @param string $s Code block
2048 * @param string $lang Programming language
2049 * @return string Formated html
2051 function text_highlight($s, $lang) {
2052 if ($lang === 'js') {
2053 $lang = 'javascript';
2056 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2058 // Autoload the library to make constants available
2059 class_exists('Text_Highlighter_Renderer_Html');
2062 'numbers' => HL_NUMBERS_LI,
2067 $s = trim(html_entity_decode($s, ENT_COMPAT));
2068 $s = str_replace(' ', "\t", $s);
2071 * The highlighter library insists on an opening php tag for php code blocks. If
2072 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2073 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2075 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2076 $s = '<?php' . "\n" . $s;
2080 $renderer = new Text_Highlighter_Renderer_Html($options);
2081 $factory = new Text_Highlighter();
2082 $hl = $factory->factory($lang);
2083 $hl->setRenderer($renderer);
2084 $o = $hl->highlight($s);
2085 $o = str_replace("\n", '', $o);
2088 $b = substr($o, 0, strpos($o, '<li>'));
2089 $e = substr($o, strpos($o, '</li>'));
2093 return '<code>' . $o . '</code>';