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.
 
 
 
 
 
 

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