Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

2238 satır
58KB

  1. <?php
  2. require_once("include/template_processor.php");
  3. require_once("include/friendica_smarty.php");
  4. require_once("include/Smilies.php");
  5. require_once("include/map.php");
  6. require_once("mod/proxy.php");
  7. if(! function_exists('replace_macros')) {
  8. /**
  9. * This is our template processor
  10. *
  11. * @param string|FriendicaSmarty $s the string requiring macro substitution,
  12. * or an instance of FriendicaSmarty
  13. * @param array $r key value pairs (search => replace)
  14. * @return string substituted string
  15. */
  16. function replace_macros($s,$r) {
  17. $stamp1 = microtime(true);
  18. $a = get_app();
  19. // pass $baseurl to all templates
  20. $r['$baseurl'] = App::get_baseurl();
  21. $t = $a->template_engine();
  22. try {
  23. $output = $t->replace_macros($s,$r);
  24. } catch (Exception $e) {
  25. echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
  26. }
  27. $a->save_timestamp($stamp1, "rendering");
  28. return $output;
  29. }}
  30. // random string, there are 86 characters max in text mode, 128 for hex
  31. // output is urlsafe
  32. define('RANDOM_STRING_HEX', 0x00 );
  33. define('RANDOM_STRING_TEXT', 0x01 );
  34. if(! function_exists('random_string')) {
  35. function random_string($size = 64,$type = RANDOM_STRING_HEX) {
  36. // generate a bit of entropy and run it through the whirlpool
  37. $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
  38. $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
  39. return(substr($s,0,$size));
  40. }}
  41. if(! function_exists('notags')) {
  42. /**
  43. * This is our primary input filter.
  44. *
  45. * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
  46. * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
  47. * after cleansing, and angle chars with the high bit set could get through as markup.
  48. *
  49. * This is now disabled because it was interfering with some legitimate unicode sequences
  50. * and hopefully there aren't a lot of those browsers left.
  51. *
  52. * Use this on any text input where angle chars are not valid or permitted
  53. * They will be replaced with safer brackets. This may be filtered further
  54. * if these are not allowed either.
  55. *
  56. * @param string $string Input string
  57. * @return string Filtered string
  58. */
  59. function notags($string) {
  60. return(str_replace(array("<",">"), array('[',']'), $string));
  61. // High-bit filter no longer used
  62. // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
  63. }}
  64. if(! function_exists('escape_tags')) {
  65. /**
  66. * use this on "body" or "content" input where angle chars shouldn't be removed,
  67. * and allow them to be safely displayed.
  68. * @param string $string
  69. * @return string
  70. */
  71. function escape_tags($string) {
  72. return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
  73. }}
  74. // generate a string that's random, but usually pronounceable.
  75. // used to generate initial passwords
  76. if(! function_exists('autoname')) {
  77. /**
  78. * generate a string that's random, but usually pronounceable.
  79. * used to generate initial passwords
  80. * @param int $len
  81. * @return string
  82. */
  83. function autoname($len) {
  84. if($len <= 0)
  85. return '';
  86. $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
  87. if(mt_rand(0,5) == 4)
  88. $vowels[] = 'y';
  89. $cons = array(
  90. 'b','bl','br',
  91. 'c','ch','cl','cr',
  92. 'd','dr',
  93. 'f','fl','fr',
  94. 'g','gh','gl','gr',
  95. 'h',
  96. 'j',
  97. 'k','kh','kl','kr',
  98. 'l',
  99. 'm',
  100. 'n',
  101. 'p','ph','pl','pr',
  102. 'qu',
  103. 'r','rh',
  104. 's','sc','sh','sm','sp','st',
  105. 't','th','tr',
  106. 'v',
  107. 'w','wh',
  108. 'x',
  109. 'z','zh'
  110. );
  111. $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
  112. 'nd','ng','nk','nt','rn','rp','rt');
  113. $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
  114. 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
  115. $start = mt_rand(0,2);
  116. if($start == 0)
  117. $table = $vowels;
  118. else
  119. $table = $cons;
  120. $word = '';
  121. for ($x = 0; $x < $len; $x ++) {
  122. $r = mt_rand(0,count($table) - 1);
  123. $word .= $table[$r];
  124. if($table == $vowels)
  125. $table = array_merge($cons,$midcons);
  126. else
  127. $table = $vowels;
  128. }
  129. $word = substr($word,0,$len);
  130. foreach($noend as $noe) {
  131. if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
  132. $word = substr($word,0,-1);
  133. break;
  134. }
  135. }
  136. if(substr($word,-1) == 'q')
  137. $word = substr($word,0,-1);
  138. return $word;
  139. }}
  140. // escape text ($str) for XML transport
  141. // returns escaped text.
  142. if(! function_exists('xmlify')) {
  143. /**
  144. * escape text ($str) for XML transport
  145. * @param string $str
  146. * @return string Escaped text.
  147. */
  148. function xmlify($str) {
  149. /* $buffer = '';
  150. $len = mb_strlen($str);
  151. for($x = 0; $x < $len; $x ++) {
  152. $char = mb_substr($str,$x,1);
  153. switch( $char ) {
  154. case "\r" :
  155. break;
  156. case "&" :
  157. $buffer .= '&amp;';
  158. break;
  159. case "'" :
  160. $buffer .= '&apos;';
  161. break;
  162. case "\"" :
  163. $buffer .= '&quot;';
  164. break;
  165. case '<' :
  166. $buffer .= '&lt;';
  167. break;
  168. case '>' :
  169. $buffer .= '&gt;';
  170. break;
  171. case "\n" :
  172. $buffer .= "\n";
  173. break;
  174. default :
  175. $buffer .= $char;
  176. break;
  177. }
  178. }*/
  179. /*
  180. $buffer = mb_ereg_replace("&", "&amp;", $str);
  181. $buffer = mb_ereg_replace("'", "&apos;", $buffer);
  182. $buffer = mb_ereg_replace('"', "&quot;", $buffer);
  183. $buffer = mb_ereg_replace("<", "&lt;", $buffer);
  184. $buffer = mb_ereg_replace(">", "&gt;", $buffer);
  185. */
  186. $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
  187. $buffer = trim($buffer);
  188. return($buffer);
  189. }}
  190. if(! function_exists('unxmlify')) {
  191. /**
  192. * undo an xmlify
  193. * @param string $s xml escaped text
  194. * @return string unescaped text
  195. */
  196. function unxmlify($s) {
  197. // $ret = str_replace('&amp;','&', $s);
  198. // $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
  199. /*$ret = mb_ereg_replace('&amp;', '&', $s);
  200. $ret = mb_ereg_replace('&apos;', "'", $ret);
  201. $ret = mb_ereg_replace('&quot;', '"', $ret);
  202. $ret = mb_ereg_replace('&lt;', "<", $ret);
  203. $ret = mb_ereg_replace('&gt;', ">", $ret);
  204. */
  205. $ret = htmlspecialchars_decode($s, ENT_QUOTES);
  206. return $ret;
  207. }}
  208. if(! function_exists('hex2bin')) {
  209. /**
  210. * convenience wrapper, reverse the operation "bin2hex"
  211. * @param string $s
  212. * @return number
  213. */
  214. function hex2bin($s) {
  215. if(! (is_string($s) && strlen($s)))
  216. return '';
  217. if(! ctype_xdigit($s)) {
  218. return($s);
  219. }
  220. return(pack("H*",$s));
  221. }}
  222. /**
  223. * @brief Paginator function. Pushes relevant links in a pager array structure.
  224. *
  225. * Links are generated depending on the current page and the total number of items.
  226. * Inactive links (like "first" and "prev" on page 1) are given the "disabled" class.
  227. * Current page link is given the "active" CSS class
  228. *
  229. * @param App $a App instance
  230. * @param int $count [optional] item count (used with minimal pager)
  231. * @return Array data for pagination template
  232. */
  233. function paginate_data(App $a, $count = null) {
  234. $stripped = preg_replace('/([&?]page=[0-9]*)/', '', $a->query_string);
  235. $stripped = str_replace('q=', '', $stripped);
  236. $stripped = trim($stripped, '/');
  237. $pagenum = $a->pager['page'];
  238. if (($a->page_offset != '') AND !preg_match('/[?&].offset=/', $stripped)) {
  239. $stripped .= '&offset=' . urlencode($a->page_offset);
  240. }
  241. $url = $stripped;
  242. $data = array();
  243. function _l(&$d, $name, $url, $text, $class = '') {
  244. if (strpos($url, '?') === false && ($pos = strpos($url, '&')) !== false) {
  245. $url = substr($url, 0, $pos) . '?' . substr($url, $pos + 1);
  246. }
  247. $d[$name] = array('url' => $url, 'text' => $text, 'class' => $class);
  248. }
  249. if (!is_null($count)) {
  250. // minimal pager (newer / older)
  251. $data['class'] = 'pager';
  252. _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('newer'), 'previous' . ($a->pager['page'] == 1 ? ' disabled' : ''));
  253. _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('older'), 'next' . ($count <= 0 ? ' disabled' : ''));
  254. } else {
  255. // full pager (first / prev / 1 / 2 / ... / 14 / 15 / next / last)
  256. $data['class'] = 'pagination';
  257. if ($a->pager['total'] > $a->pager['itemspage']) {
  258. _l($data, 'first', $url . '&page=1', t('first'), $a->pager['page'] == 1 ? 'disabled' : '');
  259. _l($data, 'prev', $url . '&page=' . ($a->pager['page'] - 1), t('prev'), $a->pager['page'] == 1 ? 'disabled' : '');
  260. $numpages = $a->pager['total'] / $a->pager['itemspage'];
  261. $numstart = 1;
  262. $numstop = $numpages;
  263. // Limit the number of displayed page number buttons.
  264. if ($numpages > 8) {
  265. $numstart = (($pagenum > 4) ? ($pagenum - 4) : 1);
  266. $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 8));
  267. }
  268. $pages = array();
  269. for ($i = $numstart; $i <= $numstop; $i++) {
  270. if ($i == $a->pager['page']) {
  271. _l($pages, $i, '#', $i, 'current active');
  272. } else {
  273. _l($pages, $i, $url . '&page='. $i, $i, 'n');
  274. }
  275. }
  276. if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
  277. if ($i == $a->pager['page']) {
  278. _l($pages, $i, '#', $i, 'current active');
  279. } else {
  280. _l($pages, $i, $url . '&page=' . $i, $i, 'n');
  281. }
  282. }
  283. $data['pages'] = $pages;
  284. $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
  285. _l($data, 'next', $url . '&page=' . ($a->pager['page'] + 1), t('next'), $a->pager['page'] == $lastpage ? 'disabled' : '');
  286. _l($data, 'last', $url . '&page=' . $lastpage, t('last'), $a->pager['page'] == $lastpage ? 'disabled' : '');
  287. }
  288. }
  289. return $data;
  290. }
  291. if(! function_exists('paginate')) {
  292. /**
  293. * Automatic pagination.
  294. *
  295. * To use, get the count of total items.
  296. * Then call $a->set_pager_total($number_items);
  297. * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
  298. * Then call paginate($a) after the end of the display loop to insert the pager block on the page
  299. * (assuming there are enough items to paginate).
  300. * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
  301. * will limit the results to the correct items for the current page.
  302. * The actual page handling is then accomplished at the application layer.
  303. *
  304. * @param App $a App instance
  305. * @return string html for pagination #FIXME remove html
  306. */
  307. function paginate(App $a) {
  308. $data = paginate_data($a);
  309. $tpl = get_markup_template("paginate.tpl");
  310. return replace_macros($tpl, array("pager" => $data));
  311. }}
  312. if(! function_exists('alt_pager')) {
  313. /**
  314. * Alternative pager
  315. * @param App $a App instance
  316. * @param int $i
  317. * @return string html for pagination #FIXME remove html
  318. */
  319. function alt_pager(App $a, $i) {
  320. $data = paginate_data($a, $i);
  321. $tpl = get_markup_template("paginate.tpl");
  322. return replace_macros($tpl, array('pager' => $data));
  323. }}
  324. if(! function_exists('scroll_loader')) {
  325. /**
  326. * Loader for infinite scrolling
  327. * @return string html for loader
  328. */
  329. function scroll_loader() {
  330. $tpl = get_markup_template("scroll_loader.tpl");
  331. return replace_macros($tpl, array(
  332. 'wait' => t('Loading more entries...'),
  333. 'end' => t('The end')
  334. ));
  335. }}
  336. if(! function_exists('expand_acl')) {
  337. /**
  338. * Turn user/group ACLs stored as angle bracketed text into arrays
  339. *
  340. * @param string $s
  341. * @return array
  342. */
  343. function expand_acl($s) {
  344. // turn string array of angle-bracketed elements into numeric array
  345. // e.g. "<1><2><3>" => array(1,2,3);
  346. $ret = array();
  347. if(strlen($s)) {
  348. $t = str_replace('<','',$s);
  349. $a = explode('>',$t);
  350. foreach($a as $aa) {
  351. if(intval($aa))
  352. $ret[] = intval($aa);
  353. }
  354. }
  355. return $ret;
  356. }}
  357. if(! function_exists('sanitise_acl')) {
  358. /**
  359. * Wrap ACL elements in angle brackets for storage
  360. * @param string $item
  361. */
  362. function sanitise_acl(&$item) {
  363. if(intval($item))
  364. $item = '<' . intval(notags(trim($item))) . '>';
  365. else
  366. unset($item);
  367. }}
  368. if(! function_exists('perms2str')) {
  369. /**
  370. * Convert an ACL array to a storable string
  371. *
  372. * Normally ACL permissions will be an array.
  373. * We'll also allow a comma-separated string.
  374. *
  375. * @param string|array $p
  376. * @return string
  377. */
  378. function perms2str($p) {
  379. $ret = '';
  380. if(is_array($p))
  381. $tmp = $p;
  382. else
  383. $tmp = explode(',',$p);
  384. if(is_array($tmp)) {
  385. array_walk($tmp,'sanitise_acl');
  386. $ret = implode('',$tmp);
  387. }
  388. return $ret;
  389. }}
  390. if(! function_exists('item_new_uri')) {
  391. /**
  392. * generate a guaranteed unique (for this domain) item ID for ATOM
  393. * safe from birthday paradox
  394. *
  395. * @param string $hostname
  396. * @param int $uid
  397. * @return string
  398. */
  399. function item_new_uri($hostname,$uid, $guid = "") {
  400. do {
  401. $dups = false;
  402. if ($guid == "")
  403. $hash = get_guid(32);
  404. else {
  405. $hash = $guid;
  406. $guid = "";
  407. }
  408. $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
  409. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
  410. dbesc($uri));
  411. if (dbm::is_result($r))
  412. $dups = true;
  413. } while($dups == true);
  414. return $uri;
  415. }}
  416. // Generate a guaranteed unique photo ID.
  417. // safe from birthday paradox
  418. if(! function_exists('photo_new_resource')) {
  419. /**
  420. * Generate a guaranteed unique photo ID.
  421. * safe from birthday paradox
  422. *
  423. * @return string
  424. */
  425. function photo_new_resource() {
  426. do {
  427. $found = false;
  428. $resource = hash('md5',uniqid(mt_rand(),true));
  429. $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
  430. dbesc($resource)
  431. );
  432. if (dbm::is_result($r))
  433. $found = true;
  434. } while($found == true);
  435. return $resource;
  436. }}
  437. if(! function_exists('load_view_file')) {
  438. /**
  439. * @deprecated
  440. * wrapper to load a view template, checking for alternate
  441. * languages before falling back to the default
  442. *
  443. * @global string $lang
  444. * @global App $a
  445. * @param string $s view name
  446. * @return string
  447. */
  448. function load_view_file($s) {
  449. global $lang, $a;
  450. if(! isset($lang))
  451. $lang = 'en';
  452. $b = basename($s);
  453. $d = dirname($s);
  454. if(file_exists("$d/$lang/$b")) {
  455. $stamp1 = microtime(true);
  456. $content = file_get_contents("$d/$lang/$b");
  457. $a->save_timestamp($stamp1, "file");
  458. return $content;
  459. }
  460. $theme = current_theme();
  461. if(file_exists("$d/theme/$theme/$b")) {
  462. $stamp1 = microtime(true);
  463. $content = file_get_contents("$d/theme/$theme/$b");
  464. $a->save_timestamp($stamp1, "file");
  465. return $content;
  466. }
  467. $stamp1 = microtime(true);
  468. $content = file_get_contents($s);
  469. $a->save_timestamp($stamp1, "file");
  470. return $content;
  471. }}
  472. if(! function_exists('get_intltext_template')) {
  473. /**
  474. * load a view template, checking for alternate
  475. * languages before falling back to the default
  476. *
  477. * @global string $lang
  478. * @param string $s view path
  479. * @return string
  480. */
  481. function get_intltext_template($s) {
  482. global $lang;
  483. $a = get_app();
  484. $engine = '';
  485. if($a->theme['template_engine'] === 'smarty3')
  486. $engine = "/smarty3";
  487. if(! isset($lang))
  488. $lang = 'en';
  489. if(file_exists("view/lang/$lang$engine/$s")) {
  490. $stamp1 = microtime(true);
  491. $content = file_get_contents("view/lang/$lang$engine/$s");
  492. $a->save_timestamp($stamp1, "file");
  493. return $content;
  494. } elseif(file_exists("view/lang/en$engine/$s")) {
  495. $stamp1 = microtime(true);
  496. $content = file_get_contents("view/lang/en$engine/$s");
  497. $a->save_timestamp($stamp1, "file");
  498. return $content;
  499. } else {
  500. $stamp1 = microtime(true);
  501. $content = file_get_contents("view$engine/$s");
  502. $a->save_timestamp($stamp1, "file");
  503. return $content;
  504. }
  505. }}
  506. if(! function_exists('get_markup_template')) {
  507. /**
  508. * load template $s
  509. *
  510. * @param string $s
  511. * @param string $root
  512. * @return string
  513. */
  514. function get_markup_template($s, $root = '') {
  515. $stamp1 = microtime(true);
  516. $a = get_app();
  517. $t = $a->template_engine();
  518. try {
  519. $template = $t->get_template_file($s, $root);
  520. } catch (Exception $e) {
  521. echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
  522. }
  523. $a->save_timestamp($stamp1, "file");
  524. return $template;
  525. }}
  526. if(! function_exists("get_template_file")) {
  527. /**
  528. *
  529. * @param App $a
  530. * @param string $filename
  531. * @param string $root
  532. * @return string
  533. */
  534. function get_template_file($a, $filename, $root = '') {
  535. $theme = current_theme();
  536. // Make sure $root ends with a slash /
  537. if($root !== '' && $root[strlen($root)-1] !== '/')
  538. $root = $root . '/';
  539. if(file_exists("{$root}view/theme/$theme/$filename"))
  540. $template_file = "{$root}view/theme/$theme/$filename";
  541. elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
  542. $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
  543. elseif (file_exists("{$root}/$filename"))
  544. $template_file = "{$root}/$filename";
  545. else
  546. $template_file = "{$root}view/$filename";
  547. return $template_file;
  548. }}
  549. if(! function_exists('attribute_contains')) {
  550. /**
  551. * for html,xml parsing - let's say you've got
  552. * an attribute foobar="class1 class2 class3"
  553. * and you want to find out if it contains 'class3'.
  554. * you can't use a normal sub string search because you
  555. * might match 'notclass3' and a regex to do the job is
  556. * possible but a bit complicated.
  557. * pass the attribute string as $attr and the attribute you
  558. * are looking for as $s - returns true if found, otherwise false
  559. *
  560. * @param string $attr attribute value
  561. * @param string $s string to search
  562. * @return boolean True if found, False otherwise
  563. */
  564. function attribute_contains($attr,$s) {
  565. $a = explode(' ', $attr);
  566. if(count($a) && in_array($s,$a))
  567. return true;
  568. return false;
  569. }}
  570. if (! function_exists('logger')) {
  571. /* setup int->string log level map */
  572. $LOGGER_LEVELS = array();
  573. /**
  574. * @brief Logs the given message at the given log level
  575. *
  576. * log levels:
  577. * LOGGER_NORMAL (default)
  578. * LOGGER_TRACE
  579. * LOGGER_DEBUG
  580. * LOGGER_DATA
  581. * LOGGER_ALL
  582. *
  583. * @global App $a
  584. * @global dba $db
  585. * @global array $LOGGER_LEVELS
  586. * @param string $msg
  587. * @param int $level
  588. */
  589. function logger($msg, $level = 0) {
  590. $a = get_app();
  591. global $db;
  592. global $LOGGER_LEVELS;
  593. // turn off logger in install mode
  594. if (
  595. $a->module == 'install'
  596. || ! ($db && $db->connected)
  597. ) {
  598. return;
  599. }
  600. $debugging = get_config('system','debugging');
  601. $logfile = get_config('system','logfile');
  602. $loglevel = intval(get_config('system','loglevel'));
  603. if (
  604. ! $debugging
  605. || ! $logfile
  606. || $level > $loglevel
  607. ) {
  608. return;
  609. }
  610. if (count($LOGGER_LEVELS) == 0) {
  611. foreach (get_defined_constants() as $k => $v) {
  612. if (substr($k, 0, 7) == "LOGGER_") {
  613. $LOGGER_LEVELS[$v] = substr($k, 7, 7);
  614. }
  615. }
  616. }
  617. $process_id = session_id();
  618. if ($process_id == '') {
  619. $process_id = get_app()->process_id;
  620. }
  621. $callers = debug_backtrace();
  622. $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
  623. datetime_convert(),
  624. $process_id,
  625. $LOGGER_LEVELS[$level],
  626. basename($callers[0]['file']),
  627. $callers[0]['line'],
  628. $callers[1]['function'],
  629. $msg
  630. );
  631. $stamp1 = microtime(true);
  632. @file_put_contents($logfile, $logline, FILE_APPEND);
  633. $a->save_timestamp($stamp1, "file");
  634. }}
  635. /**
  636. * @brief An alternative logger for development.
  637. * Works largely as logger() but allows developers
  638. * to isolate particular elements they are targetting
  639. * personally without background noise
  640. *
  641. * log levels:
  642. * LOGGER_NORMAL (default)
  643. * LOGGER_TRACE
  644. * LOGGER_DEBUG
  645. * LOGGER_DATA
  646. * LOGGER_ALL
  647. *
  648. * @global App $a
  649. * @global dba $db
  650. * @global array $LOGGER_LEVELS
  651. * @param string $msg
  652. * @param int $level
  653. */
  654. function dlogger($msg, $level = 0) {
  655. $a = get_app();
  656. global $db;
  657. // turn off logger in install mode
  658. if (
  659. $a->module == 'install'
  660. || ! ($db && $db->connected)
  661. ) {
  662. return;
  663. }
  664. $logfile = get_config('system','dlogfile');
  665. if (! $logfile) {
  666. return;
  667. }
  668. if (count($LOGGER_LEVELS) == 0) {
  669. foreach (get_defined_constants() as $k => $v) {
  670. if (substr($k, 0, 7) == "LOGGER_") {
  671. $LOGGER_LEVELS[$v] = substr($k, 7, 7);
  672. }
  673. }
  674. }
  675. $process_id = session_id();
  676. if ($process_id == '') {
  677. $process_id = get_app()->process_id;
  678. }
  679. $callers = debug_backtrace();
  680. $logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
  681. datetime_convert(),
  682. $process_id,
  683. basename($callers[0]['file']),
  684. $callers[0]['line'],
  685. $callers[1]['function'],
  686. $msg
  687. );
  688. $stamp1 = microtime(true);
  689. @file_put_contents($logfile, $logline, FILE_APPEND);
  690. $a->save_timestamp($stamp1, "file");
  691. }
  692. if(! function_exists('activity_match')) {
  693. /**
  694. * Compare activity uri. Knows about activity namespace.
  695. *
  696. * @param string $haystack
  697. * @param string $needle
  698. * @return boolean
  699. */
  700. function activity_match($haystack,$needle) {
  701. if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
  702. return true;
  703. return false;
  704. }}
  705. /**
  706. * @brief Pull out all #hashtags and @person tags from $string.
  707. *
  708. * We also get @person@domain.com - which would make
  709. * the regex quite complicated as tags can also
  710. * end a sentence. So we'll run through our results
  711. * and strip the period from any tags which end with one.
  712. * Returns array of tags found, or empty array.
  713. *
  714. * @param string $string Post content
  715. * @return array List of tag and person names
  716. */
  717. function get_tags($string) {
  718. $ret = array();
  719. // Convert hashtag links to hashtags
  720. $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
  721. // ignore anything in a code block
  722. $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
  723. // Force line feeds at bbtags
  724. $string = str_replace(array('[', ']'), array("\n[", "]\n"), $string);
  725. // ignore anything in a bbtag
  726. $string = preg_replace('/\[(.*?)\]/sm', '', $string);
  727. // Match full names against @tags including the space between first and last
  728. // We will look these up afterward to see if they are full names or not recognisable.
  729. if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
  730. foreach ($matches[1] as $match) {
  731. if (strstr($match, ']')) {
  732. // we might be inside a bbcode color tag - leave it alone
  733. continue;
  734. }
  735. if (substr($match, -1, 1) === '.') {
  736. $ret[] = substr($match, 0, -1);
  737. } else {
  738. $ret[] = $match;
  739. }
  740. }
  741. }
  742. // Otherwise pull out single word tags. These can be @nickname, @first_last
  743. // and #hash tags.
  744. if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
  745. foreach($matches[1] as $match) {
  746. if (strstr($match, ']')) {
  747. // we might be inside a bbcode color tag - leave it alone
  748. continue;
  749. }
  750. if (substr($match, -1, 1) === '.') {
  751. $match = substr($match,0,-1);
  752. }
  753. // ignore strictly numeric tags like #1
  754. if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
  755. continue;
  756. }
  757. // try not to catch url fragments
  758. if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
  759. continue;
  760. }
  761. $ret[] = $match;
  762. }
  763. }
  764. return $ret;
  765. }
  766. //
  767. if(! function_exists('qp')) {
  768. /**
  769. * quick and dirty quoted_printable encoding
  770. *
  771. * @param string $s
  772. * @return string
  773. */
  774. function qp($s) {
  775. return str_replace ("%","=",rawurlencode($s));
  776. }}
  777. if(! function_exists('contact_block')) {
  778. /**
  779. * Get html for contact block.
  780. *
  781. * @template contact_block.tpl
  782. * @hook contact_block_end (contacts=>array, output=>string)
  783. * @return string
  784. */
  785. function contact_block() {
  786. $o = '';
  787. $a = get_app();
  788. $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
  789. if($shown === false)
  790. $shown = 24;
  791. if($shown == 0)
  792. return;
  793. if((! is_array($a->profile)) || ($a->profile['hide-friends']))
  794. return $o;
  795. $r = q("SELECT COUNT(*) AS `total` FROM `contact`
  796. WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
  797. AND NOT `pending` AND NOT `hidden` AND NOT `archive`
  798. AND `network` IN ('%s', '%s', '%s')",
  799. intval($a->profile['uid']),
  800. dbesc(NETWORK_DFRN),
  801. dbesc(NETWORK_OSTATUS),
  802. dbesc(NETWORK_DIASPORA)
  803. );
  804. if (dbm::is_result($r)) {
  805. $total = intval($r[0]['total']);
  806. }
  807. if(! $total) {
  808. $contacts = t('No contacts');
  809. $micropro = Null;
  810. } else {
  811. // Splitting the query in two parts makes it much faster
  812. $r = q("SELECT `id` FROM `contact`
  813. WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
  814. AND NOT `pending` AND NOT `hidden` AND NOT `archive`
  815. AND `network` IN ('%s', '%s', '%s')
  816. ORDER BY RAND() LIMIT %d",
  817. intval($a->profile['uid']),
  818. dbesc(NETWORK_DFRN),
  819. dbesc(NETWORK_OSTATUS),
  820. dbesc(NETWORK_DIASPORA),
  821. intval($shown)
  822. );
  823. if (dbm::is_result($r)) {
  824. $contacts = array();
  825. foreach ($r AS $contact) {
  826. $contacts[] = $contact["id"];
  827. }
  828. $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
  829. dbesc(implode(",", $contacts)));
  830. if (dbm::is_result($r)) {
  831. $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
  832. $micropro = Array();
  833. foreach ($r as $rr) {
  834. $micropro[] = micropro($rr,true,'mpfriend');
  835. }
  836. }
  837. }
  838. }
  839. $tpl = get_markup_template('contact_block.tpl');
  840. $o = replace_macros($tpl, array(
  841. '$contacts' => $contacts,
  842. '$nickname' => $a->profile['nickname'],
  843. '$viewcontacts' => t('View Contacts'),
  844. '$micropro' => $micropro,
  845. ));
  846. $arr = array('contacts' => $r, 'output' => $o);
  847. call_hooks('contact_block_end', $arr);
  848. return $o;
  849. }}
  850. /**
  851. * @brief Format contacts as picture links or as texxt links
  852. *
  853. * @param array $contact Array with contacts which contains an array with
  854. * int 'id' => The ID of the contact
  855. * int 'uid' => The user ID of the user who owns this data
  856. * string 'name' => The name of the contact
  857. * string 'url' => The url to the profile page of the contact
  858. * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
  859. * string 'network' => The network to which the contact belongs to
  860. * string 'thumb' => The contact picture
  861. * string 'click' => js code which is performed when clicking on the contact
  862. * @param boolean $redirect If true try to use the redir url if it's possible
  863. * @param string $class CSS class for the
  864. * @param boolean $textmode If true display the contacts as text links
  865. * if false display the contacts as picture links
  866. * @return string Formatted html
  867. */
  868. function micropro($contact, $redirect = false, $class = '', $textmode = false) {
  869. // Use the contact URL if no address is available
  870. if ($contact["addr"] == "")
  871. $contact["addr"] = $contact["url"];
  872. $url = $contact['url'];
  873. $sparkle = '';
  874. $redir = false;
  875. if($redirect) {
  876. $a = get_app();
  877. $redirect_url = 'redir/' . $contact['id'];
  878. if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
  879. $redir = true;
  880. $url = $redirect_url;
  881. $sparkle = ' sparkle';
  882. }
  883. else
  884. $url = zrl($url);
  885. }
  886. // If there is some js available we don't need the url
  887. if(x($contact,'click'))
  888. $url = '';
  889. return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
  890. '$click' => (($contact['click']) ? $contact['click'] : ''),
  891. '$class' => $class,
  892. '$url' => $url,
  893. '$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
  894. '$name' => $contact['name'],
  895. 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
  896. '$parkle' => $sparkle,
  897. '$redir' => $redir,
  898. ));
  899. }
  900. if(! function_exists('search')) {
  901. /**
  902. * search box
  903. *
  904. * @param string $s search query
  905. * @param string $id html id
  906. * @param string $url search url
  907. * @param boolean $savedsearch show save search button
  908. */
  909. function search($s,$id='search-box',$url='search',$save = false, $aside = true) {
  910. $a = get_app();
  911. $values = array(
  912. '$s' => htmlspecialchars($s),
  913. '$id' => $id,
  914. '$action_url' => $url,
  915. '$search_label' => t('Search'),
  916. '$save_label' => t('Save'),
  917. '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
  918. '$search_hint' => t('@name, !forum, #tags, content'),
  919. );
  920. if (!$aside) {
  921. $values['$searchoption'] = array(
  922. t("Full Text"),
  923. t("Tags"),
  924. t("Contacts"));
  925. if (get_config('system','poco_local_search'))
  926. $values['$searchoption'][] = t("Forums");
  927. }
  928. return replace_macros(get_markup_template('searchbox.tpl'), $values);
  929. }}
  930. if(! function_exists('valid_email')) {
  931. /**
  932. * Check if $x is a valid email string
  933. *
  934. * @param string $x
  935. * @return boolean
  936. */
  937. function valid_email($x){
  938. // Removed because Fabio told me so.
  939. //if(get_config('system','disable_email_validation'))
  940. // return true;
  941. if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
  942. return true;
  943. return false;
  944. }}
  945. if(! function_exists('linkify')) {
  946. /**
  947. * Replace naked text hyperlink with HTML formatted hyperlink
  948. *
  949. * @param string $s
  950. */
  951. function linkify($s) {
  952. $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
  953. $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
  954. return($s);
  955. }}
  956. /**
  957. * Load poke verbs
  958. *
  959. * @return array index is present tense verb
  960. value is array containing past tense verb, translation of present, translation of past
  961. * @hook poke_verbs pokes array
  962. */
  963. function get_poke_verbs() {
  964. // index is present tense verb
  965. // value is array containing past tense verb, translation of present, translation of past
  966. $arr = array(
  967. 'poke' => array( 'poked', t('poke'), t('poked')),
  968. 'ping' => array( 'pinged', t('ping'), t('pinged')),
  969. 'prod' => array( 'prodded', t('prod'), t('prodded')),
  970. 'slap' => array( 'slapped', t('slap'), t('slapped')),
  971. 'finger' => array( 'fingered', t('finger'), t('fingered')),
  972. 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
  973. );
  974. call_hooks('poke_verbs', $arr);
  975. return $arr;
  976. }
  977. /**
  978. * Load moods
  979. * @return array index is mood, value is translated mood
  980. * @hook mood_verbs moods array
  981. */
  982. function get_mood_verbs() {
  983. $arr = array(
  984. 'happy' => t('happy'),
  985. 'sad' => t('sad'),
  986. 'mellow' => t('mellow'),
  987. 'tired' => t('tired'),
  988. 'perky' => t('perky'),
  989. 'angry' => t('angry'),
  990. 'stupefied' => t('stupified'),
  991. 'puzzled' => t('puzzled'),
  992. 'interested' => t('interested'),
  993. 'bitter' => t('bitter'),
  994. 'cheerful' => t('cheerful'),
  995. 'alive' => t('alive'),
  996. 'annoyed' => t('annoyed'),
  997. 'anxious' => t('anxious'),
  998. 'cranky' => t('cranky'),
  999. 'disturbed' => t('disturbed'),
  1000. 'frustrated' => t('frustrated'),
  1001. 'motivated' => t('motivated'),
  1002. 'relaxed' => t('relaxed'),
  1003. 'surprised' => t('surprised'),
  1004. );
  1005. call_hooks('mood_verbs', $arr);
  1006. return $arr;
  1007. }
  1008. if(! function_exists('day_translate')) {
  1009. /**
  1010. * Translate days and months names
  1011. *
  1012. * @param string $s
  1013. * @return string
  1014. */
  1015. function day_translate($s) {
  1016. $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
  1017. array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
  1018. $s);
  1019. $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
  1020. 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')),
  1021. $ret);
  1022. return $ret;
  1023. }}
  1024. if(! function_exists('normalise_link')) {
  1025. /**
  1026. * Normalize url
  1027. *
  1028. * @param string $url
  1029. * @return string
  1030. */
  1031. function normalise_link($url) {
  1032. $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
  1033. return(rtrim($ret,'/'));
  1034. }}
  1035. if(! function_exists('link_compare')) {
  1036. /**
  1037. * Compare two URLs to see if they are the same, but ignore
  1038. * slight but hopefully insignificant differences such as if one
  1039. * is https and the other isn't, or if one is www.something and
  1040. * the other isn't - and also ignore case differences.
  1041. *
  1042. * @param string $a first url
  1043. * @param string $b second url
  1044. * @return boolean True if the URLs match, otherwise False
  1045. *
  1046. */
  1047. function link_compare($a,$b) {
  1048. if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
  1049. return true;
  1050. return false;
  1051. }}
  1052. /**
  1053. * @brief Find any non-embedded images in private items and add redir links to them
  1054. *
  1055. * @param App $a
  1056. * @param array &$item The field array of an item row
  1057. */
  1058. function redir_private_images($a, &$item)
  1059. {
  1060. $matches = false;
  1061. $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
  1062. if ($cnt) {
  1063. foreach ($matches as $mtch) {
  1064. if (strpos($mtch[1], '/redir') !== false) {
  1065. continue;
  1066. }
  1067. if ((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
  1068. $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
  1069. $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
  1070. }
  1071. }
  1072. }
  1073. }
  1074. function put_item_in_cache(&$item, $update = false) {
  1075. if (($item["rendered-hash"] != hash("md5", $item["body"])) OR ($item["rendered-hash"] == "") OR
  1076. ($item["rendered-html"] == "") OR get_config("system", "ignore_cache")) {
  1077. // The function "redir_private_images" changes the body.
  1078. // I'm not sure if we should store it permanently, so we save the old value.
  1079. $body = $item["body"];
  1080. $a = get_app();
  1081. redir_private_images($a, $item);
  1082. $item["rendered-html"] = prepare_text($item["body"]);
  1083. $item["rendered-hash"] = hash("md5", $item["body"]);
  1084. $item["body"] = $body;
  1085. if ($update AND ($item["id"] != 0)) {
  1086. q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
  1087. dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
  1088. }
  1089. }
  1090. }
  1091. // Given an item array, convert the body element from bbcode to html and add smilie icons.
  1092. // If attach is true, also add icons for item attachments
  1093. if(! function_exists('prepare_body')) {
  1094. /**
  1095. * Given an item array, convert the body element from bbcode to html and add smilie icons.
  1096. * If attach is true, also add icons for item attachments
  1097. *
  1098. * @param array $item
  1099. * @param boolean $attach
  1100. * @return string item body html
  1101. * @hook prepare_body_init item array before any work
  1102. * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
  1103. * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
  1104. */
  1105. function prepare_body(&$item,$attach = false, $preview = false) {
  1106. $a = get_app();
  1107. call_hooks('prepare_body_init', $item);
  1108. $searchpath = z_root()."/search?tag=";
  1109. $tags=array();
  1110. $hashtags = array();
  1111. $mentions = array();
  1112. if (!get_config('system','suppress_tags')) {
  1113. $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
  1114. intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
  1115. foreach($taglist as $tag) {
  1116. if ($tag["url"] == "")
  1117. $tag["url"] = $searchpath.strtolower($tag["term"]);
  1118. if ($tag["type"] == TERM_HASHTAG) {
  1119. $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
  1120. $prefix = "#";
  1121. } elseif ($tag["type"] == TERM_MENTION) {
  1122. $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
  1123. $prefix = "@";
  1124. }
  1125. $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
  1126. }
  1127. }
  1128. $item['tags'] = $tags;
  1129. $item['hashtags'] = $hashtags;
  1130. $item['mentions'] = $mentions;
  1131. // Update the cached values if there is no "zrl=..." on the links
  1132. $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
  1133. // Or update it if the current viewer is the intented viewer
  1134. if (($item["uid"] == local_user()) AND ($item["uid"] != 0))
  1135. $update = true;
  1136. put_item_in_cache($item, $update);
  1137. $s = $item["rendered-html"];
  1138. $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
  1139. call_hooks('prepare_body', $prep_arr);
  1140. $s = $prep_arr['html'];
  1141. if(! $attach) {
  1142. // Replace the blockquotes with quotes that are used in mails
  1143. $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
  1144. $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
  1145. return $s;
  1146. }
  1147. $as = '';
  1148. $vhead = false;
  1149. $arr = explode('[/attach],',$item['attach']);
  1150. if(count($arr)) {
  1151. $as .= '<div class="body-attach">';
  1152. foreach($arr as $r) {
  1153. $matches = false;
  1154. $icon = '';
  1155. $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
  1156. if($cnt) {
  1157. foreach($matches as $mtch) {
  1158. $mime = $mtch[3];
  1159. if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
  1160. $the_url = 'redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
  1161. else
  1162. $the_url = $mtch[1];
  1163. if(strpos($mime, 'video') !== false) {
  1164. if(!$vhead) {
  1165. $vhead = true;
  1166. $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
  1167. '$baseurl' => z_root(),
  1168. ));
  1169. $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
  1170. '$baseurl' => z_root(),
  1171. ));
  1172. }
  1173. $id = end(explode('/', $the_url));
  1174. $as .= replace_macros(get_markup_template('video_top.tpl'), array(
  1175. '$video' => array(
  1176. 'id' => $id,
  1177. 'title' => t('View Video'),
  1178. 'src' => $the_url,
  1179. 'mime' => $mime,
  1180. ),
  1181. ));
  1182. }
  1183. $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
  1184. if($filetype) {
  1185. $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
  1186. $filesubtype = str_replace('.', '-', $filesubtype);
  1187. }
  1188. else {
  1189. $filetype = 'unkn';
  1190. $filesubtype = 'unkn';
  1191. }
  1192. $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
  1193. /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
  1194. switch($icontype) {
  1195. case 'video':
  1196. case 'audio':
  1197. case 'image':
  1198. case 'text':
  1199. $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
  1200. break;
  1201. default:
  1202. $icon = '<div class="attachtype icon s22 type-unkn"></div>';
  1203. break;
  1204. }*/
  1205. $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
  1206. $title .= ' ' . $mtch[2] . ' ' . t('bytes');
  1207. $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
  1208. }
  1209. }
  1210. }
  1211. $as .= '<div class="clear"></div></div>';
  1212. }
  1213. $s = $s . $as;
  1214. // map
  1215. if(strpos($s,'<div class="map">') !== false && $item['coord']) {
  1216. $x = generate_map(trim($item['coord']));
  1217. if ($x) {
  1218. $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
  1219. }
  1220. }
  1221. // Look for spoiler
  1222. $spoilersearch = '<blockquote class="spoiler">';
  1223. // Remove line breaks before the spoiler
  1224. while ((strpos($s, "\n".$spoilersearch) !== false))
  1225. $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
  1226. while ((strpos($s, "<br />".$spoilersearch) !== false))
  1227. $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
  1228. while ((strpos($s, $spoilersearch) !== false)) {
  1229. $pos = strpos($s, $spoilersearch);
  1230. $rnd = random_string(8);
  1231. $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
  1232. '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
  1233. $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
  1234. }
  1235. // Look for quote with author
  1236. $authorsearch = '<blockquote class="author">';
  1237. while ((strpos($s, $authorsearch) !== false)) {
  1238. $pos = strpos($s, $authorsearch);
  1239. $rnd = random_string(8);
  1240. $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" class="author-wrap fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
  1241. '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
  1242. $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
  1243. }
  1244. // replace friendica image url size with theme preference
  1245. if (x($a->theme_info,'item_image_size')){
  1246. $ps = $a->theme_info['item_image_size'];
  1247. $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|',"$1-".$ps, $s);
  1248. }
  1249. $prep_arr = array('item' => $item, 'html' => $s);
  1250. call_hooks('prepare_body_final', $prep_arr);
  1251. return $prep_arr['html'];
  1252. }}
  1253. if(! function_exists('prepare_text')) {
  1254. /**
  1255. * Given a text string, convert from bbcode to html and add smilie icons.
  1256. *
  1257. * @param string $text
  1258. * @return string
  1259. */
  1260. function prepare_text($text) {
  1261. require_once('include/bbcode.php');
  1262. if(stristr($text,'[nosmile]'))
  1263. $s = bbcode($text);
  1264. else
  1265. $s = Smilies::replace(bbcode($text));
  1266. return trim($s);
  1267. }}
  1268. /**
  1269. * return array with details for categories and folders for an item
  1270. *
  1271. * @param array $item
  1272. * @return array
  1273. *
  1274. * [
  1275. * [ // categories array
  1276. * {
  1277. * 'name': 'category name',
  1278. * 'removeurl': 'url to remove this category',
  1279. * 'first': 'is the first in this array? true/false',
  1280. * 'last': 'is the last in this array? true/false',
  1281. * } ,
  1282. * ....
  1283. * ],
  1284. * [ //folders array
  1285. * {
  1286. * 'name': 'folder name',
  1287. * 'removeurl': 'url to remove this folder',
  1288. * 'first': 'is the first in this array? true/false',
  1289. * 'last': 'is the last in this array? true/false',
  1290. * } ,
  1291. * ....
  1292. * ]
  1293. * ]
  1294. */
  1295. function get_cats_and_terms($item) {
  1296. $a = get_app();
  1297. $categories = array();
  1298. $folders = array();
  1299. $matches = false; $first = true;
  1300. $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
  1301. if($cnt) {
  1302. foreach($matches as $mtch) {
  1303. $categories[] = array(
  1304. 'name' => xmlify(file_tag_decode($mtch[1])),
  1305. 'url' => "#",
  1306. 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
  1307. 'first' => $first,
  1308. 'last' => false
  1309. );
  1310. $first = false;
  1311. }
  1312. }
  1313. if (count($categories)) $categories[count($categories)-1]['last'] = true;
  1314. if(local_user() == $item['uid']) {
  1315. $matches = false; $first = true;
  1316. $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
  1317. if($cnt) {
  1318. foreach($matches as $mtch) {
  1319. $folders[] = array(
  1320. 'name' => xmlify(file_tag_decode($mtch[1])),
  1321. 'url' => "#",
  1322. 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
  1323. 'first' => $first,
  1324. 'last' => false
  1325. );
  1326. $first = false;
  1327. }
  1328. }
  1329. }
  1330. if (count($folders)) $folders[count($folders)-1]['last'] = true;
  1331. return array($categories, $folders);
  1332. }
  1333. if(! function_exists('get_plink')) {
  1334. /**
  1335. * get private link for item
  1336. * @param array $item
  1337. * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
  1338. */
  1339. function get_plink($item) {
  1340. $a = get_app();
  1341. if ($a->user['nickname'] != "") {
  1342. $ret = array(
  1343. //'href' => "display/".$a->user['nickname']."/".$item['id'],
  1344. 'href' => "display/".$item['guid'],
  1345. 'orig' => "display/".$item['guid'],
  1346. 'title' => t('View on separate page'),
  1347. 'orig_title' => t('view on separate page'),
  1348. );
  1349. if (x($item,'plink')) {
  1350. $ret["href"] = $a->remove_baseurl($item['plink']);
  1351. $ret["title"] = t('link to source');
  1352. }
  1353. } elseif (x($item,'plink') && ($item['private'] != 1))
  1354. $ret = array(
  1355. 'href' => $item['plink'],
  1356. 'orig' => $item['plink'],
  1357. 'title' => t('link to source'),
  1358. );
  1359. else
  1360. $ret = array();
  1361. //if (x($item,'plink') && ($item['private'] != 1))
  1362. return($ret);
  1363. }}
  1364. if(! function_exists('unamp')) {
  1365. /**
  1366. * replace html amp entity with amp char
  1367. * @param string $s
  1368. * @return string
  1369. */
  1370. function unamp($s) {
  1371. return str_replace('&amp;', '&', $s);
  1372. }}
  1373. if(! function_exists('return_bytes')) {
  1374. /**
  1375. * return number of bytes in size (K, M, G)
  1376. * @param string $size_str
  1377. * @return number
  1378. */
  1379. function return_bytes ($size_str) {
  1380. switch (substr ($size_str, -1)) {
  1381. case 'M': case 'm': return (int)$size_str * 1048576;
  1382. case 'K': case 'k': return (int)$size_str * 1024;
  1383. case 'G': case 'g': return (int)$size_str * 1073741824;
  1384. default: return $size_str;
  1385. }
  1386. }}
  1387. /**
  1388. * @return string
  1389. */
  1390. function generate_user_guid() {
  1391. $found = true;
  1392. do {
  1393. $guid = get_guid(32);
  1394. $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
  1395. dbesc($guid)
  1396. );
  1397. if(! count($x))
  1398. $found = false;
  1399. } while ($found == true );
  1400. return $guid;
  1401. }
  1402. /**
  1403. * @param string $s
  1404. * @param boolean $strip_padding
  1405. * @return string
  1406. */
  1407. function base64url_encode($s, $strip_padding = false) {
  1408. $s = strtr(base64_encode($s),'+/','-_');
  1409. if($strip_padding)
  1410. $s = str_replace('=','',$s);
  1411. return $s;
  1412. }
  1413. /**
  1414. * @param string $s
  1415. * @return string
  1416. */
  1417. function base64url_decode($s) {
  1418. if(is_array($s)) {
  1419. logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
  1420. return $s;
  1421. }
  1422. /*
  1423. * // Placeholder for new rev of salmon which strips base64 padding.
  1424. * // PHP base64_decode handles the un-padded input without requiring this step
  1425. * // Uncomment if you find you need it.
  1426. *
  1427. * $l = strlen($s);
  1428. * if(! strpos($s,'=')) {
  1429. * $m = $l % 4;
  1430. * if($m == 2)
  1431. * $s .= '==';
  1432. * if($m == 3)
  1433. * $s .= '=';
  1434. * }
  1435. *
  1436. */
  1437. return base64_decode(strtr($s,'-_','+/'));
  1438. }
  1439. if (!function_exists('str_getcsv')) {
  1440. /**
  1441. * Parse csv string
  1442. *
  1443. * @param string $input
  1444. * @param string $delimiter
  1445. * @param string $enclosure
  1446. * @param string $escape
  1447. * @param string $eol
  1448. * @return boolean|array False on error, otherwise array[row][column]
  1449. */
  1450. function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
  1451. if (is_string($input) && !empty($input)) {
  1452. $output = array();
  1453. $tmp = preg_split("/".$eol."/",$input);
  1454. if (is_array($tmp) && !empty($tmp)) {
  1455. while (list($line_num, $line) = each($tmp)) {
  1456. if (preg_match("/".$escape.$enclosure."/",$line)) {
  1457. while ($strlen = strlen($line)) {
  1458. $pos_delimiter = strpos($line,$delimiter);
  1459. $pos_enclosure_start = strpos($line,$enclosure);
  1460. if (
  1461. is_int($pos_delimiter) && is_int($pos_enclosure_start)
  1462. && ($pos_enclosure_start < $pos_delimiter)
  1463. ) {
  1464. $enclosed_str = substr($line,1);
  1465. $pos_enclosure_end = strpos($enclosed_str,$enclosure);
  1466. $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
  1467. $output[$line_num][] = $enclosed_str;
  1468. $offset = $pos_enclosure_end+3;
  1469. } else {
  1470. if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
  1471. $output[$line_num][] = substr($line,0);
  1472. $offset = strlen($line);
  1473. } else {
  1474. $output[$line_num][] = substr($line,0,$pos_delimiter);
  1475. $offset = (
  1476. !empty($pos_enclosure_start)
  1477. && ($pos_enclosure_start < $pos_delimiter)
  1478. )
  1479. ?$pos_enclosure_start
  1480. :$pos_delimiter+1;
  1481. }
  1482. }
  1483. $line = substr($line,$offset);
  1484. }
  1485. } else {
  1486. $line = preg_split("/".$delimiter."/",$line);
  1487. /*
  1488. * Validating against pesky extra line breaks creating false rows.
  1489. */
  1490. if (is_array($line) && !empty($line[0])) {
  1491. $output[$line_num] = $line;
  1492. }
  1493. }
  1494. }
  1495. return $output;
  1496. } else {
  1497. return false;
  1498. }
  1499. } else {
  1500. return false;
  1501. }
  1502. }
  1503. }
  1504. /**
  1505. * return div element with class 'clear'
  1506. * @return string
  1507. * @deprecated
  1508. */
  1509. function cleardiv() {
  1510. return '<div class="clear"></div>';
  1511. }
  1512. function bb_translate_video($s) {
  1513. $matches = null;
  1514. $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
  1515. if ($r) {
  1516. foreach($matches as $mtch) {
  1517. if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
  1518. $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
  1519. elseif(stristr($mtch[1],'vimeo'))
  1520. $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
  1521. }
  1522. }
  1523. return $s;
  1524. }
  1525. function html2bb_video($s) {
  1526. $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
  1527. '[youtube]$2[/youtube]', $s);
  1528. $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
  1529. '[youtube]$2[/youtube]', $s);
  1530. $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
  1531. '[vimeo]$2[/vimeo]', $s);
  1532. return $s;
  1533. }
  1534. /**
  1535. * apply xmlify() to all values of array $val, recursively
  1536. * @param array $val
  1537. * @return array
  1538. */
  1539. function array_xmlify($val){
  1540. if (is_bool($val)) return $val?"true":"false";
  1541. if (is_array($val)) return array_map('array_xmlify', $val);
  1542. return xmlify((string) $val);
  1543. }
  1544. /**
  1545. * transorm link href and img src from relative to absolute
  1546. *
  1547. * @param string $text
  1548. * @param string $base base url
  1549. * @return string
  1550. */
  1551. function reltoabs($text, $base) {
  1552. if (empty($base))
  1553. return $text;
  1554. $base = rtrim($base,'/');
  1555. $base2 = $base . "/";
  1556. // Replace links
  1557. $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
  1558. $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
  1559. $text = preg_replace($pattern, $replace, $text);
  1560. $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
  1561. $replace = "<a\${1} href=\"" . $base . "\${2}\"";
  1562. $text = preg_replace($pattern, $replace, $text);
  1563. // Replace images
  1564. $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
  1565. $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
  1566. $text = preg_replace($pattern, $replace, $text);
  1567. $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
  1568. $replace = "<img\${1} src=\"" . $base . "\${2}\"";
  1569. $text = preg_replace($pattern, $replace, $text);
  1570. // Done
  1571. return $text;
  1572. }
  1573. /**
  1574. * get translated item type
  1575. *
  1576. * @param array $itme
  1577. * @return string
  1578. */
  1579. function item_post_type($item) {
  1580. if(intval($item['event-id']))
  1581. return t('event');
  1582. if(strlen($item['resource-id']))
  1583. return t('photo');
  1584. if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
  1585. return t('activity');
  1586. if($item['id'] != $item['parent'])
  1587. return t('comment');
  1588. return t('post');
  1589. }
  1590. // post categories and "save to file" use the same item.file table for storage.
  1591. // We will differentiate the different uses by wrapping categories in angle brackets
  1592. // and save to file categories in square brackets.
  1593. // To do this we need to escape these characters if they appear in our tag.
  1594. function file_tag_encode($s) {
  1595. return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
  1596. }
  1597. function file_tag_decode($s) {
  1598. return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
  1599. }
  1600. function file_tag_file_query($table,$s,$type = 'file') {
  1601. if($type == 'file')
  1602. $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
  1603. else
  1604. $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
  1605. return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
  1606. }
  1607. // ex. given music,video return <music><video> or [music][video]
  1608. function file_tag_list_to_file($list,$type = 'file') {
  1609. $tag_list = '';
  1610. if(strlen($list)) {
  1611. $list_array = explode(",",$list);
  1612. if($type == 'file') {
  1613. $lbracket = '[';
  1614. $rbracket = ']';
  1615. }
  1616. else {
  1617. $lbracket = '<';
  1618. $rbracket = '>';
  1619. }
  1620. foreach($list_array as $item) {
  1621. if(strlen($item)) {
  1622. $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
  1623. }
  1624. }
  1625. }
  1626. return $tag_list;
  1627. }
  1628. // ex. given <music><video>[friends], return music,video or friends
  1629. function file_tag_file_to_list($file,$type = 'file') {
  1630. $matches = false;
  1631. $list = '';
  1632. if($type == 'file') {
  1633. $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
  1634. }
  1635. else {
  1636. $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
  1637. }
  1638. if($cnt) {
  1639. foreach($matches as $mtch) {
  1640. if(strlen($list))
  1641. $list .= ',';
  1642. $list .= file_tag_decode($mtch[1]);
  1643. }
  1644. }
  1645. return $list;
  1646. }
  1647. function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
  1648. // $file_old - categories previously associated with an item
  1649. // $file_new - new list of categories for an item
  1650. if(! intval($uid))
  1651. return false;
  1652. if($file_old == $file_new)
  1653. return true;
  1654. $saved = get_pconfig($uid,'system','filetags');
  1655. if(strlen($saved)) {
  1656. if($type == 'file') {
  1657. $lbracket = '[';
  1658. $rbracket = ']';
  1659. $termtype = TERM_FILE;
  1660. }
  1661. else {
  1662. $lbracket = '<';
  1663. $rbracket = '>';
  1664. $termtype = TERM_CATEGORY;
  1665. }
  1666. $filetags_updated = $saved;
  1667. // check for new tags to be added as filetags in pconfig
  1668. $new_tags = array();
  1669. $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
  1670. foreach($check_new_tags as $tag) {
  1671. if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
  1672. $new_tags[] = $tag;
  1673. }
  1674. $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
  1675. // check for deleted tags to be removed from filetags in pconfig
  1676. $deleted_tags = array();
  1677. $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
  1678. foreach($check_deleted_tags as $tag) {
  1679. if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
  1680. $deleted_tags[] = $tag;
  1681. }
  1682. foreach($deleted_tags as $key => $tag) {
  1683. $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
  1684. dbesc($tag),
  1685. intval(TERM_OBJ_POST),
  1686. intval($termtype),
  1687. intval($uid));
  1688. //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
  1689. // intval($uid)
  1690. //);
  1691. if (dbm::is_result($r)) {
  1692. unset($deleted_tags[$key]);
  1693. }
  1694. else {
  1695. $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
  1696. }
  1697. }
  1698. if($saved != $filetags_updated) {
  1699. set_pconfig($uid,'system','filetags', $filetags_updated);
  1700. }
  1701. return true;
  1702. }
  1703. else
  1704. if(strlen($file_new)) {
  1705. set_pconfig($uid,'system','filetags', $file_new);
  1706. }
  1707. return true;
  1708. }
  1709. function file_tag_save_file($uid,$item,$file) {
  1710. require_once("include/files.php");
  1711. $result = false;
  1712. if(! intval($uid))
  1713. return false;
  1714. $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  1715. intval($item),
  1716. intval($uid)
  1717. );
  1718. if (dbm::is_result($r)) {
  1719. if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
  1720. q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
  1721. dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
  1722. intval($item),
  1723. intval($uid)
  1724. );
  1725. create_files_from_item($item);
  1726. $saved = get_pconfig($uid,'system','filetags');
  1727. if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
  1728. set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
  1729. info( t('Item filed') );
  1730. }
  1731. return true;
  1732. }
  1733. function file_tag_unsave_file($uid,$item,$file,$cat = false) {
  1734. require_once("include/files.php");
  1735. $result = false;
  1736. if(! intval($uid))
  1737. return false;
  1738. if($cat == true) {
  1739. $pattern = '<' . file_tag_encode($file) . '>' ;
  1740. $termtype = TERM_CATEGORY;
  1741. } else {
  1742. $pattern = '[' . file_tag_encode($file) . ']' ;
  1743. $termtype = TERM_FILE;
  1744. }
  1745. $r = q("SELECT `file` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  1746. intval($item),
  1747. intval($uid)
  1748. );
  1749. if (! dbm::is_result($r)) {
  1750. return false;
  1751. }
  1752. q("UPDATE `item` SET `file` = '%s' WHERE `id` = %d AND `uid` = %d",
  1753. dbesc(str_replace($pattern,'',$r[0]['file'])),
  1754. intval($item),
  1755. intval($uid)
  1756. );
  1757. create_files_from_item($item);
  1758. $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
  1759. dbesc($file),
  1760. intval(TERM_OBJ_POST),
  1761. intval($termtype),
  1762. intval($uid));
  1763. //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
  1764. //);
  1765. if (! dbm::is_result($r)) {
  1766. $saved = get_pconfig($uid,'system','filetags');
  1767. set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
  1768. }
  1769. return true;
  1770. }
  1771. function normalise_openid($s) {
  1772. return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
  1773. }
  1774. function undo_post_tagging($s) {
  1775. $matches = null;
  1776. $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
  1777. if($cnt) {
  1778. foreach($matches as $mtch) {
  1779. $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
  1780. }
  1781. }
  1782. return $s;
  1783. }
  1784. function protect_sprintf($s) {
  1785. return(str_replace('%','%%',$s));
  1786. }
  1787. function is_a_date_arg($s) {
  1788. $i = intval($s);
  1789. if($i > 1900) {
  1790. $y = date('Y');
  1791. if($i <= $y+1 && strpos($s,'-') == 4) {
  1792. $m = intval(substr($s,5));
  1793. if($m > 0 && $m <= 12)
  1794. return true;
  1795. }
  1796. }
  1797. return false;
  1798. }
  1799. /**
  1800. * remove intentation from a text
  1801. */
  1802. function deindent($text, $chr = "[\t ]", $count = NULL) {
  1803. $lines = explode("\n", $text);
  1804. if (is_null($count)) {
  1805. $m = array();
  1806. $k = 0;
  1807. while ($k < count($lines) && strlen($lines[$k]) == 0) {
  1808. $k++;
  1809. }
  1810. preg_match("|^" . $chr . "*|", $lines[$k], $m);
  1811. $count = strlen($m[0]);
  1812. }
  1813. for ($k=0; $k < count($lines); $k++) {
  1814. $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
  1815. }
  1816. return implode("\n", $lines);
  1817. }
  1818. function formatBytes($bytes, $precision = 2) {
  1819. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  1820. $bytes = max($bytes, 0);
  1821. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  1822. $pow = min($pow, count($units) - 1);
  1823. $bytes /= pow(1024, $pow);
  1824. return round($bytes, $precision) . ' ' . $units[$pow];
  1825. }
  1826. /**
  1827. * @brief translate and format the networkname of a contact
  1828. *
  1829. * @param string $network
  1830. * Networkname of the contact (e.g. dfrn, rss and so on)
  1831. * @param sting $url
  1832. * The contact url
  1833. * @return string
  1834. */
  1835. function format_network_name($network, $url = 0) {
  1836. if ($network != "") {
  1837. require_once('include/contact_selectors.php');
  1838. if ($url != "")
  1839. $network_name = '<a href="'.$url.'">'.network_to_name($network, $url)."</a>";
  1840. else
  1841. $network_name = network_to_name($network);
  1842. return $network_name;
  1843. }
  1844. }
  1845. /**
  1846. * @brief Syntax based code highlighting for popular languages.
  1847. * @param string $s Code block
  1848. * @param string $lang Programming language
  1849. * @return string Formated html
  1850. */
  1851. function text_highlight($s, $lang) {
  1852. if ($lang === 'js') {
  1853. $lang = 'javascript';
  1854. }
  1855. // @TODO: Replace Text_Highlighter_Renderer_Html by scrivo/highlight.php
  1856. // Autoload the library to make constants available
  1857. class_exists('Text_Highlighter_Renderer_Html');
  1858. $options = array(
  1859. 'numbers' => HL_NUMBERS_LI,
  1860. 'tabsize' => 4,
  1861. );
  1862. $tag_added = false;
  1863. $s = trim(html_entity_decode($s, ENT_COMPAT));
  1864. $s = str_replace(' ', "\t", $s);
  1865. // The highlighter library insists on an opening php tag for php code blocks. If
  1866. // it isn't present, nothing is highlighted. So we're going to see if it's present.
  1867. // If not, we'll add it, and then quietly remove it after we get the processed output back.
  1868. if ($lang === 'php') {
  1869. if (strpos($s, '<?php') !== 0) {
  1870. $s = '<?php' . "\n" . $s;
  1871. $tag_added = true;
  1872. }
  1873. }
  1874. $renderer = new Text_Highlighter_Renderer_Html($options);
  1875. $hl = Text_Highlighter::factory($lang);
  1876. $hl->setRenderer($renderer);
  1877. $o = $hl->highlight($s);
  1878. $o = str_replace("\n", '', $o);
  1879. if ($tag_added) {
  1880. $b = substr($o, 0, strpos($o, '<li>'));
  1881. $e = substr($o, strpos($o, '</li>'));
  1882. $o = $b . $e;
  1883. }
  1884. return '<code>' . $o . '</code>';
  1885. }