4 use Friendica\Content\Smilies;
5 use Friendica\Core\Config;
6 use Friendica\Core\PConfig;
7 use Friendica\Core\System;
8 use Friendica\Database\DBM;
10 require_once "include/friendica_smarty.php";
11 require_once "include/map.php";
12 require_once "mod/proxy.php";
15 * This is our template processor
17 * @param string|FriendicaSmarty $s the string requiring macro substitution,
18 * or an instance of FriendicaSmarty
19 * @param array $r key value pairs (search => replace)
20 * @return string substituted string
22 function replace_macros($s, $r) {
24 $stamp1 = microtime(true);
28 // pass $baseurl to all templates
29 $r['$baseurl'] = System::baseUrl();
31 $t = $a->template_engine();
33 $output = $t->replaceMacros($s, $r);
34 } catch (Exception $e) {
35 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
39 $a->save_timestamp($stamp1, "rendering");
45 * @brief Generates a pseudo-random string of hexadecimal characters
50 function random_string($size = 64)
52 $byte_size = ceil($size / 2);
54 $bytes = random_bytes($byte_size);
56 $return = substr(bin2hex($bytes), 0, $size);
62 * This is our primary input filter.
64 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
65 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
66 * after cleansing, and angle chars with the high bit set could get through as markup.
68 * This is now disabled because it was interfering with some legitimate unicode sequences
69 * and hopefully there aren't a lot of those browsers left.
71 * Use this on any text input where angle chars are not valid or permitted
72 * They will be replaced with safer brackets. This may be filtered further
73 * if these are not allowed either.
75 * @param string $string Input string
76 * @return string Filtered string
78 function notags($string) {
79 return str_replace(array("<", ">"), array('[', ']'), $string);
81 // High-bit filter no longer used
82 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
87 * use this on "body" or "content" input where angle chars shouldn't be removed,
88 * and allow them to be safely displayed.
89 * @param string $string
92 function escape_tags($string) {
93 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
98 * generate a string that's random, but usually pronounceable.
99 * used to generate initial passwords
103 function autoname($len) {
109 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
110 if (mt_rand(0, 5) == 4) {
129 's','sc','sh','sm','sp','st',
137 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
138 'nd','ng','nk','nt','rn','rp','rt');
140 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
141 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
143 $start = mt_rand(0,2);
152 for ($x = 0; $x < $len; $x ++) {
153 $r = mt_rand(0,count($table) - 1);
156 if ($table == $vowels) {
157 $table = array_merge($cons,$midcons);
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);
180 * escape text ($str) for XML transport
182 * @return string Escaped text.
184 function xmlify($str) {
185 /// @TODO deprecated code found?
188 $len = mb_strlen($str);
189 for ($x = 0; $x < $len; $x ++) {
190 $char = mb_substr($str,$x,1);
220 $buffer = mb_ereg_replace("&", "&", $str);
221 $buffer = mb_ereg_replace("'", "'", $buffer);
222 $buffer = mb_ereg_replace('"', """, $buffer);
223 $buffer = mb_ereg_replace("<", "<", $buffer);
224 $buffer = mb_ereg_replace(">", ">", $buffer);
226 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
227 $buffer = trim($buffer);
235 * @param string $s xml escaped text
236 * @return string unescaped text
238 function unxmlify($s) {
239 /// @TODO deprecated code found?
240 // $ret = str_replace('&','&', $s);
241 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
242 /*$ret = mb_ereg_replace('&', '&', $s);
243 $ret = mb_ereg_replace(''', "'", $ret);
244 $ret = mb_ereg_replace('"', '"', $ret);
245 $ret = mb_ereg_replace('<', "<", $ret);
246 $ret = mb_ereg_replace('>', ">", $ret);
248 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
254 * @brief Paginator function. Pushes relevant links in a pager array structure.
256 * Links are generated depending on the current page and the total number of items.
257 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
258 * Current page link is given the "active" CSS class
260 * @param App $a App instance
261 * @param int $count [optional] item count (used with minimal pager)
262 * @return Array data for pagination template
264 function paginate_data(App $a, $count = null) {
265 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
267 $stripped = str_replace('q=', '', $stripped);
268 $stripped = trim($stripped, '/');
269 $pagenum = $a->pager['page'];
271 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
272 $stripped .= '&offset=' . urlencode($a->page_offset);
278 function _l(&$d, $name, $url, $text, $class = '') {
279 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
280 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
283 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
286 if (!is_null($count)) {
287 // minimal pager (newer / older)
288 $data['class'] = 'pager';
289 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
290 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
292 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
293 $data['class'] = 'pagination';
294 if ($a->pager['total'] > $a->pager['itemspage']) {
295 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
296 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
298 $numpages = $a->pager['total'] / $a->pager['itemspage'];
301 $numstop = $numpages;
303 // Limit the number of displayed page number buttons.
305 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
306 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
311 for ($i = $numstart; $i <= $numstop; $i++) {
312 if ($i == $a->pager['page']) {
313 _l($pages, $i, '#', $i, 'current active');
315 _l($pages, $i, $url . '&page='. $i, $i, 'n');
319 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
320 if ($i == $a->pager['page']) {
321 _l($pages, $i, '#', $i, 'current active');
323 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
327 $data['pages'] = $pages;
329 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
330 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
331 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
340 * Automatic pagination.
342 * To use, get the count of total items.
343 * Then call $a->set_pager_total($number_items);
344 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
345 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
346 * (assuming there are enough items to paginate).
347 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
348 * will limit the results to the correct items for the current page.
349 * The actual page handling is then accomplished at the application layer.
351 * @param App $a App instance
352 * @return string html for pagination #FIXME remove html
354 function paginate(App $a) {
356 $data = paginate_data($a);
357 $tpl = get_markup_template("paginate.tpl");
358 return replace_macros($tpl, array("pager" => $data));
365 * @param App $a App instance
367 * @return string html for pagination #FIXME remove html
369 function alt_pager(App $a, $i) {
371 $data = paginate_data($a, $i);
372 $tpl = get_markup_template("paginate.tpl");
373 return replace_macros($tpl, array('pager' => $data));
379 * Loader for infinite scrolling
380 * @return string html for loader
382 function scroll_loader() {
383 $tpl = get_markup_template("scroll_loader.tpl");
384 return replace_macros($tpl, array(
385 'wait' => t('Loading more entries...'),
386 'end' => t('The end')
392 * Turn user/group ACLs stored as angle bracketed text into arrays
397 function expand_acl($s) {
398 // turn string array of angle-bracketed elements into numeric array
399 // e.g. "<1><2><3>" => array(1,2,3);
403 $t = str_replace('<', '', $s);
404 $a = explode('>', $t);
405 foreach ($a as $aa) {
407 $ret[] = intval($aa);
416 * Wrap ACL elements in angle brackets for storage
417 * @param string $item
419 function sanitise_acl(&$item) {
421 $item = '<' . intval(notags(trim($item))) . '>';
429 * Convert an ACL array to a storable string
431 * Normally ACL permissions will be an array.
432 * We'll also allow a comma-separated string.
434 * @param string|array $p
437 function perms2str($p) {
442 $tmp = explode(',',$p);
445 if (is_array($tmp)) {
446 array_walk($tmp, 'sanitise_acl');
447 $ret = implode('', $tmp);
454 * generate a guaranteed unique (for this domain) item ID for ATOM
455 * safe from birthday paradox
457 * @param string $hostname
461 function item_new_uri($hostname, $uid, $guid = "") {
465 $hash = get_guid(32);
471 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
473 $dups = dba::exists('item', array('uri' => $uri));
474 } while ($dups == true);
481 * Generate a guaranteed unique photo ID.
482 * safe from birthday paradox
486 function photo_new_resource() {
490 $resource = hash('md5',uniqid(mt_rand(),true));
491 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
495 if (DBM::is_result($r)) {
498 } while ($found == true);
506 * wrapper to load a view template, checking for alternate
507 * languages before falling back to the default
509 * @global string $lang
511 * @param string $s view name
514 function load_view_file($s) {
516 if (! isset($lang)) {
521 if (file_exists("$d/$lang/$b")) {
522 $stamp1 = microtime(true);
523 $content = file_get_contents("$d/$lang/$b");
524 $a->save_timestamp($stamp1, "file");
528 $theme = current_theme();
530 if (file_exists("$d/theme/$theme/$b")) {
531 $stamp1 = microtime(true);
532 $content = file_get_contents("$d/theme/$theme/$b");
533 $a->save_timestamp($stamp1, "file");
537 $stamp1 = microtime(true);
538 $content = file_get_contents($s);
539 $a->save_timestamp($stamp1, "file");
545 * load a view template, checking for alternate
546 * languages before falling back to the default
548 * @global string $lang
549 * @param string $s view path
552 function get_intltext_template($s) {
557 if ($a->theme['template_engine'] === 'smarty3') {
558 $engine = "/smarty3";
561 if (! isset($lang)) {
565 if (file_exists("view/lang/$lang$engine/$s")) {
566 $stamp1 = microtime(true);
567 $content = file_get_contents("view/lang/$lang$engine/$s");
568 $a->save_timestamp($stamp1, "file");
570 } elseif (file_exists("view/lang/en$engine/$s")) {
571 $stamp1 = microtime(true);
572 $content = file_get_contents("view/lang/en$engine/$s");
573 $a->save_timestamp($stamp1, "file");
576 $stamp1 = microtime(true);
577 $content = file_get_contents("view$engine/$s");
578 $a->save_timestamp($stamp1, "file");
588 * @param string $root
591 function get_markup_template($s, $root = '') {
592 $stamp1 = microtime(true);
595 $t = $a->template_engine();
597 $template = $t->getTemplateFile($s, $root);
598 } catch (Exception $e) {
599 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
603 $a->save_timestamp($stamp1, "file");
612 * @param string $filename
613 * @param string $root
616 function get_template_file($a, $filename, $root = '') {
617 $theme = current_theme();
619 // Make sure $root ends with a slash /
620 if ($root !== '' && substr($root, -1, 1) !== '/') {
624 if (file_exists("{$root}view/theme/$theme/$filename")) {
625 $template_file = "{$root}view/theme/$theme/$filename";
626 } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
627 $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
628 } elseif (file_exists("{$root}/$filename")) {
629 $template_file = "{$root}/$filename";
631 $template_file = "{$root}view/$filename";
634 return $template_file;
639 * for html,xml parsing - let's say you've got
640 * an attribute foobar="class1 class2 class3"
641 * and you want to find out if it contains 'class3'.
642 * you can't use a normal sub string search because you
643 * might match 'notclass3' and a regex to do the job is
644 * possible but a bit complicated.
645 * pass the attribute string as $attr and the attribute you
646 * are looking for as $s - returns true if found, otherwise false
648 * @param string $attr attribute value
649 * @param string $s string to search
650 * @return boolean True if found, False otherwise
652 function attribute_contains($attr, $s) {
653 $a = explode(' ', $attr);
654 return (count($a) && in_array($s,$a));
658 /* setup int->string log level map */
659 $LOGGER_LEVELS = array();
662 * @brief Logs the given message at the given log level
665 * LOGGER_NORMAL (default)
672 * @global array $LOGGER_LEVELS
676 function logger($msg, $level = 0) {
678 global $LOGGER_LEVELS;
680 // turn off logger in install mode
682 $a->module == 'install'
688 $debugging = Config::get('system','debugging');
689 $logfile = Config::get('system','logfile');
690 $loglevel = intval(Config::get('system','loglevel'));
695 || $level > $loglevel
700 if (count($LOGGER_LEVELS) == 0) {
701 foreach (get_defined_constants() as $k => $v) {
702 if (substr($k, 0, 7) == "LOGGER_") {
703 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
708 $process_id = session_id();
710 if ($process_id == '') {
711 $process_id = get_app()->process_id;
714 $callers = debug_backtrace();
715 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
716 datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
718 $LOGGER_LEVELS[$level],
719 basename($callers[0]['file']),
721 $callers[1]['function'],
725 $stamp1 = microtime(true);
726 @file_put_contents($logfile, $logline, FILE_APPEND);
727 $a->save_timestamp($stamp1, "file");
731 * @brief An alternative logger for development.
732 * Works largely as logger() but allows developers
733 * to isolate particular elements they are targetting
734 * personally without background noise
737 * LOGGER_NORMAL (default)
744 * @global array $LOGGER_LEVELS
749 function dlogger($msg, $level = 0) {
752 // turn off logger in install mode
754 $a->module == 'install'
760 $logfile = Config::get('system','dlogfile');
766 if (count($LOGGER_LEVELS) == 0) {
767 foreach (get_defined_constants() as $k => $v) {
768 if (substr($k, 0, 7) == "LOGGER_") {
769 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
774 $process_id = session_id();
776 if ($process_id == '') {
777 $process_id = get_app()->process_id;
780 $callers = debug_backtrace();
781 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
784 basename($callers[0]['file']),
786 $callers[1]['function'],
790 $stamp1 = microtime(true);
791 @file_put_contents($logfile, $logline, FILE_APPEND);
792 $a->save_timestamp($stamp1, "file");
797 * Compare activity uri. Knows about activity namespace.
799 * @param string $haystack
800 * @param string $needle
803 function activity_match($haystack,$needle) {
804 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
809 * @brief Pull out all #hashtags and @person tags from $string.
811 * We also get @person@domain.com - which would make
812 * the regex quite complicated as tags can also
813 * end a sentence. So we'll run through our results
814 * and strip the period from any tags which end with one.
815 * Returns array of tags found, or empty array.
817 * @param string $string Post content
818 * @return array List of tag and person names
820 function get_tags($string) {
823 // Convert hashtag links to hashtags
824 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
826 // ignore anything in a code block
827 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
829 // Force line feeds at bbtags
830 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
832 // ignore anything in a bbtag
833 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
835 // Match full names against @tags including the space between first and last
836 // We will look these up afterward to see if they are full names or not recognisable.
838 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
839 foreach ($matches[1] as $match) {
840 if (strstr($match, ']')) {
841 // we might be inside a bbcode color tag - leave it alone
844 if (substr($match, -1, 1) === '.') {
845 $ret[] = substr($match, 0, -1);
852 // Otherwise pull out single word tags. These can be @nickname, @first_last
855 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
856 foreach ($matches[1] as $match) {
857 if (strstr($match, ']')) {
858 // we might be inside a bbcode color tag - leave it alone
861 if (substr($match, -1, 1) === '.') {
862 $match = substr($match,0,-1);
864 // ignore strictly numeric tags like #1
865 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
868 // try not to catch url fragments
869 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
880 * quick and dirty quoted_printable encoding
886 return str_replace("%", "=", rawurlencode($s));
891 * Get html for contact block.
893 * @template contact_block.tpl
894 * @hook contact_block_end (contacts=>array, output=>string)
897 function contact_block() {
901 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
906 if (!is_array($a->profile) || $a->profile['hide-friends']) {
909 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
910 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
911 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
912 AND `network` IN ('%s', '%s', '%s')",
913 intval($a->profile['uid']),
915 dbesc(NETWORK_OSTATUS),
916 dbesc(NETWORK_DIASPORA)
918 if (DBM::is_result($r)) {
919 $total = intval($r[0]['total']);
922 $contacts = t('No contacts');
925 // Splitting the query in two parts makes it much faster
926 $r = q("SELECT `id` FROM `contact`
927 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
928 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
929 AND `network` IN ('%s', '%s', '%s')
930 ORDER BY RAND() LIMIT %d",
931 intval($a->profile['uid']),
933 dbesc(NETWORK_OSTATUS),
934 dbesc(NETWORK_DIASPORA),
937 if (DBM::is_result($r)) {
939 foreach ($r AS $contact) {
940 $contacts[] = $contact["id"];
942 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
943 dbesc(implode(",", $contacts)));
945 if (DBM::is_result($r)) {
946 $contacts = sprintf(tt('%d Contact','%d Contacts', $total),$total);
948 foreach ($r as $rr) {
949 $micropro[] = micropro($rr,true,'mpfriend');
955 $tpl = get_markup_template('contact_block.tpl');
956 $o = replace_macros($tpl, array(
957 '$contacts' => $contacts,
958 '$nickname' => $a->profile['nickname'],
959 '$viewcontacts' => t('View Contacts'),
960 '$micropro' => $micropro,
963 $arr = array('contacts' => $r, 'output' => $o);
965 call_hooks('contact_block_end', $arr);
972 * @brief Format contacts as picture links or as texxt links
974 * @param array $contact Array with contacts which contains an array with
975 * int 'id' => The ID of the contact
976 * int 'uid' => The user ID of the user who owns this data
977 * string 'name' => The name of the contact
978 * string 'url' => The url to the profile page of the contact
979 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
980 * string 'network' => The network to which the contact belongs to
981 * string 'thumb' => The contact picture
982 * string 'click' => js code which is performed when clicking on the contact
983 * @param boolean $redirect If true try to use the redir url if it's possible
984 * @param string $class CSS class for the
985 * @param boolean $textmode If true display the contacts as text links
986 * if false display the contacts as picture links
988 * @return string Formatted html
990 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
992 // Use the contact URL if no address is available
993 if ($contact["addr"] == "") {
994 $contact["addr"] = $contact["url"];
997 $url = $contact['url'];
1003 $redirect_url = 'redir/' . $contact['id'];
1004 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1006 $url = $redirect_url;
1007 $sparkle = ' sparkle';
1013 // If there is some js available we don't need the url
1014 if (x($contact, 'click')) {
1018 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1019 '$click' => (($contact['click']) ? $contact['click'] : ''),
1022 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1023 '$name' => $contact['name'],
1024 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1025 '$parkle' => $sparkle,
1034 * @param string $s search query
1035 * @param string $id html id
1036 * @param string $url search url
1037 * @param boolean $savedsearch show save search button
1039 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true) {
1043 '$s' => htmlspecialchars($s),
1045 '$action_url' => $url,
1046 '$search_label' => t('Search'),
1047 '$save_label' => t('Save'),
1048 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1049 '$search_hint' => t('@name, !forum, #tags, content'),
1053 $values['$searchoption'] = array(
1058 if (Config::get('system','poco_local_search')) {
1059 $values['$searchoption'][] = t("Forums");
1063 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1067 * Check if $x is a valid email string
1072 function valid_email($x){
1074 /// @TODO Removed because Fabio told me so.
1075 //if (Config::get('system','disable_email_validation'))
1077 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $x);
1082 * Replace naked text hyperlink with HTML formatted hyperlink
1086 function linkify($s) {
1087 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1088 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1096 * @return array index is present tense verb
1097 value is array containing past tense verb, translation of present, translation of past
1098 * @hook poke_verbs pokes array
1100 function get_poke_verbs() {
1102 // index is present tense verb
1103 // value is array containing past tense verb, translation of present, translation of past
1106 'poke' => array('poked', t('poke'), t('poked')),
1107 'ping' => array('pinged', t('ping'), t('pinged')),
1108 'prod' => array('prodded', t('prod'), t('prodded')),
1109 'slap' => array('slapped', t('slap'), t('slapped')),
1110 'finger' => array('fingered', t('finger'), t('fingered')),
1111 'rebuff' => array('rebuffed', t('rebuff'), t('rebuffed')),
1113 call_hooks('poke_verbs', $arr);
1119 * @return array index is mood, value is translated mood
1120 * @hook mood_verbs moods array
1122 function get_mood_verbs() {
1125 'happy' => t('happy'),
1127 'mellow' => t('mellow'),
1128 'tired' => t('tired'),
1129 'perky' => t('perky'),
1130 'angry' => t('angry'),
1131 'stupefied' => t('stupified'),
1132 'puzzled' => t('puzzled'),
1133 'interested' => t('interested'),
1134 'bitter' => t('bitter'),
1135 'cheerful' => t('cheerful'),
1136 'alive' => t('alive'),
1137 'annoyed' => t('annoyed'),
1138 'anxious' => t('anxious'),
1139 'cranky' => t('cranky'),
1140 'disturbed' => t('disturbed'),
1141 'frustrated' => t('frustrated'),
1142 'motivated' => t('motivated'),
1143 'relaxed' => t('relaxed'),
1144 'surprised' => t('surprised'),
1147 call_hooks('mood_verbs', $arr);
1152 * @brief Translate days and months names.
1154 * @param string $s String with day or month name.
1155 * @return string Translated string.
1157 function day_translate($s) {
1158 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1159 array(t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1162 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1163 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')),
1170 * @brief Translate short days and months names.
1172 * @param string $s String with short day or month name.
1173 * @return string Translated string.
1175 function day_short_translate($s) {
1176 $ret = str_replace(array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'),
1177 array(t('Mon'), t('Tue'), t('Wed'), t('Thu'), t('Fri'), t('Sat'), t('Sund')),
1179 $ret = str_replace(array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'),
1180 array(t('Jan'), t('Feb'), t('Mar'), t('Apr'), t('May'), ('Jun'), t('Jul'), t('Aug'), t('Sep'), t('Oct'), t('Nov'), t('Dec')),
1189 * @param string $url
1192 function normalise_link($url) {
1193 $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
1194 return rtrim($ret,'/');
1199 * Compare two URLs to see if they are the same, but ignore
1200 * slight but hopefully insignificant differences such as if one
1201 * is https and the other isn't, or if one is www.something and
1202 * the other isn't - and also ignore case differences.
1204 * @param string $a first url
1205 * @param string $b second url
1206 * @return boolean True if the URLs match, otherwise False
1209 function link_compare($a, $b) {
1210 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1215 * @brief Find any non-embedded images in private items and add redir links to them
1218 * @param array &$item The field array of an item row
1220 function redir_private_images($a, &$item)
1223 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1225 foreach ($matches as $mtch) {
1226 if (strpos($mtch[1], '/redir') !== false) {
1230 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1231 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1232 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1238 function put_item_in_cache(&$item, $update = false) {
1240 if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
1241 ($item["rendered-html"] == "") || Config::get("system", "ignore_cache")) {
1243 // The function "redir_private_images" changes the body.
1244 // I'm not sure if we should store it permanently, so we save the old value.
1245 $body = $item["body"];
1248 redir_private_images($a, $item);
1250 $item["rendered-html"] = prepare_text($item["body"]);
1251 $item["rendered-hash"] = hash("md5", $item["body"]);
1252 $item["body"] = $body;
1254 if ($update && ($item["id"] > 0)) {
1255 dba::update('item', array('rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]),
1256 array('id' => $item["id"]), false);
1262 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1263 * If attach is true, also add icons for item attachments.
1265 * @param array $item
1266 * @param boolean $attach
1267 * @return string item body html
1268 * @hook prepare_body_init item array before any work
1269 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1270 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1272 function prepare_body(&$item, $attach = false, $preview = false) {
1275 call_hooks('prepare_body_init', $item);
1277 $searchpath = System::baseUrl() . "/search?tag=";
1280 $hashtags = array();
1281 $mentions = array();
1283 // In order to provide theme developers more possibilities, event items
1284 // are treated differently.
1285 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1286 $ev = format_event_item($item);
1290 if (!Config::get('system','suppress_tags')) {
1291 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1292 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1294 while ($tag = dba::fetch($taglist)) {
1295 if ($tag["url"] == "") {
1296 $tag["url"] = $searchpath.strtolower($tag["term"]);
1299 $orig_tag = $tag["url"];
1301 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1303 if ($tag["type"] == TERM_HASHTAG) {
1304 if ($orig_tag != $tag["url"]) {
1305 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1307 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1309 } elseif ($tag["type"] == TERM_MENTION) {
1310 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1313 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1315 dba::close($taglist);
1318 $item['tags'] = $tags;
1319 $item['hashtags'] = $hashtags;
1320 $item['mentions'] = $mentions;
1322 // Update the cached values if there is no "zrl=..." on the links.
1323 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1325 // Or update it if the current viewer is the intented viewer.
1326 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1330 put_item_in_cache($item, $update);
1331 $s = $item["rendered-html"];
1333 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1334 call_hooks('prepare_body', $prep_arr);
1335 $s = $prep_arr['html'];
1338 // Replace the blockquotes with quotes that are used in mails.
1339 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1340 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1346 $arr = explode('[/attach],', $item['attach']);
1348 foreach ($arr as $r) {
1351 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1353 foreach ($matches as $mtch) {
1356 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1357 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1359 $the_url = $mtch[1];
1362 if (strpos($mime, 'video') !== false) {
1365 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1366 '$baseurl' => System::baseUrl(),
1368 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1369 '$baseurl' => System::baseUrl(),
1373 $id = end(explode('/', $the_url));
1374 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1377 'title' => t('View Video'),
1384 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1386 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1387 $filesubtype = str_replace('.', '-', $filesubtype);
1390 $filesubtype = 'unkn';
1393 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1394 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1396 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1397 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1403 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1407 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1408 $x = generate_map(trim($item['coord']));
1410 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1415 // Look for spoiler.
1416 $spoilersearch = '<blockquote class="spoiler">';
1418 // Remove line breaks before the spoiler.
1419 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1420 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1422 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1423 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1426 while ((strpos($s, $spoilersearch) !== false)) {
1427 $pos = strpos($s, $spoilersearch);
1428 $rnd = random_string(8);
1429 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1430 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1431 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1434 // Look for quote with author.
1435 $authorsearch = '<blockquote class="author">';
1437 while ((strpos($s, $authorsearch) !== false)) {
1438 $pos = strpos($s, $authorsearch);
1439 $rnd = random_string(8);
1440 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1441 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1442 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1445 // Replace friendica image url size with theme preference.
1446 if (x($a->theme_info, 'item_image_size')){
1447 $ps = $a->theme_info['item_image_size'];
1448 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1451 $prep_arr = array('item' => $item, 'html' => $s);
1452 call_hooks('prepare_body_final', $prep_arr);
1454 return $prep_arr['html'];
1458 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1460 * @param string $text String with bbcode.
1461 * @return string Formattet HTML.
1463 function prepare_text($text) {
1465 require_once 'include/bbcode.php';
1467 if (stristr($text, '[nosmile]')) {
1470 $s = Smilies::replace(bbcode($text));
1477 * return array with details for categories and folders for an item
1479 * @param array $item
1483 * [ // categories array
1485 * 'name': 'category name',
1486 * 'removeurl': 'url to remove this category',
1487 * 'first': 'is the first in this array? true/false',
1488 * 'last': 'is the last in this array? true/false',
1494 * 'name': 'folder name',
1495 * 'removeurl': 'url to remove this folder',
1496 * 'first': 'is the first in this array? true/false',
1497 * 'last': 'is the last in this array? true/false',
1503 function get_cats_and_terms($item) {
1506 $categories = array();
1511 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1513 foreach ($matches as $mtch) {
1514 $categories[] = array(
1515 'name' => xmlify(file_tag_decode($mtch[1])),
1517 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1525 if (count($categories)) {
1526 $categories[count($categories) - 1]['last'] = true;
1529 if (local_user() == $item['uid']) {
1532 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1534 foreach ($matches as $mtch) {
1536 'name' => xmlify(file_tag_decode($mtch[1])),
1538 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1547 if (count($folders)) {
1548 $folders[count($folders) - 1]['last'] = true;
1551 return array($categories, $folders);
1556 * get private link for item
1557 * @param array $item
1558 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1560 function get_plink($item) {
1563 if ($a->user['nickname'] != "") {
1565 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1566 'href' => "display/" . $item['guid'],
1567 'orig' => "display/" . $item['guid'],
1568 'title' => t('View on separate page'),
1569 'orig_title' => t('view on separate page'),
1572 if (x($item, 'plink')) {
1573 $ret["href"] = $a->remove_baseurl($item['plink']);
1574 $ret["title"] = t('link to source');
1577 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1579 'href' => $item['plink'],
1580 'orig' => $item['plink'],
1581 'title' => t('link to source'),
1592 * replace html amp entity with amp char
1596 function unamp($s) {
1597 return str_replace('&', '&', $s);
1602 * return number of bytes in size (K, M, G)
1603 * @param string $size_str
1606 function return_bytes($size_str) {
1607 switch (substr ($size_str, -1)) {
1608 case 'M': case 'm': return (int)$size_str * 1048576;
1609 case 'K': case 'k': return (int)$size_str * 1024;
1610 case 'G': case 'g': return (int)$size_str * 1073741824;
1611 default: return $size_str;
1619 function generate_user_guid() {
1622 $guid = get_guid(32);
1623 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1626 if (! DBM::is_result($x)) {
1629 } while ($found == true);
1637 * @param boolean $strip_padding
1640 function base64url_encode($s, $strip_padding = false) {
1642 $s = strtr(base64_encode($s), '+/', '-_');
1644 if ($strip_padding) {
1645 $s = str_replace('=','',$s);
1655 function base64url_decode($s) {
1658 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1663 * // Placeholder for new rev of salmon which strips base64 padding.
1664 * // PHP base64_decode handles the un-padded input without requiring this step
1665 * // Uncomment if you find you need it.
1668 * if (! strpos($s,'=')) {
1678 return base64_decode(strtr($s,'-_','+/'));
1683 * return div element with class 'clear'
1687 function cleardiv() {
1688 return '<div class="clear"></div>';
1692 function bb_translate_video($s) {
1695 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1697 foreach ($matches as $mtch) {
1698 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1699 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1700 elseif (stristr($mtch[1],'vimeo'))
1701 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1707 function html2bb_video($s) {
1709 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1710 '[youtube]$2[/youtube]', $s);
1712 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1713 '[youtube]$2[/youtube]', $s);
1715 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1716 '[vimeo]$2[/vimeo]', $s);
1722 * apply xmlify() to all values of array $val, recursively
1726 function array_xmlify($val){
1727 if (is_bool($val)) {
1728 return $val?"true":"false";
1729 } elseif (is_array($val)) {
1730 return array_map('array_xmlify', $val);
1732 return xmlify((string) $val);
1737 * transorm link href and img src from relative to absolute
1739 * @param string $text
1740 * @param string $base base url
1743 function reltoabs($text, $base) {
1748 $base = rtrim($base,'/');
1750 $base2 = $base . "/";
1753 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1754 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1755 $text = preg_replace($pattern, $replace, $text);
1757 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1758 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1759 $text = preg_replace($pattern, $replace, $text);
1762 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1763 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1764 $text = preg_replace($pattern, $replace, $text);
1766 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1767 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1768 $text = preg_replace($pattern, $replace, $text);
1776 * get translated item type
1778 * @param array $itme
1781 function item_post_type($item) {
1782 if (intval($item['event-id'])) {
1784 } elseif (strlen($item['resource-id'])) {
1786 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1787 return t('activity');
1788 } elseif ($item['id'] != $item['parent']) {
1789 return t('comment');
1795 // post categories and "save to file" use the same item.file table for storage.
1796 // We will differentiate the different uses by wrapping categories in angle brackets
1797 // and save to file categories in square brackets.
1798 // To do this we need to escape these characters if they appear in our tag.
1800 function file_tag_encode($s) {
1801 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1804 function file_tag_decode($s) {
1805 return str_replace(array('%3c', '%3e', '%5b', '%5d'), array('<', '>', '[', ']'), $s);
1808 function file_tag_file_query($table,$s,$type = 'file') {
1810 if ($type == 'file') {
1811 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1813 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1815 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1818 // ex. given music,video return <music><video> or [music][video]
1819 function file_tag_list_to_file($list,$type = 'file') {
1821 if (strlen($list)) {
1822 $list_array = explode(",",$list);
1823 if ($type == 'file') {
1831 foreach ($list_array as $item) {
1832 if (strlen($item)) {
1833 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1840 // ex. given <music><video>[friends], return music,video or friends
1841 function file_tag_file_to_list($file,$type = 'file') {
1844 if ($type == 'file') {
1845 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1847 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1850 foreach ($matches as $mtch) {
1851 if (strlen($list)) {
1854 $list .= file_tag_decode($mtch[1]);
1861 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1862 // $file_old - categories previously associated with an item
1863 // $file_new - new list of categories for an item
1865 if (!intval($uid)) {
1868 if ($file_old == $file_new) {
1872 $saved = PConfig::get($uid, 'system', 'filetags');
1873 if (strlen($saved)) {
1874 if ($type == 'file') {
1877 $termtype = TERM_FILE;
1881 $termtype = TERM_CATEGORY;
1884 $filetags_updated = $saved;
1886 // check for new tags to be added as filetags in pconfig
1887 $new_tags = array();
1888 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1890 foreach ($check_new_tags as $tag) {
1891 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1895 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1897 // check for deleted tags to be removed from filetags in pconfig
1898 $deleted_tags = array();
1899 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1901 foreach ($check_deleted_tags as $tag) {
1902 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1903 $deleted_tags[] = $tag;
1906 foreach ($deleted_tags as $key => $tag) {
1907 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1909 intval(TERM_OBJ_POST),
1913 if (DBM::is_result($r)) {
1914 unset($deleted_tags[$key]);
1916 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1920 if ($saved != $filetags_updated) {
1921 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1924 } elseif (strlen($file_new)) {
1925 PConfig::set($uid, 'system', 'filetags', $file_new);
1930 function file_tag_save_file($uid, $item, $file) {
1931 require_once "include/files.php";
1936 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1940 if (DBM::is_result($r)) {
1941 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1942 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1943 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1949 create_files_from_item($item);
1951 $saved = PConfig::get($uid, 'system', 'filetags');
1952 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1953 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1955 info(t('Item filed'));
1960 function file_tag_unsave_file($uid, $item, $file, $cat = false) {
1961 require_once "include/files.php";
1968 $pattern = '<' . file_tag_encode($file) . '>' ;
1969 $termtype = TERM_CATEGORY;
1971 $pattern = '[' . file_tag_encode($file) . ']' ;
1972 $termtype = TERM_FILE;
1976 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1980 if (! DBM::is_result($r)) {
1984 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1985 dbesc(str_replace($pattern,'',$r[0]['file'])),
1990 create_files_from_item($item);
1992 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1994 intval(TERM_OBJ_POST),
1998 if (!DBM::is_result($r)) {
1999 $saved = PConfig::get($uid, 'system', 'filetags');
2000 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
2006 function normalise_openid($s) {
2007 return trim(str_replace(array('http://', 'https://'), array('', ''), $s), '/');
2011 function undo_post_tagging($s) {
2013 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
2015 foreach ($matches as $mtch) {
2016 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2022 function protect_sprintf($s) {
2023 return str_replace('%', '%%', $s);
2027 function is_a_date_arg($s) {
2031 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2032 $m = intval(substr($s,5));
2033 if ($m > 0 && $m <= 12)
2041 * remove intentation from a text
2043 function deindent($text, $chr = "[\t ]", $count = NULL) {
2044 $lines = explode("\n", $text);
2045 if (is_null($count)) {
2048 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2051 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2052 $count = strlen($m[0]);
2054 for ($k = 0; $k < count($lines); $k++) {
2055 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2058 return implode("\n", $lines);
2061 function formatBytes($bytes, $precision = 2) {
2062 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2064 $bytes = max($bytes, 0);
2065 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2066 $pow = min($pow, count($units) - 1);
2068 $bytes /= pow(1024, $pow);
2070 return round($bytes, $precision) . ' ' . $units[$pow];
2074 * @brief translate and format the networkname of a contact
2076 * @param string $network
2077 * Networkname of the contact (e.g. dfrn, rss and so on)
2082 function format_network_name($network, $url = 0) {
2083 if ($network != "") {
2084 require_once 'include/contact_selectors.php';
2086 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2088 $network_name = network_to_name($network);
2091 return $network_name;
2097 * @brief Syntax based code highlighting for popular languages.
2098 * @param string $s Code block
2099 * @param string $lang Programming language
2100 * @return string Formated html
2102 function text_highlight($s, $lang) {
2103 if ($lang === 'js') {
2104 $lang = 'javascript';
2107 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2109 // Autoload the library to make constants available
2110 class_exists('Text_Highlighter_Renderer_Html');
2113 'numbers' => HL_NUMBERS_LI,
2118 $s = trim(html_entity_decode($s, ENT_COMPAT));
2119 $s = str_replace(' ', "\t", $s);
2122 * The highlighter library insists on an opening php tag for php code blocks. If
2123 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2124 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2126 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2127 $s = '<?php' . "\n" . $s;
2131 $renderer = new Text_Highlighter_Renderer_Html($options);
2132 $hl = Text_Highlighter::factory($lang);
2133 $hl->setRenderer($renderer);
2134 $o = $hl->highlight($s);
2135 $o = str_replace("\n", '', $o);
2138 $b = substr($o, 0, strpos($o, '<li>'));
2139 $e = substr($o, strpos($o, '</li>'));
2143 return '<code>' . $o . '</code>';