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.
 
 
 
 
 
 

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