3 * @file include/text.php
6 use Friendica\Content\ContactSelector;
7 use Friendica\Content\Feature;
8 use Friendica\Content\Smilies;
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Util\Map;
15 require_once "include/friendica_smarty.php";
16 require_once "mod/proxy.php";
17 require_once "include/conversation.php";
20 * This is our template processor
22 * @param string|FriendicaSmarty $s the string requiring macro substitution,
23 * or an instance of FriendicaSmarty
24 * @param array $r key value pairs (search => replace)
25 * @return string substituted string
27 function replace_macros($s, $r) {
29 $stamp1 = microtime(true);
33 // pass $baseurl to all templates
34 $r['$baseurl'] = System::baseUrl();
36 $t = $a->template_engine();
38 $output = $t->replaceMacros($s, $r);
39 } catch (Exception $e) {
40 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
44 $a->save_timestamp($stamp1, "rendering");
50 * @brief Generates a pseudo-random string of hexadecimal characters
55 function random_string($size = 64)
57 $byte_size = ceil($size / 2);
59 $bytes = random_bytes($byte_size);
61 $return = substr(bin2hex($bytes), 0, $size);
67 * This is our primary input filter.
69 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
70 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
71 * after cleansing, and angle chars with the high bit set could get through as markup.
73 * This is now disabled because it was interfering with some legitimate unicode sequences
74 * and hopefully there aren't a lot of those browsers left.
76 * Use this on any text input where angle chars are not valid or permitted
77 * They will be replaced with safer brackets. This may be filtered further
78 * if these are not allowed either.
80 * @param string $string Input string
81 * @return string Filtered string
83 function notags($string) {
84 return str_replace(array("<", ">"), array('[', ']'), $string);
86 // High-bit filter no longer used
87 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
92 * use this on "body" or "content" input where angle chars shouldn't be removed,
93 * and allow them to be safely displayed.
94 * @param string $string
97 function escape_tags($string) {
98 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
103 * generate a string that's random, but usually pronounceable.
104 * used to generate initial passwords
108 function autoname($len) {
114 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
115 if (mt_rand(0, 5) == 4) {
134 's','sc','sh','sm','sp','st',
142 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
143 'nd','ng','nk','nt','rn','rp','rt');
145 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
146 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
148 $start = mt_rand(0,2);
157 for ($x = 0; $x < $len; $x ++) {
158 $r = mt_rand(0,count($table) - 1);
161 if ($table == $vowels) {
162 $table = array_merge($cons,$midcons);
169 $word = substr($word,0,$len);
171 foreach ($noend as $noe) {
172 if ((strlen($word) > 2) && (substr($word, -2) == $noe)) {
173 $word = substr($word, 0, -1);
177 if (substr($word, -1) == 'q') {
178 $word = substr($word, 0, -1);
185 * escape text ($str) for XML transport
187 * @return string Escaped text.
189 function xmlify($str) {
190 /// @TODO deprecated code found?
193 $len = mb_strlen($str);
194 for ($x = 0; $x < $len; $x ++) {
195 $char = mb_substr($str,$x,1);
225 $buffer = mb_ereg_replace("&", "&", $str);
226 $buffer = mb_ereg_replace("'", "'", $buffer);
227 $buffer = mb_ereg_replace('"', """, $buffer);
228 $buffer = mb_ereg_replace("<", "<", $buffer);
229 $buffer = mb_ereg_replace(">", ">", $buffer);
231 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
232 $buffer = trim($buffer);
240 * @param string $s xml escaped text
241 * @return string unescaped text
243 function unxmlify($s) {
244 /// @TODO deprecated code found?
245 // $ret = str_replace('&','&', $s);
246 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
247 /*$ret = mb_ereg_replace('&', '&', $s);
248 $ret = mb_ereg_replace(''', "'", $ret);
249 $ret = mb_ereg_replace('"', '"', $ret);
250 $ret = mb_ereg_replace('<', "<", $ret);
251 $ret = mb_ereg_replace('>', ">", $ret);
253 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
259 * @brief Paginator function. Pushes relevant links in a pager array structure.
261 * Links are generated depending on the current page and the total number of items.
262 * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
263 * Current page link is given the "active" CSS class
265 * @param App $a App instance
266 * @param int $count [optional] item count (used with minimal pager)
267 * @return Array data for pagination template
269 function paginate_data(App $a, $count = null) {
270 $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
272 $stripped = str_replace('q=', '', $stripped);
273 $stripped = trim($stripped, '/');
274 $pagenum = $a->pager['page'];
276 if (($a->page_offset != '') && !preg_match('/[?&].offset=/', $stripped)) {
277 $stripped .= '&offset=' . urlencode($a->page_offset);
283 function _l(&$d, $name, $url, $text, $class = '') {
284 if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
285 $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
288 $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
291 if (!is_null($count)) {
292 // minimal pager (newer / older)
293 $data['class'] = 'pager';
294 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
295 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
297 // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
298 $data['class'] = 'pagination';
299 if ($a->pager['total'] > $a->pager['itemspage']) {
300 _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
301 _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
303 $numpages = $a->pager['total'] / $a->pager['itemspage'];
306 $numstop = $numpages;
308 // Limit the number of displayed page number buttons.
310 $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
311 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
316 for ($i = $numstart; $i <= $numstop; $i++) {
317 if ($i == $a->pager['page']) {
318 _l($pages, $i, '#', $i, 'current active');
320 _l($pages, $i, $url . '&page='. $i, $i, 'n');
324 if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
325 if ($i == $a->pager['page']) {
326 _l($pages, $i, '#', $i, 'current active');
328 _l($pages, $i, $url . '&page=' . $i, $i, 'n');
332 $data['pages'] = $pages;
334 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
335 _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
336 _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
345 * Automatic pagination.
347 * To use, get the count of total items.
348 * Then call $a->set_pager_total($number_items);
349 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
350 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
351 * (assuming there are enough items to paginate).
352 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
353 * will limit the results to the correct items for the current page.
354 * The actual page handling is then accomplished at the application layer.
356 * @param App $a App instance
357 * @return string html for pagination #FIXME remove html
359 function paginate(App $a) {
361 $data = paginate_data($a);
362 $tpl = get_markup_template("paginate.tpl");
363 return replace_macros($tpl, array("pager" => $data));
370 * @param App $a App instance
372 * @return string html for pagination #FIXME remove html
374 function alt_pager(App $a, $i) {
376 $data = paginate_data($a, $i);
377 $tpl = get_markup_template("paginate.tpl");
378 return replace_macros($tpl, array('pager' => $data));
384 * Loader for infinite scrolling
385 * @return string html for loader
387 function scroll_loader() {
388 $tpl = get_markup_template("scroll_loader.tpl");
389 return replace_macros($tpl, array(
390 'wait' => t('Loading more entries...'),
391 'end' => t('The end')
397 * Turn user/group ACLs stored as angle bracketed text into arrays
402 function expand_acl($s) {
403 // turn string array of angle-bracketed elements into numeric array
404 // e.g. "<1><2><3>" => array(1,2,3);
408 $t = str_replace('<', '', $s);
409 $a = explode('>', $t);
410 foreach ($a as $aa) {
412 $ret[] = intval($aa);
421 * Wrap ACL elements in angle brackets for storage
422 * @param string $item
424 function sanitise_acl(&$item) {
426 $item = '<' . intval(notags(trim($item))) . '>';
434 * Convert an ACL array to a storable string
436 * Normally ACL permissions will be an array.
437 * We'll also allow a comma-separated string.
439 * @param string|array $p
442 function perms2str($p) {
447 $tmp = explode(',',$p);
450 if (is_array($tmp)) {
451 array_walk($tmp, 'sanitise_acl');
452 $ret = implode('', $tmp);
459 * generate a guaranteed unique (for this domain) item ID for ATOM
460 * safe from birthday paradox
462 * @param string $hostname
466 function item_new_uri($hostname, $uid, $guid = "") {
470 $hash = get_guid(32);
476 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
478 $dups = dba::exists('item', array('uri' => $uri));
479 } while ($dups == true);
486 * Generate a guaranteed unique photo ID.
487 * safe from birthday paradox
491 function photo_new_resource() {
495 $resource = hash('md5',uniqid(mt_rand(),true));
496 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
500 if (DBM::is_result($r)) {
503 } while ($found == true);
511 * wrapper to load a view template, checking for alternate
512 * languages before falling back to the default
514 * @global string $lang
516 * @param string $s view name
519 function load_view_file($s) {
521 if (! isset($lang)) {
526 if (file_exists("$d/$lang/$b")) {
527 $stamp1 = microtime(true);
528 $content = file_get_contents("$d/$lang/$b");
529 $a->save_timestamp($stamp1, "file");
533 $theme = current_theme();
535 if (file_exists("$d/theme/$theme/$b")) {
536 $stamp1 = microtime(true);
537 $content = file_get_contents("$d/theme/$theme/$b");
538 $a->save_timestamp($stamp1, "file");
542 $stamp1 = microtime(true);
543 $content = file_get_contents($s);
544 $a->save_timestamp($stamp1, "file");
550 * load a view template, checking for alternate
551 * languages before falling back to the default
553 * @global string $lang
554 * @param string $s view path
557 function get_intltext_template($s) {
562 if ($a->theme['template_engine'] === 'smarty3') {
563 $engine = "/smarty3";
566 if (! isset($lang)) {
570 if (file_exists("view/lang/$lang$engine/$s")) {
571 $stamp1 = microtime(true);
572 $content = file_get_contents("view/lang/$lang$engine/$s");
573 $a->save_timestamp($stamp1, "file");
575 } elseif (file_exists("view/lang/en$engine/$s")) {
576 $stamp1 = microtime(true);
577 $content = file_get_contents("view/lang/en$engine/$s");
578 $a->save_timestamp($stamp1, "file");
581 $stamp1 = microtime(true);
582 $content = file_get_contents("view$engine/$s");
583 $a->save_timestamp($stamp1, "file");
593 * @param string $root
596 function get_markup_template($s, $root = '') {
597 $stamp1 = microtime(true);
600 $t = $a->template_engine();
602 $template = $t->getTemplateFile($s, $root);
603 } catch (Exception $e) {
604 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
608 $a->save_timestamp($stamp1, "file");
617 * @param string $filename
618 * @param string $root
621 function get_template_file($a, $filename, $root = '') {
622 $theme = current_theme();
624 // Make sure $root ends with a slash /
625 if ($root !== '' && substr($root, -1, 1) !== '/') {
629 if (file_exists("{$root}view/theme/$theme/$filename")) {
630 $template_file = "{$root}view/theme/$theme/$filename";
631 } elseif (x($a->theme_info, "extends") && file_exists(sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename))) {
632 $template_file = sprintf('%sview/theme/%s}/%s', $root, $a->theme_info["extends"], $filename);
633 } elseif (file_exists("{$root}/$filename")) {
634 $template_file = "{$root}/$filename";
636 $template_file = "{$root}view/$filename";
639 return $template_file;
644 * for html,xml parsing - let's say you've got
645 * an attribute foobar="class1 class2 class3"
646 * and you want to find out if it contains 'class3'.
647 * you can't use a normal sub string search because you
648 * might match 'notclass3' and a regex to do the job is
649 * possible but a bit complicated.
650 * pass the attribute string as $attr and the attribute you
651 * are looking for as $s - returns true if found, otherwise false
653 * @param string $attr attribute value
654 * @param string $s string to search
655 * @return boolean True if found, False otherwise
657 function attribute_contains($attr, $s) {
658 $a = explode(' ', $attr);
659 return (count($a) && in_array($s,$a));
663 /* setup int->string log level map */
664 $LOGGER_LEVELS = array();
667 * @brief Logs the given message at the given log level
670 * LOGGER_NORMAL (default)
677 * @global array $LOGGER_LEVELS
681 function logger($msg, $level = 0) {
683 global $LOGGER_LEVELS;
685 // turn off logger in install mode
687 $a->module == 'install'
693 $debugging = Config::get('system','debugging');
694 $logfile = Config::get('system','logfile');
695 $loglevel = intval(Config::get('system','loglevel'));
700 || $level > $loglevel
705 if (count($LOGGER_LEVELS) == 0) {
706 foreach (get_defined_constants() as $k => $v) {
707 if (substr($k, 0, 7) == "LOGGER_") {
708 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
713 $process_id = session_id();
715 if ($process_id == '') {
716 $process_id = get_app()->process_id;
719 $callers = debug_backtrace();
720 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
721 datetime_convert('UTC', 'UTC', 'now', 'Y-m-d\TH:i:s\Z'),
723 $LOGGER_LEVELS[$level],
724 basename($callers[0]['file']),
726 $callers[1]['function'],
730 $stamp1 = microtime(true);
731 @file_put_contents($logfile, $logline, FILE_APPEND);
732 $a->save_timestamp($stamp1, "file");
736 * @brief An alternative logger for development.
737 * Works largely as logger() but allows developers
738 * to isolate particular elements they are targetting
739 * personally without background noise
742 * LOGGER_NORMAL (default)
749 * @global array $LOGGER_LEVELS
754 function dlogger($msg, $level = 0) {
757 // turn off logger in install mode
759 $a->module == 'install'
765 $logfile = Config::get('system','dlogfile');
771 if (count($LOGGER_LEVELS) == 0) {
772 foreach (get_defined_constants() as $k => $v) {
773 if (substr($k, 0, 7) == "LOGGER_") {
774 $LOGGER_LEVELS[$v] = substr($k, 7, 7);
779 $process_id = session_id();
781 if ($process_id == '') {
782 $process_id = get_app()->process_id;
785 $callers = debug_backtrace();
786 $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
789 basename($callers[0]['file']),
791 $callers[1]['function'],
795 $stamp1 = microtime(true);
796 @file_put_contents($logfile, $logline, FILE_APPEND);
797 $a->save_timestamp($stamp1, "file");
802 * Compare activity uri. Knows about activity namespace.
804 * @param string $haystack
805 * @param string $needle
808 function activity_match($haystack,$needle) {
809 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
814 * @brief Pull out all #hashtags and @person tags from $string.
816 * We also get @person@domain.com - which would make
817 * the regex quite complicated as tags can also
818 * end a sentence. So we'll run through our results
819 * and strip the period from any tags which end with one.
820 * Returns array of tags found, or empty array.
822 * @param string $string Post content
823 * @return array List of tag and person names
825 function get_tags($string) {
828 // Convert hashtag links to hashtags
829 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
831 // ignore anything in a code block
832 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
834 // Force line feeds at bbtags
835 $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
837 // ignore anything in a bbtag
838 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
840 // Match full names against @tags including the space between first and last
841 // We will look these up afterward to see if they are full names or not recognisable.
843 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
844 foreach ($matches[1] as $match) {
845 if (strstr($match, ']')) {
846 // we might be inside a bbcode color tag - leave it alone
849 if (substr($match, -1, 1) === '.') {
850 $ret[] = substr($match, 0, -1);
857 // Otherwise pull out single word tags. These can be @nickname, @first_last
860 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
861 foreach ($matches[1] as $match) {
862 if (strstr($match, ']')) {
863 // we might be inside a bbcode color tag - leave it alone
866 if (substr($match, -1, 1) === '.') {
867 $match = substr($match,0,-1);
869 // ignore strictly numeric tags like #1
870 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
873 // try not to catch url fragments
874 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
885 * quick and dirty quoted_printable encoding
891 return str_replace("%", "=", rawurlencode($s));
896 * Get html for contact block.
898 * @template contact_block.tpl
899 * @hook contact_block_end (contacts=>array, output=>string)
902 function contact_block() {
906 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
911 if (!is_array($a->profile) || $a->profile['hide-friends']) {
914 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
915 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
916 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
917 AND `network` IN ('%s', '%s', '%s')",
918 intval($a->profile['uid']),
920 dbesc(NETWORK_OSTATUS),
921 dbesc(NETWORK_DIASPORA)
923 if (DBM::is_result($r)) {
924 $total = intval($r[0]['total']);
927 $contacts = t('No contacts');
930 // Splitting the query in two parts makes it much faster
931 $r = q("SELECT `id` FROM `contact`
932 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
933 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
934 AND `network` IN ('%s', '%s', '%s')
935 ORDER BY RAND() LIMIT %d",
936 intval($a->profile['uid']),
938 dbesc(NETWORK_OSTATUS),
939 dbesc(NETWORK_DIASPORA),
942 if (DBM::is_result($r)) {
944 foreach ($r AS $contact) {
945 $contacts[] = $contact["id"];
947 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
948 dbesc(implode(",", $contacts)));
950 if (DBM::is_result($r)) {
951 $contacts = sprintf(tt('%d Contact','%d Contacts', $total),$total);
953 foreach ($r as $rr) {
954 $micropro[] = micropro($rr,true,'mpfriend');
960 $tpl = get_markup_template('contact_block.tpl');
961 $o = replace_macros($tpl, array(
962 '$contacts' => $contacts,
963 '$nickname' => $a->profile['nickname'],
964 '$viewcontacts' => t('View Contacts'),
965 '$micropro' => $micropro,
968 $arr = array('contacts' => $r, 'output' => $o);
970 call_hooks('contact_block_end', $arr);
977 * @brief Format contacts as picture links or as texxt links
979 * @param array $contact Array with contacts which contains an array with
980 * int 'id' => The ID of the contact
981 * int 'uid' => The user ID of the user who owns this data
982 * string 'name' => The name of the contact
983 * string 'url' => The url to the profile page of the contact
984 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
985 * string 'network' => The network to which the contact belongs to
986 * string 'thumb' => The contact picture
987 * string 'click' => js code which is performed when clicking on the contact
988 * @param boolean $redirect If true try to use the redir url if it's possible
989 * @param string $class CSS class for the
990 * @param boolean $textmode If true display the contacts as text links
991 * if false display the contacts as picture links
993 * @return string Formatted html
995 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
997 // Use the contact URL if no address is available
998 if (!x($contact, "addr")) {
999 $contact["addr"] = $contact["url"];
1002 $url = $contact['url'];
1007 $redirect_url = 'redir/' . $contact['id'];
1008 if (local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
1010 $url = $redirect_url;
1011 $sparkle = ' sparkle';
1017 // If there is some js available we don't need the url
1018 if (x($contact, 'click')) {
1022 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
1023 '$click' => defaults($contact, 'click', ''),
1026 '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
1027 '$name' => $contact['name'],
1028 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
1029 '$parkle' => $sparkle,
1038 * @param string $s search query
1039 * @param string $id html id
1040 * @param string $url search url
1041 * @param boolean $savedsearch show save search button
1043 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true) {
1045 '$s' => htmlspecialchars($s),
1047 '$action_url' => $url,
1048 '$search_label' => t('Search'),
1049 '$save_label' => t('Save'),
1050 '$savedsearch' => Feature::isEnabled(local_user(),'savedsearch'),
1051 '$search_hint' => t('@name, !forum, #tags, content'),
1055 $values['$searchoption'] = array(
1060 if (Config::get('system','poco_local_search')) {
1061 $values['$searchoption'][] = t("Forums");
1065 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1069 * @brief Check for a valid email string
1071 * @param string $email_address
1074 function valid_email($email_address)
1076 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
1081 * Replace naked text hyperlink with HTML formatted hyperlink
1085 function linkify($s) {
1086 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1087 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1095 * @return array index is present tense verb
1096 value is array containing past tense verb, translation of present, translation of past
1097 * @hook poke_verbs pokes array
1099 function get_poke_verbs() {
1101 // index is present tense verb
1102 // value is array containing past tense verb, translation of present, translation of past
1105 'poke' => array('poked', t('poke'), t('poked')),
1106 'ping' => array('pinged', t('ping'), t('pinged')),
1107 'prod' => array('prodded', t('prod'), t('prodded')),
1108 'slap' => array('slapped', t('slap'), t('slapped')),
1109 'finger' => array('fingered', t('finger'), t('fingered')),
1110 'rebuff' => array('rebuffed', t('rebuff'), t('rebuffed')),
1112 call_hooks('poke_verbs', $arr);
1117 * @brief Translate days and months names.
1119 * @param string $s String with day or month name.
1120 * @return string Translated string.
1122 function day_translate($s) {
1123 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1124 array(t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1127 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1128 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')),
1135 * @brief Translate short days and months names.
1137 * @param string $s String with short day or month name.
1138 * @return string Translated string.
1140 function day_short_translate($s) {
1141 $ret = str_replace(array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'),
1142 array(t('Mon'), t('Tue'), t('Wed'), t('Thu'), t('Fri'), t('Sat'), t('Sun')),
1144 $ret = str_replace(array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'),
1145 array(t('Jan'), t('Feb'), t('Mar'), t('Apr'), t('May'), ('Jun'), t('Jul'), t('Aug'), t('Sep'), t('Oct'), t('Nov'), t('Dec')),
1154 * @param string $url
1157 function normalise_link($url) {
1158 $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);
1159 return rtrim($ret,'/');
1164 * Compare two URLs to see if they are the same, but ignore
1165 * slight but hopefully insignificant differences such as if one
1166 * is https and the other isn't, or if one is www.something and
1167 * the other isn't - and also ignore case differences.
1169 * @param string $a first url
1170 * @param string $b second url
1171 * @return boolean True if the URLs match, otherwise False
1174 function link_compare($a, $b) {
1175 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
1180 * @brief Find any non-embedded images in private items and add redir links to them
1183 * @param array &$item The field array of an item row
1185 function redir_private_images($a, &$item)
1188 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1190 foreach ($matches as $mtch) {
1191 if (strpos($mtch[1], '/redir') !== false) {
1195 if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1196 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
1197 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
1203 function put_item_in_cache(&$item, $update = false)
1205 $rendered_hash = defaults($item, 'rendered-hash', '');
1207 if ($rendered_hash == ''
1208 || $item["rendered-html"] == ""
1209 || $rendered_hash != hash("md5", $item["body"])
1210 || Config::get("system", "ignore_cache")
1212 // The function "redir_private_images" changes the body.
1213 // I'm not sure if we should store it permanently, so we save the old value.
1214 $body = $item["body"];
1217 redir_private_images($a, $item);
1219 $item["rendered-html"] = prepare_text($item["body"]);
1220 $item["rendered-hash"] = hash("md5", $item["body"]);
1221 $item["body"] = $body;
1223 if ($update && ($item["id"] > 0)) {
1224 dba::update('item', array('rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]),
1225 array('id' => $item["id"]), false);
1231 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
1232 * If attach is true, also add icons for item attachments.
1234 * @param array $item
1235 * @param boolean $attach
1236 * @return string item body html
1237 * @hook prepare_body_init item array before any work
1238 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1239 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1241 function prepare_body(&$item, $attach = false, $preview = false) {
1244 call_hooks('prepare_body_init', $item);
1246 $searchpath = System::baseUrl() . "/search?tag=";
1249 $hashtags = array();
1250 $mentions = array();
1252 // In order to provide theme developers more possibilities, event items
1253 // are treated differently.
1254 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
1255 $ev = format_event_item($item);
1259 if (!Config::get('system','suppress_tags')) {
1260 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
1261 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1263 while ($tag = dba::fetch($taglist)) {
1264 if ($tag["url"] == "") {
1265 $tag["url"] = $searchpath.strtolower($tag["term"]);
1268 $orig_tag = $tag["url"];
1270 $tag["url"] = best_link_url($item, $sp, $tag["url"]);
1272 if ($tag["type"] == TERM_HASHTAG) {
1273 if ($orig_tag != $tag["url"]) {
1274 $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
1276 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1278 } elseif ($tag["type"] == TERM_MENTION) {
1279 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1282 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1284 dba::close($taglist);
1287 $item['tags'] = $tags;
1288 $item['hashtags'] = $hashtags;
1289 $item['mentions'] = $mentions;
1291 // Update the cached values if there is no "zrl=..." on the links.
1292 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
1294 // Or update it if the current viewer is the intented viewer.
1295 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
1299 put_item_in_cache($item, $update);
1300 $s = $item["rendered-html"];
1302 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1303 call_hooks('prepare_body', $prep_arr);
1304 $s = $prep_arr['html'];
1307 // Replace the blockquotes with quotes that are used in mails.
1308 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1309 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1315 $arr = explode('[/attach],', $item['attach']);
1317 foreach ($arr as $r) {
1320 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r ,$matches, PREG_SET_ORDER);
1322 foreach ($matches as $mtch) {
1325 if ((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1326 $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1328 $the_url = $mtch[1];
1331 if (strpos($mime, 'video') !== false) {
1334 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1335 '$baseurl' => System::baseUrl(),
1337 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1338 '$baseurl' => System::baseUrl(),
1342 $id = end(explode('/', $the_url));
1343 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1346 'title' => t('View Video'),
1353 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
1355 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
1356 $filesubtype = str_replace('.', '-', $filesubtype);
1359 $filesubtype = 'unkn';
1362 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1363 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1365 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1366 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1372 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1376 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1377 $x = Map::byCoordinates(trim($item['coord']));
1379 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1384 // Look for spoiler.
1385 $spoilersearch = '<blockquote class="spoiler">';
1387 // Remove line breaks before the spoiler.
1388 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1389 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1391 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1392 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1395 while ((strpos($s, $spoilersearch) !== false)) {
1396 $pos = strpos($s, $spoilersearch);
1397 $rnd = random_string(8);
1398 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1399 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1400 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1403 // Look for quote with author.
1404 $authorsearch = '<blockquote class="author">';
1406 while ((strpos($s, $authorsearch) !== false)) {
1407 $pos = strpos($s, $authorsearch);
1408 $rnd = random_string(8);
1409 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . sprintf(t('Click to open/close')) . '</span>'.
1410 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1411 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1414 // Replace friendica image url size with theme preference.
1415 if (x($a->theme_info, 'item_image_size')){
1416 $ps = $a->theme_info['item_image_size'];
1417 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1420 $prep_arr = array('item' => $item, 'html' => $s);
1421 call_hooks('prepare_body_final', $prep_arr);
1423 return $prep_arr['html'];
1427 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1429 * @param string $text String with bbcode.
1430 * @return string Formattet HTML.
1432 function prepare_text($text) {
1434 require_once 'include/bbcode.php';
1436 if (stristr($text, '[nosmile]')) {
1439 $s = Smilies::replace(bbcode($text));
1446 * return array with details for categories and folders for an item
1448 * @param array $item
1452 * [ // categories array
1454 * 'name': 'category name',
1455 * 'removeurl': 'url to remove this category',
1456 * 'first': 'is the first in this array? true/false',
1457 * 'last': 'is the last in this array? true/false',
1463 * 'name': 'folder name',
1464 * 'removeurl': 'url to remove this folder',
1465 * 'first': 'is the first in this array? true/false',
1466 * 'last': 'is the last in this array? true/false',
1472 function get_cats_and_terms($item)
1474 $categories = array();
1479 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1481 foreach ($matches as $mtch) {
1482 $categories[] = array(
1483 'name' => xmlify(file_tag_decode($mtch[1])),
1485 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1493 if (count($categories)) {
1494 $categories[count($categories) - 1]['last'] = true;
1497 if (local_user() == $item['uid']) {
1500 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1502 foreach ($matches as $mtch) {
1504 'name' => xmlify(file_tag_decode($mtch[1])),
1506 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1515 if (count($folders)) {
1516 $folders[count($folders) - 1]['last'] = true;
1519 return array($categories, $folders);
1524 * get private link for item
1525 * @param array $item
1526 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1528 function get_plink($item) {
1531 if ($a->user['nickname'] != "") {
1533 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1534 'href' => "display/" . $item['guid'],
1535 'orig' => "display/" . $item['guid'],
1536 'title' => t('View on separate page'),
1537 'orig_title' => t('view on separate page'),
1540 if (x($item, 'plink')) {
1541 $ret["href"] = $a->remove_baseurl($item['plink']);
1542 $ret["title"] = t('link to source');
1545 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1547 'href' => $item['plink'],
1548 'orig' => $item['plink'],
1549 'title' => t('link to source'),
1560 * replace html amp entity with amp char
1564 function unamp($s) {
1565 return str_replace('&', '&', $s);
1570 * return number of bytes in size (K, M, G)
1571 * @param string $size_str
1574 function return_bytes($size_str) {
1575 switch (substr ($size_str, -1)) {
1576 case 'M': case 'm': return (int)$size_str * 1048576;
1577 case 'K': case 'k': return (int)$size_str * 1024;
1578 case 'G': case 'g': return (int)$size_str * 1073741824;
1579 default: return $size_str;
1587 function generate_user_guid() {
1590 $guid = get_guid(32);
1591 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1594 if (! DBM::is_result($x)) {
1597 } while ($found == true);
1605 * @param boolean $strip_padding
1608 function base64url_encode($s, $strip_padding = false) {
1610 $s = strtr(base64_encode($s), '+/', '-_');
1612 if ($strip_padding) {
1613 $s = str_replace('=','',$s);
1623 function base64url_decode($s) {
1626 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1631 * // Placeholder for new rev of salmon which strips base64 padding.
1632 * // PHP base64_decode handles the un-padded input without requiring this step
1633 * // Uncomment if you find you need it.
1636 * if (! strpos($s,'=')) {
1646 return base64_decode(strtr($s,'-_','+/'));
1651 * return div element with class 'clear'
1655 function cleardiv() {
1656 return '<div class="clear"></div>';
1660 function bb_translate_video($s) {
1663 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1665 foreach ($matches as $mtch) {
1666 if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1667 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1668 elseif (stristr($mtch[1],'vimeo'))
1669 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1675 function html2bb_video($s) {
1677 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1678 '[youtube]$2[/youtube]', $s);
1680 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1681 '[youtube]$2[/youtube]', $s);
1683 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1684 '[vimeo]$2[/vimeo]', $s);
1690 * apply xmlify() to all values of array $val, recursively
1694 function array_xmlify($val){
1695 if (is_bool($val)) {
1696 return $val?"true":"false";
1697 } elseif (is_array($val)) {
1698 return array_map('array_xmlify', $val);
1700 return xmlify((string) $val);
1705 * transform link href and img src from relative to absolute
1707 * @param string $text
1708 * @param string $base base url
1711 function reltoabs($text, $base) {
1716 $base = rtrim($base,'/');
1718 $base2 = $base . "/";
1721 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1722 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1723 $text = preg_replace($pattern, $replace, $text);
1725 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1726 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1727 $text = preg_replace($pattern, $replace, $text);
1730 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1731 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1732 $text = preg_replace($pattern, $replace, $text);
1734 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1735 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1736 $text = preg_replace($pattern, $replace, $text);
1744 * get translated item type
1746 * @param array $itme
1749 function item_post_type($item) {
1750 if (intval($item['event-id'])) {
1752 } elseif (strlen($item['resource-id'])) {
1754 } elseif (strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1755 return t('activity');
1756 } elseif ($item['id'] != $item['parent']) {
1757 return t('comment');
1763 // post categories and "save to file" use the same item.file table for storage.
1764 // We will differentiate the different uses by wrapping categories in angle brackets
1765 // and save to file categories in square brackets.
1766 // To do this we need to escape these characters if they appear in our tag.
1768 function file_tag_encode($s) {
1769 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1772 function file_tag_decode($s) {
1773 return str_replace(array('%3c', '%3e', '%5b', '%5d'), array('<', '>', '[', ']'), $s);
1776 function file_tag_file_query($table,$s,$type = 'file') {
1778 if ($type == 'file') {
1779 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1781 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1783 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1786 // ex. given music,video return <music><video> or [music][video]
1787 function file_tag_list_to_file($list,$type = 'file') {
1789 if (strlen($list)) {
1790 $list_array = explode(",",$list);
1791 if ($type == 'file') {
1799 foreach ($list_array as $item) {
1800 if (strlen($item)) {
1801 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1808 // ex. given <music><video>[friends], return music,video or friends
1809 function file_tag_file_to_list($file,$type = 'file') {
1812 if ($type == 'file') {
1813 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1815 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1818 foreach ($matches as $mtch) {
1819 if (strlen($list)) {
1822 $list .= file_tag_decode($mtch[1]);
1829 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1830 // $file_old - categories previously associated with an item
1831 // $file_new - new list of categories for an item
1833 if (!intval($uid)) {
1836 if ($file_old == $file_new) {
1840 $saved = PConfig::get($uid, 'system', 'filetags');
1841 if (strlen($saved)) {
1842 if ($type == 'file') {
1845 $termtype = TERM_FILE;
1849 $termtype = TERM_CATEGORY;
1852 $filetags_updated = $saved;
1854 // check for new tags to be added as filetags in pconfig
1855 $new_tags = array();
1856 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1858 foreach ($check_new_tags as $tag) {
1859 if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1863 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1865 // check for deleted tags to be removed from filetags in pconfig
1866 $deleted_tags = array();
1867 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1869 foreach ($check_deleted_tags as $tag) {
1870 if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1871 $deleted_tags[] = $tag;
1874 foreach ($deleted_tags as $key => $tag) {
1875 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1877 intval(TERM_OBJ_POST),
1881 if (DBM::is_result($r)) {
1882 unset($deleted_tags[$key]);
1884 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1888 if ($saved != $filetags_updated) {
1889 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1892 } elseif (strlen($file_new)) {
1893 PConfig::set($uid, 'system', 'filetags', $file_new);
1898 function file_tag_save_file($uid, $item, $file) {
1899 require_once "include/files.php";
1901 if (! intval($uid)) {
1905 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1909 if (DBM::is_result($r)) {
1910 if (! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']')) {
1911 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1912 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1918 create_files_from_item($item);
1920 $saved = PConfig::get($uid, 'system', 'filetags');
1921 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1922 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1924 info(t('Item filed'));
1929 function file_tag_unsave_file($uid, $item, $file, $cat = false) {
1930 require_once "include/files.php";
1932 if (! intval($uid)) {
1937 $pattern = '<' . file_tag_encode($file) . '>' ;
1938 $termtype = TERM_CATEGORY;
1940 $pattern = '[' . file_tag_encode($file) . ']' ;
1941 $termtype = TERM_FILE;
1944 $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1948 if (! DBM::is_result($r)) {
1952 q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
1953 dbesc(str_replace($pattern,'',$r[0]['file'])),
1958 create_files_from_item($item);
1960 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1962 intval(TERM_OBJ_POST),
1966 if (!DBM::is_result($r)) {
1967 $saved = PConfig::get($uid, 'system', 'filetags');
1968 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1974 function normalise_openid($s) {
1975 return trim(str_replace(array('http://', 'https://'), array('', ''), $s), '/');
1979 function undo_post_tagging($s) {
1981 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1983 foreach ($matches as $mtch) {
1984 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1990 function protect_sprintf($s) {
1991 return str_replace('%', '%%', $s);
1995 function is_a_date_arg($s) {
1999 if ($i <= $y + 1 && strpos($s, '-') == 4) {
2000 $m = intval(substr($s,5));
2001 if ($m > 0 && $m <= 12)
2009 * remove intentation from a text
2011 function deindent($text, $chr = "[\t ]", $count = NULL) {
2012 $lines = explode("\n", $text);
2013 if (is_null($count)) {
2016 while ($k < count($lines) && strlen($lines[$k]) == 0) {
2019 preg_match("|^" . $chr . "*|", $lines[$k], $m);
2020 $count = strlen($m[0]);
2022 for ($k = 0; $k < count($lines); $k++) {
2023 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
2026 return implode("\n", $lines);
2029 function formatBytes($bytes, $precision = 2) {
2030 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2032 $bytes = max($bytes, 0);
2033 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2034 $pow = min($pow, count($units) - 1);
2036 $bytes /= pow(1024, $pow);
2038 return round($bytes, $precision) . ' ' . $units[$pow];
2042 * @brief translate and format the networkname of a contact
2044 * @param string $network
2045 * Networkname of the contact (e.g. dfrn, rss and so on)
2050 function format_network_name($network, $url = 0) {
2051 if ($network != "") {
2053 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
2055 $network_name = ContactSelector::networkToName($network);
2058 return $network_name;
2063 * @brief Syntax based code highlighting for popular languages.
2064 * @param string $s Code block
2065 * @param string $lang Programming language
2066 * @return string Formated html
2068 function text_highlight($s, $lang) {
2069 if ($lang === 'js') {
2070 $lang = 'javascript';
2073 // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
2075 // Autoload the library to make constants available
2076 class_exists('Text_Highlighter_Renderer_Html');
2079 'numbers' => HL_NUMBERS_LI,
2084 $s = trim(html_entity_decode($s, ENT_COMPAT));
2085 $s = str_replace(' ', "\t", $s);
2088 * The highlighter library insists on an opening php tag for php code blocks. If
2089 * it isn't present, nothing is highlighted. So we're going to see if it's present.
2090 * If not, we'll add it, and then quietly remove it after we get the processed output back.
2092 if ($lang === 'php' && strpos($s, '<?php') !== 0) {
2093 $s = '<?php' . "\n" . $s;
2097 $renderer = new Text_Highlighter_Renderer_Html($options);
2098 $hl = Text_Highlighter::factory($lang);
2099 $hl->setRenderer($renderer);
2100 $o = $hl->highlight($s);
2101 $o = str_replace("\n", '', $o);
2104 $b = substr($o, 0, strpos($o, '<li>'));
2105 $e = substr($o, strpos($o, '</li>'));
2109 return '<code>' . $o . '</code>';