3 * @file include/text.php
6 use Friendica\Content\ContactSelector;
7 use Friendica\Content\Feature;
8 use Friendica\Content\Smilies;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Profile;
15 use Friendica\Model\Term;
16 use Friendica\Util\Map;
18 require_once "include/friendica_smarty.php";
19 require_once "mod/proxy.php";
20 require_once "include/conversation.php";
23 * This is our template processor
25 * @param string|FriendicaSmarty $s the string requiring macro substitution,
26 * or an instance of FriendicaSmarty
27 * @param array $r key value pairs (search => replace)
28 * @return string substituted string
30 function replace_macros($s, $r) {
32 $stamp1 = microtime(true);
36 // pass $baseurl to all templates
37 $r['$baseurl'] = System::baseUrl();
39 $t = $a->template_engine();
41 $output = $t->replaceMacros($s, $r);
42 } catch (Exception $e) {
43 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
47 $a->save_timestamp($stamp1, "rendering");
53 * @brief Generates a pseudo-random string of hexadecimal characters
58 function random_string($size = 64)
60 $byte_size = ceil($size / 2);
62 $bytes = random_bytes($byte_size);
64 $return = substr(bin2hex($bytes), 0, $size);
70 * This is our primary input filter.
72 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
73 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
74 * after cleansing, and angle chars with the high bit set could get through as markup.
76 * This is now disabled because it was interfering with some legitimate unicode sequences
77 * and hopefully there aren't a lot of those browsers left.
79 * Use this on any text input where angle chars are not valid or permitted
80 * They will be replaced with safer brackets. This may be filtered further
81 * if these are not allowed either.
83 * @param string $string Input string
84 * @return string Filtered string
86 function notags($string) {
87 return str_replace(["<", ">"], ['[', ']'], $string);
89 // High-bit filter no longer used
90 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
95 * use this on "body" or "content" input where angle chars shouldn't be removed,
96 * and allow them to be safely displayed.
97 * @param string $string
100 function escape_tags($string) {
101 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
106 * generate a string that's random, but usually pronounceable.
107 * used to generate initial passwords
111 function autoname($len) {
117 $vowels = ['a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'];
118 if (mt_rand(0, 5) == 4) {
137 's','sc','sh','sm','sp','st',
145 $midcons = ['ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
146 'nd','ng','nk','nt','rn','rp','rt'];
148 $noend = ['bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
149 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh'];
151 $start = mt_rand(0,2);
160 for ($x = 0; $x < $len; $x ++) {
161 $r = mt_rand(0,count($table) - 1);
164 if ($table == $vowels) {
165 $table = array_merge($cons,$midcons);
172 $word = substr($word,0,$len);
174 foreach ($noend as $noe) {
175 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
176 $word = substr($word, 0, -1);
180 if (substr($word, -1) == 'q') {
181 $word = substr($word, 0, -1);
188 * escape text ($str) for XML transport
190 * @return string Escaped text.
192 function xmlify($str) {
193 /// @TODO deprecated code found?
196 $len = mb_strlen($str);
197 for ($x = 0; $x < $len; $x ++) {
198 $char = mb_substr($str,$x,1);
228 $buffer = mb_ereg_replace("&", "&", $str);
229 $buffer = mb_ereg_replace("'", "'", $buffer);
230 $buffer = mb_ereg_replace('"', """, $buffer);
231 $buffer = mb_ereg_replace("<", "<", $buffer);
232 $buffer = mb_ereg_replace(">", ">", $buffer);
234 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
235 $buffer = trim($buffer);
243 * @param string $s xml escaped text
244 * @return string unescaped text
246 function unxmlify($s) {
247 /// @TODO deprecated code found?
248 // $ret = str_replace('&','&', $s);
249 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
250 /*$ret = mb_ereg_replace('&', '&', $s);
251 $ret = mb_ereg_replace(''', "'", $ret);
252 $ret = mb_ereg_replace('"', '"', $ret);
253 $ret = mb_ereg_replace('<', "<", $ret);
254 $ret = mb_ereg_replace('>', ">", $ret);
256 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
262 * @brief Paginator function. Pushes relevant links in a pager array structure.
264 * Links are generated depending on the current page and the total number of items.
265 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
266 * Current page link is given the "active" CSS class
268 * @param App $a App instance
269 * @param int $count [optional] item count (used with minimal pager)
270 * @return Array data for pagination template
272 function paginate_data(App $a, $count = null) {
273 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
275 $stripped = str_replace('q=', '', $stripped);
276 $stripped = trim($stripped, '/');
277 $pagenum = $a->pager['page'];
279 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
280 $stripped .= '&offset=' . urlencode($a->page_offset);
286 function _l(&$d, $name, $url, $text, $class = '') {
287 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
288 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
291 $d[$name] = ['url' => $url, 'text' => $text, 'class' => $class];
294 if (!is_null($count)) {
295 // minimal pager (newer / older)
296 $data['class'] = 'pager';
297 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
298 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
300 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
301 $data['class'] = 'pagination';
302 if ($a->pager['total'] > $a->pager['itemspage']) {
303 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
304 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
306 $numpages = $a->pager['total'] / $a->pager['itemspage'];
309 $numstop = $numpages;
311 // Limit the number of displayed page number buttons.
313 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
314 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
319 for ($i = $numstart; $i <= $numstop; $i++) {
320 if ($i == $a->pager['page']) {
321 _l($pages, $i, '#', $i, 'current active');
323 _l($pages, $i, $url . '&page='. $i, $i, 'n');
327 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
328 if ($i == $a->pager['page']) {
329 _l($pages, $i, '#', $i, 'current active');
331 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
335 $data['pages'] = $pages;
337 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
338 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
339 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
348 * Automatic pagination.
350 * To use, get the count of total items.
351 * Then call $a->set_pager_total($number_items);
352 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
353 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
354 * (assuming there are enough items to paginate).
355 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
356 * will limit the results to the correct items for the current page.
357 * The actual page handling is then accomplished at the application layer.
359 * @param App $a App instance
360 * @return string html for pagination #FIXME remove html
362 function paginate(App $a) {
364 $data = paginate_data($a);
365 $tpl = get_markup_template("paginate.tpl");
366 return replace_macros($tpl, ["pager" => $data]);
373 * @param App $a App instance
375 * @return string html for pagination #FIXME remove html
377 function alt_pager(App $a, $i) {
379 $data = paginate_data($a, $i);
380 $tpl = get_markup_template("paginate.tpl");
381 return replace_macros($tpl, ['pager' => $data]);
387 * Loader for infinite scrolling
388 * @return string html for loader
390 function scroll_loader() {
391 $tpl = get_markup_template("scroll_loader.tpl");
392 return replace_macros($tpl, [
393 'wait' => t('Loading more entries...'),
394 'end' => t('The end')
400 * Turn user/group ACLs stored as angle bracketed text into arrays
405 function expand_acl($s) {
406 // turn string array of angle-bracketed elements into numeric array
407 // e.g. "<1><2><3>" => array(1,2,3);
411 $t = str_replace('<', '', $s);
412 $a = explode('>', $t);
413 foreach ($a as $aa) {
415 $ret[] = intval($aa);
424 * Wrap ACL elements in angle brackets for storage
425 * @param string $item
427 function sanitise_acl(&$item) {
429 $item = '<' . intval(notags(trim($item))) . '>';
437 * Convert an ACL array to a storable string
439 * Normally ACL permissions will be an array.
440 * We'll also allow a comma-separated string.
442 * @param string|array $p
445 function perms2str($p) {
450 $tmp = explode(',',$p);
453 if (is_array($tmp)) {
454 array_walk($tmp, 'sanitise_acl');
455 $ret = implode('', $tmp);
462 * generate a guaranteed unique (for this domain) item ID for ATOM
463 * safe from birthday paradox
465 * @param string $hostname
469 function item_new_uri($hostname, $uid, $guid = "") {
473 $hash = get_guid(32);
479 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
481 $dups = dba::exists('item', ['uri' => $uri]);
482 } while ($dups == true);
489 * Generate a guaranteed unique photo ID.
490 * safe from birthday paradox
494 function photo_new_resource() {
498 $resource = hash('md5',uniqid(mt_rand(),true));
499 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
503 if (DBM::is_result($r)) {
506 } while ($found == true);
514 * wrapper to load a view template, checking for alternate
515 * languages before falling back to the default
517 * @global string $lang
519 * @param string $s view name
522 function load_view_file($s) {
524 if (! isset($lang)) {
529 if (file_exists("$d/$lang/$b")) {
530 $stamp1 = microtime(true);
531 $content = file_get_contents("$d/$lang/$b");
532 $a->save_timestamp($stamp1, "file");
536 $theme = current_theme();
538 if (file_exists("$d/theme/$theme/$b")) {
539 $stamp1 = microtime(true);
540 $content = file_get_contents("$d/theme/$theme/$b");
541 $a->save_timestamp($stamp1, "file");
545 $stamp1 = microtime(true);
546 $content = file_get_contents($s);
547 $a->save_timestamp($stamp1, "file");
553 * load a view template, checking for alternate
554 * languages before falling back to the default
556 * @global string $lang
557 * @param string $s view path
560 function get_intltext_template($s) {
565 if ($a->theme['template_engine'] === 'smarty3') {
566 $engine = "/smarty3";
569 if (! isset($lang)) {
573 if (file_exists("view/lang/$lang$engine/$s")) {
574 $stamp1 = microtime(true);
575 $content = file_get_contents("view/lang/$lang$engine/$s");
576 $a->save_timestamp($stamp1, "file");
578 } elseif (file_exists("view/lang/en$engine/$s")) {
579 $stamp1 = microtime(true);
580 $content = file_get_contents("view/lang/en$engine/$s");
581 $a->save_timestamp($stamp1, "file");
584 $stamp1 = microtime(true);
585 $content = file_get_contents("view$engine/$s");
586 $a->save_timestamp($stamp1, "file");
596 * @param string $root
599 function get_markup_template($s, $root = '') {
600 $stamp1 = microtime(true);
603 $t = $a->template_engine();
605 $template = $t->getTemplateFile($s, $root);
606 } catch (Exception $e) {
607 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
611 $a->save_timestamp($stamp1, "file");
620 * @param string $filename
621 * @param string $root
624 function get_template_file($a, $filename, $root = '') {
625 $theme = current_theme();
627 // Make sure $root ends with a slash /
628 if ($root !== '' && substr($root, -1, 1) !== '/') {
632 if (file_exists("{$root}view/theme/$theme/$filename")) {
633 $template_file = "{$root}view/theme/$theme/$filename";
634 } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
635 $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
636 } elseif (file_exists("{$root}/$filename")) {
637 $template_file = "{$root}/$filename";
639 $template_file = "{$root}view/$filename";
642 return $template_file;
647 * for html,xml parsing - let's say you've got
648 * an attribute foobar="class1 class2 class3"
649 * and you want to find out if it contains 'class3'.
650 * you can't use a normal sub string search because you
651 * might match 'notclass3' and a regex to do the job is
652 * possible but a bit complicated.
653 * pass the attribute string as $attr and the attribute you
654 * are looking for as $s - returns true if found, otherwise false
656 * @param string $attr attribute value
657 * @param string $s string to search
658 * @return boolean True if found, False otherwise
660 function attribute_contains($attr, $s) {
661 $a = explode(' ', $attr);
662 return (count($a) && in_array($s,$a));
666 /* setup int->string log level map */
670 * @brief Logs the given message at the given log level
673 * LOGGER_NORMAL (default)
680 * @global array $LOGGER_LEVELS
684 function logger($msg, $level = 0) {
686 global $LOGGER_LEVELS;
688 // turn off logger in install mode
690 $a->module == 'install'
696 $debugging = Config::get('system','debugging');
697 $logfile = Config::get('system','logfile');
698 $loglevel = intval(Config::get('system','loglevel'));
703 || $level > $loglevel
708 if (count($LOGGER_LEVELS) == 0) {
709 foreach (get_defined_constants() as $k => $v) {
710 if (substr($k, 0, 7) == "LOGGER_") {
711 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
716 $process_id = session_id();
718 if ($process_id == '') {
719 $process_id = get_app()->process_id;
722 $callers = debug_backtrace();
723 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
724 datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
726 $LOGGER_LEVELS[$level],
727 basename($callers[0]['file']),
729 $callers[1]['function'],
733 $stamp1 = microtime(true);
734 @file_put_contents($logfile, $logline, FILE_APPEND);
735 $a->save_timestamp($stamp1, "file");
739 * @brief An alternative logger for development.
740 * Works largely as logger() but allows developers
741 * to isolate particular elements they are targetting
742 * personally without background noise
745 * LOGGER_NORMAL (default)
752 * @global array $LOGGER_LEVELS
757 function dlogger($msg, $level = 0) {
760 // turn off logger in install mode
762 $a->module == 'install'
768 $logfile = Config::get('system','dlogfile');
774 if (count($LOGGER_LEVELS) == 0) {
775 foreach (get_defined_constants() as $k => $v) {
776 if (substr($k, 0, 7) == "LOGGER_") {
777 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
782 $process_id = session_id();
784 if ($process_id == '') {
785 $process_id = get_app()->process_id;
788 $callers = debug_backtrace();
789 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
792 basename($callers[0]['file']),
794 $callers[1]['function'],
798 $stamp1 = microtime(true);
799 @file_put_contents($logfile, $logline, FILE_APPEND);
800 $a->save_timestamp($stamp1, "file");
805 * Compare activity uri. Knows about activity namespace.
807 * @param string $haystack
808 * @param string $needle
811 function activity_match($haystack,$needle) {
812 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
817 * @brief Pull out all #hashtags and @person tags from $string.
819 * We also get @person@domain.com - which would make
820 * the regex quite complicated as tags can also
821 * end a sentence. So we'll run through our results
822 * and strip the period from any tags which end with one.
823 * Returns array of tags found, or empty array.
825 * @param string $string Post content
826 * @return array List of tag and person names
828 function get_tags($string) {
831 // Convert hashtag links to hashtags
832 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
834 // ignore anything in a code block
835 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
837 // Force line feeds at bbtags
838 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
840 // ignore anything in a bbtag
841 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
843 // Match full names against @tags including the space between first and last
844 // We will look these up afterward to see if they are full names or not recognisable.
846 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
847 foreach ($matches[1] as $match) {
848 if (strstr($match, ']')) {
849 // we might be inside a bbcode color tag - leave it alone
852 if (substr($match, -1, 1) === '.') {
853 $ret[] = substr($match, 0, -1);
860 // Otherwise pull out single word tags. These can be @nickname, @first_last
863 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
864 foreach ($matches[1] as $match) {
865 if (strstr($match, ']')) {
866 // we might be inside a bbcode color tag - leave it alone
869 if (substr($match, -1, 1) === '.') {
870 $match = substr($match,0,-1);
872 // ignore strictly numeric tags like #1
873 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
876 // try not to catch url fragments
877 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
888 * quick and dirty quoted_printable encoding
894 return str_replace("%", "=", rawurlencode($s));
899 * Get html for contact block.
901 * @template contact_block.tpl
902 * @hook contact_block_end (contacts=>array, output=>string)
905 function contact_block() {
909 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
914 if (!is_array($a->profile) || $a->profile['hide-friends']) {
917 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
918 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
919 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
920 AND `network` IN ('%s', '%s', '%s')",
921 intval($a->profile['uid']),
923 dbesc(NETWORK_OSTATUS),
924 dbesc(NETWORK_DIASPORA)
926 if (DBM::is_result($r)) {
927 $total = intval($r[0]['total']);
930 $contacts = t('No contacts');
933 // Splitting the query in two parts makes it much faster
934 $r = q("SELECT `id` FROM `contact`
935 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
936 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
937 AND `network` IN ('%s', '%s', '%s')
938 ORDER BY RAND() LIMIT %d",
939 intval($a->profile['uid']),
941 dbesc(NETWORK_OSTATUS),
942 dbesc(NETWORK_DIASPORA),
945 if (DBM::is_result($r)) {
947 foreach ($r AS $contact) {
948 $contacts[] = $contact["id"];
950 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
951 dbesc(implode(",", $contacts)));
953 if (DBM::is_result($r)) {
954 $contacts = sprintf(tt('%d Contact','%d Contacts', $total),$total);
956 foreach ($r as $rr) {
957 $micropro[] = micropro($rr,true,'mpfriend');
963 $tpl = get_markup_template('contact_block.tpl');
964 $o = replace_macros($tpl, [
965 '$contacts' => $contacts,
966 '$nickname' => $a->profile['nickname'],
967 '$viewcontacts' => t('View Contacts'),
968 '$micropro' => $micropro,
971 $arr = ['contacts' => $r, 'output' => $o];
973 Addon::callHooks('contact_block_end', $arr);
980 * @brief Format contacts as picture links or as texxt links
982 * @param array $contact Array with contacts which contains an array with
983 * int 'id' => The ID of the contact
984 * int 'uid' => The user ID of the user who owns this data
985 * string 'name' => The name of the contact
986 * string 'url' => The url to the profile page of the contact
987 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
988 * string 'network' => The network to which the contact belongs to
989 * string 'thumb' => The contact picture
990 * string 'click' => js code which is performed when clicking on the contact
991 * @param boolean $redirect If true try to use the redir url if it's possible
992 * @param string $class CSS class for the
993 * @param boolean $textmode If true display the contacts as text links
994 * if false display the contacts as picture links
996 * @return string Formatted html
998 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
1000 // Use the contact URL if no address is available
1001 if (!x($contact, "addr")) {
1002 $contact["addr"] = $contact["url"];
1005 $url = $contact['url'];
1010 $redirect_url = 'redir/' . $contact['id'];
1011 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1013 $url = $redirect_url;
1014 $sparkle = ' sparkle';
1016 $url = Profile::zrl($url);
1020 // If there is some js available we don't need the url
1021 if (x($contact, 'click')) {
1025 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),[
1026 '$click' => defaults($contact, 'click', ''),
1029 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1030 '$name' => $contact['name'],
1031 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1032 '$parkle' => $sparkle,
1041 * @param string $s Search query.
1042 * @param string $id HTML id
1043 * @param string $url Search url.
1044 * @param bool $save Show save search button.
1045 * @param bool $aside Display the search widgit aside.
1047 * @return string Formatted HTML.
1049 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
1053 if (strpos($s, '#') === 0) {
1056 $save_label = $mode === 'text' ? t('Save') : t('Follow');
1059 '$s' => htmlspecialchars($s),
1061 '$action_url' => $url,
1062 '$search_label' => t('Search'),
1063 '$save_label' => $save_label,
1064 '$savedsearch' => Feature::isEnabled(local_user(),'savedsearch'),
1065 '$search_hint' => t('@name, !forum, #tags, content'),
1070 $values['$searchoption'] = [
1075 if (Config::get('system','poco_local_search')) {
1076 $values['$searchoption'][] = t("Forums");
1080 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1084 * @brief Check for a valid email string
1086 * @param string $email_address
1089 function valid_email($email_address)
1091 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
1096 * Replace naked text hyperlink with HTML formatted hyperlink
1100 function linkify($s) {
1101 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1102 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1110 * @return array index is present tense verb
1111 value is array containing past tense verb, translation of present, translation of past
1112 * @hook poke_verbs pokes array
1114 function get_poke_verbs() {
1116 // index is present tense verb
1117 // value is array containing past tense verb, translation of present, translation of past
1120 'poke' => ['poked', t('poke'), t('poked')],
1121 'ping' => ['pinged', t('ping'), t('pinged')],
1122 'prod' => ['prodded', t('prod'), t('prodded')],
1123 'slap' => ['slapped', t('slap'), t('slapped')],
1124 'finger' => ['fingered', t('finger'), t('fingered')],
1125 'rebuff' => ['rebuffed', t('rebuff'), t('rebuffed')],
1127 Addon::callHooks('poke_verbs', $arr);
1132 * @brief Translate days and months names.
1134 * @param string $s String with day or month name.
1135 * @return string Translated string.
1137 function day_translate($s) {
1138 $ret = str_replace(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
1139 [t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')],
1142 $ret = str_replace(['January','February','March','April','May','June','July','August','September','October','November','December'],
1143 [t('January'), t('February'), t('March'), t('April'), t('May'), t('June'), t('July'), t('August'), t('September'), t('October'), t('November'), t('December')],
1150 * @brief Translate short days and months names.
1152 * @param string $s String with short day or month name.
1153 * @return string Translated string.
1155 function day_short_translate($s) {
1156 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
1157 [t('Mon'), t('Tue'), t('Wed'), t('Thu'), t('Fri'), t('Sat'), t('Sun')],
1159 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'],
1160 [t('Jan'), t('Feb'), t('Mar'), t('Apr'), t('May'), ('Jun'), t('Jul'), t('Aug'), t('Sep'), t('Oct'), t('Nov'), t('Dec')],
1169 * @param string $url
1172 function normalise_link($url) {
1173 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
1174 return rtrim($ret,'/');
1179 * Compare two URLs to see if they are the same, but ignore
1180 * slight but hopefully insignificant differences such as if one
1181 * is https and the other isn't, or if one is www.something and
1182 * the other isn't - and also ignore case differences.
1184 * @param string $a first url
1185 * @param string $b second url
1186 * @return boolean True if the URLs match, otherwise False
1189 function link_compare($a, $b) {
1190 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1195 * @brief Find any non-embedded images in private items and add redir links to them
1198 * @param array &$item The field array of an item row
1200 function redir_private_images($a, &$item)
1203 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1205 foreach ($matches as $mtch) {
1206 if (strpos($mtch[1], '/redir') !== false) {
1210 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1211 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1212 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1218 function put_item_in_cache(&$item, $update = false)
1220 $rendered_hash = defaults($item, 'rendered-hash', '');
1222 if ($rendered_hash == ''
1223 || $item["rendered-html"] == ""
1224 || $rendered_hash != hash("md5", $item["body"])
1225 || Config::get("system", "ignore_cache")
1227 // The function "redir_private_images" changes the body.
1228 // I'm not sure if we should store it permanently, so we save the old value.
1229 $body = $item["body"];
1232 redir_private_images($a, $item);
1234 $item["rendered-html"] = prepare_text($item["body"]);
1235 $item["rendered-hash"] = hash("md5", $item["body"]);
1236 $item["body"] = $body;
1238 if ($update && ($item["id"] > 0)) {
1239 dba::update('item', ['rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]],
1240 ['id' => $item["id"]], false);
1246 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1247 * If attach is true, also add icons for item attachments.
1249 * @param array $item
1250 * @param boolean $attach
1251 * @return string item body html
1252 * @hook prepare_body_init item array before any work
1253 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1254 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1256 function prepare_body(&$item, $attach = false, $preview = false) {
1259 Addon::callHooks('prepare_body_init', $item);
1261 $searchpath = System::baseUrl() . "/search?tag=";
1267 // In order to provide theme developers more possibilities, event items
1268 // are treated differently.
1269 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1270 $ev = format_event_item($item);
1274 if (!Config::get('system','suppress_tags')) {
1275 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1276 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1278 while ($tag = dba::fetch($taglist)) {
1279 if ($tag["url"] == "") {
1280 $tag["url"] = $searchpath.strtolower($tag["term"]);
1283 $orig_tag = $tag["url"];
1285 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1287 if ($tag["type"] == TERM_HASHTAG) {
1288 if ($orig_tag != $tag["url"]) {
1289 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1291 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1293 } elseif ($tag["type"] == TERM_MENTION) {
1294 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1297 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1299 dba::close($taglist);
1302 $item['tags'] = $tags;
1303 $item['hashtags'] = $hashtags;
1304 $item['mentions'] = $mentions;
1306 // Update the cached values if there is no "zrl=..." on the links.
1307 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1309 // Or update it if the current viewer is the intented viewer.
1310 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1314 put_item_in_cache($item, $update);
1315 $s = $item["rendered-html"];
1317 $prep_arr = ['item' => $item, 'html' => $s, 'preview' => $preview];
1318 Addon::callHooks('prepare_body', $prep_arr);
1319 $s = $prep_arr['html'];
1322 // Replace the blockquotes with quotes that are used in mails.
1323 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1324 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
1330 $arr = explode('[/attach],', $item['attach']);
1332 foreach ($arr as $r) {
1335 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1337 foreach ($matches as $mtch) {
1340 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1341 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1343 $the_url = $mtch[1];
1346 if (strpos($mime, 'video') !== false) {
1349 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), [
1350 '$baseurl' => System::baseUrl(),
1352 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), [
1353 '$baseurl' => System::baseUrl(),
1357 $id = end(explode('/', $the_url));
1358 $as .= replace_macros(get_markup_template('video_top.tpl'), [
1361 'title' => t('View Video'),
1368 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1370 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1371 $filesubtype = str_replace('.', '-', $filesubtype);
1374 $filesubtype = 'unkn';
1377 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1378 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1380 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1381 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1387 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1391 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1392 $x = Map::byCoordinates(trim($item['coord']));
1394 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1399 // Look for spoiler.
1400 $spoilersearch = '<blockquote class="spoiler">';
1402 // Remove line breaks before the spoiler.
1403 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1404 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1406 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1407 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1410 while ((strpos($s, $spoilersearch) !== false)) {
1411 $pos = strpos($s, $spoilersearch);
1412 $rnd = random_string(8);
1413 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1414 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1415 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1418 // Look for quote with author.
1419 $authorsearch = '<blockquote class="author">';
1421 while ((strpos($s, $authorsearch) !== false)) {
1422 $pos = strpos($s, $authorsearch);
1423 $rnd = random_string(8);
1424 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1425 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1426 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1429 // Replace friendica image url size with theme preference.
1430 if (x($a->theme_info, 'item_image_size')){
1431 $ps = $a->theme_info['item_image_size'];
1432 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1435 $prep_arr = ['item' => $item, 'html' => $s];
1436 Addon::callHooks('prepare_body_final', $prep_arr);
1438 return $prep_arr['html'];
1442 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1444 * @param string $text String with bbcode.
1445 * @return string Formattet HTML.
1447 function prepare_text($text) {
1449 require_once 'include/bbcode.php';
1451 if (stristr($text, '[nosmile]')) {
1454 $s = Smilies::replace(bbcode($text));
1461 * return array with details for categories and folders for an item
1463 * @param array $item
1467 * [ // categories array
1469 * 'name': 'category name',
1470 * 'removeurl': 'url to remove this category',
1471 * 'first': 'is the first in this array? true/false',
1472 * 'last': 'is the last in this array? true/false',
1478 * 'name': 'folder name',
1479 * 'removeurl': 'url to remove this folder',
1480 * 'first': 'is the first in this array? true/false',
1481 * 'last': 'is the last in this array? true/false',
1487 function get_cats_and_terms($item)
1494 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1496 foreach ($matches as $mtch) {
1498 'name' => xmlify(file_tag_decode($mtch[1])),
1500 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1508 if (count($categories)) {
1509 $categories[count($categories) - 1]['last'] = true;
1512 if (local_user() == $item['uid']) {
1515 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1517 foreach ($matches as $mtch) {
1519 'name' => xmlify(file_tag_decode($mtch[1])),
1521 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1530 if (count($folders)) {
1531 $folders[count($folders) - 1]['last'] = true;
1534 return [$categories, $folders];
1539 * get private link for item
1540 * @param array $item
1541 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1543 function get_plink($item) {
1546 if ($a->user['nickname'] != "") {
1548 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1549 'href' => "display/" . $item['guid'],
1550 'orig' => "display/" . $item['guid'],
1551 'title' => t('View on separate page'),
1552 'orig_title' => t('view on separate page'),
1555 if (x($item, 'plink')) {
1556 $ret["href"] = $a->remove_baseurl($item['plink']);
1557 $ret["title"] = t('link to source');
1560 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1562 'href' => $item['plink'],
1563 'orig' => $item['plink'],
1564 'title' => t('link to source'),
1575 * replace html amp entity with amp char
1579 function unamp($s) {
1580 return str_replace('&', '&', $s);
1585 * return number of bytes in size (K, M, G)
1586 * @param string $size_str
1589 function return_bytes($size_str) {
1590 switch (substr ($size_str, -1)) {
1591 case 'M': case 'm': return (int)$size_str * 1048576;
1592 case 'K': case 'k': return (int)$size_str * 1024;
1593 case 'G': case 'g': return (int)$size_str * 1073741824;
1594 default: return $size_str;
1602 function generate_user_guid() {
1605 $guid = get_guid(32);
1606 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1609 if (! DBM::is_result($x)) {
1612 } while ($found == true);
1620 * @param boolean $strip_padding
1623 function base64url_encode($s, $strip_padding = false) {
1625 $s = strtr(base64_encode($s), '+/', '-_');
1627 if ($strip_padding) {
1628 $s = str_replace('=','',$s);
1638 function base64url_decode($s) {
1641 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1646 * // Placeholder for new rev of salmon which strips base64 padding.
1647 * // PHP base64_decode handles the un-padded input without requiring this step
1648 * // Uncomment if you find you need it.
1651 * if (! strpos($s,'=')) {
1661 return base64_decode(strtr($s,'-_','+/'));
1666 * return div element with class 'clear'
1670 function cleardiv() {
1671 return '<div class="clear"></div>';
1675 function bb_translate_video($s) {
1678 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1680 foreach ($matches as $mtch) {
1681 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1682 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1683 elseif (stristr($mtch[1],'vimeo'))
1684 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1690 function html2bb_video($s) {
1692 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1693 '[youtube]$2[/youtube]', $s);
1695 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1696 '[youtube]$2[/youtube]', $s);
1698 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1699 '[vimeo]$2[/vimeo]', $s);
1705 * apply xmlify() to all values of array $val, recursively
1709 function array_xmlify($val){
1710 if (is_bool($val)) {
1711 return $val?"true":"false";
1712 } elseif (is_array($val)) {
1713 return array_map('array_xmlify', $val);
1715 return xmlify((string) $val);
1720 * transform link href and img src from relative to absolute
1722 * @param string $text
1723 * @param string $base base url
1726 function reltoabs($text, $base) {
1731 $base = rtrim($base,'/');
1733 $base2 = $base . "/";
1736 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1737 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1738 $text = preg_replace($pattern, $replace, $text);
1740 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1741 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1742 $text = preg_replace($pattern, $replace, $text);
1745 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1746 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1747 $text = preg_replace($pattern, $replace, $text);
1749 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1750 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1751 $text = preg_replace($pattern, $replace, $text);
1759 * get translated item type
1761 * @param array $itme
1764 function item_post_type($item) {
1765 if (intval($item['event-id'])) {
1767 } elseif (strlen($item['resource-id'])) {
1769 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1770 return t('activity');
1771 } elseif ($item['id'] != $item['parent']) {
1772 return t('comment');
1778 // post categories and "save to file" use the same item.file table for storage.
1779 // We will differentiate the different uses by wrapping categories in angle brackets
1780 // and save to file categories in square brackets.
1781 // To do this we need to escape these characters if they appear in our tag.
1783 function file_tag_encode($s) {
1784 return str_replace(['<','>','[',']'],['%3c','%3e','%5b','%5d'],$s);
1787 function file_tag_decode($s) {
1788 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
1791 function file_tag_file_query($table,$s,$type = 'file') {
1793 if ($type == 'file') {
1794 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1796 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1798 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1801 // ex. given music,video return <music><video> or [music][video]
1802 function file_tag_list_to_file($list,$type = 'file') {
1804 if (strlen($list)) {
1805 $list_array = explode(",",$list);
1806 if ($type == 'file') {
1814 foreach ($list_array as $item) {
1815 if (strlen($item)) {
1816 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1823 // ex. given <music><video>[friends], return music,video or friends
1824 function file_tag_file_to_list($file,$type = 'file') {
1827 if ($type == 'file') {
1828 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1830 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1833 foreach ($matches as $mtch) {
1834 if (strlen($list)) {
1837 $list .= file_tag_decode($mtch[1]);
1844 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1845 // $file_old - categories previously associated with an item
1846 // $file_new - new list of categories for an item
1848 if (!intval($uid)) {
1851 if ($file_old == $file_new) {
1855 $saved = PConfig::get($uid, 'system', 'filetags');
1856 if (strlen($saved)) {
1857 if ($type == 'file') {
1860 $termtype = TERM_FILE;
1864 $termtype = TERM_CATEGORY;
1867 $filetags_updated = $saved;
1869 // check for new tags to be added as filetags in pconfig
1871 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1873 foreach ($check_new_tags as $tag) {
1874 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1878 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1880 // check for deleted tags to be removed from filetags in pconfig
1882 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1884 foreach ($check_deleted_tags as $tag) {
1885 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1886 $deleted_tags[] = $tag;
1889 foreach ($deleted_tags as $key => $tag) {
1890 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1892 intval(TERM_OBJ_POST),
1896 if (DBM::is_result($r)) {
1897 unset($deleted_tags[$key]);
1899 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1903 if ($saved != $filetags_updated) {
1904 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1907 } elseif (strlen($file_new)) {
1908 PConfig::set($uid, 'system', 'filetags', $file_new);
1913 function file_tag_save_file($uid, $item, $file)
1915 if (! intval($uid)) {
1919 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1923 if (DBM::is_result($r)) {
1924 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1925 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1926 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1932 Term::createFromItem($item);
1934 $saved = PConfig::get($uid, 'system', 'filetags');
1935 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1936 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1938 info(t('Item filed'));
1943 function file_tag_unsave_file($uid, $item, $file, $cat = false)
1945 if (! intval($uid)) {
1950 $pattern = '<' . file_tag_encode($file) . '>' ;
1951 $termtype = TERM_CATEGORY;
1953 $pattern = '[' . file_tag_encode($file) . ']' ;
1954 $termtype = TERM_FILE;
1957 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1961 if (! DBM::is_result($r)) {
1965 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1966 dbesc(str_replace($pattern,'',$r[0]['file'])),
1971 Term::createFromItem($item);
1973 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1975 intval(TERM_OBJ_POST),
1979 if (!DBM::is_result($r)) {
1980 $saved = PConfig::get($uid, 'system', 'filetags');
1981 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1987 function normalise_openid($s) {
1988 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
1992 function undo_post_tagging($s) {
1994 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1996 foreach ($matches as $mtch) {
1997 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2003 function protect_sprintf($s) {
2004 return str_replace('%', '%%', $s);
2008 function is_a_date_arg($s) {
2012 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2013 $m = intval(substr($s,5));
2014 if ($m > 0 && $m <= 12)
2022 * remove intentation from a text
2024 function deindent($text, $chr = "[\t ]", $count = NULL) {
2025 $lines = explode("\n", $text);
2026 if (is_null($count)) {
2029 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2032 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2033 $count = strlen($m[0]);
2035 for ($k = 0; $k < count($lines); $k++) {
2036 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2039 return implode("\n", $lines);
2042 function formatBytes($bytes, $precision = 2) {
2043 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
2045 $bytes = max($bytes, 0);
2046 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2047 $pow = min($pow, count($units) - 1);
2049 $bytes /= pow(1024, $pow);
2051 return round($bytes, $precision) . ' ' . $units[$pow];
2055 * @brief translate and format the networkname of a contact
2057 * @param string $network
2058 * Networkname of the contact (e.g. dfrn, rss and so on)
2063 function format_network_name($network, $url = 0) {
2064 if ($network != "") {
2066 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
2068 $network_name = ContactSelector::networkToName($network);
2071 return $network_name;
2076 * @brief Syntax based code highlighting for popular languages.
2077 * @param string $s Code block
2078 * @param string $lang Programming language
2079 * @return string Formated html
2081 function text_highlight($s, $lang) {
2082 if ($lang === 'js') {
2083 $lang = 'javascript';
2086 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2088 // Autoload the library to make constants available
2089 class_exists('Text_Highlighter_Renderer_Html');
2092 'numbers' => HL_NUMBERS_LI,
2097 $s = trim(html_entity_decode($s, ENT_COMPAT));
2098 $s = str_replace(' ', "\t", $s);
2101 * The highlighter library insists on an opening php tag for php code blocks. If
2102 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2103 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2105 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2106 $s = '<?php' . "\n" . $s;
2110 $renderer = new Text_Highlighter_Renderer_Html($options);
2111 $factory = new Text_Highlighter();
2112 $hl = $factory->factory($lang);
2113 $hl->setRenderer($renderer);
2114 $o = $hl->highlight($s);
2115 $o = str_replace("\n", '', $o);
2118 $b = substr($o, 0, strpos($o, '<li>'));
2119 $e = substr($o, strpos($o, '</li>'));
2123 return '<code>' . $o . '</code>';