5 require_once "include/template_processor.php";
6 require_once "include/friendica_smarty.php";
7 require_once "include/Smilies.php";
8 require_once "include/map.php";
9 require_once "mod/proxy.php";
11 if (! function_exists('replace_macros')) {
13 * This is our template processor
15 * @param string|FriendicaSmarty $s the string requiring macro substitution,
16 * or an instance of FriendicaSmarty
17 * @param array $r key value pairs (search => replace)
18 * @return string substituted string
20 function replace_macros($s, $r) {
22 $stamp1 = microtime(true);
26 // pass $baseurl to all templates
27 $r['$baseurl'] = App::get_baseurl();
29 $t = $a->template_engine();
31 $output = $t->replace_macros($s, $r);
32 } catch (Exception $e) {
33 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
37 $a->save_timestamp($stamp1, "rendering");
43 // random string, there are 86 characters max in text mode, 128 for hex
46 define('RANDOM_STRING_HEX', 0x00 );
47 define('RANDOM_STRING_TEXT', 0x01 );
49 if (! function_exists('random_string')) {
50 function random_string($size = 64, $type = RANDOM_STRING_HEX) {
51 // generate a bit of entropy and run it through the whirlpool
52 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(), (($type == RANDOM_STRING_TEXT) ? true : false));
53 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n", "", base64url_encode($s,true)) : $s);
54 return(substr($s,0,$size));
57 if (! function_exists('notags')) {
59 * This is our primary input filter.
61 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
62 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
63 * after cleansing, and angle chars with the high bit set could get through as markup.
65 * This is now disabled because it was interfering with some legitimate unicode sequences
66 * and hopefully there aren't a lot of those browsers left.
68 * Use this on any text input where angle chars are not valid or permitted
69 * They will be replaced with safer brackets. This may be filtered further
70 * if these are not allowed either.
72 * @param string $string Input string
73 * @return string Filtered string
75 function notags($string) {
76 return str_replace(array("<", ">"), array('[', ']'), $string);
78 // High-bit filter no longer used
79 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
84 if (! function_exists('escape_tags')) {
86 * use this on "body" or "content" input where angle chars shouldn't be removed,
87 * and allow them to be safely displayed.
88 * @param string $string
91 function escape_tags($string) {
92 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
96 // generate a string that's random, but usually pronounceable.
97 // used to generate initial passwords
99 if (! function_exists('autoname')) {
101 * generate a string that's random, but usually pronounceable.
102 * used to generate initial passwords
106 function autoname($len) {
112 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
113 if (mt_rand(0, 5) == 4) {
132 's','sc','sh','sm','sp','st',
140 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
141 'nd','ng','nk','nt','rn','rp','rt');
143 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
144 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
146 $start = mt_rand(0,2);
155 for ($x = 0; $x < $len; $x ++) {
156 $r = mt_rand(0,count($table) - 1);
159 if ($table == $vowels) {
160 $table = array_merge($cons,$midcons);
167 $word = substr($word,0,$len);
169 foreach ($noend as $noe) {
170 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
171 $word = substr($word, 0, -1);
175 if (substr($word, -1) == 'q') {
176 $word = substr($word, 0, -1);
182 // escape text ($str) for XML transport
183 // returns escaped text.
185 if (! function_exists('xmlify')) {
187 * escape text ($str) for XML transport
189 * @return string Escaped text.
191 function xmlify($str) {
192 /// @TODO deprecated code found?
195 $len = mb_strlen($str);
196 for ($x = 0; $x < $len; $x ++) {
197 $char = mb_substr($str,$x,1);
227 $buffer = mb_ereg_replace("&", "&", $str);
228 $buffer = mb_ereg_replace("'", "'", $buffer);
229 $buffer = mb_ereg_replace('"', """, $buffer);
230 $buffer = mb_ereg_replace("<", "<", $buffer);
231 $buffer = mb_ereg_replace(">", ">", $buffer);
233 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
234 $buffer = trim($buffer);
239 if (! function_exists('unxmlify')) {
242 * @param string $s xml escaped text
243 * @return string unescaped text
245 function unxmlify($s) {
246 /// @TODO deprecated code found?
247 // $ret = str_replace('&','&', $s);
248 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
249 /*$ret = mb_ereg_replace('&', '&', $s);
250 $ret = mb_ereg_replace(''', "'", $ret);
251 $ret = mb_ereg_replace('"', '"', $ret);
252 $ret = mb_ereg_replace('<', "<", $ret);
253 $ret = mb_ereg_replace('>', ">", $ret);
255 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
259 if (! function_exists('hex2bin')) {
261 * convenience wrapper, reverse the operation "bin2hex"
265 function hex2bin($s) {
266 if (! (is_string($s) && strlen($s))) {
270 if (! ctype_xdigit($s)) {
274 return pack("H*",$s);
279 * @brief Paginator function. Pushes relevant links in a pager array structure.
281 * Links are generated depending on the current page and the total number of items.
282 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
283 * Current page link is given the "active" CSS class
285 * @param App $a App instance
286 * @param int $count [optional] item count (used with minimal pager)
287 * @return Array data for pagination template
289 function paginate_data(App $a, $count = null) {
290 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
292 $stripped = str_replace('q=', '', $stripped);
293 $stripped = trim($stripped, '/');
294 $pagenum = $a->pager['page'];
296 if (($a->page_offset != '') AND !preg_match('/[?&].offset=/', $stripped)) {
297 $stripped .= '&offset=' . urlencode($a->page_offset);
303 function _l(&$d, $name, $url, $text, $class = '') {
304 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
305 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
308 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
311 if (!is_null($count)) {
312 // minimal pager (newer / older)
313 $data['class'] = 'pager';
314 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
315 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
317 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
318 $data['class'] = 'pagination';
319 if ($a->pager['total'] > $a->pager['itemspage']) {
320 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
321 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
323 $numpages = $a->pager['total'] / $a->pager['itemspage'];
326 $numstop = $numpages;
328 // Limit the number of displayed page number buttons.
330 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
331 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
336 for ($i = $numstart; $i <= $numstop; $i++) {
337 if ($i == $a->pager['page']) {
338 _l($pages, $i, '#', $i, 'current active');
340 _l($pages, $i, $url . '&page='. $i, $i, 'n');
344 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
345 if ($i == $a->pager['page']) {
346 _l($pages, $i, '#', $i, 'current active');
348 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
352 $data['pages'] = $pages;
354 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
355 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
356 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
363 if (! function_exists('paginate')) {
365 * Automatic pagination.
367 * To use, get the count of total items.
368 * Then call $a->set_pager_total($number_items);
369 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
370 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
371 * (assuming there are enough items to paginate).
372 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
373 * will limit the results to the correct items for the current page.
374 * The actual page handling is then accomplished at the application layer.
376 * @param App $a App instance
377 * @return string html for pagination #FIXME remove html
379 function paginate(App $a) {
381 $data = paginate_data($a);
382 $tpl = get_markup_template("paginate.tpl");
383 return replace_macros($tpl, array("pager" => $data));
387 if (! function_exists('alt_pager')) {
390 * @param App $a App instance
392 * @return string html for pagination #FIXME remove html
394 function alt_pager(App $a, $i) {
396 $data = paginate_data($a, $i);
397 $tpl = get_markup_template("paginate.tpl");
398 return replace_macros($tpl, array('pager' => $data));
402 if (! function_exists('scroll_loader')) {
404 * Loader for infinite scrolling
405 * @return string html for loader
407 function scroll_loader() {
408 $tpl = get_markup_template("scroll_loader.tpl");
409 return replace_macros($tpl, array(
410 'wait' => t('Loading more entries...'),
411 'end' => t('The end')
415 if (! function_exists('expand_acl')) {
417 * Turn user/group ACLs stored as angle bracketed text into arrays
422 function expand_acl($s) {
423 // turn string array of angle-bracketed elements into numeric array
424 // e.g. "<1><2><3>" => array(1,2,3);
428 $t = str_replace('<','',$s);
429 $a = explode('>',$t);
432 $ret[] = intval($aa);
439 if (! function_exists('sanitise_acl')) {
441 * Wrap ACL elements in angle brackets for storage
442 * @param string $item
444 function sanitise_acl(&$item) {
446 $item = '<' . intval(notags(trim($item))) . '>';
452 if (! function_exists('perms2str')) {
454 * Convert an ACL array to a storable string
456 * Normally ACL permissions will be an array.
457 * We'll also allow a comma-separated string.
459 * @param string|array $p
462 function perms2str($p) {
467 $tmp = explode(',',$p);
469 if (is_array($tmp)) {
470 array_walk($tmp,'sanitise_acl');
471 $ret = implode('',$tmp);
477 if (! function_exists('item_new_uri')) {
479 * generate a guaranteed unique (for this domain) item ID for ATOM
480 * safe from birthday paradox
482 * @param string $hostname
486 function item_new_uri($hostname, $uid, $guid = "") {
492 $hash = get_guid(32);
498 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
500 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
502 if (dbm::is_result($r)) {
505 } while ($dups == true);
510 // Generate a guaranteed unique photo ID.
511 // safe from birthday paradox
513 if (! function_exists('photo_new_resource')) {
515 * Generate a guaranteed unique photo ID.
516 * safe from birthday paradox
520 function photo_new_resource() {
524 $resource = hash('md5',uniqid(mt_rand(),true));
525 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
529 if (dbm::is_result($r)) {
532 } while ($found == true);
538 if (! function_exists('load_view_file')) {
541 * wrapper to load a view template, checking for alternate
542 * languages before falling back to the default
544 * @global string $lang
546 * @param string $s view name
549 function load_view_file($s) {
551 if (! isset($lang)) {
556 if (file_exists("$d/$lang/$b")) {
557 $stamp1 = microtime(true);
558 $content = file_get_contents("$d/$lang/$b");
559 $a->save_timestamp($stamp1, "file");
563 $theme = current_theme();
565 if (file_exists("$d/theme/$theme/$b")) {
566 $stamp1 = microtime(true);
567 $content = file_get_contents("$d/theme/$theme/$b");
568 $a->save_timestamp($stamp1, "file");
572 $stamp1 = microtime(true);
573 $content = file_get_contents($s);
574 $a->save_timestamp($stamp1, "file");
578 if (! function_exists('get_intltext_template')) {
580 * load a view template, checking for alternate
581 * languages before falling back to the default
583 * @global string $lang
584 * @param string $s view path
587 function get_intltext_template($s) {
592 if ($a->theme['template_engine'] === 'smarty3') {
593 $engine = "/smarty3";
596 if (! isset($lang)) {
600 if (file_exists("view/lang/$lang$engine/$s")) {
601 $stamp1 = microtime(true);
602 $content = file_get_contents("view/lang/$lang$engine/$s");
603 $a->save_timestamp($stamp1, "file");
605 } elseif (file_exists("view/lang/en$engine/$s")) {
606 $stamp1 = microtime(true);
607 $content = file_get_contents("view/lang/en$engine/$s");
608 $a->save_timestamp($stamp1, "file");
611 $stamp1 = microtime(true);
612 $content = file_get_contents("view$engine/$s");
613 $a->save_timestamp($stamp1, "file");
618 if (! function_exists('get_markup_template')) {
623 * @param string $root
626 function get_markup_template($s, $root = '') {
627 $stamp1 = microtime(true);
630 $t = $a->template_engine();
632 $template = $t->get_template_file($s, $root);
633 } catch (Exception $e) {
634 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
638 $a->save_timestamp($stamp1, "file");
643 if (! function_exists("get_template_file")) {
647 * @param string $filename
648 * @param string $root
651 function get_template_file($a, $filename, $root = '') {
652 $theme = current_theme();
654 // Make sure $root ends with a slash /
655 if ($root !== '' && $root[strlen($root) - 1] !== '/') {
659 if (file_exists("{$root}view/theme/$theme/$filename")) {
660 $template_file = "{$root}view/theme/$theme/$filename";
661 } elseif (x($a->theme_info, "extends") && file_exists("{$root}view/theme/{$a->theme_info[\"extends\"]}/$filename")) {
662 $template_file = "{$root}view/theme/{$a->theme_info[\"extends\"]}/$filename";
663 } elseif (file_exists("{$root}/$filename")) {
664 $template_file = "{$root}/$filename";
666 $template_file = "{$root}view/$filename";
669 return $template_file;
678 if (! function_exists('attribute_contains')) {
680 * for html,xml parsing - let's say you've got
681 * an attribute foobar="class1 class2 class3"
682 * and you want to find out if it contains 'class3'.
683 * you can't use a normal sub string search because you
684 * might match 'notclass3' and a regex to do the job is
685 * possible but a bit complicated.
686 * pass the attribute string as $attr and the attribute you
687 * are looking for as $s - returns true if found, otherwise false
689 * @param string $attr attribute value
690 * @param string $s string to search
691 * @return boolean True if found, False otherwise
693 function attribute_contains($attr, $s) {
694 $a = explode(' ', $attr);
695 return (count($a) && in_array($s,$a));
698 if (! function_exists('logger')) {
699 /* setup int->string log level map */
700 $LOGGER_LEVELS = array();
703 * @brief Logs the given message at the given log level
706 * LOGGER_NORMAL (default)
714 * @global array $LOGGER_LEVELS
718 function logger($msg, $level = 0) {
721 global $LOGGER_LEVELS;
723 // turn off logger in install mode
725 $a->module == 'install'
726 || ! ($db && $db->connected)
731 $debugging = get_config('system','debugging');
732 $logfile = get_config('system','logfile');
733 $loglevel = intval(get_config('system','loglevel'));
738 || $level > $loglevel
743 if (count($LOGGER_LEVELS) == 0) {
744 foreach (get_defined_constants() as $k => $v) {
745 if (substr($k, 0, 7) == "LOGGER_") {
746 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
751 $process_id = session_id();
753 if ($process_id == '') {
754 $process_id = get_app()->process_id;
757 $callers = debug_backtrace();
758 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
761 $LOGGER_LEVELS[$level],
762 basename($callers[0]['file']),
764 $callers[1]['function'],
768 $stamp1 = microtime(true);
769 @file_put_contents($logfile, $logline, FILE_APPEND);
770 $a->save_timestamp($stamp1, "file");
774 * @brief An alternative logger for development.
775 * Works largely as logger() but allows developers
776 * to isolate particular elements they are targetting
777 * personally without background noise
780 * LOGGER_NORMAL (default)
788 * @global array $LOGGER_LEVELS
793 function dlogger($msg, $level = 0) {
797 // turn off logger in install mode
799 $a->module == 'install'
800 || ! ($db && $db->connected)
805 $logfile = get_config('system','dlogfile');
811 if (count($LOGGER_LEVELS) == 0) {
812 foreach (get_defined_constants() as $k => $v) {
813 if (substr($k, 0, 7) == "LOGGER_") {
814 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
819 $process_id = session_id();
821 if ($process_id == '') {
822 $process_id = get_app()->process_id;
825 $callers = debug_backtrace();
826 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
829 basename($callers[0]['file']),
831 $callers[1]['function'],
835 $stamp1 = microtime(true);
836 @file_put_contents($logfile, $logline, FILE_APPEND);
837 $a->save_timestamp($stamp1, "file");
840 if (! function_exists('activity_match')) {
842 * Compare activity uri. Knows about activity namespace.
844 * @param string $haystack
845 * @param string $needle
848 function activity_match($haystack,$needle) {
849 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
854 * @brief Pull out all #hashtags and @person tags from $string.
856 * We also get @person@domain.com - which would make
857 * the regex quite complicated as tags can also
858 * end a sentence. So we'll run through our results
859 * and strip the period from any tags which end with one.
860 * Returns array of tags found, or empty array.
862 * @param string $string Post content
863 * @return array List of tag and person names
865 function get_tags($string) {
868 // Convert hashtag links to hashtags
869 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
871 // ignore anything in a code block
872 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
874 // Force line feeds at bbtags
875 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
877 // ignore anything in a bbtag
878 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
880 // Match full names against @tags including the space between first and last
881 // We will look these up afterward to see if they are full names or not recognisable.
883 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
884 foreach ($matches[1] as $match) {
885 if (strstr($match, ']')) {
886 // we might be inside a bbcode color tag - leave it alone
889 if (substr($match, -1, 1) === '.') {
890 $ret[] = substr($match, 0, -1);
897 // Otherwise pull out single word tags. These can be @nickname, @first_last
900 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
901 foreach ($matches[1] as $match) {
902 if (strstr($match, ']')) {
903 // we might be inside a bbcode color tag - leave it alone
906 if (substr($match, -1, 1) === '.') {
907 $match = substr($match,0,-1);
909 // ignore strictly numeric tags like #1
910 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
913 // try not to catch url fragments
914 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
926 if (! function_exists('qp')) {
928 * quick and dirty quoted_printable encoding
934 return str_replace("%", "=", rawurlencode($s));
937 if (! function_exists('contact_block')) {
939 * Get html for contact block.
941 * @template contact_block.tpl
942 * @hook contact_block_end (contacts=>array, output=>string)
945 function contact_block() {
949 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
950 if ($shown === false) {
957 if ((! is_array($a->profile)) || ($a->profile['hide-friends'])) {
960 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
961 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
962 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
963 AND `network` IN ('%s', '%s', '%s')",
964 intval($a->profile['uid']),
966 dbesc(NETWORK_OSTATUS),
967 dbesc(NETWORK_DIASPORA)
969 if (dbm::is_result($r)) {
970 $total = intval($r[0]['total']);
973 $contacts = t('No contacts');
976 // Splitting the query in two parts makes it much faster
977 $r = q("SELECT `id` FROM `contact`
978 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
979 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
980 AND `network` IN ('%s', '%s', '%s')
981 ORDER BY RAND() LIMIT %d",
982 intval($a->profile['uid']),
984 dbesc(NETWORK_OSTATUS),
985 dbesc(NETWORK_DIASPORA),
988 if (dbm::is_result($r)) {
990 foreach ($r AS $contact) {
991 $contacts[] = $contact["id"];
993 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
994 dbesc(implode(",", $contacts)));
996 if (dbm::is_result($r)) {
997 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
999 foreach ($r as $rr) {
1000 $micropro[] = micropro($rr,true,'mpfriend');
1006 $tpl = get_markup_template('contact_block.tpl');
1007 $o = replace_macros($tpl, array(
1008 '$contacts' => $contacts,
1009 '$nickname' => $a->profile['nickname'],
1010 '$viewcontacts' => t('View Contacts'),
1011 '$micropro' => $micropro,
1014 $arr = array('contacts' => $r, 'output' => $o);
1016 call_hooks('contact_block_end', $arr);
1022 * @brief Format contacts as picture links or as texxt links
1024 * @param array $contact Array with contacts which contains an array with
1025 * int 'id' => The ID of the contact
1026 * int 'uid' => The user ID of the user who owns this data
1027 * string 'name' => The name of the contact
1028 * string 'url' => The url to the profile page of the contact
1029 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
1030 * string 'network' => The network to which the contact belongs to
1031 * string 'thumb' => The contact picture
1032 * string 'click' => js code which is performed when clicking on the contact
1033 * @param boolean $redirect If true try to use the redir url if it's possible
1034 * @param string $class CSS class for the
1035 * @param boolean $textmode If true display the contacts as text links
1036 * if false display the contacts as picture links
1038 * @return string Formatted html
1040 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
1042 // Use the contact URL if no address is available
1043 if ($contact["addr"] == "") {
1044 $contact["addr"] = $contact["url"];
1047 $url = $contact['url'];
1053 $redirect_url = 'redir/' . $contact['id'];
1054 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1056 $url = $redirect_url;
1057 $sparkle = ' sparkle';
1063 // If there is some js available we don't need the url
1064 if (x($contact, 'click')) {
1068 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1069 '$click' => (($contact['click']) ? $contact['click'] : ''),
1072 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1073 '$name' => $contact['name'],
1074 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1075 '$parkle' => $sparkle,
1083 if (! function_exists('search')) {
1087 * @param string $s search query
1088 * @param string $id html id
1089 * @param string $url search url
1090 * @param boolean $savedsearch show save search button
1092 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true) {
1096 '$s' => htmlspecialchars($s),
1098 '$action_url' => $url,
1099 '$search_label' => t('Search'),
1100 '$save_label' => t('Save'),
1101 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1102 '$search_hint' => t('@name, !forum, #tags, content'),
1106 $values['$searchoption'] = array(
1111 if (get_config('system','poco_local_search')) {
1112 $values['$searchoption'][] = t("Forums");
1116 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1119 if (! function_exists('valid_email')) {
1121 * Check if $x is a valid email string
1126 function valid_email($x){
1128 /// @TODO Removed because Fabio told me so.
1129 //if (get_config('system','disable_email_validation'))
1131 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $x);
1135 if (! function_exists('linkify')) {
1137 * Replace naked text hyperlink with HTML formatted hyperlink
1141 function linkify($s) {
1142 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1143 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1151 * @return array index is present tense verb
1152 value is array containing past tense verb, translation of present, translation of past
1153 * @hook poke_verbs pokes array
1155 function get_poke_verbs() {
1157 // index is present tense verb
1158 // value is array containing past tense verb, translation of present, translation of past
1161 'poke' => array( 'poked', t('poke'), t('poked')),
1162 'ping' => array( 'pinged', t('ping'), t('pinged')),
1163 'prod' => array( 'prodded', t('prod'), t('prodded')),
1164 'slap' => array( 'slapped', t('slap'), t('slapped')),
1165 'finger' => array( 'fingered', t('finger'), t('fingered')),
1166 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1168 call_hooks('poke_verbs', $arr);
1174 * @return array index is mood, value is translated mood
1175 * @hook mood_verbs moods array
1177 function get_mood_verbs() {
1180 'happy' => t('happy'),
1182 'mellow' => t('mellow'),
1183 'tired' => t('tired'),
1184 'perky' => t('perky'),
1185 'angry' => t('angry'),
1186 'stupefied' => t('stupified'),
1187 'puzzled' => t('puzzled'),
1188 'interested' => t('interested'),
1189 'bitter' => t('bitter'),
1190 'cheerful' => t('cheerful'),
1191 'alive' => t('alive'),
1192 'annoyed' => t('annoyed'),
1193 'anxious' => t('anxious'),
1194 'cranky' => t('cranky'),
1195 'disturbed' => t('disturbed'),
1196 'frustrated' => t('frustrated'),
1197 'motivated' => t('motivated'),
1198 'relaxed' => t('relaxed'),
1199 'surprised' => t('surprised'),
1202 call_hooks('mood_verbs', $arr);
1206 if (! function_exists('day_translate')) {
1208 * Translate days and months names
1213 function day_translate($s) {
1214 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1215 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1218 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1219 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')),
1226 if (! function_exists('normalise_link')) {
1230 * @param string $url
1233 function normalise_link($url) {
1234 $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
1235 return rtrim($ret,'/');
1240 if (! function_exists('link_compare')) {
1242 * Compare two URLs to see if they are the same, but ignore
1243 * slight but hopefully insignificant differences such as if one
1244 * is https and the other isn't, or if one is www.something and
1245 * the other isn't - and also ignore case differences.
1247 * @param string $a first url
1248 * @param string $b second url
1249 * @return boolean True if the URLs match, otherwise False
1252 function link_compare($a,$b) {
1253 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1257 * @brief Find any non-embedded images in private items and add redir links to them
1260 * @param array &$item The field array of an item row
1262 function redir_private_images($a, &$item)
1265 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1267 foreach ($matches as $mtch) {
1268 if (strpos($mtch[1], '/redir') !== false) {
1272 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1273 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1274 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1280 function put_item_in_cache(&$item, $update = false) {
1282 if (($item["rendered-hash"] != hash("md5", $item["body"])) OR ($item["rendered-hash"] == "") OR
1283 ($item["rendered-html"] == "") OR get_config("system", "ignore_cache")) {
1285 // The function "redir_private_images" changes the body.
1286 // I'm not sure if we should store it permanently, so we save the old value.
1287 $body = $item["body"];
1290 redir_private_images($a, $item);
1292 $item["rendered-html"] = prepare_text($item["body"]);
1293 $item["rendered-hash"] = hash("md5", $item["body"]);
1294 $item["body"] = $body;
1296 if ($update AND ($item["id"] != 0)) {
1297 q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
1298 dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
1303 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1304 // If attach is true, also add icons for item attachments
1306 if (! function_exists('prepare_body')) {
1308 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1309 * If attach is true, also add icons for item attachments
1311 * @param array $item
1312 * @param boolean $attach
1313 * @return string item body html
1314 * @hook prepare_body_init item array before any work
1315 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1316 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1318 function prepare_body(&$item,$attach = false, $preview = false) {
1321 call_hooks('prepare_body_init', $item);
1323 $searchpath = z_root()."/search?tag=";
1326 $hashtags = array();
1327 $mentions = array();
1329 if (!get_config('system','suppress_tags')) {
1330 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1331 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1333 foreach ($taglist as $tag) {
1335 if ($tag["url"] == "") {
1336 $tag["url"] = $searchpath.strtolower($tag["term"]);
1339 if ($tag["type"] == TERM_HASHTAG) {
1340 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1342 } elseif ($tag["type"] == TERM_MENTION) {
1343 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1346 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1350 $item['tags'] = $tags;
1351 $item['hashtags'] = $hashtags;
1352 $item['mentions'] = $mentions;
1354 // Update the cached values if there is no "zrl=..." on the links
1355 $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
1357 // Or update it if the current viewer is the intented viewer
1358 if (($item["uid"] == local_user()) AND ($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 $as .= '<div class="body-attach">';
1380 foreach ($arr as $r) {
1383 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1385 foreach ($matches as $mtch) {
1388 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1389 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1391 $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' => z_root(),
1399 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1400 '$baseurl' => z_root(),
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);
1422 $filesubtype = 'unkn';
1425 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1426 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1432 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1435 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1439 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1440 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1442 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1446 $as .= '<div class="clear"></div></div>';
1451 if (strpos($s, '<div class="map">') !== false && $item['coord']) {
1452 $x = generate_map(trim($item['coord']));
1454 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1460 $spoilersearch = '<blockquote class="spoiler">';
1462 // Remove line breaks before the spoiler
1463 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1464 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1466 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1467 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1470 while ((strpos($s, $spoilersearch) !== false)) {
1471 $pos = strpos($s, $spoilersearch);
1472 $rnd = random_string(8);
1473 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1474 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1475 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1478 // Look for quote with author
1479 $authorsearch = '<blockquote class="author">';
1481 while ((strpos($s, $authorsearch) !== false)) {
1482 $pos = strpos($s, $authorsearch);
1483 $rnd = random_string(8);
1484 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1485 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1486 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1489 // replace friendica image url size with theme preference
1490 if (x($a->theme_info, 'item_image_size')){
1491 $ps = $a->theme_info['item_image_size'];
1492 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1495 $prep_arr = array('item' => $item, 'html' => $s);
1496 call_hooks('prepare_body_final', $prep_arr);
1498 return $prep_arr['html'];
1502 if (! function_exists('prepare_text')) {
1504 * Given a text string, convert from bbcode to html and add smilie icons.
1506 * @param string $text
1509 function prepare_text($text) {
1511 require_once 'include/bbcode.php';
1513 if (stristr($text, '[nosmile]')) {
1516 $s = Smilies::replace(bbcode($text));
1525 * return array with details for categories and folders for an item
1527 * @param array $item
1531 * [ // categories array
1533 * 'name': 'category name',
1534 * 'removeurl': 'url to remove this category',
1535 * 'first': 'is the first in this array? true/false',
1536 * 'last': 'is the last in this array? true/false',
1542 * 'name': 'folder name',
1543 * 'removeurl': 'url to remove this folder',
1544 * 'first': 'is the first in this array? true/false',
1545 * 'last': 'is the last in this array? true/false',
1551 function get_cats_and_terms($item) {
1554 $categories = array();
1557 $matches = false; $first = true;
1558 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1560 foreach ($matches as $mtch) {
1561 $categories[] = array(
1562 'name' => xmlify(file_tag_decode($mtch[1])),
1564 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1572 if (count($categories)) {
1573 $categories[count($categories) - 1]['last'] = true;
1576 if (local_user() == $item['uid']) {
1577 $matches = false; $first = true;
1578 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1580 foreach ($matches as $mtch) {
1582 'name' => xmlify(file_tag_decode($mtch[1])),
1584 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1593 if (count($folders)) {
1594 $folders[count($folders) - 1]['last'] = true;
1597 return array($categories, $folders);
1600 if (! function_exists('get_plink')) {
1602 * get private link for item
1603 * @param array $item
1604 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1606 function get_plink($item) {
1609 if ($a->user['nickname'] != "") {
1611 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1612 'href' => "display/" . $item['guid'],
1613 'orig' => "display/" . $item['guid'],
1614 'title' => t('View on separate page'),
1615 'orig_title' => t('view on separate page'),
1618 if (x($item, 'plink')) {
1619 $ret["href"] = $a->remove_baseurl($item['plink']);
1620 $ret["title"] = t('link to source');
1623 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1625 'href' => $item['plink'],
1626 'orig' => $item['plink'],
1627 'title' => t('link to source'),
1633 //if (x($item,'plink') && ($item['private'] != 1))
1638 if (! function_exists('unamp')) {
1640 * replace html amp entity with amp char
1644 function unamp($s) {
1645 return str_replace('&', '&', $s);
1649 if (! function_exists('return_bytes')) {
1651 * return number of bytes in size (K, M, G)
1652 * @param string $size_str
1655 function return_bytes ($size_str) {
1656 switch (substr ($size_str, -1)) {
1657 case 'M': case 'm': return (int)$size_str * 1048576;
1658 case 'K': case 'k': return (int)$size_str * 1024;
1659 case 'G': case 'g': return (int)$size_str * 1073741824;
1660 default: return $size_str;
1667 function generate_user_guid() {
1670 $guid = get_guid(32);
1671 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1674 if (! dbm::is_result($x)) {
1677 } while ($found == true );
1685 * @param boolean $strip_padding
1688 function base64url_encode($s, $strip_padding = false) {
1690 $s = strtr(base64_encode($s), '+/', '-_');
1692 if ($strip_padding) {
1693 $s = str_replace('=','',$s);
1703 function base64url_decode($s) {
1706 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1711 * // Placeholder for new rev of salmon which strips base64 padding.
1712 * // PHP base64_decode handles the un-padded input without requiring this step
1713 * // Uncomment if you find you need it.
1716 * if (! strpos($s,'=')) {
1726 return base64_decode(strtr($s,'-_','+/'));
1730 if (!function_exists('str_getcsv')) {
1734 * @param string $input
1735 * @param string $delimiter
1736 * @param string $enclosure
1737 * @param string $escape
1738 * @param string $eol
1739 * @return boolean|array False on error, otherwise array[row][column]
1741 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1742 if (is_string($input) && !empty($input)) {
1744 $tmp = preg_split("/".$eol."/",$input);
1745 if (is_array($tmp) && !empty($tmp)) {
1746 while (list($line_num, $line) = each($tmp)) {
1747 if (preg_match("/".$escape.$enclosure."/",$line)) {
1748 while ($strlen = strlen($line)) {
1749 $pos_delimiter = strpos($line,$delimiter);
1750 $pos_enclosure_start = strpos($line,$enclosure);
1752 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1753 && ($pos_enclosure_start < $pos_delimiter)
1755 $enclosed_str = substr($line,1);
1756 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1757 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1758 $output[$line_num][] = $enclosed_str;
1759 $offset = $pos_enclosure_end+3;
1761 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1762 $output[$line_num][] = substr($line,0);
1763 $offset = strlen($line);
1765 $output[$line_num][] = substr($line,0,$pos_delimiter);
1767 !empty($pos_enclosure_start)
1768 && ($pos_enclosure_start < $pos_delimiter)
1770 ?$pos_enclosure_start
1774 $line = substr($line,$offset);
1777 $line = preg_split("/".$delimiter."/",$line);
1780 * Validating against pesky extra line breaks creating false rows.
1782 if (is_array($line) && !empty($line[0])) {
1783 $output[$line_num] = $line;
1798 * return div element with class 'clear'
1802 function cleardiv() {
1803 return '<div class="clear"></div>';
1807 function bb_translate_video($s) {
1810 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1812 foreach ($matches as $mtch) {
1813 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1814 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1815 elseif (stristr($mtch[1],'vimeo'))
1816 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1822 function html2bb_video($s) {
1824 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1825 '[youtube]$2[/youtube]', $s);
1827 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1828 '[youtube]$2[/youtube]', $s);
1830 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1831 '[vimeo]$2[/vimeo]', $s);
1837 * apply xmlify() to all values of array $val, recursively
1841 function array_xmlify($val){
1842 if (is_bool($val)) {
1843 return $val?"true":"false";
1844 } elseif (is_array($val)) {
1845 return array_map('array_xmlify', $val);
1847 return xmlify((string) $val);
1852 * transorm link href and img src from relative to absolute
1854 * @param string $text
1855 * @param string $base base url
1858 function reltoabs($text, $base) {
1863 $base = rtrim($base,'/');
1865 $base2 = $base . "/";
1868 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1869 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1870 $text = preg_replace($pattern, $replace, $text);
1872 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1873 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1874 $text = preg_replace($pattern, $replace, $text);
1877 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1878 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1879 $text = preg_replace($pattern, $replace, $text);
1881 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1882 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1883 $text = preg_replace($pattern, $replace, $text);
1891 * get translated item type
1893 * @param array $itme
1896 function item_post_type($item) {
1897 if (intval($item['event-id'])) {
1899 } elseif (strlen($item['resource-id'])) {
1901 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1902 return t('activity');
1903 } elseif ($item['id'] != $item['parent']) {
1904 return t('comment');
1910 // post categories and "save to file" use the same item.file table for storage.
1911 // We will differentiate the different uses by wrapping categories in angle brackets
1912 // and save to file categories in square brackets.
1913 // To do this we need to escape these characters if they appear in our tag.
1915 function file_tag_encode($s) {
1916 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1919 function file_tag_decode($s) {
1920 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1923 function file_tag_file_query($table,$s,$type = 'file') {
1925 if ($type == 'file')
1926 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1928 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1929 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1932 // ex. given music,video return <music><video> or [music][video]
1933 function file_tag_list_to_file($list,$type = 'file') {
1935 if (strlen($list)) {
1936 $list_array = explode(",",$list);
1937 if ($type == 'file') {
1946 foreach ($list_array as $item) {
1947 if (strlen($item)) {
1948 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1955 // ex. given <music><video>[friends], return music,video or friends
1956 function file_tag_file_to_list($file,$type = 'file') {
1959 if ($type == 'file') {
1960 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1963 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1966 foreach ($matches as $mtch) {
1969 $list .= file_tag_decode($mtch[1]);
1976 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1977 // $file_old - categories previously associated with an item
1978 // $file_new - new list of categories for an item
1983 if ($file_old == $file_new)
1986 $saved = get_pconfig($uid,'system','filetags');
1987 if (strlen($saved)) {
1988 if ($type == 'file') {
1991 $termtype = TERM_FILE;
1996 $termtype = TERM_CATEGORY;
1999 $filetags_updated = $saved;
2001 // check for new tags to be added as filetags in pconfig
2002 $new_tags = array();
2003 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
2005 foreach ($check_new_tags as $tag) {
2006 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
2010 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
2012 // check for deleted tags to be removed from filetags in pconfig
2013 $deleted_tags = array();
2014 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2016 foreach ($check_deleted_tags as $tag) {
2017 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2018 $deleted_tags[] = $tag;
2021 foreach ($deleted_tags as $key => $tag) {
2022 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2024 intval(TERM_OBJ_POST),
2028 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2032 if (dbm::is_result($r)) {
2033 unset($deleted_tags[$key]);
2036 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2040 if ($saved != $filetags_updated) {
2041 set_pconfig($uid,'system','filetags', $filetags_updated);
2046 if (strlen($file_new)) {
2047 set_pconfig($uid,'system','filetags', $file_new);
2052 function file_tag_save_file($uid,$item,$file) {
2053 require_once("include/files.php");
2058 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2062 if (dbm::is_result($r)) {
2063 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2064 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2065 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2070 create_files_from_item($item);
2072 $saved = get_pconfig($uid,'system','filetags');
2073 if ((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2074 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2075 info( t('Item filed') );
2080 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2081 require_once("include/files.php");
2088 $pattern = '<' . file_tag_encode($file) . '>' ;
2089 $termtype = TERM_CATEGORY;
2091 $pattern = '[' . file_tag_encode($file) . ']' ;
2092 $termtype = TERM_FILE;
2096 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2100 if (! dbm::is_result($r)) {
2104 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2105 dbesc(str_replace($pattern,'',$r[0]['file'])),
2110 create_files_from_item($item);
2112 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2114 intval(TERM_OBJ_POST),
2118 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2121 if (! dbm::is_result($r)) {
2122 $saved = get_pconfig($uid,'system','filetags');
2123 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2129 function normalise_openid($s) {
2130 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2134 function undo_post_tagging($s) {
2136 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2138 foreach ($matches as $mtch) {
2139 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2145 function protect_sprintf($s) {
2146 return str_replace('%', '%%', $s);
2150 function is_a_date_arg($s) {
2154 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2155 $m = intval(substr($s,5));
2156 if ($m > 0 && $m <= 12)
2164 * remove intentation from a text
2166 function deindent($text, $chr = "[\t ]", $count = NULL) {
2167 $lines = explode("\n", $text);
2168 if (is_null($count)) {
2171 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2174 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2175 $count = strlen($m[0]);
2177 for ($k=0; $k < count($lines); $k++) {
2178 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2181 return implode("\n", $lines);
2184 function formatBytes($bytes, $precision = 2) {
2185 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2187 $bytes = max($bytes, 0);
2188 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2189 $pow = min($pow, count($units) - 1);
2191 $bytes /= pow(1024, $pow);
2193 return round($bytes, $precision) . ' ' . $units[$pow];
2197 * @brief translate and format the networkname of a contact
2199 * @param string $network
2200 * Networkname of the contact (e.g. dfrn, rss and so on)
2205 function format_network_name($network, $url = 0) {
2206 if ($network != "") {
2207 require_once('include/contact_selectors.php');
2209 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2211 $network_name = network_to_name($network);
2213 return $network_name;
2219 * @brief Syntax based code highlighting for popular languages.
2220 * @param string $s Code block
2221 * @param string $lang Programming language
2222 * @return string Formated html
2224 function text_highlight($s, $lang) {
2225 if ($lang === 'js') {
2226 $lang = 'javascript';
2229 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2231 // Autoload the library to make constants available
2232 class_exists('Text_Highlighter_Renderer_Html');
2235 'numbers' => HL_NUMBERS_LI,
2240 $s = trim(html_entity_decode($s, ENT_COMPAT));
2241 $s = str_replace(' ', "\t", $s);
2244 * The highlighter library insists on an opening php tag for php code blocks. If
2245 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2246 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2248 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2249 $s = '<?php' . "\n" . $s;
2253 $renderer = new Text_Highlighter_Renderer_Html($options);
2254 $hl = Text_Highlighter::factory($lang);
2255 $hl->setRenderer($renderer);
2256 $o = $hl->highlight($s);
2257 $o = str_replace("\n", '', $o);
2260 $b = substr($o, 0, strpos($o, '<li>'));
2261 $e = substr($o, strpos($o, '</li>'));
2265 return '<code>' . $o . '</code>';