Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1339 lines
39 KiB

  1. <?php
  2. // This is our template processor.
  3. // $s is the string requiring macro substitution.
  4. // $r is an array of key value pairs (search => replace)
  5. // returns substituted string.
  6. // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
  7. // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
  8. // depending on the order in which they were declared in the array.
  9. require_once("include/template_processor.php");
  10. if(! function_exists('replace_macros')) {
  11. function replace_macros($s,$r) {
  12. global $t;
  13. //$ts = microtime();
  14. $r = $t->replace($s,$r);
  15. //$tt = microtime() - $ts;
  16. //$a = get_app();
  17. //$a->page['debug'] .= "$tt <br>\n";
  18. return $r;
  19. }}
  20. // random string, there are 86 characters max in text mode, 128 for hex
  21. // output is urlsafe
  22. define('RANDOM_STRING_HEX', 0x00 );
  23. define('RANDOM_STRING_TEXT', 0x01 );
  24. if(! function_exists('random_string')) {
  25. function random_string($size = 64,$type = RANDOM_STRING_HEX) {
  26. // generate a bit of entropy and run it through the whirlpool
  27. $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
  28. $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
  29. return(substr($s,0,$size));
  30. }}
  31. /**
  32. * This is our primary input filter.
  33. *
  34. * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
  35. * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
  36. * after cleansing, and angle chars with the high bit set could get through as markup.
  37. *
  38. * This is now disabled because it was interfering with some legitimate unicode sequences
  39. * and hopefully there aren't a lot of those browsers left.
  40. *
  41. * Use this on any text input where angle chars are not valid or permitted
  42. * They will be replaced with safer brackets. This may be filtered further
  43. * if these are not allowed either.
  44. *
  45. */
  46. if(! function_exists('notags')) {
  47. function notags($string) {
  48. return(str_replace(array("<",">"), array('[',']'), $string));
  49. // High-bit filter no longer used
  50. // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
  51. }}
  52. // use this on "body" or "content" input where angle chars shouldn't be removed,
  53. // and allow them to be safely displayed.
  54. if(! function_exists('escape_tags')) {
  55. function escape_tags($string) {
  56. return(htmlspecialchars($string));
  57. }}
  58. // generate a string that's random, but usually pronounceable.
  59. // used to generate initial passwords
  60. if(! function_exists('autoname')) {
  61. function autoname($len) {
  62. $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
  63. if(mt_rand(0,5) == 4)
  64. $vowels[] = 'y';
  65. $cons = array(
  66. 'b','bl','br',
  67. 'c','ch','cl','cr',
  68. 'd','dr',
  69. 'f','fl','fr',
  70. 'g','gh','gl','gr',
  71. 'h',
  72. 'j',
  73. 'k','kh','kl','kr',
  74. 'l',
  75. 'm',
  76. 'n',
  77. 'p','ph','pl','pr',
  78. 'qu',
  79. 'r','rh',
  80. 's','sc','sh','sm','sp','st',
  81. 't','th','tr',
  82. 'v',
  83. 'w','wh',
  84. 'x',
  85. 'z','zh'
  86. );
  87. $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
  88. 'nd','ng','nk','nt','rn','rp','rt');
  89. $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
  90. 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
  91. $start = mt_rand(0,2);
  92. if($start == 0)
  93. $table = $vowels;
  94. else
  95. $table = $cons;
  96. $word = '';
  97. for ($x = 0; $x < $len; $x ++) {
  98. $r = mt_rand(0,count($table) - 1);
  99. $word .= $table[$r];
  100. if($table == $vowels)
  101. $table = array_merge($cons,$midcons);
  102. else
  103. $table = $vowels;
  104. }
  105. $word = substr($word,0,$len);
  106. foreach($noend as $noe) {
  107. if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
  108. $word = substr($word,0,-1);
  109. break;
  110. }
  111. }
  112. if(substr($word,-1) == 'q')
  113. $word = substr($word,0,-1);
  114. return $word;
  115. }}
  116. // escape text ($str) for XML transport
  117. // returns escaped text.
  118. if(! function_exists('xmlify')) {
  119. function xmlify($str) {
  120. $buffer = '';
  121. for($x = 0; $x < mb_strlen($str); $x ++) {
  122. $char = $str[$x];
  123. switch( $char ) {
  124. case "\r" :
  125. break;
  126. case "&" :
  127. $buffer .= '&amp;';
  128. break;
  129. case "'" :
  130. $buffer .= '&apos;';
  131. break;
  132. case "\"" :
  133. $buffer .= '&quot;';
  134. break;
  135. case '<' :
  136. $buffer .= '&lt;';
  137. break;
  138. case '>' :
  139. $buffer .= '&gt;';
  140. break;
  141. case "\n" :
  142. $buffer .= "\n";
  143. break;
  144. default :
  145. $buffer .= $char;
  146. break;
  147. }
  148. }
  149. $buffer = trim($buffer);
  150. return($buffer);
  151. }}
  152. // undo an xmlify
  153. // pass xml escaped text ($s), returns unescaped text
  154. if(! function_exists('unxmlify')) {
  155. function unxmlify($s) {
  156. $ret = str_replace('&amp;','&', $s);
  157. $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
  158. return $ret;
  159. }}
  160. // convenience wrapper, reverse the operation "bin2hex"
  161. if(! function_exists('hex2bin')) {
  162. function hex2bin($s) {
  163. if(! (is_string($s) && strlen($s)))
  164. return '';
  165. if(! ctype_xdigit($s)) {
  166. logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
  167. return($s);
  168. }
  169. return(pack("H*",$s));
  170. }}
  171. // Automatic pagination.
  172. // To use, get the count of total items.
  173. // Then call $a->set_pager_total($number_items);
  174. // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
  175. // Then call paginate($a) after the end of the display loop to insert the pager block on the page
  176. // (assuming there are enough items to paginate).
  177. // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
  178. // will limit the results to the correct items for the current page.
  179. // The actual page handling is then accomplished at the application layer.
  180. if(! function_exists('paginate')) {
  181. function paginate(&$a) {
  182. $o = '';
  183. $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
  184. $stripped = str_replace('q=','',$stripped);
  185. $stripped = trim($stripped,'/');
  186. $pagenum = $a->pager['page'];
  187. $url = $a->get_baseurl() . '/' . $stripped;
  188. if($a->pager['total'] > $a->pager['itemspage']) {
  189. $o .= '<div class="pager">';
  190. if($a->pager['page'] != 1)
  191. $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
  192. $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
  193. $numpages = $a->pager['total'] / $a->pager['itemspage'];
  194. $numstart = 1;
  195. $numstop = $numpages;
  196. if($numpages > 14) {
  197. $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
  198. $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
  199. }
  200. for($i = $numstart; $i <= $numstop; $i++){
  201. if($i == $a->pager['page'])
  202. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  203. else
  204. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  205. $o .= '</span> ';
  206. }
  207. if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
  208. if($i == $a->pager['page'])
  209. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  210. else
  211. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  212. $o .= '</span> ';
  213. }
  214. $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
  215. $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
  216. if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
  217. $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
  218. $o .= '</div>'."\r\n";
  219. }
  220. return $o;
  221. }}
  222. // Turn user/group ACLs stored as angle bracketed text into arrays
  223. if(! function_exists('expand_acl')) {
  224. function expand_acl($s) {
  225. // turn string array of angle-bracketed elements into numeric array
  226. // e.g. "<1><2><3>" => array(1,2,3);
  227. $ret = array();
  228. if(strlen($s)) {
  229. $t = str_replace('<','',$s);
  230. $a = explode('>',$t);
  231. foreach($a as $aa) {
  232. if(intval($aa))
  233. $ret[] = intval($aa);
  234. }
  235. }
  236. return $ret;
  237. }}
  238. // Used to wrap ACL elements in angle brackets for storage
  239. if(! function_exists('sanitise_acl')) {
  240. function sanitise_acl(&$item) {
  241. if(intval($item))
  242. $item = '<' . intval(notags(trim($item))) . '>';
  243. else
  244. unset($item);
  245. }}
  246. // Convert an ACL array to a storable string
  247. if(! function_exists('perms2str')) {
  248. function perms2str($p) {
  249. $ret = '';
  250. $tmp = $p;
  251. if(is_array($tmp)) {
  252. array_walk($tmp,'sanitise_acl');
  253. $ret = implode('',$tmp);
  254. }
  255. return $ret;
  256. }}
  257. // generate a guaranteed unique (for this domain) item ID for ATOM
  258. // safe from birthday paradox
  259. if(! function_exists('item_new_uri')) {
  260. function item_new_uri($hostname,$uid) {
  261. do {
  262. $dups = false;
  263. $hash = random_string();
  264. $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
  265. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
  266. dbesc($uri));
  267. if(count($r))
  268. $dups = true;
  269. } while($dups == true);
  270. return $uri;
  271. }}
  272. // Generate a guaranteed unique photo ID.
  273. // safe from birthday paradox
  274. if(! function_exists('photo_new_resource')) {
  275. function photo_new_resource() {
  276. do {
  277. $found = false;
  278. $resource = hash('md5',uniqid(mt_rand(),true));
  279. $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
  280. dbesc($resource)
  281. );
  282. if(count($r))
  283. $found = true;
  284. } while($found == true);
  285. return $resource;
  286. }}
  287. // wrapper to load a view template, checking for alternate
  288. // languages before falling back to the default
  289. // obsolete, deprecated.
  290. if(! function_exists('load_view_file')) {
  291. function load_view_file($s) {
  292. global $lang, $a;
  293. if(! isset($lang))
  294. $lang = 'en';
  295. $b = basename($s);
  296. $d = dirname($s);
  297. if(file_exists("$d/$lang/$b"))
  298. return file_get_contents("$d/$lang/$b");
  299. $theme = current_theme();
  300. if(file_exists("$d/theme/$theme/$b"))
  301. return file_get_contents("$d/theme/$theme/$b");
  302. return file_get_contents($s);
  303. }}
  304. if(! function_exists('get_intltext_template')) {
  305. function get_intltext_template($s) {
  306. global $lang;
  307. if(! isset($lang))
  308. $lang = 'en';
  309. if(file_exists("view/$lang/$s"))
  310. return file_get_contents("view/$lang/$s");
  311. elseif(file_exists("view/en/$s"))
  312. return file_get_contents("view/en/$s");
  313. else
  314. return file_get_contents("view/$s");
  315. }}
  316. if(! function_exists('get_markup_template')) {
  317. function get_markup_template($s) {
  318. $a=get_app();
  319. $theme = current_theme();
  320. if(file_exists("view/theme/$theme/$s"))
  321. return file_get_contents("view/theme/$theme/$s");
  322. elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
  323. return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
  324. else
  325. return file_get_contents("view/$s");
  326. }}
  327. // for html,xml parsing - let's say you've got
  328. // an attribute foobar="class1 class2 class3"
  329. // and you want to find out if it contains 'class3'.
  330. // you can't use a normal sub string search because you
  331. // might match 'notclass3' and a regex to do the job is
  332. // possible but a bit complicated.
  333. // pass the attribute string as $attr and the attribute you
  334. // are looking for as $s - returns true if found, otherwise false
  335. if(! function_exists('attribute_contains')) {
  336. function attribute_contains($attr,$s) {
  337. $a = explode(' ', $attr);
  338. if(count($a) && in_array($s,$a))
  339. return true;
  340. return false;
  341. }}
  342. if(! function_exists('logger')) {
  343. function logger($msg,$level = 0) {
  344. // turn off logger in install mode
  345. global $a;
  346. global $db;
  347. if(($a->module == 'install') || (! ($db && $db->connected))) return;
  348. $debugging = get_config('system','debugging');
  349. $loglevel = intval(get_config('system','loglevel'));
  350. $logfile = get_config('system','logfile');
  351. if((! $debugging) || (! $logfile) || ($level > $loglevel))
  352. return;
  353. @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
  354. return;
  355. }}
  356. if(! function_exists('activity_match')) {
  357. function activity_match($haystack,$needle) {
  358. if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
  359. return true;
  360. return false;
  361. }}
  362. // Pull out all #hashtags and @person tags from $s;
  363. // We also get @person@domain.com - which would make
  364. // the regex quite complicated as tags can also
  365. // end a sentence. So we'll run through our results
  366. // and strip the period from any tags which end with one.
  367. // Returns array of tags found, or empty array.
  368. if(! function_exists('get_tags')) {
  369. function get_tags($s) {
  370. $ret = array();
  371. // ignore anything in a code block
  372. $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
  373. // Match full names against @tags including the space between first and last
  374. // We will look these up afterward to see if they are full names or not recognisable.
  375. if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
  376. foreach($match[1] as $mtch) {
  377. if(strstr($mtch,"]")) {
  378. // we might be inside a bbcode color tag - leave it alone
  379. continue;
  380. }
  381. if(substr($mtch,-1,1) === '.')
  382. $ret[] = substr($mtch,0,-1);
  383. else
  384. $ret[] = $mtch;
  385. }
  386. }
  387. // Otherwise pull out single word tags. These can be @nickname, @first_last
  388. // and #hash tags.
  389. if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
  390. foreach($match[1] as $mtch) {
  391. if(strstr($mtch,"]")) {
  392. // we might be inside a bbcode color tag - leave it alone
  393. continue;
  394. }
  395. if(substr($mtch,-1,1) === '.')
  396. $mtch = substr($mtch,0,-1);
  397. // ignore strictly numeric tags like #1
  398. if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
  399. continue;
  400. // try not to catch url fragments
  401. if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
  402. continue;
  403. $ret[] = $mtch;
  404. }
  405. }
  406. return $ret;
  407. }}
  408. // quick and dirty quoted_printable encoding
  409. if(! function_exists('qp')) {
  410. function qp($s) {
  411. return str_replace ("%","=",rawurlencode($s));
  412. }}
  413. if(! function_exists('get_mentions')) {
  414. function get_mentions($item) {
  415. $o = '';
  416. if(! strlen($item['tag']))
  417. return $o;
  418. $arr = explode(',',$item['tag']);
  419. foreach($arr as $x) {
  420. $matches = null;
  421. if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
  422. $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
  423. $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
  424. }
  425. }
  426. return $o;
  427. }}
  428. if(! function_exists('contact_block')) {
  429. function contact_block() {
  430. $o = '';
  431. $a = get_app();
  432. $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
  433. if($shown === false)
  434. $shown = 24;
  435. if($shown == 0)
  436. return;
  437. if((! is_array($a->profile)) || ($a->profile['hide-friends']))
  438. return $o;
  439. $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0",
  440. intval($a->profile['uid'])
  441. );
  442. if(count($r)) {
  443. $total = intval($r[0]['total']);
  444. }
  445. if(! $total) {
  446. $contacts = t('No contacts');
  447. $micropro = Null;
  448. } else {
  449. $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 ORDER BY RAND() LIMIT %d",
  450. intval($a->profile['uid']),
  451. intval($shown)
  452. );
  453. if(count($r)) {
  454. $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
  455. $micropro = Array();
  456. foreach($r as $rr) {
  457. $micropro[] = micropro($rr,true,'mpfriend');
  458. }
  459. }
  460. }
  461. $tpl = get_markup_template('contact_block.tpl');
  462. $o = replace_macros($tpl, array(
  463. '$contacts' => $contacts,
  464. '$nickname' => $a->profile['nickname'],
  465. '$viewcontacts' => t('View Contacts'),
  466. '$micropro' => $micropro,
  467. ));
  468. $arr = array('contacts' => $r, 'output' => $o);
  469. call_hooks('contact_block_end', $arr);
  470. return $o;
  471. }}
  472. if(! function_exists('micropro')) {
  473. function micropro($contact, $redirect = false, $class = '', $textmode = false) {
  474. if($class)
  475. $class = ' ' . $class;
  476. $url = $contact['url'];
  477. $sparkle = '';
  478. $redir = false;
  479. if($redirect) {
  480. $a = get_app();
  481. $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
  482. if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
  483. $redir = true;
  484. $url = $redirect_url;
  485. $sparkle = ' sparkle';
  486. }
  487. }
  488. $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
  489. if($click)
  490. $url = '';
  491. if($textmode) {
  492. return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
  493. . (($click) ? ' fakelink' : '') . '" '
  494. . (($redir) ? ' target="redir" ' : '')
  495. . (($url) ? ' href="' . $url . '"' : '') . $click
  496. . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
  497. . '" >'. $contact['name'] . '</a></div>' . "\r\n";
  498. }
  499. else {
  500. return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
  501. . (($click) ? ' fakelink' : '') . '" '
  502. . (($redir) ? ' target="redir" ' : '')
  503. . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
  504. . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
  505. . '" /></a></div>' . "\r\n";
  506. }
  507. }}
  508. if(! function_exists('search')) {
  509. function search($s,$id='search-box',$url='/search',$save = false) {
  510. $a = get_app();
  511. $o = '<div id="' . $id . '">';
  512. $o .= '<form action="' . $a->get_baseurl() . $url . '" method="get" >';
  513. $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
  514. $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
  515. if($save)
  516. $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
  517. $o .= '</form></div>';
  518. return $o;
  519. }}
  520. if(! function_exists('valid_email')) {
  521. function valid_email($x){
  522. if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
  523. return true;
  524. return false;
  525. }}
  526. /**
  527. *
  528. * Function: linkify
  529. *
  530. * Replace naked text hyperlink with HTML formatted hyperlink
  531. *
  532. */
  533. if(! function_exists('linkify')) {
  534. function linkify($s) {
  535. $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
  536. $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
  537. return($s);
  538. }}
  539. /**
  540. *
  541. * Function: smilies
  542. *
  543. * Description:
  544. * Replaces text emoticons with graphical images
  545. *
  546. * @Parameter: string $s
  547. *
  548. * Returns string
  549. *
  550. * It is expected that this function will be called using HTML text.
  551. * We will escape text between HTML pre and code blocks from being
  552. * processed.
  553. *
  554. * At a higher level, the bbcode [nosmile] tag can be used to prevent this
  555. * function from being executed by the prepare_text() routine when preparing
  556. * bbcode source for HTML display
  557. *
  558. */
  559. if(! function_exists('smilies')) {
  560. function smilies($s, $sample = false) {
  561. $a = get_app();
  562. $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
  563. $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
  564. $texts = array(
  565. '&lt;3',
  566. '&lt;/3',
  567. '&lt;\\3',
  568. ':-)',
  569. // ':)',
  570. ';-)',
  571. // ';)',
  572. ':-(',
  573. // ':(',
  574. ':-P',
  575. // ':P',
  576. ':-"',
  577. ':-&quot;',
  578. ':-x',
  579. ':-X',
  580. ':-D',
  581. // ':D',
  582. '8-|',
  583. '8-O',
  584. ':-O',
  585. '\\o/',
  586. 'o.O',
  587. 'O.o',
  588. '\\.../',
  589. '\\ooo/',
  590. ":'(",
  591. ":-!",
  592. ":-/",
  593. ":-[",
  594. "8-)",
  595. ':beer',
  596. ':homebrew',
  597. ':coffee',
  598. ':facepalm',
  599. ':headdesk',
  600. '~friendika',
  601. '~friendica',
  602. // 'Diaspora*'
  603. ':beard',
  604. ':whitebeard'
  605. );
  606. $icons = array(
  607. '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
  608. '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
  609. '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
  610. '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
  611. // '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
  612. '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
  613. // '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";)"/>',
  614. '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
  615. // '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
  616. '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
  617. // '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
  618. '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
  619. '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
  620. '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
  621. '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
  622. '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
  623. // '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":D"/>',
  624. '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
  625. '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
  626. '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
  627. '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
  628. '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
  629. '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
  630. '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\.../" />',
  631. '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\ooo/" />',
  632. '<img src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
  633. '<img src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
  634. '<img src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
  635. '<img src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
  636. '<img src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
  637. '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
  638. '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
  639. '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
  640. '<img src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
  641. '<img src="' . $a->get_baseurl() . '/images/smiley-bangheaddesk.gif" alt=":headdesk" />',
  642. '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
  643. '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
  644. // '<a href="http://diasporafoundation.org">Diaspora<img src="' . $a->get_baseurl() . '/images/diaspora.png" alt="Diaspora*" /></a>',
  645. '<img src="' . $a->get_baseurl() . '/images/smiley-beard.png" alt=":beard" />',
  646. '<img src="' . $a->get_baseurl() . '/images/smiley-whitebeard.png" alt=":whitebeard" />'
  647. );
  648. $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
  649. call_hooks('smilie', $params);
  650. if($sample) {
  651. $s = '<div class="smiley-sample">';
  652. for($x = 0; $x < count($params['texts']); $x ++) {
  653. $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
  654. }
  655. }
  656. else {
  657. $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
  658. $s = str_replace($params['texts'],$params['icons'],$params['string']);
  659. }
  660. $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
  661. $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
  662. return $s;
  663. }}
  664. function smile_encode($m) {
  665. return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
  666. }
  667. function smile_decode($m) {
  668. return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
  669. }
  670. // expand <3333 to the correct number of hearts
  671. function preg_heart($x) {
  672. $a = get_app();
  673. if(strlen($x[1]) == 1)
  674. return $x[0];
  675. $t = '';
  676. for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
  677. $t .= '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
  678. $r = str_replace($x[0],$t,$x[0]);
  679. return $r;
  680. }
  681. if(! function_exists('day_translate')) {
  682. function day_translate($s) {
  683. $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
  684. array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
  685. $s);
  686. $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
  687. 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')),
  688. $ret);
  689. return $ret;
  690. }}
  691. if(! function_exists('normalise_link')) {
  692. function normalise_link($url) {
  693. $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
  694. return(rtrim($ret,'/'));
  695. }}
  696. /**
  697. *
  698. * Compare two URLs to see if they are the same, but ignore
  699. * slight but hopefully insignificant differences such as if one
  700. * is https and the other isn't, or if one is www.something and
  701. * the other isn't - and also ignore case differences.
  702. *
  703. * Return true if the URLs match, otherwise false.
  704. *
  705. */
  706. if(! function_exists('link_compare')) {
  707. function link_compare($a,$b) {
  708. if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
  709. return true;
  710. return false;
  711. }}
  712. // Given an item array, convert the body element from bbcode to html and add smilie icons.
  713. // If attach is true, also add icons for item attachments
  714. if(! function_exists('prepare_body')) {
  715. function prepare_body($item,$attach = false) {
  716. call_hooks('prepare_body_init', $item);
  717. $s = prepare_text($item['body']);
  718. $prep_arr = array('item' => $item, 'html' => $s);
  719. call_hooks('prepare_body', $prep_arr);
  720. $s = $prep_arr['html'];
  721. if(! $attach)
  722. return $s;
  723. $arr = explode(',',$item['attach']);
  724. if(count($arr)) {
  725. $s .= '<div class="body-attach">';
  726. foreach($arr as $r) {
  727. $matches = false;
  728. $icon = '';
  729. $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
  730. if($cnt) {
  731. $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
  732. switch($icontype) {
  733. case 'video':
  734. case 'audio':
  735. case 'image':
  736. case 'text':
  737. $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
  738. break;
  739. default:
  740. $icon = '<div class="attachtype icon s22 type-unkn"></div>';
  741. break;
  742. }
  743. $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
  744. $title .= ' ' . $matches[2] . ' ' . t('bytes');
  745. $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
  746. }
  747. }
  748. $s .= '<div class="clear"></div></div>';
  749. }
  750. $matches = false;
  751. $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
  752. if($cnt) {
  753. logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
  754. foreach($matches as $mtch) {
  755. if(strlen($x))
  756. $x .= ',';
  757. $x .= file_tag_decode($mtch[1]);
  758. }
  759. if(strlen($x))
  760. $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>';
  761. }
  762. $matches = false;
  763. $x = '';
  764. $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
  765. if($cnt) {
  766. logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
  767. foreach($matches as $mtch) {
  768. if(strlen($x))
  769. $x .= ',';
  770. $x .= file_tag_decode($mtch[1]);
  771. }
  772. if(strlen($x) && (local_user() == $item['uid']))
  773. $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>';
  774. }
  775. $prep_arr = array('item' => $item, 'html' => $s);
  776. call_hooks('prepare_body_final', $prep_arr);
  777. return $prep_arr['html'];
  778. }}
  779. // Given a text string, convert from bbcode to html and add smilie icons.
  780. if(! function_exists('prepare_text')) {
  781. function prepare_text($text) {
  782. require_once('include/bbcode.php');
  783. if(stristr($text,'[nosmile]'))
  784. $s = bbcode($text);
  785. else
  786. $s = smilies(bbcode($text));
  787. return $s;
  788. }}
  789. /**
  790. * return atom link elements for all of our hubs
  791. */
  792. if(! function_exists('feed_hublinks')) {
  793. function feed_hublinks() {
  794. $hub = get_config('system','huburl');
  795. $hubxml = '';
  796. if(strlen($hub)) {
  797. $hubs = explode(',', $hub);
  798. if(count($hubs)) {
  799. foreach($hubs as $h) {
  800. $h = trim($h);
  801. if(! strlen($h))
  802. continue;
  803. $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
  804. }
  805. }
  806. }
  807. return $hubxml;
  808. }}
  809. /* return atom link elements for salmon endpoints */
  810. if(! function_exists('feed_salmonlinks')) {
  811. function feed_salmonlinks($nick) {
  812. $a = get_app();
  813. $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
  814. // old style links that status.net still needed as of 12/2010
  815. $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
  816. $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
  817. return $salmon;
  818. }}
  819. if(! function_exists('get_plink')) {
  820. function get_plink($item) {
  821. $a = get_app();
  822. if (x($item,'plink') && (! $item['private'])){
  823. return array(
  824. 'href' => $item['plink'],
  825. 'title' => t('link to source'),
  826. );
  827. } else {
  828. return false;
  829. }
  830. }}
  831. if(! function_exists('unamp')) {
  832. function unamp($s) {
  833. return str_replace('&amp;', '&', $s);
  834. }}
  835. if(! function_exists('lang_selector')) {
  836. function lang_selector() {
  837. global $lang;
  838. $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
  839. $o .= '<div id="language-selector" style="display: none;" >';
  840. $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
  841. $langs = glob('view/*/strings.php');
  842. if(is_array($langs) && count($langs)) {
  843. $langs[] = '';
  844. if(! in_array('view/en/strings.php',$langs))
  845. $langs[] = 'view/en/';
  846. asort($langs);
  847. foreach($langs as $l) {
  848. if($l == '') {
  849. $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
  850. $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
  851. continue;
  852. }
  853. $ll = substr($l,5);
  854. $ll = substr($ll,0,strrpos($ll,'/'));
  855. $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? ' selected="selected" ' : '');
  856. $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
  857. }
  858. }
  859. $o .= '</select></form></div>';
  860. return $o;
  861. }}
  862. if(! function_exists('return_bytes')) {
  863. function return_bytes ($size_str) {
  864. switch (substr ($size_str, -1))
  865. {
  866. case 'M': case 'm': return (int)$size_str * 1048576;
  867. case 'K': case 'k': return (int)$size_str * 1024;
  868. case 'G': case 'g': return (int)$size_str * 1073741824;
  869. default: return $size_str;
  870. }
  871. }}
  872. function generate_user_guid() {
  873. $found = true;
  874. do {
  875. $guid = random_string(16);
  876. $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
  877. dbesc($guid)
  878. );
  879. if(! count($x))
  880. $found = false;
  881. } while ($found == true );
  882. return $guid;
  883. }
  884. function base64url_encode($s, $strip_padding = false) {
  885. $s = strtr(base64_encode($s),'+/','-_');
  886. if($strip_padding)
  887. $s = str_replace('=','',$s);
  888. return $s;
  889. }
  890. function base64url_decode($s) {
  891. if(is_array($s)) {
  892. logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
  893. return $s;
  894. }
  895. /*
  896. * // Placeholder for new rev of salmon which strips base64 padding.
  897. * // PHP base64_decode handles the un-padded input without requiring this step
  898. * // Uncomment if you find you need it.
  899. *
  900. * $l = strlen($s);
  901. * if(! strpos($s,'=')) {
  902. * $m = $l % 4;
  903. * if($m == 2)
  904. * $s .= '==';
  905. * if($m == 3)
  906. * $s .= '=';
  907. * }
  908. *
  909. */
  910. return base64_decode(strtr($s,'-_','+/'));
  911. }
  912. if (!function_exists('str_getcsv')) {
  913. function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
  914. if (is_string($input) && !empty($input)) {
  915. $output = array();
  916. $tmp = preg_split("/".$eol."/",$input);
  917. if (is_array($tmp) && !empty($tmp)) {
  918. while (list($line_num, $line) = each($tmp)) {
  919. if (preg_match("/".$escape.$enclosure."/",$line)) {
  920. while ($strlen = strlen($line)) {
  921. $pos_delimiter = strpos($line,$delimiter);
  922. $pos_enclosure_start = strpos($line,$enclosure);
  923. if (
  924. is_int($pos_delimiter) && is_int($pos_enclosure_start)
  925. && ($pos_enclosure_start < $pos_delimiter)
  926. ) {
  927. $enclosed_str = substr($line,1);
  928. $pos_enclosure_end = strpos($enclosed_str,$enclosure);
  929. $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
  930. $output[$line_num][] = $enclosed_str;
  931. $offset = $pos_enclosure_end+3;
  932. } else {
  933. if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
  934. $output[$line_num][] = substr($line,0);
  935. $offset = strlen($line);
  936. } else {
  937. $output[$line_num][] = substr($line,0,$pos_delimiter);
  938. $offset = (
  939. !empty($pos_enclosure_start)
  940. && ($pos_enclosure_start < $pos_delimiter)
  941. )
  942. ?$pos_enclosure_start
  943. :$pos_delimiter+1;
  944. }
  945. }
  946. $line = substr($line,$offset);
  947. }
  948. } else {
  949. $line = preg_split("/".$delimiter."/",$line);
  950. /*
  951. * Validating against pesky extra line breaks creating false rows.
  952. */
  953. if (is_array($line) && !empty($line[0])) {
  954. $output[$line_num] = $line;
  955. }
  956. }
  957. }
  958. return $output;
  959. } else {
  960. return false;
  961. }
  962. } else {
  963. return false;
  964. }
  965. }
  966. }
  967. function cleardiv() {
  968. return '<div class="clear"></div>';
  969. }
  970. function bb_translate_video($s) {
  971. $matches = null;
  972. $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
  973. if($r) {
  974. foreach($matches as $mtch) {
  975. if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
  976. $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
  977. elseif(stristr($mtch[1],'vimeo'))
  978. $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
  979. }
  980. }
  981. return $s;
  982. }
  983. function html2bb_video($s) {
  984. $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
  985. '[youtube]$2[/youtube]', $s);
  986. $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
  987. '[youtube]$2[/youtube]', $s);
  988. $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
  989. '[vimeo]$2[/vimeo]', $s);
  990. return $s;
  991. }
  992. /**
  993. * apply xmlify() to all values of array $val, recursively
  994. */
  995. function array_xmlify($val){
  996. if (is_bool($val)) return $val?"true":"false";
  997. if (is_array($val)) return array_map('array_xmlify', $val);
  998. return xmlify((string) $val);
  999. }
  1000. function reltoabs($text, $base)
  1001. {
  1002. if (empty($base))
  1003. return $text;
  1004. $base = rtrim($base,'/');
  1005. $base2 = $base . "/";
  1006. // Replace links
  1007. $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
  1008. $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
  1009. $text = preg_replace($pattern, $replace, $text);
  1010. $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
  1011. $replace = "<a\${1} href=\"" . $base . "\${2}\"";
  1012. $text = preg_replace($pattern, $replace, $text);
  1013. // Replace images
  1014. $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
  1015. $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
  1016. $text = preg_replace($pattern, $replace, $text);
  1017. $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
  1018. $replace = "<img\${1} src=\"" . $base . "\${2}\"";
  1019. $text = preg_replace($pattern, $replace, $text);
  1020. // Done
  1021. return $text;
  1022. }
  1023. function item_post_type($item) {
  1024. if(intval($item['event-id']))
  1025. return t('event');
  1026. if(strlen($item['resource-id']))
  1027. return t('photo');
  1028. if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
  1029. return t('activity');
  1030. if($item['id'] != $item['parent'])
  1031. return t('comment');
  1032. return t('post');
  1033. }
  1034. // post categories and "save to file" use the same item.file table for storage.
  1035. // We will differentiate the different uses by wrapping categories in angle brackets
  1036. // and save to file categories in square brackets.
  1037. // To do this we need to escape these characters if they appear in our tag.
  1038. function file_tag_encode($s) {
  1039. return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
  1040. }
  1041. function file_tag_decode($s) {
  1042. return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
  1043. }
  1044. function file_tag_file_query($table,$s,$type = 'file') {
  1045. if($type == 'file')
  1046. $str = preg_quote( '[' . file_tag_encode($s) . ']' );
  1047. else
  1048. $str = preg_quote( '<' . file_tag_encode($s) . '>' );
  1049. return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
  1050. }
  1051. function file_tag_save_file($uid,$item,$file) {
  1052. $result = false;
  1053. if(! intval($uid))
  1054. return false;
  1055. $r = q("select file from item where id = %d and uid = %d limit 1",
  1056. intval($item),
  1057. intval($uid)
  1058. );
  1059. if(count($r)) {
  1060. if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
  1061. q("update item set file = '%s' where id = %d and uid = %d limit 1",
  1062. dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
  1063. intval($item),
  1064. intval($uid)
  1065. );
  1066. $saved = get_pconfig($uid,'system','filetags');
  1067. if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
  1068. set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
  1069. }
  1070. return true;
  1071. }
  1072. function file_tag_unsave_file($uid,$item,$file) {
  1073. $result = false;
  1074. if(! intval($uid))
  1075. return false;
  1076. $pattern = '[' . file_tag_encode($file) . ']' ;
  1077. $r = q("select file from item where id = %d and uid = %d limit 1",
  1078. intval($item),
  1079. intval($uid)
  1080. );
  1081. if(! count($r))
  1082. return false;
  1083. q("update item set file = '%s' where id = %d and uid = %d limit 1",
  1084. dbesc(str_replace($pattern,'',$r[0]['file'])),
  1085. intval($item),
  1086. intval($uid)
  1087. );
  1088. $r = q("select file from item where uid = %d " . file_tag_file_query('item',$file),
  1089. intval($uid)
  1090. );
  1091. if(! count($r)) {
  1092. $saved = get_pconfig($uid,'system','filetags');
  1093. set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
  1094. }
  1095. return true;
  1096. }