3 require_once("include/template_processor.php");
4 require_once("include/friendica_smarty.php");
5 require_once("include/Smilies.php");
6 require_once("include/map.php");
7 require_once("mod/proxy.php");
9 if(! function_exists('replace_macros')) {
11 * This is our template processor
13 * @param string|FriendicaSmarty $s the string requiring macro substitution,
14 * or an instance of FriendicaSmarty
15 * @param array $r key value pairs (search => replace)
16 * @return string substituted string
18 function replace_macros($s,$r) {
20 $stamp1 = microtime(true);
24 // pass $baseurl to all templates
25 $r['$baseurl'] = App::get_baseurl();
28 $t = $a->template_engine();
30 $output = $t->replace_macros($s,$r);
31 } catch (Exception $e) {
32 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
35 $a->save_timestamp($stamp1, "rendering");
41 // random string, there are 86 characters max in text mode, 128 for hex
44 define('RANDOM_STRING_HEX', 0x00 );
45 define('RANDOM_STRING_TEXT', 0x01 );
47 if(! function_exists('random_string')) {
48 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
49 // generate a bit of entropy and run it through the whirlpool
50 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
51 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
52 return(substr($s,0,$size));
55 if(! function_exists('notags')) {
57 * This is our primary input filter.
59 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
60 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
61 * after cleansing, and angle chars with the high bit set could get through as markup.
63 * This is now disabled because it was interfering with some legitimate unicode sequences
64 * and hopefully there aren't a lot of those browsers left.
66 * Use this on any text input where angle chars are not valid or permitted
67 * They will be replaced with safer brackets. This may be filtered further
68 * if these are not allowed either.
70 * @param string $string Input string
71 * @return string Filtered string
73 function notags($string) {
75 return(str_replace(array("<",">"), array('[',']'), $string));
77 // High-bit filter no longer used
78 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
83 if(! function_exists('escape_tags')) {
85 * use this on "body" or "content" input where angle chars shouldn't be removed,
86 * and allow them to be safely displayed.
87 * @param string $string
90 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) {
111 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
112 if(mt_rand(0,5) == 4)
130 's','sc','sh','sm','sp','st',
138 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
139 'nd','ng','nk','nt','rn','rp','rt');
141 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
142 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
144 $start = mt_rand(0,2);
152 for ($x = 0; $x < $len; $x ++) {
153 $r = mt_rand(0,count($table) - 1);
156 if($table == $vowels)
157 $table = array_merge($cons,$midcons);
163 $word = substr($word,0,$len);
165 foreach($noend as $noe) {
166 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
167 $word = substr($word,0,-1);
171 if(substr($word,-1) == 'q')
172 $word = substr($word,0,-1);
177 // escape text ($str) for XML transport
178 // returns escaped text.
180 if(! function_exists('xmlify')) {
182 * escape text ($str) for XML transport
184 * @return string Escaped text.
186 function xmlify($str) {
189 $len = mb_strlen($str);
190 for($x = 0; $x < $len; $x ++) {
191 $char = mb_substr($str,$x,1);
221 $buffer = mb_ereg_replace("&", "&", $str);
222 $buffer = mb_ereg_replace("'", "'", $buffer);
223 $buffer = mb_ereg_replace('"', """, $buffer);
224 $buffer = mb_ereg_replace("<", "<", $buffer);
225 $buffer = mb_ereg_replace(">", ">", $buffer);
227 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
228 $buffer = trim($buffer);
233 if(! function_exists('unxmlify')) {
236 * @param string $s xml escaped text
237 * @return string unescaped text
239 function unxmlify($s) {
240 // $ret = str_replace('&','&', $s);
241 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
242 /*$ret = mb_ereg_replace('&', '&', $s);
243 $ret = mb_ereg_replace(''', "'", $ret);
244 $ret = mb_ereg_replace('"', '"', $ret);
245 $ret = mb_ereg_replace('<', "<", $ret);
246 $ret = mb_ereg_replace('>', ">", $ret);
248 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
252 if(! function_exists('hex2bin')) {
254 * convenience wrapper, reverse the operation "bin2hex"
258 function hex2bin($s) {
259 if(! (is_string($s) && strlen($s)))
262 if(! ctype_xdigit($s)) {
266 return(pack("H*",$s));
271 * @brief Paginator function. Pushes relevant links in a pager array structure.
273 * Links are generated depending on the current page and the total number of items.
274 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
275 * Current page link is given the "active" CSS class
277 * @param App $a App instance
278 * @param int $count [optional] item count (used with minimal pager)
279 * @return Array data for pagination template
281 function paginate_data(App $a, $count = null) {
282 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
284 $stripped = str_replace('q=', '', $stripped);
285 $stripped = trim($stripped, '/');
286 $pagenum = $a->pager['page'];
288 if (($a->page_offset != '') AND !preg_match('/[?&].offset=/', $stripped)) {
289 $stripped .= '&offset=' . urlencode($a->page_offset);
295 function _l(&$d, $name, $url, $text, $class = '') {
296 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
297 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
300 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
303 if (!is_null($count)) {
304 // minimal pager (newer / older)
305 $data['class'] = 'pager';
306 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
307 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
309 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
310 $data['class'] = 'pagination';
311 if ($a->pager['total'] > $a->pager['itemspage']) {
312 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
313 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
315 $numpages = $a->pager['total'] / $a->pager['itemspage'];
318 $numstop = $numpages;
320 // Limit the number of displayed page number buttons.
322 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
323 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
328 for ($i = $numstart; $i <= $numstop; $i++) {
329 if ($i == $a->pager['page']) {
330 _l($pages, $i, '#', $i, 'current active');
332 _l($pages, $i, $url . '&page='. $i, $i, 'n');
336 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
337 if ($i == $a->pager['page']) {
338 _l($pages, $i, '#', $i, 'current active');
340 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
344 $data['pages'] = $pages;
346 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
347 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
348 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
355 if(! function_exists('paginate')) {
357 * Automatic pagination.
359 * To use, get the count of total items.
360 * Then call $a->set_pager_total($number_items);
361 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
362 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
363 * (assuming there are enough items to paginate).
364 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
365 * will limit the results to the correct items for the current page.
366 * The actual page handling is then accomplished at the application layer.
368 * @param App $a App instance
369 * @return string html for pagination #FIXME remove html
371 function paginate(App $a) {
373 $data = paginate_data($a);
374 $tpl = get_markup_template("paginate.tpl");
375 return replace_macros($tpl, array("pager" => $data));
379 if(! function_exists('alt_pager')) {
382 * @param App $a App instance
384 * @return string html for pagination #FIXME remove html
386 function alt_pager(App $a, $i) {
388 $data = paginate_data($a, $i);
389 $tpl = get_markup_template("paginate.tpl");
390 return replace_macros($tpl, array('pager' => $data));
394 if(! function_exists('scroll_loader')) {
396 * Loader for infinite scrolling
397 * @return string html for loader
399 function scroll_loader() {
400 $tpl = get_markup_template("scroll_loader.tpl");
401 return replace_macros($tpl, array(
402 'wait' => t('Loading more entries...'),
403 'end' => t('The end')
407 if(! function_exists('expand_acl')) {
409 * Turn user/group ACLs stored as angle bracketed text into arrays
414 function expand_acl($s) {
415 // turn string array of angle-bracketed elements into numeric array
416 // e.g. "<1><2><3>" => array(1,2,3);
420 $t = str_replace('<','',$s);
421 $a = explode('>',$t);
424 $ret[] = intval($aa);
430 if(! function_exists('sanitise_acl')) {
432 * Wrap ACL elements in angle brackets for storage
433 * @param string $item
435 function sanitise_acl(&$item) {
437 $item = '<' . intval(notags(trim($item))) . '>';
443 if(! function_exists('perms2str')) {
445 * Convert an ACL array to a storable string
447 * Normally ACL permissions will be an array.
448 * We'll also allow a comma-separated string.
450 * @param string|array $p
453 function perms2str($p) {
458 $tmp = explode(',',$p);
461 array_walk($tmp,'sanitise_acl');
462 $ret = implode('',$tmp);
468 if(! function_exists('item_new_uri')) {
470 * generate a guaranteed unique (for this domain) item ID for ATOM
471 * safe from birthday paradox
473 * @param string $hostname
477 function item_new_uri($hostname,$uid, $guid = "") {
483 $hash = get_guid(32);
489 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
491 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
493 if (dbm::is_result($r))
495 } while($dups == true);
499 // Generate a guaranteed unique photo ID.
500 // safe from birthday paradox
502 if(! function_exists('photo_new_resource')) {
504 * Generate a guaranteed unique photo ID.
505 * safe from birthday paradox
509 function photo_new_resource() {
513 $resource = hash('md5',uniqid(mt_rand(),true));
514 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
517 if (dbm::is_result($r))
519 } while($found == true);
524 if(! function_exists('load_view_file')) {
527 * wrapper to load a view template, checking for alternate
528 * languages before falling back to the default
530 * @global string $lang
532 * @param string $s view name
535 function load_view_file($s) {
541 if(file_exists("$d/$lang/$b")) {
542 $stamp1 = microtime(true);
543 $content = file_get_contents("$d/$lang/$b");
544 $a->save_timestamp($stamp1, "file");
548 $theme = current_theme();
550 if(file_exists("$d/theme/$theme/$b")) {
551 $stamp1 = microtime(true);
552 $content = file_get_contents("$d/theme/$theme/$b");
553 $a->save_timestamp($stamp1, "file");
557 $stamp1 = microtime(true);
558 $content = file_get_contents($s);
559 $a->save_timestamp($stamp1, "file");
563 if(! function_exists('get_intltext_template')) {
565 * load a view template, checking for alternate
566 * languages before falling back to the default
568 * @global string $lang
569 * @param string $s view path
572 function get_intltext_template($s) {
577 if($a->theme['template_engine'] === 'smarty3')
578 $engine = "/smarty3";
583 if(file_exists("view/lang/$lang$engine/$s")) {
584 $stamp1 = microtime(true);
585 $content = file_get_contents("view/lang/$lang$engine/$s");
586 $a->save_timestamp($stamp1, "file");
588 } elseif(file_exists("view/lang/en$engine/$s")) {
589 $stamp1 = microtime(true);
590 $content = file_get_contents("view/lang/en$engine/$s");
591 $a->save_timestamp($stamp1, "file");
594 $stamp1 = microtime(true);
595 $content = file_get_contents("view$engine/$s");
596 $a->save_timestamp($stamp1, "file");
601 if(! function_exists('get_markup_template')) {
606 * @param string $root
609 function get_markup_template($s, $root = '') {
610 $stamp1 = microtime(true);
613 $t = $a->template_engine();
615 $template = $t->get_template_file($s, $root);
616 } catch (Exception $e) {
617 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
620 $a->save_timestamp($stamp1, "file");
625 if(! function_exists("get_template_file")) {
629 * @param string $filename
630 * @param string $root
633 function get_template_file($a, $filename, $root = '') {
634 $theme = current_theme();
636 // Make sure $root ends with a slash /
637 if($root !== '' && $root[strlen($root)-1] !== '/')
640 if(file_exists("{$root}view/theme/$theme/$filename"))
641 $template_file = "{$root}view/theme/$theme/$filename";
642 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
643 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
644 elseif (file_exists("{$root}/$filename"))
645 $template_file = "{$root}/$filename";
647 $template_file = "{$root}view/$filename";
649 return $template_file;
658 if(! function_exists('attribute_contains')) {
660 * for html,xml parsing - let's say you've got
661 * an attribute foobar="class1 class2 class3"
662 * and you want to find out if it contains 'class3'.
663 * you can't use a normal sub string search because you
664 * might match 'notclass3' and a regex to do the job is
665 * possible but a bit complicated.
666 * pass the attribute string as $attr and the attribute you
667 * are looking for as $s - returns true if found, otherwise false
669 * @param string $attr attribute value
670 * @param string $s string to search
671 * @return boolean True if found, False otherwise
673 function attribute_contains($attr,$s) {
674 $a = explode(' ', $attr);
675 if(count($a) && in_array($s,$a))
680 if (! function_exists('logger')) {
681 /* setup int->string log level map */
682 $LOGGER_LEVELS = array();
685 * @brief Logs the given message at the given log level
688 * LOGGER_NORMAL (default)
696 * @global array $LOGGER_LEVELS
700 function logger($msg, $level = 0) {
703 global $LOGGER_LEVELS;
705 // turn off logger in install mode
707 $a->module == 'install'
708 || ! ($db && $db->connected)
713 $debugging = get_config('system','debugging');
714 $logfile = get_config('system','logfile');
715 $loglevel = intval(get_config('system','loglevel'));
720 || $level > $loglevel
725 if (count($LOGGER_LEVELS) == 0) {
726 foreach (get_defined_constants() as $k => $v) {
727 if (substr($k, 0, 7) == "LOGGER_") {
728 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
733 $process_id = session_id();
735 if ($process_id == '') {
736 $process_id = get_app()->process_id;
739 $callers = debug_backtrace();
740 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
743 $LOGGER_LEVELS[$level],
744 basename($callers[0]['file']),
746 $callers[1]['function'],
750 $stamp1 = microtime(true);
751 @file_put_contents($logfile, $logline, FILE_APPEND);
752 $a->save_timestamp($stamp1, "file");
756 * @brief An alternative logger for development.
757 * Works largely as logger() but allows developers
758 * to isolate particular elements they are targetting
759 * personally without background noise
762 * LOGGER_NORMAL (default)
770 * @global array $LOGGER_LEVELS
775 function dlogger($msg, $level = 0) {
779 // turn off logger in install mode
781 $a->module == 'install'
782 || ! ($db && $db->connected)
787 $logfile = get_config('system','dlogfile');
793 if (count($LOGGER_LEVELS) == 0) {
794 foreach (get_defined_constants() as $k => $v) {
795 if (substr($k, 0, 7) == "LOGGER_") {
796 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
801 $process_id = session_id();
803 if ($process_id == '') {
804 $process_id = get_app()->process_id;
807 $callers = debug_backtrace();
808 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
811 basename($callers[0]['file']),
813 $callers[1]['function'],
817 $stamp1 = microtime(true);
818 @file_put_contents($logfile, $logline, FILE_APPEND);
819 $a->save_timestamp($stamp1, "file");
822 if(! function_exists('activity_match')) {
824 * Compare activity uri. Knows about activity namespace.
826 * @param string $haystack
827 * @param string $needle
830 function activity_match($haystack,$needle) {
831 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
838 * @brief Pull out all #hashtags and @person tags from $string.
840 * We also get @person@domain.com - which would make
841 * the regex quite complicated as tags can also
842 * end a sentence. So we'll run through our results
843 * and strip the period from any tags which end with one.
844 * Returns array of tags found, or empty array.
846 * @param string $string Post content
847 * @return array List of tag and person names
849 function get_tags($string) {
852 // Convert hashtag links to hashtags
853 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
855 // ignore anything in a code block
856 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
858 // Force line feeds at bbtags
859 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
861 // ignore anything in a bbtag
862 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
864 // Match full names against @tags including the space between first and last
865 // We will look these up afterward to see if they are full names or not recognisable.
867 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
868 foreach ($matches[1] as $match) {
869 if (strstr($match, ']')) {
870 // we might be inside a bbcode color tag - leave it alone
873 if (substr($match, -1, 1) === '.') {
874 $ret[] = substr($match, 0, -1);
881 // Otherwise pull out single word tags. These can be @nickname, @first_last
884 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
885 foreach($matches[1] as $match) {
886 if (strstr($match, ']')) {
887 // we might be inside a bbcode color tag - leave it alone
890 if (substr($match, -1, 1) === '.') {
891 $match = substr($match,0,-1);
893 // ignore strictly numeric tags like #1
894 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
897 // try not to catch url fragments
898 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
910 if(! function_exists('qp')) {
912 * quick and dirty quoted_printable encoding
918 return str_replace ("%","=",rawurlencode($s));
921 if(! function_exists('contact_block')) {
923 * Get html for contact block.
925 * @template contact_block.tpl
926 * @hook contact_block_end (contacts=>array, output=>string)
929 function contact_block() {
933 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
939 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
941 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
942 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
943 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
944 AND `network` IN ('%s', '%s', '%s')",
945 intval($a->profile['uid']),
947 dbesc(NETWORK_OSTATUS),
948 dbesc(NETWORK_DIASPORA)
950 if (dbm::is_result($r)) {
951 $total = intval($r[0]['total']);
954 $contacts = t('No contacts');
958 // Splitting the query in two parts makes it much faster
959 $r = q("SELECT `id` FROM `contact`
960 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
961 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
962 AND `network` IN ('%s', '%s', '%s')
963 ORDER BY RAND() LIMIT %d",
964 intval($a->profile['uid']),
966 dbesc(NETWORK_OSTATUS),
967 dbesc(NETWORK_DIASPORA),
970 if (dbm::is_result($r)) {
972 foreach ($r AS $contact) {
973 $contacts[] = $contact["id"];
975 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
976 dbesc(implode(",", $contacts)));
978 if (dbm::is_result($r)) {
979 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
981 foreach ($r as $rr) {
982 $micropro[] = micropro($rr,true,'mpfriend');
988 $tpl = get_markup_template('contact_block.tpl');
989 $o = replace_macros($tpl, array(
990 '$contacts' => $contacts,
991 '$nickname' => $a->profile['nickname'],
992 '$viewcontacts' => t('View Contacts'),
993 '$micropro' => $micropro,
996 $arr = array('contacts' => $r, 'output' => $o);
998 call_hooks('contact_block_end', $arr);
1004 * @brief Format contacts as picture links or as texxt links
1006 * @param array $contact Array with contacts which contains an array with
1007 * int 'id' => The ID of the contact
1008 * int 'uid' => The user ID of the user who owns this data
1009 * string 'name' => The name of the contact
1010 * string 'url' => The url to the profile page of the contact
1011 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
1012 * string 'network' => The network to which the contact belongs to
1013 * string 'thumb' => The contact picture
1014 * string 'click' => js code which is performed when clicking on the contact
1015 * @param boolean $redirect If true try to use the redir url if it's possible
1016 * @param string $class CSS class for the
1017 * @param boolean $textmode If true display the contacts as text links
1018 * if false display the contacts as picture links
1020 * @return string Formatted html
1022 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
1024 // Use the contact URL if no address is available
1025 if ($contact["addr"] == "")
1026 $contact["addr"] = $contact["url"];
1028 $url = $contact['url'];
1034 $redirect_url = 'redir/' . $contact['id'];
1035 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1037 $url = $redirect_url;
1038 $sparkle = ' sparkle';
1044 // If there is some js available we don't need the url
1045 if(x($contact,'click'))
1048 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1049 '$click' => (($contact['click']) ? $contact['click'] : ''),
1052 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1053 '$name' => $contact['name'],
1054 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1055 '$parkle' => $sparkle,
1063 if(! function_exists('search')) {
1067 * @param string $s search query
1068 * @param string $id html id
1069 * @param string $url search url
1070 * @param boolean $savedsearch show save search button
1072 function search($s,$id='search-box',$url='search',$save = false, $aside = true) {
1076 '$s' => htmlspecialchars($s),
1078 '$action_url' => $url,
1079 '$search_label' => t('Search'),
1080 '$save_label' => t('Save'),
1081 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1082 '$search_hint' => t('@name, !forum, #tags, content'),
1086 $values['$searchoption'] = array(
1091 if (get_config('system','poco_local_search'))
1092 $values['$searchoption'][] = t("Forums");
1095 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1098 if(! function_exists('valid_email')) {
1100 * Check if $x is a valid email string
1105 function valid_email($x){
1107 // Removed because Fabio told me so.
1108 //if(get_config('system','disable_email_validation'))
1111 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
1117 if(! function_exists('linkify')) {
1119 * Replace naked text hyperlink with HTML formatted hyperlink
1123 function linkify($s) {
1124 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1125 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1133 * @return array index is present tense verb
1134 value is array containing past tense verb, translation of present, translation of past
1135 * @hook poke_verbs pokes array
1137 function get_poke_verbs() {
1139 // index is present tense verb
1140 // value is array containing past tense verb, translation of present, translation of past
1143 'poke' => array( 'poked', t('poke'), t('poked')),
1144 'ping' => array( 'pinged', t('ping'), t('pinged')),
1145 'prod' => array( 'prodded', t('prod'), t('prodded')),
1146 'slap' => array( 'slapped', t('slap'), t('slapped')),
1147 'finger' => array( 'fingered', t('finger'), t('fingered')),
1148 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1150 call_hooks('poke_verbs', $arr);
1156 * @return array index is mood, value is translated mood
1157 * @hook mood_verbs moods array
1159 function get_mood_verbs() {
1162 'happy' => t('happy'),
1164 'mellow' => t('mellow'),
1165 'tired' => t('tired'),
1166 'perky' => t('perky'),
1167 'angry' => t('angry'),
1168 'stupefied' => t('stupified'),
1169 'puzzled' => t('puzzled'),
1170 'interested' => t('interested'),
1171 'bitter' => t('bitter'),
1172 'cheerful' => t('cheerful'),
1173 'alive' => t('alive'),
1174 'annoyed' => t('annoyed'),
1175 'anxious' => t('anxious'),
1176 'cranky' => t('cranky'),
1177 'disturbed' => t('disturbed'),
1178 'frustrated' => t('frustrated'),
1179 'motivated' => t('motivated'),
1180 'relaxed' => t('relaxed'),
1181 'surprised' => t('surprised'),
1184 call_hooks('mood_verbs', $arr);
1188 if(! function_exists('day_translate')) {
1190 * Translate days and months names
1195 function day_translate($s) {
1196 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1197 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1200 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1201 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')),
1208 if(! function_exists('normalise_link')) {
1212 * @param string $url
1215 function normalise_link($url) {
1216 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1217 return(rtrim($ret,'/'));
1222 if(! function_exists('link_compare')) {
1224 * Compare two URLs to see if they are the same, but ignore
1225 * slight but hopefully insignificant differences such as if one
1226 * is https and the other isn't, or if one is www.something and
1227 * the other isn't - and also ignore case differences.
1229 * @param string $a first url
1230 * @param string $b second url
1231 * @return boolean True if the URLs match, otherwise False
1234 function link_compare($a,$b) {
1235 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1241 * @brief Find any non-embedded images in private items and add redir links to them
1244 * @param array &$item The field array of an item row
1246 function redir_private_images($a, &$item)
1249 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1251 foreach ($matches as $mtch) {
1252 if (strpos($mtch[1], '/redir') !== false) {
1256 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1257 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1258 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1264 function put_item_in_cache(&$item, $update = false) {
1266 if (($item["rendered-hash"] != hash("md5", $item["body"])) OR ($item["rendered-hash"] == "") OR
1267 ($item["rendered-html"] == "") OR get_config("system", "ignore_cache")) {
1269 // The function "redir_private_images" changes the body.
1270 // I'm not sure if we should store it permanently, so we save the old value.
1271 $body = $item["body"];
1274 redir_private_images($a, $item);
1276 $item["rendered-html"] = prepare_text($item["body"]);
1277 $item["rendered-hash"] = hash("md5", $item["body"]);
1278 $item["body"] = $body;
1280 if ($update AND ($item["id"] != 0)) {
1281 q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
1282 dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
1287 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1288 // If attach is true, also add icons for item attachments
1290 if(! function_exists('prepare_body')) {
1292 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1293 * If attach is true, also add icons for item attachments
1295 * @param array $item
1296 * @param boolean $attach
1297 * @return string item body html
1298 * @hook prepare_body_init item array before any work
1299 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1300 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1302 function prepare_body(&$item,$attach = false, $preview = false) {
1305 call_hooks('prepare_body_init', $item);
1307 $searchpath = z_root()."/search?tag=";
1310 $hashtags = array();
1311 $mentions = array();
1313 if (!get_config('system','suppress_tags')) {
1314 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1315 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1317 foreach($taglist as $tag) {
1319 if ($tag["url"] == "")
1320 $tag["url"] = $searchpath.strtolower($tag["term"]);
1322 if ($tag["type"] == TERM_HASHTAG) {
1323 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1325 } elseif ($tag["type"] == TERM_MENTION) {
1326 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1329 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1333 $item['tags'] = $tags;
1334 $item['hashtags'] = $hashtags;
1335 $item['mentions'] = $mentions;
1337 // Update the cached values if there is no "zrl=..." on the links
1338 $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
1340 // Or update it if the current viewer is the intented viewer
1341 if (($item["uid"] == local_user()) AND ($item["uid"] != 0))
1344 put_item_in_cache($item, $update);
1345 $s = $item["rendered-html"];
1347 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1348 call_hooks('prepare_body', $prep_arr);
1349 $s = $prep_arr['html'];
1352 // Replace the blockquotes with quotes that are used in mails
1353 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1354 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1360 $arr = explode('[/attach],',$item['attach']);
1362 $as .= '<div class="body-attach">';
1363 foreach($arr as $r) {
1366 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1368 foreach($matches as $mtch) {
1371 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1372 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1374 $the_url = $mtch[1];
1376 if(strpos($mime, 'video') !== false) {
1379 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1380 '$baseurl' => z_root(),
1382 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1383 '$baseurl' => z_root(),
1387 $id = end(explode('/', $the_url));
1388 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1391 'title' => t('View Video'),
1398 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1400 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1401 $filesubtype = str_replace('.', '-', $filesubtype);
1405 $filesubtype = 'unkn';
1408 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1409 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1415 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1418 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1422 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1423 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1425 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1429 $as .= '<div class="clear"></div></div>';
1434 if(strpos($s,'<div class="map">') !== false && $item['coord']) {
1435 $x = generate_map(trim($item['coord']));
1437 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1443 $spoilersearch = '<blockquote class="spoiler">';
1445 // Remove line breaks before the spoiler
1446 while ((strpos($s, "\n".$spoilersearch) !== false))
1447 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1448 while ((strpos($s, "<br />".$spoilersearch) !== false))
1449 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1451 while ((strpos($s, $spoilersearch) !== false)) {
1453 $pos = strpos($s, $spoilersearch);
1454 $rnd = random_string(8);
1455 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1456 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1457 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1460 // Look for quote with author
1461 $authorsearch = '<blockquote class="author">';
1463 while ((strpos($s, $authorsearch) !== false)) {
1465 $pos = strpos($s, $authorsearch);
1466 $rnd = random_string(8);
1467 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" class="author-wrap fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1468 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1469 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1472 // replace friendica image url size with theme preference
1473 if (x($a->theme_info,'item_image_size')){
1474 $ps = $a->theme_info['item_image_size'];
1476 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|',"$1-".$ps, $s);
1479 $prep_arr = array('item' => $item, 'html' => $s);
1480 call_hooks('prepare_body_final', $prep_arr);
1482 return $prep_arr['html'];
1486 if(! function_exists('prepare_text')) {
1488 * Given a text string, convert from bbcode to html and add smilie icons.
1490 * @param string $text
1493 function prepare_text($text) {
1495 require_once('include/bbcode.php');
1497 if(stristr($text,'[nosmile]'))
1500 $s = Smilies::replace(bbcode($text));
1508 * return array with details for categories and folders for an item
1510 * @param array $item
1514 * [ // categories array
1516 * 'name': 'category name',
1517 * 'removeurl': 'url to remove this category',
1518 * 'first': 'is the first in this array? true/false',
1519 * 'last': 'is the last in this array? true/false',
1525 * 'name': 'folder name',
1526 * 'removeurl': 'url to remove this folder',
1527 * 'first': 'is the first in this array? true/false',
1528 * 'last': 'is the last in this array? true/false',
1534 function get_cats_and_terms($item) {
1537 $categories = array();
1540 $matches = false; $first = true;
1541 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1543 foreach($matches as $mtch) {
1544 $categories[] = array(
1545 'name' => xmlify(file_tag_decode($mtch[1])),
1547 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1554 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1557 if(local_user() == $item['uid']) {
1558 $matches = false; $first = true;
1559 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1561 foreach($matches as $mtch) {
1563 'name' => xmlify(file_tag_decode($mtch[1])),
1565 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1574 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1576 return array($categories, $folders);
1579 if(! function_exists('get_plink')) {
1581 * get private link for item
1582 * @param array $item
1583 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1585 function get_plink($item) {
1588 if ($a->user['nickname'] != "") {
1590 //'href' => "display/".$a->user['nickname']."/".$item['id'],
1591 'href' => "display/".$item['guid'],
1592 'orig' => "display/".$item['guid'],
1593 'title' => t('View on separate page'),
1594 'orig_title' => t('view on separate page'),
1597 if (x($item,'plink')) {
1598 $ret["href"] = $a->remove_baseurl($item['plink']);
1599 $ret["title"] = t('link to source');
1602 } elseif (x($item,'plink') && ($item['private'] != 1))
1604 'href' => $item['plink'],
1605 'orig' => $item['plink'],
1606 'title' => t('link to source'),
1611 //if (x($item,'plink') && ($item['private'] != 1))
1616 if(! function_exists('unamp')) {
1618 * replace html amp entity with amp char
1622 function unamp($s) {
1623 return str_replace('&', '&', $s);
1627 if(! function_exists('return_bytes')) {
1629 * return number of bytes in size (K, M, G)
1630 * @param string $size_str
1633 function return_bytes ($size_str) {
1634 switch (substr ($size_str, -1)) {
1635 case 'M': case 'm': return (int)$size_str * 1048576;
1636 case 'K': case 'k': return (int)$size_str * 1024;
1637 case 'G': case 'g': return (int)$size_str * 1073741824;
1638 default: return $size_str;
1645 function generate_user_guid() {
1648 $guid = get_guid(32);
1649 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1654 } while ($found == true );
1661 * @param boolean $strip_padding
1664 function base64url_encode($s, $strip_padding = false) {
1666 $s = strtr(base64_encode($s),'+/','-_');
1669 $s = str_replace('=','',$s);
1678 function base64url_decode($s) {
1681 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1686 * // Placeholder for new rev of salmon which strips base64 padding.
1687 * // PHP base64_decode handles the un-padded input without requiring this step
1688 * // Uncomment if you find you need it.
1691 * if(! strpos($s,'=')) {
1701 return base64_decode(strtr($s,'-_','+/'));
1705 if (!function_exists('str_getcsv')) {
1709 * @param string $input
1710 * @param string $delimiter
1711 * @param string $enclosure
1712 * @param string $escape
1713 * @param string $eol
1714 * @return boolean|array False on error, otherwise array[row][column]
1716 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1717 if (is_string($input) && !empty($input)) {
1719 $tmp = preg_split("/".$eol."/",$input);
1720 if (is_array($tmp) && !empty($tmp)) {
1721 while (list($line_num, $line) = each($tmp)) {
1722 if (preg_match("/".$escape.$enclosure."/",$line)) {
1723 while ($strlen = strlen($line)) {
1724 $pos_delimiter = strpos($line,$delimiter);
1725 $pos_enclosure_start = strpos($line,$enclosure);
1727 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1728 && ($pos_enclosure_start < $pos_delimiter)
1730 $enclosed_str = substr($line,1);
1731 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1732 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1733 $output[$line_num][] = $enclosed_str;
1734 $offset = $pos_enclosure_end+3;
1736 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1737 $output[$line_num][] = substr($line,0);
1738 $offset = strlen($line);
1740 $output[$line_num][] = substr($line,0,$pos_delimiter);
1742 !empty($pos_enclosure_start)
1743 && ($pos_enclosure_start < $pos_delimiter)
1745 ?$pos_enclosure_start
1749 $line = substr($line,$offset);
1752 $line = preg_split("/".$delimiter."/",$line);
1755 * Validating against pesky extra line breaks creating false rows.
1757 if (is_array($line) && !empty($line[0])) {
1758 $output[$line_num] = $line;
1773 * return div element with class 'clear'
1777 function cleardiv() {
1778 return '<div class="clear"></div>';
1782 function bb_translate_video($s) {
1785 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1787 foreach($matches as $mtch) {
1788 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1789 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1790 elseif(stristr($mtch[1],'vimeo'))
1791 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1797 function html2bb_video($s) {
1799 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1800 '[youtube]$2[/youtube]', $s);
1802 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1803 '[youtube]$2[/youtube]', $s);
1805 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1806 '[vimeo]$2[/vimeo]', $s);
1812 * apply xmlify() to all values of array $val, recursively
1816 function array_xmlify($val){
1817 if (is_bool($val)) return $val?"true":"false";
1818 if (is_array($val)) return array_map('array_xmlify', $val);
1819 return xmlify((string) $val);
1824 * transorm link href and img src from relative to absolute
1826 * @param string $text
1827 * @param string $base base url
1830 function reltoabs($text, $base) {
1834 $base = rtrim($base,'/');
1836 $base2 = $base . "/";
1839 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1840 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1841 $text = preg_replace($pattern, $replace, $text);
1843 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1844 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1845 $text = preg_replace($pattern, $replace, $text);
1848 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1849 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1850 $text = preg_replace($pattern, $replace, $text);
1852 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1853 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1854 $text = preg_replace($pattern, $replace, $text);
1862 * get translated item type
1864 * @param array $itme
1867 function item_post_type($item) {
1868 if(intval($item['event-id']))
1870 if(strlen($item['resource-id']))
1872 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1873 return t('activity');
1874 if($item['id'] != $item['parent'])
1875 return t('comment');
1879 // post categories and "save to file" use the same item.file table for storage.
1880 // We will differentiate the different uses by wrapping categories in angle brackets
1881 // and save to file categories in square brackets.
1882 // To do this we need to escape these characters if they appear in our tag.
1884 function file_tag_encode($s) {
1885 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1888 function file_tag_decode($s) {
1889 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1892 function file_tag_file_query($table,$s,$type = 'file') {
1895 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1897 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1898 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1901 // ex. given music,video return <music><video> or [music][video]
1902 function file_tag_list_to_file($list,$type = 'file') {
1905 $list_array = explode(",",$list);
1906 if($type == 'file') {
1915 foreach($list_array as $item) {
1917 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1924 // ex. given <music><video>[friends], return music,video or friends
1925 function file_tag_file_to_list($file,$type = 'file') {
1928 if($type == 'file') {
1929 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1932 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1935 foreach($matches as $mtch) {
1938 $list .= file_tag_decode($mtch[1]);
1945 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1946 // $file_old - categories previously associated with an item
1947 // $file_new - new list of categories for an item
1952 if($file_old == $file_new)
1955 $saved = get_pconfig($uid,'system','filetags');
1956 if(strlen($saved)) {
1957 if($type == 'file') {
1960 $termtype = TERM_FILE;
1965 $termtype = TERM_CATEGORY;
1968 $filetags_updated = $saved;
1970 // check for new tags to be added as filetags in pconfig
1971 $new_tags = array();
1972 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1974 foreach($check_new_tags as $tag) {
1975 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1979 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1981 // check for deleted tags to be removed from filetags in pconfig
1982 $deleted_tags = array();
1983 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1985 foreach($check_deleted_tags as $tag) {
1986 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1987 $deleted_tags[] = $tag;
1990 foreach($deleted_tags as $key => $tag) {
1991 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1993 intval(TERM_OBJ_POST),
1997 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2001 if (dbm::is_result($r)) {
2002 unset($deleted_tags[$key]);
2005 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2009 if($saved != $filetags_updated) {
2010 set_pconfig($uid,'system','filetags', $filetags_updated);
2015 if(strlen($file_new)) {
2016 set_pconfig($uid,'system','filetags', $file_new);
2021 function file_tag_save_file($uid,$item,$file) {
2022 require_once("include/files.php");
2027 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2031 if (dbm::is_result($r)) {
2032 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2033 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2034 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2039 create_files_from_item($item);
2041 $saved = get_pconfig($uid,'system','filetags');
2042 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2043 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2044 info( t('Item filed') );
2049 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2050 require_once("include/files.php");
2057 $pattern = '<' . file_tag_encode($file) . '>' ;
2058 $termtype = TERM_CATEGORY;
2060 $pattern = '[' . file_tag_encode($file) . ']' ;
2061 $termtype = TERM_FILE;
2065 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2069 if (! dbm::is_result($r)) {
2073 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2074 dbesc(str_replace($pattern,'',$r[0]['file'])),
2079 create_files_from_item($item);
2081 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2083 intval(TERM_OBJ_POST),
2087 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2090 if (! dbm::is_result($r)) {
2091 $saved = get_pconfig($uid,'system','filetags');
2092 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2098 function normalise_openid($s) {
2099 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2103 function undo_post_tagging($s) {
2105 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2107 foreach($matches as $mtch) {
2108 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2114 function protect_sprintf($s) {
2115 return(str_replace('%','%%',$s));
2119 function is_a_date_arg($s) {
2123 if($i <= $y+1 && strpos($s,'-') == 4) {
2124 $m = intval(substr($s,5));
2125 if($m > 0 && $m <= 12)
2133 * remove intentation from a text
2135 function deindent($text, $chr = "[\t ]", $count = NULL) {
2136 $lines = explode("\n", $text);
2137 if (is_null($count)) {
2140 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2143 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2144 $count = strlen($m[0]);
2146 for ($k=0; $k < count($lines); $k++) {
2147 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2150 return implode("\n", $lines);
2153 function formatBytes($bytes, $precision = 2) {
2154 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2156 $bytes = max($bytes, 0);
2157 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2158 $pow = min($pow, count($units) - 1);
2160 $bytes /= pow(1024, $pow);
2162 return round($bytes, $precision) . ' ' . $units[$pow];
2166 * @brief translate and format the networkname of a contact
2168 * @param string $network
2169 * Networkname of the contact (e.g. dfrn, rss and so on)
2174 function format_network_name($network, $url = 0) {
2175 if ($network != "") {
2176 require_once('include/contact_selectors.php');
2178 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2180 $network_name = network_to_name($network);
2182 return $network_name;
2188 * @brief Syntax based code highlighting for popular languages.
2189 * @param string $s Code block
2190 * @param string $lang Programming language
2191 * @return string Formated html
2193 function text_highlight($s, $lang) {
2194 if ($lang === 'js') {
2195 $lang = 'javascript';
2198 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2200 // Autoload the library to make constants available
2201 class_exists('Text_Highlighter_Renderer_Html');
2204 'numbers' => HL_NUMBERS_LI,
2209 $s = trim(html_entity_decode($s, ENT_COMPAT));
2210 $s = str_replace(' ', "\t", $s);
2212 // The highlighter library insists on an opening php tag for php code blocks. If
2213 // it isn't present, nothing is highlighted. So we're going to see if it's present.
2214 // If not, we'll add it, and then quietly remove it after we get the processed output back.
2216 if ($lang === 'php') {
2217 if (strpos($s, '<?php') !== 0) {
2218 $s = '<?php' . "\n" . $s;
2223 $renderer = new Text_Highlighter_Renderer_Html($options);
2224 $hl = Text_Highlighter::factory($lang);
2225 $hl->setRenderer($renderer);
2226 $o = $hl->highlight($s);
2227 $o = str_replace("\n", '', $o);
2231 $b = substr($o, 0, strpos($o, '<li>'));
2232 $e = substr($o, strpos($o, '</li>'));
2236 return '<code>' . $o . '</code>';