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.

2763 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
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
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
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
  1. <?php
  2. set_time_limit(0);
  3. define ( 'FRIENDIKA_VERSION', '2.1.939' );
  4. define ( 'DFRN_PROTOCOL_VERSION', '2.2' );
  5. define ( 'DB_UPDATE_VERSION', 1046 );
  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. if(! x($_SERVER,'SERVER_NAME'))
  350. return;
  351. $build = get_config('system','build');
  352. if(! x($build))
  353. $build = set_config('system','build',DB_UPDATE_VERSION);
  354. $url = get_config('system','url');
  355. if(! x($url))
  356. $url = set_config('system','url',$a->get_baseurl());
  357. if($build != DB_UPDATE_VERSION) {
  358. $stored = intval($build);
  359. $current = intval(DB_UPDATE_VERSION);
  360. if(($stored < $current) && file_exists('update.php')) {
  361. // We're reporting a different version than what is currently installed.
  362. // Run any existing update scripts to bring the database up to current.
  363. require_once('update.php');
  364. for($x = $stored; $x < $current; $x ++) {
  365. if(function_exists('update_' . $x)) {
  366. $func = 'update_' . $x;
  367. $func($a);
  368. }
  369. }
  370. set_config('system','build', DB_UPDATE_VERSION);
  371. }
  372. }
  373. /**
  374. *
  375. * Synchronise plugins:
  376. *
  377. * $a->config['system']['addon'] contains a comma-separated list of names
  378. * of plugins/addons which are used on this system.
  379. * Go through the database list of already installed addons, and if we have
  380. * an entry, but it isn't in the config list, call the uninstall procedure
  381. * and mark it uninstalled in the database (for now we'll remove it).
  382. * Then go through the config list and if we have a plugin that isn't installed,
  383. * call the install procedure and add it to the database.
  384. *
  385. */
  386. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  387. if(count($r))
  388. $installed = $r;
  389. else
  390. $installed = array();
  391. $plugins = get_config('system','addon');
  392. $plugins_arr = array();
  393. if($plugins)
  394. $plugins_arr = explode(',',str_replace(' ', '',$plugins));
  395. $a->plugins = $plugins_arr;
  396. $installed_arr = array();
  397. if(count($installed)) {
  398. foreach($installed as $i) {
  399. if(! in_array($i['name'],$plugins_arr)) {
  400. logger("Addons: uninstalling " . $i['name']);
  401. q("DELETE FROM `addon` WHERE `id` = %d LIMIT 1",
  402. intval($i['id'])
  403. );
  404. @include_once('addon/' . $i['name'] . '/' . $i['name'] . '.php');
  405. if(function_exists($i['name'] . '_uninstall')) {
  406. $func = $i['name'] . '_uninstall';
  407. $func();
  408. }
  409. }
  410. else
  411. $installed_arr[] = $i['name'];
  412. }
  413. }
  414. if(count($plugins_arr)) {
  415. foreach($plugins_arr as $p) {
  416. if(! in_array($p,$installed_arr)) {
  417. logger("Addons: installing " . $p);
  418. $t = filemtime('addon/' . $p . '/' . $p . '.php');
  419. @include_once('addon/' . $p . '/' . $p . '.php');
  420. if(function_exists($p . '_install')) {
  421. $func = $p . '_install';
  422. $func();
  423. $r = q("INSERT INTO `addon` (`name`, `installed`, `timestamp`) VALUES ( '%s', 1, %d ) ",
  424. dbesc($p),
  425. intval($t)
  426. );
  427. }
  428. }
  429. }
  430. }
  431. load_hooks();
  432. return;
  433. }}
  434. // reload all updated plugins
  435. if(! function_exists('reload_plugins')) {
  436. function reload_plugins() {
  437. $plugins = get_config('system','addon');
  438. if(strlen($plugins)) {
  439. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  440. if(count($r))
  441. $installed = $r;
  442. else
  443. $installed = array();
  444. $parr = explode(',',$plugins);
  445. if(count($parr)) {
  446. foreach($parr as $pl) {
  447. $pl = trim($pl);
  448. $t = filemtime('addon/' . $pl . '/' . $pl . '.php');
  449. foreach($installed as $i) {
  450. if(($i['name'] == $pl) && ($i['timestamp'] != $t)) {
  451. logger('Reloading plugin: ' . $i['name']);
  452. @include_once('addon/' . $pl . '/' . $pl . '.php');
  453. if(function_exists($pl . '_uninstall')) {
  454. $func = $pl . '_uninstall';
  455. $func();
  456. }
  457. if(function_exists($pl . '_install')) {
  458. $func = $pl . '_install';
  459. $func();
  460. }
  461. q("UPDATE `addon` SET `timestamp` = %d WHERE `id` = %d LIMIT 1",
  462. intval($t),
  463. intval($i['id'])
  464. );
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }}
  471. // This is our template processor.
  472. // $s is the string requiring macro substitution.
  473. // $r is an array of key value pairs (search => replace)
  474. // returns substituted string.
  475. // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
  476. // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
  477. // depending on the order in which they were declared in the array.
  478. if(! function_exists('replace_macros')) {
  479. function replace_macros($s,$r) {
  480. $search = array();
  481. $replace = array();
  482. if(is_array($r) && count($r)) {
  483. foreach ($r as $k => $v ) {
  484. $search[] = $k;
  485. $replace[] = $v;
  486. }
  487. }
  488. return str_replace($search,$replace,$s);
  489. }}
  490. // curl wrapper. If binary flag is true, return binary
  491. // results.
  492. if(! function_exists('fetch_url')) {
  493. function fetch_url($url,$binary = false, &$redirects = 0) {
  494. $a = get_app();
  495. $ch = curl_init($url);
  496. if(($redirects > 8) || (! $ch))
  497. return false;
  498. curl_setopt($ch, CURLOPT_HEADER, true);
  499. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  500. $curl_time = intval(get_config('system','curl_timeout'));
  501. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  502. // by default we will allow self-signed certs
  503. // but you can override this
  504. $check_cert = get_config('system','verifyssl');
  505. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  506. $prx = get_config('system','proxy');
  507. if(strlen($prx)) {
  508. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  509. curl_setopt($ch, CURLOPT_PROXY, $prx);
  510. $prxusr = get_config('system','proxyuser');
  511. if(strlen($prxusr))
  512. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  513. }
  514. if($binary)
  515. curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  516. $a->set_curl_code(0);
  517. // don't let curl abort the entire application
  518. // if it throws any errors.
  519. $s = @curl_exec($ch);
  520. $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  521. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  522. if(stristr($header,'100') && (strlen($header) < 30)) {
  523. // 100 Continue has two headers, get the real one
  524. $s = substr($s,strlen($header)+4);
  525. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  526. }
  527. if($http_code == 301 || $http_code == 302 || $http_code == 303) {
  528. $matches = array();
  529. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  530. $url = trim(array_pop($matches));
  531. $url_parsed = @parse_url($url);
  532. if (isset($url_parsed)) {
  533. $redirects++;
  534. return fetch_url($url,$binary,$redirects);
  535. }
  536. }
  537. $a->set_curl_code($http_code);
  538. $body = substr($s,strlen($header)+4);
  539. /* one more try to make sure there are no more headers */
  540. if(strpos($body,'HTTP/') === 0) {
  541. $header = substr($body,0,strpos($body,"\r\n\r\n"));
  542. $body = substr($body,strlen($header)+4);
  543. }
  544. $a->set_curl_headers($header);
  545. curl_close($ch);
  546. return($body);
  547. }}
  548. // post request to $url. $params is an array of post variables.
  549. if(! function_exists('post_url')) {
  550. function post_url($url,$params, $headers = null, &$redirects = 0) {
  551. $a = get_app();
  552. $ch = curl_init($url);
  553. if(($redirects > 8) || (! $ch))
  554. return false;
  555. curl_setopt($ch, CURLOPT_HEADER, true);
  556. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  557. curl_setopt($ch, CURLOPT_POST,1);
  558. curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
  559. $curl_time = intval(get_config('system','curl_timeout'));
  560. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  561. if(is_array($headers))
  562. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  563. $check_cert = get_config('system','verifyssl');
  564. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  565. $prx = get_config('system','proxy');
  566. if(strlen($prx)) {
  567. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  568. curl_setopt($ch, CURLOPT_PROXY, $prx);
  569. $prxusr = get_config('system','proxyuser');
  570. if(strlen($prxusr))
  571. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  572. }
  573. $a->set_curl_code(0);
  574. // don't let curl abort the entire application
  575. // if it throws any errors.
  576. $s = @curl_exec($ch);
  577. $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  578. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  579. if(stristr($header,'100') && (strlen($header) < 30)) {
  580. // 100 Continue has two headers, get the real one
  581. $s = substr($s,strlen($header)+4);
  582. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  583. }
  584. if($http_code == 301 || $http_code == 302 || $http_code == 303) {
  585. $matches = array();
  586. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  587. $url = trim(array_pop($matches));
  588. $url_parsed = @parse_url($url);
  589. if (isset($url_parsed)) {
  590. $redirects++;
  591. return post_url($url,$binary,$headers,$redirects);
  592. }
  593. }
  594. $a->set_curl_code($http_code);
  595. $body = substr($s,strlen($header)+4);
  596. /* one more try to make sure there are no more headers */
  597. if(strpos($body,'HTTP/') === 0) {
  598. $header = substr($body,0,strpos($body,"\r\n\r\n"));
  599. $body = substr($body,strlen($header)+4);
  600. }
  601. $a->set_curl_headers($header);
  602. curl_close($ch);
  603. return($body);
  604. }}
  605. // random hash, 64 chars
  606. if(! function_exists('random_string')) {
  607. function random_string() {
  608. return(hash('sha256',uniqid(rand(),true)));
  609. }}
  610. /**
  611. * This is our primary input filter.
  612. *
  613. * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
  614. * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
  615. * after cleansing, and angle chars with the high bit set could get through as markup.
  616. *
  617. * This is now disabled because it was interfering with some legitimate unicode sequences
  618. * and hopefully there aren't a lot of those browsers left.
  619. *
  620. * Use this on any text input where angle chars are not valid or permitted
  621. * They will be replaced with safer brackets. This may be filtered further
  622. * if these are not allowed either.
  623. *
  624. */
  625. if(! function_exists('notags')) {
  626. function notags($string) {
  627. return(str_replace(array("<",">"), array('[',']'), $string));
  628. // High-bit filter no longer used
  629. // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
  630. }}
  631. // use this on "body" or "content" input where angle chars shouldn't be removed,
  632. // and allow them to be safely displayed.
  633. if(! function_exists('escape_tags')) {
  634. function escape_tags($string) {
  635. return(htmlspecialchars($string));
  636. }}
  637. // wrapper for adding a login box. If $register == true provide a registration
  638. // link. This will most always depend on the value of $a->config['register_policy'].
  639. // returns the complete html for inserting into the page
  640. if(! function_exists('login')) {
  641. function login($register = false) {
  642. $o = "";
  643. $register_tpl = (($register) ? load_view_file("view/register-link.tpl") : "");
  644. $register_html = replace_macros($register_tpl,array(
  645. '$title' => t('Create a New Account'),
  646. '$desc' => t('Register')
  647. ));
  648. $noid = get_config('system','no_openid');
  649. if($noid) {
  650. $classname = 'no-openid';
  651. $namelabel = t('Nickname or Email address: ');
  652. $passlabel = t('Password: ');
  653. $login = t('Login');
  654. }
  655. else {
  656. $classname = 'openid';
  657. $namelabel = t('Nickname/Email/OpenID: ');
  658. $passlabel = t("Password \x28if not OpenID\x29: ");
  659. $login = t('Login');
  660. }
  661. $lostpass = t('Forgot your password?');
  662. $lostlink = t('Password Reset');
  663. if(local_user()) {
  664. $tpl = load_view_file("view/logout.tpl");
  665. }
  666. else {
  667. $tpl = load_view_file("view/login.tpl");
  668. }
  669. $o = replace_macros($tpl,array(
  670. '$logout' => t('Logout'),
  671. '$register_html' => $register_html,
  672. '$classname' => $classname,
  673. '$namelabel' => $namelabel,
  674. '$passlabel' => $passlabel,
  675. '$login' => $login,
  676. '$lostpass' => $lostpass,
  677. '$lostlink' => $lostlink
  678. ));
  679. return $o;
  680. }}
  681. // generate a string that's random, but usually pronounceable.
  682. // used to generate initial passwords
  683. if(! function_exists('autoname')) {
  684. function autoname($len) {
  685. $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
  686. if(mt_rand(0,5) == 4)
  687. $vowels[] = 'y';
  688. $cons = array(
  689. 'b','bl','br',
  690. 'c','ch','cl','cr',
  691. 'd','dr',
  692. 'f','fl','fr',
  693. 'g','gh','gl','gr',
  694. 'h',
  695. 'j',
  696. 'k','kh','kl','kr',
  697. 'l',
  698. 'm',
  699. 'n',
  700. 'p','ph','pl','pr',
  701. 'qu',
  702. 'r','rh',
  703. 's','sc','sh','sm','sp','st',
  704. 't','th','tr',
  705. 'v',
  706. 'w','wh',
  707. 'x',
  708. 'z','zh'
  709. );
  710. $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
  711. 'nd','ng','nk','nt','rn','rp','rt');
  712. $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
  713. 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
  714. $start = mt_rand(0,2);
  715. if($start == 0)
  716. $table = $vowels;
  717. else
  718. $table = $cons;
  719. $word = '';
  720. for ($x = 0; $x < $len; $x ++) {
  721. $r = mt_rand(0,count($table) - 1);
  722. $word .= $table[$r];
  723. if($table == $vowels)
  724. $table = array_merge($cons,$midcons);
  725. else
  726. $table = $vowels;
  727. }
  728. $word = substr($word,0,$len);
  729. foreach($noend as $noe) {
  730. if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
  731. $word = substr($word,0,-1);
  732. break;
  733. }
  734. }
  735. if(substr($word,-1) == 'q')
  736. $word = substr($word,0,-1);
  737. return $word;
  738. }}
  739. // Used to end the current process, after saving session state.
  740. if(! function_exists('killme')) {
  741. function killme() {
  742. session_write_close();
  743. exit;
  744. }}
  745. // redirect to another URL and terminate this process.
  746. if(! function_exists('goaway')) {
  747. function goaway($s) {
  748. header("Location: $s");
  749. killme();
  750. }}
  751. // Generic XML return
  752. // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
  753. // of $st and an optional text <message> of $message and terminates the current process.
  754. if(! function_exists('xml_status')) {
  755. function xml_status($st, $message = '') {
  756. $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
  757. if($st)
  758. logger('xml_status returning non_zero: ' . $st . " message=" . $message);
  759. header( "Content-type: text/xml" );
  760. echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
  761. echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
  762. killme();
  763. }}
  764. // Returns the uid of locally logged in user or false.
  765. if(! function_exists('local_user')) {
  766. function local_user() {
  767. if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
  768. return intval($_SESSION['uid']);
  769. return false;
  770. }}
  771. // Returns contact id of authenticated site visitor or false
  772. if(! function_exists('remote_user')) {
  773. function remote_user() {
  774. if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
  775. return intval($_SESSION['visitor_id']);
  776. return false;
  777. }}
  778. // contents of $s are displayed prominently on the page the next time
  779. // a page is loaded. Usually used for errors or alerts.
  780. if(! function_exists('notice')) {
  781. function notice($s) {
  782. $a = get_app();
  783. if($a->interactive)
  784. $_SESSION['sysmsg'] .= $s;
  785. }}
  786. // wrapper around config to limit the text length of an incoming message
  787. if(! function_exists('get_max_import_size')) {
  788. function get_max_import_size() {
  789. global $a;
  790. return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
  791. }}
  792. // escape text ($str) for XML transport
  793. // returns escaped text.
  794. if(! function_exists('xmlify')) {
  795. function xmlify($str) {
  796. $buffer = '';
  797. for($x = 0; $x < strlen($str); $x ++) {
  798. $char = $str[$x];
  799. switch( $char ) {
  800. case "\r" :
  801. break;
  802. case "&" :
  803. $buffer .= '&amp;';
  804. break;
  805. case "'" :
  806. $buffer .= '&apos;';
  807. break;
  808. case "\"" :
  809. $buffer .= '&quot;';
  810. break;
  811. case '<' :
  812. $buffer .= '&lt;';
  813. break;
  814. case '>' :
  815. $buffer .= '&gt;';
  816. break;
  817. case "\n" :
  818. $buffer .= "\n";
  819. break;
  820. default :
  821. $buffer .= $char;
  822. break;
  823. }
  824. }
  825. $buffer = trim($buffer);
  826. return($buffer);
  827. }}
  828. // undo an xmlify
  829. // pass xml escaped text ($s), returns unescaped text
  830. if(! function_exists('unxmlify')) {
  831. function unxmlify($s) {
  832. $ret = str_replace('&amp;','&', $s);
  833. $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
  834. return $ret;
  835. }}
  836. // convenience wrapper, reverse the operation "bin2hex"
  837. if(! function_exists('hex2bin')) {
  838. function hex2bin($s) {
  839. if(! ctype_xdigit($s)) {
  840. logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
  841. return($s);
  842. }
  843. return(pack("H*",$s));
  844. }}
  845. // Automatic pagination.
  846. // To use, get the count of total items.
  847. // Then call $a->set_pager_total($number_items);
  848. // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
  849. // Then call paginate($a) after the end of the display loop to insert the pager block on the page
  850. // (assuming there are enough items to paginate).
  851. // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
  852. // will limit the results to the correct items for the current page.
  853. // The actual page handling is then accomplished at the application layer.
  854. if(! function_exists('paginate')) {
  855. function paginate(&$a) {
  856. $o = '';
  857. $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
  858. $stripped = str_replace('q=','',$stripped);
  859. $stripped = trim($stripped,'/');
  860. $pagenum = $a->pager['page'];
  861. $url = $a->get_baseurl() . '/' . $stripped;
  862. if($a->pager['total'] > $a->pager['itemspage']) {
  863. $o .= '<div class="pager">';
  864. if($a->pager['page'] != 1)
  865. $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
  866. $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
  867. $numpages = $a->pager['total'] / $a->pager['itemspage'];
  868. $numstart = 1;
  869. $numstop = $numpages;
  870. if($numpages > 14) {
  871. $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
  872. $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
  873. }
  874. for($i = $numstart; $i <= $numstop; $i++){
  875. if($i == $a->pager['page'])
  876. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  877. else
  878. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  879. $o .= '</span> ';
  880. }
  881. if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
  882. if($i == $a->pager['page'])
  883. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  884. else
  885. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  886. $o .= '</span> ';
  887. }
  888. $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
  889. $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
  890. if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
  891. $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
  892. $o .= '</div>'."\r\n";
  893. }
  894. return $o;
  895. }}
  896. // Turn user/group ACLs stored as angle bracketed text into arrays
  897. if(! function_exists('expand_acl')) {
  898. function expand_acl($s) {
  899. // turn string array of angle-bracketed elements into numeric array
  900. // e.g. "<1><2><3>" => array(1,2,3);
  901. $ret = array();
  902. if(strlen($s)) {
  903. $t = str_replace('<','',$s);
  904. $a = explode('>',$t);
  905. foreach($a as $aa) {
  906. if(intval($aa))
  907. $ret[] = intval($aa);
  908. }
  909. }
  910. return $ret;
  911. }}
  912. // Used to wrap ACL elements in angle brackets for storage
  913. if(! function_exists('sanitise_acl')) {
  914. function sanitise_acl(&$item) {
  915. if(intval($item))
  916. $item = '<' . intval(notags(trim($item))) . '>';
  917. else
  918. unset($item);
  919. }}
  920. // retrieve a "family" of config variables from database to cached storage
  921. if(! function_exists('load_config')) {
  922. function load_config($family) {
  923. global $a;
  924. $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
  925. dbesc($family)
  926. );
  927. if(count($r)) {
  928. foreach($r as $rr) {
  929. $k = $rr['k'];
  930. $a->config[$family][$k] = $rr['v'];
  931. }
  932. }
  933. }}
  934. // get a particular config variable given the family name
  935. // and key. Returns false if not set.
  936. // $instore is only used by the set_config function
  937. // to determine if the key already exists in the DB
  938. // If a key is found in the DB but doesn't exist in
  939. // local config cache, pull it into the cache so we don't have
  940. // to hit the DB again for this item.
  941. if(! function_exists('get_config')) {
  942. function get_config($family, $key, $instore = false) {
  943. global $a;
  944. if(! $instore) {
  945. if(isset($a->config[$family][$key])) {
  946. if($a->config[$family][$key] === '!<unset>!') {
  947. return false;
  948. }
  949. return $a->config[$family][$key];
  950. }
  951. }
  952. $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  953. dbesc($family),
  954. dbesc($key)
  955. );
  956. if(count($ret)) {
  957. $a->config[$family][$key] = $ret[0]['v'];
  958. return $ret[0]['v'];
  959. }
  960. else {
  961. $a->config[$family][$key] = '!<unset>!';
  962. }
  963. return false;
  964. }}
  965. // Store a config value ($value) in the category ($family)
  966. // under the key ($key)
  967. // Return the value, or false if the database update failed
  968. if(! function_exists('set_config')) {
  969. function set_config($family,$key,$value) {
  970. global $a;
  971. if(get_config($family,$key,true) === false) {
  972. $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
  973. dbesc($family),
  974. dbesc($key),
  975. dbesc($value)
  976. );
  977. if($ret)
  978. return $value;
  979. return $ret;
  980. }
  981. $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  982. dbesc($value),
  983. dbesc($family),
  984. dbesc($key)
  985. );
  986. $a->config[$family][$key] = $value;
  987. if($ret)
  988. return $value;
  989. return $ret;
  990. }}
  991. if(! function_exists('load_pconfig')) {
  992. function load_pconfig($uid,$family) {
  993. global $a;
  994. $r = q("SELECT * FROM `pconfig` WHERE `cat` = '%s' AND `uid` = %d",
  995. dbesc($family),
  996. intval($uid)
  997. );
  998. if(count($r)) {
  999. foreach($r as $rr) {
  1000. $k = $rr['k'];
  1001. $a->config[$uid][$family][$k] = $rr['v'];
  1002. }
  1003. }
  1004. }}
  1005. if(! function_exists('get_pconfig')) {
  1006. function get_pconfig($uid,$family, $key, $instore = false) {
  1007. global $a;
  1008. if(! $instore) {
  1009. if(isset($a->config[$uid][$family][$key])) {
  1010. if($a->config[$uid][$family][$key] === '!<unset>!') {
  1011. return false;
  1012. }
  1013. return $a->config[$uid][$family][$key];
  1014. }
  1015. }
  1016. $ret = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1017. intval($uid),
  1018. dbesc($family),
  1019. dbesc($key)
  1020. );
  1021. if(count($ret)) {
  1022. $a->config[$uid][$family][$key] = $ret[0]['v'];
  1023. return $ret[0]['v'];
  1024. }
  1025. else {
  1026. $a->config[$uid][$family][$key] = '!<unset>!';
  1027. }
  1028. return false;
  1029. }}
  1030. if(! function_exists('del_config')) {
  1031. function del_config($family,$key) {
  1032. global $a;
  1033. if(x($a->config[$family],$key))
  1034. unset($a->config[$family][$key]);
  1035. $ret = q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1036. dbesc($cat),
  1037. dbesc($key)
  1038. );
  1039. return $ret;
  1040. }}
  1041. // Same as above functions except these are for personal config storage and take an
  1042. // additional $uid argument.
  1043. if(! function_exists('set_pconfig')) {
  1044. function set_pconfig($uid,$family,$key,$value) {
  1045. global $a;
  1046. if(get_pconfig($uid,$family,$key,true) === false) {
  1047. $ret = q("INSERT INTO `pconfig` ( `uid`, `cat`, `k`, `v` ) VALUES ( %d, '%s', '%s', '%s' ) ",
  1048. intval($uid),
  1049. dbesc($family),
  1050. dbesc($key),
  1051. dbesc($value)
  1052. );
  1053. if($ret)
  1054. return $value;
  1055. return $ret;
  1056. }
  1057. $ret = q("UPDATE `pconfig` SET `v` = '%s' WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1058. dbesc($value),
  1059. intval($uid),
  1060. dbesc($family),
  1061. dbesc($key)
  1062. );
  1063. $a->config[$uid][$family][$key] = $value;
  1064. if($ret)
  1065. return $value;
  1066. return $ret;
  1067. }}
  1068. if(! function_exists('del_pconfig')) {
  1069. function del_pconfig($uid,$family,$key) {
  1070. global $a;
  1071. if(x($a->config[$uid][$family],$key))
  1072. unset($a->config[$uid][$family][$key]);
  1073. $ret = q("DELETE FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1074. intval($uid),
  1075. dbesc($family),
  1076. dbesc($key)
  1077. );
  1078. return $ret;
  1079. }}
  1080. // convert an XML document to a normalised, case-corrected array
  1081. // used by webfinger
  1082. if(! function_exists('convert_xml_element_to_array')) {
  1083. function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
  1084. // If we're getting too deep, bail out
  1085. if ($recursion_depth > 512) {
  1086. return(null);
  1087. }
  1088. if (!is_string($xml_element) &&
  1089. !is_array($xml_element) &&
  1090. (get_class($xml_element) == 'SimpleXMLElement')) {
  1091. $xml_element_copy = $xml_element;
  1092. $xml_element = get_object_vars($xml_element);
  1093. }
  1094. if (is_array($xml_element)) {
  1095. $result_array = array();
  1096. if (count($xml_element) <= 0) {
  1097. return (trim(strval($xml_element_copy)));
  1098. }
  1099. foreach($xml_element as $key=>$value) {
  1100. $recursion_depth++;
  1101. $result_array[strtolower($key)] =
  1102. convert_xml_element_to_array($value, $recursion_depth);
  1103. $recursion_depth--;
  1104. }
  1105. if ($recursion_depth == 0) {
  1106. $temp_array = $result_array;
  1107. $result_array = array(
  1108. strtolower($xml_element_copy->getName()) => $temp_array,
  1109. );
  1110. }
  1111. return ($result_array);
  1112. } else {
  1113. return (trim(strval($xml_element)));
  1114. }
  1115. }}
  1116. // Given an email style address, perform webfinger lookup and
  1117. // return the resulting DFRN profile URL, or if no DFRN profile URL
  1118. // is located, returns an OStatus subscription template (prefixed
  1119. // with the string 'stat:' to identify it as on OStatus template).
  1120. // If this isn't an email style address just return $s.
  1121. // Return an empty string if email-style addresses but webfinger fails,
  1122. // or if the resultant personal XRD doesn't contain a supported
  1123. // subscription/friend-request attribute.
  1124. if(! function_exists('webfinger_dfrn')) {
  1125. function webfinger_dfrn($s) {
  1126. if(! strstr($s,'@')) {
  1127. return $s;
  1128. }
  1129. $links = webfinger($s);
  1130. logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
  1131. if(count($links)) {
  1132. foreach($links as $link)
  1133. if($link['@attributes']['rel'] === NAMESPACE_DFRN)
  1134. return $link['@attributes']['href'];
  1135. foreach($links as $link)
  1136. if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
  1137. return 'stat:' . $link['@attributes']['template'];
  1138. }
  1139. return '';
  1140. }}
  1141. // Given an email style address, perform webfinger lookup and
  1142. // return the array of link attributes from the personal XRD file.
  1143. // On error/failure return an empty array.
  1144. if(! function_exists('webfinger')) {
  1145. function webfinger($s) {
  1146. $host = '';
  1147. if(strstr($s,'@')) {
  1148. $host = substr($s,strpos($s,'@') + 1);
  1149. }
  1150. if(strlen($host)) {
  1151. $tpl = fetch_lrdd_template($host);
  1152. logger('webfinger: lrdd template: ' . $tpl);
  1153. if(strlen($tpl)) {
  1154. $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
  1155. logger('webfinger: pxrd: ' . $pxrd);
  1156. $links = fetch_xrd_links($pxrd);
  1157. if(! count($links)) {
  1158. // try with double slashes
  1159. $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
  1160. logger('webfinger: pxrd: ' . $pxrd);
  1161. $links = fetch_xrd_links($pxrd);
  1162. }
  1163. return $links;
  1164. }
  1165. }
  1166. return array();
  1167. }}
  1168. if(! function_exists('lrdd')) {
  1169. function lrdd($uri) {
  1170. $a = get_app();
  1171. // default priority is host priority, host-meta first
  1172. $priority = 'host';
  1173. // All we have is an email address. Resource-priority is irrelevant
  1174. // because our URI isn't directly resolvable.
  1175. if(strstr($uri,'@')) {
  1176. return(webfinger($uri));
  1177. }
  1178. // get the host meta file
  1179. $host = @parse_url($uri);
  1180. if($host) {
  1181. $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
  1182. $url .= $host['host'] . '/.well-known/host-meta' ;
  1183. }
  1184. else
  1185. return array();
  1186. logger('lrdd: constructed url: ' . $url);
  1187. $xml = fetch_url($url);
  1188. $headers = $a->get_curl_headers();
  1189. if (! $xml)
  1190. return array();
  1191. logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
  1192. $h = simplexml_load_string($xml);
  1193. $arr = convert_xml_element_to_array($h);
  1194. if(isset($arr['xrd']['property'])) {
  1195. $property = $arr['crd']['property'];
  1196. if(! isset($property[0]))
  1197. $properties = array($property);
  1198. else
  1199. $properties = $property;
  1200. foreach($properties as $prop)
  1201. if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
  1202. $priority = 'resource';
  1203. }
  1204. // save the links in case we need them
  1205. $links = array();
  1206. if(isset($arr['xrd']['link'])) {
  1207. $link = $arr['xrd']['link'];
  1208. if(! isset($link[0]))
  1209. $links = array($link);
  1210. else
  1211. $links = $link;
  1212. }
  1213. // do we have a template or href?
  1214. if(count($links)) {
  1215. foreach($links as $link) {
  1216. if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
  1217. if(x($link['@attributes'],'template'))
  1218. $tpl = $link['@attributes']['template'];
  1219. elseif(x($link['@attributes'],'href'))
  1220. $href = $link['@attributes']['href'];
  1221. }
  1222. }
  1223. }
  1224. if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
  1225. $tpl = '';
  1226. if($priority === 'host') {
  1227. if(strlen($tpl))
  1228. $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
  1229. elseif(isset($href))
  1230. $pxrd = $href;
  1231. if(isset($pxrd)) {
  1232. logger('lrdd: (host priority) pxrd: ' . $pxrd);
  1233. $links = fetch_xrd_links($pxrd);
  1234. return $links;
  1235. }
  1236. $lines = explode("\n",$headers);
  1237. if(count($lines)) {
  1238. foreach($lines as $line) {
  1239. if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
  1240. return(fetch_xrd_links($matches[1]));
  1241. break;
  1242. }
  1243. }
  1244. }
  1245. }
  1246. // priority 'resource'
  1247. $html = fetch_url($uri);
  1248. $headers = $a->get_curl_headers();
  1249. logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
  1250. require_once('library/HTML5/Parser.php');
  1251. $dom = @HTML5_Parser::parse($html);
  1252. if($dom) {
  1253. $items = $dom->getElementsByTagName('link');
  1254. foreach($items as $item) {
  1255. $x = $item->getAttribute('rel');
  1256. if($x == "lrdd") {
  1257. $pagelink = $item->getAttribute('href');
  1258. break;
  1259. }
  1260. }
  1261. }
  1262. if(isset($pagelink))
  1263. return(fetch_xrd_links($pagelink));
  1264. // next look in HTTP headers
  1265. $lines = explode("\n",$headers);
  1266. if(count($lines)) {
  1267. foreach($lines as $line) {
  1268. // TODO alter the following regex to support multiple relations (space separated)
  1269. if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
  1270. $pagelink = $matches[1];
  1271. break;
  1272. }
  1273. // don't try and run feeds through the html5 parser
  1274. if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
  1275. return array();
  1276. if(stristr($html,'<rss') || stristr($html,'<feed'))
  1277. return array();
  1278. }
  1279. }
  1280. if(isset($pagelink))
  1281. return(fetch_xrd_links($pagelink));
  1282. // If we haven't found any links, return the host xrd links (which we have already fetched)
  1283. if(isset($links))
  1284. return $links;
  1285. return array();
  1286. }}
  1287. // Given a host name, locate the LRDD template from that
  1288. // host. Returns the LRDD template or an empty string on
  1289. // error/failure.
  1290. if(! function_exists('fetch_lrdd_template')) {
  1291. function fetch_lrdd_template($host) {
  1292. $tpl = '';
  1293. $url1 = 'https://' . $host . '/.well-known/host-meta' ;
  1294. $url2 = 'http://' . $host . '/.well-known/host-meta' ;
  1295. $links = fetch_xrd_links($url1);
  1296. logger('template (https): ' . print_r($links,true));
  1297. if(! count($links)) {
  1298. $links = fetch_xrd_links($url2);
  1299. logger('template (http): ' . print_r($links,true));
  1300. }
  1301. if(count($links)) {
  1302. foreach($links as $link)
  1303. if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
  1304. $tpl = $link['@attributes']['template'];
  1305. }
  1306. if(! strpos($tpl,'{uri}'))
  1307. $tpl = '';
  1308. return $tpl;
  1309. }}
  1310. // Given a URL, retrieve the page as an XRD document.
  1311. // Return an array of links.
  1312. // on error/failure return empty array.
  1313. if(! function_exists('fetch_xrd_links')) {
  1314. function fetch_xrd_links($url) {
  1315. $xml = fetch_url($url);
  1316. if (! $xml)
  1317. return array();
  1318. logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
  1319. $h = simplexml_load_string($xml);
  1320. $arr = convert_xml_element_to_array($h);
  1321. $links = array();
  1322. if(isset($arr['xrd']['link'])) {
  1323. $link = $arr['xrd']['link'];
  1324. if(! isset($link[0]))
  1325. $links = array($link);
  1326. else
  1327. $links = $link;
  1328. }
  1329. if(isset($arr['xrd']['alias'])) {
  1330. $alias = $arr['xrd']['alias'];
  1331. if(! isset($alias[0]))
  1332. $aliases = array($alias);
  1333. else
  1334. $aliases = $alias;
  1335. foreach($aliases as $alias) {
  1336. $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
  1337. }
  1338. }
  1339. logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
  1340. return $links;
  1341. }}
  1342. // Convert an ACL array to a storable string
  1343. if(! function_exists('perms2str')) {
  1344. function perms2str($p) {
  1345. $ret = '';
  1346. $tmp = $p;
  1347. if(is_array($tmp)) {
  1348. array_walk($tmp,'sanitise_acl');
  1349. $ret = implode('',$tmp);
  1350. }
  1351. return $ret;
  1352. }}
  1353. // generate a guaranteed unique (for this domain) item ID for ATOM
  1354. // safe from birthday paradox
  1355. if(! function_exists('item_new_uri')) {
  1356. function item_new_uri($hostname,$uid) {
  1357. do {
  1358. $dups = false;
  1359. $hash = random_string();
  1360. $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
  1361. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
  1362. dbesc($uri));
  1363. if(count($r))
  1364. $dups = true;
  1365. } while($dups == true);
  1366. return $uri;
  1367. }}
  1368. // Generate a guaranteed unique photo ID.
  1369. // safe from birthday paradox
  1370. if(! function_exists('photo_new_resource')) {
  1371. function photo_new_resource() {
  1372. do {
  1373. $found = false;
  1374. $resource = hash('md5',uniqid(mt_rand(),true));
  1375. $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
  1376. dbesc($resource)
  1377. );
  1378. if(count($r))
  1379. $found = true;
  1380. } while($found == true);
  1381. return $resource