3 * @file include/text.php
7 use Friendica\Content\ContactSelector;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Smilies;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Item;
17 use Friendica\Model\Profile;
18 use Friendica\Model\Term;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Map;
22 require_once "mod/proxy.php";
23 require_once "include/conversation.php";
26 * This is our template processor
28 * @param string|FriendicaSmarty $s the string requiring macro substitution,
29 * or an instance of FriendicaSmarty
30 * @param array $r key value pairs (search => replace)
31 * @return string substituted string
33 function replace_macros($s, $r) {
35 $stamp1 = microtime(true);
39 // pass $baseurl to all templates
40 $r['$baseurl'] = System::baseUrl();
42 $t = $a->template_engine();
44 $output = $t->replaceMacros($s, $r);
45 } catch (Exception $e) {
46 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
50 $a->save_timestamp($stamp1, "rendering");
56 * @brief Generates a pseudo-random string of hexadecimal characters
61 function random_string($size = 64)
63 $byte_size = ceil($size / 2);
65 $bytes = random_bytes($byte_size);
67 $return = substr(bin2hex($bytes), 0, $size);
73 * This is our primary input filter.
75 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
76 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
77 * after cleansing, and angle chars with the high bit set could get through as markup.
79 * This is now disabled because it was interfering with some legitimate unicode sequences
80 * and hopefully there aren't a lot of those browsers left.
82 * Use this on any text input where angle chars are not valid or permitted
83 * They will be replaced with safer brackets. This may be filtered further
84 * if these are not allowed either.
86 * @param string $string Input string
87 * @return string Filtered string
89 function notags($string) {
90 return str_replace(["<", ">"], ['[', ']'], $string);
92 // High-bit filter no longer used
93 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
98 * use this on "body" or "content" input where angle chars shouldn't be removed,
99 * and allow them to be safely displayed.
100 * @param string $string
103 function escape_tags($string) {
104 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
109 * generate a string that's random, but usually pronounceable.
110 * used to generate initial passwords
114 function autoname($len) {
120 $vowels = ['a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'];
121 if (mt_rand(0, 5) == 4) {
140 's','sc','sh','sm','sp','st',
148 $midcons = ['ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
149 'nd','ng','nk','nt','rn','rp','rt'];
151 $noend = ['bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
152 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh'];
154 $start = mt_rand(0,2);
163 for ($x = 0; $x < $len; $x ++) {
164 $r = mt_rand(0,count($table) - 1);
167 if ($table == $vowels) {
168 $table = array_merge($cons,$midcons);
175 $word = substr($word,0,$len);
177 foreach ($noend as $noe) {
178 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
179 $word = substr($word, 0, -1);
183 if (substr($word, -1) == 'q') {
184 $word = substr($word, 0, -1);
191 * escape text ($str) for XML transport
193 * @return string Escaped text.
195 function xmlify($str) {
196 /// @TODO deprecated code found?
199 $len = mb_strlen($str);
200 for ($x = 0; $x < $len; $x ++) {
201 $char = mb_substr($str,$x,1);
231 $buffer = mb_ereg_replace("&", "&", $str);
232 $buffer = mb_ereg_replace("'", "'", $buffer);
233 $buffer = mb_ereg_replace('"', """, $buffer);
234 $buffer = mb_ereg_replace("<", "<", $buffer);
235 $buffer = mb_ereg_replace(">", ">", $buffer);
237 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
238 $buffer = trim($buffer);
246 * @param string $s xml escaped text
247 * @return string unescaped text
249 function unxmlify($s) {
250 /// @TODO deprecated code found?
251 // $ret = str_replace('&','&', $s);
252 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
253 /*$ret = mb_ereg_replace('&', '&', $s);
254 $ret = mb_ereg_replace(''', "'", $ret);
255 $ret = mb_ereg_replace('"', '"', $ret);
256 $ret = mb_ereg_replace('<', "<", $ret);
257 $ret = mb_ereg_replace('>', ">", $ret);
259 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
265 * @brief Paginator function. Pushes relevant links in a pager array structure.
267 * Links are generated depending on the current page and the total number of items.
268 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
269 * Current page link is given the "active" CSS class
271 * @param App $a App instance
272 * @param int $count [optional] item count (used with minimal pager)
273 * @return Array data for pagination template
275 function paginate_data(App $a, $count = null) {
276 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
278 $stripped = str_replace('q=', '', $stripped);
279 $stripped = trim($stripped, '/');
280 $pagenum = $a->pager['page'];
282 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
283 $stripped .= '&offset=' . urlencode($a->page_offset);
289 function _l(&$d, $name, $url, $text, $class = '') {
290 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
291 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
294 $d[$name] = ['url' => $url, 'text' => $text, 'class' => $class];
297 if (!is_null($count)) {
298 // minimal pager (newer / older)
299 $data['class'] = 'pager';
300 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
301 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
303 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
304 $data['class'] = 'pagination';
305 if ($a->pager['total'] > $a->pager['itemspage']) {
306 _l($data, 'first', $url . '&page=1', L10n::t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
307 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), L10n::t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
309 $numpages = $a->pager['total'] / $a->pager['itemspage'];
312 $numstop = $numpages;
314 // Limit the number of displayed page number buttons.
316 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
317 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
322 for ($i = $numstart; $i <= $numstop; $i++) {
323 if ($i == $a->pager['page']) {
324 _l($pages, $i, '#', $i, 'current active');
326 _l($pages, $i, $url . '&page='. $i, $i, 'n');
330 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
331 if ($i == $a->pager['page']) {
332 _l($pages, $i, '#', $i, 'current active');
334 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
338 $data['pages'] = $pages;
340 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
341 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), L10n::t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
342 _l($data, 'last', $url . '&page=' . $lastpage, L10n::t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
351 * Automatic pagination.
353 * To use, get the count of total items.
354 * Then call $a->set_pager_total($number_items);
355 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
356 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
357 * (assuming there are enough items to paginate).
358 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
359 * will limit the results to the correct items for the current page.
360 * The actual page handling is then accomplished at the application layer.
362 * @param App $a App instance
363 * @return string html for pagination #FIXME remove html
365 function paginate(App $a) {
367 $data = paginate_data($a);
368 $tpl = get_markup_template("paginate.tpl");
369 return replace_macros($tpl, ["pager" => $data]);
376 * @param App $a App instance
378 * @return string html for pagination #FIXME remove html
380 function alt_pager(App $a, $i) {
382 $data = paginate_data($a, $i);
383 $tpl = get_markup_template("paginate.tpl");
384 return replace_macros($tpl, ['pager' => $data]);
390 * Loader for infinite scrolling
391 * @return string html for loader
393 function scroll_loader() {
394 $tpl = get_markup_template("scroll_loader.tpl");
395 return replace_macros($tpl, [
396 'wait' => L10n::t('Loading more entries...'),
397 'end' => L10n::t('The end')
403 * Turn user/group ACLs stored as angle bracketed text into arrays
408 function expand_acl($s) {
409 // turn string array of angle-bracketed elements into numeric array
410 // e.g. "<1><2><3>" => array(1,2,3);
414 $t = str_replace('<', '', $s);
415 $a = explode('>', $t);
416 foreach ($a as $aa) {
418 $ret[] = intval($aa);
427 * Wrap ACL elements in angle brackets for storage
428 * @param string $item
430 function sanitise_acl(&$item) {
432 $item = '<' . intval(notags(trim($item))) . '>';
440 * Convert an ACL array to a storable string
442 * Normally ACL permissions will be an array.
443 * We'll also allow a comma-separated string.
445 * @param string|array $p
448 function perms2str($p) {
453 $tmp = explode(',',$p);
456 if (is_array($tmp)) {
457 array_walk($tmp, 'sanitise_acl');
458 $ret = implode('', $tmp);
465 * generate a guaranteed unique (for this domain) item ID for ATOM
466 * safe from birthday paradox
468 * @param string $hostname
472 function item_new_uri($hostname, $uid, $guid = "") {
476 $hash = get_guid(32);
482 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
484 $dups = dba::exists('item', ['uri' => $uri]);
485 } while ($dups == true);
492 * Generate a guaranteed unique photo ID.
493 * safe from birthday paradox
497 function photo_new_resource() {
501 $resource = hash('md5',uniqid(mt_rand(),true));
502 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
506 if (DBM::is_result($r)) {
509 } while ($found == true);
517 * wrapper to load a view template, checking for alternate
518 * languages before falling back to the default
520 * @global string $lang
522 * @param string $s view name
525 function load_view_file($s) {
527 if (! isset($lang)) {
532 if (file_exists("$d/$lang/$b")) {
533 $stamp1 = microtime(true);
534 $content = file_get_contents("$d/$lang/$b");
535 $a->save_timestamp($stamp1, "file");
539 $theme = current_theme();
541 if (file_exists("$d/theme/$theme/$b")) {
542 $stamp1 = microtime(true);
543 $content = file_get_contents("$d/theme/$theme/$b");
544 $a->save_timestamp($stamp1, "file");
548 $stamp1 = microtime(true);
549 $content = file_get_contents($s);
550 $a->save_timestamp($stamp1, "file");
556 * load a view template, checking for alternate
557 * languages before falling back to the default
559 * @global string $lang
560 * @param string $s view path
563 function get_intltext_template($s) {
568 if ($a->theme['template_engine'] === 'smarty3') {
569 $engine = "/smarty3";
572 if (! isset($lang)) {
576 if (file_exists("view/lang/$lang$engine/$s")) {
577 $stamp1 = microtime(true);
578 $content = file_get_contents("view/lang/$lang$engine/$s");
579 $a->save_timestamp($stamp1, "file");
581 } elseif (file_exists("view/lang/en$engine/$s")) {
582 $stamp1 = microtime(true);
583 $content = file_get_contents("view/lang/en$engine/$s");
584 $a->save_timestamp($stamp1, "file");
587 $stamp1 = microtime(true);
588 $content = file_get_contents("view$engine/$s");
589 $a->save_timestamp($stamp1, "file");
599 * @param string $root
602 function get_markup_template($s, $root = '') {
603 $stamp1 = microtime(true);
606 $t = $a->template_engine();
608 $template = $t->getTemplateFile($s, $root);
609 } catch (Exception $e) {
610 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
614 $a->save_timestamp($stamp1, "file");
620 * for html,xml parsing - let's say you've got
621 * an attribute foobar="class1 class2 class3"
622 * and you want to find out if it contains 'class3'.
623 * you can't use a normal sub string search because you
624 * might match 'notclass3' and a regex to do the job is
625 * possible but a bit complicated.
626 * pass the attribute string as $attr and the attribute you
627 * are looking for as $s - returns true if found, otherwise false
629 * @param string $attr attribute value
630 * @param string $s string to search
631 * @return boolean True if found, False otherwise
633 function attribute_contains($attr, $s) {
634 $a = explode(' ', $attr);
635 return (count($a) && in_array($s,$a));
639 /* setup int->string log level map */
643 * @brief Logs the given message at the given log level
646 * LOGGER_NORMAL (default)
653 * @global array $LOGGER_LEVELS
657 function logger($msg, $level = 0) {
659 global $LOGGER_LEVELS;
661 // turn off logger in install mode
663 $a->module == 'install'
669 $debugging = Config::get('system','debugging');
670 $logfile = Config::get('system','logfile');
671 $loglevel = intval(Config::get('system','loglevel'));
676 || $level > $loglevel
681 if (count($LOGGER_LEVELS) == 0) {
682 foreach (get_defined_constants() as $k => $v) {
683 if (substr($k, 0, 7) == "LOGGER_") {
684 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
689 $process_id = session_id();
691 if ($process_id == '') {
692 $process_id = get_app()->process_id;
695 $callers = debug_backtrace();
696 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
697 DateTimeFormat::utcNow(DateTimeFormat::ATOM),
699 $LOGGER_LEVELS[$level],
700 basename($callers[0]['file']),
702 $callers[1]['function'],
706 $stamp1 = microtime(true);
707 @file_put_contents($logfile, $logline, FILE_APPEND);
708 $a->save_timestamp($stamp1, "file");
712 * @brief An alternative logger for development.
713 * Works largely as logger() but allows developers
714 * to isolate particular elements they are targetting
715 * personally without background noise
718 * LOGGER_NORMAL (default)
725 * @global array $LOGGER_LEVELS
730 function dlogger($msg, $level = 0) {
733 // turn off logger in install mode
735 $a->module == 'install'
741 $logfile = Config::get('system', 'dlogfile');
746 $dlogip = Config::get('system', 'dlogip');
747 if (!is_null($dlogip) && $_SERVER['REMOTE_ADDR'] != $dlogip) {
751 if (count($LOGGER_LEVELS) == 0) {
752 foreach (get_defined_constants() as $k => $v) {
753 if (substr($k, 0, 7) == "LOGGER_") {
754 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
759 $process_id = session_id();
761 if ($process_id == '') {
762 $process_id = get_app()->process_id;
765 $callers = debug_backtrace();
766 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
767 DateTimeFormat::utcNow(),
769 basename($callers[0]['file']),
771 $callers[1]['function'],
775 $stamp1 = microtime(true);
776 @file_put_contents($logfile, $logline, FILE_APPEND);
777 $a->save_timestamp($stamp1, "file");
782 * Compare activity uri. Knows about activity namespace.
784 * @param string $haystack
785 * @param string $needle
788 function activity_match($haystack,$needle) {
789 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
794 * @brief Pull out all #hashtags and @person tags from $string.
796 * We also get @person@domain.com - which would make
797 * the regex quite complicated as tags can also
798 * end a sentence. So we'll run through our results
799 * and strip the period from any tags which end with one.
800 * Returns array of tags found, or empty array.
802 * @param string $string Post content
803 * @return array List of tag and person names
805 function get_tags($string) {
808 // Convert hashtag links to hashtags
809 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
811 // ignore anything in a code block
812 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
814 // Force line feeds at bbtags
815 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
817 // ignore anything in a bbtag
818 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
820 // Match full names against @tags including the space between first and last
821 // We will look these up afterward to see if they are full names or not recognisable.
823 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
824 foreach ($matches[1] as $match) {
825 if (strstr($match, ']')) {
826 // we might be inside a bbcode color tag - leave it alone
829 if (substr($match, -1, 1) === '.') {
830 $ret[] = substr($match, 0, -1);
837 // Otherwise pull out single word tags. These can be @nickname, @first_last
840 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
841 foreach ($matches[1] as $match) {
842 if (strstr($match, ']')) {
843 // we might be inside a bbcode color tag - leave it alone
846 if (substr($match, -1, 1) === '.') {
847 $match = substr($match,0,-1);
849 // ignore strictly numeric tags like #1
850 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
853 // try not to catch url fragments
854 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
865 * quick and dirty quoted_printable encoding
871 return str_replace("%", "=", rawurlencode($s));
876 * Get html for contact block.
878 * @template contact_block.tpl
879 * @hook contact_block_end (contacts=>array, output=>string)
882 function contact_block() {
886 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
891 if (!is_array($a->profile) || $a->profile['hide-friends']) {
894 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
895 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
896 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
897 AND `network` IN ('%s', '%s', '%s')",
898 intval($a->profile['uid']),
900 dbesc(NETWORK_OSTATUS),
901 dbesc(NETWORK_DIASPORA)
903 if (DBM::is_result($r)) {
904 $total = intval($r[0]['total']);
907 $contacts = L10n::t('No contacts');
910 // Splitting the query in two parts makes it much faster
911 $r = q("SELECT `id` FROM `contact`
912 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
913 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
914 AND `network` IN ('%s', '%s', '%s')
915 ORDER BY RAND() LIMIT %d",
916 intval($a->profile['uid']),
918 dbesc(NETWORK_OSTATUS),
919 dbesc(NETWORK_DIASPORA),
922 if (DBM::is_result($r)) {
924 foreach ($r AS $contact) {
925 $contacts[] = $contact["id"];
927 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
928 dbesc(implode(",", $contacts)));
930 if (DBM::is_result($r)) {
931 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
933 foreach ($r as $rr) {
934 $micropro[] = micropro($rr, true, 'mpfriend');
940 $tpl = get_markup_template('contact_block.tpl');
941 $o = replace_macros($tpl, [
942 '$contacts' => $contacts,
943 '$nickname' => $a->profile['nickname'],
944 '$viewcontacts' => L10n::t('View Contacts'),
945 '$micropro' => $micropro,
948 $arr = ['contacts' => $r, 'output' => $o];
950 Addon::callHooks('contact_block_end', $arr);
957 * @brief Format contacts as picture links or as texxt links
959 * @param array $contact Array with contacts which contains an array with
960 * int 'id' => The ID of the contact
961 * int 'uid' => The user ID of the user who owns this data
962 * string 'name' => The name of the contact
963 * string 'url' => The url to the profile page of the contact
964 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
965 * string 'network' => The network to which the contact belongs to
966 * string 'thumb' => The contact picture
967 * string 'click' => js code which is performed when clicking on the contact
968 * @param boolean $redirect If true try to use the redir url if it's possible
969 * @param string $class CSS class for the
970 * @param boolean $textmode If true display the contacts as text links
971 * if false display the contacts as picture links
973 * @return string Formatted html
975 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
977 // Use the contact URL if no address is available
978 if (!x($contact, "addr")) {
979 $contact["addr"] = $contact["url"];
982 $url = $contact['url'];
987 $redirect_url = 'redir/' . $contact['id'];
988 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
990 $url = $redirect_url;
991 $sparkle = ' sparkle';
993 $url = Profile::zrl($url);
997 // If there is some js available we don't need the url
998 if (x($contact, 'click')) {
1002 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),[
1003 '$click' => defaults($contact, 'click', ''),
1006 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1007 '$name' => $contact['name'],
1008 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1009 '$parkle' => $sparkle,
1018 * @param string $s Search query.
1019 * @param string $id HTML id
1020 * @param string $url Search url.
1021 * @param bool $save Show save search button.
1022 * @param bool $aside Display the search widgit aside.
1024 * @return string Formatted HTML.
1026 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
1030 if (strpos($s, '#') === 0) {
1033 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
1036 '$s' => htmlspecialchars($s),
1038 '$action_url' => $url,
1039 '$search_label' => L10n::t('Search'),
1040 '$save_label' => $save_label,
1041 '$savedsearch' => Feature::isEnabled(local_user(),'savedsearch'),
1042 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
1047 $values['$searchoption'] = [
1048 L10n::t("Full Text"),
1050 L10n::t("Contacts")];
1052 if (Config::get('system','poco_local_search')) {
1053 $values['$searchoption'][] = L10n::t("Forums");
1057 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1061 * @brief Check for a valid email string
1063 * @param string $email_address
1066 function valid_email($email_address)
1068 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
1073 * Replace naked text hyperlink with HTML formatted hyperlink
1077 function linkify($s) {
1078 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1079 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1087 * @return array index is present tense verb
1088 value is array containing past tense verb, translation of present, translation of past
1089 * @hook poke_verbs pokes array
1091 function get_poke_verbs() {
1093 // index is present tense verb
1094 // value is array containing past tense verb, translation of present, translation of past
1097 'poke' => ['poked', L10n::t('poke'), L10n::t('poked')],
1098 'ping' => ['pinged', L10n::t('ping'), L10n::t('pinged')],
1099 'prod' => ['prodded', L10n::t('prod'), L10n::t('prodded')],
1100 'slap' => ['slapped', L10n::t('slap'), L10n::t('slapped')],
1101 'finger' => ['fingered', L10n::t('finger'), L10n::t('fingered')],
1102 'rebuff' => ['rebuffed', L10n::t('rebuff'), L10n::t('rebuffed')],
1104 Addon::callHooks('poke_verbs', $arr);
1109 * @brief Translate days and months names.
1111 * @param string $s String with day or month name.
1112 * @return string Translated string.
1114 function day_translate($s) {
1115 $ret = str_replace(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
1116 [L10n::t('Monday'), L10n::t('Tuesday'), L10n::t('Wednesday'), L10n::t('Thursday'), L10n::t('Friday'), L10n::t('Saturday'), L10n::t('Sunday')],
1119 $ret = str_replace(['January','February','March','April','May','June','July','August','September','October','November','December'],
1120 [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')],
1127 * @brief Translate short days and months names.
1129 * @param string $s String with short day or month name.
1130 * @return string Translated string.
1132 function day_short_translate($s) {
1133 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
1134 [L10n::t('Mon'), L10n::t('Tue'), L10n::t('Wed'), L10n::t('Thu'), L10n::t('Fri'), L10n::t('Sat'), L10n::t('Sun')],
1136 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'],
1137 [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')],
1146 * @param string $url
1149 function normalise_link($url) {
1150 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
1151 return rtrim($ret,'/');
1156 * Compare two URLs to see if they are the same, but ignore
1157 * slight but hopefully insignificant differences such as if one
1158 * is https and the other isn't, or if one is www.something and
1159 * the other isn't - and also ignore case differences.
1161 * @param string $a first url
1162 * @param string $b second url
1163 * @return boolean True if the URLs match, otherwise False
1166 function link_compare($a, $b) {
1167 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1172 * @brief Find any non-embedded images in private items and add redir links to them
1175 * @param array &$item The field array of an item row
1177 function redir_private_images($a, &$item)
1180 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1182 foreach ($matches as $mtch) {
1183 if (strpos($mtch[1], '/redir') !== false) {
1187 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1188 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1189 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1195 function put_item_in_cache(&$item, $update = false)
1197 $rendered_hash = defaults($item, 'rendered-hash', '');
1199 if ($rendered_hash == ''
1200 || $item["rendered-html"] == ""
1201 || $rendered_hash != hash("md5", $item["body"])
1202 || Config::get("system", "ignore_cache")
1204 // The function "redir_private_images" changes the body.
1205 // I'm not sure if we should store it permanently, so we save the old value.
1206 $body = $item["body"];
1209 redir_private_images($a, $item);
1211 $item["rendered-html"] = prepare_text($item["body"]);
1212 $item["rendered-hash"] = hash("md5", $item["body"]);
1213 $item["body"] = $body;
1215 if ($update && ($item["id"] > 0)) {
1216 dba::update('item', ['rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]],
1217 ['id' => $item["id"]], false);
1223 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1224 * If attach is true, also add icons for item attachments.
1226 * @param array $item
1227 * @param boolean $attach
1228 * @return string item body html
1229 * @hook prepare_body_init item array before any work
1230 * @hook prepare_body ('item'=>item array, 'html'=>body string) 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(&$item, $attach = false, $preview = false) {
1236 Addon::callHooks('prepare_body_init', $item);
1238 $searchpath = System::baseUrl() . "/search?tag=";
1244 // In order to provide theme developers more possibilities, event items
1245 // are treated differently.
1246 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1247 $ev = format_event_item($item);
1251 if (!Config::get('system','suppress_tags')) {
1252 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1253 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1255 while ($tag = dba::fetch($taglist)) {
1256 if ($tag["url"] == "") {
1257 $tag["url"] = $searchpath.strtolower($tag["term"]);
1260 $orig_tag = $tag["url"];
1262 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1264 if ($tag["type"] == TERM_HASHTAG) {
1265 if ($orig_tag != $tag["url"]) {
1266 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1268 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1270 } elseif ($tag["type"] == TERM_MENTION) {
1271 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1274 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1276 dba::close($taglist);
1279 $item['tags'] = $tags;
1280 $item['hashtags'] = $hashtags;
1281 $item['mentions'] = $mentions;
1283 // Update the cached values if there is no "zrl=..." on the links.
1284 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1286 // Or update it if the current viewer is the intented viewer.
1287 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1291 put_item_in_cache($item, $update);
1292 $s = $item["rendered-html"];
1294 $prep_arr = ['item' => $item, 'html' => $s, 'preview' => $preview];
1295 Addon::callHooks('prepare_body', $prep_arr);
1296 $s = $prep_arr['html'];
1299 // Replace the blockquotes with quotes that are used in mails.
1300 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1301 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
1307 $arr = explode('[/attach],', $item['attach']);
1309 foreach ($arr as $r) {
1312 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1314 foreach ($matches as $mtch) {
1317 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1318 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1320 $the_url = $mtch[1];
1323 if (strpos($mime, 'video') !== false) {
1326 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), [
1327 '$baseurl' => System::baseUrl(),
1329 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), [
1330 '$baseurl' => System::baseUrl(),
1334 $id = end(explode('/', $the_url));
1335 $as .= replace_macros(get_markup_template('video_top.tpl'), [
1338 'title' => L10n::t('View Video'),
1345 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1347 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1348 $filesubtype = str_replace('.', '-', $filesubtype);
1351 $filesubtype = 'unkn';
1354 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1355 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
1357 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1358 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1364 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1368 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1369 $x = Map::byCoordinates(trim($item['coord']));
1371 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1376 // Look for spoiler.
1377 $spoilersearch = '<blockquote class="spoiler">';
1379 // Remove line breaks before the spoiler.
1380 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1381 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1383 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1384 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1387 while ((strpos($s, $spoilersearch) !== false)) {
1388 $pos = strpos($s, $spoilersearch);
1389 $rnd = random_string(8);
1390 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1391 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1392 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1395 // Look for quote with author.
1396 $authorsearch = '<blockquote class="author">';
1398 while ((strpos($s, $authorsearch) !== false)) {
1399 $pos = strpos($s, $authorsearch);
1400 $rnd = random_string(8);
1401 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1402 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1403 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1406 // Replace friendica image url size with theme preference.
1407 if (x($a->theme_info, 'item_image_size')){
1408 $ps = $a->theme_info['item_image_size'];
1409 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1412 $prep_arr = ['item' => $item, 'html' => $s];
1413 Addon::callHooks('prepare_body_final', $prep_arr);
1415 return $prep_arr['html'];
1419 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1421 * @param string $text String with bbcode.
1422 * @return string Formattet HTML.
1424 function prepare_text($text) {
1426 require_once 'include/bbcode.php';
1428 if (stristr($text, '[nosmile]')) {
1431 $s = Smilies::replace(bbcode($text));
1438 * return array with details for categories and folders for an item
1440 * @param array $item
1444 * [ // categories array
1446 * 'name': 'category name',
1447 * 'removeurl': 'url to remove this category',
1448 * 'first': 'is the first in this array? true/false',
1449 * 'last': 'is the last in this array? true/false',
1455 * 'name': 'folder name',
1456 * 'removeurl': 'url to remove this folder',
1457 * 'first': 'is the first in this array? true/false',
1458 * 'last': 'is the last in this array? true/false',
1464 function get_cats_and_terms($item)
1471 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1473 foreach ($matches as $mtch) {
1475 'name' => xmlify(file_tag_decode($mtch[1])),
1477 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1485 if (count($categories)) {
1486 $categories[count($categories) - 1]['last'] = true;
1489 if (local_user() == $item['uid']) {
1492 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1494 foreach ($matches as $mtch) {
1496 'name' => xmlify(file_tag_decode($mtch[1])),
1498 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1507 if (count($folders)) {
1508 $folders[count($folders) - 1]['last'] = true;
1511 return [$categories, $folders];
1516 * get private link for item
1517 * @param array $item
1518 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1520 function get_plink($item) {
1523 if ($a->user['nickname'] != "") {
1525 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1526 'href' => "display/" . $item['guid'],
1527 'orig' => "display/" . $item['guid'],
1528 'title' => L10n::t('View on separate page'),
1529 'orig_title' => L10n::t('view on separate page'),
1532 if (x($item, 'plink')) {
1533 $ret["href"] = $a->remove_baseurl($item['plink']);
1534 $ret["title"] = L10n::t('link to source');
1537 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1539 'href' => $item['plink'],
1540 'orig' => $item['plink'],
1541 'title' => L10n::t('link to source'),
1552 * replace html amp entity with amp char
1556 function unamp($s) {
1557 return str_replace('&', '&', $s);
1562 * return number of bytes in size (K, M, G)
1563 * @param string $size_str
1566 function return_bytes($size_str) {
1567 switch (substr ($size_str, -1)) {
1568 case 'M': case 'm': return (int)$size_str * 1048576;
1569 case 'K': case 'k': return (int)$size_str * 1024;
1570 case 'G': case 'g': return (int)$size_str * 1073741824;
1571 default: return $size_str;
1579 function generate_user_guid() {
1582 $guid = get_guid(32);
1583 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1586 if (! DBM::is_result($x)) {
1589 } while ($found == true);
1597 * @param boolean $strip_padding
1600 function base64url_encode($s, $strip_padding = false) {
1602 $s = strtr(base64_encode($s), '+/', '-_');
1604 if ($strip_padding) {
1605 $s = str_replace('=','',$s);
1615 function base64url_decode($s) {
1618 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1623 * // Placeholder for new rev of salmon which strips base64 padding.
1624 * // PHP base64_decode handles the un-padded input without requiring this step
1625 * // Uncomment if you find you need it.
1628 * if (! strpos($s,'=')) {
1638 return base64_decode(strtr($s,'-_','+/'));
1643 * return div element with class 'clear'
1647 function cleardiv() {
1648 return '<div class="clear"></div>';
1652 function bb_translate_video($s) {
1655 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1657 foreach ($matches as $mtch) {
1658 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1659 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1660 elseif (stristr($mtch[1],'vimeo'))
1661 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1667 function html2bb_video($s) {
1669 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1670 '[youtube]$2[/youtube]', $s);
1672 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1673 '[youtube]$2[/youtube]', $s);
1675 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1676 '[vimeo]$2[/vimeo]', $s);
1682 * apply xmlify() to all values of array $val, recursively
1686 function array_xmlify($val){
1687 if (is_bool($val)) {
1688 return $val?"true":"false";
1689 } elseif (is_array($val)) {
1690 return array_map('array_xmlify', $val);
1692 return xmlify((string) $val);
1697 * transform link href and img src from relative to absolute
1699 * @param string $text
1700 * @param string $base base url
1703 function reltoabs($text, $base) {
1708 $base = rtrim($base,'/');
1710 $base2 = $base . "/";
1713 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1714 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1715 $text = preg_replace($pattern, $replace, $text);
1717 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1718 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1719 $text = preg_replace($pattern, $replace, $text);
1722 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1723 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1724 $text = preg_replace($pattern, $replace, $text);
1726 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1727 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1728 $text = preg_replace($pattern, $replace, $text);
1736 * get translated item type
1738 * @param array $itme
1741 function item_post_type($item) {
1742 if (intval($item['event-id'])) {
1743 return L10n::t('event');
1744 } elseif (strlen($item['resource-id'])) {
1745 return L10n::t('photo');
1746 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1747 return L10n::t('activity');
1748 } elseif ($item['id'] != $item['parent']) {
1749 return L10n::t('comment');
1752 return L10n::t('post');
1755 // post categories and "save to file" use the same item.file table for storage.
1756 // We will differentiate the different uses by wrapping categories in angle brackets
1757 // and save to file categories in square brackets.
1758 // To do this we need to escape these characters if they appear in our tag.
1760 function file_tag_encode($s) {
1761 return str_replace(['<','>','[',']'],['%3c','%3e','%5b','%5d'],$s);
1764 function file_tag_decode($s) {
1765 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
1768 function file_tag_file_query($table,$s,$type = 'file') {
1770 if ($type == 'file') {
1771 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1773 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1775 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1778 // ex. given music,video return <music><video> or [music][video]
1779 function file_tag_list_to_file($list,$type = 'file') {
1781 if (strlen($list)) {
1782 $list_array = explode(",",$list);
1783 if ($type == 'file') {
1791 foreach ($list_array as $item) {
1792 if (strlen($item)) {
1793 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1800 // ex. given <music><video>[friends], return music,video or friends
1801 function file_tag_file_to_list($file,$type = 'file') {
1804 if ($type == 'file') {
1805 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1807 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1810 foreach ($matches as $mtch) {
1811 if (strlen($list)) {
1814 $list .= file_tag_decode($mtch[1]);
1821 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1822 // $file_old - categories previously associated with an item
1823 // $file_new - new list of categories for an item
1825 if (!intval($uid)) {
1828 if ($file_old == $file_new) {
1832 $saved = PConfig::get($uid, 'system', 'filetags');
1833 if (strlen($saved)) {
1834 if ($type == 'file') {
1837 $termtype = TERM_FILE;
1841 $termtype = TERM_CATEGORY;
1844 $filetags_updated = $saved;
1846 // check for new tags to be added as filetags in pconfig
1848 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1850 foreach ($check_new_tags as $tag) {
1851 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1855 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1857 // check for deleted tags to be removed from filetags in pconfig
1859 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1861 foreach ($check_deleted_tags as $tag) {
1862 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1863 $deleted_tags[] = $tag;
1866 foreach ($deleted_tags as $key => $tag) {
1867 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1869 intval(TERM_OBJ_POST),
1873 if (DBM::is_result($r)) {
1874 unset($deleted_tags[$key]);
1876 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1880 if ($saved != $filetags_updated) {
1881 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1884 } elseif (strlen($file_new)) {
1885 PConfig::set($uid, 'system', 'filetags', $file_new);
1890 function file_tag_save_file($uid, $item, $file)
1892 if (! intval($uid)) {
1896 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1900 if (DBM::is_result($r)) {
1901 if (!stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1902 $fields = ['file' => $r[0]['file'] . '[' . file_tag_encode($file) . ']'];
1903 Item::update($fields, ['id' => $item]);
1905 $saved = PConfig::get($uid, 'system', 'filetags');
1906 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1907 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1909 info(L10n::t('Item filed'));
1914 function file_tag_unsave_file($uid, $item, $file, $cat = false)
1916 if (! intval($uid)) {
1921 $pattern = '<' . file_tag_encode($file) . '>' ;
1922 $termtype = TERM_CATEGORY;
1924 $pattern = '[' . file_tag_encode($file) . ']' ;
1925 $termtype = TERM_FILE;
1928 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1932 if (! DBM::is_result($r)) {
1936 $fields = ['file' => str_replace($pattern,'',$r[0]['file'])];
1937 Item::update($fields, ['id' => $item]);
1939 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1941 intval(TERM_OBJ_POST),
1945 if (!DBM::is_result($r)) {
1946 $saved = PConfig::get($uid, 'system', 'filetags');
1947 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1953 function normalise_openid($s) {
1954 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
1958 function undo_post_tagging($s) {
1960 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1962 foreach ($matches as $mtch) {
1963 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1969 function protect_sprintf($s) {
1970 return str_replace('%', '%%', $s);
1974 function is_a_date_arg($s) {
1978 if ($i <= $y + 1 && strpos($s, '-') == 4) {
1979 $m = intval(substr($s,5));
1980 if ($m > 0 && $m <= 12)
1988 * remove intentation from a text
1990 function deindent($text, $chr = "[\t ]", $count = NULL) {
1991 $lines = explode("\n", $text);
1992 if (is_null($count)) {
1995 while ($k < count($lines) && strlen($lines[$k]) == 0) {
1998 preg_match("|^" . $chr . "*|", $lines[$k], $m);
1999 $count = strlen($m[0]);
2001 for ($k = 0; $k < count($lines); $k++) {
2002 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2005 return implode("\n", $lines);
2008 function formatBytes($bytes, $precision = 2) {
2009 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
2011 $bytes = max($bytes, 0);
2012 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2013 $pow = min($pow, count($units) - 1);
2015 $bytes /= pow(1024, $pow);
2017 return round($bytes, $precision) . ' ' . $units[$pow];
2021 * @brief translate and format the networkname of a contact
2023 * @param string $network
2024 * Networkname of the contact (e.g. dfrn, rss and so on)
2029 function format_network_name($network, $url = 0) {
2030 if ($network != "") {
2032 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
2034 $network_name = ContactSelector::networkToName($network);
2037 return $network_name;
2042 * @brief Syntax based code highlighting for popular languages.
2043 * @param string $s Code block
2044 * @param string $lang Programming language
2045 * @return string Formated html
2047 function text_highlight($s, $lang) {
2048 if ($lang === 'js') {
2049 $lang = 'javascript';
2052 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2054 // Autoload the library to make constants available
2055 class_exists('Text_Highlighter_Renderer_Html');
2058 'numbers' => HL_NUMBERS_LI,
2063 $s = trim(html_entity_decode($s, ENT_COMPAT));
2064 $s = str_replace(' ', "\t", $s);
2067 * The highlighter library insists on an opening php tag for php code blocks. If
2068 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2069 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2071 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2072 $s = '<?php' . "\n" . $s;
2076 $renderer = new Text_Highlighter_Renderer_Html($options);
2077 $factory = new Text_Highlighter();
2078 $hl = $factory->factory($lang);
2079 $hl->setRenderer($renderer);
2080 $o = $hl->highlight($s);
2081 $o = str_replace("\n", '', $o);
2084 $b = substr($o, 0, strpos($o, '<li>'));
2085 $e = substr($o, strpos($o, '</li>'));
2089 return '<code>' . $o . '</code>';