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();
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>"; killme();
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) {
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) {
94 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
98 // generate a string that's random, but usually pronounceable.
99 // used to generate initial passwords
101 if(! function_exists('autoname')) {
103 * generate a string that's random, but usually pronounceable.
104 * used to generate initial passwords
108 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)
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);
154 for ($x = 0; $x < $len; $x ++) {
155 $r = mt_rand(0,count($table) - 1);
158 if($table == $vowels)
159 $table = array_merge($cons,$midcons);
165 $word = substr($word,0,$len);
167 foreach($noend as $noe) {
168 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
169 $word = substr($word,0,-1);
173 if(substr($word,-1) == 'q')
174 $word = substr($word,0,-1);
179 // escape text ($str) for XML transport
180 // returns escaped text.
182 if(! function_exists('xmlify')) {
184 * escape text ($str) for XML transport
186 * @return string Escaped text.
188 function xmlify($str) {
191 $len = mb_strlen($str);
192 for($x = 0; $x < $len; $x ++) {
193 $char = mb_substr($str,$x,1);
223 $buffer = mb_ereg_replace("&", "&", $str);
224 $buffer = mb_ereg_replace("'", "'", $buffer);
225 $buffer = mb_ereg_replace('"', """, $buffer);
226 $buffer = mb_ereg_replace("<", "<", $buffer);
227 $buffer = mb_ereg_replace(">", ">", $buffer);
229 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
230 $buffer = trim($buffer);
235 if(! function_exists('unxmlify')) {
238 * @param string $s xml escaped text
239 * @return string unescaped text
241 function unxmlify($s) {
242 // $ret = str_replace('&','&', $s);
243 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
244 /*$ret = mb_ereg_replace('&', '&', $s);
245 $ret = mb_ereg_replace(''', "'", $ret);
246 $ret = mb_ereg_replace('"', '"', $ret);
247 $ret = mb_ereg_replace('<', "<", $ret);
248 $ret = mb_ereg_replace('>', ">", $ret);
250 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
254 if(! function_exists('hex2bin')) {
256 * convenience wrapper, reverse the operation "bin2hex"
260 function hex2bin($s) {
261 if(! (is_string($s) && strlen($s)))
264 if(! ctype_xdigit($s)) {
268 return(pack("H*",$s));
273 * @brief Paginator function. Pushes relevant links in a pager array structure.
275 * Links are generated depending on the current page and the total number of items.
276 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
277 * Current page link is given the "active" CSS class
279 * @param App $a App instance
280 * @param int $count [optional] item count (used with minimal pager)
281 * @return Array data for pagination template
283 function paginate_data(App $a, $count = null) {
284 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
286 $stripped = str_replace('q=', '', $stripped);
287 $stripped = trim($stripped, '/');
288 $pagenum = $a->pager['page'];
290 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
291 $stripped .= '&offset=' . urlencode($a->page_offset);
297 function _l(&$d, $name, $url, $text, $class = '') {
298 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
299 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
302 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
305 if (!is_null($count)) {
306 // minimal pager (newer / older)
307 $data['class'] = 'pager';
308 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
309 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
311 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
312 $data['class'] = 'pagination';
313 if ($a->pager['total'] > $a->pager['itemspage']) {
314 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
315 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
317 $numpages = $a->pager['total'] / $a->pager['itemspage'];
320 $numstop = $numpages;
322 // Limit the number of displayed page number buttons.
324 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
325 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
330 for ($i = $numstart; $i <= $numstop; $i++) {
331 if ($i == $a->pager['page']) {
332 _l($pages, $i, '#', $i, 'current active');
334 _l($pages, $i, $url . '&page='. $i, $i, 'n');
338 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
339 if ($i == $a->pager['page']) {
340 _l($pages, $i, '#', $i, 'current active');
342 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
346 $data['pages'] = $pages;
348 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
349 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
350 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
357 if(! function_exists('paginate')) {
359 * Automatic pagination.
361 * To use, get the count of total items.
362 * Then call $a->set_pager_total($number_items);
363 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
364 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
365 * (assuming there are enough items to paginate).
366 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
367 * will limit the results to the correct items for the current page.
368 * The actual page handling is then accomplished at the application layer.
370 * @param App $a App instance
371 * @return string html for pagination #FIXME remove html
373 function paginate(App $a) {
375 $data = paginate_data($a);
376 $tpl = get_markup_template("paginate.tpl");
377 return replace_macros($tpl, array("pager" => $data));
381 if(! function_exists('alt_pager')) {
384 * @param App $a App instance
386 * @return string html for pagination #FIXME remove html
388 function alt_pager(App $a, $i) {
390 $data = paginate_data($a, $i);
391 $tpl = get_markup_template("paginate.tpl");
392 return replace_macros($tpl, array('pager' => $data));
396 if(! function_exists('scroll_loader')) {
398 * Loader for infinite scrolling
399 * @return string html for loader
401 function scroll_loader() {
402 $tpl = get_markup_template("scroll_loader.tpl");
403 return replace_macros($tpl, array(
404 'wait' => t('Loading more entries...'),
405 'end' => t('The end')
409 if(! function_exists('expand_acl')) {
411 * Turn user/group ACLs stored as angle bracketed text into arrays
416 function expand_acl($s) {
417 // turn string array of angle-bracketed elements into numeric array
418 // e.g. "<1><2><3>" => array(1,2,3);
422 $t = str_replace('<','',$s);
423 $a = explode('>',$t);
426 $ret[] = intval($aa);
432 if(! function_exists('sanitise_acl')) {
434 * Wrap ACL elements in angle brackets for storage
435 * @param string $item
437 function sanitise_acl(&$item) {
439 $item = '<' . intval(notags(trim($item))) . '>';
445 if(! function_exists('perms2str')) {
447 * Convert an ACL array to a storable string
449 * Normally ACL permissions will be an array.
450 * We'll also allow a comma-separated string.
452 * @param string|array $p
455 function perms2str($p) {
460 $tmp = explode(',',$p);
463 array_walk($tmp,'sanitise_acl');
464 $ret = implode('',$tmp);
470 if(! function_exists('item_new_uri')) {
472 * generate a guaranteed unique (for this domain) item ID for ATOM
473 * safe from birthday paradox
475 * @param string $hostname
479 function item_new_uri($hostname,$uid, $guid = "") {
485 $hash = get_guid(32);
491 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
493 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
495 if (dbm::is_result($r))
497 } while($dups == true);
501 // Generate a guaranteed unique photo ID.
502 // safe from birthday paradox
504 if(! function_exists('photo_new_resource')) {
506 * Generate a guaranteed unique photo ID.
507 * safe from birthday paradox
511 function photo_new_resource() {
515 $resource = hash('md5',uniqid(mt_rand(),true));
516 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
519 if (dbm::is_result($r))
521 } while($found == true);
526 if(! function_exists('load_view_file')) {
529 * wrapper to load a view template, checking for alternate
530 * languages before falling back to the default
532 * @global string $lang
534 * @param string $s view name
537 function load_view_file($s) {
543 if(file_exists("$d/$lang/$b")) {
544 $stamp1 = microtime(true);
545 $content = file_get_contents("$d/$lang/$b");
546 $a->save_timestamp($stamp1, "file");
550 $theme = current_theme();
552 if(file_exists("$d/theme/$theme/$b")) {
553 $stamp1 = microtime(true);
554 $content = file_get_contents("$d/theme/$theme/$b");
555 $a->save_timestamp($stamp1, "file");
559 $stamp1 = microtime(true);
560 $content = file_get_contents($s);
561 $a->save_timestamp($stamp1, "file");
565 if(! function_exists('get_intltext_template')) {
567 * load a view template, checking for alternate
568 * languages before falling back to the default
570 * @global string $lang
571 * @param string $s view path
574 function get_intltext_template($s) {
579 if($a->theme['template_engine'] === 'smarty3')
580 $engine = "/smarty3";
585 if(file_exists("view/lang/$lang$engine/$s")) {
586 $stamp1 = microtime(true);
587 $content = file_get_contents("view/lang/$lang$engine/$s");
588 $a->save_timestamp($stamp1, "file");
590 } elseif(file_exists("view/lang/en$engine/$s")) {
591 $stamp1 = microtime(true);
592 $content = file_get_contents("view/lang/en$engine/$s");
593 $a->save_timestamp($stamp1, "file");
596 $stamp1 = microtime(true);
597 $content = file_get_contents("view$engine/$s");
598 $a->save_timestamp($stamp1, "file");
603 if(! function_exists('get_markup_template')) {
608 * @param string $root
611 function get_markup_template($s, $root = '') {
612 $stamp1 = microtime(true);
615 $t = $a->template_engine();
617 $template = $t->get_template_file($s, $root);
618 } catch (Exception $e) {
619 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
622 $a->save_timestamp($stamp1, "file");
627 if(! function_exists("get_template_file")) {
631 * @param string $filename
632 * @param string $root
635 function get_template_file($a, $filename, $root = '') {
636 $theme = current_theme();
638 // Make sure $root ends with a slash /
639 if($root !== '' && $root[strlen($root)-1] !== '/')
642 if(file_exists("{$root}view/theme/$theme/$filename"))
643 $template_file = "{$root}view/theme/$theme/$filename";
644 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
645 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
646 elseif (file_exists("{$root}/$filename"))
647 $template_file = "{$root}/$filename";
649 $template_file = "{$root}view/$filename";
651 return $template_file;
660 if(! function_exists('attribute_contains')) {
662 * for html,xml parsing - let's say you've got
663 * an attribute foobar="class1 class2 class3"
664 * and you want to find out if it contains 'class3'.
665 * you can't use a normal sub string search because you
666 * might match 'notclass3' and a regex to do the job is
667 * possible but a bit complicated.
668 * pass the attribute string as $attr and the attribute you
669 * are looking for as $s - returns true if found, otherwise false
671 * @param string $attr attribute value
672 * @param string $s string to search
673 * @return boolean True if found, False otherwise
675 function attribute_contains($attr,$s) {
676 $a = explode(' ', $attr);
677 if(count($a) && in_array($s,$a))
682 if (! function_exists('logger')) {
683 /* setup int->string log level map */
684 $LOGGER_LEVELS = array();
687 * @brief Logs the given message at the given log level
690 * LOGGER_NORMAL (default)
698 * @global array $LOGGER_LEVELS
702 function logger($msg, $level = 0) {
705 global $LOGGER_LEVELS;
707 // turn off logger in install mode
709 $a->module == 'install'
710 || ! ($db && $db->connected)
715 $debugging = get_config('system','debugging');
716 $logfile = get_config('system','logfile');
717 $loglevel = intval(get_config('system','loglevel'));
722 || $level > $loglevel
727 if (count($LOGGER_LEVELS) == 0) {
728 foreach (get_defined_constants() as $k => $v) {
729 if (substr($k, 0, 7) == "LOGGER_") {
730 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
735 $process_id = session_id();
737 if ($process_id == '') {
738 $process_id = get_app()->process_id;
741 $callers = debug_backtrace();
742 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
745 $LOGGER_LEVELS[$level],
746 basename($callers[0]['file']),
748 $callers[1]['function'],
752 $stamp1 = microtime(true);
753 @file_put_contents($logfile, $logline, FILE_APPEND);
754 $a->save_timestamp($stamp1, "file");
758 * @brief An alternative logger for development.
759 * Works largely as logger() but allows developers
760 * to isolate particular elements they are targetting
761 * personally without background noise
764 * LOGGER_NORMAL (default)
772 * @global array $LOGGER_LEVELS
777 function dlogger($msg, $level = 0) {
781 // turn off logger in install mode
783 $a->module == 'install'
784 || ! ($db && $db->connected)
789 $logfile = get_config('system','dlogfile');
795 if (count($LOGGER_LEVELS) == 0) {
796 foreach (get_defined_constants() as $k => $v) {
797 if (substr($k, 0, 7) == "LOGGER_") {
798 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
803 $process_id = session_id();
805 if ($process_id == '') {
806 $process_id = get_app()->process_id;
809 $callers = debug_backtrace();
810 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
813 basename($callers[0]['file']),
815 $callers[1]['function'],
819 $stamp1 = microtime(true);
820 @file_put_contents($logfile, $logline, FILE_APPEND);
821 $a->save_timestamp($stamp1, "file");
824 if(! function_exists('activity_match')) {
826 * Compare activity uri. Knows about activity namespace.
828 * @param string $haystack
829 * @param string $needle
832 function activity_match($haystack,$needle) {
833 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
840 * @brief Pull out all #hashtags and @person tags from $string.
842 * We also get @person@domain.com - which would make
843 * the regex quite complicated as tags can also
844 * end a sentence. So we'll run through our results
845 * and strip the period from any tags which end with one.
846 * Returns array of tags found, or empty array.
848 * @param string $string Post content
849 * @return array List of tag and person names
851 function get_tags($string) {
854 // Convert hashtag links to hashtags
855 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
857 // ignore anything in a code block
858 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
860 // Force line feeds at bbtags
861 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
863 // ignore anything in a bbtag
864 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
866 // Match full names against @tags including the space between first and last
867 // We will look these up afterward to see if they are full names or not recognisable.
869 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
870 foreach ($matches[1] as $match) {
871 if (strstr($match, ']')) {
872 // we might be inside a bbcode color tag - leave it alone
875 if (substr($match, -1, 1) === '.') {
876 $ret[] = substr($match, 0, -1);
883 // Otherwise pull out single word tags. These can be @nickname, @first_last
886 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
887 foreach($matches[1] as $match) {
888 if (strstr($match, ']')) {
889 // we might be inside a bbcode color tag - leave it alone
892 if (substr($match, -1, 1) === '.') {
893 $match = substr($match,0,-1);
895 // ignore strictly numeric tags like #1
896 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
899 // try not to catch url fragments
900 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
912 if(! function_exists('qp')) {
914 * quick and dirty quoted_printable encoding
920 return str_replace ("%","=",rawurlencode($s));
923 if(! function_exists('contact_block')) {
925 * Get html for contact block.
927 * @template contact_block.tpl
928 * @hook contact_block_end (contacts=>array, output=>string)
931 function contact_block() {
935 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
941 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
943 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
944 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
945 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
946 AND `network` IN ('%s', '%s', '%s')",
947 intval($a->profile['uid']),
949 dbesc(NETWORK_OSTATUS),
950 dbesc(NETWORK_DIASPORA)
952 if (dbm::is_result($r)) {
953 $total = intval($r[0]['total']);
956 $contacts = t('No contacts');
960 // Splitting the query in two parts makes it much faster
961 $r = q("SELECT `id` FROM `contact`
962 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
963 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
964 AND `network` IN ('%s', '%s', '%s')
965 ORDER BY RAND() LIMIT %d",
966 intval($a->profile['uid']),
968 dbesc(NETWORK_OSTATUS),
969 dbesc(NETWORK_DIASPORA),
972 if (dbm::is_result($r)) {
974 foreach ($r AS $contact) {
975 $contacts[] = $contact["id"];
977 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
978 dbesc(implode(",", $contacts)));
980 if (dbm::is_result($r)) {
981 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
983 foreach ($r as $rr) {
984 $micropro[] = micropro($rr,true,'mpfriend');
990 $tpl = get_markup_template('contact_block.tpl');
991 $o = replace_macros($tpl, array(
992 '$contacts' => $contacts,
993 '$nickname' => $a->profile['nickname'],
994 '$viewcontacts' => t('View Contacts'),
995 '$micropro' => $micropro,
998 $arr = array('contacts' => $r, 'output' => $o);
1000 call_hooks('contact_block_end', $arr);
1006 * @brief Format contacts as picture links or as texxt links
1008 * @param array $contact Array with contacts which contains an array with
1009 * int 'id' => The ID of the contact
1010 * int 'uid' => The user ID of the user who owns this data
1011 * string 'name' => The name of the contact
1012 * string 'url' => The url to the profile page of the contact
1013 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
1014 * string 'network' => The network to which the contact belongs to
1015 * string 'thumb' => The contact picture
1016 * string 'click' => js code which is performed when clicking on the contact
1017 * @param boolean $redirect If true try to use the redir url if it's possible
1018 * @param string $class CSS class for the
1019 * @param boolean $textmode If true display the contacts as text links
1020 * if false display the contacts as picture links
1022 * @return string Formatted html
1024 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
1026 // Use the contact URL if no address is available
1027 if ($contact["addr"] == "")
1028 $contact["addr"] = $contact["url"];
1030 $url = $contact['url'];
1036 $redirect_url = 'redir/' . $contact['id'];
1037 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1039 $url = $redirect_url;
1040 $sparkle = ' sparkle';
1046 // If there is some js available we don't need the url
1047 if(x($contact,'click'))
1050 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1051 '$click' => (($contact['click']) ? $contact['click'] : ''),
1054 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1055 '$name' => $contact['name'],
1056 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1057 '$parkle' => $sparkle,
1065 if(! function_exists('search')) {
1069 * @param string $s search query
1070 * @param string $id html id
1071 * @param string $url search url
1072 * @param boolean $savedsearch show save search button
1074 function search($s,$id='search-box',$url='search',$save = false, $aside = true) {
1078 '$s' => htmlspecialchars($s),
1080 '$action_url' => $url,
1081 '$search_label' => t('Search'),
1082 '$save_label' => t('Save'),
1083 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1084 '$search_hint' => t('@name, !forum, #tags, content'),
1088 $values['$searchoption'] = array(
1093 if (get_config('system','poco_local_search'))
1094 $values['$searchoption'][] = t("Forums");
1097 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1100 if(! function_exists('valid_email')) {
1102 * Check if $x is a valid email string
1107 function valid_email($x){
1109 // Removed because Fabio told me so.
1110 //if(get_config('system','disable_email_validation'))
1113 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
1119 if(! function_exists('linkify')) {
1121 * Replace naked text hyperlink with HTML formatted hyperlink
1125 function linkify($s) {
1126 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1127 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1135 * @return array index is present tense verb
1136 value is array containing past tense verb, translation of present, translation of past
1137 * @hook poke_verbs pokes array
1139 function get_poke_verbs() {
1141 // index is present tense verb
1142 // value is array containing past tense verb, translation of present, translation of past
1145 'poke' => array( 'poked', t('poke'), t('poked')),
1146 'ping' => array( 'pinged', t('ping'), t('pinged')),
1147 'prod' => array( 'prodded', t('prod'), t('prodded')),
1148 'slap' => array( 'slapped', t('slap'), t('slapped')),
1149 'finger' => array( 'fingered', t('finger'), t('fingered')),
1150 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1152 call_hooks('poke_verbs', $arr);
1158 * @return array index is mood, value is translated mood
1159 * @hook mood_verbs moods array
1161 function get_mood_verbs() {
1164 'happy' => t('happy'),
1166 'mellow' => t('mellow'),
1167 'tired' => t('tired'),
1168 'perky' => t('perky'),
1169 'angry' => t('angry'),
1170 'stupefied' => t('stupified'),
1171 'puzzled' => t('puzzled'),
1172 'interested' => t('interested'),
1173 'bitter' => t('bitter'),
1174 'cheerful' => t('cheerful'),
1175 'alive' => t('alive'),
1176 'annoyed' => t('annoyed'),
1177 'anxious' => t('anxious'),
1178 'cranky' => t('cranky'),
1179 'disturbed' => t('disturbed'),
1180 'frustrated' => t('frustrated'),
1181 'motivated' => t('motivated'),
1182 'relaxed' => t('relaxed'),
1183 'surprised' => t('surprised'),
1186 call_hooks('mood_verbs', $arr);
1190 if(! function_exists('day_translate')) {
1192 * Translate days and months names
1197 function day_translate($s) {
1198 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1199 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1202 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1203 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')),
1210 if(! function_exists('normalise_link')) {
1214 * @param string $url
1217 function normalise_link($url) {
1218 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1219 return(rtrim($ret,'/'));
1224 if(! function_exists('link_compare')) {
1226 * Compare two URLs to see if they are the same, but ignore
1227 * slight but hopefully insignificant differences such as if one
1228 * is https and the other isn't, or if one is www.something and
1229 * the other isn't - and also ignore case differences.
1231 * @param string $a first url
1232 * @param string $b second url
1233 * @return boolean True if the URLs match, otherwise False
1236 function link_compare($a,$b) {
1237 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1243 * @brief Find any non-embedded images in private items and add redir links to them
1246 * @param array &$item The field array of an item row
1248 function redir_private_images($a, &$item)
1251 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1253 foreach ($matches as $mtch) {
1254 if (strpos($mtch[1], '/redir') !== false) {
1258 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1259 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1260 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1266 function put_item_in_cache(&$item, $update = false) {
1268 if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
1269 ($item["rendered-html"] == "") || get_config("system", "ignore_cache")) {
1271 // The function "redir_private_images" changes the body.
1272 // I'm not sure if we should store it permanently, so we save the old value.
1273 $body = $item["body"];
1276 redir_private_images($a, $item);
1278 $item["rendered-html"] = prepare_text($item["body"]);
1279 $item["rendered-hash"] = hash("md5", $item["body"]);
1280 $item["body"] = $body;
1282 if ($update && ($item["id"] != 0)) {
1283 q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
1284 dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
1289 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1290 // If attach is true, also add icons for item attachments
1292 if(! function_exists('prepare_body')) {
1294 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1295 * If attach is true, also add icons for item attachments
1297 * @param array $item
1298 * @param boolean $attach
1299 * @return string item body html
1300 * @hook prepare_body_init item array before any work
1301 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1302 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1304 function prepare_body(&$item,$attach = false, $preview = false) {
1307 call_hooks('prepare_body_init', $item);
1309 $searchpath = z_root()."/search?tag=";
1312 $hashtags = array();
1313 $mentions = array();
1315 if (!get_config('system','suppress_tags')) {
1316 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1317 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1319 foreach($taglist as $tag) {
1321 if ($tag["url"] == "")
1322 $tag["url"] = $searchpath.strtolower($tag["term"]);
1324 if ($tag["type"] == TERM_HASHTAG) {
1325 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1327 } elseif ($tag["type"] == TERM_MENTION) {
1328 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1331 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1335 $item['tags'] = $tags;
1336 $item['hashtags'] = $hashtags;
1337 $item['mentions'] = $mentions;
1339 // Update the cached values if there is no "zrl=..." on the links
1340 $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
1342 // Or update it if the current viewer is the intented viewer
1343 if (($item["uid"] == local_user()) && ($item["uid"] != 0))
1346 put_item_in_cache($item, $update);
1347 $s = $item["rendered-html"];
1349 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1350 call_hooks('prepare_body', $prep_arr);
1351 $s = $prep_arr['html'];
1354 // Replace the blockquotes with quotes that are used in mails
1355 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1356 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1362 $arr = explode('[/attach],',$item['attach']);
1364 $as .= '<div class="body-attach">';
1365 foreach($arr as $r) {
1368 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1370 foreach($matches as $mtch) {
1373 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1374 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1376 $the_url = $mtch[1];
1378 if(strpos($mime, 'video') !== false) {
1381 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1382 '$baseurl' => z_root(),
1384 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1385 '$baseurl' => z_root(),
1389 $id = end(explode('/', $the_url));
1390 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1393 'title' => t('View Video'),
1400 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1402 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1403 $filesubtype = str_replace('.', '-', $filesubtype);
1407 $filesubtype = 'unkn';
1410 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1411 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1417 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1420 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1424 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1425 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1427 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1431 $as .= '<div class="clear"></div></div>';
1436 if(strpos($s,'<div class="map">') !== false && $item['coord']) {
1437 $x = generate_map(trim($item['coord']));
1439 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1445 $spoilersearch = '<blockquote class="spoiler">';
1447 // Remove line breaks before the spoiler
1448 while ((strpos($s, "\n".$spoilersearch) !== false))
1449 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1450 while ((strpos($s, "<br />".$spoilersearch) !== false))
1451 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1453 while ((strpos($s, $spoilersearch) !== false)) {
1455 $pos = strpos($s, $spoilersearch);
1456 $rnd = random_string(8);
1457 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1458 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1459 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1462 // Look for quote with author
1463 $authorsearch = '<blockquote class="author">';
1465 while ((strpos($s, $authorsearch) !== false)) {
1467 $pos = strpos($s, $authorsearch);
1468 $rnd = random_string(8);
1469 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" class="author-wrap fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1470 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1471 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1474 // replace friendica image url size with theme preference
1475 if (x($a->theme_info,'item_image_size')){
1476 $ps = $a->theme_info['item_image_size'];
1478 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|',"$1-".$ps, $s);
1481 $prep_arr = array('item' => $item, 'html' => $s);
1482 call_hooks('prepare_body_final', $prep_arr);
1484 return $prep_arr['html'];
1488 if(! function_exists('prepare_text')) {
1490 * Given a text string, convert from bbcode to html and add smilie icons.
1492 * @param string $text
1495 function prepare_text($text) {
1497 require_once('include/bbcode.php');
1499 if(stristr($text,'[nosmile]'))
1502 $s = Smilies::replace(bbcode($text));
1510 * return array with details for categories and folders for an item
1512 * @param array $item
1516 * [ // categories array
1518 * 'name': 'category name',
1519 * 'removeurl': 'url to remove this category',
1520 * 'first': 'is the first in this array? true/false',
1521 * 'last': 'is the last in this array? true/false',
1527 * 'name': 'folder name',
1528 * 'removeurl': 'url to remove this folder',
1529 * 'first': 'is the first in this array? true/false',
1530 * 'last': 'is the last in this array? true/false',
1536 function get_cats_and_terms($item) {
1539 $categories = array();
1542 $matches = false; $first = true;
1543 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1545 foreach($matches as $mtch) {
1546 $categories[] = array(
1547 'name' => xmlify(file_tag_decode($mtch[1])),
1549 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1556 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1559 if(local_user() == $item['uid']) {
1560 $matches = false; $first = true;
1561 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1563 foreach($matches as $mtch) {
1565 'name' => xmlify(file_tag_decode($mtch[1])),
1567 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1576 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1578 return array($categories, $folders);
1581 if(! function_exists('get_plink')) {
1583 * get private link for item
1584 * @param array $item
1585 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1587 function get_plink($item) {
1590 if ($a->user['nickname'] != "") {
1592 //'href' => "display/".$a->user['nickname']."/".$item['id'],
1593 'href' => "display/".$item['guid'],
1594 'orig' => "display/".$item['guid'],
1595 'title' => t('View on separate page'),
1596 'orig_title' => t('view on separate page'),
1599 if (x($item,'plink')) {
1600 $ret["href"] = $a->remove_baseurl($item['plink']);
1601 $ret["title"] = t('link to source');
1604 } elseif (x($item,'plink') && ($item['private'] != 1))
1606 'href' => $item['plink'],
1607 'orig' => $item['plink'],
1608 'title' => t('link to source'),
1613 //if (x($item,'plink') && ($item['private'] != 1))
1618 if(! function_exists('unamp')) {
1620 * replace html amp entity with amp char
1624 function unamp($s) {
1625 return str_replace('&', '&', $s);
1629 if(! function_exists('return_bytes')) {
1631 * return number of bytes in size (K, M, G)
1632 * @param string $size_str
1635 function return_bytes ($size_str) {
1636 switch (substr ($size_str, -1)) {
1637 case 'M': case 'm': return (int)$size_str * 1048576;
1638 case 'K': case 'k': return (int)$size_str * 1024;
1639 case 'G': case 'g': return (int)$size_str * 1073741824;
1640 default: return $size_str;
1647 function generate_user_guid() {
1650 $guid = get_guid(32);
1651 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1656 } while ($found == true );
1663 * @param boolean $strip_padding
1666 function base64url_encode($s, $strip_padding = false) {
1668 $s = strtr(base64_encode($s),'+/','-_');
1671 $s = str_replace('=','',$s);
1680 function base64url_decode($s) {
1683 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1688 * // Placeholder for new rev of salmon which strips base64 padding.
1689 * // PHP base64_decode handles the un-padded input without requiring this step
1690 * // Uncomment if you find you need it.
1693 * if(! strpos($s,'=')) {
1703 return base64_decode(strtr($s,'-_','+/'));
1707 if (!function_exists('str_getcsv')) {
1711 * @param string $input
1712 * @param string $delimiter
1713 * @param string $enclosure
1714 * @param string $escape
1715 * @param string $eol
1716 * @return boolean|array False on error, otherwise array[row][column]
1718 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1719 if (is_string($input) && !empty($input)) {
1721 $tmp = preg_split("/".$eol."/",$input);
1722 if (is_array($tmp) && !empty($tmp)) {
1723 while (list($line_num, $line) = each($tmp)) {
1724 if (preg_match("/".$escape.$enclosure."/",$line)) {
1725 while ($strlen = strlen($line)) {
1726 $pos_delimiter = strpos($line,$delimiter);
1727 $pos_enclosure_start = strpos($line,$enclosure);
1729 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1730 && ($pos_enclosure_start < $pos_delimiter)
1732 $enclosed_str = substr($line,1);
1733 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1734 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1735 $output[$line_num][] = $enclosed_str;
1736 $offset = $pos_enclosure_end+3;
1738 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1739 $output[$line_num][] = substr($line,0);
1740 $offset = strlen($line);
1742 $output[$line_num][] = substr($line,0,$pos_delimiter);
1744 !empty($pos_enclosure_start)
1745 && ($pos_enclosure_start < $pos_delimiter)
1747 ?$pos_enclosure_start
1751 $line = substr($line,$offset);
1754 $line = preg_split("/".$delimiter."/",$line);
1757 * Validating against pesky extra line breaks creating false rows.
1759 if (is_array($line) && !empty($line[0])) {
1760 $output[$line_num] = $line;
1775 * return div element with class 'clear'
1779 function cleardiv() {
1780 return '<div class="clear"></div>';
1784 function bb_translate_video($s) {
1787 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1789 foreach($matches as $mtch) {
1790 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1791 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1792 elseif(stristr($mtch[1],'vimeo'))
1793 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1799 function html2bb_video($s) {
1801 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1802 '[youtube]$2[/youtube]', $s);
1804 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1805 '[youtube]$2[/youtube]', $s);
1807 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1808 '[vimeo]$2[/vimeo]', $s);
1814 * apply xmlify() to all values of array $val, recursively
1818 function array_xmlify($val){
1819 if (is_bool($val)) return $val?"true":"false";
1820 if (is_array($val)) return array_map('array_xmlify', $val);
1821 return xmlify((string) $val);
1826 * transorm link href and img src from relative to absolute
1828 * @param string $text
1829 * @param string $base base url
1832 function reltoabs($text, $base) {
1836 $base = rtrim($base,'/');
1838 $base2 = $base . "/";
1841 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1842 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1843 $text = preg_replace($pattern, $replace, $text);
1845 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1846 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1847 $text = preg_replace($pattern, $replace, $text);
1850 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1851 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1852 $text = preg_replace($pattern, $replace, $text);
1854 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1855 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1856 $text = preg_replace($pattern, $replace, $text);
1864 * get translated item type
1866 * @param array $itme
1869 function item_post_type($item) {
1870 if(intval($item['event-id']))
1872 if(strlen($item['resource-id']))
1874 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1875 return t('activity');
1876 if($item['id'] != $item['parent'])
1877 return t('comment');
1881 // post categories and "save to file" use the same item.file table for storage.
1882 // We will differentiate the different uses by wrapping categories in angle brackets
1883 // and save to file categories in square brackets.
1884 // To do this we need to escape these characters if they appear in our tag.
1886 function file_tag_encode($s) {
1887 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1890 function file_tag_decode($s) {
1891 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1894 function file_tag_file_query($table,$s,$type = 'file') {
1897 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1899 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1900 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1903 // ex. given music,video return <music><video> or [music][video]
1904 function file_tag_list_to_file($list,$type = 'file') {
1907 $list_array = explode(",",$list);
1908 if($type == 'file') {
1917 foreach($list_array as $item) {
1919 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1926 // ex. given <music><video>[friends], return music,video or friends
1927 function file_tag_file_to_list($file,$type = 'file') {
1930 if($type == 'file') {
1931 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1934 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1937 foreach($matches as $mtch) {
1940 $list .= file_tag_decode($mtch[1]);
1947 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1948 // $file_old - categories previously associated with an item
1949 // $file_new - new list of categories for an item
1954 if($file_old == $file_new)
1957 $saved = get_pconfig($uid,'system','filetags');
1958 if(strlen($saved)) {
1959 if($type == 'file') {
1962 $termtype = TERM_FILE;
1967 $termtype = TERM_CATEGORY;
1970 $filetags_updated = $saved;
1972 // check for new tags to be added as filetags in pconfig
1973 $new_tags = array();
1974 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1976 foreach($check_new_tags as $tag) {
1977 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1981 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1983 // check for deleted tags to be removed from filetags in pconfig
1984 $deleted_tags = array();
1985 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1987 foreach($check_deleted_tags as $tag) {
1988 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1989 $deleted_tags[] = $tag;
1992 foreach($deleted_tags as $key => $tag) {
1993 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1995 intval(TERM_OBJ_POST),
1999 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2003 if (dbm::is_result($r)) {
2004 unset($deleted_tags[$key]);
2007 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2011 if($saved != $filetags_updated) {
2012 set_pconfig($uid,'system','filetags', $filetags_updated);
2017 if(strlen($file_new)) {
2018 set_pconfig($uid,'system','filetags', $file_new);
2023 function file_tag_save_file($uid,$item,$file) {
2024 require_once("include/files.php");
2029 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2033 if (dbm::is_result($r)) {
2034 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2035 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2036 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2041 create_files_from_item($item);
2043 $saved = get_pconfig($uid,'system','filetags');
2044 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2045 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2046 info( t('Item filed') );
2051 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2052 require_once("include/files.php");
2059 $pattern = '<' . file_tag_encode($file) . '>' ;
2060 $termtype = TERM_CATEGORY;
2062 $pattern = '[' . file_tag_encode($file) . ']' ;
2063 $termtype = TERM_FILE;
2067 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2071 if (! dbm::is_result($r)) {
2075 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2076 dbesc(str_replace($pattern,'',$r[0]['file'])),
2081 create_files_from_item($item);
2083 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2085 intval(TERM_OBJ_POST),
2089 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2092 if (! dbm::is_result($r)) {
2093 $saved = get_pconfig($uid,'system','filetags');
2094 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2100 function normalise_openid($s) {
2101 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2105 function undo_post_tagging($s) {
2107 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2109 foreach($matches as $mtch) {
2110 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2116 function protect_sprintf($s) {
2117 return(str_replace('%','%%',$s));
2121 function is_a_date_arg($s) {
2125 if($i <= $y+1 && strpos($s,'-') == 4) {
2126 $m = intval(substr($s,5));
2127 if($m > 0 && $m <= 12)
2135 * remove intentation from a text
2137 function deindent($text, $chr = "[\t ]", $count = NULL) {
2138 $lines = explode("\n", $text);
2139 if (is_null($count)) {
2142 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2145 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2146 $count = strlen($m[0]);
2148 for ($k=0; $k < count($lines); $k++) {
2149 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2152 return implode("\n", $lines);
2155 function formatBytes($bytes, $precision = 2) {
2156 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2158 $bytes = max($bytes, 0);
2159 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2160 $pow = min($pow, count($units) - 1);
2162 $bytes /= pow(1024, $pow);
2164 return round($bytes, $precision) . ' ' . $units[$pow];
2168 * @brief translate and format the networkname of a contact
2170 * @param string $network
2171 * Networkname of the contact (e.g. dfrn, rss and so on)
2176 function format_network_name($network, $url = 0) {
2177 if ($network != "") {
2178 require_once('include/contact_selectors.php');
2180 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2182 $network_name = network_to_name($network);
2184 return $network_name;
2190 * @brief Syntax based code highlighting for popular languages.
2191 * @param string $s Code block
2192 * @param string $lang Programming language
2193 * @return string Formated html
2195 function text_highlight($s, $lang) {
2196 if ($lang === 'js') {
2197 $lang = 'javascript';
2200 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2202 // Autoload the library to make constants available
2203 class_exists('Text_Highlighter_Renderer_Html');
2206 'numbers' => HL_NUMBERS_LI,
2211 $s = trim(html_entity_decode($s, ENT_COMPAT));
2212 $s = str_replace(' ', "\t", $s);
2214 // The highlighter library insists on an opening php tag for php code blocks. If
2215 // it isn't present, nothing is highlighted. So we're going to see if it's present.
2216 // If not, we'll add it, and then quietly remove it after we get the processed output back.
2218 if ($lang === 'php') {
2219 if (strpos($s, '<?php') !== 0) {
2220 $s = '<?php' . "\n" . $s;
2225 $renderer = new Text_Highlighter_Renderer_Html($options);
2226 $hl = Text_Highlighter::factory($lang);
2227 $hl->setRenderer($renderer);
2228 $o = $hl->highlight($s);
2229 $o = str_replace("\n", '', $o);
2233 $b = substr($o, 0, strpos($o, '<li>'));
2234 $e = substr($o, strpos($o, '</li>'));
2238 return '<code>' . $o . '</code>';