4 use Friendica\Core\System;
6 require_once "include/template_processor.php";
7 require_once "include/friendica_smarty.php";
8 require_once "include/Smilies.php";
9 require_once "include/map.php";
10 require_once "mod/proxy.php";
12 if (! function_exists('replace_macros')) {
14 * This is our template processor
16 * @param string|FriendicaSmarty $s the string requiring macro substitution,
17 * or an instance of FriendicaSmarty
18 * @param array $r key value pairs (search => replace)
19 * @return string substituted string
21 function replace_macros($s, $r) {
23 $stamp1 = microtime(true);
27 // pass $baseurl to all templates
28 $r['$baseurl'] = System::baseUrl();
30 $t = $a->template_engine();
32 $output = $t->replace_macros($s, $r);
33 } catch (Exception $e) {
34 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
38 $a->save_timestamp($stamp1, "rendering");
44 // random string, there are 86 characters max in text mode, 128 for hex
47 define('RANDOM_STRING_HEX', 0x00 );
48 define('RANDOM_STRING_TEXT', 0x01 );
50 if (! function_exists('random_string')) {
51 function random_string($size = 64, $type = RANDOM_STRING_HEX) {
52 // generate a bit of entropy and run it through the whirlpool
53 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(), (($type == RANDOM_STRING_TEXT) ? true : false));
54 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n", "", base64url_encode($s,true)) : $s);
55 return(substr($s,0,$size));
58 if (! function_exists('notags')) {
60 * This is our primary input filter.
62 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
63 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
64 * after cleansing, and angle chars with the high bit set could get through as markup.
66 * This is now disabled because it was interfering with some legitimate unicode sequences
67 * and hopefully there aren't a lot of those browsers left.
69 * Use this on any text input where angle chars are not valid or permitted
70 * They will be replaced with safer brackets. This may be filtered further
71 * if these are not allowed either.
73 * @param string $string Input string
74 * @return string Filtered string
76 function notags($string) {
77 return str_replace(array("<", ">"), array('[', ']'), $string);
79 // High-bit filter no longer used
80 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
85 if (! function_exists('escape_tags')) {
87 * use this on "body" or "content" input where angle chars shouldn't be removed,
88 * and allow them to be safely displayed.
89 * @param string $string
92 function escape_tags($string) {
93 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
97 // generate a string that's random, but usually pronounceable.
98 // used to generate initial passwords
100 if (! function_exists('autoname')) {
102 * generate a string that's random, but usually pronounceable.
103 * used to generate initial passwords
107 function autoname($len) {
113 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
114 if (mt_rand(0, 5) == 4) {
133 's','sc','sh','sm','sp','st',
141 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
142 'nd','ng','nk','nt','rn','rp','rt');
144 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
145 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
147 $start = mt_rand(0,2);
156 for ($x = 0; $x < $len; $x ++) {
157 $r = mt_rand(0,count($table) - 1);
160 if ($table == $vowels) {
161 $table = array_merge($cons,$midcons);
168 $word = substr($word,0,$len);
170 foreach ($noend as $noe) {
171 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
172 $word = substr($word, 0, -1);
176 if (substr($word, -1) == 'q') {
177 $word = substr($word, 0, -1);
183 // escape text ($str) for XML transport
184 // returns escaped text.
186 if (! function_exists('xmlify')) {
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);
240 if (! function_exists('unxmlify')) {
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);
260 if (! function_exists('hex2bin')) {
262 * convenience wrapper, reverse the operation "bin2hex"
266 function hex2bin($s) {
267 if (! (is_string($s) && strlen($s))) {
271 if (! ctype_xdigit($s)) {
275 return pack("H*",$s);
280 * @brief Paginator function. Pushes relevant links in a pager array structure.
282 * Links are generated depending on the current page and the total number of items.
283 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
284 * Current page link is given the "active" CSS class
286 * @param App $a App instance
287 * @param int $count [optional] item count (used with minimal pager)
288 * @return Array data for pagination template
290 function paginate_data(App $a, $count = null) {
291 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
293 $stripped = str_replace('q=', '', $stripped);
294 $stripped = trim($stripped, '/');
295 $pagenum = $a->pager['page'];
297 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
298 $stripped .= '&offset=' . urlencode($a->page_offset);
304 function _l(&$d, $name, $url, $text, $class = '') {
305 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
306 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
309 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
312 if (!is_null($count)) {
313 // minimal pager (newer / older)
314 $data['class'] = 'pager';
315 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
316 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
318 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
319 $data['class'] = 'pagination';
320 if ($a->pager['total'] > $a->pager['itemspage']) {
321 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
322 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
324 $numpages = $a->pager['total'] / $a->pager['itemspage'];
327 $numstop = $numpages;
329 // Limit the number of displayed page number buttons.
331 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
332 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
337 for ($i = $numstart; $i <= $numstop; $i++) {
338 if ($i == $a->pager['page']) {
339 _l($pages, $i, '#', $i, 'current active');
341 _l($pages, $i, $url . '&page='. $i, $i, 'n');
345 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
346 if ($i == $a->pager['page']) {
347 _l($pages, $i, '#', $i, 'current active');
349 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
353 $data['pages'] = $pages;
355 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
356 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
357 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
364 if (! function_exists('paginate')) {
366 * Automatic pagination.
368 * To use, get the count of total items.
369 * Then call $a->set_pager_total($number_items);
370 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
371 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
372 * (assuming there are enough items to paginate).
373 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
374 * will limit the results to the correct items for the current page.
375 * The actual page handling is then accomplished at the application layer.
377 * @param App $a App instance
378 * @return string html for pagination #FIXME remove html
380 function paginate(App $a) {
382 $data = paginate_data($a);
383 $tpl = get_markup_template("paginate.tpl");
384 return replace_macros($tpl, array("pager" => $data));
388 if (! function_exists('alt_pager')) {
391 * @param App $a App instance
393 * @return string html for pagination #FIXME remove html
395 function alt_pager(App $a, $i) {
397 $data = paginate_data($a, $i);
398 $tpl = get_markup_template("paginate.tpl");
399 return replace_macros($tpl, array('pager' => $data));
403 if (! function_exists('scroll_loader')) {
405 * Loader for infinite scrolling
406 * @return string html for loader
408 function scroll_loader() {
409 $tpl = get_markup_template("scroll_loader.tpl");
410 return replace_macros($tpl, array(
411 'wait' => t('Loading more entries...'),
412 'end' => t('The end')
416 if (! function_exists('expand_acl')) {
418 * Turn user/group ACLs stored as angle bracketed text into arrays
423 function expand_acl($s) {
424 // turn string array of angle-bracketed elements into numeric array
425 // e.g. "<1><2><3>" => array(1,2,3);
429 $t = str_replace('<', '', $s);
430 $a = explode('>', $t);
431 foreach ($a as $aa) {
433 $ret[] = intval($aa);
440 if (! function_exists('sanitise_acl')) {
442 * Wrap ACL elements in angle brackets for storage
443 * @param string $item
445 function sanitise_acl(&$item) {
447 $item = '<' . intval(notags(trim($item))) . '>';
454 if (! function_exists('perms2str')) {
456 * Convert an ACL array to a storable string
458 * Normally ACL permissions will be an array.
459 * We'll also allow a comma-separated string.
461 * @param string|array $p
464 function perms2str($p) {
469 $tmp = explode(',',$p);
472 if (is_array($tmp)) {
473 array_walk($tmp, 'sanitise_acl');
474 $ret = implode('', $tmp);
480 if (! function_exists('item_new_uri')) {
482 * generate a guaranteed unique (for this domain) item ID for ATOM
483 * safe from birthday paradox
485 * @param string $hostname
489 function item_new_uri($hostname, $uid, $guid = "") {
493 $hash = get_guid(32);
499 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
501 $dups = dba::exists('item', array('uri' => $uri));
502 } while ($dups == true);
507 // Generate a guaranteed unique photo ID.
508 // safe from birthday paradox
510 if (! function_exists('photo_new_resource')) {
512 * Generate a guaranteed unique photo ID.
513 * safe from birthday paradox
517 function photo_new_resource() {
521 $resource = hash('md5',uniqid(mt_rand(),true));
522 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
526 if (dbm::is_result($r)) {
529 } while ($found == true);
535 if (! function_exists('load_view_file')) {
538 * wrapper to load a view template, checking for alternate
539 * languages before falling back to the default
541 * @global string $lang
543 * @param string $s view name
546 function load_view_file($s) {
548 if (! isset($lang)) {
553 if (file_exists("$d/$lang/$b")) {
554 $stamp1 = microtime(true);
555 $content = file_get_contents("$d/$lang/$b");
556 $a->save_timestamp($stamp1, "file");
560 $theme = current_theme();
562 if (file_exists("$d/theme/$theme/$b")) {
563 $stamp1 = microtime(true);
564 $content = file_get_contents("$d/theme/$theme/$b");
565 $a->save_timestamp($stamp1, "file");
569 $stamp1 = microtime(true);
570 $content = file_get_contents($s);
571 $a->save_timestamp($stamp1, "file");
575 if (! function_exists('get_intltext_template')) {
577 * load a view template, checking for alternate
578 * languages before falling back to the default
580 * @global string $lang
581 * @param string $s view path
584 function get_intltext_template($s) {
589 if ($a->theme['template_engine'] === 'smarty3') {
590 $engine = "/smarty3";
593 if (! isset($lang)) {
597 if (file_exists("view/lang/$lang$engine/$s")) {
598 $stamp1 = microtime(true);
599 $content = file_get_contents("view/lang/$lang$engine/$s");
600 $a->save_timestamp($stamp1, "file");
602 } elseif (file_exists("view/lang/en$engine/$s")) {
603 $stamp1 = microtime(true);
604 $content = file_get_contents("view/lang/en$engine/$s");
605 $a->save_timestamp($stamp1, "file");
608 $stamp1 = microtime(true);
609 $content = file_get_contents("view$engine/$s");
610 $a->save_timestamp($stamp1, "file");
615 if (! function_exists('get_markup_template')) {
620 * @param string $root
623 function get_markup_template($s, $root = '') {
624 $stamp1 = microtime(true);
627 $t = $a->template_engine();
629 $template = $t->get_template_file($s, $root);
630 } catch (Exception $e) {
631 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
635 $a->save_timestamp($stamp1, "file");
640 if (! function_exists("get_template_file")) {
644 * @param string $filename
645 * @param string $root
648 function get_template_file($a, $filename, $root = '') {
649 $theme = current_theme();
651 // Make sure $root ends with a slash /
652 if ($root !== '' && substr($root, -1, 1) !== '/') {
656 if (file_exists("{$root}view/theme/$theme/$filename")) {
657 $template_file = "{$root}view/theme/$theme/$filename";
658 } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
659 $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
660 } elseif (file_exists("{$root}/$filename")) {
661 $template_file = "{$root}/$filename";
663 $template_file = "{$root}view/$filename";
666 return $template_file;
670 if (! function_exists('attribute_contains')) {
672 * for html,xml parsing - let's say you've got
673 * an attribute foobar="class1 class2 class3"
674 * and you want to find out if it contains 'class3'.
675 * you can't use a normal sub string search because you
676 * might match 'notclass3' and a regex to do the job is
677 * possible but a bit complicated.
678 * pass the attribute string as $attr and the attribute you
679 * are looking for as $s - returns true if found, otherwise false
681 * @param string $attr attribute value
682 * @param string $s string to search
683 * @return boolean True if found, False otherwise
685 function attribute_contains($attr, $s) {
686 $a = explode(' ', $attr);
687 return (count($a) && in_array($s,$a));
690 if (! function_exists('logger')) {
691 /* setup int->string log level map */
692 $LOGGER_LEVELS = array();
695 * @brief Logs the given message at the given log level
698 * LOGGER_NORMAL (default)
706 * @global array $LOGGER_LEVELS
710 function logger($msg, $level = 0) {
713 global $LOGGER_LEVELS;
715 // turn off logger in install mode
717 $a->module == 'install'
718 || ! ($db && $db->connected)
723 $debugging = get_config('system','debugging');
724 $logfile = get_config('system','logfile');
725 $loglevel = intval(get_config('system','loglevel'));
730 || $level > $loglevel
735 if (count($LOGGER_LEVELS) == 0) {
736 foreach (get_defined_constants() as $k => $v) {
737 if (substr($k, 0, 7) == "LOGGER_") {
738 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
743 $process_id = session_id();
745 if ($process_id == '') {
746 $process_id = get_app()->process_id;
749 $callers = debug_backtrace();
750 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
751 datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
753 $LOGGER_LEVELS[$level],
754 basename($callers[0]['file']),
756 $callers[1]['function'],
760 $stamp1 = microtime(true);
761 @file_put_contents($logfile, $logline, FILE_APPEND);
762 $a->save_timestamp($stamp1, "file");
766 * @brief An alternative logger for development.
767 * Works largely as logger() but allows developers
768 * to isolate particular elements they are targetting
769 * personally without background noise
772 * LOGGER_NORMAL (default)
780 * @global array $LOGGER_LEVELS
785 function dlogger($msg, $level = 0) {
789 // turn off logger in install mode
791 $a->module == 'install'
792 || ! ($db && $db->connected)
797 $logfile = get_config('system','dlogfile');
803 if (count($LOGGER_LEVELS) == 0) {
804 foreach (get_defined_constants() as $k => $v) {
805 if (substr($k, 0, 7) == "LOGGER_") {
806 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
811 $process_id = session_id();
813 if ($process_id == '') {
814 $process_id = get_app()->process_id;
817 $callers = debug_backtrace();
818 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
821 basename($callers[0]['file']),
823 $callers[1]['function'],
827 $stamp1 = microtime(true);
828 @file_put_contents($logfile, $logline, FILE_APPEND);
829 $a->save_timestamp($stamp1, "file");
832 if (! function_exists('activity_match')) {
834 * Compare activity uri. Knows about activity namespace.
836 * @param string $haystack
837 * @param string $needle
840 function activity_match($haystack,$needle) {
841 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
846 * @brief Pull out all #hashtags and @person tags from $string.
848 * We also get @person@domain.com - which would make
849 * the regex quite complicated as tags can also
850 * end a sentence. So we'll run through our results
851 * and strip the period from any tags which end with one.
852 * Returns array of tags found, or empty array.
854 * @param string $string Post content
855 * @return array List of tag and person names
857 function get_tags($string) {
860 // Convert hashtag links to hashtags
861 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
863 // ignore anything in a code block
864 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
866 // Force line feeds at bbtags
867 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
869 // ignore anything in a bbtag
870 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
872 // Match full names against @tags including the space between first and last
873 // We will look these up afterward to see if they are full names or not recognisable.
875 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
876 foreach ($matches[1] as $match) {
877 if (strstr($match, ']')) {
878 // we might be inside a bbcode color tag - leave it alone
881 if (substr($match, -1, 1) === '.') {
882 $ret[] = substr($match, 0, -1);
889 // Otherwise pull out single word tags. These can be @nickname, @first_last
892 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
893 foreach ($matches[1] as $match) {
894 if (strstr($match, ']')) {
895 // we might be inside a bbcode color tag - leave it alone
898 if (substr($match, -1, 1) === '.') {
899 $match = substr($match,0,-1);
901 // ignore strictly numeric tags like #1
902 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
905 // try not to catch url fragments
906 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
918 if (! function_exists('qp')) {
920 * quick and dirty quoted_printable encoding
926 return str_replace("%", "=", rawurlencode($s));
929 if (! function_exists('contact_block')) {
931 * Get html for contact block.
933 * @template contact_block.tpl
934 * @hook contact_block_end (contacts=>array, output=>string)
937 function contact_block() {
941 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
942 if ($shown === false) {
949 if ((! is_array($a->profile)) || ($a->profile['hide-friends'])) {
952 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
953 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
954 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
955 AND `network` IN ('%s', '%s', '%s')",
956 intval($a->profile['uid']),
958 dbesc(NETWORK_OSTATUS),
959 dbesc(NETWORK_DIASPORA)
961 if (dbm::is_result($r)) {
962 $total = intval($r[0]['total']);
965 $contacts = t('No contacts');
968 // Splitting the query in two parts makes it much faster
969 $r = q("SELECT `id` FROM `contact`
970 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
971 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
972 AND `network` IN ('%s', '%s', '%s')
973 ORDER BY RAND() LIMIT %d",
974 intval($a->profile['uid']),
976 dbesc(NETWORK_OSTATUS),
977 dbesc(NETWORK_DIASPORA),
980 if (dbm::is_result($r)) {
982 foreach ($r AS $contact) {
983 $contacts[] = $contact["id"];
985 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
986 dbesc(implode(",", $contacts)));
988 if (dbm::is_result($r)) {
989 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
991 foreach ($r as $rr) {
992 $micropro[] = micropro($rr,true,'mpfriend');
998 $tpl = get_markup_template('contact_block.tpl');
999 $o = replace_macros($tpl, array(
1000 '$contacts' => $contacts,
1001 '$nickname' => $a->profile['nickname'],
1002 '$viewcontacts' => t('View Contacts'),
1003 '$micropro' => $micropro,
1006 $arr = array('contacts' => $r, 'output' => $o);
1008 call_hooks('contact_block_end', $arr);
1014 * @brief Format contacts as picture links or as texxt links
1016 * @param array $contact Array with contacts which contains an array with
1017 * int 'id' => The ID of the contact
1018 * int 'uid' => The user ID of the user who owns this data
1019 * string 'name' => The name of the contact
1020 * string 'url' => The url to the profile page of the contact
1021 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
1022 * string 'network' => The network to which the contact belongs to
1023 * string 'thumb' => The contact picture
1024 * string 'click' => js code which is performed when clicking on the contact
1025 * @param boolean $redirect If true try to use the redir url if it's possible
1026 * @param string $class CSS class for the
1027 * @param boolean $textmode If true display the contacts as text links
1028 * if false display the contacts as picture links
1030 * @return string Formatted html
1032 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
1034 // Use the contact URL if no address is available
1035 if ($contact["addr"] == "") {
1036 $contact["addr"] = $contact["url"];
1039 $url = $contact['url'];
1045 $redirect_url = 'redir/' . $contact['id'];
1046 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1048 $url = $redirect_url;
1049 $sparkle = ' sparkle';
1055 // If there is some js available we don't need the url
1056 if (x($contact, 'click')) {
1060 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1061 '$click' => (($contact['click']) ? $contact['click'] : ''),
1064 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1065 '$name' => $contact['name'],
1066 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1067 '$parkle' => $sparkle,
1075 if (! function_exists('search')) {
1079 * @param string $s search query
1080 * @param string $id html id
1081 * @param string $url search url
1082 * @param boolean $savedsearch show save search button
1084 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true) {
1088 '$s' => htmlspecialchars($s),
1090 '$action_url' => $url,
1091 '$search_label' => t('Search'),
1092 '$save_label' => t('Save'),
1093 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1094 '$search_hint' => t('@name, !forum, #tags, content'),
1098 $values['$searchoption'] = array(
1103 if (get_config('system','poco_local_search')) {
1104 $values['$searchoption'][] = t("Forums");
1108 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1111 if (! function_exists('valid_email')) {
1113 * Check if $x is a valid email string
1118 function valid_email($x){
1120 /// @TODO Removed because Fabio told me so.
1121 //if (get_config('system','disable_email_validation'))
1123 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $x);
1127 if (! function_exists('linkify')) {
1129 * Replace naked text hyperlink with HTML formatted hyperlink
1133 function linkify($s) {
1134 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1135 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1143 * @return array index is present tense verb
1144 value is array containing past tense verb, translation of present, translation of past
1145 * @hook poke_verbs pokes array
1147 function get_poke_verbs() {
1149 // index is present tense verb
1150 // value is array containing past tense verb, translation of present, translation of past
1153 'poke' => array( 'poked', t('poke'), t('poked')),
1154 'ping' => array( 'pinged', t('ping'), t('pinged')),
1155 'prod' => array( 'prodded', t('prod'), t('prodded')),
1156 'slap' => array( 'slapped', t('slap'), t('slapped')),
1157 'finger' => array( 'fingered', t('finger'), t('fingered')),
1158 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1160 call_hooks('poke_verbs', $arr);
1166 * @return array index is mood, value is translated mood
1167 * @hook mood_verbs moods array
1169 function get_mood_verbs() {
1172 'happy' => t('happy'),
1174 'mellow' => t('mellow'),
1175 'tired' => t('tired'),
1176 'perky' => t('perky'),
1177 'angry' => t('angry'),
1178 'stupefied' => t('stupified'),
1179 'puzzled' => t('puzzled'),
1180 'interested' => t('interested'),
1181 'bitter' => t('bitter'),
1182 'cheerful' => t('cheerful'),
1183 'alive' => t('alive'),
1184 'annoyed' => t('annoyed'),
1185 'anxious' => t('anxious'),
1186 'cranky' => t('cranky'),
1187 'disturbed' => t('disturbed'),
1188 'frustrated' => t('frustrated'),
1189 'motivated' => t('motivated'),
1190 'relaxed' => t('relaxed'),
1191 'surprised' => t('surprised'),
1194 call_hooks('mood_verbs', $arr);
1198 if (! function_exists('day_translate')) {
1200 * Translate days and months names
1205 function day_translate($s) {
1206 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1207 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1210 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1211 array( t('January'), t('February'), t('March'), t('April'), t('May'), t('June'), t('July'), t('August'), t('September'), t('October'), t('November'), t('December')),
1218 if (! function_exists('normalise_link')) {
1222 * @param string $url
1225 function normalise_link($url) {
1226 $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
1227 return rtrim($ret,'/');
1232 if (! function_exists('link_compare')) {
1234 * Compare two URLs to see if they are the same, but ignore
1235 * slight but hopefully insignificant differences such as if one
1236 * is https and the other isn't, or if one is www.something and
1237 * the other isn't - and also ignore case differences.
1239 * @param string $a first url
1240 * @param string $b second url
1241 * @return boolean True if the URLs match, otherwise False
1244 function link_compare($a, $b) {
1245 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1249 * @brief Find any non-embedded images in private items and add redir links to them
1252 * @param array &$item The field array of an item row
1254 function redir_private_images($a, &$item)
1257 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1259 foreach ($matches as $mtch) {
1260 if (strpos($mtch[1], '/redir') !== false) {
1264 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1265 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1266 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1272 function put_item_in_cache(&$item, $update = false) {
1274 if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
1275 ($item["rendered-html"] == "") || get_config("system", "ignore_cache")) {
1277 // The function "redir_private_images" changes the body.
1278 // I'm not sure if we should store it permanently, so we save the old value.
1279 $body = $item["body"];
1282 redir_private_images($a, $item);
1284 $item["rendered-html"] = prepare_text($item["body"]);
1285 $item["rendered-hash"] = hash("md5", $item["body"]);
1286 $item["body"] = $body;
1288 if ($update && ($item["id"] > 0)) {
1289 dba::update('item', array('rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]),
1290 array('id' => $item["id"]), false);
1295 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1296 // If attach is true, also add icons for item attachments
1298 if (! function_exists('prepare_body')) {
1300 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1301 * If attach is true, also add icons for item attachments
1303 * @param array $item
1304 * @param boolean $attach
1305 * @return string item body html
1306 * @hook prepare_body_init item array before any work
1307 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1308 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1310 function prepare_body(&$item, $attach = false, $preview = false) {
1313 call_hooks('prepare_body_init', $item);
1315 $searchpath = System::baseUrl() . "/search?tag=";
1318 $hashtags = array();
1319 $mentions = array();
1321 if (!get_config('system','suppress_tags')) {
1322 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1323 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1325 while ($tag = dba::fetch($taglist)) {
1326 if ($tag["url"] == "") {
1327 $tag["url"] = $searchpath.strtolower($tag["term"]);
1330 $orig_tag = $tag["url"];
1332 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1334 if ($tag["type"] == TERM_HASHTAG) {
1335 if ($orig_tag != $tag["url"]) {
1336 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1338 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1340 } elseif ($tag["type"] == TERM_MENTION) {
1341 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1344 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1346 dba::close($taglist);
1349 $item['tags'] = $tags;
1350 $item['hashtags'] = $hashtags;
1351 $item['mentions'] = $mentions;
1353 // Update the cached values if there is no "zrl=..." on the links
1354 $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
1356 // Or update it if the current viewer is the intented viewer
1357 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1361 put_item_in_cache($item, $update);
1362 $s = $item["rendered-html"];
1364 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1365 call_hooks('prepare_body', $prep_arr);
1366 $s = $prep_arr['html'];
1369 // Replace the blockquotes with quotes that are used in mails
1370 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1371 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1377 $arr = explode('[/attach],', $item['attach']);
1379 foreach ($arr as $r) {
1382 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1384 foreach ($matches as $mtch) {
1387 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1388 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1390 $the_url = $mtch[1];
1393 if (strpos($mime, 'video') !== false) {
1396 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1397 '$baseurl' => System::baseUrl(),
1399 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1400 '$baseurl' => System::baseUrl(),
1404 $id = end(explode('/', $the_url));
1405 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1408 'title' => t('View Video'),
1415 $filetype = strtolower(substr($mime, 0, strpos($mime,'/')));
1417 $filesubtype = strtolower(substr($mime, strpos($mime,'/') + 1));
1418 $filesubtype = str_replace('.', '-', $filesubtype);
1421 $filesubtype = 'unkn';
1424 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1425 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1427 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1428 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1434 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1438 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1439 $x = generate_map(trim($item['coord']));
1441 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1447 $spoilersearch = '<blockquote class="spoiler">';
1449 // Remove line breaks before the spoiler
1450 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1451 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1453 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1454 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1457 while ((strpos($s, $spoilersearch) !== false)) {
1458 $pos = strpos($s, $spoilersearch);
1459 $rnd = random_string(8);
1460 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1461 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1462 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1465 // Look for quote with author
1466 $authorsearch = '<blockquote class="author">';
1468 while ((strpos($s, $authorsearch) !== false)) {
1469 $pos = strpos($s, $authorsearch);
1470 $rnd = random_string(8);
1471 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1472 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1473 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1476 // replace friendica image url size with theme preference
1477 if (x($a->theme_info, 'item_image_size')){
1478 $ps = $a->theme_info['item_image_size'];
1479 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1482 $prep_arr = array('item' => $item, 'html' => $s);
1483 call_hooks('prepare_body_final', $prep_arr);
1485 return $prep_arr['html'];
1489 if (! function_exists('prepare_text')) {
1491 * Given a text string, convert from bbcode to html and add smilie icons.
1493 * @param string $text
1496 function prepare_text($text) {
1498 require_once 'include/bbcode.php';
1500 if (stristr($text, '[nosmile]')) {
1503 $s = Smilies::replace(bbcode($text));
1512 * return array with details for categories and folders for an item
1514 * @param array $item
1518 * [ // categories array
1520 * 'name': 'category name',
1521 * 'removeurl': 'url to remove this category',
1522 * 'first': 'is the first in this array? true/false',
1523 * 'last': 'is the last in this array? true/false',
1529 * 'name': 'folder name',
1530 * 'removeurl': 'url to remove this folder',
1531 * 'first': 'is the first in this array? true/false',
1532 * 'last': 'is the last in this array? true/false',
1538 function get_cats_and_terms($item) {
1541 $categories = array();
1546 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1548 foreach ($matches as $mtch) {
1549 $categories[] = array(
1550 'name' => xmlify(file_tag_decode($mtch[1])),
1552 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1560 if (count($categories)) {
1561 $categories[count($categories) - 1]['last'] = true;
1564 if (local_user() == $item['uid']) {
1567 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1569 foreach ($matches as $mtch) {
1571 'name' => xmlify(file_tag_decode($mtch[1])),
1573 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1582 if (count($folders)) {
1583 $folders[count($folders) - 1]['last'] = true;
1586 return array($categories, $folders);
1589 if (! function_exists('get_plink')) {
1591 * get private link for item
1592 * @param array $item
1593 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1595 function get_plink($item) {
1598 if ($a->user['nickname'] != "") {
1600 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1601 'href' => "display/" . $item['guid'],
1602 'orig' => "display/" . $item['guid'],
1603 'title' => t('View on separate page'),
1604 'orig_title' => t('view on separate page'),
1607 if (x($item, 'plink')) {
1608 $ret["href"] = $a->remove_baseurl($item['plink']);
1609 $ret["title"] = t('link to source');
1612 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1614 'href' => $item['plink'],
1615 'orig' => $item['plink'],
1616 'title' => t('link to source'),
1625 if (! function_exists('unamp')) {
1627 * replace html amp entity with amp char
1631 function unamp($s) {
1632 return str_replace('&', '&', $s);
1636 if (! function_exists('return_bytes')) {
1638 * return number of bytes in size (K, M, G)
1639 * @param string $size_str
1642 function return_bytes ($size_str) {
1643 switch (substr ($size_str, -1)) {
1644 case 'M': case 'm': return (int)$size_str * 1048576;
1645 case 'K': case 'k': return (int)$size_str * 1024;
1646 case 'G': case 'g': return (int)$size_str * 1073741824;
1647 default: return $size_str;
1654 function generate_user_guid() {
1657 $guid = get_guid(32);
1658 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1661 if (! dbm::is_result($x)) {
1664 } while ($found == true);
1672 * @param boolean $strip_padding
1675 function base64url_encode($s, $strip_padding = false) {
1677 $s = strtr(base64_encode($s), '+/', '-_');
1679 if ($strip_padding) {
1680 $s = str_replace('=','',$s);
1690 function base64url_decode($s) {
1693 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1698 * // Placeholder for new rev of salmon which strips base64 padding.
1699 * // PHP base64_decode handles the un-padded input without requiring this step
1700 * // Uncomment if you find you need it.
1703 * if (! strpos($s,'=')) {
1713 return base64_decode(strtr($s,'-_','+/'));
1717 if (!function_exists('str_getcsv')) {
1721 * @param string $input
1722 * @param string $delimiter
1723 * @param string $enclosure
1724 * @param string $escape
1725 * @param string $eol
1726 * @return boolean|array False on error, otherwise array[row][column]
1728 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1729 if (is_string($input) && !empty($input)) {
1731 $tmp = preg_split("/".$eol."/",$input);
1732 if (is_array($tmp) && !empty($tmp)) {
1733 while (list($line_num, $line) = each($tmp)) {
1734 if (preg_match("/".$escape.$enclosure."/",$line)) {
1735 while ($strlen = strlen($line)) {
1736 $pos_delimiter = strpos($line,$delimiter);
1737 $pos_enclosure_start = strpos($line,$enclosure);
1739 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1740 && ($pos_enclosure_start < $pos_delimiter)
1742 $enclosed_str = substr($line,1);
1743 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1744 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1745 $output[$line_num][] = $enclosed_str;
1746 $offset = $pos_enclosure_end+3;
1748 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1749 $output[$line_num][] = substr($line,0);
1750 $offset = strlen($line);
1752 $output[$line_num][] = substr($line,0,$pos_delimiter);
1754 !empty($pos_enclosure_start)
1755 && ($pos_enclosure_start < $pos_delimiter)
1757 ?$pos_enclosure_start
1761 $line = substr($line,$offset);
1764 $line = preg_split("/".$delimiter."/",$line);
1767 * Validating against pesky extra line breaks creating false rows.
1769 if (is_array($line) && !empty($line[0])) {
1770 $output[$line_num] = $line;
1785 * return div element with class 'clear'
1789 function cleardiv() {
1790 return '<div class="clear"></div>';
1794 function bb_translate_video($s) {
1797 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1799 foreach ($matches as $mtch) {
1800 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1801 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1802 elseif (stristr($mtch[1],'vimeo'))
1803 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1809 function html2bb_video($s) {
1811 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1812 '[youtube]$2[/youtube]', $s);
1814 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1815 '[youtube]$2[/youtube]', $s);
1817 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1818 '[vimeo]$2[/vimeo]', $s);
1824 * apply xmlify() to all values of array $val, recursively
1828 function array_xmlify($val){
1829 if (is_bool($val)) {
1830 return $val?"true":"false";
1831 } elseif (is_array($val)) {
1832 return array_map('array_xmlify', $val);
1834 return xmlify((string) $val);
1839 * transorm link href and img src from relative to absolute
1841 * @param string $text
1842 * @param string $base base url
1845 function reltoabs($text, $base) {
1850 $base = rtrim($base,'/');
1852 $base2 = $base . "/";
1855 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1856 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1857 $text = preg_replace($pattern, $replace, $text);
1859 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1860 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1861 $text = preg_replace($pattern, $replace, $text);
1864 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1865 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1866 $text = preg_replace($pattern, $replace, $text);
1868 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1869 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1870 $text = preg_replace($pattern, $replace, $text);
1878 * get translated item type
1880 * @param array $itme
1883 function item_post_type($item) {
1884 if (intval($item['event-id'])) {
1886 } elseif (strlen($item['resource-id'])) {
1888 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1889 return t('activity');
1890 } elseif ($item['id'] != $item['parent']) {
1891 return t('comment');
1897 // post categories and "save to file" use the same item.file table for storage.
1898 // We will differentiate the different uses by wrapping categories in angle brackets
1899 // and save to file categories in square brackets.
1900 // To do this we need to escape these characters if they appear in our tag.
1902 function file_tag_encode($s) {
1903 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1906 function file_tag_decode($s) {
1907 return str_replace(array('%3c', '%3e', '%5b', '%5d'), array('<', '>', '[', ']'), $s);
1910 function file_tag_file_query($table,$s,$type = 'file') {
1912 if ($type == 'file') {
1913 $str = preg_quote( '[' . str_replace('%', '%%', file_tag_encode($s)) . ']' );
1915 $str = preg_quote( '<' . str_replace('%', '%%', file_tag_encode($s)) . '>' );
1917 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1920 // ex. given music,video return <music><video> or [music][video]
1921 function file_tag_list_to_file($list,$type = 'file') {
1923 if (strlen($list)) {
1924 $list_array = explode(",",$list);
1925 if ($type == 'file') {
1933 foreach ($list_array as $item) {
1934 if (strlen($item)) {
1935 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1942 // ex. given <music><video>[friends], return music,video or friends
1943 function file_tag_file_to_list($file,$type = 'file') {
1946 if ($type == 'file') {
1947 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1949 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1952 foreach ($matches as $mtch) {
1953 if (strlen($list)) {
1956 $list .= file_tag_decode($mtch[1]);
1963 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1964 // $file_old - categories previously associated with an item
1965 // $file_new - new list of categories for an item
1970 if ($file_old == $file_new)
1973 $saved = get_pconfig($uid,'system','filetags');
1974 if (strlen($saved)) {
1975 if ($type == 'file') {
1978 $termtype = TERM_FILE;
1983 $termtype = TERM_CATEGORY;
1986 $filetags_updated = $saved;
1988 // check for new tags to be added as filetags in pconfig
1989 $new_tags = array();
1990 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1992 foreach ($check_new_tags as $tag) {
1993 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1997 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1999 // check for deleted tags to be removed from filetags in pconfig
2000 $deleted_tags = array();
2001 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2003 foreach ($check_deleted_tags as $tag) {
2004 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2005 $deleted_tags[] = $tag;
2008 foreach ($deleted_tags as $key => $tag) {
2009 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2011 intval(TERM_OBJ_POST),
2015 if (dbm::is_result($r)) {
2016 unset($deleted_tags[$key]);
2019 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2023 if ($saved != $filetags_updated) {
2024 set_pconfig($uid, 'system', 'filetags', $filetags_updated);
2029 if (strlen($file_new)) {
2030 set_pconfig($uid, 'system', 'filetags', $file_new);
2035 function file_tag_save_file($uid, $item, $file) {
2036 require_once "include/files.php";
2041 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2045 if (dbm::is_result($r)) {
2046 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
2047 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2048 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2054 create_files_from_item($item);
2056 $saved = get_pconfig($uid,'system','filetags');
2057 if ((! strlen($saved)) || (! stristr($saved, '[' . file_tag_encode($file) . ']'))) {
2058 set_pconfig($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
2060 info( t('Item filed') );
2065 function file_tag_unsave_file($uid, $item, $file, $cat = false) {
2066 require_once "include/files.php";
2073 $pattern = '<' . file_tag_encode($file) . '>' ;
2074 $termtype = TERM_CATEGORY;
2076 $pattern = '[' . file_tag_encode($file) . ']' ;
2077 $termtype = TERM_FILE;
2081 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2085 if (! dbm::is_result($r)) {
2089 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2090 dbesc(str_replace($pattern,'',$r[0]['file'])),
2095 create_files_from_item($item);
2097 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2099 intval(TERM_OBJ_POST),
2103 if (! dbm::is_result($r)) {
2104 $saved = get_pconfig($uid,'system','filetags');
2105 set_pconfig($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
2111 function normalise_openid($s) {
2112 return trim(str_replace(array('http://', 'https://'), array('', ''), $s), '/');
2116 function undo_post_tagging($s) {
2118 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
2120 foreach ($matches as $mtch) {
2121 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2127 function protect_sprintf($s) {
2128 return str_replace('%', '%%', $s);
2132 function is_a_date_arg($s) {
2136 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2137 $m = intval(substr($s,5));
2138 if ($m > 0 && $m <= 12)
2146 * remove intentation from a text
2148 function deindent($text, $chr = "[\t ]", $count = NULL) {
2149 $lines = explode("\n", $text);
2150 if (is_null($count)) {
2153 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2156 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2157 $count = strlen($m[0]);
2159 for ($k = 0; $k < count($lines); $k++) {
2160 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2163 return implode("\n", $lines);
2166 function formatBytes($bytes, $precision = 2) {
2167 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2169 $bytes = max($bytes, 0);
2170 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2171 $pow = min($pow, count($units) - 1);
2173 $bytes /= pow(1024, $pow);
2175 return round($bytes, $precision) . ' ' . $units[$pow];
2179 * @brief translate and format the networkname of a contact
2181 * @param string $network
2182 * Networkname of the contact (e.g. dfrn, rss and so on)
2187 function format_network_name($network, $url = 0) {
2188 if ($network != "") {
2189 require_once 'include/contact_selectors.php';
2191 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2193 $network_name = network_to_name($network);
2196 return $network_name;
2202 * @brief Syntax based code highlighting for popular languages.
2203 * @param string $s Code block
2204 * @param string $lang Programming language
2205 * @return string Formated html
2207 function text_highlight($s, $lang) {
2208 if ($lang === 'js') {
2209 $lang = 'javascript';
2212 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2214 // Autoload the library to make constants available
2215 class_exists('Text_Highlighter_Renderer_Html');
2218 'numbers' => HL_NUMBERS_LI,
2223 $s = trim(html_entity_decode($s, ENT_COMPAT));
2224 $s = str_replace(' ', "\t", $s);
2227 * The highlighter library insists on an opening php tag for php code blocks. If
2228 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2229 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2231 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2232 $s = '<?php' . "\n" . $s;
2236 $renderer = new Text_Highlighter_Renderer_Html($options);
2237 $hl = Text_Highlighter::factory($lang);
2238 $hl->setRenderer($renderer);
2239 $o = $hl->highlight($s);
2240 $o = str_replace("\n", '', $o);
2243 $b = substr($o, 0, strpos($o, '<li>'));
2244 $e = substr($o, strpos($o, '</li>'));
2248 return '<code>' . $o . '</code>';