3 * @file include/text.php
7 use Friendica\Content\ContactSelector;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Smilies;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Item;
18 use Friendica\Model\Profile;
19 use Friendica\Render\FriendicaSmarty;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Map;
23 require_once "mod/proxy.php";
24 require_once "include/event.php";
25 require_once "include/conversation.php";
28 * This is our template processor
30 * @param string|FriendicaSmarty $s the string requiring macro substitution,
31 * or an instance of FriendicaSmarty
32 * @param array $r key value pairs (search => replace)
33 * @return string substituted string
35 function replace_macros($s, $r) {
37 $stamp1 = microtime(true);
41 // pass $baseurl to all templates
42 $r['$baseurl'] = System::baseUrl();
44 $t = $a->template_engine();
46 $output = $t->replaceMacros($s, $r);
47 } catch (Exception $e) {
48 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
52 $a->save_timestamp($stamp1, "rendering");
58 * @brief Generates a pseudo-random string of hexadecimal characters
63 function random_string($size = 64)
65 $byte_size = ceil($size / 2);
67 $bytes = random_bytes($byte_size);
69 $return = substr(bin2hex($bytes), 0, $size);
75 * This is our primary input filter.
77 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
78 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
79 * after cleansing, and angle chars with the high bit set could get through as markup.
81 * This is now disabled because it was interfering with some legitimate unicode sequences
82 * and hopefully there aren't a lot of those browsers left.
84 * Use this on any text input where angle chars are not valid or permitted
85 * They will be replaced with safer brackets. This may be filtered further
86 * if these are not allowed either.
88 * @param string $string Input string
89 * @return string Filtered string
91 function notags($string) {
92 return str_replace(["<", ">"], ['[', ']'], $string);
94 // High-bit filter no longer used
95 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
100 * use this on "body" or "content" input where angle chars shouldn't be removed,
101 * and allow them to be safely displayed.
102 * @param string $string
105 function escape_tags($string) {
106 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
111 * generate a string that's random, but usually pronounceable.
112 * used to generate initial passwords
116 function autoname($len) {
122 $vowels = ['a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'];
123 if (mt_rand(0, 5) == 4) {
142 's','sc','sh','sm','sp','st',
150 $midcons = ['ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
151 'nd','ng','nk','nt','rn','rp','rt'];
153 $noend = ['bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
154 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh'];
156 $start = mt_rand(0,2);
165 for ($x = 0; $x < $len; $x ++) {
166 $r = mt_rand(0,count($table) - 1);
169 if ($table == $vowels) {
170 $table = array_merge($cons,$midcons);
177 $word = substr($word,0,$len);
179 foreach ($noend as $noe) {
180 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
181 $word = substr($word, 0, -1);
185 if (substr($word, -1) == 'q') {
186 $word = substr($word, 0, -1);
193 * escape text ($str) for XML transport
195 * @return string Escaped text.
197 function xmlify($str) {
198 /// @TODO deprecated code found?
201 $len = mb_strlen($str);
202 for ($x = 0; $x < $len; $x ++) {
203 $char = mb_substr($str,$x,1);
233 $buffer = mb_ereg_replace("&", "&", $str);
234 $buffer = mb_ereg_replace("'", "'", $buffer);
235 $buffer = mb_ereg_replace('"', """, $buffer);
236 $buffer = mb_ereg_replace("<", "<", $buffer);
237 $buffer = mb_ereg_replace(">", ">", $buffer);
239 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
240 $buffer = trim($buffer);
248 * @param string $s xml escaped text
249 * @return string unescaped text
251 function unxmlify($s) {
252 /// @TODO deprecated code found?
253 // $ret = str_replace('&','&', $s);
254 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
255 /*$ret = mb_ereg_replace('&', '&', $s);
256 $ret = mb_ereg_replace(''', "'", $ret);
257 $ret = mb_ereg_replace('"', '"', $ret);
258 $ret = mb_ereg_replace('<', "<", $ret);
259 $ret = mb_ereg_replace('>', ">", $ret);
261 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
267 * @brief Paginator function. Pushes relevant links in a pager array structure.
269 * Links are generated depending on the current page and the total number of items.
270 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
271 * Current page link is given the "active" CSS class
273 * @param App $a App instance
274 * @param int $count [optional] item count (used with minimal pager)
275 * @return Array data for pagination template
277 function paginate_data(App $a, $count = null) {
278 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
280 $stripped = str_replace('q=', '', $stripped);
281 $stripped = trim($stripped, '/');
282 $pagenum = $a->pager['page'];
284 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
285 $stripped .= '&offset=' . urlencode($a->page_offset);
291 function _l(&$d, $name, $url, $text, $class = '') {
292 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
293 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
296 $d[$name] = ['url' => $url, 'text' => $text, 'class' => $class];
299 if (!is_null($count)) {
300 // minimal pager (newer / older)
301 $data['class'] = 'pager';
302 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
303 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
305 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
306 $data['class'] = 'pagination';
307 if ($a->pager['total'] > $a->pager['itemspage']) {
308 _l($data, 'first', $url . '&page=1', L10n::t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
309 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
311 $numpages = $a->pager['total'] / $a->pager['itemspage'];
314 $numstop = $numpages;
316 // Limit the number of displayed page number buttons.
318 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
319 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
324 for ($i = $numstart; $i <= $numstop; $i++) {
325 if ($i == $a->pager['page']) {
326 _l($pages, $i, '#', $i, 'current active');
328 _l($pages, $i, $url . '&page='. $i, $i, 'n');
332 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
333 if ($i == $a->pager['page']) {
334 _l($pages, $i, '#', $i, 'current active');
336 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
340 $data['pages'] = $pages;
342 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
343 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
344 _l($data, 'last', $url . '&page=' . $lastpage, L10n::t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
353 * Automatic pagination.
355 * To use, get the count of total items.
356 * Then call $a->set_pager_total($number_items);
357 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
358 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
359 * (assuming there are enough items to paginate).
360 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
361 * will limit the results to the correct items for the current page.
362 * The actual page handling is then accomplished at the application layer.
364 * @param App $a App instance
365 * @return string html for pagination #FIXME remove html
367 function paginate(App $a) {
369 $data = paginate_data($a);
370 $tpl = get_markup_template("paginate.tpl");
371 return replace_macros($tpl, ["pager" => $data]);
378 * @param App $a App instance
380 * @return string html for pagination #FIXME remove html
382 function alt_pager(App $a, $i) {
384 $data = paginate_data($a, $i);
385 $tpl = get_markup_template("paginate.tpl");
386 return replace_macros($tpl, ['pager' => $data]);
392 * Loader for infinite scrolling
393 * @return string html for loader
395 function scroll_loader() {
396 $tpl = get_markup_template("scroll_loader.tpl");
397 return replace_macros($tpl, [
398 'wait' => L10n::t('Loading more entries...'),
399 'end' => L10n::t('The end')
405 * Turn user/group ACLs stored as angle bracketed text into arrays
410 function expand_acl($s) {
411 // turn string array of angle-bracketed elements into numeric array
412 // e.g. "<1><2><3>" => array(1,2,3);
416 $t = str_replace('<', '', $s);
417 $a = explode('>', $t);
418 foreach ($a as $aa) {
420 $ret[] = intval($aa);
429 * Wrap ACL elements in angle brackets for storage
430 * @param string $item
432 function sanitise_acl(&$item) {
434 $item = '<' . intval(notags(trim($item))) . '>';
442 * Convert an ACL array to a storable string
444 * Normally ACL permissions will be an array.
445 * We'll also allow a comma-separated string.
447 * @param string|array $p
450 function perms2str($p) {
455 $tmp = explode(',',$p);
458 if (is_array($tmp)) {
459 array_walk($tmp, 'sanitise_acl');
460 $ret = implode('', $tmp);
467 * generate a guaranteed unique (for this domain) item ID for ATOM
468 * safe from birthday paradox
470 * @param string $hostname
474 function item_new_uri($hostname, $uid, $guid = "") {
478 $hash = get_guid(32);
484 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
486 $dups = dba::exists('item', ['uri' => $uri]);
487 } while ($dups == true);
494 * wrapper to load a view template, checking for alternate
495 * languages before falling back to the default
497 * @global string $lang
499 * @param string $s view name
502 function load_view_file($s) {
504 if (! isset($lang)) {
509 if (file_exists("$d/$lang/$b")) {
510 $stamp1 = microtime(true);
511 $content = file_get_contents("$d/$lang/$b");
512 $a->save_timestamp($stamp1, "file");
516 $theme = current_theme();
518 if (file_exists("$d/theme/$theme/$b")) {
519 $stamp1 = microtime(true);
520 $content = file_get_contents("$d/theme/$theme/$b");
521 $a->save_timestamp($stamp1, "file");
525 $stamp1 = microtime(true);
526 $content = file_get_contents($s);
527 $a->save_timestamp($stamp1, "file");
533 * load a view template, checking for alternate
534 * languages before falling back to the default
536 * @global string $lang
537 * @param string $s view path
540 function get_intltext_template($s) {
545 if ($a->theme['template_engine'] === 'smarty3') {
546 $engine = "/smarty3";
549 if (! isset($lang)) {
553 if (file_exists("view/lang/$lang$engine/$s")) {
554 $stamp1 = microtime(true);
555 $content = file_get_contents("view/lang/$lang$engine/$s");
556 $a->save_timestamp($stamp1, "file");
558 } elseif (file_exists("view/lang/en$engine/$s")) {
559 $stamp1 = microtime(true);
560 $content = file_get_contents("view/lang/en$engine/$s");
561 $a->save_timestamp($stamp1, "file");
564 $stamp1 = microtime(true);
565 $content = file_get_contents("view$engine/$s");
566 $a->save_timestamp($stamp1, "file");
576 * @param string $root
579 function get_markup_template($s, $root = '') {
580 $stamp1 = microtime(true);
583 $t = $a->template_engine();
585 $template = $t->getTemplateFile($s, $root);
586 } catch (Exception $e) {
587 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
591 $a->save_timestamp($stamp1, "file");
597 * for html,xml parsing - let's say you've got
598 * an attribute foobar="class1 class2 class3"
599 * and you want to find out if it contains 'class3'.
600 * you can't use a normal sub string search because you
601 * might match 'notclass3' and a regex to do the job is
602 * possible but a bit complicated.
603 * pass the attribute string as $attr and the attribute you
604 * are looking for as $s - returns true if found, otherwise false
606 * @param string $attr attribute value
607 * @param string $s string to search
608 * @return boolean True if found, False otherwise
610 function attribute_contains($attr, $s) {
611 $a = explode(' ', $attr);
612 return (count($a) && in_array($s,$a));
616 /* setup int->string log level map */
620 * @brief Logs the given message at the given log level
623 * LOGGER_NORMAL (default)
630 * @global array $LOGGER_LEVELS
634 function logger($msg, $level = 0) {
636 global $LOGGER_LEVELS;
638 // turn off logger in install mode
640 $a->module == 'install'
646 $debugging = Config::get('system','debugging');
647 $logfile = Config::get('system','logfile');
648 $loglevel = intval(Config::get('system','loglevel'));
653 || $level > $loglevel
658 if (count($LOGGER_LEVELS) == 0) {
659 foreach (get_defined_constants() as $k => $v) {
660 if (substr($k, 0, 7) == "LOGGER_") {
661 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
666 $process_id = session_id();
668 if ($process_id == '') {
669 $process_id = get_app()->process_id;
672 $callers = debug_backtrace();
673 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
674 DateTimeFormat::utcNow(DateTimeFormat::ATOM),
676 $LOGGER_LEVELS[$level],
677 basename($callers[0]['file']),
679 $callers[1]['function'],
683 $stamp1 = microtime(true);
684 @file_put_contents($logfile, $logline, FILE_APPEND);
685 $a->save_timestamp($stamp1, "file");
689 * @brief An alternative logger for development.
690 * Works largely as logger() but allows developers
691 * to isolate particular elements they are targetting
692 * personally without background noise
695 * LOGGER_NORMAL (default)
702 * @global array $LOGGER_LEVELS
707 function dlogger($msg, $level = 0) {
710 // turn off logger in install mode
712 $a->module == 'install'
718 $logfile = Config::get('system', 'dlogfile');
723 $dlogip = Config::get('system', 'dlogip');
724 if (!is_null($dlogip) && $_SERVER['REMOTE_ADDR'] != $dlogip) {
728 if (count($LOGGER_LEVELS) == 0) {
729 foreach (get_defined_constants() as $k => $v) {
730 if (substr($k, 0, 7) == "LOGGER_") {
731 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
736 $process_id = session_id();
738 if ($process_id == '') {
739 $process_id = get_app()->process_id;
742 $callers = debug_backtrace();
743 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
744 DateTimeFormat::utcNow(),
746 basename($callers[0]['file']),
748 $callers[1]['function'],
752 $stamp1 = microtime(true);
753 @file_put_contents($logfile, $logline, FILE_APPEND);
754 $a->save_timestamp($stamp1, "file");
759 * Compare activity uri. Knows about activity namespace.
761 * @param string $haystack
762 * @param string $needle
765 function activity_match($haystack,$needle) {
766 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
771 * @brief Pull out all #hashtags and @person tags from $string.
773 * We also get @person@domain.com - which would make
774 * the regex quite complicated as tags can also
775 * end a sentence. So we'll run through our results
776 * and strip the period from any tags which end with one.
777 * Returns array of tags found, or empty array.
779 * @param string $string Post content
780 * @return array List of tag and person names
782 function get_tags($string) {
785 // Convert hashtag links to hashtags
786 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
788 // ignore anything in a code block
789 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
791 // Force line feeds at bbtags
792 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
794 // ignore anything in a bbtag
795 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
797 // Match full names against @tags including the space between first and last
798 // We will look these up afterward to see if they are full names or not recognisable.
800 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
801 foreach ($matches[1] as $match) {
802 if (strstr($match, ']')) {
803 // we might be inside a bbcode color tag - leave it alone
806 if (substr($match, -1, 1) === '.') {
807 $ret[] = substr($match, 0, -1);
814 // Otherwise pull out single word tags. These can be @nickname, @first_last
817 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
818 foreach ($matches[1] as $match) {
819 if (strstr($match, ']')) {
820 // we might be inside a bbcode color tag - leave it alone
823 if (substr($match, -1, 1) === '.') {
824 $match = substr($match,0,-1);
826 // ignore strictly numeric tags like #1
827 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
830 // try not to catch url fragments
831 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
842 * quick and dirty quoted_printable encoding
848 return str_replace("%", "=", rawurlencode($s));
853 * Get html for contact block.
855 * @template contact_block.tpl
856 * @hook contact_block_end (contacts=>array, output=>string)
859 function contact_block() {
863 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
868 if (!is_array($a->profile) || $a->profile['hide-friends']) {
871 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
872 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
873 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
874 AND `network` IN ('%s', '%s', '%s')",
875 intval($a->profile['uid']),
877 dbesc(NETWORK_OSTATUS),
878 dbesc(NETWORK_DIASPORA)
880 if (DBM::is_result($r)) {
881 $total = intval($r[0]['total']);
884 $contacts = L10n::t('No contacts');
887 // Splitting the query in two parts makes it much faster
888 $r = q("SELECT `id` FROM `contact`
889 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
890 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
891 AND `network` IN ('%s', '%s', '%s')
892 ORDER BY RAND() LIMIT %d",
893 intval($a->profile['uid']),
895 dbesc(NETWORK_OSTATUS),
896 dbesc(NETWORK_DIASPORA),
899 if (DBM::is_result($r)) {
901 foreach ($r AS $contact) {
902 $contacts[] = $contact["id"];
904 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
905 dbesc(implode(",", $contacts)));
907 if (DBM::is_result($r)) {
908 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
910 foreach ($r as $rr) {
911 $micropro[] = micropro($rr, true, 'mpfriend');
917 $tpl = get_markup_template('contact_block.tpl');
918 $o = replace_macros($tpl, [
919 '$contacts' => $contacts,
920 '$nickname' => $a->profile['nickname'],
921 '$viewcontacts' => L10n::t('View Contacts'),
922 '$micropro' => $micropro,
925 $arr = ['contacts' => $r, 'output' => $o];
927 Addon::callHooks('contact_block_end', $arr);
934 * @brief Format contacts as picture links or as texxt links
936 * @param array $contact Array with contacts which contains an array with
937 * int 'id' => The ID of the contact
938 * int 'uid' => The user ID of the user who owns this data
939 * string 'name' => The name of the contact
940 * string 'url' => The url to the profile page of the contact
941 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
942 * string 'network' => The network to which the contact belongs to
943 * string 'thumb' => The contact picture
944 * string 'click' => js code which is performed when clicking on the contact
945 * @param boolean $redirect If true try to use the redir url if it's possible
946 * @param string $class CSS class for the
947 * @param boolean $textmode If true display the contacts as text links
948 * if false display the contacts as picture links
950 * @return string Formatted html
952 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
954 // Use the contact URL if no address is available
955 if (!x($contact, "addr")) {
956 $contact["addr"] = $contact["url"];
959 $url = $contact['url'];
964 $redirect_url = 'redir/' . $contact['id'];
965 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
967 $url = $redirect_url;
968 $sparkle = ' sparkle';
970 $url = Profile::zrl($url);
974 // If there is some js available we don't need the url
975 if (x($contact, 'click')) {
979 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),[
980 '$click' => defaults($contact, 'click', ''),
983 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
984 '$name' => $contact['name'],
985 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
986 '$parkle' => $sparkle,
995 * @param string $s Search query.
996 * @param string $id HTML id
997 * @param string $url Search url.
998 * @param bool $save Show save search button.
999 * @param bool $aside Display the search widgit aside.
1001 * @return string Formatted HTML.
1003 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
1007 if (strpos($s, '#') === 0) {
1010 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
1013 '$s' => htmlspecialchars($s),
1015 '$action_url' => $url,
1016 '$search_label' => L10n::t('Search'),
1017 '$save_label' => $save_label,
1018 '$savedsearch' => Feature::isEnabled(local_user(),'savedsearch'),
1019 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
1024 $values['$searchoption'] = [
1025 L10n::t("Full Text"),
1027 L10n::t("Contacts")];
1029 if (Config::get('system','poco_local_search')) {
1030 $values['$searchoption'][] = L10n::t("Forums");
1034 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1038 * @brief Check for a valid email string
1040 * @param string $email_address
1043 function valid_email($email_address)
1045 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
1050 * Replace naked text hyperlink with HTML formatted hyperlink
1054 function linkify($s) {
1055 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1056 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1064 * @return array index is present tense verb
1065 value is array containing past tense verb, translation of present, translation of past
1066 * @hook poke_verbs pokes array
1068 function get_poke_verbs() {
1070 // index is present tense verb
1071 // value is array containing past tense verb, translation of present, translation of past
1074 'poke' => ['poked', L10n::t('poke'), L10n::t('poked')],
1075 'ping' => ['pinged', L10n::t('ping'), L10n::t('pinged')],
1076 'prod' => ['prodded', L10n::t('prod'), L10n::t('prodded')],
1077 'slap' => ['slapped', L10n::t('slap'), L10n::t('slapped')],
1078 'finger' => ['fingered', L10n::t('finger'), L10n::t('fingered')],
1079 'rebuff' => ['rebuffed', L10n::t('rebuff'), L10n::t('rebuffed')],
1081 Addon::callHooks('poke_verbs', $arr);
1086 * @brief Translate days and months names.
1088 * @param string $s String with day or month name.
1089 * @return string Translated string.
1091 function day_translate($s) {
1092 $ret = str_replace(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
1093 [L10n::t('Monday'), L10n::t('Tuesday'), L10n::t('Wednesday'), L10n::t('Thursday'), L10n::t('Friday'), L10n::t('Saturday'), L10n::t('Sunday')],
1096 $ret = str_replace(['January','February','March','April','May','June','July','August','September','October','November','December'],
1097 [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')],
1104 * @brief Translate short days and months names.
1106 * @param string $s String with short day or month name.
1107 * @return string Translated string.
1109 function day_short_translate($s) {
1110 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
1111 [L10n::t('Mon'), L10n::t('Tue'), L10n::t('Wed'), L10n::t('Thu'), L10n::t('Fri'), L10n::t('Sat'), L10n::t('Sun')],
1113 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'],
1114 [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')],
1123 * @param string $url
1126 function normalise_link($url) {
1127 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
1128 return rtrim($ret,'/');
1133 * Compare two URLs to see if they are the same, but ignore
1134 * slight but hopefully insignificant differences such as if one
1135 * is https and the other isn't, or if one is www.something and
1136 * the other isn't - and also ignore case differences.
1138 * @param string $a first url
1139 * @param string $b second url
1140 * @return boolean True if the URLs match, otherwise False
1143 function link_compare($a, $b) {
1144 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1149 * @brief Find any non-embedded images in private items and add redir links to them
1152 * @param array &$item The field array of an item row
1154 function redir_private_images($a, &$item)
1157 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1159 foreach ($matches as $mtch) {
1160 if (strpos($mtch[1], '/redir') !== false) {
1164 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1165 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1166 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1172 function put_item_in_cache(&$item, $update = false)
1174 $rendered_hash = defaults($item, 'rendered-hash', '');
1176 if ($rendered_hash == ''
1177 || $item["rendered-html"] == ""
1178 || $rendered_hash != hash("md5", $item["body"])
1179 || Config::get("system", "ignore_cache")
1181 // The function "redir_private_images" changes the body.
1182 // I'm not sure if we should store it permanently, so we save the old value.
1183 $body = $item["body"];
1186 redir_private_images($a, $item);
1188 $item["rendered-html"] = prepare_text($item["body"]);
1189 $item["rendered-hash"] = hash("md5", $item["body"]);
1190 $item["body"] = $body;
1192 if ($update && ($item["id"] > 0)) {
1193 dba::update('item', ['rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]],
1194 ['id' => $item["id"]], false);
1200 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1201 * If attach is true, also add icons for item attachments.
1203 * @param array $item
1204 * @param boolean $attach
1205 * @return string item body html
1206 * @hook prepare_body_init item array before any work
1207 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1208 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1210 function prepare_body(&$item, $attach = false, $preview = false) {
1213 Addon::callHooks('prepare_body_init', $item);
1215 $searchpath = System::baseUrl() . "/search?tag=";
1221 // In order to provide theme developers more possibilities, event items
1222 // are treated differently.
1223 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1224 $ev = format_event_item($item);
1228 if (!Config::get('system','suppress_tags')) {
1229 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1230 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1232 while ($tag = dba::fetch($taglist)) {
1233 if ($tag["url"] == "") {
1234 $tag["url"] = $searchpath.strtolower($tag["term"]);
1237 $orig_tag = $tag["url"];
1239 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1241 if ($tag["type"] == TERM_HASHTAG) {
1242 if ($orig_tag != $tag["url"]) {
1243 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1245 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1247 } elseif ($tag["type"] == TERM_MENTION) {
1248 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1251 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1253 dba::close($taglist);
1256 $item['tags'] = $tags;
1257 $item['hashtags'] = $hashtags;
1258 $item['mentions'] = $mentions;
1260 // Update the cached values if there is no "zrl=..." on the links.
1261 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1263 // Or update it if the current viewer is the intented viewer.
1264 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1268 put_item_in_cache($item, $update);
1269 $s = $item["rendered-html"];
1271 $prep_arr = ['item' => $item, 'html' => $s, 'preview' => $preview];
1272 Addon::callHooks('prepare_body', $prep_arr);
1273 $s = $prep_arr['html'];
1276 // Replace the blockquotes with quotes that are used in mails.
1277 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1278 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
1284 $arr = explode('[/attach],', $item['attach']);
1286 foreach ($arr as $r) {
1289 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1291 foreach ($matches as $mtch) {
1294 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1295 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1297 $the_url = $mtch[1];
1300 if (strpos($mime, 'video') !== false) {
1303 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), [
1304 '$baseurl' => System::baseUrl(),
1306 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), [
1307 '$baseurl' => System::baseUrl(),
1311 $id = end(explode('/', $the_url));
1312 $as .= replace_macros(get_markup_template('video_top.tpl'), [
1315 'title' => L10n::t('View Video'),
1322 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1324 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1325 $filesubtype = str_replace('.', '-', $filesubtype);
1328 $filesubtype = 'unkn';
1331 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1332 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
1334 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1335 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1341 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1345 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1346 $x = Map::byCoordinates(trim($item['coord']));
1348 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1353 // Look for spoiler.
1354 $spoilersearch = '<blockquote class="spoiler">';
1356 // Remove line breaks before the spoiler.
1357 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1358 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1360 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1361 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1364 while ((strpos($s, $spoilersearch) !== false)) {
1365 $pos = strpos($s, $spoilersearch);
1366 $rnd = random_string(8);
1367 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1368 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1369 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1372 // Look for quote with author.
1373 $authorsearch = '<blockquote class="author">';
1375 while ((strpos($s, $authorsearch) !== false)) {
1376 $pos = strpos($s, $authorsearch);
1377 $rnd = random_string(8);
1378 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1379 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1380 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1383 // Replace friendica image url size with theme preference.
1384 if (x($a->theme_info, 'item_image_size')){
1385 $ps = $a->theme_info['item_image_size'];
1386 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1389 $prep_arr = ['item' => $item, 'html' => $s];
1390 Addon::callHooks('prepare_body_final', $prep_arr);
1392 return $prep_arr['html'];
1396 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1398 * @param string $text String with bbcode.
1399 * @return string Formattet HTML.
1401 function prepare_text($text) {
1402 if (stristr($text, '[nosmile]')) {
1403 $s = BBCode::convert($text);
1405 $s = Smilies::replace(BBCode::convert($text));
1412 * return array with details for categories and folders for an item
1414 * @param array $item
1418 * [ // categories array
1420 * 'name': 'category name',
1421 * 'removeurl': 'url to remove this category',
1422 * 'first': 'is the first in this array? true/false',
1423 * 'last': 'is the last in this array? true/false',
1429 * 'name': 'folder name',
1430 * 'removeurl': 'url to remove this folder',
1431 * 'first': 'is the first in this array? true/false',
1432 * 'last': 'is the last in this array? true/false',
1438 function get_cats_and_terms($item)
1445 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1447 foreach ($matches as $mtch) {
1449 'name' => xmlify(file_tag_decode($mtch[1])),
1451 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1459 if (count($categories)) {
1460 $categories[count($categories) - 1]['last'] = true;
1463 if (local_user() == $item['uid']) {
1466 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1468 foreach ($matches as $mtch) {
1470 'name' => xmlify(file_tag_decode($mtch[1])),
1472 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1481 if (count($folders)) {
1482 $folders[count($folders) - 1]['last'] = true;
1485 return [$categories, $folders];
1490 * get private link for item
1491 * @param array $item
1492 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1494 function get_plink($item) {
1497 if ($a->user['nickname'] != "") {
1499 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1500 'href' => "display/" . $item['guid'],
1501 'orig' => "display/" . $item['guid'],
1502 'title' => L10n::t('View on separate page'),
1503 'orig_title' => L10n::t('view on separate page'),
1506 if (x($item, 'plink')) {
1507 $ret["href"] = $a->remove_baseurl($item['plink']);
1508 $ret["title"] = L10n::t('link to source');
1511 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1513 'href' => $item['plink'],
1514 'orig' => $item['plink'],
1515 'title' => L10n::t('link to source'),
1526 * replace html amp entity with amp char
1530 function unamp($s) {
1531 return str_replace('&', '&', $s);
1536 * return number of bytes in size (K, M, G)
1537 * @param string $size_str
1540 function return_bytes($size_str) {
1541 switch (substr ($size_str, -1)) {
1542 case 'M': case 'm': return (int)$size_str * 1048576;
1543 case 'K': case 'k': return (int)$size_str * 1024;
1544 case 'G': case 'g': return (int)$size_str * 1073741824;
1545 default: return $size_str;
1553 function generate_user_guid() {
1556 $guid = get_guid(32);
1557 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1560 if (! DBM::is_result($x)) {
1563 } while ($found == true);
1571 * @param boolean $strip_padding
1574 function base64url_encode($s, $strip_padding = false) {
1576 $s = strtr(base64_encode($s), '+/', '-_');
1578 if ($strip_padding) {
1579 $s = str_replace('=','',$s);
1589 function base64url_decode($s) {
1592 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1597 * // Placeholder for new rev of salmon which strips base64 padding.
1598 * // PHP base64_decode handles the un-padded input without requiring this step
1599 * // Uncomment if you find you need it.
1602 * if (! strpos($s,'=')) {
1612 return base64_decode(strtr($s,'-_','+/'));
1617 * return div element with class 'clear'
1621 function cleardiv() {
1622 return '<div class="clear"></div>';
1626 function bb_translate_video($s) {
1629 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1631 foreach ($matches as $mtch) {
1632 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1633 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1634 elseif (stristr($mtch[1],'vimeo'))
1635 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1641 function html2bb_video($s) {
1643 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1644 '[youtube]$2[/youtube]', $s);
1646 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1647 '[youtube]$2[/youtube]', $s);
1649 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1650 '[vimeo]$2[/vimeo]', $s);
1656 * apply xmlify() to all values of array $val, recursively
1660 function array_xmlify($val){
1661 if (is_bool($val)) {
1662 return $val?"true":"false";
1663 } elseif (is_array($val)) {
1664 return array_map('array_xmlify', $val);
1666 return xmlify((string) $val);
1671 * transform link href and img src from relative to absolute
1673 * @param string $text
1674 * @param string $base base url
1677 function reltoabs($text, $base) {
1682 $base = rtrim($base,'/');
1684 $base2 = $base . "/";
1687 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1688 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1689 $text = preg_replace($pattern, $replace, $text);
1691 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1692 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1693 $text = preg_replace($pattern, $replace, $text);
1696 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1697 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1698 $text = preg_replace($pattern, $replace, $text);
1700 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1701 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1702 $text = preg_replace($pattern, $replace, $text);
1710 * get translated item type
1712 * @param array $itme
1715 function item_post_type($item) {
1716 if (intval($item['event-id'])) {
1717 return L10n::t('event');
1718 } elseif (strlen($item['resource-id'])) {
1719 return L10n::t('photo');
1720 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1721 return L10n::t('activity');
1722 } elseif ($item['id'] != $item['parent']) {
1723 return L10n::t('comment');
1726 return L10n::t('post');
1729 // post categories and "save to file" use the same item.file table for storage.
1730 // We will differentiate the different uses by wrapping categories in angle brackets
1731 // and save to file categories in square brackets.
1732 // To do this we need to escape these characters if they appear in our tag.
1734 function file_tag_encode($s) {
1735 return str_replace(['<','>','[',']'],['%3c','%3e','%5b','%5d'],$s);
1738 function file_tag_decode($s) {
1739 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
1742 function file_tag_file_query($table,$s,$type = 'file') {
1744 if ($type == 'file') {
1745 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1747 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1749 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1752 // ex. given music,video return <music><video> or [music][video]
1753 function file_tag_list_to_file($list,$type = 'file') {
1755 if (strlen($list)) {
1756 $list_array = explode(",",$list);
1757 if ($type == 'file') {
1765 foreach ($list_array as $item) {
1766 if (strlen($item)) {
1767 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1774 // ex. given <music><video>[friends], return music,video or friends
1775 function file_tag_file_to_list($file,$type = 'file') {
1778 if ($type == 'file') {
1779 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1781 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1784 foreach ($matches as $mtch) {
1785 if (strlen($list)) {
1788 $list .= file_tag_decode($mtch[1]);
1795 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1796 // $file_old - categories previously associated with an item
1797 // $file_new - new list of categories for an item
1799 if (!intval($uid)) {
1802 if ($file_old == $file_new) {
1806 $saved = PConfig::get($uid, 'system', 'filetags');
1807 if (strlen($saved)) {
1808 if ($type == 'file') {
1811 $termtype = TERM_FILE;
1815 $termtype = TERM_CATEGORY;
1818 $filetags_updated = $saved;
1820 // check for new tags to be added as filetags in pconfig
1822 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1824 foreach ($check_new_tags as $tag) {
1825 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1829 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1831 // check for deleted tags to be removed from filetags in pconfig
1833 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1835 foreach ($check_deleted_tags as $tag) {
1836 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1837 $deleted_tags[] = $tag;
1840 foreach ($deleted_tags as $key => $tag) {
1841 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1843 intval(TERM_OBJ_POST),
1847 if (DBM::is_result($r)) {
1848 unset($deleted_tags[$key]);
1850 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1854 if ($saved != $filetags_updated) {
1855 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1858 } elseif (strlen($file_new)) {
1859 PConfig::set($uid, 'system', 'filetags', $file_new);
1864 function file_tag_save_file($uid, $item, $file)
1866 if (! intval($uid)) {
1870 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1874 if (DBM::is_result($r)) {
1875 if (!stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1876 $fields = ['file' => $r[0]['file'] . '[' . file_tag_encode($file) . ']'];
1877 Item::update($fields, ['id' => $item]);
1879 $saved = PConfig::get($uid, 'system', 'filetags');
1880 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1881 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1883 info(L10n::t('Item filed'));
1888 function file_tag_unsave_file($uid, $item, $file, $cat = false)
1890 if (! intval($uid)) {
1895 $pattern = '<' . file_tag_encode($file) . '>' ;
1896 $termtype = TERM_CATEGORY;
1898 $pattern = '[' . file_tag_encode($file) . ']' ;
1899 $termtype = TERM_FILE;
1902 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1906 if (! DBM::is_result($r)) {
1910 $fields = ['file' => str_replace($pattern,'',$r[0]['file'])];
1911 Item::update($fields, ['id' => $item]);
1913 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1915 intval(TERM_OBJ_POST),
1919 if (!DBM::is_result($r)) {
1920 $saved = PConfig::get($uid, 'system', 'filetags');
1921 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1927 function normalise_openid($s) {
1928 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
1932 function undo_post_tagging($s) {
1934 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1936 foreach ($matches as $mtch) {
1937 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1943 function protect_sprintf($s) {
1944 return str_replace('%', '%%', $s);
1948 function is_a_date_arg($s) {
1952 if ($i <= $y + 1 && strpos($s, '-') == 4) {
1953 $m = intval(substr($s,5));
1954 if ($m > 0 && $m <= 12)
1962 * remove intentation from a text
1964 function deindent($text, $chr = "[\t ]", $count = NULL) {
1965 $lines = explode("\n", $text);
1966 if (is_null($count)) {
1969 while ($k < count($lines) && strlen($lines[$k]) == 0) {
1972 preg_match("|^" . $chr . "*|", $lines[$k], $m);
1973 $count = strlen($m[0]);
1975 for ($k = 0; $k < count($lines); $k++) {
1976 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
1979 return implode("\n", $lines);
1982 function formatBytes($bytes, $precision = 2) {
1983 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
1985 $bytes = max($bytes, 0);
1986 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
1987 $pow = min($pow, count($units) - 1);
1989 $bytes /= pow(1024, $pow);
1991 return round($bytes, $precision) . ' ' . $units[$pow];
1995 * @brief translate and format the networkname of a contact
1997 * @param string $network
1998 * Networkname of the contact (e.g. dfrn, rss and so on)
2003 function format_network_name($network, $url = 0) {
2004 if ($network != "") {
2006 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
2008 $network_name = ContactSelector::networkToName($network);
2011 return $network_name;
2016 * @brief Syntax based code highlighting for popular languages.
2017 * @param string $s Code block
2018 * @param string $lang Programming language
2019 * @return string Formated html
2021 function text_highlight($s, $lang) {
2022 if ($lang === 'js') {
2023 $lang = 'javascript';
2026 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2028 // Autoload the library to make constants available
2029 class_exists('Text_Highlighter_Renderer_Html');
2032 'numbers' => HL_NUMBERS_LI,
2037 $s = trim(html_entity_decode($s, ENT_COMPAT));
2038 $s = str_replace(' ', "\t", $s);
2041 * The highlighter library insists on an opening php tag for php code blocks. If
2042 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2043 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2045 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2046 $s = '<?php' . "\n" . $s;
2050 $renderer = new Text_Highlighter_Renderer_Html($options);
2051 $factory = new Text_Highlighter();
2052 $hl = $factory->factory($lang);
2053 $hl->setRenderer($renderer);
2054 $o = $hl->highlight($s);
2055 $o = str_replace("\n", '', $o);
2058 $b = substr($o, 0, strpos($o, '<li>'));
2059 $e = substr($o, strpos($o, '</li>'));
2063 return '<code>' . $o . '</code>';