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.

2237 lines
58 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
3 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
4 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
7 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  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(