5 require_once "include/template_processor.php";
6 require_once "include/friendica_smarty.php";
7 require_once "include/Smilies.php";
8 require_once "include/map.php";
9 require_once "mod/proxy.php";
11 if (! function_exists('replace_macros')) {
13 * This is our template processor
15 * @param string|FriendicaSmarty $s the string requiring macro substitution,
16 * or an instance of FriendicaSmarty
17 * @param array $r key value pairs (search => replace)
18 * @return string substituted string
20 function replace_macros($s, $r) {
22 $stamp1 = microtime(true);
26 // pass $baseurl to all templates
27 $r['$baseurl'] = App::get_baseurl();
29 $t = $a->template_engine();
31 $output = $t->replace_macros($s, $r);
32 } catch (Exception $e) {
33 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
37 $a->save_timestamp($stamp1, "rendering");
43 // random string, there are 86 characters max in text mode, 128 for hex
46 define('RANDOM_STRING_HEX', 0x00 );
47 define('RANDOM_STRING_TEXT', 0x01 );
49 if (! function_exists('random_string')) {
50 function random_string($size = 64, $type = RANDOM_STRING_HEX) {
51 // generate a bit of entropy and run it through the whirlpool
52 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(), (($type == RANDOM_STRING_TEXT) ? true : false));
53 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n", "", base64url_encode($s,true)) : $s);
54 return(substr($s,0,$size));
57 if (! function_exists('notags')) {
59 * This is our primary input filter.
61 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
62 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
63 * after cleansing, and angle chars with the high bit set could get through as markup.
65 * This is now disabled because it was interfering with some legitimate unicode sequences
66 * and hopefully there aren't a lot of those browsers left.
68 * Use this on any text input where angle chars are not valid or permitted
69 * They will be replaced with safer brackets. This may be filtered further
70 * if these are not allowed either.
72 * @param string $string Input string
73 * @return string Filtered string
75 function notags($string) {
76 return str_replace(array("<", ">"), array('[', ']'), $string);
78 // High-bit filter no longer used
79 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
84 if (! function_exists('escape_tags')) {
86 * use this on "body" or "content" input where angle chars shouldn't be removed,
87 * and allow them to be safely displayed.
88 * @param string $string
91 function escape_tags($string) {
92 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
96 // generate a string that's random, but usually pronounceable.
97 // used to generate initial passwords
99 if (! function_exists('autoname')) {
101 * generate a string that's random, but usually pronounceable.
102 * used to generate initial passwords
106 function autoname($len) {
112 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
113 if (mt_rand(0, 5) == 4) {
132 's','sc','sh','sm','sp','st',
140 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
141 'nd','ng','nk','nt','rn','rp','rt');
143 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
144 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
146 $start = mt_rand(0,2);
155 for ($x = 0; $x < $len; $x ++) {
156 $r = mt_rand(0,count($table) - 1);
159 if ($table == $vowels) {
160 $table = array_merge($cons,$midcons);
167 $word = substr($word,0,$len);
169 foreach ($noend as $noe) {
170 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
171 $word = substr($word, 0, -1);
175 if (substr($word, -1) == 'q') {
176 $word = substr($word, 0, -1);
182 // escape text ($str) for XML transport
183 // returns escaped text.
185 if (! function_exists('xmlify')) {
187 * escape text ($str) for XML transport
189 * @return string Escaped text.
191 function xmlify($str) {
192 /// @TODO deprecated code found?
195 $len = mb_strlen($str);
196 for ($x = 0; $x < $len; $x ++) {
197 $char = mb_substr($str,$x,1);
227 $buffer = mb_ereg_replace("&", "&", $str);
228 $buffer = mb_ereg_replace("'", "'", $buffer);
229 $buffer = mb_ereg_replace('"', """, $buffer);
230 $buffer = mb_ereg_replace("<", "<", $buffer);
231 $buffer = mb_ereg_replace(">", ">", $buffer);
233 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
234 $buffer = trim($buffer);
239 if (! function_exists('unxmlify')) {
242 * @param string $s xml escaped text
243 * @return string unescaped text
245 function unxmlify($s) {
246 /// @TODO deprecated code found?
247 // $ret = str_replace('&','&', $s);
248 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
249 /*$ret = mb_ereg_replace('&', '&', $s);
250 $ret = mb_ereg_replace(''', "'", $ret);
251 $ret = mb_ereg_replace('"', '"', $ret);
252 $ret = mb_ereg_replace('<', "<", $ret);
253 $ret = mb_ereg_replace('>', ">", $ret);
255 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
259 if (! function_exists('hex2bin')) {
261 * convenience wrapper, reverse the operation "bin2hex"
265 function hex2bin($s) {
266 if (! (is_string($s) && strlen($s))) {
270 if (! ctype_xdigit($s)) {
274 return pack("H*",$s);
279 * @brief Paginator function. Pushes relevant links in a pager array structure.
281 * Links are generated depending on the current page and the total number of items.
282 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
283 * Current page link is given the "active" CSS class
285 * @param App $a App instance
286 * @param int $count [optional] item count (used with minimal pager)
287 * @return Array data for pagination template
289 function paginate_data(App $a, $count = null) {
290 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
292 $stripped = str_replace('q=', '', $stripped);
293 $stripped = trim($stripped, '/');
294 $pagenum = $a->pager['page'];
296 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
297 $stripped .= '&offset=' . urlencode($a->page_offset);
303 function _l(&$d, $name, $url, $text, $class = '') {
304 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
305 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
308 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
311 if (!is_null($count)) {
312 // minimal pager (newer / older)
313 $data['class'] = 'pager';
314 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
315 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
317 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
318 $data['class'] = 'pagination';
319 if ($a->pager['total'] > $a->pager['itemspage']) {
320 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
321 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
323 $numpages = $a->pager['total'] / $a->pager['itemspage'];
326 $numstop = $numpages;
328 // Limit the number of displayed page number buttons.
330 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
331 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
336 for ($i = $numstart; $i <= $numstop; $i++) {
337 if ($i == $a->pager['page']) {
338 _l($pages, $i, '#', $i, 'current active');
340 _l($pages, $i, $url . '&page='. $i, $i, 'n');
344 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
345 if ($i == $a->pager['page']) {
346 _l($pages, $i, '#', $i, 'current active');
348 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
352 $data['pages'] = $pages;
354 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
355 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
356 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
363 if (! function_exists('paginate')) {
365 * Automatic pagination.
367 * To use, get the count of total items.
368 * Then call $a->set_pager_total($number_items);
369 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
370 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
371 * (assuming there are enough items to paginate).
372 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
373 * will limit the results to the correct items for the current page.
374 * The actual page handling is then accomplished at the application layer.
376 * @param App $a App instance
377 * @return string html for pagination #FIXME remove html
379 function paginate(App $a) {
381 $data = paginate_data($a);
382 $tpl = get_markup_template("paginate.tpl");
383 return replace_macros($tpl, array("pager" => $data));
387 if (! function_exists('alt_pager')) {
390 * @param App $a App instance
392 * @return string html for pagination #FIXME remove html
394 function alt_pager(App $a, $i) {
396 $data = paginate_data($a, $i);
397 $tpl = get_markup_template("paginate.tpl");
398 return replace_macros($tpl, array('pager' => $data));
402 if (! function_exists('scroll_loader')) {
404 * Loader for infinite scrolling
405 * @return string html for loader
407 function scroll_loader() {
408 $tpl = get_markup_template("scroll_loader.tpl");
409 return replace_macros($tpl, array(
410 'wait' => t('Loading more entries...'),
411 'end' => t('The end')
415 if (! function_exists('expand_acl')) {
417 * Turn user/group ACLs stored as angle bracketed text into arrays
422 function expand_acl($s) {
423 // turn string array of angle-bracketed elements into numeric array
424 // e.g. "<1><2><3>" => array(1,2,3);
428 $t = str_replace('<', '', $s);
429 $a = explode('>', $t);
430 foreach ($a as $aa) {
432 $ret[] = intval($aa);
439 if (! function_exists('sanitise_acl')) {
441 * Wrap ACL elements in angle brackets for storage
442 * @param string $item
444 function sanitise_acl(&$item) {
446 $item = '<' . intval(notags(trim($item))) . '>';
453 if (! function_exists('perms2str')) {
455 * Convert an ACL array to a storable string
457 * Normally ACL permissions will be an array.
458 * We'll also allow a comma-separated string.
460 * @param string|array $p
463 function perms2str($p) {
468 $tmp = explode(',',$p);
471 if (is_array($tmp)) {
472 array_walk($tmp, 'sanitise_acl');
473 $ret = implode('', $tmp);
479 if (! function_exists('item_new_uri')) {
481 * generate a guaranteed unique (for this domain) item ID for ATOM
482 * safe from birthday paradox
484 * @param string $hostname
488 function item_new_uri($hostname, $uid, $guid = "") {
494 $hash = get_guid(32);
500 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
502 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
504 if (dbm::is_result($r)) {
507 } while ($dups == true);
512 // Generate a guaranteed unique photo ID.
513 // safe from birthday paradox
515 if (! function_exists('photo_new_resource')) {
517 * Generate a guaranteed unique photo ID.
518 * safe from birthday paradox
522 function photo_new_resource() {
526 $resource = hash('md5',uniqid(mt_rand(),true));
527 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
531 if (dbm::is_result($r)) {
534 } while ($found == true);
540 if (! function_exists('load_view_file')) {
543 * wrapper to load a view template, checking for alternate
544 * languages before falling back to the default
546 * @global string $lang
548 * @param string $s view name
551 function load_view_file($s) {
553 if (! isset($lang)) {
558 if (file_exists("$d/$lang/$b")) {
559 $stamp1 = microtime(true);
560 $content = file_get_contents("$d/$lang/$b");
561 $a->save_timestamp($stamp1, "file");
565 $theme = current_theme();
567 if (file_exists("$d/theme/$theme/$b")) {
568 $stamp1 = microtime(true);
569 $content = file_get_contents("$d/theme/$theme/$b");
570 $a->save_timestamp($stamp1, "file");
574 $stamp1 = microtime(true);
575 $content = file_get_contents($s);
576 $a->save_timestamp($stamp1, "file");
580 if (! function_exists('get_intltext_template')) {
582 * load a view template, checking for alternate
583 * languages before falling back to the default
585 * @global string $lang
586 * @param string $s view path
589 function get_intltext_template($s) {
594 if ($a->theme['template_engine'] === 'smarty3') {
595 $engine = "/smarty3";
598 if (! isset($lang)) {
602 if (file_exists("view/lang/$lang$engine/$s")) {
603 $stamp1 = microtime(true);
604 $content = file_get_contents("view/lang/$lang$engine/$s");
605 $a->save_timestamp($stamp1, "file");
607 } elseif (file_exists("view/lang/en$engine/$s")) {
608 $stamp1 = microtime(true);
609 $content = file_get_contents("view/lang/en$engine/$s");
610 $a->save_timestamp($stamp1, "file");
613 $stamp1 = microtime(true);
614 $content = file_get_contents("view$engine/$s");
615 $a->save_timestamp($stamp1, "file");
620 if (! function_exists('get_markup_template')) {
625 * @param string $root
628 function get_markup_template($s, $root = '') {
629 $stamp1 = microtime(true);
632 $t = $a->template_engine();
634 $template = $t->get_template_file($s, $root);
635 } catch (Exception $e) {
636 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
640 $a->save_timestamp($stamp1, "file");
645 if (! function_exists("get_template_file")) {
649 * @param string $filename
650 * @param string $root
653 function get_template_file($a, $filename, $root = '') {
654 $theme = current_theme();
656 // Make sure $root ends with a slash /
657 if ($root !== '' && substr($root, -1, 1) !== '/') {
661 if (file_exists("{$root}view/theme/$theme/$filename")) {
662 $template_file = "{$root}view/theme/$theme/$filename";
663 } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
664 $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
665 } elseif (file_exists("{$root}/$filename")) {
666 $template_file = "{$root}/$filename";
668 $template_file = "{$root}view/$filename";
671 return $template_file;
675 if (! function_exists('attribute_contains')) {
677 * for html,xml parsing - let's say you've got
678 * an attribute foobar="class1 class2 class3"
679 * and you want to find out if it contains 'class3'.
680 * you can't use a normal sub string search because you
681 * might match 'notclass3' and a regex to do the job is
682 * possible but a bit complicated.
683 * pass the attribute string as $attr and the attribute you
684 * are looking for as $s - returns true if found, otherwise false
686 * @param string $attr attribute value
687 * @param string $s string to search
688 * @return boolean True if found, False otherwise
690 function attribute_contains($attr, $s) {
691 $a = explode(' ', $attr);
692 return (count($a) && in_array($s,$a));
695 if (! function_exists('logger')) {
696 /* setup int->string log level map */
697 $LOGGER_LEVELS = array();
700 * @brief Logs the given message at the given log level
703 * LOGGER_NORMAL (default)
711 * @global array $LOGGER_LEVELS
715 function logger($msg, $level = 0) {
718 global $LOGGER_LEVELS;
720 // turn off logger in install mode
722 $a->module == 'install'
723 || ! ($db && $db->connected)
728 $debugging = get_config('system','debugging');
729 $logfile = get_config('system','logfile');
730 $loglevel = intval(get_config('system','loglevel'));
735 || $level > $loglevel
740 if (count($LOGGER_LEVELS) == 0) {
741 foreach (get_defined_constants() as $k => $v) {
742 if (substr($k, 0, 7) == "LOGGER_") {
743 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
748 $process_id = session_id();
750 if ($process_id == '') {
751 $process_id = get_app()->process_id;
754 $callers = debug_backtrace();
755 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
758 $LOGGER_LEVELS[$level],
759 basename($callers[0]['file']),
761 $callers[1]['function'],
765 $stamp1 = microtime(true);
766 @file_put_contents($logfile, $logline, FILE_APPEND);
767 $a->save_timestamp($stamp1, "file");
771 * @brief An alternative logger for development.
772 * Works largely as logger() but allows developers
773 * to isolate particular elements they are targetting
774 * personally without background noise
777 * LOGGER_NORMAL (default)
785 * @global array $LOGGER_LEVELS
790 function dlogger($msg, $level = 0) {
794 // turn off logger in install mode
796 $a->module == 'install'
797 || ! ($db && $db->connected)
802 $logfile = get_config('system','dlogfile');
808 if (count($LOGGER_LEVELS) == 0) {
809 foreach (get_defined_constants() as $k => $v) {
810 if (substr($k, 0, 7) == "LOGGER_") {
811 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
816 $process_id = session_id();
818 if ($process_id == '') {
819 $process_id = get_app()->process_id;
822 $callers = debug_backtrace();
823 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
826 basename($callers[0]['file']),
828 $callers[1]['function'],
832 $stamp1 = microtime(true);
833 @file_put_contents($logfile, $logline, FILE_APPEND);
834 $a->save_timestamp($stamp1, "file");
837 if (! function_exists('activity_match')) {
839 * Compare activity uri. Knows about activity namespace.
841 * @param string $haystack
842 * @param string $needle
845 function activity_match($haystack,$needle) {
846 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
851 * @brief Pull out all #hashtags and @person tags from $string.
853 * We also get @person@domain.com - which would make
854 * the regex quite complicated as tags can also
855 * end a sentence. So we'll run through our results
856 * and strip the period from any tags which end with one.
857 * Returns array of tags found, or empty array.
859 * @param string $string Post content
860 * @return array List of tag and person names
862 function get_tags($string) {
865 // Convert hashtag links to hashtags
866 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
868 // ignore anything in a code block
869 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
871 // Force line feeds at bbtags
872 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
874 // ignore anything in a bbtag
875 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
877 // Match full names against @tags including the space between first and last
878 // We will look these up afterward to see if they are full names or not recognisable.
880 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
881 foreach ($matches[1] as $match) {
882 if (strstr($match, ']')) {
883 // we might be inside a bbcode color tag - leave it alone
886 if (substr($match, -1, 1) === '.') {
887 $ret[] = substr($match, 0, -1);
894 // Otherwise pull out single word tags. These can be @nickname, @first_last
897 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
898 foreach ($matches[1] as $match) {
899 if (strstr($match, ']')) {
900 // we might be inside a bbcode color tag - leave it alone
903 if (substr($match, -1, 1) === '.') {
904 $match = substr($match,0,-1);
906 // ignore strictly numeric tags like #1
907 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
910 // try not to catch url fragments
911 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
923 if (! function_exists('qp')) {
925 * quick and dirty quoted_printable encoding
931 return str_replace("%", "=", rawurlencode($s));
934 if (! function_exists('contact_block')) {
936 * Get html for contact block.
938 * @template contact_block.tpl
939 * @hook contact_block_end (contacts=>array, output=>string)
942 function contact_block() {
946 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
947 if ($shown === false) {
954 if ((! is_array($a->profile)) || ($a->profile['hide-friends'])) {
957 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
958 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
959 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
960 AND `network` IN ('%s', '%s', '%s')",
961 intval($a->profile['uid']),
963 dbesc(NETWORK_OSTATUS),
964 dbesc(NETWORK_DIASPORA)
966 if (dbm::is_result($r)) {
967 $total = intval($r[0]['total']);
970 $contacts = t('No contacts');
973 // Splitting the query in two parts makes it much faster
974 $r = q("SELECT `id` FROM `contact`
975 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
976 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
977 AND `network` IN ('%s', '%s', '%s')
978 ORDER BY RAND() LIMIT %d",
979 intval($a->profile['uid']),
981 dbesc(NETWORK_OSTATUS),
982 dbesc(NETWORK_DIASPORA),
985 if (dbm::is_result($r)) {
987 foreach ($r AS $contact) {
988 $contacts[] = $contact["id"];
990 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
991 dbesc(implode(",", $contacts)));
993 if (dbm::is_result($r)) {
994 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
996 foreach ($r as $rr) {
997 $micropro[] = micropro($rr,true,'mpfriend');
1003 $tpl = get_markup_template('contact_block.tpl');
1004 $o = replace_macros($tpl, array(
1005 '$contacts' => $contacts,
1006 '$nickname' => $a->profile['nickname'],
1007 '$viewcontacts' => t('View Contacts'),
1008 '$micropro' => $micropro,
1011 $arr = array('contacts' => $r, 'output' => $o);
1013 call_hooks('contact_block_end', $arr);
1019 * @brief Format contacts as picture links or as texxt links
1021 * @param array $contact Array with contacts which contains an array with
1022 * int 'id' => The ID of the contact
1023 * int 'uid' => The user ID of the user who owns this data
1024 * string 'name' => The name of the contact
1025 * string 'url' => The url to the profile page of the contact
1026 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
1027 * string 'network' => The network to which the contact belongs to
1028 * string 'thumb' => The contact picture
1029 * string 'click' => js code which is performed when clicking on the contact
1030 * @param boolean $redirect If true try to use the redir url if it's possible
1031 * @param string $class CSS class for the
1032 * @param boolean $textmode If true display the contacts as text links
1033 * if false display the contacts as picture links
1035 * @return string Formatted html
1037 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
1039 // Use the contact URL if no address is available
1040 if ($contact["addr"] == "") {
1041 $contact["addr"] = $contact["url"];
1044 $url = $contact['url'];
1050 $redirect_url = 'redir/' . $contact['id'];
1051 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1053 $url = $redirect_url;
1054 $sparkle = ' sparkle';
1060 // If there is some js available we don't need the url
1061 if (x($contact, 'click')) {
1065 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1066 '$click' => (($contact['click']) ? $contact['click'] : ''),
1069 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1070 '$name' => $contact['name'],
1071 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1072 '$parkle' => $sparkle,
1080 if (! function_exists('search')) {
1084 * @param string $s search query
1085 * @param string $id html id
1086 * @param string $url search url
1087 * @param boolean $savedsearch show save search button
1089 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true) {
1093 '$s' => htmlspecialchars($s),
1095 '$action_url' => $url,
1096 '$search_label' => t('Search'),
1097 '$save_label' => t('Save'),
1098 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1099 '$search_hint' => t('@name, !forum, #tags, content'),
1103 $values['$searchoption'] = array(
1108 if (get_config('system','poco_local_search')) {
1109 $values['$searchoption'][] = t("Forums");
1113 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1116 if (! function_exists('valid_email')) {
1118 * Check if $x is a valid email string
1123 function valid_email($x){
1125 /// @TODO Removed because Fabio told me so.
1126 //if (get_config('system','disable_email_validation'))
1128 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $x);
1132 if (! function_exists('linkify')) {
1134 * Replace naked text hyperlink with HTML formatted hyperlink
1138 function linkify($s) {
1139 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1140 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1148 * @return array index is present tense verb
1149 value is array containing past tense verb, translation of present, translation of past
1150 * @hook poke_verbs pokes array
1152 function get_poke_verbs() {
1154 // index is present tense verb
1155 // value is array containing past tense verb, translation of present, translation of past
1158 'poke' => array( 'poked', t('poke'), t('poked')),
1159 'ping' => array( 'pinged', t('ping'), t('pinged')),
1160 'prod' => array( 'prodded', t('prod'), t('prodded')),
1161 'slap' => array( 'slapped', t('slap'), t('slapped')),
1162 'finger' => array( 'fingered', t('finger'), t('fingered')),
1163 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1165 call_hooks('poke_verbs', $arr);
1171 * @return array index is mood, value is translated mood
1172 * @hook mood_verbs moods array
1174 function get_mood_verbs() {
1177 'happy' => t('happy'),
1179 'mellow' => t('mellow'),
1180 'tired' => t('tired'),
1181 'perky' => t('perky'),
1182 'angry' => t('angry'),
1183 'stupefied' => t('stupified'),
1184 'puzzled' => t('puzzled'),
1185 'interested' => t('interested'),
1186 'bitter' => t('bitter'),
1187 'cheerful' => t('cheerful'),
1188 'alive' => t('alive'),
1189 'annoyed' => t('annoyed'),
1190 'anxious' => t('anxious'),
1191 'cranky' => t('cranky'),
1192 'disturbed' => t('disturbed'),
1193 'frustrated' => t('frustrated'),
1194 'motivated' => t('motivated'),
1195 'relaxed' => t('relaxed'),
1196 'surprised' => t('surprised'),
1199 call_hooks('mood_verbs', $arr);
1203 if (! function_exists('day_translate')) {
1205 * Translate days and months names
1210 function day_translate($s) {
1211 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1212 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1215 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1216 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')),
1223 if (! function_exists('normalise_link')) {
1227 * @param string $url
1230 function normalise_link($url) {
1231 $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
1232 return rtrim($ret,'/');
1237 if (! function_exists('link_compare')) {
1239 * Compare two URLs to see if they are the same, but ignore
1240 * slight but hopefully insignificant differences such as if one
1241 * is https and the other isn't, or if one is www.something and
1242 * the other isn't - and also ignore case differences.
1244 * @param string $a first url
1245 * @param string $b second url
1246 * @return boolean True if the URLs match, otherwise False
1249 function link_compare($a, $b) {
1250 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1254 * @brief Find any non-embedded images in private items and add redir links to them
1257 * @param array &$item The field array of an item row
1259 function redir_private_images($a, &$item)
1262 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1264 foreach ($matches as $mtch) {
1265 if (strpos($mtch[1], '/redir') !== false) {
1269 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1270 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1271 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1277 function put_item_in_cache(&$item, $update = false) {
1279 if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
1280 ($item["rendered-html"] == "") || get_config("system", "ignore_cache")) {
1282 // The function "redir_private_images" changes the body.
1283 // I'm not sure if we should store it permanently, so we save the old value.
1284 $body = $item["body"];
1287 redir_private_images($a, $item);
1289 $item["rendered-html"] = prepare_text($item["body"]);
1290 $item["rendered-hash"] = hash("md5", $item["body"]);
1291 $item["body"] = $body;
1293 if ($update && ($item["id"] != 0)) {
1294 q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
1295 dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
1300 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1301 // If attach is true, also add icons for item attachments
1303 if (! function_exists('prepare_body')) {
1305 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1306 * If attach is true, also add icons for item attachments
1308 * @param array $item
1309 * @param boolean $attach
1310 * @return string item body html
1311 * @hook prepare_body_init item array before any work
1312 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1313 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1315 function prepare_body(&$item, $attach = false, $preview = false) {
1318 call_hooks('prepare_body_init', $item);
1320 $searchpath = z_root() . "/search?tag=";
1323 $hashtags = array();
1324 $mentions = array();
1326 if (!get_config('system','suppress_tags')) {
1327 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1328 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1330 foreach ($taglist as $tag) {
1332 if ($tag["url"] == "") {
1333 $tag["url"] = $searchpath.strtolower($tag["term"]);
1336 if ($tag["type"] == TERM_HASHTAG) {
1337 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1339 } elseif ($tag["type"] == TERM_MENTION) {
1340 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1343 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1347 $item['tags'] = $tags;
1348 $item['hashtags'] = $hashtags;
1349 $item['mentions'] = $mentions;
1351 // Update the cached values if there is no "zrl=..." on the links
1352 $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
1354 // Or update it if the current viewer is the intented viewer
1355 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1359 put_item_in_cache($item, $update);
1360 $s = $item["rendered-html"];
1362 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1363 call_hooks('prepare_body', $prep_arr);
1364 $s = $prep_arr['html'];
1367 // Replace the blockquotes with quotes that are used in mails
1368 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1369 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1375 $arr = explode('[/attach],', $item['attach']);
1377 $as .= '<div class="body-attach">';
1378 foreach ($arr as $r) {
1381 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1383 foreach ($matches as $mtch) {
1386 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1387 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1389 $the_url = $mtch[1];
1392 if (strpos($mime, 'video') !== false) {
1395 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1396 '$baseurl' => z_root(),
1398 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1399 '$baseurl' => z_root(),
1403 $id = end(explode('/', $the_url));
1404 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1407 'title' => t('View Video'),
1414 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1416 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1417 $filesubtype = str_replace('.', '-', $filesubtype);
1420 $filesubtype = 'unkn';
1423 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1424 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1430 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1433 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1437 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1438 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1440 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1444 $as .= '<div class="clear"></div></div>';
1449 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1450 $x = generate_map(trim($item['coord']));
1452 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1458 $spoilersearch = '<blockquote class="spoiler">';
1460 // Remove line breaks before the spoiler
1461 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1462 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1464 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1465 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1468 while ((strpos($s, $spoilersearch) !== false)) {
1469 $pos = strpos($s, $spoilersearch);
1470 $rnd = random_string(8);
1471 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1472 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1473 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1476 // Look for quote with author
1477 $authorsearch = '<blockquote class="author">';
1479 while ((strpos($s, $authorsearch) !== false)) {
1480 $pos = strpos($s, $authorsearch);
1481 $rnd = random_string(8);
1482 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1483 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1484 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1487 // replace friendica image url size with theme preference
1488 if (x($a->theme_info, 'item_image_size')){
1489 $ps = $a->theme_info['item_image_size'];
1490 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1493 $prep_arr = array('item' => $item, 'html' => $s);
1494 call_hooks('prepare_body_final', $prep_arr);
1496 return $prep_arr['html'];
1500 if (! function_exists('prepare_text')) {
1502 * Given a text string, convert from bbcode to html and add smilie icons.
1504 * @param string $text
1507 function prepare_text($text) {
1509 require_once 'include/bbcode.php';
1511 if (stristr($text, '[nosmile]')) {
1514 $s = Smilies::replace(bbcode($text));
1523 * return array with details for categories and folders for an item
1525 * @param array $item
1529 * [ // categories array
1531 * 'name': 'category name',
1532 * 'removeurl': 'url to remove this category',
1533 * 'first': 'is the first in this array? true/false',
1534 * 'last': 'is the last in this array? true/false',
1540 * 'name': 'folder name',
1541 * 'removeurl': 'url to remove this folder',
1542 * 'first': 'is the first in this array? true/false',
1543 * 'last': 'is the last in this array? true/false',
1549 function get_cats_and_terms($item) {
1552 $categories = array();
1557 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1559 foreach ($matches as $mtch) {
1560 $categories[] = array(
1561 'name' => xmlify(file_tag_decode($mtch[1])),
1563 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1571 if (count($categories)) {
1572 $categories[count($categories) - 1]['last'] = true;
1575 if (local_user() == $item['uid']) {
1578 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1580 foreach ($matches as $mtch) {
1582 'name' => xmlify(file_tag_decode($mtch[1])),
1584 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1593 if (count($folders)) {
1594 $folders[count($folders) - 1]['last'] = true;
1597 return array($categories, $folders);
1600 if (! function_exists('get_plink')) {
1602 * get private link for item
1603 * @param array $item
1604 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1606 function get_plink($item) {
1609 if ($a->user['nickname'] != "") {
1611 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1612 'href' => "display/" . $item['guid'],
1613 'orig' => "display/" . $item['guid'],
1614 'title' => t('View on separate page'),
1615 'orig_title' => t('view on separate page'),
1618 if (x($item, 'plink')) {
1619 $ret["href"] = $a->remove_baseurl($item['plink']);
1620 $ret["title"] = t('link to source');
1623 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1625 'href' => $item['plink'],
1626 'orig' => $item['plink'],
1627 'title' => t('link to source'),
1636 if (! function_exists('unamp')) {
1638 * replace html amp entity with amp char
1642 function unamp($s) {
1643 return str_replace('&', '&', $s);
1647 if (! function_exists('return_bytes')) {
1649 * return number of bytes in size (K, M, G)
1650 * @param string $size_str
1653 function return_bytes ($size_str) {
1654 switch (substr ($size_str, -1)) {
1655 case 'M': case 'm': return (int)$size_str * 1048576;
1656 case 'K': case 'k': return (int)$size_str * 1024;
1657 case 'G': case 'g': return (int)$size_str * 1073741824;
1658 default: return $size_str;
1665 function generate_user_guid() {
1668 $guid = get_guid(32);
1669 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1672 if (! dbm::is_result($x)) {
1675 } while ($found == true );
1683 * @param boolean $strip_padding
1686 function base64url_encode($s, $strip_padding = false) {
1688 $s = strtr(base64_encode($s), '+/', '-_');
1690 if ($strip_padding) {
1691 $s = str_replace('=','',$s);
1701 function base64url_decode($s) {
1704 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1709 * // Placeholder for new rev of salmon which strips base64 padding.
1710 * // PHP base64_decode handles the un-padded input without requiring this step
1711 * // Uncomment if you find you need it.
1714 * if (! strpos($s,'=')) {
1724 return base64_decode(strtr($s,'-_','+/'));
1728 if (!function_exists('str_getcsv')) {
1732 * @param string $input
1733 * @param string $delimiter
1734 * @param string $enclosure
1735 * @param string $escape
1736 * @param string $eol
1737 * @return boolean|array False on error, otherwise array[row][column]
1739 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1740 if (is_string($input) && !empty($input)) {
1742 $tmp = preg_split("/".$eol."/",$input);
1743 if (is_array($tmp) && !empty($tmp)) {
1744 while (list($line_num, $line) = each($tmp)) {
1745 if (preg_match("/".$escape.$enclosure."/",$line)) {
1746 while ($strlen = strlen($line)) {
1747 $pos_delimiter = strpos($line,$delimiter);
1748 $pos_enclosure_start = strpos($line,$enclosure);
1750 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1751 && ($pos_enclosure_start < $pos_delimiter)
1753 $enclosed_str = substr($line,1);
1754 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1755 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1756 $output[$line_num][] = $enclosed_str;
1757 $offset = $pos_enclosure_end+3;
1759 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1760 $output[$line_num][] = substr($line,0);
1761 $offset = strlen($line);
1763 $output[$line_num][] = substr($line,0,$pos_delimiter);
1765 !empty($pos_enclosure_start)
1766 && ($pos_enclosure_start < $pos_delimiter)
1768 ?$pos_enclosure_start
1772 $line = substr($line,$offset);
1775 $line = preg_split("/".$delimiter."/",$line);
1778 * Validating against pesky extra line breaks creating false rows.
1780 if (is_array($line) && !empty($line[0])) {
1781 $output[$line_num] = $line;
1796 * return div element with class 'clear'
1800 function cleardiv() {
1801 return '<div class="clear"></div>';
1805 function bb_translate_video($s) {
1808 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1810 foreach ($matches as $mtch) {
1811 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1812 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1813 elseif (stristr($mtch[1],'vimeo'))
1814 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1820 function html2bb_video($s) {
1822 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1823 '[youtube]$2[/youtube]', $s);
1825 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1826 '[youtube]$2[/youtube]', $s);
1828 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1829 '[vimeo]$2[/vimeo]', $s);
1835 * apply xmlify() to all values of array $val, recursively
1839 function array_xmlify($val){
1840 if (is_bool($val)) {
1841 return $val?"true":"false";
1842 } elseif (is_array($val)) {
1843 return array_map('array_xmlify', $val);
1845 return xmlify((string) $val);
1850 * transorm link href and img src from relative to absolute
1852 * @param string $text
1853 * @param string $base base url
1856 function reltoabs($text, $base) {
1861 $base = rtrim($base,'/');
1863 $base2 = $base . "/";
1866 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1867 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1868 $text = preg_replace($pattern, $replace, $text);
1870 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1871 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1872 $text = preg_replace($pattern, $replace, $text);
1875 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1876 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1877 $text = preg_replace($pattern, $replace, $text);
1879 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1880 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1881 $text = preg_replace($pattern, $replace, $text);
1889 * get translated item type
1891 * @param array $itme
1894 function item_post_type($item) {
1895 if (intval($item['event-id'])) {
1897 } elseif (strlen($item['resource-id'])) {
1899 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1900 return t('activity');
1901 } elseif ($item['id'] != $item['parent']) {
1902 return t('comment');
1908 // post categories and "save to file" use the same item.file table for storage.
1909 // We will differentiate the different uses by wrapping categories in angle brackets
1910 // and save to file categories in square brackets.
1911 // To do this we need to escape these characters if they appear in our tag.
1913 function file_tag_encode($s) {
1914 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1917 function file_tag_decode($s) {
1918 return str_replace(array('%3c', '%3e', '%5b', '%5d'), array('<', '>', '[', ']'), $s);
1921 function file_tag_file_query($table,$s,$type = 'file') {
1923 if ($type == 'file') {
1924 $str = preg_quote( '[' . str_replace('%', '%%', file_tag_encode($s)) . ']' );
1926 $str = preg_quote( '<' . str_replace('%', '%%', file_tag_encode($s)) . '>' );
1928 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1931 // ex. given music,video return <music><video> or [music][video]
1932 function file_tag_list_to_file($list,$type = 'file') {
1934 if (strlen($list)) {
1935 $list_array = explode(",",$list);
1936 if ($type == 'file') {
1944 foreach ($list_array as $item) {
1945 if (strlen($item)) {
1946 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1953 // ex. given <music><video>[friends], return music,video or friends
1954 function file_tag_file_to_list($file,$type = 'file') {
1957 if ($type == 'file') {
1958 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1960 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1963 foreach ($matches as $mtch) {
1964 if (strlen($list)) {
1967 $list .= file_tag_decode($mtch[1]);
1974 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1975 // $file_old - categories previously associated with an item
1976 // $file_new - new list of categories for an item
1981 if ($file_old == $file_new)
1984 $saved = get_pconfig($uid,'system','filetags');
1985 if (strlen($saved)) {
1986 if ($type == 'file') {
1989 $termtype = TERM_FILE;
1994 $termtype = TERM_CATEGORY;
1997 $filetags_updated = $saved;
1999 // check for new tags to be added as filetags in pconfig
2000 $new_tags = array();
2001 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
2003 foreach ($check_new_tags as $tag) {
2004 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
2008 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
2010 // check for deleted tags to be removed from filetags in pconfig
2011 $deleted_tags = array();
2012 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2014 foreach ($check_deleted_tags as $tag) {
2015 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2016 $deleted_tags[] = $tag;
2019 foreach ($deleted_tags as $key => $tag) {
2020 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2022 intval(TERM_OBJ_POST),
2026 if (dbm::is_result($r)) {
2027 unset($deleted_tags[$key]);
2030 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2034 if ($saved != $filetags_updated) {
2035 set_pconfig($uid, 'system', 'filetags', $filetags_updated);
2040 if (strlen($file_new)) {
2041 set_pconfig($uid, 'system', 'filetags', $file_new);
2046 function file_tag_save_file($uid, $item, $file) {
2047 require_once "include/files.php";
2052 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2056 if (dbm::is_result($r)) {
2057 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
2058 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2059 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2065 create_files_from_item($item);
2067 $saved = get_pconfig($uid,'system','filetags');
2068 if ((! strlen($saved)) || (! stristr($saved, '[' . file_tag_encode($file) . ']'))) {
2069 set_pconfig($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
2071 info( t('Item filed') );
2076 function file_tag_unsave_file($uid, $item, $file, $cat = false) {
2077 require_once "include/files.php";
2084 $pattern = '<' . file_tag_encode($file) . '>' ;
2085 $termtype = TERM_CATEGORY;
2087 $pattern = '[' . file_tag_encode($file) . ']' ;
2088 $termtype = TERM_FILE;
2092 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2096 if (! dbm::is_result($r)) {
2100 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
2101 dbesc(str_replace($pattern,'',$r[0]['file'])),
2106 create_files_from_item($item);
2108 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2110 intval(TERM_OBJ_POST),
2114 if (! dbm::is_result($r)) {
2115 $saved = get_pconfig($uid,'system','filetags');
2116 set_pconfig($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
2122 function normalise_openid($s) {
2123 return trim(str_replace(array('http://', 'https://'), array('', ''), $s), '/');
2127 function undo_post_tagging($s) {
2129 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
2131 foreach ($matches as $mtch) {
2132 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2138 function protect_sprintf($s) {
2139 return str_replace('%', '%%', $s);
2143 function is_a_date_arg($s) {
2147 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2148 $m = intval(substr($s,5));
2149 if ($m > 0 && $m <= 12)
2157 * remove intentation from a text
2159 function deindent($text, $chr = "[\t ]", $count = NULL) {
2160 $lines = explode("\n", $text);
2161 if (is_null($count)) {
2164 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2167 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2168 $count = strlen($m[0]);
2170 for ($k = 0; $k < count($lines); $k++) {
2171 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2174 return implode("\n", $lines);
2177 function formatBytes($bytes, $precision = 2) {
2178 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2180 $bytes = max($bytes, 0);
2181 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2182 $pow = min($pow, count($units) - 1);
2184 $bytes /= pow(1024, $pow);
2186 return round($bytes, $precision) . ' ' . $units[$pow];
2190 * @brief translate and format the networkname of a contact
2192 * @param string $network
2193 * Networkname of the contact (e.g. dfrn, rss and so on)
2198 function format_network_name($network, $url = 0) {
2199 if ($network != "") {
2200 require_once 'include/contact_selectors.php';
2202 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2204 $network_name = network_to_name($network);
2207 return $network_name;
2213 * @brief Syntax based code highlighting for popular languages.
2214 * @param string $s Code block
2215 * @param string $lang Programming language
2216 * @return string Formated html
2218 function text_highlight($s, $lang) {
2219 if ($lang === 'js') {
2220 $lang = 'javascript';
2223 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2225 // Autoload the library to make constants available
2226 class_exists('Text_Highlighter_Renderer_Html');
2229 'numbers' => HL_NUMBERS_LI,
2234 $s = trim(html_entity_decode($s, ENT_COMPAT));
2235 $s = str_replace(' ', "\t", $s);
2238 * The highlighter library insists on an opening php tag for php code blocks. If
2239 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2240 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2242 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2243 $s = '<?php' . "\n" . $s;
2247 $renderer = new Text_Highlighter_Renderer_Html($options);
2248 $hl = Text_Highlighter::factory($lang);
2249 $hl->setRenderer($renderer);
2250 $o = $hl->highlight($s);
2251 $o = str_replace("\n", '', $o);
2254 $b = substr($o, 0, strpos($o, '<li>'));
2255 $e = substr($o, strpos($o, '</li>'));
2259 return '<code>' . $o . '</code>';