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");
10 if(! function_exists('replace_macros')) {
12 * This is our template processor
14 * @param string|FriendicaSmarty $s the string requiring macro substitution,
15 * or an instance of FriendicaSmarty
16 * @param array $r key value pairs (search => replace)
17 * @return string substituted string
19 function replace_macros($s,$r) {
21 $stamp1 = microtime(true);
25 // pass $baseurl to all templates
26 $r['$baseurl'] = App::get_baseurl();
29 $t = $a->template_engine();
31 $output = $t->replace_macros($s,$r);
32 } catch (Exception $e) {
33 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
36 $a->save_timestamp($stamp1, "rendering");
42 // random string, there are 86 characters max in text mode, 128 for hex
45 define('RANDOM_STRING_HEX', 0x00 );
46 define('RANDOM_STRING_TEXT', 0x01 );
48 if(! function_exists('random_string')) {
49 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
50 // generate a bit of entropy and run it through the whirlpool
51 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
52 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
53 return(substr($s,0,$size));
56 if(! function_exists('notags')) {
58 * This is our primary input filter.
60 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
61 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
62 * after cleansing, and angle chars with the high bit set could get through as markup.
64 * This is now disabled because it was interfering with some legitimate unicode sequences
65 * and hopefully there aren't a lot of those browsers left.
67 * Use this on any text input where angle chars are not valid or permitted
68 * They will be replaced with safer brackets. This may be filtered further
69 * if these are not allowed either.
71 * @param string $string Input string
72 * @return string Filtered string
74 function notags($string) {
76 return(str_replace(array("<",">"), array('[',']'), $string));
78 // High-bit filter no longer used
79 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
84 if(! function_exists('escape_tags')) {
86 * use this on "body" or "content" input where angle chars shouldn't be removed,
87 * and allow them to be safely displayed.
88 * @param string $string
91 function escape_tags($string) {
93 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
97 // generate a string that's random, but usually pronounceable.
98 // used to generate initial passwords
100 if(! function_exists('autoname')) {
102 * generate a string that's random, but usually pronounceable.
103 * used to generate initial passwords
107 function autoname($len) {
112 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
113 if(mt_rand(0,5) == 4)
131 's','sc','sh','sm','sp','st',
139 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
140 'nd','ng','nk','nt','rn','rp','rt');
142 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
143 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
145 $start = mt_rand(0,2);
153 for ($x = 0; $x < $len; $x ++) {
154 $r = mt_rand(0,count($table) - 1);
157 if($table == $vowels)
158 $table = array_merge($cons,$midcons);
164 $word = substr($word,0,$len);
166 foreach($noend as $noe) {
167 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
168 $word = substr($word,0,-1);
172 if(substr($word,-1) == 'q')
173 $word = substr($word,0,-1);
178 // escape text ($str) for XML transport
179 // returns escaped text.
181 if(! function_exists('xmlify')) {
183 * escape text ($str) for XML transport
185 * @return string Escaped text.
187 function xmlify($str) {
190 $len = mb_strlen($str);
191 for($x = 0; $x < $len; $x ++) {
192 $char = mb_substr($str,$x,1);
222 $buffer = mb_ereg_replace("&", "&", $str);
223 $buffer = mb_ereg_replace("'", "'", $buffer);
224 $buffer = mb_ereg_replace('"', """, $buffer);
225 $buffer = mb_ereg_replace("<", "<", $buffer);
226 $buffer = mb_ereg_replace(">", ">", $buffer);
228 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
229 $buffer = trim($buffer);
234 if(! function_exists('unxmlify')) {
237 * @param string $s xml escaped text
238 * @return string unescaped text
240 function unxmlify($s) {
241 // $ret = str_replace('&','&', $s);
242 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
243 /*$ret = mb_ereg_replace('&', '&', $s);
244 $ret = mb_ereg_replace(''', "'", $ret);
245 $ret = mb_ereg_replace('"', '"', $ret);
246 $ret = mb_ereg_replace('<', "<", $ret);
247 $ret = mb_ereg_replace('>', ">", $ret);
249 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
253 if(! function_exists('hex2bin')) {
255 * convenience wrapper, reverse the operation "bin2hex"
259 function hex2bin($s) {
260 if(! (is_string($s) && strlen($s)))
263 if(! ctype_xdigit($s)) {
267 return(pack("H*",$s));
272 * @brief Paginator function. Pushes relevant links in a pager array structure.
274 * Links are generated depending on the current page and the total number of items.
275 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
276 * Current page link is given the "active" CSS class
278 * @param App $a App instance
279 * @param int $count [optional] item count (used with minimal pager)
280 * @return Array data for pagination template
282 function paginate_data(App $a, $count = null) {
283 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
285 $stripped = str_replace('q=', '', $stripped);
286 $stripped = trim($stripped, '/');
287 $pagenum = $a->pager['page'];
289 if (($a->page_offset != '') AND !preg_match('/[?&].offset=/', $stripped)) {
290 $stripped .= '&offset=' . urlencode($a->page_offset);
296 function _l(&$d, $name, $url, $text, $class = '') {
297 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
298 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
301 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
304 if (!is_null($count)) {
305 // minimal pager (newer / older)
306 $data['class'] = 'pager';
307 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
308 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
310 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
311 $data['class'] = 'pagination';
312 if ($a->pager['total'] > $a->pager['itemspage']) {
313 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
314 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
316 $numpages = $a->pager['total'] / $a->pager['itemspage'];
319 $numstop = $numpages;
321 // Limit the number of displayed page number buttons.
323 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
324 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
329 for ($i = $numstart; $i <= $numstop; $i++) {
330 if ($i == $a->pager['page']) {
331 _l($pages, $i, '#', $i, 'current active');
333 _l($pages, $i, $url . '&page='. $i, $i, 'n');
337 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
338 if ($i == $a->pager['page']) {
339 _l($pages, $i, '#', $i, 'current active');
341 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
345 $data['pages'] = $pages;
347 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
348 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
349 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
356 if(! function_exists('paginate')) {
358 * Automatic pagination.
360 * To use, get the count of total items.
361 * Then call $a->set_pager_total($number_items);
362 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
363 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
364 * (assuming there are enough items to paginate).
365 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
366 * will limit the results to the correct items for the current page.
367 * The actual page handling is then accomplished at the application layer.
369 * @param App $a App instance
370 * @return string html for pagination #FIXME remove html
372 function paginate(App $a) {
374 $data = paginate_data($a);
375 $tpl = get_markup_template("paginate.tpl");
376 return replace_macros($tpl, array("pager" => $data));
380 if(! function_exists('alt_pager')) {
383 * @param App $a App instance
385 * @return string html for pagination #FIXME remove html
387 function alt_pager(App $a, $i) {
389 $data = paginate_data($a, $i);
390 $tpl = get_markup_template("paginate.tpl");
391 return replace_macros($tpl, array('pager' => $data));
395 if(! function_exists('scroll_loader')) {
397 * Loader for infinite scrolling
398 * @return string html for loader
400 function scroll_loader() {
401 $tpl = get_markup_template("scroll_loader.tpl");
402 return replace_macros($tpl, array(
403 'wait' => t('Loading more entries...'),
404 'end' => t('The end')
408 if(! function_exists('expand_acl')) {
410 * Turn user/group ACLs stored as angle bracketed text into arrays
415 function expand_acl($s) {
416 // turn string array of angle-bracketed elements into numeric array
417 // e.g. "<1><2><3>" => array(1,2,3);
421 $t = str_replace('<','',$s);
422 $a = explode('>',$t);
425 $ret[] = intval($aa);
431 if(! function_exists('sanitise_acl')) {
433 * Wrap ACL elements in angle brackets for storage
434 * @param string $item
436 function sanitise_acl(&$item) {
438 $item = '<' . intval(notags(trim($item))) . '>';
444 if(! function_exists('perms2str')) {
446 * Convert an ACL array to a storable string
448 * Normally ACL permissions will be an array.
449 * We'll also allow a comma-separated string.
451 * @param string|array $p
454 function perms2str($p) {
459 $tmp = explode(',',$p);
462 array_walk($tmp,'sanitise_acl');
463 $ret = implode('',$tmp);
469 if(! function_exists('item_new_uri')) {
471 * generate a guaranteed unique (for this domain) item ID for ATOM
472 * safe from birthday paradox
474 * @param string $hostname
478 function item_new_uri($hostname,$uid, $guid = "") {
484 $hash = get_guid(32);
490 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
492 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
494 if (dbm::is_result($r))
496 } while($dups == true);
500 // Generate a guaranteed unique photo ID.
501 // safe from birthday paradox
503 if(! function_exists('photo_new_resource')) {
505 * Generate a guaranteed unique photo ID.
506 * safe from birthday paradox
510 function photo_new_resource() {
514 $resource = hash('md5',uniqid(mt_rand(),true));
515 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
518 if (dbm::is_result($r))
520 } while($found == true);
525 if(! function_exists('load_view_file')) {
528 * wrapper to load a view template, checking for alternate
529 * languages before falling back to the default
531 * @global string $lang
533 * @param string $s view name
536 function load_view_file($s) {
542 if(file_exists("$d/$lang/$b")) {
543 $stamp1 = microtime(true);
544 $content = file_get_contents("$d/$lang/$b");
545 $a->save_timestamp($stamp1, "file");
549 $theme = current_theme();
551 if(file_exists("$d/theme/$theme/$b")) {
552 $stamp1 = microtime(true);
553 $content = file_get_contents("$d/theme/$theme/$b");
554 $a->save_timestamp($stamp1, "file");
558 $stamp1 = microtime(true);
559 $content = file_get_contents($s);
560 $a->save_timestamp($stamp1, "file");
564 if(! function_exists('get_intltext_template')) {
566 * load a view template, checking for alternate
567 * languages before falling back to the default
569 * @global string $lang
570 * @param string $s view path
573 function get_intltext_template($s) {
578 if($a->theme['template_engine'] === 'smarty3')
579 $engine = "/smarty3";
584 if(file_exists("view/lang/$lang$engine/$s")) {
585 $stamp1 = microtime(true);
586 $content = file_get_contents("view/lang/$lang$engine/$s");
587 $a->save_timestamp($stamp1, "file");
589 } elseif(file_exists("view/lang/en$engine/$s")) {
590 $stamp1 = microtime(true);
591 $content = file_get_contents("view/lang/en$engine/$s");
592 $a->save_timestamp($stamp1, "file");
595 $stamp1 = microtime(true);
596 $content = file_get_contents("view$engine/$s");
597 $a->save_timestamp($stamp1, "file");
602 if(! function_exists('get_markup_template')) {
607 * @param string $root
610 function get_markup_template($s, $root = '') {
611 $stamp1 = microtime(true);
614 $t = $a->template_engine();
616 $template = $t->get_template_file($s, $root);
617 } catch (Exception $e) {
618 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
621 $a->save_timestamp($stamp1, "file");
626 if(! function_exists("get_template_file")) {
630 * @param string $filename
631 * @param string $root
634 function get_template_file($a, $filename, $root = '') {
635 $theme = current_theme();
637 // Make sure $root ends with a slash /
638 if($root !== '' && $root[strlen($root)-1] !== '/')
641 if(file_exists("{$root}view/theme/$theme/$filename"))
642 $template_file = "{$root}view/theme/$theme/$filename";
643 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
644 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
645 elseif (file_exists("{$root}/$filename"))
646 $template_file = "{$root}/$filename";
648 $template_file = "{$root}view/$filename";
650 return $template_file;
659 if(! function_exists('attribute_contains')) {
661 * for html,xml parsing - let's say you've got
662 * an attribute foobar="class1 class2 class3"
663 * and you want to find out if it contains 'class3'.
664 * you can't use a normal sub string search because you
665 * might match 'notclass3' and a regex to do the job is
666 * possible but a bit complicated.
667 * pass the attribute string as $attr and the attribute you
668 * are looking for as $s - returns true if found, otherwise false
670 * @param string $attr attribute value
671 * @param string $s string to search
672 * @return boolean True if found, False otherwise
674 function attribute_contains($attr,$s) {
675 $a = explode(' ', $attr);
676 if(count($a) && in_array($s,$a))
681 if (! function_exists('logger')) {
682 /* setup int->string log level map */
683 $LOGGER_LEVELS = array();
686 * @brief Logs the given message at the given log level
689 * LOGGER_NORMAL (default)
697 * @global array $LOGGER_LEVELS
701 function logger($msg, $level = 0) {
704 global $LOGGER_LEVELS;
706 // turn off logger in install mode
708 $a->module == 'install'
709 || ! ($db && $db->connected)
714 $debugging = get_config('system','debugging');
715 $logfile = get_config('system','logfile');
716 $loglevel = intval(get_config('system','loglevel'));
721 || $level > $loglevel
726 if (count($LOGGER_LEVELS) == 0) {
727 foreach (get_defined_constants() as $k => $v) {
728 if (substr($k, 0, 7) == "LOGGER_") {
729 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
734 $process_id = session_id();
736 if ($process_id == '') {
737 $process_id = get_app()->process_id;
740 $callers = debug_backtrace();
741 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
744 $LOGGER_LEVELS[$level],
745 basename($callers[0]['file']),
747 $callers[1]['function'],
751 $stamp1 = microtime(true);
752 @file_put_contents($logfile, $logline, FILE_APPEND);
753 $a->save_timestamp($stamp1, "file");
757 if(! function_exists('activity_match')) {
759 * Compare activity uri. Knows about activity namespace.
761 * @param string $haystack
762 * @param string $needle
765 function activity_match($haystack,$needle) {
766 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
773 * @brief Pull out all #hashtags and @person tags from $string.
775 * We also get @person@domain.com - which would make
776 * the regex quite complicated as tags can also
777 * end a sentence. So we'll run through our results
778 * and strip the period from any tags which end with one.
779 * Returns array of tags found, or empty array.
781 * @param string $string Post content
782 * @return array List of tag and person names
784 function get_tags($string) {
787 // Convert hashtag links to hashtags
788 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
790 // ignore anything in a code block
791 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
793 // Force line feeds at bbtags
794 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
796 // ignore anything in a bbtag
797 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
799 // Match full names against @tags including the space between first and last
800 // We will look these up afterward to see if they are full names or not recognisable.
802 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
803 foreach ($matches[1] as $match) {
804 if (strstr($match, ']')) {
805 // we might be inside a bbcode color tag - leave it alone
808 if (substr($match, -1, 1) === '.') {
809 $ret[] = substr($match, 0, -1);
816 // Otherwise pull out single word tags. These can be @nickname, @first_last
819 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
820 foreach($matches[1] as $match) {
821 if (strstr($match, ']')) {
822 // we might be inside a bbcode color tag - leave it alone
825 if (substr($match, -1, 1) === '.') {
826 $match = substr($match,0,-1);
828 // ignore strictly numeric tags like #1
829 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
832 // try not to catch url fragments
833 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
845 if(! function_exists('qp')) {
847 * quick and dirty quoted_printable encoding
853 return str_replace ("%","=",rawurlencode($s));
856 if(! function_exists('contact_block')) {
858 * Get html for contact block.
860 * @template contact_block.tpl
861 * @hook contact_block_end (contacts=>array, output=>string)
864 function contact_block() {
868 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
874 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
876 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
877 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
878 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
879 AND `network` IN ('%s', '%s', '%s')",
880 intval($a->profile['uid']),
882 dbesc(NETWORK_OSTATUS),
883 dbesc(NETWORK_DIASPORA)
885 if (dbm::is_result($r)) {
886 $total = intval($r[0]['total']);
889 $contacts = t('No contacts');
893 // Splitting the query in two parts makes it much faster
894 $r = q("SELECT `id` FROM `contact`
895 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
896 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
897 AND `network` IN ('%s', '%s', '%s')
898 ORDER BY RAND() LIMIT %d",
899 intval($a->profile['uid']),
901 dbesc(NETWORK_OSTATUS),
902 dbesc(NETWORK_DIASPORA),
905 if (dbm::is_result($r)) {
907 foreach ($r AS $contact) {
908 $contacts[] = $contact["id"];
910 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
911 dbesc(implode(",", $contacts)));
913 if (dbm::is_result($r)) {
914 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
916 foreach ($r as $rr) {
917 $micropro[] = micropro($rr,true,'mpfriend');
923 $tpl = get_markup_template('contact_block.tpl');
924 $o = replace_macros($tpl, array(
925 '$contacts' => $contacts,
926 '$nickname' => $a->profile['nickname'],
927 '$viewcontacts' => t('View Contacts'),
928 '$micropro' => $micropro,
931 $arr = array('contacts' => $r, 'output' => $o);
933 call_hooks('contact_block_end', $arr);
939 * @brief Format contacts as picture links or as texxt links
941 * @param array $contact Array with contacts which contains an array with
942 * int 'id' => The ID of the contact
943 * int 'uid' => The user ID of the user who owns this data
944 * string 'name' => The name of the contact
945 * string 'url' => The url to the profile page of the contact
946 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
947 * string 'network' => The network to which the contact belongs to
948 * string 'thumb' => The contact picture
949 * string 'click' => js code which is performed when clicking on the contact
950 * @param boolean $redirect If true try to use the redir url if it's possible
951 * @param string $class CSS class for the
952 * @param boolean $textmode If true display the contacts as text links
953 * if false display the contacts as picture links
955 * @return string Formatted html
957 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
959 // Use the contact URL if no address is available
960 if ($contact["addr"] == "")
961 $contact["addr"] = $contact["url"];
963 $url = $contact['url'];
969 $redirect_url = 'redir/' . $contact['id'];
970 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
972 $url = $redirect_url;
973 $sparkle = ' sparkle';
979 // If there is some js available we don't need the url
980 if(x($contact,'click'))
983 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
984 '$click' => (($contact['click']) ? $contact['click'] : ''),
987 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
988 '$name' => $contact['name'],
989 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
990 '$parkle' => $sparkle,
998 if(! function_exists('search')) {
1002 * @param string $s search query
1003 * @param string $id html id
1004 * @param string $url search url
1005 * @param boolean $savedsearch show save search button
1007 function search($s,$id='search-box',$url='search',$save = false, $aside = true) {
1011 '$s' => htmlspecialchars($s),
1013 '$action_url' => $url,
1014 '$search_label' => t('Search'),
1015 '$save_label' => t('Save'),
1016 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1017 '$search_hint' => t('@name, !forum, #tags, content'),
1021 $values['$searchoption'] = array(
1026 if (get_config('system','poco_local_search'))
1027 $values['$searchoption'][] = t("Forums");
1030 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1033 if(! function_exists('valid_email')) {
1035 * Check if $x is a valid email string
1040 function valid_email($x){
1042 // Removed because Fabio told me so.
1043 //if(get_config('system','disable_email_validation'))
1046 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
1052 if(! function_exists('linkify')) {
1054 * Replace naked text hyperlink with HTML formatted hyperlink
1058 function linkify($s) {
1059 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1060 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1068 * @return array index is present tense verb
1069 value is array containing past tense verb, translation of present, translation of past
1070 * @hook poke_verbs pokes array
1072 function get_poke_verbs() {
1074 // index is present tense verb
1075 // value is array containing past tense verb, translation of present, translation of past
1078 'poke' => array( 'poked', t('poke'), t('poked')),
1079 'ping' => array( 'pinged', t('ping'), t('pinged')),
1080 'prod' => array( 'prodded', t('prod'), t('prodded')),
1081 'slap' => array( 'slapped', t('slap'), t('slapped')),
1082 'finger' => array( 'fingered', t('finger'), t('fingered')),
1083 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1085 call_hooks('poke_verbs', $arr);
1091 * @return array index is mood, value is translated mood
1092 * @hook mood_verbs moods array
1094 function get_mood_verbs() {
1097 'happy' => t('happy'),
1099 'mellow' => t('mellow'),
1100 'tired' => t('tired'),
1101 'perky' => t('perky'),
1102 'angry' => t('angry'),
1103 'stupefied' => t('stupified'),
1104 'puzzled' => t('puzzled'),
1105 'interested' => t('interested'),
1106 'bitter' => t('bitter'),
1107 'cheerful' => t('cheerful'),
1108 'alive' => t('alive'),
1109 'annoyed' => t('annoyed'),
1110 'anxious' => t('anxious'),
1111 'cranky' => t('cranky'),
1112 'disturbed' => t('disturbed'),
1113 'frustrated' => t('frustrated'),
1114 'motivated' => t('motivated'),
1115 'relaxed' => t('relaxed'),
1116 'surprised' => t('surprised'),
1119 call_hooks('mood_verbs', $arr);
1123 if(! function_exists('day_translate')) {
1125 * Translate days and months names
1130 function day_translate($s) {
1131 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1132 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1135 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1136 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')),
1143 if(! function_exists('normalise_link')) {
1147 * @param string $url
1150 function normalise_link($url) {
1151 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1152 return(rtrim($ret,'/'));
1157 if(! function_exists('link_compare')) {
1159 * Compare two URLs to see if they are the same, but ignore
1160 * slight but hopefully insignificant differences such as if one
1161 * is https and the other isn't, or if one is www.something and
1162 * the other isn't - and also ignore case differences.
1164 * @param string $a first url
1165 * @param string $b second url
1166 * @return boolean True if the URLs match, otherwise False
1169 function link_compare($a,$b) {
1170 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1176 * @brief Find any non-embedded images in private items and add redir links to them
1179 * @param array &$item The field array of an item row
1181 function redir_private_images($a, &$item)
1184 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1186 foreach ($matches as $mtch) {
1187 if (strpos($mtch[1], '/redir') !== false) {
1191 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1192 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1193 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1199 function put_item_in_cache(&$item, $update = false) {
1201 if (($item["rendered-hash"] != hash("md5", $item["body"])) OR ($item["rendered-hash"] == "") OR
1202 ($item["rendered-html"] == "") OR get_config("system", "ignore_cache")) {
1204 // The function "redir_private_images" changes the body.
1205 // I'm not sure if we should store it permanently, so we save the old value.
1206 $body = $item["body"];
1209 redir_private_images($a, $item);
1211 $item["rendered-html"] = prepare_text($item["body"]);
1212 $item["rendered-hash"] = hash("md5", $item["body"]);
1213 $item["body"] = $body;
1215 if ($update AND ($item["id"] != 0)) {
1216 q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
1217 dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
1222 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1223 // If attach is true, also add icons for item attachments
1225 if(! function_exists('prepare_body')) {
1227 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1228 * If attach is true, also add icons for item attachments
1230 * @param array $item
1231 * @param boolean $attach
1232 * @return string item body html
1233 * @hook prepare_body_init item array before any work
1234 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1235 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1237 function prepare_body(&$item,$attach = false, $preview = false) {
1240 call_hooks('prepare_body_init', $item);
1242 $searchpath = z_root()."/search?tag=";
1245 $hashtags = array();
1246 $mentions = array();
1248 if (!get_config('system','suppress_tags')) {
1249 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1250 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1252 foreach($taglist as $tag) {
1254 if ($tag["url"] == "")
1255 $tag["url"] = $searchpath.strtolower($tag["term"]);
1257 if ($tag["type"] == TERM_HASHTAG) {
1258 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1260 } elseif ($tag["type"] == TERM_MENTION) {
1261 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1264 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1268 $item['tags'] = $tags;
1269 $item['hashtags'] = $hashtags;
1270 $item['mentions'] = $mentions;
1272 // Update the cached values if there is no "zrl=..." on the links
1273 $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
1275 // Or update it if the current viewer is the intented viewer
1276 if (($item["uid"] == local_user()) AND ($item["uid"] != 0))
1279 put_item_in_cache($item, $update);
1280 $s = $item["rendered-html"];
1282 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1283 call_hooks('prepare_body', $prep_arr);
1284 $s = $prep_arr['html'];
1287 // Replace the blockquotes with quotes that are used in mails
1288 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1289 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1295 $arr = explode('[/attach],',$item['attach']);
1297 $as .= '<div class="body-attach">';
1298 foreach($arr as $r) {
1301 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1303 foreach($matches as $mtch) {
1306 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1307 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1309 $the_url = $mtch[1];
1311 if(strpos($mime, 'video') !== false) {
1314 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1315 '$baseurl' => z_root(),
1317 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1318 '$baseurl' => z_root(),
1322 $id = end(explode('/', $the_url));
1323 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1326 'title' => t('View Video'),
1333 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1335 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1336 $filesubtype = str_replace('.', '-', $filesubtype);
1340 $filesubtype = 'unkn';
1343 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1344 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1350 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1353 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1357 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1358 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1360 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1364 $as .= '<div class="clear"></div></div>';
1369 if(strpos($s,'<div class="map">') !== false && $item['coord']) {
1370 $x = generate_map(trim($item['coord']));
1372 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1378 $spoilersearch = '<blockquote class="spoiler">';
1380 // Remove line breaks before the spoiler
1381 while ((strpos($s, "\n".$spoilersearch) !== false))
1382 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1383 while ((strpos($s, "<br />".$spoilersearch) !== false))
1384 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1386 while ((strpos($s, $spoilersearch) !== false)) {
1388 $pos = strpos($s, $spoilersearch);
1389 $rnd = random_string(8);
1390 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1391 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1392 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1395 // Look for quote with author
1396 $authorsearch = '<blockquote class="author">';
1398 while ((strpos($s, $authorsearch) !== false)) {
1400 $pos = strpos($s, $authorsearch);
1401 $rnd = random_string(8);
1402 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" class="author-wrap fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1403 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1404 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1407 // replace friendica image url size with theme preference
1408 if (x($a->theme_info,'item_image_size')){
1409 $ps = $a->theme_info['item_image_size'];
1411 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|',"$1-".$ps, $s);
1414 $prep_arr = array('item' => $item, 'html' => $s);
1415 call_hooks('prepare_body_final', $prep_arr);
1417 return $prep_arr['html'];
1421 if(! function_exists('prepare_text')) {
1423 * Given a text string, convert from bbcode to html and add smilie icons.
1425 * @param string $text
1428 function prepare_text($text) {
1430 require_once('include/bbcode.php');
1432 if(stristr($text,'[nosmile]'))
1435 $s = Smilies::replace(bbcode($text));
1443 * return array with details for categories and folders for an item
1445 * @param array $item
1449 * [ // categories array
1451 * 'name': 'category name',
1452 * 'removeurl': 'url to remove this category',
1453 * 'first': 'is the first in this array? true/false',
1454 * 'last': 'is the last in this array? true/false',
1460 * 'name': 'folder name',
1461 * 'removeurl': 'url to remove this folder',
1462 * 'first': 'is the first in this array? true/false',
1463 * 'last': 'is the last in this array? true/false',
1469 function get_cats_and_terms($item) {
1472 $categories = array();
1475 $matches = false; $first = true;
1476 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1478 foreach($matches as $mtch) {
1479 $categories[] = array(
1480 'name' => xmlify(file_tag_decode($mtch[1])),
1482 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1489 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1492 if(local_user() == $item['uid']) {
1493 $matches = false; $first = true;
1494 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1496 foreach($matches as $mtch) {
1498 'name' => xmlify(file_tag_decode($mtch[1])),
1500 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1509 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1511 return array($categories, $folders);
1514 if(! function_exists('get_plink')) {
1516 * get private link for item
1517 * @param array $item
1518 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1520 function get_plink($item) {
1523 if ($a->user['nickname'] != "") {
1525 //'href' => "display/".$a->user['nickname']."/".$item['id'],
1526 'href' => "display/".$item['guid'],
1527 'orig' => "display/".$item['guid'],
1528 'title' => t('View on separate page'),
1529 'orig_title' => t('view on separate page'),
1532 if (x($item,'plink')) {
1533 $ret["href"] = $a->remove_baseurl($item['plink']);
1534 $ret["title"] = t('link to source');
1537 } elseif (x($item,'plink') && ($item['private'] != 1))
1539 'href' => $item['plink'],
1540 'orig' => $item['plink'],
1541 'title' => t('link to source'),
1546 //if (x($item,'plink') && ($item['private'] != 1))
1551 if(! function_exists('unamp')) {
1553 * replace html amp entity with amp char
1557 function unamp($s) {
1558 return str_replace('&', '&', $s);
1562 if(! function_exists('return_bytes')) {
1564 * return number of bytes in size (K, M, G)
1565 * @param string $size_str
1568 function return_bytes ($size_str) {
1569 switch (substr ($size_str, -1)) {
1570 case 'M': case 'm': return (int)$size_str * 1048576;
1571 case 'K': case 'k': return (int)$size_str * 1024;
1572 case 'G': case 'g': return (int)$size_str * 1073741824;
1573 default: return $size_str;
1580 function generate_user_guid() {
1583 $guid = get_guid(32);
1584 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1589 } while ($found == true );
1596 * @param boolean $strip_padding
1599 function base64url_encode($s, $strip_padding = false) {
1601 $s = strtr(base64_encode($s),'+/','-_');
1604 $s = str_replace('=','',$s);
1613 function base64url_decode($s) {
1616 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1621 * // Placeholder for new rev of salmon which strips base64 padding.
1622 * // PHP base64_decode handles the un-padded input without requiring this step
1623 * // Uncomment if you find you need it.
1626 * if(! strpos($s,'=')) {
1636 return base64_decode(strtr($s,'-_','+/'));
1640 if (!function_exists('str_getcsv')) {
1644 * @param string $input
1645 * @param string $delimiter
1646 * @param string $enclosure
1647 * @param string $escape
1648 * @param string $eol
1649 * @return boolean|array False on error, otherwise array[row][column]
1651 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1652 if (is_string($input) && !empty($input)) {
1654 $tmp = preg_split("/".$eol."/",$input);
1655 if (is_array($tmp) && !empty($tmp)) {
1656 while (list($line_num, $line) = each($tmp)) {
1657 if (preg_match("/".$escape.$enclosure."/",$line)) {
1658 while ($strlen = strlen($line)) {
1659 $pos_delimiter = strpos($line,$delimiter);
1660 $pos_enclosure_start = strpos($line,$enclosure);
1662 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1663 && ($pos_enclosure_start < $pos_delimiter)
1665 $enclosed_str = substr($line,1);
1666 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1667 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1668 $output[$line_num][] = $enclosed_str;
1669 $offset = $pos_enclosure_end+3;
1671 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1672 $output[$line_num][] = substr($line,0);
1673 $offset = strlen($line);
1675 $output[$line_num][] = substr($line,0,$pos_delimiter);
1677 !empty($pos_enclosure_start)
1678 && ($pos_enclosure_start < $pos_delimiter)
1680 ?$pos_enclosure_start
1684 $line = substr($line,$offset);
1687 $line = preg_split("/".$delimiter."/",$line);
1690 * Validating against pesky extra line breaks creating false rows.
1692 if (is_array($line) && !empty($line[0])) {
1693 $output[$line_num] = $line;
1708 * return div element with class 'clear'
1712 function cleardiv() {
1713 return '<div class="clear"></div>';
1717 function bb_translate_video($s) {
1720 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1722 foreach($matches as $mtch) {
1723 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1724 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1725 elseif(stristr($mtch[1],'vimeo'))
1726 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1732 function html2bb_video($s) {
1734 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1735 '[youtube]$2[/youtube]', $s);
1737 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1738 '[youtube]$2[/youtube]', $s);
1740 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1741 '[vimeo]$2[/vimeo]', $s);
1747 * apply xmlify() to all values of array $val, recursively
1751 function array_xmlify($val){
1752 if (is_bool($val)) return $val?"true":"false";
1753 if (is_array($val)) return array_map('array_xmlify', $val);
1754 return xmlify((string) $val);
1759 * transorm link href and img src from relative to absolute
1761 * @param string $text
1762 * @param string $base base url
1765 function reltoabs($text, $base) {
1769 $base = rtrim($base,'/');
1771 $base2 = $base . "/";
1774 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1775 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1776 $text = preg_replace($pattern, $replace, $text);
1778 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1779 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1780 $text = preg_replace($pattern, $replace, $text);
1783 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1784 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1785 $text = preg_replace($pattern, $replace, $text);
1787 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1788 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1789 $text = preg_replace($pattern, $replace, $text);
1797 * get translated item type
1799 * @param array $itme
1802 function item_post_type($item) {
1803 if(intval($item['event-id']))
1805 if(strlen($item['resource-id']))
1807 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1808 return t('activity');
1809 if($item['id'] != $item['parent'])
1810 return t('comment');
1814 // post categories and "save to file" use the same item.file table for storage.
1815 // We will differentiate the different uses by wrapping categories in angle brackets
1816 // and save to file categories in square brackets.
1817 // To do this we need to escape these characters if they appear in our tag.
1819 function file_tag_encode($s) {
1820 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1823 function file_tag_decode($s) {
1824 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1827 function file_tag_file_query($table,$s,$type = 'file') {
1830 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1832 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1833 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1836 // ex. given music,video return <music><video> or [music][video]
1837 function file_tag_list_to_file($list,$type = 'file') {
1840 $list_array = explode(",",$list);
1841 if($type == 'file') {
1850 foreach($list_array as $item) {
1852 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1859 // ex. given <music><video>[friends], return music,video or friends
1860 function file_tag_file_to_list($file,$type = 'file') {
1863 if($type == 'file') {
1864 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1867 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1870 foreach($matches as $mtch) {
1873 $list .= file_tag_decode($mtch[1]);
1880 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1881 // $file_old - categories previously associated with an item
1882 // $file_new - new list of categories for an item
1887 if($file_old == $file_new)
1890 $saved = get_pconfig($uid,'system','filetags');
1891 if(strlen($saved)) {
1892 if($type == 'file') {
1895 $termtype = TERM_FILE;
1900 $termtype = TERM_CATEGORY;
1903 $filetags_updated = $saved;
1905 // check for new tags to be added as filetags in pconfig
1906 $new_tags = array();
1907 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1909 foreach($check_new_tags as $tag) {
1910 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1914 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1916 // check for deleted tags to be removed from filetags in pconfig
1917 $deleted_tags = array();
1918 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1920 foreach($check_deleted_tags as $tag) {
1921 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1922 $deleted_tags[] = $tag;
1925 foreach($deleted_tags as $key => $tag) {
1926 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1928 intval(TERM_OBJ_POST),
1932 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1936 if (dbm::is_result($r)) {
1937 unset($deleted_tags[$key]);
1940 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1944 if($saved != $filetags_updated) {
1945 set_pconfig($uid,'system','filetags', $filetags_updated);
1950 if(strlen($file_new)) {
1951 set_pconfig($uid,'system','filetags', $file_new);
1956 function file_tag_save_file($uid,$item,$file) {
1957 require_once("include/files.php");
1962 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1966 if (dbm::is_result($r)) {
1967 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1968 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1969 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1974 create_files_from_item($item);
1976 $saved = get_pconfig($uid,'system','filetags');
1977 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1978 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1979 info( t('Item filed') );
1984 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
1985 require_once("include/files.php");
1992 $pattern = '<' . file_tag_encode($file) . '>' ;
1993 $termtype = TERM_CATEGORY;
1995 $pattern = '[' . file_tag_encode($file) . ']' ;
1996 $termtype = TERM_FILE;
2000 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2004 if (! dbm::is_result($r)) {
2008 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2009 dbesc(str_replace($pattern,'',$r[0]['file'])),
2014 create_files_from_item($item);
2016 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2018 intval(TERM_OBJ_POST),
2022 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2025 if (! dbm::is_result($r)) {
2026 $saved = get_pconfig($uid,'system','filetags');
2027 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2033 function normalise_openid($s) {
2034 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2038 function undo_post_tagging($s) {
2040 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2042 foreach($matches as $mtch) {
2043 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2049 function protect_sprintf($s) {
2050 return(str_replace('%','%%',$s));
2054 function is_a_date_arg($s) {
2058 if($i <= $y+1 && strpos($s,'-') == 4) {
2059 $m = intval(substr($s,5));
2060 if($m > 0 && $m <= 12)
2068 * remove intentation from a text
2070 function deindent($text, $chr = "[\t ]", $count = NULL) {
2071 $lines = explode("\n", $text);
2072 if (is_null($count)) {
2075 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2078 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2079 $count = strlen($m[0]);
2081 for ($k=0; $k < count($lines); $k++) {
2082 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2085 return implode("\n", $lines);
2088 function formatBytes($bytes, $precision = 2) {
2089 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2091 $bytes = max($bytes, 0);
2092 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2093 $pow = min($pow, count($units) - 1);
2095 $bytes /= pow(1024, $pow);
2097 return round($bytes, $precision) . ' ' . $units[$pow];
2101 * @brief translate and format the networkname of a contact
2103 * @param string $network
2104 * Networkname of the contact (e.g. dfrn, rss and so on)
2109 function format_network_name($network, $url = 0) {
2110 if ($network != "") {
2111 require_once('include/contact_selectors.php');
2113 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2115 $network_name = network_to_name($network);
2117 return $network_name;
2123 * @brief Syntax based code highlighting for popular languages.
2124 * @param string $s Code block
2125 * @param string $lang Programming language
2126 * @return string Formated html
2128 function text_highlight($s,$lang) {
2130 $lang = 'javascript';
2132 if(! strpos('Text_Highlighter',get_include_path())) {
2133 set_include_path(get_include_path() . PATH_SEPARATOR . 'library/Text_Highlighter');
2136 require_once('library/Text_Highlighter/Text/Highlighter.php');
2137 require_once('library/Text_Highlighter/Text/Highlighter/Renderer/Html.php');
2139 'numbers' => HL_NUMBERS_LI,
2144 $s = trim(html_entity_decode($s,ENT_COMPAT));
2145 $s = str_replace(" ","\t",$s);
2147 // The highlighter library insists on an opening php tag for php code blocks. If
2148 // it isn't present, nothing is highlighted. So we're going to see if it's present.
2149 // If not, we'll add it, and then quietly remove it after we get the processed output back.
2151 if($lang === 'php') {
2152 if(strpos('<?php',$s) !== 0) {
2153 $s = '<?php' . "\n" . $s;
2158 $renderer = new Text_Highlighter_Renderer_HTML($options);
2159 $hl = Text_Highlighter::factory($lang);
2160 $hl->setRenderer($renderer);
2161 $o = $hl->highlight($s);
2162 $o = str_replace([" ","\n"],[" ",''],$o);
2165 $b = substr($o,0,strpos($o,'<li>'));
2166 $e = substr($o,strpos($o,'</li>'));
2170 return('<code>' . $o . '</code>');