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";
13 require_once "include/conversation.php";
16 * This is our template processor
18 * @param string|FriendicaSmarty $s the string requiring macro substitution,
19 * or an instance of FriendicaSmarty
20 * @param array $r key value pairs (search => replace)
21 * @return string substituted string
23 function replace_macros($s, $r) {
25 $stamp1 = microtime(true);
29 // pass $baseurl to all templates
30 $r['$baseurl'] = System::baseUrl();
32 $t = $a->template_engine();
34 $output = $t->replaceMacros($s, $r);
35 } catch (Exception $e) {
36 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
40 $a->save_timestamp($stamp1, "rendering");
46 * @brief Generates a pseudo-random string of hexadecimal characters
51 function random_string($size = 64)
53 $byte_size = ceil($size / 2);
55 $bytes = random_bytes($byte_size);
57 $return = substr(bin2hex($bytes), 0, $size);
63 * This is our primary input filter.
65 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
66 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
67 * after cleansing, and angle chars with the high bit set could get through as markup.
69 * This is now disabled because it was interfering with some legitimate unicode sequences
70 * and hopefully there aren't a lot of those browsers left.
72 * Use this on any text input where angle chars are not valid or permitted
73 * They will be replaced with safer brackets. This may be filtered further
74 * if these are not allowed either.
76 * @param string $string Input string
77 * @return string Filtered string
79 function notags($string) {
80 return str_replace(array("<", ">"), array('[', ']'), $string);
82 // High-bit filter no longer used
83 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
88 * use this on "body" or "content" input where angle chars shouldn't be removed,
89 * and allow them to be safely displayed.
90 * @param string $string
93 function escape_tags($string) {
94 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
99 * generate a string that's random, but usually pronounceable.
100 * used to generate initial passwords
104 function autoname($len) {
110 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
111 if (mt_rand(0, 5) == 4) {
130 's','sc','sh','sm','sp','st',
138 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
139 'nd','ng','nk','nt','rn','rp','rt');
141 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
142 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
144 $start = mt_rand(0,2);
153 for ($x = 0; $x < $len; $x ++) {
154 $r = mt_rand(0,count($table) - 1);
157 if ($table == $vowels) {
158 $table = array_merge($cons,$midcons);
165 $word = substr($word,0,$len);
167 foreach ($noend as $noe) {
168 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
169 $word = substr($word, 0, -1);
173 if (substr($word, -1) == 'q') {
174 $word = substr($word, 0, -1);
181 * escape text ($str) for XML transport
183 * @return string Escaped text.
185 function xmlify($str) {
186 /// @TODO deprecated code found?
189 $len = mb_strlen($str);
190 for ($x = 0; $x < $len; $x ++) {
191 $char = mb_substr($str,$x,1);
221 $buffer = mb_ereg_replace("&", "&", $str);
222 $buffer = mb_ereg_replace("'", "'", $buffer);
223 $buffer = mb_ereg_replace('"', """, $buffer);
224 $buffer = mb_ereg_replace("<", "<", $buffer);
225 $buffer = mb_ereg_replace(">", ">", $buffer);
227 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
228 $buffer = trim($buffer);
236 * @param string $s xml escaped text
237 * @return string unescaped text
239 function unxmlify($s) {
240 /// @TODO deprecated code found?
241 // $ret = str_replace('&','&', $s);
242 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
243 /*$ret = mb_ereg_replace('&', '&', $s);
244 $ret = mb_ereg_replace(''', "'", $ret);
245 $ret = mb_ereg_replace('"', '"', $ret);
246 $ret = mb_ereg_replace('<', "<", $ret);
247 $ret = mb_ereg_replace('>', ">", $ret);
249 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
255 * @brief Paginator function. Pushes relevant links in a pager array structure.
257 * Links are generated depending on the current page and the total number of items.
258 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
259 * Current page link is given the "active" CSS class
261 * @param App $a App instance
262 * @param int $count [optional] item count (used with minimal pager)
263 * @return Array data for pagination template
265 function paginate_data(App $a, $count = null) {
266 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
268 $stripped = str_replace('q=', '', $stripped);
269 $stripped = trim($stripped, '/');
270 $pagenum = $a->pager['page'];
272 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
273 $stripped .= '&offset=' . urlencode($a->page_offset);
279 function _l(&$d, $name, $url, $text, $class = '') {
280 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
281 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
284 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
287 if (!is_null($count)) {
288 // minimal pager (newer / older)
289 $data['class'] = 'pager';
290 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
291 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
293 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
294 $data['class'] = 'pagination';
295 if ($a->pager['total'] > $a->pager['itemspage']) {
296 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
297 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
299 $numpages = $a->pager['total'] / $a->pager['itemspage'];
302 $numstop = $numpages;
304 // Limit the number of displayed page number buttons.
306 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
307 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
312 for ($i = $numstart; $i <= $numstop; $i++) {
313 if ($i == $a->pager['page']) {
314 _l($pages, $i, '#', $i, 'current active');
316 _l($pages, $i, $url . '&page='. $i, $i, 'n');
320 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
321 if ($i == $a->pager['page']) {
322 _l($pages, $i, '#', $i, 'current active');
324 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
328 $data['pages'] = $pages;
330 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
331 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
332 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
341 * Automatic pagination.
343 * To use, get the count of total items.
344 * Then call $a->set_pager_total($number_items);
345 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
346 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
347 * (assuming there are enough items to paginate).
348 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
349 * will limit the results to the correct items for the current page.
350 * The actual page handling is then accomplished at the application layer.
352 * @param App $a App instance
353 * @return string html for pagination #FIXME remove html
355 function paginate(App $a) {
357 $data = paginate_data($a);
358 $tpl = get_markup_template("paginate.tpl");
359 return replace_macros($tpl, array("pager" => $data));
366 * @param App $a App instance
368 * @return string html for pagination #FIXME remove html
370 function alt_pager(App $a, $i) {
372 $data = paginate_data($a, $i);
373 $tpl = get_markup_template("paginate.tpl");
374 return replace_macros($tpl, array('pager' => $data));
380 * Loader for infinite scrolling
381 * @return string html for loader
383 function scroll_loader() {
384 $tpl = get_markup_template("scroll_loader.tpl");
385 return replace_macros($tpl, array(
386 'wait' => t('Loading more entries...'),
387 'end' => t('The end')
393 * Turn user/group ACLs stored as angle bracketed text into arrays
398 function expand_acl($s) {
399 // turn string array of angle-bracketed elements into numeric array
400 // e.g. "<1><2><3>" => array(1,2,3);
404 $t = str_replace('<', '', $s);
405 $a = explode('>', $t);
406 foreach ($a as $aa) {
408 $ret[] = intval($aa);
417 * Wrap ACL elements in angle brackets for storage
418 * @param string $item
420 function sanitise_acl(&$item) {
422 $item = '<' . intval(notags(trim($item))) . '>';
430 * Convert an ACL array to a storable string
432 * Normally ACL permissions will be an array.
433 * We'll also allow a comma-separated string.
435 * @param string|array $p
438 function perms2str($p) {
443 $tmp = explode(',',$p);
446 if (is_array($tmp)) {
447 array_walk($tmp, 'sanitise_acl');
448 $ret = implode('', $tmp);
455 * generate a guaranteed unique (for this domain) item ID for ATOM
456 * safe from birthday paradox
458 * @param string $hostname
462 function item_new_uri($hostname, $uid, $guid = "") {
466 $hash = get_guid(32);
472 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
474 $dups = dba::exists('item', array('uri' => $uri));
475 } while ($dups == true);
482 * Generate a guaranteed unique photo ID.
483 * safe from birthday paradox
487 function photo_new_resource() {
491 $resource = hash('md5',uniqid(mt_rand(),true));
492 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
496 if (DBM::is_result($r)) {
499 } while ($found == true);
507 * wrapper to load a view template, checking for alternate
508 * languages before falling back to the default
510 * @global string $lang
512 * @param string $s view name
515 function load_view_file($s) {
517 if (! isset($lang)) {
522 if (file_exists("$d/$lang/$b")) {
523 $stamp1 = microtime(true);
524 $content = file_get_contents("$d/$lang/$b");
525 $a->save_timestamp($stamp1, "file");
529 $theme = current_theme();
531 if (file_exists("$d/theme/$theme/$b")) {
532 $stamp1 = microtime(true);
533 $content = file_get_contents("$d/theme/$theme/$b");
534 $a->save_timestamp($stamp1, "file");
538 $stamp1 = microtime(true);
539 $content = file_get_contents($s);
540 $a->save_timestamp($stamp1, "file");
546 * load a view template, checking for alternate
547 * languages before falling back to the default
549 * @global string $lang
550 * @param string $s view path
553 function get_intltext_template($s) {
558 if ($a->theme['template_engine'] === 'smarty3') {
559 $engine = "/smarty3";
562 if (! isset($lang)) {
566 if (file_exists("view/lang/$lang$engine/$s")) {
567 $stamp1 = microtime(true);
568 $content = file_get_contents("view/lang/$lang$engine/$s");
569 $a->save_timestamp($stamp1, "file");
571 } elseif (file_exists("view/lang/en$engine/$s")) {
572 $stamp1 = microtime(true);
573 $content = file_get_contents("view/lang/en$engine/$s");
574 $a->save_timestamp($stamp1, "file");
577 $stamp1 = microtime(true);
578 $content = file_get_contents("view$engine/$s");
579 $a->save_timestamp($stamp1, "file");
589 * @param string $root
592 function get_markup_template($s, $root = '') {
593 $stamp1 = microtime(true);
596 $t = $a->template_engine();
598 $template = $t->getTemplateFile($s, $root);
599 } catch (Exception $e) {
600 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
604 $a->save_timestamp($stamp1, "file");
613 * @param string $filename
614 * @param string $root
617 function get_template_file($a, $filename, $root = '') {
618 $theme = current_theme();
620 // Make sure $root ends with a slash /
621 if ($root !== '' && substr($root, -1, 1) !== '/') {
625 if (file_exists("{$root}view/theme/$theme/$filename")) {
626 $template_file = "{$root}view/theme/$theme/$filename";
627 } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
628 $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
629 } elseif (file_exists("{$root}/$filename")) {
630 $template_file = "{$root}/$filename";
632 $template_file = "{$root}view/$filename";
635 return $template_file;
640 * for html,xml parsing - let's say you've got
641 * an attribute foobar="class1 class2 class3"
642 * and you want to find out if it contains 'class3'.
643 * you can't use a normal sub string search because you
644 * might match 'notclass3' and a regex to do the job is
645 * possible but a bit complicated.
646 * pass the attribute string as $attr and the attribute you
647 * are looking for as $s - returns true if found, otherwise false
649 * @param string $attr attribute value
650 * @param string $s string to search
651 * @return boolean True if found, False otherwise
653 function attribute_contains($attr, $s) {
654 $a = explode(' ', $attr);
655 return (count($a) && in_array($s,$a));
659 /* setup int->string log level map */
660 $LOGGER_LEVELS = array();
663 * @brief Logs the given message at the given log level
666 * LOGGER_NORMAL (default)
673 * @global array $LOGGER_LEVELS
677 function logger($msg, $level = 0) {
679 global $LOGGER_LEVELS;
681 // turn off logger in install mode
683 $a->module == 'install'
689 $debugging = Config::get('system','debugging');
690 $logfile = Config::get('system','logfile');
691 $loglevel = intval(Config::get('system','loglevel'));
696 || $level > $loglevel
701 if (count($LOGGER_LEVELS) == 0) {
702 foreach (get_defined_constants() as $k => $v) {
703 if (substr($k, 0, 7) == "LOGGER_") {
704 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
709 $process_id = session_id();
711 if ($process_id == '') {
712 $process_id = get_app()->process_id;
715 $callers = debug_backtrace();
716 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
717 datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
719 $LOGGER_LEVELS[$level],
720 basename($callers[0]['file']),
722 $callers[1]['function'],
726 $stamp1 = microtime(true);
727 @file_put_contents($logfile, $logline, FILE_APPEND);
728 $a->save_timestamp($stamp1, "file");
732 * @brief An alternative logger for development.
733 * Works largely as logger() but allows developers
734 * to isolate particular elements they are targetting
735 * personally without background noise
738 * LOGGER_NORMAL (default)
745 * @global array $LOGGER_LEVELS
750 function dlogger($msg, $level = 0) {
753 // turn off logger in install mode
755 $a->module == 'install'
761 $logfile = Config::get('system','dlogfile');
767 if (count($LOGGER_LEVELS) == 0) {
768 foreach (get_defined_constants() as $k => $v) {
769 if (substr($k, 0, 7) == "LOGGER_") {
770 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
775 $process_id = session_id();
777 if ($process_id == '') {
778 $process_id = get_app()->process_id;
781 $callers = debug_backtrace();
782 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
785 basename($callers[0]['file']),
787 $callers[1]['function'],
791 $stamp1 = microtime(true);
792 @file_put_contents($logfile, $logline, FILE_APPEND);
793 $a->save_timestamp($stamp1, "file");
798 * Compare activity uri. Knows about activity namespace.
800 * @param string $haystack
801 * @param string $needle
804 function activity_match($haystack,$needle) {
805 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
810 * @brief Pull out all #hashtags and @person tags from $string.
812 * We also get @person@domain.com - which would make
813 * the regex quite complicated as tags can also
814 * end a sentence. So we'll run through our results
815 * and strip the period from any tags which end with one.
816 * Returns array of tags found, or empty array.
818 * @param string $string Post content
819 * @return array List of tag and person names
821 function get_tags($string) {
824 // Convert hashtag links to hashtags
825 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
827 // ignore anything in a code block
828 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
830 // Force line feeds at bbtags
831 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
833 // ignore anything in a bbtag
834 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
836 // Match full names against @tags including the space between first and last
837 // We will look these up afterward to see if they are full names or not recognisable.
839 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
840 foreach ($matches[1] as $match) {
841 if (strstr($match, ']')) {
842 // we might be inside a bbcode color tag - leave it alone
845 if (substr($match, -1, 1) === '.') {
846 $ret[] = substr($match, 0, -1);
853 // Otherwise pull out single word tags. These can be @nickname, @first_last
856 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
857 foreach ($matches[1] as $match) {
858 if (strstr($match, ']')) {
859 // we might be inside a bbcode color tag - leave it alone
862 if (substr($match, -1, 1) === '.') {
863 $match = substr($match,0,-1);
865 // ignore strictly numeric tags like #1
866 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
869 // try not to catch url fragments
870 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
881 * quick and dirty quoted_printable encoding
887 return str_replace("%", "=", rawurlencode($s));
892 * Get html for contact block.
894 * @template contact_block.tpl
895 * @hook contact_block_end (contacts=>array, output=>string)
898 function contact_block() {
902 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
907 if (!is_array($a->profile) || $a->profile['hide-friends']) {
910 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
911 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
912 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
913 AND `network` IN ('%s', '%s', '%s')",
914 intval($a->profile['uid']),
916 dbesc(NETWORK_OSTATUS),
917 dbesc(NETWORK_DIASPORA)
919 if (DBM::is_result($r)) {
920 $total = intval($r[0]['total']);
923 $contacts = t('No contacts');
926 // Splitting the query in two parts makes it much faster
927 $r = q("SELECT `id` FROM `contact`
928 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
929 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
930 AND `network` IN ('%s', '%s', '%s')
931 ORDER BY RAND() LIMIT %d",
932 intval($a->profile['uid']),
934 dbesc(NETWORK_OSTATUS),
935 dbesc(NETWORK_DIASPORA),
938 if (DBM::is_result($r)) {
940 foreach ($r AS $contact) {
941 $contacts[] = $contact["id"];
943 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
944 dbesc(implode(",", $contacts)));
946 if (DBM::is_result($r)) {
947 $contacts = sprintf(tt('%d Contact','%d Contacts', $total),$total);
949 foreach ($r as $rr) {
950 $micropro[] = micropro($rr,true,'mpfriend');
956 $tpl = get_markup_template('contact_block.tpl');
957 $o = replace_macros($tpl, array(
958 '$contacts' => $contacts,
959 '$nickname' => $a->profile['nickname'],
960 '$viewcontacts' => t('View Contacts'),
961 '$micropro' => $micropro,
964 $arr = array('contacts' => $r, 'output' => $o);
966 call_hooks('contact_block_end', $arr);
973 * @brief Format contacts as picture links or as texxt links
975 * @param array $contact Array with contacts which contains an array with
976 * int 'id' => The ID of the contact
977 * int 'uid' => The user ID of the user who owns this data
978 * string 'name' => The name of the contact
979 * string 'url' => The url to the profile page of the contact
980 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
981 * string 'network' => The network to which the contact belongs to
982 * string 'thumb' => The contact picture
983 * string 'click' => js code which is performed when clicking on the contact
984 * @param boolean $redirect If true try to use the redir url if it's possible
985 * @param string $class CSS class for the
986 * @param boolean $textmode If true display the contacts as text links
987 * if false display the contacts as picture links
989 * @return string Formatted html
991 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
993 // Use the contact URL if no address is available
994 if ($contact["addr"] == "") {
995 $contact["addr"] = $contact["url"];
998 $url = $contact['url'];
1004 $redirect_url = 'redir/' . $contact['id'];
1005 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1007 $url = $redirect_url;
1008 $sparkle = ' sparkle';
1014 // If there is some js available we don't need the url
1015 if (x($contact, 'click')) {
1019 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1020 '$click' => (($contact['click']) ? $contact['click'] : ''),
1023 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1024 '$name' => $contact['name'],
1025 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1026 '$parkle' => $sparkle,
1035 * @param string $s search query
1036 * @param string $id html id
1037 * @param string $url search url
1038 * @param boolean $savedsearch show save search button
1040 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true) {
1044 '$s' => htmlspecialchars($s),
1046 '$action_url' => $url,
1047 '$search_label' => t('Search'),
1048 '$save_label' => t('Save'),
1049 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1050 '$search_hint' => t('@name, !forum, #tags, content'),
1054 $values['$searchoption'] = array(
1059 if (Config::get('system','poco_local_search')) {
1060 $values['$searchoption'][] = t("Forums");
1064 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1068 * Check if $x is a valid email string
1073 function valid_email($x){
1075 /// @TODO Removed because Fabio told me so.
1076 //if (Config::get('system','disable_email_validation'))
1078 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $x);
1083 * Replace naked text hyperlink with HTML formatted hyperlink
1087 function linkify($s) {
1088 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1089 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1097 * @return array index is present tense verb
1098 value is array containing past tense verb, translation of present, translation of past
1099 * @hook poke_verbs pokes array
1101 function get_poke_verbs() {
1103 // index is present tense verb
1104 // value is array containing past tense verb, translation of present, translation of past
1107 'poke' => array('poked', t('poke'), t('poked')),
1108 'ping' => array('pinged', t('ping'), t('pinged')),
1109 'prod' => array('prodded', t('prod'), t('prodded')),
1110 'slap' => array('slapped', t('slap'), t('slapped')),
1111 'finger' => array('fingered', t('finger'), t('fingered')),
1112 'rebuff' => array('rebuffed', t('rebuff'), t('rebuffed')),
1114 call_hooks('poke_verbs', $arr);
1120 * @return array index is mood, value is translated mood
1121 * @hook mood_verbs moods array
1123 function get_mood_verbs() {
1126 'happy' => t('happy'),
1128 'mellow' => t('mellow'),
1129 'tired' => t('tired'),
1130 'perky' => t('perky'),
1131 'angry' => t('angry'),
1132 'stupefied' => t('stupified'),
1133 'puzzled' => t('puzzled'),
1134 'interested' => t('interested'),
1135 'bitter' => t('bitter'),
1136 'cheerful' => t('cheerful'),
1137 'alive' => t('alive'),
1138 'annoyed' => t('annoyed'),
1139 'anxious' => t('anxious'),
1140 'cranky' => t('cranky'),
1141 'disturbed' => t('disturbed'),
1142 'frustrated' => t('frustrated'),
1143 'motivated' => t('motivated'),
1144 'relaxed' => t('relaxed'),
1145 'surprised' => t('surprised'),
1148 call_hooks('mood_verbs', $arr);
1153 * @brief Translate days and months names.
1155 * @param string $s String with day or month name.
1156 * @return string Translated string.
1158 function day_translate($s) {
1159 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1160 array(t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1163 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1164 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')),
1171 * @brief Translate short days and months names.
1173 * @param string $s String with short day or month name.
1174 * @return string Translated string.
1176 function day_short_translate($s) {
1177 $ret = str_replace(array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'),
1178 array(t('Mon'), t('Tue'), t('Wed'), t('Thu'), t('Fri'), t('Sat'), t('Sund')),
1180 $ret = str_replace(array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'),
1181 array(t('Jan'), t('Feb'), t('Mar'), t('Apr'), t('May'), ('Jun'), t('Jul'), t('Aug'), t('Sep'), t('Oct'), t('Nov'), t('Dec')),
1190 * @param string $url
1193 function normalise_link($url) {
1194 $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
1195 return rtrim($ret,'/');
1200 * Compare two URLs to see if they are the same, but ignore
1201 * slight but hopefully insignificant differences such as if one
1202 * is https and the other isn't, or if one is www.something and
1203 * the other isn't - and also ignore case differences.
1205 * @param string $a first url
1206 * @param string $b second url
1207 * @return boolean True if the URLs match, otherwise False
1210 function link_compare($a, $b) {
1211 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1216 * @brief Find any non-embedded images in private items and add redir links to them
1219 * @param array &$item The field array of an item row
1221 function redir_private_images($a, &$item)
1224 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1226 foreach ($matches as $mtch) {
1227 if (strpos($mtch[1], '/redir') !== false) {
1231 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1232 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1233 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1239 function put_item_in_cache(&$item, $update = false) {
1241 if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
1242 ($item["rendered-html"] == "") || Config::get("system", "ignore_cache")) {
1244 // The function "redir_private_images" changes the body.
1245 // I'm not sure if we should store it permanently, so we save the old value.
1246 $body = $item["body"];
1249 redir_private_images($a, $item);
1251 $item["rendered-html"] = prepare_text($item["body"]);
1252 $item["rendered-hash"] = hash("md5", $item["body"]);
1253 $item["body"] = $body;
1255 if ($update && ($item["id"] > 0)) {
1256 dba::update('item', array('rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]),
1257 array('id' => $item["id"]), false);
1263 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1264 * If attach is true, also add icons for item attachments.
1266 * @param array $item
1267 * @param boolean $attach
1268 * @return string item body html
1269 * @hook prepare_body_init item array before any work
1270 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1271 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1273 function prepare_body(&$item, $attach = false, $preview = false) {
1276 call_hooks('prepare_body_init', $item);
1278 $searchpath = System::baseUrl() . "/search?tag=";
1281 $hashtags = array();
1282 $mentions = array();
1284 // In order to provide theme developers more possibilities, event items
1285 // are treated differently.
1286 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1287 $ev = format_event_item($item);
1291 if (!Config::get('system','suppress_tags')) {
1292 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1293 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1295 while ($tag = dba::fetch($taglist)) {
1296 if ($tag["url"] == "") {
1297 $tag["url"] = $searchpath.strtolower($tag["term"]);
1300 $orig_tag = $tag["url"];
1302 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1304 if ($tag["type"] == TERM_HASHTAG) {
1305 if ($orig_tag != $tag["url"]) {
1306 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1308 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1310 } elseif ($tag["type"] == TERM_MENTION) {
1311 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1314 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1316 dba::close($taglist);
1319 $item['tags'] = $tags;
1320 $item['hashtags'] = $hashtags;
1321 $item['mentions'] = $mentions;
1323 // Update the cached values if there is no "zrl=..." on the links.
1324 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1326 // Or update it if the current viewer is the intented viewer.
1327 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1331 put_item_in_cache($item, $update);
1332 $s = $item["rendered-html"];
1334 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1335 call_hooks('prepare_body', $prep_arr);
1336 $s = $prep_arr['html'];
1339 // Replace the blockquotes with quotes that are used in mails.
1340 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1341 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1347 $arr = explode('[/attach],', $item['attach']);
1349 foreach ($arr as $r) {
1352 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1354 foreach ($matches as $mtch) {
1357 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1358 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1360 $the_url = $mtch[1];
1363 if (strpos($mime, 'video') !== false) {
1366 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1367 '$baseurl' => System::baseUrl(),
1369 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1370 '$baseurl' => System::baseUrl(),
1374 $id = end(explode('/', $the_url));
1375 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1378 'title' => t('View Video'),
1385 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1387 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1388 $filesubtype = str_replace('.', '-', $filesubtype);
1391 $filesubtype = 'unkn';
1394 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1395 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1397 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1398 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1404 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1408 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1409 $x = generate_map(trim($item['coord']));
1411 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1416 // Look for spoiler.
1417 $spoilersearch = '<blockquote class="spoiler">';
1419 // Remove line breaks before the spoiler.
1420 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1421 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1423 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1424 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1427 while ((strpos($s, $spoilersearch) !== false)) {
1428 $pos = strpos($s, $spoilersearch);
1429 $rnd = random_string(8);
1430 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1431 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1432 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1435 // Look for quote with author.
1436 $authorsearch = '<blockquote class="author">';
1438 while ((strpos($s, $authorsearch) !== false)) {
1439 $pos = strpos($s, $authorsearch);
1440 $rnd = random_string(8);
1441 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1442 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1443 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1446 // Replace friendica image url size with theme preference.
1447 if (x($a->theme_info, 'item_image_size')){
1448 $ps = $a->theme_info['item_image_size'];
1449 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1452 $prep_arr = array('item' => $item, 'html' => $s);
1453 call_hooks('prepare_body_final', $prep_arr);
1455 return $prep_arr['html'];
1459 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1461 * @param string $text String with bbcode.
1462 * @return string Formattet HTML.
1464 function prepare_text($text) {
1466 require_once 'include/bbcode.php';
1468 if (stristr($text, '[nosmile]')) {
1471 $s = Smilies::replace(bbcode($text));
1478 * return array with details for categories and folders for an item
1480 * @param array $item
1484 * [ // categories array
1486 * 'name': 'category name',
1487 * 'removeurl': 'url to remove this category',
1488 * 'first': 'is the first in this array? true/false',
1489 * 'last': 'is the last in this array? true/false',
1495 * 'name': 'folder name',
1496 * 'removeurl': 'url to remove this folder',
1497 * 'first': 'is the first in this array? true/false',
1498 * 'last': 'is the last in this array? true/false',
1504 function get_cats_and_terms($item) {
1507 $categories = array();
1512 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1514 foreach ($matches as $mtch) {
1515 $categories[] = array(
1516 'name' => xmlify(file_tag_decode($mtch[1])),
1518 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1526 if (count($categories)) {
1527 $categories[count($categories) - 1]['last'] = true;
1530 if (local_user() == $item['uid']) {
1533 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1535 foreach ($matches as $mtch) {
1537 'name' => xmlify(file_tag_decode($mtch[1])),
1539 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1548 if (count($folders)) {
1549 $folders[count($folders) - 1]['last'] = true;
1552 return array($categories, $folders);
1557 * get private link for item
1558 * @param array $item
1559 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1561 function get_plink($item) {
1564 if ($a->user['nickname'] != "") {
1566 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1567 'href' => "display/" . $item['guid'],
1568 'orig' => "display/" . $item['guid'],
1569 'title' => t('View on separate page'),
1570 'orig_title' => t('view on separate page'),
1573 if (x($item, 'plink')) {
1574 $ret["href"] = $a->remove_baseurl($item['plink']);
1575 $ret["title"] = t('link to source');
1578 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1580 'href' => $item['plink'],
1581 'orig' => $item['plink'],
1582 'title' => t('link to source'),
1593 * replace html amp entity with amp char
1597 function unamp($s) {
1598 return str_replace('&', '&', $s);
1603 * return number of bytes in size (K, M, G)
1604 * @param string $size_str
1607 function return_bytes($size_str) {
1608 switch (substr ($size_str, -1)) {
1609 case 'M': case 'm': return (int)$size_str * 1048576;
1610 case 'K': case 'k': return (int)$size_str * 1024;
1611 case 'G': case 'g': return (int)$size_str * 1073741824;
1612 default: return $size_str;
1620 function generate_user_guid() {
1623 $guid = get_guid(32);
1624 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1627 if (! DBM::is_result($x)) {
1630 } while ($found == true);
1638 * @param boolean $strip_padding
1641 function base64url_encode($s, $strip_padding = false) {
1643 $s = strtr(base64_encode($s), '+/', '-_');
1645 if ($strip_padding) {
1646 $s = str_replace('=','',$s);
1656 function base64url_decode($s) {
1659 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1664 * // Placeholder for new rev of salmon which strips base64 padding.
1665 * // PHP base64_decode handles the un-padded input without requiring this step
1666 * // Uncomment if you find you need it.
1669 * if (! strpos($s,'=')) {
1679 return base64_decode(strtr($s,'-_','+/'));
1684 * return div element with class 'clear'
1688 function cleardiv() {
1689 return '<div class="clear"></div>';
1693 function bb_translate_video($s) {
1696 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1698 foreach ($matches as $mtch) {
1699 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1700 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1701 elseif (stristr($mtch[1],'vimeo'))
1702 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1708 function html2bb_video($s) {
1710 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1711 '[youtube]$2[/youtube]', $s);
1713 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1714 '[youtube]$2[/youtube]', $s);
1716 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1717 '[vimeo]$2[/vimeo]', $s);
1723 * apply xmlify() to all values of array $val, recursively
1727 function array_xmlify($val){
1728 if (is_bool($val)) {
1729 return $val?"true":"false";
1730 } elseif (is_array($val)) {
1731 return array_map('array_xmlify', $val);
1733 return xmlify((string) $val);
1738 * transorm link href and img src from relative to absolute
1740 * @param string $text
1741 * @param string $base base url
1744 function reltoabs($text, $base) {
1749 $base = rtrim($base,'/');
1751 $base2 = $base . "/";
1754 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1755 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1756 $text = preg_replace($pattern, $replace, $text);
1758 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1759 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1760 $text = preg_replace($pattern, $replace, $text);
1763 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1764 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1765 $text = preg_replace($pattern, $replace, $text);
1767 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1768 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1769 $text = preg_replace($pattern, $replace, $text);
1777 * get translated item type
1779 * @param array $itme
1782 function item_post_type($item) {
1783 if (intval($item['event-id'])) {
1785 } elseif (strlen($item['resource-id'])) {
1787 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1788 return t('activity');
1789 } elseif ($item['id'] != $item['parent']) {
1790 return t('comment');
1796 // post categories and "save to file" use the same item.file table for storage.
1797 // We will differentiate the different uses by wrapping categories in angle brackets
1798 // and save to file categories in square brackets.
1799 // To do this we need to escape these characters if they appear in our tag.
1801 function file_tag_encode($s) {
1802 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1805 function file_tag_decode($s) {
1806 return str_replace(array('%3c', '%3e', '%5b', '%5d'), array('<', '>', '[', ']'), $s);
1809 function file_tag_file_query($table,$s,$type = 'file') {
1811 if ($type == 'file') {
1812 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1814 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1816 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1819 // ex. given music,video return <music><video> or [music][video]
1820 function file_tag_list_to_file($list,$type = 'file') {
1822 if (strlen($list)) {
1823 $list_array = explode(",",$list);
1824 if ($type == 'file') {
1832 foreach ($list_array as $item) {
1833 if (strlen($item)) {
1834 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1841 // ex. given <music><video>[friends], return music,video or friends
1842 function file_tag_file_to_list($file,$type = 'file') {
1845 if ($type == 'file') {
1846 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1848 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1851 foreach ($matches as $mtch) {
1852 if (strlen($list)) {
1855 $list .= file_tag_decode($mtch[1]);
1862 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1863 // $file_old - categories previously associated with an item
1864 // $file_new - new list of categories for an item
1866 if (!intval($uid)) {
1869 if ($file_old == $file_new) {
1873 $saved = PConfig::get($uid, 'system', 'filetags');
1874 if (strlen($saved)) {
1875 if ($type == 'file') {
1878 $termtype = TERM_FILE;
1882 $termtype = TERM_CATEGORY;
1885 $filetags_updated = $saved;
1887 // check for new tags to be added as filetags in pconfig
1888 $new_tags = array();
1889 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1891 foreach ($check_new_tags as $tag) {
1892 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1896 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1898 // check for deleted tags to be removed from filetags in pconfig
1899 $deleted_tags = array();
1900 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1902 foreach ($check_deleted_tags as $tag) {
1903 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1904 $deleted_tags[] = $tag;
1907 foreach ($deleted_tags as $key => $tag) {
1908 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1910 intval(TERM_OBJ_POST),
1914 if (DBM::is_result($r)) {
1915 unset($deleted_tags[$key]);
1917 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1921 if ($saved != $filetags_updated) {
1922 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1925 } elseif (strlen($file_new)) {
1926 PConfig::set($uid, 'system', 'filetags', $file_new);
1931 function file_tag_save_file($uid, $item, $file) {
1932 require_once "include/files.php";
1937 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1941 if (DBM::is_result($r)) {
1942 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1943 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1944 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1950 create_files_from_item($item);
1952 $saved = PConfig::get($uid, 'system', 'filetags');
1953 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1954 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1956 info(t('Item filed'));
1961 function file_tag_unsave_file($uid, $item, $file, $cat = false) {
1962 require_once "include/files.php";
1969 $pattern = '<' . file_tag_encode($file) . '>' ;
1970 $termtype = TERM_CATEGORY;
1972 $pattern = '[' . file_tag_encode($file) . ']' ;
1973 $termtype = TERM_FILE;
1977 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1981 if (! DBM::is_result($r)) {
1985 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1986 dbesc(str_replace($pattern,'',$r[0]['file'])),
1991 create_files_from_item($item);
1993 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1995 intval(TERM_OBJ_POST),
1999 if (!DBM::is_result($r)) {
2000 $saved = PConfig::get($uid, 'system', 'filetags');
2001 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
2007 function normalise_openid($s) {
2008 return trim(str_replace(array('http://', 'https://'), array('', ''), $s), '/');
2012 function undo_post_tagging($s) {
2014 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
2016 foreach ($matches as $mtch) {
2017 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2023 function protect_sprintf($s) {
2024 return str_replace('%', '%%', $s);
2028 function is_a_date_arg($s) {
2032 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2033 $m = intval(substr($s,5));
2034 if ($m > 0 && $m <= 12)
2042 * remove intentation from a text
2044 function deindent($text, $chr = "[\t ]", $count = NULL) {
2045 $lines = explode("\n", $text);
2046 if (is_null($count)) {
2049 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2052 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2053 $count = strlen($m[0]);
2055 for ($k = 0; $k < count($lines); $k++) {
2056 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2059 return implode("\n", $lines);
2062 function formatBytes($bytes, $precision = 2) {
2063 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2065 $bytes = max($bytes, 0);
2066 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2067 $pow = min($pow, count($units) - 1);
2069 $bytes /= pow(1024, $pow);
2071 return round($bytes, $precision) . ' ' . $units[$pow];
2075 * @brief translate and format the networkname of a contact
2077 * @param string $network
2078 * Networkname of the contact (e.g. dfrn, rss and so on)
2083 function format_network_name($network, $url = 0) {
2084 if ($network != "") {
2085 require_once 'include/contact_selectors.php';
2087 $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
2089 $network_name = network_to_name($network);
2092 return $network_name;
2098 * @brief Syntax based code highlighting for popular languages.
2099 * @param string $s Code block
2100 * @param string $lang Programming language
2101 * @return string Formated html
2103 function text_highlight($s, $lang) {
2104 if ($lang === 'js') {
2105 $lang = 'javascript';
2108 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2110 // Autoload the library to make constants available
2111 class_exists('Text_Highlighter_Renderer_Html');
2114 'numbers' => HL_NUMBERS_LI,
2119 $s = trim(html_entity_decode($s, ENT_COMPAT));
2120 $s = str_replace(' ', "\t", $s);
2123 * The highlighter library insists on an opening php tag for php code blocks. If
2124 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2125 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2127 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2128 $s = '<?php' . "\n" . $s;
2132 $renderer = new Text_Highlighter_Renderer_Html($options);
2133 $hl = Text_Highlighter::factory($lang);
2134 $hl->setRenderer($renderer);
2135 $o = $hl->highlight($s);
2136 $o = str_replace("\n", '', $o);
2139 $b = substr($o, 0, strpos($o, '<li>'));
2140 $e = substr($o, strpos($o, '</li>'));
2144 return '<code>' . $o . '</code>';