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\Contact;
18 use Friendica\Model\Event;
19 use Friendica\Model\Item;
20 use Friendica\Model\Profile;
21 use Friendica\Render\FriendicaSmarty;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Map;
25 require_once "mod/proxy.php";
26 require_once "include/conversation.php";
29 * This is our template processor
31 * @param string|FriendicaSmarty $s the string requiring macro substitution,
32 * or an instance of FriendicaSmarty
33 * @param array $r key value pairs (search => replace)
34 * @return string substituted string
36 function replace_macros($s, $r) {
38 $stamp1 = microtime(true);
42 // pass $baseurl to all templates
43 $r['$baseurl'] = System::baseUrl();
45 $t = $a->template_engine();
47 $output = $t->replaceMacros($s, $r);
48 } catch (Exception $e) {
49 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
53 $a->save_timestamp($stamp1, "rendering");
59 * @brief Generates a pseudo-random string of hexadecimal characters
64 function random_string($size = 64)
66 $byte_size = ceil($size / 2);
68 $bytes = random_bytes($byte_size);
70 $return = substr(bin2hex($bytes), 0, $size);
76 * This is our primary input filter.
78 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
79 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
80 * after cleansing, and angle chars with the high bit set could get through as markup.
82 * This is now disabled because it was interfering with some legitimate unicode sequences
83 * and hopefully there aren't a lot of those browsers left.
85 * Use this on any text input where angle chars are not valid or permitted
86 * They will be replaced with safer brackets. This may be filtered further
87 * if these are not allowed either.
89 * @param string $string Input string
90 * @return string Filtered string
92 function notags($string) {
93 return str_replace(["<", ">"], ['[', ']'], $string);
95 // High-bit filter no longer used
96 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
101 * use this on "body" or "content" input where angle chars shouldn't be removed,
102 * and allow them to be safely displayed.
103 * @param string $string
106 function escape_tags($string) {
107 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
112 * generate a string that's random, but usually pronounceable.
113 * used to generate initial passwords
117 function autoname($len) {
123 $vowels = ['a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'];
124 if (mt_rand(0, 5) == 4) {
143 's','sc','sh','sm','sp','st',
151 $midcons = ['ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
152 'nd','ng','nk','nt','rn','rp','rt'];
154 $noend = ['bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
155 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh'];
157 $start = mt_rand(0,2);
166 for ($x = 0; $x < $len; $x ++) {
167 $r = mt_rand(0,count($table) - 1);
170 if ($table == $vowels) {
171 $table = array_merge($cons,$midcons);
178 $word = substr($word,0,$len);
180 foreach ($noend as $noe) {
181 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
182 $word = substr($word, 0, -1);
186 if (substr($word, -1) == 'q') {
187 $word = substr($word, 0, -1);
194 * escape text ($str) for XML transport
196 * @return string Escaped text.
198 function xmlify($str) {
199 /// @TODO deprecated code found?
202 $len = mb_strlen($str);
203 for ($x = 0; $x < $len; $x ++) {
204 $char = mb_substr($str,$x,1);
234 $buffer = mb_ereg_replace("&", "&", $str);
235 $buffer = mb_ereg_replace("'", "'", $buffer);
236 $buffer = mb_ereg_replace('"', """, $buffer);
237 $buffer = mb_ereg_replace("<", "<", $buffer);
238 $buffer = mb_ereg_replace(">", ">", $buffer);
240 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
241 $buffer = trim($buffer);
249 * @param string $s xml escaped text
250 * @return string unescaped text
252 function unxmlify($s) {
253 /// @TODO deprecated code found?
254 // $ret = str_replace('&','&', $s);
255 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
256 /*$ret = mb_ereg_replace('&', '&', $s);
257 $ret = mb_ereg_replace(''', "'", $ret);
258 $ret = mb_ereg_replace('"', '"', $ret);
259 $ret = mb_ereg_replace('<', "<", $ret);
260 $ret = mb_ereg_replace('>', ">", $ret);
262 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
268 * @brief Paginator function. Pushes relevant links in a pager array structure.
270 * Links are generated depending on the current page and the total number of items.
271 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
272 * Current page link is given the "active" CSS class
274 * @param App $a App instance
275 * @param int $count [optional] item count (used with minimal pager)
276 * @return Array data for pagination template
278 function paginate_data(App $a, $count = null) {
279 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
281 $stripped = str_replace('q=', '', $stripped);
282 $stripped = trim($stripped, '/');
283 $pagenum = $a->pager['page'];
285 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
286 $stripped .= '&offset=' . urlencode($a->page_offset);
292 function _l(&$d, $name, $url, $text, $class = '') {
293 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
294 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
297 $d[$name] = ['url' => $url, 'text' => $text, 'class' => $class];
300 if (!is_null($count)) {
301 // minimal pager (newer / older)
302 $data['class'] = 'pager';
303 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
304 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
306 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
307 $data['class'] = 'pagination';
308 if ($a->pager['total'] > $a->pager['itemspage']) {
309 _l($data, 'first', $url . '&page=1', L10n::t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
310 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
312 $numpages = $a->pager['total'] / $a->pager['itemspage'];
315 $numstop = $numpages;
317 // Limit the number of displayed page number buttons.
319 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
320 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
325 for ($i = $numstart; $i <= $numstop; $i++) {
326 if ($i == $a->pager['page']) {
327 _l($pages, $i, '#', $i, 'current active');
329 _l($pages, $i, $url . '&page='. $i, $i, 'n');
333 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
334 if ($i == $a->pager['page']) {
335 _l($pages, $i, '#', $i, 'current active');
337 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
341 $data['pages'] = $pages;
343 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
344 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
345 _l($data, 'last', $url . '&page=' . $lastpage, L10n::t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
354 * Automatic pagination.
356 * To use, get the count of total items.
357 * Then call $a->set_pager_total($number_items);
358 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
359 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
360 * (assuming there are enough items to paginate).
361 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
362 * will limit the results to the correct items for the current page.
363 * The actual page handling is then accomplished at the application layer.
365 * @param App $a App instance
366 * @return string html for pagination #FIXME remove html
368 function paginate(App $a) {
370 $data = paginate_data($a);
371 $tpl = get_markup_template("paginate.tpl");
372 return replace_macros($tpl, ["pager" => $data]);
379 * @param App $a App instance
381 * @return string html for pagination #FIXME remove html
383 function alt_pager(App $a, $i) {
385 $data = paginate_data($a, $i);
386 $tpl = get_markup_template("paginate.tpl");
387 return replace_macros($tpl, ['pager' => $data]);
393 * Loader for infinite scrolling
394 * @return string html for loader
396 function scroll_loader() {
397 $tpl = get_markup_template("scroll_loader.tpl");
398 return replace_macros($tpl, [
399 'wait' => L10n::t('Loading more entries...'),
400 'end' => L10n::t('The end')
406 * Turn user/group ACLs stored as angle bracketed text into arrays
411 function expand_acl($s) {
412 // turn string array of angle-bracketed elements into numeric array
413 // e.g. "<1><2><3>" => array(1,2,3);
417 $t = str_replace('<', '', $s);
418 $a = explode('>', $t);
419 foreach ($a as $aa) {
421 $ret[] = intval($aa);
430 * Wrap ACL elements in angle brackets for storage
431 * @param string $item
433 function sanitise_acl(&$item) {
435 $item = '<' . intval(notags(trim($item))) . '>';
443 * Convert an ACL array to a storable string
445 * Normally ACL permissions will be an array.
446 * We'll also allow a comma-separated string.
448 * @param string|array $p
451 function perms2str($p) {
456 $tmp = explode(',',$p);
459 if (is_array($tmp)) {
460 array_walk($tmp, 'sanitise_acl');
461 $ret = implode('', $tmp);
468 * generate a guaranteed unique (for this domain) item ID for ATOM
469 * safe from birthday paradox
471 * @param string $hostname
475 function item_new_uri($hostname, $uid, $guid = "") {
479 $hash = get_guid(32);
485 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
487 $dups = dba::exists('item', ['uri' => $uri]);
488 } while ($dups == true);
495 * wrapper to load a view template, checking for alternate
496 * languages before falling back to the default
498 * @global string $lang
500 * @param string $s view name
503 function load_view_file($s) {
505 if (! isset($lang)) {
510 if (file_exists("$d/$lang/$b")) {
511 $stamp1 = microtime(true);
512 $content = file_get_contents("$d/$lang/$b");
513 $a->save_timestamp($stamp1, "file");
517 $theme = $a->getCurrentTheme();
519 if (file_exists("$d/theme/$theme/$b")) {
520 $stamp1 = microtime(true);
521 $content = file_get_contents("$d/theme/$theme/$b");
522 $a->save_timestamp($stamp1, "file");
526 $stamp1 = microtime(true);
527 $content = file_get_contents($s);
528 $a->save_timestamp($stamp1, "file");
534 * load a view template, checking for alternate
535 * languages before falling back to the default
537 * @global string $lang
538 * @param string $s view path
541 function get_intltext_template($s) {
546 if ($a->theme['template_engine'] === 'smarty3') {
547 $engine = "/smarty3";
550 if (! isset($lang)) {
554 if (file_exists("view/lang/$lang$engine/$s")) {
555 $stamp1 = microtime(true);
556 $content = file_get_contents("view/lang/$lang$engine/$s");
557 $a->save_timestamp($stamp1, "file");
559 } elseif (file_exists("view/lang/en$engine/$s")) {
560 $stamp1 = microtime(true);
561 $content = file_get_contents("view/lang/en$engine/$s");
562 $a->save_timestamp($stamp1, "file");
565 $stamp1 = microtime(true);
566 $content = file_get_contents("view$engine/$s");
567 $a->save_timestamp($stamp1, "file");
577 * @param string $root
580 function get_markup_template($s, $root = '') {
581 $stamp1 = microtime(true);
584 $t = $a->template_engine();
586 $template = $t->getTemplateFile($s, $root);
587 } catch (Exception $e) {
588 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
592 $a->save_timestamp($stamp1, "file");
598 * for html,xml parsing - let's say you've got
599 * an attribute foobar="class1 class2 class3"
600 * and you want to find out if it contains 'class3'.
601 * you can't use a normal sub string search because you
602 * might match 'notclass3' and a regex to do the job is
603 * possible but a bit complicated.
604 * pass the attribute string as $attr and the attribute you
605 * are looking for as $s - returns true if found, otherwise false
607 * @param string $attr attribute value
608 * @param string $s string to search
609 * @return boolean True if found, False otherwise
611 function attribute_contains($attr, $s) {
612 $a = explode(' ', $attr);
613 return (count($a) && in_array($s,$a));
617 /* setup int->string log level map */
621 * @brief Logs the given message at the given log level
624 * LOGGER_NORMAL (default)
631 * @global array $LOGGER_LEVELS
635 function logger($msg, $level = 0) {
637 global $LOGGER_LEVELS;
639 // turn off logger in install mode
641 $a->mode == App::MODE_INSTALL
647 $debugging = Config::get('system','debugging');
648 $logfile = Config::get('system','logfile');
649 $loglevel = intval(Config::get('system','loglevel'));
654 || $level > $loglevel
659 if (count($LOGGER_LEVELS) == 0) {
660 foreach (get_defined_constants() as $k => $v) {
661 if (substr($k, 0, 7) == "LOGGER_") {
662 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
667 $process_id = session_id();
669 if ($process_id == '') {
670 $process_id = get_app()->process_id;
673 $callers = debug_backtrace();
674 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
675 DateTimeFormat::utcNow(DateTimeFormat::ATOM),
677 $LOGGER_LEVELS[$level],
678 basename($callers[0]['file']),
680 $callers[1]['function'],
684 $stamp1 = microtime(true);
685 @file_put_contents($logfile, $logline, FILE_APPEND);
686 $a->save_timestamp($stamp1, "file");
690 * @brief An alternative logger for development.
691 * Works largely as logger() but allows developers
692 * to isolate particular elements they are targetting
693 * personally without background noise
696 * LOGGER_NORMAL (default)
703 * @global array $LOGGER_LEVELS
708 function dlogger($msg, $level = 0) {
711 // turn off logger in install mode
713 $a->mode == App::MODE_INSTALL
719 $logfile = Config::get('system', 'dlogfile');
724 $dlogip = Config::get('system', 'dlogip');
725 if (!is_null($dlogip) && $_SERVER['REMOTE_ADDR'] != $dlogip) {
729 if (count($LOGGER_LEVELS) == 0) {
730 foreach (get_defined_constants() as $k => $v) {
731 if (substr($k, 0, 7) == "LOGGER_") {
732 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
737 $process_id = session_id();
739 if ($process_id == '') {
740 $process_id = get_app()->process_id;
743 $callers = debug_backtrace();
744 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
745 DateTimeFormat::utcNow(),
747 basename($callers[0]['file']),
749 $callers[1]['function'],
753 $stamp1 = microtime(true);
754 @file_put_contents($logfile, $logline, FILE_APPEND);
755 $a->save_timestamp($stamp1, "file");
760 * Compare activity uri. Knows about activity namespace.
762 * @param string $haystack
763 * @param string $needle
766 function activity_match($haystack,$needle) {
767 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
772 * @brief Pull out all #hashtags and @person tags from $string.
774 * We also get @person@domain.com - which would make
775 * the regex quite complicated as tags can also
776 * end a sentence. So we'll run through our results
777 * and strip the period from any tags which end with one.
778 * Returns array of tags found, or empty array.
780 * @param string $string Post content
781 * @return array List of tag and person names
783 function get_tags($string) {
786 // Convert hashtag links to hashtags
787 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
789 // ignore anything in a code block
790 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
792 // Force line feeds at bbtags
793 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
795 // ignore anything in a bbtag
796 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
798 // Match full names against @tags including the space between first and last
799 // We will look these up afterward to see if they are full names or not recognisable.
801 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
802 foreach ($matches[1] as $match) {
803 if (strstr($match, ']')) {
804 // we might be inside a bbcode color tag - leave it alone
807 if (substr($match, -1, 1) === '.') {
808 $ret[] = substr($match, 0, -1);
815 // Otherwise pull out single word tags. These can be @nickname, @first_last
818 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
819 foreach ($matches[1] as $match) {
820 if (strstr($match, ']')) {
821 // we might be inside a bbcode color tag - leave it alone
824 if (substr($match, -1, 1) === '.') {
825 $match = substr($match,0,-1);
827 // ignore strictly numeric tags like #1
828 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
831 // try not to catch url fragments
832 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
843 * quick and dirty quoted_printable encoding
849 return str_replace("%", "=", rawurlencode($s));
854 * Get html for contact block.
856 * @template contact_block.tpl
857 * @hook contact_block_end (contacts=>array, output=>string)
860 function contact_block() {
864 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
869 if (!is_array($a->profile) || $a->profile['hide-friends']) {
872 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
873 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
874 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
875 AND `network` IN ('%s', '%s', '%s')",
876 intval($a->profile['uid']),
878 dbesc(NETWORK_OSTATUS),
879 dbesc(NETWORK_DIASPORA)
881 if (DBM::is_result($r)) {
882 $total = intval($r[0]['total']);
885 $contacts = L10n::t('No contacts');
888 // Splitting the query in two parts makes it much faster
889 $r = q("SELECT `id` FROM `contact`
890 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
891 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
892 AND `network` IN ('%s', '%s', '%s')
893 ORDER BY RAND() LIMIT %d",
894 intval($a->profile['uid']),
896 dbesc(NETWORK_OSTATUS),
897 dbesc(NETWORK_DIASPORA),
900 if (DBM::is_result($r)) {
902 foreach ($r AS $contact) {
903 $contacts[] = $contact["id"];
905 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
906 dbesc(implode(",", $contacts)));
908 if (DBM::is_result($r)) {
909 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
911 foreach ($r as $rr) {
912 $micropro[] = micropro($rr, true, 'mpfriend');
918 $tpl = get_markup_template('contact_block.tpl');
919 $o = replace_macros($tpl, [
920 '$contacts' => $contacts,
921 '$nickname' => $a->profile['nickname'],
922 '$viewcontacts' => L10n::t('View Contacts'),
923 '$micropro' => $micropro,
926 $arr = ['contacts' => $r, 'output' => $o];
928 Addon::callHooks('contact_block_end', $arr);
935 * @brief Format contacts as picture links or as texxt links
937 * @param array $contact Array with contacts which contains an array with
938 * int 'id' => The ID of the contact
939 * int 'uid' => The user ID of the user who owns this data
940 * string 'name' => The name of the contact
941 * string 'url' => The url to the profile page of the contact
942 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
943 * string 'network' => The network to which the contact belongs to
944 * string 'thumb' => The contact picture
945 * string 'click' => js code which is performed when clicking on the contact
946 * @param boolean $redirect If true try to use the redir url if it's possible
947 * @param string $class CSS class for the
948 * @param boolean $textmode If true display the contacts as text links
949 * if false display the contacts as picture links
951 * @return string Formatted html
953 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
955 // Use the contact URL if no address is available
956 if (!x($contact, "addr")) {
957 $contact["addr"] = $contact["url"];
960 $url = $contact['url'];
965 $redirect_url = 'redir/' . $contact['id'];
966 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
968 $url = $redirect_url;
969 $sparkle = ' sparkle';
971 $url = Profile::zrl($url);
975 // If there is some js available we don't need the url
976 if (x($contact, 'click')) {
980 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),[
981 '$click' => defaults($contact, 'click', ''),
984 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
985 '$name' => $contact['name'],
986 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
987 '$parkle' => $sparkle,
996 * @param string $s Search query.
997 * @param string $id HTML id
998 * @param string $url Search url.
999 * @param bool $save Show save search button.
1000 * @param bool $aside Display the search widgit aside.
1002 * @return string Formatted HTML.
1004 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
1008 if (strpos($s, '#') === 0) {
1011 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
1014 '$s' => htmlspecialchars($s),
1016 '$action_url' => $url,
1017 '$search_label' => L10n::t('Search'),
1018 '$save_label' => $save_label,
1019 '$savedsearch' => Feature::isEnabled(local_user(),'savedsearch'),
1020 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
1025 $values['$searchoption'] = [
1026 L10n::t("Full Text"),
1028 L10n::t("Contacts")];
1030 if (Config::get('system','poco_local_search')) {
1031 $values['$searchoption'][] = L10n::t("Forums");
1035 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1039 * @brief Check for a valid email string
1041 * @param string $email_address
1044 function valid_email($email_address)
1046 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
1051 * Replace naked text hyperlink with HTML formatted hyperlink
1055 function linkify($s) {
1056 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1057 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1065 * @return array index is present tense verb
1066 * value is array containing past tense verb, translation of present, translation of past
1067 * @hook poke_verbs pokes array
1069 function get_poke_verbs() {
1071 // index is present tense verb
1072 // value is array containing past tense verb, translation of present, translation of past
1075 'poke' => ['poked', L10n::t('poke'), L10n::t('poked')],
1076 'ping' => ['pinged', L10n::t('ping'), L10n::t('pinged')],
1077 'prod' => ['prodded', L10n::t('prod'), L10n::t('prodded')],
1078 'slap' => ['slapped', L10n::t('slap'), L10n::t('slapped')],
1079 'finger' => ['fingered', L10n::t('finger'), L10n::t('fingered')],
1080 'rebuff' => ['rebuffed', L10n::t('rebuff'), L10n::t('rebuffed')],
1082 Addon::callHooks('poke_verbs', $arr);
1087 * @brief Translate days and months names.
1089 * @param string $s String with day or month name.
1090 * @return string Translated string.
1092 function day_translate($s) {
1093 $ret = str_replace(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
1094 [L10n::t('Monday'), L10n::t('Tuesday'), L10n::t('Wednesday'), L10n::t('Thursday'), L10n::t('Friday'), L10n::t('Saturday'), L10n::t('Sunday')],
1097 $ret = str_replace(['January','February','March','April','May','June','July','August','September','October','November','December'],
1098 [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')],
1105 * @brief Translate short days and months names.
1107 * @param string $s String with short day or month name.
1108 * @return string Translated string.
1110 function day_short_translate($s) {
1111 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
1112 [L10n::t('Mon'), L10n::t('Tue'), L10n::t('Wed'), L10n::t('Thu'), L10n::t('Fri'), L10n::t('Sat'), L10n::t('Sun')],
1114 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'],
1115 [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')],
1124 * @param string $url
1127 function normalise_link($url) {
1128 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
1129 return rtrim($ret,'/');
1134 * Compare two URLs to see if they are the same, but ignore
1135 * slight but hopefully insignificant differences such as if one
1136 * is https and the other isn't, or if one is www.something and
1137 * the other isn't - and also ignore case differences.
1139 * @param string $a first url
1140 * @param string $b second url
1141 * @return boolean True if the URLs match, otherwise False
1144 function link_compare($a, $b) {
1145 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1150 * @brief Find any non-embedded images in private items and add redir links to them
1153 * @param array &$item The field array of an item row
1155 function redir_private_images($a, &$item)
1158 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1160 foreach ($matches as $mtch) {
1161 if (strpos($mtch[1], '/redir') !== false) {
1165 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1166 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1167 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1174 * Sets the "rendered-html" field of the provided item
1176 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
1178 * @param array $item
1179 * @param bool $update
1181 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
1183 function put_item_in_cache(&$item, $update = false)
1185 $body = $item["body"];
1187 $rendered_hash = defaults($item, 'rendered-hash', '');
1188 $rendered_html = defaults($item, 'rendered-html', '');
1190 if ($rendered_hash == ''
1191 || $item["rendered-html"] == ""
1192 || $rendered_hash != hash("md5", $item["body"])
1193 || Config::get("system", "ignore_cache")
1196 redir_private_images($a, $item);
1198 $item["rendered-html"] = prepare_text($item["body"]);
1199 $item["rendered-hash"] = hash("md5", $item["body"]);
1201 // Force an update if the generated values differ from the existing ones
1202 if ($rendered_hash != $item["rendered-hash"]) {
1206 // Only compare the HTML when we forcefully ignore the cache
1207 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
1211 if ($update && ($item["id"] > 0)) {
1212 dba::update('item', ['rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]],
1213 ['id' => $item["id"]], false);
1217 $item["body"] = $body;
1221 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1222 * If attach is true, also add icons for item attachments.
1224 * @param array $item
1225 * @param boolean $attach
1226 * @param boolean $is_preview
1227 * @return string item body html
1228 * @hook prepare_body_init item array before any work
1229 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
1230 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
1231 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1233 function prepare_body(array &$item, $attach = false, $is_preview = false)
1236 Addon::callHooks('prepare_body_init', $item);
1238 // In order to provide theme developers more possibilities, event items
1239 // are treated differently.
1240 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1241 $ev = Event::getItemHTML($item);
1245 $tags = \Friendica\Model\Term::populateTagsFromItem($item);
1247 $item['tags'] = $tags['tags'];
1248 $item['hashtags'] = $tags['hashtags'];
1249 $item['mentions'] = $tags['mentions'];
1251 // Compile eventual content filter reasons
1252 $filter_reasons = [];
1253 if (!$is_preview && public_contact() != $item['author-id']) {
1254 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
1255 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
1260 'filter_reasons' => $filter_reasons
1262 Addon::callHooks('prepare_body_content_filter', $hook_data);
1263 $filter_reasons = $hook_data['filter_reasons'];
1267 // Update the cached values if there is no "zrl=..." on the links.
1268 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1270 // Or update it if the current viewer is the intented viewer.
1271 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1275 put_item_in_cache($item, $update);
1276 $s = $item["rendered-html"];
1281 'preview' => $is_preview,
1282 'filter_reasons' => $filter_reasons
1284 Addon::callHooks('prepare_body', $hook_data);
1285 $s = $hook_data['html'];
1288 $s = apply_content_filter($s, $filter_reasons);
1291 // Replace the blockquotes with quotes that are used in mails.
1292 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1293 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
1300 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
1301 foreach ($matches as $mtch) {
1304 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1305 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1307 $the_url = $mtch[1];
1310 if (strpos($mime, 'video') !== false) {
1313 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), [
1314 '$baseurl' => System::baseUrl(),
1316 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), [
1317 '$baseurl' => System::baseUrl(),
1321 $id = end(explode('/', $the_url));
1322 $as .= replace_macros(get_markup_template('video_top.tpl'), [
1325 'title' => L10n::t('View Video'),
1332 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1334 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1335 $filesubtype = str_replace('.', '-', $filesubtype);
1338 $filesubtype = 'unkn';
1341 $title = escape_tags(trim(!empty($mtch[4]) ? $mtch[4] : $mtch[1]));
1342 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
1344 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1345 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1349 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1353 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1354 $x = Map::byCoordinates(trim($item['coord']));
1356 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1361 // Look for spoiler.
1362 $spoilersearch = '<blockquote class="spoiler">';
1364 // Remove line breaks before the spoiler.
1365 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1366 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1368 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1369 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1372 while ((strpos($s, $spoilersearch) !== false)) {
1373 $pos = strpos($s, $spoilersearch);
1374 $rnd = random_string(8);
1375 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1376 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1377 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1380 // Look for quote with author.
1381 $authorsearch = '<blockquote class="author">';
1383 while ((strpos($s, $authorsearch) !== false)) {
1384 $pos = strpos($s, $authorsearch);
1385 $rnd = random_string(8);
1386 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1387 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1388 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1391 // Replace friendica image url size with theme preference.
1392 if (x($a->theme_info, 'item_image_size')){
1393 $ps = $a->theme_info['item_image_size'];
1394 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1397 $hook_data = ['item' => $item, 'html' => $s];
1398 Addon::callHooks('prepare_body_final', $hook_data);
1400 return $hook_data['html'];
1404 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
1406 * Reasons are expected to have been translated already.
1408 * @param string $html
1409 * @param array $reasons
1412 function apply_content_filter($html, array $reasons)
1414 if (count($reasons)) {
1415 $tpl = get_markup_template('wall/content_filter.tpl');
1416 $html = replace_macros($tpl, [
1417 '$reasons' => $reasons,
1418 '$rnd' => random_string(8),
1419 '$openclose' => L10n::t('Click to open/close'),
1428 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1430 * @param string $text String with bbcode.
1431 * @return string Formattet HTML.
1433 function prepare_text($text) {
1434 if (stristr($text, '[nosmile]')) {
1435 $s = BBCode::convert($text);
1437 $s = Smilies::replace(BBCode::convert($text));
1444 * return array with details for categories and folders for an item
1446 * @param array $item
1450 * [ // categories array
1452 * 'name': 'category name',
1453 * 'removeurl': 'url to remove this category',
1454 * 'first': 'is the first in this array? true/false',
1455 * 'last': 'is the last in this array? true/false',
1461 * 'name': 'folder name',
1462 * 'removeurl': 'url to remove this folder',
1463 * 'first': 'is the first in this array? true/false',
1464 * 'last': 'is the last in this array? true/false',
1470 function get_cats_and_terms($item)
1477 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1479 foreach ($matches as $mtch) {
1481 'name' => xmlify(file_tag_decode($mtch[1])),
1483 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1491 if (count($categories)) {
1492 $categories[count($categories) - 1]['last'] = true;
1495 if (local_user() == $item['uid']) {
1498 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1500 foreach ($matches as $mtch) {
1502 'name' => xmlify(file_tag_decode($mtch[1])),
1504 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1513 if (count($folders)) {
1514 $folders[count($folders) - 1]['last'] = true;
1517 return [$categories, $folders];
1522 * get private link for item
1523 * @param array $item
1524 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1526 function get_plink($item) {
1529 if ($a->user['nickname'] != "") {
1531 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1532 'href' => "display/" . $item['guid'],
1533 'orig' => "display/" . $item['guid'],
1534 'title' => L10n::t('View on separate page'),
1535 'orig_title' => L10n::t('view on separate page'),
1538 if (x($item, 'plink')) {
1539 $ret["href"] = $a->remove_baseurl($item['plink']);
1540 $ret["title"] = L10n::t('link to source');
1543 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1545 'href' => $item['plink'],
1546 'orig' => $item['plink'],
1547 'title' => L10n::t('link to source'),
1558 * replace html amp entity with amp char
1562 function unamp($s) {
1563 return str_replace('&', '&', $s);
1568 * return number of bytes in size (K, M, G)
1569 * @param string $size_str
1572 function return_bytes($size_str) {
1573 switch (substr ($size_str, -1)) {
1574 case 'M': case 'm': return (int)$size_str * 1048576;
1575 case 'K': case 'k': return (int)$size_str * 1024;
1576 case 'G': case 'g': return (int)$size_str * 1073741824;
1577 default: return $size_str;
1585 function generate_user_guid() {
1588 $guid = get_guid(32);
1589 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1592 if (! DBM::is_result($x)) {
1595 } while ($found == true);
1603 * @param boolean $strip_padding
1606 function base64url_encode($s, $strip_padding = false) {
1608 $s = strtr(base64_encode($s), '+/', '-_');
1610 if ($strip_padding) {
1611 $s = str_replace('=','',$s);
1621 function base64url_decode($s) {
1624 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1629 * // Placeholder for new rev of salmon which strips base64 padding.
1630 * // PHP base64_decode handles the un-padded input without requiring this step
1631 * // Uncomment if you find you need it.
1634 * if (! strpos($s,'=')) {
1644 return base64_decode(strtr($s,'-_','+/'));
1649 * return div element with class 'clear'
1653 function cleardiv() {
1654 return '<div class="clear"></div>';
1658 function bb_translate_video($s) {
1661 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1663 foreach ($matches as $mtch) {
1664 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1665 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1666 elseif (stristr($mtch[1],'vimeo'))
1667 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1673 function html2bb_video($s) {
1675 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1676 '[youtube]$2[/youtube]', $s);
1678 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1679 '[youtube]$2[/youtube]', $s);
1681 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1682 '[vimeo]$2[/vimeo]', $s);
1688 * apply xmlify() to all values of array $val, recursively
1692 function array_xmlify($val){
1693 if (is_bool($val)) {
1694 return $val?"true":"false";
1695 } elseif (is_array($val)) {
1696 return array_map('array_xmlify', $val);
1698 return xmlify((string) $val);
1703 * transform link href and img src from relative to absolute
1705 * @param string $text
1706 * @param string $base base url
1709 function reltoabs($text, $base) {
1714 $base = rtrim($base,'/');
1716 $base2 = $base . "/";
1719 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1720 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1721 $text = preg_replace($pattern, $replace, $text);
1723 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1724 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1725 $text = preg_replace($pattern, $replace, $text);
1728 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1729 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1730 $text = preg_replace($pattern, $replace, $text);
1732 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1733 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1734 $text = preg_replace($pattern, $replace, $text);
1742 * get translated item type
1744 * @param array $itme
1747 function item_post_type($item) {
1748 if (intval($item['event-id'])) {
1749 return L10n::t('event');
1750 } elseif (strlen($item['resource-id'])) {
1751 return L10n::t('photo');
1752 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1753 return L10n::t('activity');
1754 } elseif ($item['id'] != $item['parent']) {
1755 return L10n::t('comment');
1758 return L10n::t('post');
1761 // post categories and "save to file" use the same item.file table for storage.
1762 // We will differentiate the different uses by wrapping categories in angle brackets
1763 // and save to file categories in square brackets.
1764 // To do this we need to escape these characters if they appear in our tag.
1766 function file_tag_encode($s) {
1767 return str_replace(['<','>','[',']'],['%3c','%3e','%5b','%5d'],$s);
1770 function file_tag_decode($s) {
1771 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
1774 function file_tag_file_query($table,$s,$type = 'file') {
1776 if ($type == 'file') {
1777 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1779 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1781 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1784 // ex. given music,video return <music><video> or [music][video]
1785 function file_tag_list_to_file($list,$type = 'file') {
1787 if (strlen($list)) {
1788 $list_array = explode(",",$list);
1789 if ($type == 'file') {
1797 foreach ($list_array as $item) {
1798 if (strlen($item)) {
1799 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1806 // ex. given <music><video>[friends], return music,video or friends
1807 function file_tag_file_to_list($file,$type = 'file') {
1810 if ($type == 'file') {
1811 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1813 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1816 foreach ($matches as $mtch) {
1817 if (strlen($list)) {
1820 $list .= file_tag_decode($mtch[1]);
1827 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1828 // $file_old - categories previously associated with an item
1829 // $file_new - new list of categories for an item
1831 if (!intval($uid)) {
1834 if ($file_old == $file_new) {
1838 $saved = PConfig::get($uid, 'system', 'filetags');
1839 if (strlen($saved)) {
1840 if ($type == 'file') {
1843 $termtype = TERM_FILE;
1847 $termtype = TERM_CATEGORY;
1850 $filetags_updated = $saved;
1852 // check for new tags to be added as filetags in pconfig
1854 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1856 foreach ($check_new_tags as $tag) {
1857 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1861 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1863 // check for deleted tags to be removed from filetags in pconfig
1865 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1867 foreach ($check_deleted_tags as $tag) {
1868 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1869 $deleted_tags[] = $tag;
1872 foreach ($deleted_tags as $key => $tag) {
1873 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1875 intval(TERM_OBJ_POST),
1879 if (DBM::is_result($r)) {
1880 unset($deleted_tags[$key]);
1882 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1886 if ($saved != $filetags_updated) {
1887 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1890 } elseif (strlen($file_new)) {
1891 PConfig::set($uid, 'system', 'filetags', $file_new);
1896 function file_tag_save_file($uid, $item, $file)
1898 if (! intval($uid)) {
1902 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1906 if (DBM::is_result($r)) {
1907 if (!stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1908 $fields = ['file' => $r[0]['file'] . '[' . file_tag_encode($file) . ']'];
1909 Item::update($fields, ['id' => $item]);
1911 $saved = PConfig::get($uid, 'system', 'filetags');
1912 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1913 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1915 info(L10n::t('Item filed'));
1920 function file_tag_unsave_file($uid, $item, $file, $cat = false)
1922 if (! intval($uid)) {
1927 $pattern = '<' . file_tag_encode($file) . '>' ;
1928 $termtype = TERM_CATEGORY;
1930 $pattern = '[' . file_tag_encode($file) . ']' ;
1931 $termtype = TERM_FILE;
1934 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1938 if (! DBM::is_result($r)) {
1942 $fields = ['file' => str_replace($pattern,'',$r[0]['file'])];
1943 Item::update($fields, ['id' => $item]);
1945 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1947 intval(TERM_OBJ_POST),
1951 if (!DBM::is_result($r)) {
1952 $saved = PConfig::get($uid, 'system', 'filetags');
1953 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1959 function normalise_openid($s) {
1960 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
1964 function undo_post_tagging($s) {
1966 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1968 foreach ($matches as $mtch) {
1969 if (in_array($mtch[1], ['!', '@'])) {
1970 $contact = Contact::getDetailsByURL($mtch[2]);
1971 $mtch[3] = empty($contact['addr']) ? $mtch[2] : $contact['addr'];
1973 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1979 function protect_sprintf($s) {
1980 return str_replace('%', '%%', $s);
1984 function is_a_date_arg($s) {
1988 if ($i <= $y + 1 && strpos($s, '-') == 4) {
1989 $m = intval(substr($s,5));
1990 if ($m > 0 && $m <= 12)
1998 * remove intentation from a text
2000 function deindent($text, $chr = "[\t ]", $count = NULL) {
2001 $lines = explode("\n", $text);
2002 if (is_null($count)) {
2005 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2008 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2009 $count = strlen($m[0]);
2011 for ($k = 0; $k < count($lines); $k++) {
2012 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2015 return implode("\n", $lines);
2018 function formatBytes($bytes, $precision = 2) {
2019 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
2021 $bytes = max($bytes, 0);
2022 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2023 $pow = min($pow, count($units) - 1);
2025 $bytes /= pow(1024, $pow);
2027 return round($bytes, $precision) . ' ' . $units[$pow];
2031 * @brief translate and format the networkname of a contact
2033 * @param string $network
2034 * Networkname of the contact (e.g. dfrn, rss and so on)
2039 function format_network_name($network, $url = 0) {
2040 if ($network != "") {
2042 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
2044 $network_name = ContactSelector::networkToName($network);
2047 return $network_name;
2052 * @brief Syntax based code highlighting for popular languages.
2053 * @param string $s Code block
2054 * @param string $lang Programming language
2055 * @return string Formated html
2057 function text_highlight($s, $lang) {
2058 if ($lang === 'js') {
2059 $lang = 'javascript';
2062 if ($lang === 'bash') {
2066 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2068 // Autoload the library to make constants available
2069 class_exists('Text_Highlighter_Renderer_Html');
2072 'numbers' => HL_NUMBERS_LI,
2077 $s = trim(html_entity_decode($s, ENT_COMPAT));
2078 $s = str_replace(' ', "\t", $s);
2081 * The highlighter library insists on an opening php tag for php code blocks. If
2082 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2083 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2085 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2086 $s = '<?php' . "\n" . $s;
2090 $renderer = new Text_Highlighter_Renderer_Html($options);
2091 $factory = new Text_Highlighter();
2092 $hl = $factory->factory($lang);
2093 $hl->setRenderer($renderer);
2094 $o = $hl->highlight($s);
2095 $o = str_replace("\n", '', $o);
2098 $b = substr($o, 0, strpos($o, '<li>'));
2099 $e = substr($o, strpos($o, '</li>'));
2103 return '<code>' . $o . '</code>';