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.

2781 lines
75 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
  1. <?php
  2. set_time_limit(0);
  3. define ( 'FRIENDIKA_VERSION', '2.1.942' );
  4. define ( 'DFRN_PROTOCOL_VERSION', '2.2' );
  5. define ( 'DB_UPDATE_VERSION', 1047 );
  6. define ( 'EOL', "<br />\r\n" );
  7. define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
  8. define ( 'DOWN_ARROW', '&#x21e9;' );
  9. /**
  10. * SSL redirection policies
  11. */
  12. define ( 'SSL_POLICY_NONE', 0 );
  13. define ( 'SSL_POLICY_FULL', 1 );
  14. define ( 'SSL_POLICY_SELFSIGN', 2 );
  15. /**
  16. * log levels
  17. */
  18. define ( 'LOGGER_NORMAL', 0 );
  19. define ( 'LOGGER_TRACE', 1 );
  20. define ( 'LOGGER_DEBUG', 2 );
  21. define ( 'LOGGER_DATA', 3 );
  22. define ( 'LOGGER_ALL', 4 );
  23. /**
  24. * registration policies
  25. */
  26. define ( 'REGISTER_CLOSED', 0 );
  27. define ( 'REGISTER_APPROVE', 1 );
  28. define ( 'REGISTER_OPEN', 2 );
  29. /**
  30. * relationship types
  31. * When used in contact records, this indicates that 'uid' has
  32. * this relationship with contact['name']
  33. */
  34. define ( 'REL_VIP', 1);
  35. define ( 'REL_FAN', 2);
  36. define ( 'REL_BUD', 3);
  37. /**
  38. * Hook array order
  39. */
  40. define ( 'HOOK_HOOK', 0);
  41. define ( 'HOOK_FILE', 1);
  42. define ( 'HOOK_FUNCTION', 2);
  43. /**
  44. *
  45. * page/profile types
  46. *
  47. * PAGE_NORMAL is a typical personal profile account
  48. * PAGE_SOAPBOX automatically approves all friend requests as REL_FAN, (readonly)
  49. * PAGE_COMMUNITY automatically approves all friend requests as REL_FAN, but with
  50. * write access to wall and comments (no email and not included in page owner's ACL lists)
  51. * PAGE_FREELOVE automatically approves all friend requests as full friends (REL_BUD).
  52. *
  53. */
  54. define ( 'PAGE_NORMAL', 0 );
  55. define ( 'PAGE_SOAPBOX', 1 );
  56. define ( 'PAGE_COMMUNITY', 2 );
  57. define ( 'PAGE_FREELOVE', 3 );
  58. /**
  59. * Maximum number of "people who like (or don't like) this" that we will list by name
  60. */
  61. define ( 'MAX_LIKERS', 75);
  62. /**
  63. * email notification options
  64. */
  65. define ( 'NOTIFY_INTRO', 0x0001 );
  66. define ( 'NOTIFY_CONFIRM', 0x0002 );
  67. define ( 'NOTIFY_WALL', 0x0004 );
  68. define ( 'NOTIFY_COMMENT', 0x0008 );
  69. define ( 'NOTIFY_MAIL', 0x0010 );
  70. /**
  71. * various namespaces we may need to parse
  72. */
  73. define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
  74. define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
  75. define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
  76. define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
  77. define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
  78. define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
  79. define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
  80. define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
  81. define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
  82. define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
  83. define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
  84. /**
  85. * activity stream defines
  86. */
  87. define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
  88. define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
  89. define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
  90. define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
  91. define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
  92. define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
  93. define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
  94. define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
  95. define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
  96. define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
  97. define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
  98. define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
  99. define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
  100. define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
  101. define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
  102. /**
  103. * item weight for query ordering
  104. */
  105. define ( 'GRAVITY_PARENT', 0);
  106. define ( 'GRAVITY_LIKE', 3);
  107. define ( 'GRAVITY_COMMENT', 6);
  108. /**
  109. *
  110. * Reverse the effect of magic_quotes_gpc if it is enabled.
  111. * Please disable magic_quotes_gpc so we don't have to do this.
  112. * See http://php.net/manual/en/security.magicquotes.disabling.php
  113. *
  114. */
  115. if (get_magic_quotes_gpc()) {
  116. $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  117. while (list($key, $val) = each($process)) {
  118. foreach ($val as $k => $v) {
  119. unset($process[$key][$k]);
  120. if (is_array($v)) {
  121. $process[$key][stripslashes($k)] = $v;
  122. $process[] = &$process[$key][stripslashes($k)];
  123. } else {
  124. $process[$key][stripslashes($k)] = stripslashes($v);
  125. }
  126. }
  127. }
  128. unset($process);
  129. }
  130. /*
  131. * translation system
  132. */
  133. require_once("include/pgettext.php");
  134. /**
  135. *
  136. * class: App
  137. *
  138. * Our main application structure for the life of this page
  139. * Primarily deals with the URL that got us here
  140. * and tries to make some sense of it, and
  141. * stores our page contents and config storage
  142. * and anything else that might need to be passed around
  143. * before we spit the page out.
  144. *
  145. */
  146. if(! class_exists('App')) {
  147. class App {
  148. public $module_loaded = false;
  149. public $query_string;
  150. public $config;
  151. public $page;
  152. public $profile;
  153. public $user;
  154. public $cid;
  155. public $contact;
  156. public $content;
  157. public $data;
  158. public $error = false;
  159. public $cmd;
  160. public $argv;
  161. public $argc;
  162. public $module;
  163. public $pager;
  164. public $strings;
  165. public $path;
  166. public $hooks;
  167. public $timezone;
  168. public $interactive = true;
  169. public $plugins;
  170. public $apps;
  171. public $identities;
  172. private $scheme;
  173. private $hostname;
  174. private $baseurl;
  175. private $db;
  176. private $curl_code;
  177. private $curl_headers;
  178. function __construct() {
  179. $this->config = array();
  180. $this->page = array();
  181. $this->pager= array();
  182. $this->query_string = '';
  183. $this->scheme = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'])) ? 'https' : 'http' );
  184. if(x($_SERVER,'SERVER_NAME')) {
  185. $this->hostname = $_SERVER['SERVER_NAME'];
  186. /**
  187. * Figure out if we are running at the top of a domain
  188. * or in a sub-directory and adjust accordingly
  189. */
  190. $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
  191. if(isset($path) && strlen($path) && ($path != $this->path))
  192. $this->path = $path;
  193. }
  194. set_include_path("include/$this->hostname" . PATH_SEPARATOR . 'include' . PATH_SEPARATOR . '.' );
  195. if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=")
  196. $this->query_string = substr($_SERVER['QUERY_STRING'],2);
  197. if(x($_GET,'q'))
  198. $this->cmd = trim($_GET['q'],'/\\');
  199. /**
  200. *
  201. * Break the URL path into C style argc/argv style arguments for our
  202. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  203. * will be 3 (integer) and $this->argv will contain:
  204. * [0] => 'module'
  205. * [1] => 'arg1'
  206. * [2] => 'arg2'
  207. *
  208. *
  209. * There will always be one argument. If provided a naked domain
  210. * URL, $this->argv[0] is set to "home".
  211. *
  212. */
  213. $this->argv = explode('/',$this->cmd);
  214. $this->argc = count($this->argv);
  215. if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
  216. $this->module = $this->argv[0];
  217. }
  218. else {
  219. $this->module = 'home';
  220. }
  221. /**
  222. * Special handling for the webfinger/lrdd host XRD file
  223. * Just spit out the contents and exit.
  224. */
  225. if($this->cmd === '.well-known/host-meta') {
  226. require_once('include/hostxrd.php');
  227. hostxrd($this->hostname);
  228. // NOTREACHED
  229. }
  230. /**
  231. * See if there is any page number information, and initialise
  232. * pagination
  233. */
  234. $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
  235. $this->pager['itemspage'] = 50;
  236. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  237. $this->pager['total'] = 0;
  238. }
  239. function get_baseurl($ssl = false) {
  240. $scheme = $this->scheme;
  241. if(x($this->config,'ssl_policy')) {
  242. if(($ssl) || ($this->config['ssl_policy'] == SSL_POLICY_FULL))
  243. $scheme = 'https';
  244. if(($this->config['ssl_policy'] == SSL_POLICY_SELFSIGN) && (local_user() || x($_POST,'auth-params')))
  245. $scheme = 'https';
  246. }
  247. $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
  248. return $this->baseurl;
  249. }
  250. function set_baseurl($url) {
  251. $parsed = @parse_url($url);
  252. $this->baseurl = $url;
  253. if($parsed) {
  254. $this->scheme = $parsed['scheme'];
  255. $this->hostname = $parsed['host'];
  256. if(x($parsed,'port'))
  257. $this->hostname .= ':' . $parsed['port'];
  258. if(x($parsed,'path'))
  259. $this->path = trim($parsed['path'],'\\/');
  260. }
  261. }
  262. function get_hostname() {
  263. return $this->hostname;
  264. }
  265. function set_hostname($h) {
  266. $this->hostname = $h;
  267. }
  268. function set_path($p) {
  269. $this->path = trim(trim($p),'/');
  270. }
  271. function get_path() {
  272. return $this->path;
  273. }
  274. function set_pager_total($n) {
  275. $this->pager['total'] = intval($n);
  276. }
  277. function set_pager_itemspage($n) {
  278. $this->pager['itemspage'] = intval($n);
  279. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  280. }
  281. function init_pagehead() {
  282. $this->page['title'] = $this->config['sitename'];
  283. $tpl = load_view_file('view/head.tpl');
  284. $this->page['htmlhead'] = replace_macros($tpl,array(
  285. '$baseurl' => $this->get_baseurl() . '/',
  286. '$generator' => 'Friendika' . ' ' . FRIENDIKA_VERSION,
  287. '$delitem' => t('Delete this item?'),
  288. '$comment' => t('Comment')
  289. ));
  290. }
  291. function set_curl_code($code) {
  292. $this->curl_code = $code;
  293. }
  294. function get_curl_code() {
  295. return $this->curl_code;
  296. }
  297. function set_curl_headers($headers) {
  298. $this->curl_headers = $headers;
  299. }
  300. function get_curl_headers() {
  301. return $this->curl_headers;
  302. }
  303. }}
  304. // retrieve the App structure
  305. // useful in functions which require it but don't get it passed to them
  306. if(! function_exists('get_app')) {
  307. function get_app() {
  308. global $a;
  309. return $a;
  310. }};
  311. // Multi-purpose function to check variable state.
  312. // Usage: x($var) or $x($array,'key')
  313. // returns false if variable/key is not set
  314. // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
  315. // e.g. x('') or x(0) returns 0;
  316. if(! function_exists('x')) {
  317. function x($s,$k = NULL) {
  318. if($k != NULL) {
  319. if((is_array($s)) && (array_key_exists($k,$s))) {
  320. if($s[$k])
  321. return (int) 1;
  322. return (int) 0;
  323. }
  324. return false;
  325. }
  326. else {
  327. if(isset($s)) {
  328. if($s) {
  329. return (int) 1;
  330. }
  331. return (int) 0;
  332. }
  333. return false;
  334. }
  335. }}
  336. // called from db initialisation if db is dead.
  337. if(! function_exists('system_unavailable')) {
  338. function system_unavailable() {
  339. include('system_unavailable.php');
  340. system_down();
  341. killme();
  342. }}
  343. // Primarily involved with database upgrade, but also sets the
  344. // base url for use in cmdline programs which don't have
  345. // $_SERVER variables, and synchronising the state of installed plugins.
  346. if(! function_exists('check_config')) {
  347. function check_config(&$a) {
  348. load_config('system');
  349. $build = get_config('system','build');
  350. if(! x($build))
  351. $build = set_config('system','build',DB_UPDATE_VERSION);
  352. $url = get_config('system','url');
  353. // if the url isn't set or the stored url is radically different
  354. // than the currently visited url, store the current value accordingly.
  355. // "Radically different" ignores common variations such as http vs https
  356. // and www.example.com vs example.com.
  357. if((! x($url)) || (! link_compare($url,$a->get_baseurl())))
  358. $url = set_config('system','url',$a->get_baseurl());
  359. if($build != DB_UPDATE_VERSION) {
  360. $stored = intval($build);
  361. $current = intval(DB_UPDATE_VERSION);
  362. if(($stored < $current) && file_exists('update.php')) {
  363. // We're reporting a different version than what is currently installed.
  364. // Run any existing update scripts to bring the database up to current.
  365. require_once('update.php');
  366. for($x = $stored; $x < $current; $x ++) {
  367. if(function_exists('update_' . $x)) {
  368. $func = 'update_' . $x;
  369. $func($a);
  370. }
  371. }
  372. set_config('system','build', DB_UPDATE_VERSION);
  373. }
  374. }
  375. /**
  376. *
  377. * Synchronise plugins:
  378. *
  379. * $a->config['system']['addon'] contains a comma-separated list of names
  380. * of plugins/addons which are used on this system.
  381. * Go through the database list of already installed addons, and if we have
  382. * an entry, but it isn't in the config list, call the uninstall procedure
  383. * and mark it uninstalled in the database (for now we'll remove it).
  384. * Then go through the config list and if we have a plugin that isn't installed,
  385. * call the install procedure and add it to the database.
  386. *
  387. */
  388. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  389. if(count($r))
  390. $installed = $r;
  391. else
  392. $installed = array();
  393. $plugins = get_config('system','addon');
  394. $plugins_arr = array();
  395. if($plugins)
  396. $plugins_arr = explode(',',str_replace(' ', '',$plugins));
  397. $a->plugins = $plugins_arr;
  398. $installed_arr = array();
  399. if(count($installed)) {
  400. foreach($installed as $i) {
  401. if(! in_array($i['name'],$plugins_arr)) {
  402. logger("Addons: uninstalling " . $i['name']);
  403. q("DELETE FROM `addon` WHERE `id` = %d LIMIT 1",
  404. intval($i['id'])
  405. );
  406. @include_once('addon/' . $i['name'] . '/' . $i['name'] . '.php');
  407. if(function_exists($i['name'] . '_uninstall')) {
  408. $func = $i['name'] . '_uninstall';
  409. $func();
  410. }
  411. }
  412. else
  413. $installed_arr[] = $i['name'];
  414. }
  415. }
  416. if(count($plugins_arr)) {
  417. foreach($plugins_arr as $p) {
  418. if(! in_array($p,$installed_arr)) {
  419. logger("Addons: installing " . $p);
  420. $t = filemtime('addon/' . $p . '/' . $p . '.php');
  421. @include_once('addon/' . $p . '/' . $p . '.php');
  422. if(function_exists($p . '_install')) {
  423. $func = $p . '_install';
  424. $func();
  425. $r = q("INSERT INTO `addon` (`name`, `installed`, `timestamp`) VALUES ( '%s', 1, %d ) ",
  426. dbesc($p),
  427. intval($t)
  428. );
  429. }
  430. }
  431. }
  432. }
  433. load_hooks();
  434. return;
  435. }}
  436. // reload all updated plugins
  437. if(! function_exists('reload_plugins')) {
  438. function reload_plugins() {
  439. $plugins = get_config('system','addon');
  440. if(strlen($plugins)) {
  441. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  442. if(count($r))
  443. $installed = $r;
  444. else
  445. $installed = array();
  446. $parr = explode(',',$plugins);
  447. if(count($parr)) {
  448. foreach($parr as $pl) {
  449. $pl = trim($pl);
  450. $t = filemtime('addon/' . $pl . '/' . $pl . '.php');
  451. foreach($installed as $i) {
  452. if(($i['name'] == $pl) && ($i['timestamp'] != $t)) {
  453. logger('Reloading plugin: ' . $i['name']);
  454. @include_once('addon/' . $pl . '/' . $pl . '.php');
  455. if(function_exists($pl . '_uninstall')) {
  456. $func = $pl . '_uninstall';
  457. $func();
  458. }
  459. if(function_exists($pl . '_install')) {
  460. $func = $pl . '_install';
  461. $func();
  462. }
  463. q("UPDATE `addon` SET `timestamp` = %d WHERE `id` = %d LIMIT 1",
  464. intval($t),
  465. intval($i['id'])
  466. );
  467. }
  468. }
  469. }
  470. }
  471. }
  472. }}
  473. // This is our template processor.
  474. // $s is the string requiring macro substitution.
  475. // $r is an array of key value pairs (search => replace)
  476. // returns substituted string.
  477. // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
  478. // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
  479. // depending on the order in which they were declared in the array.
  480. if(! function_exists('replace_macros')) {
  481. function replace_macros($s,$r) {
  482. $search = array();
  483. $replace = array();
  484. if(is_array($r) && count($r)) {
  485. foreach ($r as $k => $v ) {
  486. $search[] = $k;
  487. $replace[] = $v;
  488. }
  489. }
  490. return str_replace($search,$replace,$s);
  491. }}
  492. // curl wrapper. If binary flag is true, return binary
  493. // results.
  494. if(! function_exists('fetch_url')) {
  495. function fetch_url($url,$binary = false, &$redirects = 0) {
  496. $a = get_app();
  497. $ch = curl_init($url);
  498. if(($redirects > 8) || (! $ch))
  499. return false;
  500. curl_setopt($ch, CURLOPT_HEADER, true);
  501. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  502. $curl_time = intval(get_config('system','curl_timeout'));
  503. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  504. // by default we will allow self-signed certs
  505. // but you can override this
  506. $check_cert = get_config('system','verifyssl');
  507. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  508. $prx = get_config('system','proxy');
  509. if(strlen($prx)) {
  510. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  511. curl_setopt($ch, CURLOPT_PROXY, $prx);
  512. $prxusr = get_config('system','proxyuser');
  513. if(strlen($prxusr))
  514. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  515. }
  516. if($binary)
  517. curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  518. $a->set_curl_code(0);
  519. // don't let curl abort the entire application
  520. // if it throws any errors.
  521. $s = @curl_exec($ch);
  522. $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  523. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  524. if(stristr($header,'100') && (strlen($header) < 30)) {
  525. // 100 Continue has two headers, get the real one
  526. $s = substr($s,strlen($header)+4);
  527. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  528. }
  529. if($http_code == 301 || $http_code == 302 || $http_code == 303) {
  530. $matches = array();
  531. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  532. $url = trim(array_pop($matches));
  533. $url_parsed = @parse_url($url);
  534. if (isset($url_parsed)) {
  535. $redirects++;
  536. return fetch_url($url,$binary,$redirects);
  537. }
  538. }
  539. $a->set_curl_code($http_code);
  540. $body = substr($s,strlen($header)+4);
  541. /* one more try to make sure there are no more headers */
  542. if(strpos($body,'HTTP/') === 0) {
  543. $header = substr($body,0,strpos($body,"\r\n\r\n"));
  544. $body = substr($body,strlen($header)+4);
  545. }
  546. $a->set_curl_headers($header);
  547. curl_close($ch);
  548. return($body);
  549. }}
  550. // post request to $url. $params is an array of post variables.
  551. if(! function_exists('post_url')) {
  552. function post_url($url,$params, $headers = null, &$redirects = 0) {
  553. $a = get_app();
  554. $ch = curl_init($url);
  555. if(($redirects > 8) || (! $ch))
  556. return false;
  557. curl_setopt($ch, CURLOPT_HEADER, true);
  558. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  559. curl_setopt($ch, CURLOPT_POST,1);
  560. curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
  561. $curl_time = intval(get_config('system','curl_timeout'));
  562. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  563. if(is_array($headers))
  564. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  565. $check_cert = get_config('system','verifyssl');
  566. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  567. $prx = get_config('system','proxy');
  568. if(strlen($prx)) {
  569. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  570. curl_setopt($ch, CURLOPT_PROXY, $prx);
  571. $prxusr = get_config('system','proxyuser');
  572. if(strlen($prxusr))
  573. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  574. }
  575. $a->set_curl_code(0);
  576. // don't let curl abort the entire application
  577. // if it throws any errors.
  578. $s = @curl_exec($ch);
  579. $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  580. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  581. if(stristr($header,'100') && (strlen($header) < 30)) {
  582. // 100 Continue has two headers, get the real one
  583. $s = substr($s,strlen($header)+4);
  584. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  585. }
  586. if($http_code == 301 || $http_code == 302 || $http_code == 303) {
  587. $matches = array();
  588. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  589. $url = trim(array_pop($matches));
  590. $url_parsed = @parse_url($url);
  591. if (isset($url_parsed)) {
  592. $redirects++;
  593. return post_url($url,$binary,$headers,$redirects);
  594. }
  595. }
  596. $a->set_curl_code($http_code);
  597. $body = substr($s,strlen($header)+4);
  598. /* one more try to make sure there are no more headers */
  599. if(strpos($body,'HTTP/') === 0) {
  600. $header = substr($body,0,strpos($body,"\r\n\r\n"));
  601. $body = substr($body,strlen($header)+4);
  602. }
  603. $a->set_curl_headers($header);
  604. curl_close($ch);
  605. return($body);
  606. }}
  607. // random hash, 64 chars
  608. if(! function_exists('random_string')) {
  609. function random_string() {
  610. return(hash('sha256',uniqid(rand(),true)));
  611. }}
  612. /**
  613. * This is our primary input filter.
  614. *
  615. * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
  616. * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
  617. * after cleansing, and angle chars with the high bit set could get through as markup.
  618. *
  619. * This is now disabled because it was interfering with some legitimate unicode sequences
  620. * and hopefully there aren't a lot of those browsers left.
  621. *
  622. * Use this on any text input where angle chars are not valid or permitted
  623. * They will be replaced with safer brackets. This may be filtered further
  624. * if these are not allowed either.
  625. *
  626. */
  627. if(! function_exists('notags')) {
  628. function notags($string) {
  629. return(str_replace(array("<",">"), array('[',']'), $string));
  630. // High-bit filter no longer used
  631. // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
  632. }}
  633. // use this on "body" or "content" input where angle chars shouldn't be removed,
  634. // and allow them to be safely displayed.
  635. if(! function_exists('escape_tags')) {
  636. function escape_tags($string) {
  637. return(htmlspecialchars($string));
  638. }}
  639. // wrapper for adding a login box. If $register == true provide a registration
  640. // link. This will most always depend on the value of $a->config['register_policy'].
  641. // returns the complete html for inserting into the page
  642. if(! function_exists('login')) {
  643. function login($register = false) {
  644. $o = "";
  645. $register_tpl = (($register) ? load_view_file("view/register-link.tpl") : "");
  646. $register_html = replace_macros($register_tpl,array(
  647. '$title' => t('Create a New Account'),
  648. '$desc' => t('Register')
  649. ));
  650. $noid = get_config('system','no_openid');
  651. if($noid) {
  652. $classname = 'no-openid';
  653. $namelabel = t('Nickname or Email address: ');
  654. $passlabel = t('Password: ');
  655. $login = t('Login');
  656. }
  657. else {
  658. $classname = 'openid';
  659. $namelabel = t('Nickname/Email/OpenID: ');
  660. $passlabel = t("Password \x28if not OpenID\x29: ");
  661. $login = t('Login');
  662. }
  663. $lostpass = t('Forgot your password?');
  664. $lostlink = t('Password Reset');
  665. if(local_user()) {
  666. $tpl = load_view_file("view/logout.tpl");
  667. }
  668. else {
  669. $tpl = load_view_file("view/login.tpl");
  670. }
  671. $o = replace_macros($tpl,array(
  672. '$logout' => t('Logout'),
  673. '$register_html' => $register_html,
  674. '$classname' => $classname,
  675. '$namelabel' => $namelabel,
  676. '$passlabel' => $passlabel,
  677. '$login' => $login,
  678. '$lostpass' => $lostpass,
  679. '$lostlink' => $lostlink
  680. ));
  681. return $o;
  682. }}
  683. // generate a string that's random, but usually pronounceable.
  684. // used to generate initial passwords
  685. if(! function_exists('autoname')) {
  686. function autoname($len) {
  687. $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
  688. if(mt_rand(0,5) == 4)
  689. $vowels[] = 'y';
  690. $cons = array(
  691. 'b','bl','br',
  692. 'c','ch','cl','cr',
  693. 'd','dr',
  694. 'f','fl','fr',
  695. 'g','gh','gl','gr',
  696. 'h',
  697. 'j',
  698. 'k','kh','kl','kr',
  699. 'l',
  700. 'm',
  701. 'n',
  702. 'p','ph','pl','pr',
  703. 'qu',
  704. 'r','rh',
  705. 's','sc','sh','sm','sp','st',
  706. 't','th','tr',
  707. 'v',
  708. 'w','wh',
  709. 'x',
  710. 'z','zh'
  711. );
  712. $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
  713. 'nd','ng','nk','nt','rn','rp','rt');
  714. $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
  715. 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
  716. $start = mt_rand(0,2);
  717. if($start == 0)
  718. $table = $vowels;
  719. else
  720. $table = $cons;
  721. $word = '';
  722. for ($x = 0; $x < $len; $x ++) {
  723. $r = mt_rand(0,count($table) - 1);
  724. $word .= $table[$r];
  725. if($table == $vowels)
  726. $table = array_merge($cons,$midcons);
  727. else
  728. $table = $vowels;
  729. }
  730. $word = substr($word,0,$len);
  731. foreach($noend as $noe) {
  732. if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
  733. $word = substr($word,0,-1);
  734. break;
  735. }
  736. }
  737. if(substr($word,-1) == 'q')
  738. $word = substr($word,0,-1);
  739. return $word;
  740. }}
  741. // Used to end the current process, after saving session state.
  742. if(! function_exists('killme')) {
  743. function killme() {
  744. session_write_close();
  745. exit;
  746. }}
  747. // redirect to another URL and terminate this process.
  748. if(! function_exists('goaway')) {
  749. function goaway($s) {
  750. header("Location: $s");
  751. killme();
  752. }}
  753. // Generic XML return
  754. // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
  755. // of $st and an optional text <message> of $message and terminates the current process.
  756. if(! function_exists('xml_status')) {
  757. function xml_status($st, $message = '') {
  758. $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
  759. if($st)
  760. logger('xml_status returning non_zero: ' . $st . " message=" . $message);
  761. header( "Content-type: text/xml" );
  762. echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
  763. echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
  764. killme();
  765. }}
  766. // Returns the uid of locally logged in user or false.
  767. if(! function_exists('local_user')) {
  768. function local_user() {
  769. if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
  770. return intval($_SESSION['uid']);
  771. return false;
  772. }}
  773. // Returns contact id of authenticated site visitor or false
  774. if(! function_exists('remote_user')) {
  775. function remote_user() {
  776. if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
  777. return intval($_SESSION['visitor_id']);
  778. return false;
  779. }}
  780. // contents of $s are displayed prominently on the page the next time
  781. // a page is loaded. Usually used for errors or alerts.
  782. if(! function_exists('notice')) {
  783. function notice($s) {
  784. $a = get_app();
  785. if($a->interactive)
  786. $_SESSION['sysmsg'] .= $s;
  787. }}
  788. // wrapper around config to limit the text length of an incoming message
  789. if(! function_exists('get_max_import_size')) {
  790. function get_max_import_size() {
  791. global $a;
  792. return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
  793. }}
  794. // escape text ($str) for XML transport
  795. // returns escaped text.
  796. if(! function_exists('xmlify')) {
  797. function xmlify($str) {
  798. $buffer = '';
  799. for($x = 0; $x < strlen($str); $x ++) {
  800. $char = $str[$x];
  801. switch( $char ) {
  802. case "\r" :
  803. break;
  804. case "&" :
  805. $buffer .= '&amp;';
  806. break;
  807. case "'" :
  808. $buffer .= '&apos;';
  809. break;
  810. case "\"" :
  811. $buffer .= '&quot;';
  812. break;
  813. case '<' :
  814. $buffer .= '&lt;';
  815. break;
  816. case '>' :
  817. $buffer .= '&gt;';
  818. break;
  819. case "\n" :
  820. $buffer .= "\n";
  821. break;
  822. default :
  823. $buffer .= $char;
  824. break;
  825. }
  826. }
  827. $buffer = trim($buffer);
  828. return($buffer);
  829. }}
  830. // undo an xmlify
  831. // pass xml escaped text ($s), returns unescaped text
  832. if(! function_exists('unxmlify')) {
  833. function unxmlify($s) {
  834. $ret = str_replace('&amp;','&', $s);
  835. $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
  836. return $ret;
  837. }}
  838. // convenience wrapper, reverse the operation "bin2hex"
  839. if(! function_exists('hex2bin')) {
  840. function hex2bin($s) {
  841. if(! ctype_xdigit($s)) {
  842. logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
  843. return($s);
  844. }
  845. return(pack("H*",$s));
  846. }}
  847. // Automatic pagination.
  848. // To use, get the count of total items.
  849. // Then call $a->set_pager_total($number_items);
  850. // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
  851. // Then call paginate($a) after the end of the display loop to insert the pager block on the page
  852. // (assuming there are enough items to paginate).
  853. // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
  854. // will limit the results to the correct items for the current page.
  855. // The actual page handling is then accomplished at the application layer.
  856. if(! function_exists('paginate')) {
  857. function paginate(&$a) {
  858. $o = '';
  859. $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
  860. $stripped = str_replace('q=','',$stripped);
  861. $stripped = trim($stripped,'/');
  862. $pagenum = $a->pager['page'];
  863. $url = $a->get_baseurl() . '/' . $stripped;
  864. if($a->pager['total'] > $a->pager['itemspage']) {
  865. $o .= '<div class="pager">';
  866. if($a->pager['page'] != 1)
  867. $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
  868. $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
  869. $numpages = $a->pager['total'] / $a->pager['itemspage'];
  870. $numstart = 1;
  871. $numstop = $numpages;
  872. if($numpages > 14) {
  873. $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
  874. $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
  875. }
  876. for($i = $numstart; $i <= $numstop; $i++){
  877. if($i == $a->pager['page'])
  878. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  879. else
  880. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  881. $o .= '</span> ';
  882. }
  883. if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
  884. if($i == $a->pager['page'])
  885. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  886. else
  887. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  888. $o .= '</span> ';
  889. }
  890. $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
  891. $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
  892. if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
  893. $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
  894. $o .= '</div>'."\r\n";
  895. }
  896. return $o;
  897. }}
  898. // Turn user/group ACLs stored as angle bracketed text into arrays
  899. if(! function_exists('expand_acl')) {
  900. function expand_acl($s) {
  901. // turn string array of angle-bracketed elements into numeric array
  902. // e.g. "<1><2><3>" => array(1,2,3);
  903. $ret = array();
  904. if(strlen($s)) {
  905. $t = str_replace('<','',$s);
  906. $a = explode('>',$t);
  907. foreach($a as $aa) {
  908. if(intval($aa))
  909. $ret[] = intval($aa);
  910. }
  911. }
  912. return $ret;
  913. }}
  914. // Used to wrap ACL elements in angle brackets for storage
  915. if(! function_exists('sanitise_acl')) {
  916. function sanitise_acl(&$item) {
  917. if(intval($item))
  918. $item = '<' . intval(notags(trim($item))) . '>';
  919. else
  920. unset($item);
  921. }}
  922. // retrieve a "family" of config variables from database to cached storage
  923. if(! function_exists('load_config')) {
  924. function load_config($family) {
  925. global $a;
  926. $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
  927. dbesc($family)
  928. );
  929. if(count($r)) {
  930. foreach($r as $rr) {
  931. $k = $rr['k'];
  932. $a->config[$family][$k] = $rr['v'];
  933. }
  934. }
  935. }}
  936. // get a particular config variable given the family name
  937. // and key. Returns false if not set.
  938. // $instore is only used by the set_config function
  939. // to determine if the key already exists in the DB
  940. // If a key is found in the DB but doesn't exist in
  941. // local config cache, pull it into the cache so we don't have
  942. // to hit the DB again for this item.
  943. if(! function_exists('get_config')) {
  944. function get_config($family, $key, $instore = false) {
  945. global $a;
  946. if(! $instore) {
  947. if(isset($a->config[$family][$key])) {
  948. if($a->config[$family][$key] === '!<unset>!') {
  949. return false;
  950. }
  951. return $a->config[$family][$key];
  952. }
  953. }
  954. $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  955. dbesc($family),
  956. dbesc($key)
  957. );
  958. if(count($ret)) {
  959. $a->config[$family][$key] = $ret[0]['v'];
  960. return $ret[0]['v'];
  961. }
  962. else {
  963. $a->config[$family][$key] = '!<unset>!';
  964. }
  965. return false;
  966. }}
  967. // Store a config value ($value) in the category ($family)
  968. // under the key ($key)
  969. // Return the value, or false if the database update failed
  970. if(! function_exists('set_config')) {
  971. function set_config($family,$key,$value) {
  972. global $a;
  973. if(get_config($family,$key,true) === false) {
  974. $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
  975. dbesc($family),
  976. dbesc($key),
  977. dbesc($value)
  978. );
  979. if($ret)
  980. return $value;
  981. return $ret;
  982. }
  983. $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  984. dbesc($value),
  985. dbesc($family),
  986. dbesc($key)
  987. );
  988. $a->config[$family][$key] = $value;
  989. if($ret)
  990. return $value;
  991. return $ret;
  992. }}
  993. if(! function_exists('load_pconfig')) {
  994. function load_pconfig($uid,$family) {
  995. global $a;
  996. $r = q("SELECT * FROM `pconfig` WHERE `cat` = '%s' AND `uid` = %d",
  997. dbesc($family),
  998. intval($uid)
  999. );
  1000. if(count($r)) {
  1001. foreach($r as $rr) {
  1002. $k = $rr['k'];
  1003. $a->config[$uid][$family][$k] = $rr['v'];
  1004. }
  1005. }
  1006. }}
  1007. if(! function_exists('get_pconfig')) {
  1008. function get_pconfig($uid,$family, $key, $instore = false) {
  1009. global $a;
  1010. if(! $instore) {
  1011. if(isset($a->config[$uid][$family][$key])) {
  1012. if($a->config[$uid][$family][$key] === '!<unset>!') {
  1013. return false;
  1014. }
  1015. return $a->config[$uid][$family][$key];
  1016. }
  1017. }
  1018. $ret = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1019. intval($uid),
  1020. dbesc($family),
  1021. dbesc($key)
  1022. );
  1023. if(count($ret)) {
  1024. $a->config[$uid][$family][$key] = $ret[0]['v'];
  1025. return $ret[0]['v'];
  1026. }
  1027. else {
  1028. $a->config[$uid][$family][$key] = '!<unset>!';
  1029. }
  1030. return false;
  1031. }}
  1032. if(! function_exists('del_config')) {
  1033. function del_config($family,$key) {
  1034. global $a;
  1035. if(x($a->config[$family],$key))
  1036. unset($a->config[$family][$key]);
  1037. $ret = q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1038. dbesc($cat),
  1039. dbesc($key)
  1040. );
  1041. return $ret;
  1042. }}
  1043. // Same as above functions except these are for personal config storage and take an
  1044. // additional $uid argument.
  1045. if(! function_exists('set_pconfig')) {
  1046. function set_pconfig($uid,$family,$key,$value) {
  1047. global $a;
  1048. if(get_pconfig($uid,$family,$key,true) === false) {
  1049. $ret = q("INSERT INTO `pconfig` ( `uid`, `cat`, `k`, `v` ) VALUES ( %d, '%s', '%s', '%s' ) ",
  1050. intval($uid),
  1051. dbesc($family),
  1052. dbesc($key),
  1053. dbesc($value)
  1054. );
  1055. if($ret)
  1056. return $value;
  1057. return $ret;
  1058. }
  1059. $ret = q("UPDATE `pconfig` SET `v` = '%s' WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1060. dbesc($value),
  1061. intval($uid),
  1062. dbesc($family),
  1063. dbesc($key)
  1064. );
  1065. $a->config[$uid][$family][$key] = $value;
  1066. if($ret)
  1067. return $value;
  1068. return $ret;
  1069. }}
  1070. if(! function_exists('del_pconfig')) {
  1071. function del_pconfig($uid,$family,$key) {
  1072. global $a;
  1073. if(x($a->config[$uid][$family],$key))
  1074. unset($a->config[$uid][$family][$key]);
  1075. $ret = q("DELETE FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1076. intval($uid),
  1077. dbesc($family),
  1078. dbesc($key)
  1079. );
  1080. return $ret;
  1081. }}
  1082. // convert an XML document to a normalised, case-corrected array
  1083. // used by webfinger
  1084. if(! function_exists('convert_xml_element_to_array')) {
  1085. function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
  1086. // If we're getting too deep, bail out
  1087. if ($recursion_depth > 512) {
  1088. return(null);
  1089. }
  1090. if (!is_string($xml_element) &&
  1091. !is_array($xml_element) &&
  1092. (get_class($xml_element) == 'SimpleXMLElement')) {
  1093. $xml_element_copy = $xml_element;
  1094. $xml_element = get_object_vars($xml_element);
  1095. }
  1096. if (is_array($xml_element)) {
  1097. $result_array = array();
  1098. if (count($xml_element) <= 0) {
  1099. return (trim(strval($xml_element_copy)));
  1100. }
  1101. foreach($xml_element as $key=>$value) {
  1102. $recursion_depth++;
  1103. $result_array[strtolower($key)] =
  1104. convert_xml_element_to_array($value, $recursion_depth);
  1105. $recursion_depth--;
  1106. }
  1107. if ($recursion_depth == 0) {
  1108. $temp_array = $result_array;
  1109. $result_array = array(
  1110. strtolower($xml_element_copy->getName()) => $temp_array,
  1111. );
  1112. }
  1113. return ($result_array);
  1114. } else {
  1115. return (trim(strval($xml_element)));
  1116. }
  1117. }}
  1118. // Given an email style address, perform webfinger lookup and
  1119. // return the resulting DFRN profile URL, or if no DFRN profile URL
  1120. // is located, returns an OStatus subscription template (prefixed
  1121. // with the string 'stat:' to identify it as on OStatus template).
  1122. // If this isn't an email style address just return $s.
  1123. // Return an empty string if email-style addresses but webfinger fails,
  1124. // or if the resultant personal XRD doesn't contain a supported
  1125. // subscription/friend-request attribute.
  1126. if(! function_exists('webfinger_dfrn')) {
  1127. function webfinger_dfrn($s) {
  1128. if(! strstr($s,'@')) {
  1129. return $s;
  1130. }
  1131. $links = webfinger($s);
  1132. logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
  1133. if(count($links)) {
  1134. foreach($links as $link)
  1135. if($link['@attributes']['rel'] === NAMESPACE_DFRN)
  1136. return $link['@attributes']['href'];
  1137. foreach($links as $link)
  1138. if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
  1139. return 'stat:' . $link['@attributes']['template'];
  1140. }
  1141. return '';
  1142. }}
  1143. // Given an email style address, perform webfinger lookup and
  1144. // return the array of link attributes from the personal XRD file.
  1145. // On error/failure return an empty array.
  1146. if(! function_exists('webfinger')) {
  1147. function webfinger($s) {
  1148. $host = '';
  1149. if(strstr($s,'@')) {
  1150. $host = substr($s,strpos($s,'@') + 1);
  1151. }
  1152. if(strlen($host)) {
  1153. $tpl = fetch_lrdd_template($host);
  1154. logger('webfinger: lrdd template: ' . $tpl);
  1155. if(strlen($tpl)) {
  1156. $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
  1157. logger('webfinger: pxrd: ' . $pxrd);
  1158. $links = fetch_xrd_links($pxrd);
  1159. if(! count($links)) {
  1160. // try with double slashes
  1161. $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
  1162. logger('webfinger: pxrd: ' . $pxrd);
  1163. $links = fetch_xrd_links($pxrd);
  1164. }
  1165. return $links;
  1166. }
  1167. }
  1168. return array();
  1169. }}
  1170. if(! function_exists('lrdd')) {
  1171. function lrdd($uri) {
  1172. $a = get_app();
  1173. // default priority is host priority, host-meta first
  1174. $priority = 'host';
  1175. // All we have is an email address. Resource-priority is irrelevant
  1176. // because our URI isn't directly resolvable.
  1177. if(strstr($uri,'@')) {
  1178. return(webfinger($uri));
  1179. }
  1180. // get the host meta file
  1181. $host = @parse_url($uri);
  1182. if($host) {
  1183. $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
  1184. $url .= $host['host'] . '/.well-known/host-meta' ;
  1185. }
  1186. else
  1187. return array();
  1188. logger('lrdd: constructed url: ' . $url);
  1189. $xml = fetch_url($url);
  1190. $headers = $a->get_curl_headers();
  1191. if (! $xml)
  1192. return array();
  1193. logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
  1194. $h = parse_xml_string($xml);
  1195. $arr = convert_xml_element_to_array($h);
  1196. if(isset($arr['xrd']['property'])) {
  1197. $property = $arr['crd']['property'];
  1198. if(! isset($property[0]))
  1199. $properties = array($property);
  1200. else
  1201. $properties = $property;
  1202. foreach($properties as $prop)
  1203. if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
  1204. $priority = 'resource';
  1205. }
  1206. // save the links in case we need them
  1207. $links = array();
  1208. if(isset($arr['xrd']['link'])) {
  1209. $link = $arr['xrd']['link'];
  1210. if(! isset($link[0]))
  1211. $links = array($link);
  1212. else
  1213. $links = $link;
  1214. }
  1215. // do we have a template or href?
  1216. if(count($links)) {
  1217. foreach($links as $link) {
  1218. if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
  1219. if(x($link['@attributes'],'template'))
  1220. $tpl = $link['@attributes']['template'];
  1221. elseif(x($link['@attributes'],'href'))
  1222. $href = $link['@attributes']['href'];
  1223. }
  1224. }
  1225. }
  1226. if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
  1227. $tpl = '';
  1228. if($priority === 'host') {
  1229. if(strlen($tpl))
  1230. $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
  1231. elseif(isset($href))
  1232. $pxrd = $href;
  1233. if(isset($pxrd)) {
  1234. logger('lrdd: (host priority) pxrd: ' . $pxrd);
  1235. $links = fetch_xrd_links($pxrd);
  1236. return $links;
  1237. }
  1238. $lines = explode("\n",$headers);
  1239. if(count($lines)) {
  1240. foreach($lines as $line) {
  1241. if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
  1242. return(fetch_xrd_links($matches[1]));
  1243. break;
  1244. }
  1245. }
  1246. }
  1247. }
  1248. // priority 'resource'
  1249. $html = fetch_url($uri);
  1250. $headers = $a->get_curl_headers();
  1251. logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
  1252. // don't try and parse raw xml as html
  1253. if(! strstr($html,'<?xml')) {
  1254. require_once('library/HTML5/Parser.php');
  1255. $dom = @HTML5_Parser::parse($html);
  1256. if($dom) {
  1257. $items = $dom->getElementsByTagName('link');
  1258. foreach($items as $item) {
  1259. $x = $item->getAttribute('rel');
  1260. if($x == "lrdd") {
  1261. $pagelink = $item->getAttribute('href');
  1262. break;
  1263. }
  1264. }
  1265. }
  1266. }
  1267. if(isset($pagelink))
  1268. return(fetch_xrd_links($pagelink));
  1269. // next look in HTTP headers
  1270. $lines = explode("\n",$headers);
  1271. if(count($lines)) {
  1272. foreach($lines as $line) {
  1273. // TODO alter the following regex to support multiple relations (space separated)
  1274. if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
  1275. $pagelink = $matches[1];
  1276. break;
  1277. }
  1278. // don't try and run feeds through the html5 parser
  1279. if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
  1280. return array();
  1281. if(stristr($html,'<rss') || stristr($html,'<feed'))
  1282. return array();
  1283. }
  1284. }
  1285. if(isset($pagelink))
  1286. return(fetch_xrd_links($pagelink));
  1287. // If we haven't found any links, return the host xrd links (which we have already fetched)
  1288. if(isset($links))
  1289. return $links;
  1290. return array();
  1291. }}
  1292. // Given a host name, locate the LRDD template from that
  1293. // host. Returns the LRDD template or an empty string on
  1294. // error/failure.
  1295. if(! function_exists('fetch_lrdd_template')) {
  1296. function fetch_lrdd_template($host) {
  1297. $tpl = '';
  1298. $url1 = 'https://' . $host . '/.well-known/host-meta' ;
  1299. $url2 = 'http://' . $host . '/.well-known/host-meta' ;
  1300. $links = fetch_xrd_links($url1);
  1301. logger('template (https): ' . print_r($links,true));
  1302. if(! count($links)) {
  1303. $links = fetch_xrd_links($url2);
  1304. logger('template (http): ' . print_r($links,true));
  1305. }
  1306. if(count($links)) {
  1307. foreach($links as $link)
  1308. if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
  1309. $tpl = $link['@attributes']['template'];
  1310. }
  1311. if(! strpos($tpl,'{uri}'))
  1312. $tpl = '';
  1313. return $tpl;
  1314. }}
  1315. // Given a URL, retrieve the page as an XRD document.
  1316. // Return an array of links.
  1317. // on error/failure return empty array.
  1318. if(! function_exists('fetch_xrd_links')) {
  1319. function fetch_xrd_links($url) {
  1320. $xml = fetch_url($url);
  1321. if (! $xml)
  1322. return array();
  1323. logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
  1324. $h = parse_xml_string($xml);
  1325. $arr = convert_xml_element_to_array($h);
  1326. $links = array();
  1327. if(isset($arr['xrd']['link'])) {
  1328. $link = $arr['xrd']['link'];
  1329. if(! isset($link[0]))
  1330. $links = array($link);
  1331. else
  1332. $links = $link;
  1333. }
  1334. if(isset($arr['xrd']['alias'])) {
  1335. $alias = $arr['xrd']['alias'];
  1336. if(! isset($alias[0]))
  1337. $aliases = array($alias);
  1338. else
  1339. $aliases = $alias;
  1340. foreach($aliases as $alias) {
  1341. $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
  1342. }
  1343. }
  1344. logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
  1345. return $links;
  1346. }}
  1347. // Convert an ACL array to a storable string
  1348. if(! function_exists('perms2str')) {
  1349. function perms2str($p) {
  1350. $ret = '';
  1351. $tmp = $p;
  1352. if(is_array($tmp)) {
  1353. array_walk($tmp,'sanitise_acl');
  1354. $ret = implode('',$tmp);
  1355. }
  1356. return $ret;
  1357. }}
  1358. // generate a guaranteed unique (for this domain) item ID for ATOM
  1359. // safe from birthday paradox
  1360. if(! function_exists('item_new_uri')) {
  1361. function item_new_uri($hostname,$uid) {
  1362. do {
  1363. $dups = false;
  1364. $hash = random_string();
  1365. $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
  1366. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
  1367. dbesc($uri));
  1368. if(count($r))
  1369. $dups = true;
  1370. } while($dups == true);
  1371. return $uri;
  1372. }}
  1373. // Generate a guaranteed unique photo ID.
  1374. // safe from birthday paradox
  1375. if(! function_exists('photo_new_resource')) {
  1376. function photo_new_resource() {
  1377. do {
  1378. $found = false;
  1379. $resource = hash('md5',uniqid(mt_rand(),true));
  1380. $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
  1381. dbesc($resource)
  1382. );
  1383. if(count($r))
  1384. $found = true;
  1385. } while($found == true);
  1386. return $resource;
  1387. }}
  1388. // Take a URL from the wild, prepend http:// if necessary
  1389. // and check DNS to see if it's real
  1390. // return true if it's OK, false if something is wrong with it
  1391. if(! function_exists('validate_url')) {
  1392. function validate_url(&$url) {
  1393. if(substr($url,0,4) != 'http')
  1394. $url = 'http://' . $url;
  1395. $h = @parse_url($url);
  1396. if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
  1397. return true;
  1398. }
  1399. return false;
  1400. }}
  1401. // checks that email is an actual resolvable internet address
  1402. if(! function_exists('validate_email')) {
  1403. function validate_email($addr) {
  1404. if(! strpos($addr,'@'))
  1405. return false;
  1406. $h = substr($addr,strpos($addr,'@') + 1);
  1407. if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
  1408. return true;
  1409. }
  1410. return false;
  1411. }}
  1412. // Check $url against our list of allowed sites,
  1413. // wildcards allowed. If allowed_sites is unset return true;
  1414. // If url is allowed, return true.
  1415. // otherwise, return false
  1416. if(! function_exists('allowed_url')) {
  1417. function allowed_url($url) {
  1418. $h = @parse_url($url);
  1419. if(! $h) {
  1420. return false;
  1421. }
  1422. $str_allowed = get_config('system','allowed_sites');
  1423. if(! $str_allowed)
  1424. return true;
  1425. $found = false;
  1426. $host = strtolower($h['host']);
  1427. // always allow our own site
  1428. if($host == strtolower($_SERVER['SERVER_NAME']))
  1429. return true;
  1430. $fnmatch = function_exists('fnmatch');
  1431. $allowed = explode(',',$str_allowed);
  1432. if(count($allowed)) {
  1433. foreach($allowed as $a) {
  1434. $pat = strtolower(trim($a));
  1435. if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
  1436. $found = true;
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. return $found;
  1442. }}
  1443. // check if email address is allowed to register here.
  1444. // Compare against our list (wildcards allowed).
  1445. // Returns false if not allowed, true if allowed or if
  1446. // allowed list is not configured.
  1447. if(! function_exists('allowed_email')) {
  1448. function allowed_email($email) {
  1449. $domain = strtolower(substr($email,strpos($email,'@') + 1));
  1450. if(! $domain)
  1451. return false;
  1452. $str_allowed = get_config('system','allowed_email');
  1453. if(! $str_allowed)
  1454. return true;
  1455. $found = false;
  1456. $fnmatch = function_exists('fnmatch');
  1457. $allowed = explode(',',$str_allowed);
  1458. if(count($allowed)) {
  1459. foreach($allowed as $a) {
  1460. $pat = strtolower(trim($a));
  1461. if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
  1462. $found = true;
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. return $found;
  1468. }}
  1469. // Format the like/dislike text for a profile item
  1470. // $cnt = number of people who like/dislike the item
  1471. // $arr = array of pre-linked names of likers/dislikers
  1472. // $type = one of 'like, 'dislike'
  1473. // $id = item id
  1474. // returns formatted text
  1475. if(! function_exists('format_like')) {
  1476. function format_like($cnt,$arr,$type,$id) {
  1477. $o = '';
  1478. if($cnt == 1)
  1479. $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
  1480. else {
  1481. $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
  1482. $o .= (($type === 'like') ?
  1483. sprintf( t('<span %1$s>%2$d people</span> like this.'), $spanatts, $cnt)
  1484. :
  1485. sprintf( t('<span %1$s>%2$d people</span> don\'t like this.'), $spanatts, $cnt) );
  1486. $o .= EOL ;
  1487. $total = count($arr);
  1488. if($total >= MAX_LIKERS)
  1489. $arr = array_slice($arr, 0, MAX_LIKERS - 1);
  1490. if($total < MAX_LIKERS)
  1491. $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
  1492. $str = implode(', ', $arr);
  1493. if($total >= MAX_LIKERS)
  1494. $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
  1495. $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
  1496. $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
  1497. }
  1498. return $o;
  1499. }}
  1500. // wrapper to load a view template, checking for alternate
  1501. // languages before falling back to the default
  1502. if(! function_exists('load_view_file')) {
  1503. function load_view_file($s) {
  1504. global $lang;
  1505. if(! isset($lang))
  1506. $lang = 'en';
  1507. $b = basename($s);
  1508. $d = dirname($s);
  1509. if(file_exists("$d/$lang/$b"))
  1510. return file_get_contents("$d/$lang/$b");
  1511. return file_get_contents($s);
  1512. }}
  1513. // for html,xml parsing - let's say you've got
  1514. // an attribute foobar="class1 class2 class3"
  1515. // and you want to find out if it contains 'class3'.
  1516. // you can't use a normal sub string search because you
  1517. // might match 'notclass3' and a regex to do the job is
  1518. // possible but a bit complicated.
  1519. // pass the attribute string as $attr and the attribute you
  1520. // are looking for as $s - returns true if found, otherwise false
  1521. if(! function_exists('attribute_contains')) {
  1522. function attribute_contains($attr,$s) {
  1523. $a = explode(' ', $attr);
  1524. if(count($a) && in_array($s,$a))
  1525. return true;
  1526. return false;
  1527. }}
  1528. if(! function_exists('logger')) {
  1529. function logger($msg,$level = 0) {
  1530. $debugging = get_config('system','debugging');
  1531. $loglevel = intval(get_config('system','loglevel'));
  1532. $logfile = get_config('system','logfile');
  1533. if((! $debugging) || (! $logfile) || ($level > $loglevel))
  1534. return;
  1535. @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
  1536. return;
  1537. }}
  1538. if(! function_exists('activity_match')) {
  1539. function activity_match($haystack,$needle) {
  1540. if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
  1541. return true;
  1542. return false;
  1543. }}
  1544. // Pull out all #hashtags and @person tags from $s;
  1545. // We also get @person@domain.com - which would make
  1546. // the regex quite complicated as tags can also
  1547. // end a sentence. So we'll run through our results
  1548. // and strip the period from any tags which end with one.
  1549. // Returns array of tags found, or empty array.
  1550. if(! function_exists('get_tags')) {
  1551. function get_tags($s) {
  1552. $ret = array();
  1553. // ignore anything in a code block
  1554. $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
  1555. if(preg_match_all('/([@#][^ \x0D\x0A,:?]+)([ \x0D\x0A,:?]|$)/',$s,$match)) {
  1556. foreach($match[1] as $match) {
  1557. if(strstr($match,"]")) {
  1558. // we might be inside a bbcode color tag - leave it alone
  1559. continue;
  1560. }
  1561. if(substr($match,-1,1) === '.')
  1562. $ret[] = substr($match,0,-1);
  1563. else
  1564. $ret[] = $match;
  1565. }
  1566. }
  1567. return $ret;
  1568. }}
  1569. // quick and dirty quoted_printable encoding
  1570. if(! function_exists('qp')) {
  1571. function qp($s) {
  1572. return str_replace ("%","=",rawurlencode($s));
  1573. }}
  1574. if(! function_exists('like_puller')) {
  1575. function like_puller($a,$item,&$arr,$mode) {
  1576. $url = '';
  1577. $sparkle = '';
  1578. $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
  1579. if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
  1580. $url = $item['author-link'];
  1581. if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
  1582. $url = $a->get_baseurl() . '/redir/' . $item['contact-id'];
  1583. $sparkle = ' class="sparkle" ';
  1584. }
  1585. if(! ((isset($arr[$item['parent'] . '-l'])) && (is_array($arr[$item['parent'] . '-l']))))
  1586. $arr[$item['parent'] . '-l'] = array();
  1587. if(! isset($arr[$item['parent']]))
  1588. $arr[$item['parent']] = 1;
  1589. else
  1590. $arr[$item['parent']] ++;
  1591. $arr[$item['parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
  1592. }
  1593. return;
  1594. }}
  1595. if(! function_exists('get_mentions')) {
  1596. function get_mentions($item) {
  1597. $o = '';
  1598. if(! strlen($item['tag']))
  1599. return $o;
  1600. $arr = explode(',',$item['tag']);
  1601. foreach($arr as $x) {
  1602. $matches = null;
  1603. if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
  1604. $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
  1605. $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
  1606. }
  1607. }
  1608. return $o;
  1609. }}
  1610. if(! function_exists('contact_block')) {
  1611. function contact_block() {
  1612. $o = '';
  1613. $a = get_app();
  1614. $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
  1615. if(! $shown)
  1616. $shown = 24;
  1617. if((! is_array($a->profile)) || ($a->profile['hide-friends']))
  1618. return $o;
  1619. $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0",
  1620. intval($a->profile['uid'])
  1621. );
  1622. if(count($r)) {
  1623. $total = intval($r[0]['total']);
  1624. }
  1625. if(! $total) {
  1626. $o .= '<h4 class="contact-h4">' . t('No contacts') . '</h4>';
  1627. return $o;
  1628. }
  1629. $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 ORDER BY RAND() LIMIT %d",
  1630. intval($a->profile['uid']),
  1631. intval($shown)
  1632. );
  1633. if(count($r)) {
  1634. $o .= '<h4 class="contact-h4">' . sprintf( tt('%d Contact','%d Contacts', $total),$total) . '</h4><div id="contact-block">';
  1635. foreach($r as $rr) {
  1636. $redirect_url = $a->get_baseurl() . '/redir/' . $rr['id'];
  1637. if(local_user() && ($rr['uid'] == local_user())
  1638. && ($rr['network'] === 'dfrn')) {
  1639. $url = $redirect_url;
  1640. $sparkle = ' sparkle';
  1641. }
  1642. else {
  1643. $url = $rr['url'];
  1644. $sparkle = '';
  1645. }
  1646. $o .= '<div class="contact-block-div"><a class="contact-block-link' . $sparkle . '" href="' . $url . '" ><img class="contact-block-img' . $sparkle . '" src="' . $rr['micro'] . '" title="' . $rr['name'] . ' [' . $rr['url'] . ']" alt="' . $rr['name'] . '" /></a></div>' . "\r\n";
  1647. }
  1648. $o .= '</div><div id="contact-block-end"></div>';
  1649. $o .= '<div id="viewcontacts"><a id="viewcontacts-link" href="viewcontacts/' . $a->profile['nickname'] . '">' . t('View Contacts') . '</a></div>';
  1650. }
  1651. $arr = array('contacts' => $r, 'output' => $o);
  1652. call_hooks('contact_block_end', $arr);
  1653. return $o;
  1654. }}
  1655. if(! function_exists('search')) {
  1656. function search($s) {
  1657. $a = get_app();
  1658. $o = '<div id="search-box">';
  1659. $o .= '<form action="' . $a->get_baseurl() . '/search' . '" method="get" >';
  1660. $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
  1661. $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
  1662. $o .= '</form></div>';
  1663. return $o;
  1664. }}
  1665. if(! function_exists('valid_email')) {
  1666. function valid_email($x){
  1667. if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
  1668. return true;
  1669. return false;
  1670. }}
  1671. if(! function_exists('gravatar_img')) {
  1672. function gravatar_img($email) {
  1673. $size = 175;
  1674. $opt = 'identicon'; // psuedo-random geometric pattern if not found
  1675. $rating = 'pg';
  1676. $hash = md5(trim(strtolower($email)));
  1677. $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
  1678. . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
  1679. logger('gravatar: ' . $email . ' ' . $url);
  1680. return $url;
  1681. }}
  1682. if(! function_exists('aes_decrypt')) {
  1683. function aes_decrypt($val,$ky)
  1684. {
  1685. $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  1686. for($a=0;$a<strlen($ky);$a++)
  1687. $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
  1688. $mode = MCRYPT_MODE_ECB;
  1689. $enc = MCRYPT_RIJNDAEL_128;
  1690. $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
  1691. return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
  1692. }}
  1693. if(! function_exists('aes_encrypt')) {
  1694. function aes_encrypt($val,$ky)
  1695. {
  1696. $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  1697. for($a=0;$a<strlen($ky);$a++)
  1698. $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
  1699. $mode=MCRYPT_MODE_ECB;
  1700. $enc=MCRYPT_RIJNDAEL_128;
  1701. $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
  1702. return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
  1703. }}
  1704. /**
  1705. *
  1706. * Function: linkify
  1707. *
  1708. * Replace naked text hyperlink with HTML formatted hyperlink
  1709. *
  1710. */
  1711. if(! function_exists('linkify')) {
  1712. function linkify($s) {
  1713. $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
  1714. return($s);
  1715. }}
  1716. /**
  1717. *
  1718. * Function: smilies
  1719. *
  1720. * Description:
  1721. * Replaces text emoticons with graphical images
  1722. *
  1723. * @Parameter: string $s
  1724. *
  1725. * Returns string
  1726. */
  1727. if(! function_exists('smilies')) {
  1728. function smilies($s) {
  1729. $a = get_app();
  1730. return str_replace(
  1731. array( '&lt;3', '&lt;/3', '&lt;\\3', ':-)', ';-)', ':-(', ':(', ':-P', ':-"', ':-x', ':-X', ':-D', '8-|', '8-O'),
  1732. array(
  1733. '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
  1734. '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
  1735. '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
  1736. '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
  1737. '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
  1738. '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
  1739. '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
  1740. '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
  1741. '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
  1742. '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
  1743. '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
  1744. '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
  1745. '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
  1746. '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />'
  1747. ), $s);
  1748. }}
  1749. /**
  1750. *
  1751. * Function : profile_load
  1752. * @parameter App $a
  1753. * @parameter string $nickname
  1754. * @parameter int $profile
  1755. *
  1756. * Summary: Loads a profile into the page sidebar.
  1757. * The function requires a writeable copy of the main App structure, and the nickname
  1758. * of a registered local account.
  1759. *
  1760. * If the viewer is an authenticated remote viewer, the profile displayed is the
  1761. * one that has been configured for his/her viewing in the Contact manager.
  1762. * Passing a non-zero profile ID can also allow a preview of a selected profile
  1763. * by the owner.
  1764. *
  1765. * Profile information is placed in the App structure for later retrieval.
  1766. * Honours the owner's chosen theme for display.
  1767. *
  1768. */
  1769. if(! function_exists('profile_load')) {
  1770. function profile_load(&$a, $nickname, $profile = 0) {
  1771. if(remote_user()) {
  1772. $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
  1773. intval($_SESSION['visitor_id']));
  1774. if(count($r))
  1775. $profile = $r[0]['profile-id'];
  1776. }
  1777. $r = null;
  1778. if($profile) {
  1779. $profile_int = intval($profile);
  1780. $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
  1781. LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
  1782. WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d LIMIT 1",
  1783. dbesc($nickname),
  1784. intval($profile_int)
  1785. );
  1786. }
  1787. if(! count($r)) {
  1788. $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
  1789. LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
  1790. WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 LIMIT 1",
  1791. dbesc($nickname)
  1792. );
  1793. }
  1794. if(($r === false) || (! count($r))) {
  1795. notice( t('No profile') . EOL );
  1796. $a->error = 404;
  1797. return;
  1798. }
  1799. $a->profile = $r[0];
  1800. $a->page['title'] = $a->profile