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.
 
 
 
 
 
 

1772 lines
51 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. require_once("include/friendica_smarty.php");
  11. if(! function_exists('replace_macros')) {
  12. function replace_macros($s,$r) {
  13. global $t;
  14. $stamp1 = microtime(true);
  15. $a = get_app();
  16. if($a->theme['template_engine'] === 'smarty3') {
  17. $template = '';
  18. if(gettype($s) === 'string') {
  19. $template = $s;
  20. $s = new FriendicaSmarty();
  21. }
  22. foreach($r as $key=>$value) {
  23. if($key[0] === '$') {
  24. $key = substr($key, 1);
  25. }
  26. $s->assign($key, $value);
  27. }
  28. $output = $s->parsed($template);
  29. }
  30. else {
  31. $r = $t->replace($s,$r);
  32. $output = template_unescape($r);
  33. }
  34. $a = get_app();
  35. $a->save_timestamp($stamp1, "rendering");
  36. return $output;
  37. }}
  38. // random string, there are 86 characters max in text mode, 128 for hex
  39. // output is urlsafe
  40. define('RANDOM_STRING_HEX', 0x00 );
  41. define('RANDOM_STRING_TEXT', 0x01 );
  42. if(! function_exists('random_string')) {
  43. function random_string($size = 64,$type = RANDOM_STRING_HEX) {
  44. // generate a bit of entropy and run it through the whirlpool
  45. $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
  46. $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
  47. return(substr($s,0,$size));
  48. }}
  49. /**
  50. * This is our primary input filter.
  51. *
  52. * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
  53. * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
  54. * after cleansing, and angle chars with the high bit set could get through as markup.
  55. *
  56. * This is now disabled because it was interfering with some legitimate unicode sequences
  57. * and hopefully there aren't a lot of those browsers left.
  58. *
  59. * Use this on any text input where angle chars are not valid or permitted
  60. * They will be replaced with safer brackets. This may be filtered further
  61. * if these are not allowed either.
  62. *
  63. */
  64. if(! function_exists('notags')) {
  65. function notags($string) {
  66. return(str_replace(array("<",">"), array('[',']'), $string));
  67. // High-bit filter no longer used
  68. // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
  69. }}
  70. // use this on "body" or "content" input where angle chars shouldn't be removed,
  71. // and allow them to be safely displayed.
  72. if(! function_exists('escape_tags')) {
  73. function escape_tags($string) {
  74. return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
  75. }}
  76. // generate a string that's random, but usually pronounceable.
  77. // used to generate initial passwords
  78. if(! function_exists('autoname')) {
  79. function autoname($len) {
  80. if($len <= 0)
  81. return '';
  82. $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
  83. if(mt_rand(0,5) == 4)
  84. $vowels[] = 'y';
  85. $cons = array(
  86. 'b','bl','br',
  87. 'c','ch','cl','cr',
  88. 'd','dr',
  89. 'f','fl','fr',
  90. 'g','gh','gl','gr',
  91. 'h',
  92. 'j',
  93. 'k','kh','kl','kr',
  94. 'l',
  95. 'm',
  96. 'n',
  97. 'p','ph','pl','pr',
  98. 'qu',
  99. 'r','rh',
  100. 's','sc','sh','sm','sp','st',
  101. 't','th','tr',
  102. 'v',
  103. 'w','wh',
  104. 'x',
  105. 'z','zh'
  106. );
  107. $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
  108. 'nd','ng','nk','nt','rn','rp','rt');
  109. $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
  110. 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
  111. $start = mt_rand(0,2);
  112. if($start == 0)
  113. $table = $vowels;
  114. else
  115. $table = $cons;
  116. $word = '';
  117. for ($x = 0; $x < $len; $x ++) {
  118. $r = mt_rand(0,count($table) - 1);
  119. $word .= $table[$r];
  120. if($table == $vowels)
  121. $table = array_merge($cons,$midcons);
  122. else
  123. $table = $vowels;
  124. }
  125. $word = substr($word,0,$len);
  126. foreach($noend as $noe) {
  127. if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
  128. $word = substr($word,0,-1);
  129. break;
  130. }
  131. }
  132. if(substr($word,-1) == 'q')
  133. $word = substr($word,0,-1);
  134. return $word;
  135. }}
  136. // escape text ($str) for XML transport
  137. // returns escaped text.
  138. if(! function_exists('xmlify')) {
  139. function xmlify($str) {
  140. $buffer = '';
  141. for($x = 0; $x < mb_strlen($str); $x ++) {
  142. $char = $str[$x];
  143. switch( $char ) {
  144. case "\r" :
  145. break;
  146. case "&" :
  147. $buffer .= '&amp;';
  148. break;
  149. case "'" :
  150. $buffer .= '&apos;';
  151. break;
  152. case "\"" :
  153. $buffer .= '&quot;';
  154. break;
  155. case '<' :
  156. $buffer .= '&lt;';
  157. break;
  158. case '>' :
  159. $buffer .= '&gt;';
  160. break;
  161. case "\n" :
  162. $buffer .= "\n";
  163. break;
  164. default :
  165. $buffer .= $char;
  166. break;
  167. }
  168. }
  169. $buffer = trim($buffer);
  170. return($buffer);
  171. }}
  172. // undo an xmlify
  173. // pass xml escaped text ($s), returns unescaped text
  174. if(! function_exists('unxmlify')) {
  175. function unxmlify($s) {
  176. $ret = str_replace('&amp;','&', $s);
  177. $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
  178. return $ret;
  179. }}
  180. // convenience wrapper, reverse the operation "bin2hex"
  181. if(! function_exists('hex2bin')) {
  182. function hex2bin($s) {
  183. if(! (is_string($s) && strlen($s)))
  184. return '';
  185. if(! ctype_xdigit($s)) {
  186. return($s);
  187. }
  188. return(pack("H*",$s));
  189. }}
  190. // Automatic pagination.
  191. // To use, get the count of total items.
  192. // Then call $a->set_pager_total($number_items);
  193. // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
  194. // Then call paginate($a) after the end of the display loop to insert the pager block on the page
  195. // (assuming there are enough items to paginate).
  196. // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
  197. // will limit the results to the correct items for the current page.
  198. // The actual page handling is then accomplished at the application layer.
  199. if(! function_exists('paginate')) {
  200. function paginate(&$a) {
  201. $o = '';
  202. $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
  203. // $stripped = preg_replace('/&zrl=(.*?)([\?&]|$)/ism','',$stripped);
  204. $stripped = str_replace('q=','',$stripped);
  205. $stripped = trim($stripped,'/');
  206. $pagenum = $a->pager['page'];
  207. $url = $a->get_baseurl() . '/' . $stripped;
  208. if($a->pager['total'] > $a->pager['itemspage']) {
  209. $o .= '<div class="pager">';
  210. if($a->pager['page'] != 1)
  211. $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
  212. $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
  213. $numpages = $a->pager['total'] / $a->pager['itemspage'];
  214. $numstart = 1;
  215. $numstop = $numpages;
  216. if($numpages > 14) {
  217. $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
  218. $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
  219. }
  220. for($i = $numstart; $i <= $numstop; $i++){
  221. if($i == $a->pager['page'])
  222. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  223. else
  224. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  225. $o .= '</span> ';
  226. }
  227. if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
  228. if($i == $a->pager['page'])
  229. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  230. else
  231. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  232. $o .= '</span> ';
  233. }
  234. $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
  235. $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
  236. if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
  237. $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
  238. $o .= '</div>'."\r\n";
  239. }
  240. return $o;
  241. }}
  242. if(! function_exists('alt_pager')) {
  243. function alt_pager(&$a, $i) {
  244. $o = '';
  245. $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
  246. $stripped = str_replace('q=','',$stripped);
  247. $stripped = trim($stripped,'/');
  248. $pagenum = $a->pager['page'];
  249. $url = $a->get_baseurl() . '/' . $stripped;
  250. $o .= '<div class="pager">';
  251. if($a->pager['page']>1)
  252. $o .= "<a href=\"$url"."&page=".($a->pager['page'] - 1).'" class="pager_newer">' . t('newer') . '</a>';
  253. if($i>0) {
  254. if($a->pager['page']>1)
  255. $o .= "&nbsp;-&nbsp;";
  256. $o .= "<a href=\"$url"."&page=".($a->pager['page'] + 1).'" class="pager_older">' . t('older') . '</a>';
  257. }
  258. $o .= '</div>'."\r\n";
  259. return $o;
  260. }}
  261. // Turn user/group ACLs stored as angle bracketed text into arrays
  262. if(! function_exists('expand_acl')) {
  263. function expand_acl($s) {
  264. // turn string array of angle-bracketed elements into numeric array
  265. // e.g. "<1><2><3>" => array(1,2,3);
  266. $ret = array();
  267. if(strlen($s)) {
  268. $t = str_replace('<','',$s);
  269. $a = explode('>',$t);
  270. foreach($a as $aa) {
  271. if(intval($aa))
  272. $ret[] = intval($aa);
  273. }
  274. }
  275. return $ret;
  276. }}
  277. // Used to wrap ACL elements in angle brackets for storage
  278. if(! function_exists('sanitise_acl')) {
  279. function sanitise_acl(&$item) {
  280. if(intval($item))
  281. $item = '<' . intval(notags(trim($item))) . '>';
  282. else
  283. unset($item);
  284. }}
  285. // Convert an ACL array to a storable string
  286. // Normally ACL permissions will be an array.
  287. // We'll also allow a comma-separated string.
  288. if(! function_exists('perms2str')) {
  289. function perms2str($p) {
  290. $ret = '';
  291. if(is_array($p))
  292. $tmp = $p;
  293. else
  294. $tmp = explode(',',$p);
  295. if(is_array($tmp)) {
  296. array_walk($tmp,'sanitise_acl');
  297. $ret = implode('',$tmp);
  298. }
  299. return $ret;
  300. }}
  301. // generate a guaranteed unique (for this domain) item ID for ATOM
  302. // safe from birthday paradox
  303. if(! function_exists('item_new_uri')) {
  304. function item_new_uri($hostname,$uid) {
  305. do {
  306. $dups = false;
  307. $hash = random_string();
  308. $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
  309. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
  310. dbesc($uri));
  311. if(count($r))
  312. $dups = true;
  313. } while($dups == true);
  314. return $uri;
  315. }}
  316. // Generate a guaranteed unique photo ID.
  317. // safe from birthday paradox
  318. if(! function_exists('photo_new_resource')) {
  319. function photo_new_resource() {
  320. do {
  321. $found = false;
  322. $resource = hash('md5',uniqid(mt_rand(),true));
  323. $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
  324. dbesc($resource)
  325. );
  326. if(count($r))
  327. $found = true;
  328. } while($found == true);
  329. return $resource;
  330. }}
  331. // wrapper to load a view template, checking for alternate
  332. // languages before falling back to the default
  333. // obsolete, deprecated.
  334. if(! function_exists('load_view_file')) {
  335. function load_view_file($s) {
  336. global $lang, $a;
  337. if(! isset($lang))
  338. $lang = 'en';
  339. $b = basename($s);
  340. $d = dirname($s);
  341. if(file_exists("$d/$lang/$b")) {
  342. $stamp1 = microtime(true);
  343. $content = file_get_contents("$d/$lang/$b");
  344. $a->save_timestamp($stamp1, "file");
  345. return $content;
  346. }
  347. $theme = current_theme();
  348. if(file_exists("$d/theme/$theme/$b")) {
  349. $stamp1 = microtime(true);
  350. $content = file_get_contents("$d/theme/$theme/$b");
  351. $a->save_timestamp($stamp1, "file");
  352. return $content;
  353. }
  354. $stamp1 = microtime(true);
  355. $content = file_get_contents($s);
  356. $a->save_timestamp($stamp1, "file");
  357. return $content;
  358. }}
  359. if(! function_exists('get_intltext_template')) {
  360. function get_intltext_template($s) {
  361. global $lang;
  362. $a = get_app();
  363. $engine = '';
  364. if($a->theme['template_engine'] === 'smarty3')
  365. $engine = "/smarty3";
  366. if(! isset($lang))
  367. $lang = 'en';
  368. if(file_exists("view/$lang$engine/$s")) {
  369. $stamp1 = microtime(true);
  370. $content = file_get_contents("view/$lang$engine/$s");
  371. $a->save_timestamp($stamp1, "file");
  372. return $content;
  373. } elseif(file_exists("view/en$engine/$s")) {
  374. $stamp1 = microtime(true);
  375. $content = file_get_contents("view/en$engine/$s");
  376. $a->save_timestamp($stamp1, "file");
  377. return $content;
  378. } else {
  379. $stamp1 = microtime(true);
  380. $content = file_get_contents("view$engine/$s");
  381. $a->save_timestamp($stamp1, "file");
  382. return $content;
  383. }
  384. }}
  385. if(! function_exists('get_markup_template')) {
  386. function get_markup_template($s, $root = '') {
  387. $stamp1 = microtime(true);
  388. $a = get_app();
  389. if($a->theme['template_engine'] === 'smarty3') {
  390. $template_file = get_template_file($a, 'smarty3/' . $s, $root);
  391. $template = new FriendicaSmarty();
  392. $template->filename = $template_file;
  393. $a->save_timestamp($stamp1, "rendering");
  394. return $template;
  395. }
  396. else {
  397. $template_file = get_template_file($a, $s, $root);
  398. $a->save_timestamp($stamp1, "rendering");
  399. $stamp1 = microtime(true);
  400. $content = file_get_contents($template_file);
  401. $a->save_timestamp($stamp1, "file");
  402. return $content;
  403. }
  404. }}
  405. if(! function_exists("get_template_file")) {
  406. function get_template_file($a, $filename, $root = '') {
  407. $theme = current_theme();
  408. // Make sure $root ends with a slash /
  409. if($root !== '' && $root[strlen($root)-1] !== '/')
  410. $root = $root . '/';
  411. if(file_exists("{$root}view/theme/$theme/$filename"))
  412. $template_file = "{$root}view/theme/$theme/$filename";
  413. elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
  414. $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
  415. else
  416. $template_file = "{$root}view/$filename";
  417. return $template_file;
  418. }}
  419. // for html,xml parsing - let's say you've got
  420. // an attribute foobar="class1 class2 class3"
  421. // and you want to find out if it contains 'class3'.
  422. // you can't use a normal sub string search because you
  423. // might match 'notclass3' and a regex to do the job is
  424. // possible but a bit complicated.
  425. // pass the attribute string as $attr and the attribute you
  426. // are looking for as $s - returns true if found, otherwise false
  427. if(! function_exists('attribute_contains')) {
  428. function attribute_contains($attr,$s) {
  429. $a = explode(' ', $attr);
  430. if(count($a) && in_array($s,$a))
  431. return true;
  432. return false;
  433. }}
  434. if(! function_exists('logger')) {
  435. function logger($msg,$level = 0) {
  436. // turn off logger in install mode
  437. global $a;
  438. global $db;
  439. if(($a->module == 'install') || (! ($db && $db->connected))) return;
  440. $debugging = get_config('system','debugging');
  441. $loglevel = intval(get_config('system','loglevel'));
  442. $logfile = get_config('system','logfile');
  443. if((! $debugging) || (! $logfile) || ($level > $loglevel))
  444. return;
  445. $stamp1 = microtime(true);
  446. @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
  447. $a->save_timestamp($stamp1, "file");
  448. return;
  449. }}
  450. if(! function_exists('activity_match')) {
  451. function activity_match($haystack,$needle) {
  452. if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
  453. return true;
  454. return false;
  455. }}
  456. // Pull out all #hashtags and @person tags from $s;
  457. // We also get @person@domain.com - which would make
  458. // the regex quite complicated as tags can also
  459. // end a sentence. So we'll run through our results
  460. // and strip the period from any tags which end with one.
  461. // Returns array of tags found, or empty array.
  462. if(! function_exists('get_tags')) {
  463. function get_tags($s) {
  464. $ret = array();
  465. // ignore anything in a code block
  466. $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
  467. // Force line feeds at bbtags
  468. $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
  469. // ignore anything in a bbtag
  470. $s = preg_replace('/\[(.*?)\]/sm','',$s);
  471. // Match full names against @tags including the space between first and last
  472. // We will look these up afterward to see if they are full names or not recognisable.
  473. if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
  474. foreach($match[1] as $mtch) {
  475. if(strstr($mtch,"]")) {
  476. // we might be inside a bbcode color tag - leave it alone
  477. continue;
  478. }
  479. if(substr($mtch,-1,1) === '.')
  480. $ret[] = substr($mtch,0,-1);
  481. else
  482. $ret[] = $mtch;
  483. }
  484. }
  485. // Otherwise pull out single word tags. These can be @nickname, @first_last
  486. // and #hash tags.
  487. if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
  488. foreach($match[1] as $mtch) {
  489. if(strstr($mtch,"]")) {
  490. // we might be inside a bbcode color tag - leave it alone
  491. continue;
  492. }
  493. if(substr($mtch,-1,1) === '.')
  494. $mtch = substr($mtch,0,-1);
  495. // ignore strictly numeric tags like #1
  496. if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
  497. continue;
  498. // try not to catch url fragments
  499. if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
  500. continue;
  501. $ret[] = $mtch;
  502. }
  503. }
  504. return $ret;
  505. }}
  506. // quick and dirty quoted_printable encoding
  507. if(! function_exists('qp')) {
  508. function qp($s) {
  509. return str_replace ("%","=",rawurlencode($s));
  510. }}
  511. if(! function_exists('get_mentions')) {
  512. function get_mentions($item) {
  513. $o = '';
  514. if(! strlen($item['tag']))
  515. return $o;
  516. $arr = explode(',',$item['tag']);
  517. foreach($arr as $x) {
  518. $matches = null;
  519. if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
  520. $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
  521. $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
  522. }
  523. }
  524. return $o;
  525. }}
  526. if(! function_exists('contact_block')) {
  527. function contact_block() {
  528. $o = '';
  529. $a = get_app();
  530. $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
  531. if($shown === false)
  532. $shown = 24;
  533. if($shown == 0)
  534. return;
  535. if((! is_array($a->profile)) || ($a->profile['hide-friends']))
  536. return $o;
  537. $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0",
  538. intval($a->profile['uid'])
  539. );
  540. if(count($r)) {
  541. $total = intval($r[0]['total']);
  542. }
  543. if(! $total) {
  544. $contacts = t('No contacts');
  545. $micropro = Null;
  546. } else {
  547. $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY RAND() LIMIT %d",
  548. intval($a->profile['uid']),
  549. intval($shown)
  550. );
  551. if(count($r)) {
  552. $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
  553. $micropro = Array();
  554. foreach($r as $rr) {
  555. $micropro[] = micropro($rr,true,'mpfriend');
  556. }
  557. }
  558. }
  559. $tpl = get_markup_template('contact_block.tpl');
  560. $o = replace_macros($tpl, array(
  561. '$contacts' => $contacts,
  562. '$nickname' => $a->profile['nickname'],
  563. '$viewcontacts' => t('View Contacts'),
  564. '$micropro' => $micropro,
  565. ));
  566. $arr = array('contacts' => $r, 'output' => $o);
  567. call_hooks('contact_block_end', $arr);
  568. return $o;
  569. }}
  570. if(! function_exists('micropro')) {
  571. function micropro($contact, $redirect = false, $class = '', $textmode = false) {
  572. if($class)
  573. $class = ' ' . $class;
  574. $url = $contact['url'];
  575. $sparkle = '';
  576. $redir = false;
  577. if($redirect) {
  578. $a = get_app();
  579. $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
  580. if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
  581. $redir = true;
  582. $url = $redirect_url;
  583. $sparkle = ' sparkle';
  584. }
  585. else
  586. $url = zrl($url);
  587. }
  588. $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
  589. if($click)
  590. $url = '';
  591. if($textmode) {
  592. return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
  593. . (($click) ? ' fakelink' : '') . '" '
  594. . (($redir) ? ' target="redir" ' : '')
  595. . (($url) ? ' href="' . $url . '"' : '') . $click
  596. . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
  597. . '" >'. $contact['name'] . '</a></div>' . "\r\n";
  598. }
  599. else {
  600. return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
  601. . (($click) ? ' fakelink' : '') . '" '
  602. . (($redir) ? ' target="redir" ' : '')
  603. . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
  604. . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
  605. . '" /></a></div>' . "\r\n";
  606. }
  607. }}
  608. if(! function_exists('search')) {
  609. function search($s,$id='search-box',$url='/search',$save = false) {
  610. $a = get_app();
  611. $o = '<div id="' . $id . '">';
  612. $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
  613. $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
  614. $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
  615. if($save)
  616. $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
  617. $o .= '</form></div>';
  618. return $o;
  619. }}
  620. if(! function_exists('valid_email')) {
  621. function valid_email($x){
  622. if(get_config('system','disable_email_validation'))
  623. return true;
  624. if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
  625. return true;
  626. return false;
  627. }}
  628. /**
  629. *
  630. * Function: linkify
  631. *
  632. * Replace naked text hyperlink with HTML formatted hyperlink
  633. *
  634. */
  635. if(! function_exists('linkify')) {
  636. function linkify($s) {
  637. $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
  638. $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
  639. return($s);
  640. }}
  641. function get_poke_verbs() {
  642. // index is present tense verb
  643. // value is array containing past tense verb, translation of present, translation of past
  644. $arr = array(
  645. 'poke' => array( 'poked', t('poke'), t('poked')),
  646. 'ping' => array( 'pinged', t('ping'), t('pinged')),
  647. 'prod' => array( 'prodded', t('prod'), t('prodded')),
  648. 'slap' => array( 'slapped', t('slap'), t('slapped')),
  649. 'finger' => array( 'fingered', t('finger'), t('fingered')),
  650. 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
  651. );
  652. call_hooks('poke_verbs', $arr);
  653. return $arr;
  654. }
  655. function get_mood_verbs() {
  656. // index is present tense verb
  657. // value is array containing past tense verb, translation of present, translation of past
  658. $arr = array(
  659. 'happy' => t('happy'),
  660. 'sad' => t('sad'),
  661. 'mellow' => t('mellow'),
  662. 'tired' => t('tired'),
  663. 'perky' => t('perky'),
  664. 'angry' => t('angry'),
  665. 'stupefied' => t('stupified'),
  666. 'puzzled' => t('puzzled'),
  667. 'interested' => t('interested'),
  668. 'bitter' => t('bitter'),
  669. 'cheerful' => t('cheerful'),
  670. 'alive' => t('alive'),
  671. 'annoyed' => t('annoyed'),
  672. 'anxious' => t('anxious'),
  673. 'cranky' => t('cranky'),
  674. 'disturbed' => t('disturbed'),
  675. 'frustrated' => t('frustrated'),
  676. 'motivated' => t('motivated'),
  677. 'relaxed' => t('relaxed'),
  678. 'surprised' => t('surprised'),
  679. );
  680. call_hooks('mood_verbs', $arr);
  681. return $arr;
  682. }
  683. /**
  684. *
  685. * Function: smilies
  686. *
  687. * Description:
  688. * Replaces text emoticons with graphical images
  689. *
  690. * @Parameter: string $s
  691. *
  692. * Returns string
  693. *
  694. * It is expected that this function will be called using HTML text.
  695. * We will escape text between HTML pre and code blocks from being
  696. * processed.
  697. *
  698. * At a higher level, the bbcode [nosmile] tag can be used to prevent this
  699. * function from being executed by the prepare_text() routine when preparing
  700. * bbcode source for HTML display
  701. *
  702. */
  703. if(! function_exists('smilies')) {
  704. function smilies($s, $sample = false) {
  705. $a = get_app();
  706. if(intval(get_config('system','no_smilies'))
  707. || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
  708. return $s;
  709. $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
  710. $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
  711. $texts = array(
  712. '&lt;3',
  713. '&lt;/3',
  714. '&lt;\\3',
  715. ':-)',
  716. ';-)',
  717. ':-(',
  718. ':-P',
  719. ':-p',
  720. ':-"',
  721. ':-&quot;',
  722. ':-x',
  723. ':-X',
  724. ':-D',
  725. '8-|',
  726. '8-O',
  727. ':-O',
  728. '\\o/',
  729. 'o.O',
  730. 'O.o',
  731. 'o_O',
  732. 'O_o',
  733. ":'(",
  734. ":-!",
  735. ":-/",
  736. ":-[",
  737. "8-)",
  738. ':beer',
  739. ':homebrew',
  740. ':coffee',
  741. ':facepalm',
  742. ':like',
  743. ':dislike',
  744. '~friendica'
  745. );
  746. $icons = array(
  747. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
  748. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
  749. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
  750. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
  751. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
  752. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
  753. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
  754. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
  755. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
  756. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
  757. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
  758. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
  759. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
  760. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
  761. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
  762. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
  763. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
  764. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
  765. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
  766. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
  767. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
  768. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
  769. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
  770. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
  771. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
  772. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
  773. '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
  774. '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
  775. '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
  776. '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
  777. '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
  778. '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
  779. '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
  780. );
  781. $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
  782. call_hooks('smilie', $params);
  783. if($sample) {
  784. $s = '<div class="smiley-sample">';
  785. for($x = 0; $x < count($params['texts']); $x ++) {
  786. $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
  787. }
  788. }
  789. else {
  790. $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
  791. $s = str_replace($params['texts'],$params['icons'],$params['string']);
  792. }
  793. $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
  794. $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
  795. return $s;
  796. }}
  797. function smile_encode($m) {
  798. return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
  799. }
  800. function smile_decode($m) {
  801. return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
  802. }
  803. // expand <3333 to the correct number of hearts
  804. function preg_heart($x) {
  805. $a = get_app();
  806. if(strlen($x[1]) == 1)
  807. return $x[0];
  808. $t = '';
  809. for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
  810. $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
  811. $r = str_replace($x[0],$t,$x[0]);
  812. return $r;
  813. }
  814. if(! function_exists('day_translate')) {
  815. function day_translate($s) {
  816. $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
  817. array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
  818. $s);
  819. $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
  820. 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')),
  821. $ret);
  822. return $ret;
  823. }}
  824. if(! function_exists('normalise_link')) {
  825. function normalise_link($url) {
  826. $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
  827. return(rtrim($ret,'/'));
  828. }}
  829. /**
  830. *
  831. * Compare two URLs to see if they are the same, but ignore
  832. * slight but hopefully insignificant differences such as if one
  833. * is https and the other isn't, or if one is www.something and
  834. * the other isn't - and also ignore case differences.
  835. *
  836. * Return true if the URLs match, otherwise false.
  837. *
  838. */
  839. if(! function_exists('link_compare')) {
  840. function link_compare($a,$b) {
  841. if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
  842. return true;
  843. return false;
  844. }}
  845. // Given an item array, convert the body element from bbcode to html and add smilie icons.
  846. // If attach is true, also add icons for item attachments
  847. if(! function_exists('prepare_body')) {
  848. function prepare_body($item,$attach = false) {
  849. $a = get_app();
  850. call_hooks('prepare_body_init', $item);
  851. //$cachefile = get_cachefile($item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']));
  852. $cachefile = get_cachefile($item["guid"]."-".hash("md5", $item['body']));
  853. if (($cachefile != '')) {
  854. if (file_exists($cachefile)) {
  855. $stamp1 = microtime(true);
  856. $s = file_get_contents($cachefile);
  857. $a->save_timestamp($stamp1, "file");
  858. } else {
  859. $s = prepare_text($item['body']);
  860. $stamp1 = microtime(true);
  861. file_put_contents($cachefile, $s);
  862. $a->save_timestamp($stamp1, "file");
  863. logger('prepare_body: put item '.$item["id"].' into cachefile '.$cachefile);
  864. }
  865. } else
  866. $s = prepare_text($item['body']);
  867. $prep_arr = array('item' => $item, 'html' => $s);
  868. call_hooks('prepare_body', $prep_arr);
  869. $s = $prep_arr['html'];
  870. if(! $attach) {
  871. // Replace the blockquotes with quotes that are used in mails
  872. $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
  873. $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
  874. return $s;
  875. }
  876. $arr = explode('[/attach],',$item['attach']);
  877. if(count($arr)) {
  878. $s .= '<div class="body-attach">';
  879. foreach($arr as $r) {
  880. $matches = false;
  881. $icon = '';
  882. $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
  883. if($cnt) {
  884. foreach($matches as $mtch) {
  885. $icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
  886. switch($icontype) {
  887. case 'video':
  888. case 'audio':
  889. case 'image':
  890. case 'text':
  891. $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
  892. break;
  893. default:
  894. $icon = '<div class="attachtype icon s22 type-unkn"></div>';
  895. break;
  896. }
  897. $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
  898. $title .= ' ' . $mtch[2] . ' ' . t('bytes');
  899. if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
  900. $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
  901. else
  902. $the_url = $mtch[1];
  903. $s .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
  904. }
  905. }
  906. }
  907. $s .= '<div class="clear"></div></div>';
  908. }
  909. // Look for spoiler
  910. $spoilersearch = '<blockquote class="spoiler">';
  911. // Remove line breaks before the spoiler
  912. while ((strpos($s, "\n".$spoilersearch) !== false))
  913. $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
  914. while ((strpos($s, "<br />".$spoilersearch) !== false))
  915. $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
  916. while ((strpos($s, $spoilersearch) !== false)) {
  917. $pos = strpos($s, $spoilersearch);
  918. $rnd = random_string(8);
  919. $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
  920. '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
  921. $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
  922. }
  923. // Look for quote with author
  924. $authorsearch = '<blockquote class="author">';
  925. while ((strpos($s, $authorsearch) !== false)) {
  926. $pos = strpos($s, $authorsearch);
  927. $rnd = random_string(8);
  928. $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
  929. '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
  930. $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
  931. }
  932. $prep_arr = array('item' => $item, 'html' => $s);
  933. call_hooks('prepare_body_final', $prep_arr);
  934. return $prep_arr['html'];
  935. }}
  936. // Given a text string, convert from bbcode to html and add smilie icons.
  937. if(! function_exists('prepare_text')) {
  938. function prepare_text($text) {
  939. require_once('include/bbcode.php');
  940. if(stristr($text,'[nosmile]'))
  941. $s = bbcode($text);
  942. else
  943. $s = smilies(bbcode($text));
  944. return $s;
  945. }}
  946. /**
  947. * returns
  948. * [
  949. * //categories [
  950. * {
  951. * 'name': 'category name',
  952. * 'removeurl': 'url to remove this category',
  953. * 'first': 'is the first in this array? true/false',
  954. * 'last': 'is the last in this array? true/false',
  955. * } ,
  956. * ....
  957. * ],
  958. * // folders [
  959. * 'name': 'folder name',
  960. * 'removeurl': 'url to remove this folder',
  961. * 'first': 'is the first in this array? true/false',
  962. * 'last': 'is the last in this array? true/false',
  963. * } ,
  964. * ....
  965. * ]
  966. * ]
  967. */
  968. function get_cats_and_terms($item) {
  969. $a = get_app();
  970. $categories = array();
  971. $folders = array();
  972. $matches = false; $first = true;
  973. $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
  974. if($cnt) {
  975. foreach($matches as $mtch) {
  976. $categories[] = array(
  977. 'name' => xmlify(file_tag_decode($mtch[1])),
  978. 'url' => "#",
  979. 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
  980. 'first' => $first,
  981. 'last' => false
  982. );
  983. $first = false;
  984. }
  985. }
  986. if (count($categories)) $categories[count($categories)-1]['last'] = true;
  987. if(local_user() == $item['uid']) {
  988. $matches = false; $first = true;
  989. $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
  990. if($cnt) {
  991. foreach($matches as $mtch) {
  992. $folders[] = array(
  993. 'name' => xmlify(file_tag_decode($mtch[1])),
  994. 'url' => "#",
  995. 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
  996. 'first' => $first,
  997. 'last' => false
  998. );
  999. $first = false;
  1000. }
  1001. }
  1002. }
  1003. if (count($folders)) $folders[count($folders)-1]['last'] = true;
  1004. return array($categories, $folders);
  1005. }
  1006. /**
  1007. * return atom link elements for all of our hubs
  1008. */
  1009. if(! function_exists('feed_hublinks')) {
  1010. function feed_hublinks() {
  1011. $hub = get_config('system','huburl');
  1012. $hubxml = '';
  1013. if(strlen($hub)) {
  1014. $hubs = explode(',', $hub);
  1015. if(count($hubs)) {
  1016. foreach($hubs as $h) {
  1017. $h = trim($h);
  1018. if(! strlen($h))
  1019. continue;
  1020. $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
  1021. }
  1022. }
  1023. }
  1024. return $hubxml;
  1025. }}
  1026. /* return atom link elements for salmon endpoints */
  1027. if(! function_exists('feed_salmonlinks')) {
  1028. function feed_salmonlinks($nick) {
  1029. $a = get_app();
  1030. $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
  1031. // old style links that status.net still needed as of 12/2010
  1032. $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
  1033. $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
  1034. return $salmon;
  1035. }}
  1036. if(! function_exists('get_plink')) {
  1037. function get_plink($item) {
  1038. $a = get_app();
  1039. if (x($item,'plink') && ($item['private'] != 1)) {
  1040. return array(
  1041. 'href' => $item['plink'],
  1042. 'title' => t('link to source'),
  1043. );
  1044. }
  1045. else {
  1046. return false;
  1047. }
  1048. }}
  1049. if(! function_exists('unamp')) {
  1050. function unamp($s) {
  1051. return str_replace('&amp;', '&', $s);
  1052. }}
  1053. if(! function_exists('lang_selector')) {
  1054. function lang_selector() {
  1055. global $lang;
  1056. $langs = glob('view/*/strings.php');
  1057. $lang_options = array();
  1058. $selected = "";
  1059. if(is_array($langs) && count($langs)) {
  1060. $langs[] = '';
  1061. if(! in_array('view/en/strings.php',$langs))
  1062. $langs[] = 'view/en/';
  1063. asort($langs);
  1064. foreach($langs as $l) {
  1065. if($l == '') {
  1066. $lang_options[""] = t('default');
  1067. continue;
  1068. }
  1069. $ll = substr($l,5);
  1070. $ll = substr($ll,0,strrpos($ll,'/'));
  1071. $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
  1072. $lang_options[$ll]=$ll;
  1073. }
  1074. }
  1075. $tpl = get_markup_template("lang_selector.tpl");
  1076. $o = replace_macros($tpl, array(
  1077. '$title' => t('Select an alternate language'),
  1078. '$langs' => array($lang_options, $selected),
  1079. ));
  1080. return $o;
  1081. }}
  1082. if(! function_exists('return_bytes')) {
  1083. function return_bytes ($size_str) {
  1084. switch (substr ($size_str, -1))
  1085. {
  1086. case 'M': case 'm': return (int)$size_str * 1048576;
  1087. case 'K': case 'k': return (int)$size_str * 1024;
  1088. case 'G': case 'g': return (int)$size_str * 1073741824;
  1089. default: return $size_str;
  1090. }
  1091. }}
  1092. function generate_user_guid() {
  1093. $found = true;
  1094. do {
  1095. $guid = random_string(16);
  1096. $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
  1097. dbesc($guid)
  1098. );
  1099. if(! count($x))
  1100. $found = false;
  1101. } while ($found == true );
  1102. return $guid;
  1103. }
  1104. function base64url_encode($s, $strip_padding = false) {
  1105. $s = strtr(base64_encode($s),'+/','-_');
  1106. if($strip_padding)
  1107. $s = str_replace('=','',$s);
  1108. return $s;
  1109. }
  1110. function base64url_decode($s) {
  1111. if(is_array($s)) {
  1112. logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
  1113. return $s;
  1114. }
  1115. /*
  1116. * // Placeholder for new rev of salmon which strips base64 padding.
  1117. * // PHP base64_decode handles the un-padded input without requiring this step
  1118. * // Uncomment if you find you need it.
  1119. *
  1120. * $l = strlen($s);
  1121. * if(! strpos($s,'=')) {
  1122. * $m = $l % 4;
  1123. * if($m == 2)
  1124. * $s .= '==';
  1125. * if($m == 3)
  1126. * $s .= '=';
  1127. * }
  1128. *
  1129. */
  1130. return base64_decode(strtr($s,'-_','+/'));
  1131. }
  1132. if (!function_exists('str_getcsv')) {
  1133. function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
  1134. if (is_string($input) && !empty($input)) {
  1135. $output = array();
  1136. $tmp = preg_split("/".$eol."/",$input);
  1137. if (is_array($tmp) && !empty($tmp)) {
  1138. while (list($line_num, $line) = each($tmp)) {
  1139. if (preg_match("/".$escape.$enclosure."/",$line)) {
  1140. while ($strlen = strlen($line)) {
  1141. $pos_delimiter = strpos($line,$delimiter);
  1142. $pos_enclosure_start = strpos($line,$enclosure);
  1143. if (
  1144. is_int($pos_delimiter) && is_int($pos_enclosure_start)
  1145. && ($pos_enclosure_start < $pos_delimiter)
  1146. ) {
  1147. $enclosed_str = substr($line,1);
  1148. $pos_enclosure_end = strpos($enclosed_str,$enclosure);
  1149. $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
  1150. $output[$line_num][] = $enclosed_str;
  1151. $offset = $pos_enclosure_end+3;
  1152. } else {
  1153. if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
  1154. $output[$line_num][] = substr($line,0);
  1155. $offset = strlen($line);
  1156. } else {
  1157. $output[$line_num][] = substr($line,0,$pos_delimiter);
  1158. $offset = (
  1159. !empty($pos_enclosure_start)
  1160. && ($pos_enclosure_start < $pos_delimiter)
  1161. )
  1162. ?$pos_enclosure_start
  1163. :$pos_delimiter+1;
  1164. }
  1165. }
  1166. $line = substr($line,$offset);
  1167. }
  1168. } else {
  1169. $line = preg_split("/".$delimiter."/",$line);
  1170. /*
  1171. * Validating against pesky extra line breaks creating false rows.
  1172. */
  1173. if (is_array($line) && !empty($line[0])) {
  1174. $output[$line_num] = $line;
  1175. }
  1176. }
  1177. }
  1178. return $output;
  1179. } else {
  1180. return false;
  1181. }
  1182. } else {
  1183. return false;
  1184. }
  1185. }
  1186. }
  1187. function cleardiv() {
  1188. return '<div class="clear"></div>';
  1189. }
  1190. function bb_translate_video($s) {
  1191. $matches = null;
  1192. $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
  1193. if($r) {
  1194. foreach($matches as $mtch) {
  1195. if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
  1196. $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
  1197. elseif(stristr($mtch[1],'vimeo'))
  1198. $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
  1199. }
  1200. }
  1201. return $s;
  1202. }
  1203. function html2bb_video($s) {
  1204. $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
  1205. '[youtube]$2[/youtube]', $s);
  1206. $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
  1207. '[youtube]$2[/youtube]', $s);
  1208. $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
  1209. '[vimeo]$2[/vimeo]', $s);
  1210. return $s;
  1211. }
  1212. /**
  1213. * apply xmlify() to all values of array $val, recursively
  1214. */
  1215. function array_xmlify($val){
  1216. if (is_bool($val)) return $val?"true":"false";
  1217. if (is_array($val)) return array_map('array_xmlify', $val);
  1218. return xmlify((string) $val);
  1219. }
  1220. function reltoabs($text, $base)
  1221. {
  1222. if (empty($base))
  1223. return $text;
  1224. $base = rtrim($base,'/');
  1225. $base2 = $base . "/";
  1226. // Replace links
  1227. $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
  1228. $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
  1229. $text = preg_replace($pattern, $replace, $text);
  1230. $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
  1231. $replace = "<a\${1} href=\"" . $base . "\${2}\"";
  1232. $text = preg_replace($pattern, $replace, $text);
  1233. // Replace images
  1234. $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
  1235. $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
  1236. $text = preg_replace($pattern, $replace, $text);
  1237. $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
  1238. $replace = "<img\${1} src=\"" . $base . "\${2}\"";
  1239. $text = preg_replace($pattern, $replace, $text);
  1240. // Done
  1241. return $text;
  1242. }
  1243. function item_post_type($item) {
  1244. if(intval($item['event-id']))
  1245. return t('event');
  1246. if(strlen($item['resource-id']))
  1247. return t('photo');
  1248. if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
  1249. return t('activity');
  1250. if($item['id'] != $item['parent'])
  1251. return t('comment');
  1252. return t('post');
  1253. }
  1254. // post categories and "save to file" use the same item.file table for storage.
  1255. // We will differentiate the different uses by wrapping categories in angle brackets
  1256. // and save to file categories in square brackets.
  1257. // To do this we need to escape these characters if they appear in our tag.
  1258. function file_tag_encode($s) {
  1259. return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
  1260. }
  1261. function file_tag_decode($s) {
  1262. return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
  1263. }
  1264. function file_tag_file_query($table,$s,$type = 'file') {
  1265. if($type == 'file')
  1266. $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
  1267. else
  1268. $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
  1269. return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
  1270. }
  1271. // ex. given music,video return <music><video> or [music][video]
  1272. function file_tag_list_to_file($list,$type = 'file') {
  1273. $tag_list = '';
  1274. if(strlen($list)) {
  1275. $list_array = explode(",",$list);
  1276. if($type == 'file') {
  1277. $lbracket = '[';
  1278. $rbracket = ']';
  1279. }
  1280. else {
  1281. $lbracket = '<';
  1282. $rbracket = '>';
  1283. }
  1284. foreach($list_array as $item) {
  1285. if(strlen($item)) {
  1286. $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
  1287. }
  1288. }
  1289. }
  1290. return $tag_list;
  1291. }
  1292. // ex. given <music><video>[friends], return music,video or friends
  1293. function file_tag_file_to_list($file,$type = 'file') {
  1294. $matches = false;
  1295. $list = '';
  1296. if($type == 'file') {
  1297. $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
  1298. }
  1299. else {
  1300. $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
  1301. }
  1302. if($cnt) {
  1303. foreach($matches as $mtch) {
  1304. if(strlen($list))
  1305. $list .= ',';
  1306. $list .= file_tag_decode($mtch[1]);
  1307. }
  1308. }
  1309. return $list;
  1310. }
  1311. function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
  1312. // $file_old - categories previously associated with an item
  1313. // $file_new - new list of categories for an item
  1314. if(! intval($uid))
  1315. return false;
  1316. if($file_old == $file_new)
  1317. return true;
  1318. $saved = get_pconfig($uid,'system','filetags');
  1319. if(strlen($saved)) {
  1320. if($type == 'file') {
  1321. $lbracket = '[';
  1322. $rbracket = ']';
  1323. }
  1324. else {
  1325. $lbracket = '<';
  1326. $rbracket = '>';
  1327. }
  1328. $filetags_updated = $saved;
  1329. // check for new tags to be added as filetags in pconfig
  1330. $new_tags = array();
  1331. $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
  1332. foreach($check_new_tags as $tag) {
  1333. if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
  1334. $new_tags[] = $tag;
  1335. }
  1336. $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
  1337. // check for deleted tags to be removed from filetags in pconfig
  1338. $deleted_tags = array();
  1339. $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
  1340. foreach($check_deleted_tags as $tag) {
  1341. if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
  1342. $deleted_tags[] = $tag;
  1343. }
  1344. foreach($deleted_tags as $key => $tag) {
  1345. $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
  1346. intval($uid)
  1347. );
  1348. if(count($r)) {
  1349. unset($deleted_tags[$key]);
  1350. }
  1351. else {
  1352. $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
  1353. }
  1354. }
  1355. if($saved != $filetags_updated) {
  1356. set_pconfig($uid,'system','filetags', $filetags_updated);
  1357. }
  1358. return true;
  1359. }
  1360. else
  1361. if(strlen($file_new)) {
  1362. set_pconfig($uid,'system','filetags', $file_new);
  1363. }
  1364. return true;
  1365. }
  1366. function file_tag_save_file($uid,$item,$file) {
  1367. $result = false;
  1368. if(! intval($uid))
  1369. return false;
  1370. $r = q("select file from item where id = %d and uid = %d limit 1",
  1371. intval($item),
  1372. intval($uid)
  1373. );
  1374. if(count($r)) {
  1375. if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
  1376. q("update item set file = '%s' where id = %d and uid = %d limit 1",
  1377. dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
  1378. intval($item),
  1379. intval($uid)
  1380. );
  1381. $saved = get_pconfig($uid,'system','filetags');
  1382. if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
  1383. set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
  1384. info( t('Item filed') );
  1385. }
  1386. return true;
  1387. }
  1388. function file_tag_unsave_file($uid,$item,$file,$cat = false) {
  1389. $result = false;
  1390. if(! intval($uid))
  1391. return false;
  1392. if($cat == true)
  1393. $pattern = '<' . file_tag_encode($file) . '>' ;
  1394. else
  1395. $pattern = '[' . file_tag_encode($file) . ']' ;
  1396. $r = q("select file from item where id = %d and uid = %d limit 1",
  1397. intval($item),
  1398. intval($uid)
  1399. );
  1400. if(! count($r))
  1401. return false;
  1402. q("update item set file = '%s' where id = %d and uid = %d limit 1",
  1403. dbesc(str_replace($pattern,'',$r[0]['file'])),
  1404. intval($item),
  1405. intval($uid)
  1406. );
  1407. $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
  1408. intval($uid)
  1409. );
  1410. if(! count($r)) {
  1411. $saved = get_pconfig($uid,'system','filetags');
  1412. set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
  1413. }
  1414. return true;
  1415. }
  1416. function normalise_openid($s) {
  1417. return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
  1418. }
  1419. function undo_post_tagging($s) {
  1420. $matches = null;
  1421. $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
  1422. if($cnt) {
  1423. foreach($matches as $mtch) {
  1424. $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
  1425. }
  1426. }
  1427. return $s;
  1428. }
  1429. function fix_mce_lf($s) {
  1430. $s = str_replace("\r\n","\n",$s);
  1431. // $s = str_replace("\n\n","\n",$s);
  1432. return $s;
  1433. }
  1434. function protect_sprintf($s) {
  1435. return(str_replace('%','%%',$s));
  1436. }
  1437. function is_a_date_arg($s) {
  1438. $i = intval($s);
  1439. if($i > 1900) {
  1440. $y = date('Y');
  1441. if($i <= $y+1 && strpos($s,'-') == 4) {
  1442. $m = intval(substr($s,5));
  1443. if($m > 0 && $m <= 12)
  1444. return true;
  1445. }
  1446. }
  1447. return false;
  1448. }