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.

2810 lines
76 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
11 years ago
11 years ago
  1. <?php
  2. set_time_limit(0);
  3. ini_set('pcre.backtrack_limit', 250000);
  4. define ( 'FRIENDIKA_VERSION', '2.2.1005' );
  5. define ( 'DFRN_PROTOCOL_VERSION', '2.21' );
  6. define ( 'DB_UPDATE_VERSION', 1063 );
  7. define ( 'EOL', "<br />\r\n" );
  8. define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
  9. define ( 'DOWN_ARROW', '&#x21e9;' );
  10. /**
  11. *
  12. * Image storage quality. Lower numbers save space at cost of image detail.
  13. * For ease of upgrade, please do not change here. Change jpeg quality with
  14. * set_config('system','jpeg_quality',n) in .htconfig.php
  15. * where n is netween 1 and 100, and with very poor results below about 50
  16. *
  17. */
  18. define ( 'JPEG_QUALITY', 100 );
  19. /**
  20. * SSL redirection policies
  21. */
  22. define ( 'SSL_POLICY_NONE', 0 );
  23. define ( 'SSL_POLICY_FULL', 1 );
  24. define ( 'SSL_POLICY_SELFSIGN', 2 );
  25. /**
  26. * log levels
  27. */
  28. define ( 'LOGGER_NORMAL', 0 );
  29. define ( 'LOGGER_TRACE', 1 );
  30. define ( 'LOGGER_DEBUG', 2 );
  31. define ( 'LOGGER_DATA', 3 );
  32. define ( 'LOGGER_ALL', 4 );
  33. /**
  34. * registration policies
  35. */
  36. define ( 'REGISTER_CLOSED', 0 );
  37. define ( 'REGISTER_APPROVE', 1 );
  38. define ( 'REGISTER_OPEN', 2 );
  39. /**
  40. * relationship types
  41. * When used in contact records, this indicates that 'uid' has
  42. * this relationship with contact['name']
  43. */
  44. define ( 'REL_VIP', 1);
  45. define ( 'REL_FAN', 2);
  46. define ( 'REL_BUD', 3);
  47. /**
  48. * Hook array order
  49. */
  50. define ( 'HOOK_HOOK', 0);
  51. define ( 'HOOK_FILE', 1);
  52. define ( 'HOOK_FUNCTION', 2);
  53. /**
  54. *
  55. * page/profile types
  56. *
  57. * PAGE_NORMAL is a typical personal profile account
  58. * PAGE_SOAPBOX automatically approves all friend requests as REL_FAN, (readonly)
  59. * PAGE_COMMUNITY automatically approves all friend requests as REL_FAN, but with
  60. * write access to wall and comments (no email and not included in page owner's ACL lists)
  61. * PAGE_FREELOVE automatically approves all friend requests as full friends (REL_BUD).
  62. *
  63. */
  64. define ( 'PAGE_NORMAL', 0 );
  65. define ( 'PAGE_SOAPBOX', 1 );
  66. define ( 'PAGE_COMMUNITY', 2 );
  67. define ( 'PAGE_FREELOVE', 3 );
  68. /**
  69. * Network and protocol family types
  70. */
  71. define ( 'NETWORK_DFRN', 'dfrn'); // Friendika, Mistpark, other DFRN implementations
  72. define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
  73. define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
  74. define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
  75. define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
  76. define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
  77. /**
  78. * Maximum number of "people who like (or don't like) this" that we will list by name
  79. */
  80. define ( 'MAX_LIKERS', 75);
  81. /**
  82. * email notification options
  83. */
  84. define ( 'NOTIFY_INTRO', 0x0001 );
  85. define ( 'NOTIFY_CONFIRM', 0x0002 );
  86. define ( 'NOTIFY_WALL', 0x0004 );
  87. define ( 'NOTIFY_COMMENT', 0x0008 );
  88. define ( 'NOTIFY_MAIL', 0x0010 );
  89. /**
  90. * various namespaces we may need to parse
  91. */
  92. define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
  93. define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
  94. define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
  95. define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
  96. define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
  97. define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
  98. define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
  99. define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
  100. define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
  101. define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
  102. define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
  103. /**
  104. * activity stream defines
  105. */
  106. define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
  107. define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
  108. define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
  109. define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
  110. define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
  111. define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
  112. define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
  113. define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
  114. define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
  115. define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
  116. define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
  117. define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
  118. define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
  119. define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
  120. define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
  121. /**
  122. * item weight for query ordering
  123. */
  124. define ( 'GRAVITY_PARENT', 0);
  125. define ( 'GRAVITY_LIKE', 3);
  126. define ( 'GRAVITY_COMMENT', 6);
  127. /**
  128. *
  129. * Reverse the effect of magic_quotes_gpc if it is enabled.
  130. * Please disable magic_quotes_gpc so we don't have to do this.
  131. * See http://php.net/manual/en/security.magicquotes.disabling.php
  132. *
  133. */
  134. if (get_magic_quotes_gpc()) {
  135. $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  136. while (list($key, $val) = each($process)) {
  137. foreach ($val as $k => $v) {
  138. unset($process[$key][$k]);
  139. if (is_array($v)) {
  140. $process[$key][stripslashes($k)] = $v;
  141. $process[] = &$process[$key][stripslashes($k)];
  142. } else {
  143. $process[$key][stripslashes($k)] = stripslashes($v);
  144. }
  145. }
  146. }
  147. unset($process);
  148. }
  149. /*
  150. * translation system
  151. */
  152. require_once("include/pgettext.php");
  153. /**
  154. *
  155. * class: App
  156. *
  157. * Our main application structure for the life of this page
  158. * Primarily deals with the URL that got us here
  159. * and tries to make some sense of it, and
  160. * stores our page contents and config storage
  161. * and anything else that might need to be passed around
  162. * before we spit the page out.
  163. *
  164. */
  165. if(! class_exists('App')) {
  166. class App {
  167. public $module_loaded = false;
  168. public $query_string;
  169. public $config;
  170. public $page;
  171. public $profile;
  172. public $user;
  173. public $cid;
  174. public $contact;
  175. public $contacts;
  176. public $page_contact;
  177. public $content;
  178. public $data;
  179. public $error = false;
  180. public $cmd;
  181. public $argv;
  182. public $argc;
  183. public $module;
  184. public $pager;
  185. public $strings;
  186. public $path;
  187. public $hooks;
  188. public $timezone;
  189. public $interactive = true;
  190. public $plugins;
  191. public $apps;
  192. public $identities;
  193. private $scheme;
  194. private $hostname;
  195. private $baseurl;
  196. private $db;
  197. private $curl_code;
  198. private $curl_headers;
  199. function __construct() {
  200. $this->config = array();
  201. $this->page = array();
  202. $this->pager= array();
  203. $this->query_string = '';
  204. $this->scheme = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'])) ? 'https' : 'http' );
  205. if(x($_SERVER,'SERVER_NAME')) {
  206. $this->hostname = $_SERVER['SERVER_NAME'];
  207. /**
  208. * Figure out if we are running at the top of a domain
  209. * or in a sub-directory and adjust accordingly
  210. */
  211. $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
  212. if(isset($path) && strlen($path) && ($path != $this->path))
  213. $this->path = $path;
  214. }
  215. set_include_path("include/$this->hostname" . PATH_SEPARATOR . 'include' . PATH_SEPARATOR . '.' );
  216. if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=")
  217. $this->query_string = substr($_SERVER['QUERY_STRING'],2);
  218. if(x($_GET,'q'))
  219. $this->cmd = trim($_GET['q'],'/\\');
  220. /**
  221. *
  222. * Break the URL path into C style argc/argv style arguments for our
  223. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  224. * will be 3 (integer) and $this->argv will contain:
  225. * [0] => 'module'
  226. * [1] => 'arg1'
  227. * [2] => 'arg2'
  228. *
  229. *
  230. * There will always be one argument. If provided a naked domain
  231. * URL, $this->argv[0] is set to "home".
  232. *
  233. */
  234. $this->argv = explode('/',$this->cmd);
  235. $this->argc = count($this->argv);
  236. if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
  237. $this->module = str_replace(".", "_", $this->argv[0]);
  238. }
  239. else {
  240. $this->module = 'home';
  241. }
  242. /**
  243. * Special handling for the webfinger/lrdd host XRD file
  244. * Just spit out the contents and exit.
  245. */
  246. if($this->cmd === '.well-known/host-meta') {
  247. require_once('include/hostxrd.php');
  248. hostxrd($this->get_baseurl());
  249. // NOTREACHED
  250. }
  251. /**
  252. * See if there is any page number information, and initialise
  253. * pagination
  254. */
  255. $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
  256. $this->pager['itemspage'] = 50;
  257. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  258. $this->pager['total'] = 0;
  259. }
  260. function get_baseurl($ssl = false) {
  261. $scheme = $this->scheme;
  262. if(x($this->config,'ssl_policy')) {
  263. if(($ssl) || ($this->config['ssl_policy'] == SSL_POLICY_FULL))
  264. $scheme = 'https';
  265. if(($this->config['ssl_policy'] == SSL_POLICY_SELFSIGN) && (local_user() || x($_POST,'auth-params')))
  266. $scheme = 'https';
  267. }
  268. $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
  269. return $this->baseurl;
  270. }
  271. function set_baseurl($url) {
  272. $parsed = @parse_url($url);
  273. $this->baseurl = $url;
  274. if($parsed) {
  275. $this->scheme = $parsed['scheme'];
  276. $this->hostname = $parsed['host'];
  277. if(x($parsed,'port'))
  278. $this->hostname .= ':' . $parsed['port'];
  279. if(x($parsed,'path'))
  280. $this->path = trim($parsed['path'],'\\/');
  281. }
  282. }
  283. function get_hostname() {
  284. return $this->hostname;
  285. }
  286. function set_hostname($h) {
  287. $this->hostname = $h;
  288. }
  289. function set_path($p) {
  290. $this->path = trim(trim($p),'/');
  291. }
  292. function get_path() {
  293. return $this->path;
  294. }
  295. function set_pager_total($n) {
  296. $this->pager['total'] = intval($n);
  297. }
  298. function set_pager_itemspage($n) {
  299. $this->pager['itemspage'] = intval($n);
  300. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  301. }
  302. function init_pagehead() {
  303. $this->page['title'] = $this->config['sitename'];
  304. $tpl = file_get_contents('view/head.tpl');
  305. $this->page['htmlhead'] = replace_macros($tpl,array(
  306. '$baseurl' => $this->get_baseurl(),
  307. '$generator' => 'Friendika' . ' ' . FRIENDIKA_VERSION,
  308. '$delitem' => t('Delete this item?'),
  309. '$comment' => t('Comment')
  310. ));
  311. }
  312. function set_curl_code($code) {
  313. $this->curl_code = $code;
  314. }
  315. function get_curl_code() {
  316. return $this->curl_code;
  317. }
  318. function set_curl_headers($headers) {
  319. $this->curl_headers = $headers;
  320. }
  321. function get_curl_headers() {
  322. return $this->curl_headers;
  323. }
  324. }}
  325. // retrieve the App structure
  326. // useful in functions which require it but don't get it passed to them
  327. if(! function_exists('get_app')) {
  328. function get_app() {
  329. global $a;
  330. return $a;
  331. }};
  332. // Multi-purpose function to check variable state.
  333. // Usage: x($var) or $x($array,'key')
  334. // returns false if variable/key is not set
  335. // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
  336. // e.g. x('') or x(0) returns 0;
  337. if(! function_exists('x')) {
  338. function x($s,$k = NULL) {
  339. if($k != NULL) {
  340. if((is_array($s)) && (array_key_exists($k,$s))) {
  341. if($s[$k])
  342. return (int) 1;
  343. return (int) 0;
  344. }
  345. return false;
  346. }
  347. else {
  348. if(isset($s)) {
  349. if($s) {
  350. return (int) 1;
  351. }
  352. return (int) 0;
  353. }
  354. return false;
  355. }
  356. }}
  357. // called from db initialisation if db is dead.
  358. if(! function_exists('system_unavailable')) {
  359. function system_unavailable() {
  360. include('system_unavailable.php');
  361. system_down();
  362. killme();
  363. }}
  364. // Primarily involved with database upgrade, but also sets the
  365. // base url for use in cmdline programs which don't have
  366. // $_SERVER variables, and synchronising the state of installed plugins.
  367. if(! function_exists('check_config')) {
  368. function check_config(&$a) {
  369. load_config('system');
  370. $build = get_config('system','build');
  371. if(! x($build))
  372. $build = set_config('system','build',DB_UPDATE_VERSION);
  373. $url = get_config('system','url');
  374. // if the url isn't set or the stored url is radically different
  375. // than the currently visited url, store the current value accordingly.
  376. // "Radically different" ignores common variations such as http vs https
  377. // and www.example.com vs example.com.
  378. if((! x($url)) || (! link_compare($url,$a->get_baseurl())))
  379. $url = set_config('system','url',$a->get_baseurl());
  380. if($build != DB_UPDATE_VERSION) {
  381. $stored = intval($build);
  382. $current = intval(DB_UPDATE_VERSION);
  383. if(($stored < $current) && file_exists('update.php')) {
  384. // We're reporting a different version than what is currently installed.
  385. // Run any existing update scripts to bring the database up to current.
  386. require_once('update.php');
  387. // make sure that boot.php and update.php are the same release, we might be
  388. // updating right this very second and the correct version of the update.php
  389. // file may not be here yet. This can happen on a very busy site.
  390. if(DB_UPDATE_VERSION == UPDATE_VERSION) {
  391. for($x = $stored; $x < $current; $x ++) {
  392. if(function_exists('update_' . $x)) {
  393. $func = 'update_' . $x;
  394. $func($a);
  395. }
  396. }
  397. set_config('system','build', DB_UPDATE_VERSION);
  398. }
  399. }
  400. }
  401. /**
  402. *
  403. * Synchronise plugins:
  404. *
  405. * $a->config['system']['addon'] contains a comma-separated list of names
  406. * of plugins/addons which are used on this system.
  407. * Go through the database list of already installed addons, and if we have
  408. * an entry, but it isn't in the config list, call the uninstall procedure
  409. * and mark it uninstalled in the database (for now we'll remove it).
  410. * Then go through the config list and if we have a plugin that isn't installed,
  411. * call the install procedure and add it to the database.
  412. *
  413. */
  414. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  415. if(count($r))
  416. $installed = $r;
  417. else
  418. $installed = array();
  419. $plugins = get_config('system','addon');
  420. $plugins_arr = array();
  421. if($plugins)
  422. $plugins_arr = explode(',',str_replace(' ', '',$plugins));
  423. $a->plugins = $plugins_arr;
  424. $installed_arr = array();
  425. if(count($installed)) {
  426. foreach($installed as $i) {
  427. if(! in_array($i['name'],$plugins_arr)) {
  428. logger("Addons: uninstalling " . $i['name']);
  429. q("DELETE FROM `addon` WHERE `id` = %d LIMIT 1",
  430. intval($i['id'])
  431. );
  432. @include_once('addon/' . $i['name'] . '/' . $i['name'] . '.php');
  433. if(function_exists($i['name'] . '_uninstall')) {
  434. $func = $i['name'] . '_uninstall';
  435. $func();
  436. }
  437. }
  438. else
  439. $installed_arr[] = $i['name'];
  440. }
  441. }
  442. if(count($plugins_arr)) {
  443. foreach($plugins_arr as $p) {
  444. if(! in_array($p,$installed_arr)) {
  445. logger("Addons: installing " . $p);
  446. $t = filemtime('addon/' . $p . '/' . $p . '.php');
  447. @include_once('addon/' . $p . '/' . $p . '.php');
  448. if(function_exists($p . '_install')) {
  449. $func = $p . '_install';
  450. $func();
  451. $r = q("INSERT INTO `addon` (`name`, `installed`, `timestamp`) VALUES ( '%s', 1, %d ) ",
  452. dbesc($p),
  453. intval($t)
  454. );
  455. }
  456. }
  457. }
  458. }
  459. load_hooks();
  460. return;
  461. }}
  462. // reload all updated plugins
  463. if(! function_exists('reload_plugins')) {
  464. function reload_plugins() {
  465. $plugins = get_config('system','addon');
  466. if(strlen($plugins)) {
  467. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  468. if(count($r))
  469. $installed = $r;
  470. else
  471. $installed = array();
  472. $parr = explode(',',$plugins);
  473. if(count($parr)) {
  474. foreach($parr as $pl) {
  475. $pl = trim($pl);
  476. $t = filemtime('addon/' . $pl . '/' . $pl . '.php');
  477. foreach($installed as $i) {
  478. if(($i['name'] == $pl) && ($i['timestamp'] != $t)) {
  479. logger('Reloading plugin: ' . $i['name']);
  480. @include_once('addon/' . $pl . '/' . $pl . '.php');
  481. if(function_exists($pl . '_uninstall')) {
  482. $func = $pl . '_uninstall';
  483. $func();
  484. }
  485. if(function_exists($pl . '_install')) {
  486. $func = $pl . '_install';
  487. $func();
  488. }
  489. q("UPDATE `addon` SET `timestamp` = %d WHERE `id` = %d LIMIT 1",
  490. intval($t),
  491. intval($i['id'])
  492. );
  493. }
  494. }
  495. }
  496. }
  497. }
  498. }}
  499. // This is our template processor.
  500. // $s is the string requiring macro substitution.
  501. // $r is an array of key value pairs (search => replace)
  502. // returns substituted string.
  503. // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
  504. // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
  505. // depending on the order in which they were declared in the array.
  506. require_once("include/template_processor.php");
  507. if(! function_exists('replace_macros')) {
  508. function replace_macros($s,$r) {
  509. global $t;
  510. return $t->replace($s,$r);
  511. }}
  512. // curl wrapper. If binary flag is true, return binary
  513. // results.
  514. if(! function_exists('fetch_url')) {
  515. function fetch_url($url,$binary = false, &$redirects = 0) {
  516. $a = get_app();
  517. $ch = curl_init($url);
  518. if(($redirects > 8) || (! $ch))
  519. return false;
  520. curl_setopt($ch, CURLOPT_HEADER, true);
  521. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  522. $curl_time = intval(get_config('system','curl_timeout'));
  523. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  524. // by default we will allow self-signed certs
  525. // but you can override this
  526. $check_cert = get_config('system','verifyssl');
  527. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  528. $prx = get_config('system','proxy');
  529. if(strlen($prx)) {
  530. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  531. curl_setopt($ch, CURLOPT_PROXY, $prx);
  532. $prxusr = get_config('system','proxyuser');
  533. if(strlen($prxusr))
  534. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  535. }
  536. if($binary)
  537. curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  538. $a->set_curl_code(0);
  539. // don't let curl abort the entire application
  540. // if it throws any errors.
  541. $s = @curl_exec($ch);
  542. $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  543. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  544. if(stristr($header,'100') && (strlen($header) < 30)) {
  545. // 100 Continue has two headers, get the real one
  546. $s = substr($s,strlen($header)+4);
  547. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  548. }
  549. if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
  550. $matches = array();
  551. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  552. $url = trim(array_pop($matches));
  553. $url_parsed = @parse_url($url);
  554. if (isset($url_parsed)) {
  555. $redirects++;
  556. return fetch_url($url,$binary,$redirects);
  557. }
  558. }
  559. $a->set_curl_code($http_code);
  560. $body = substr($s,strlen($header)+4);
  561. /* one more try to make sure there are no more headers */
  562. if(strpos($body,'HTTP/') === 0) {
  563. $header = substr($body,0,strpos($body,"\r\n\r\n"));
  564. $body = substr($body,strlen($header)+4);
  565. }
  566. $a->set_curl_headers($header);
  567. curl_close($ch);
  568. return($body);
  569. }}
  570. // post request to $url. $params is an array of post variables.
  571. if(! function_exists('post_url')) {
  572. function post_url($url,$params, $headers = null, &$redirects = 0) {
  573. $a = get_app();
  574. $ch = curl_init($url);
  575. if(($redirects > 8) || (! $ch))
  576. return false;
  577. curl_setopt($ch, CURLOPT_HEADER, true);
  578. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  579. curl_setopt($ch, CURLOPT_POST,1);
  580. curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
  581. $curl_time = intval(get_config('system','curl_timeout'));
  582. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  583. if(is_array($headers))
  584. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  585. $check_cert = get_config('system','verifyssl');
  586. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  587. $prx = get_config('system','proxy');
  588. if(strlen($prx)) {
  589. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  590. curl_setopt($ch, CURLOPT_PROXY, $prx);
  591. $prxusr = get_config('system','proxyuser');
  592. if(strlen($prxusr))
  593. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  594. }
  595. $a->set_curl_code(0);
  596. // don't let curl abort the entire application
  597. // if it throws any errors.
  598. $s = @curl_exec($ch);
  599. $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  600. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  601. if(stristr($header,'100') && (strlen($header) < 30)) {
  602. // 100 Continue has two headers, get the real one
  603. $s = substr($s,strlen($header)+4);
  604. $header = substr($s,0,strpos($s,"\r\n\r\n"));
  605. }
  606. if($http_code == 301 || $http_code == 302 || $http_code == 303) {
  607. $matches = array();
  608. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  609. $url = trim(array_pop($matches));
  610. $url_parsed = @parse_url($url);
  611. if (isset($url_parsed)) {
  612. $redirects++;
  613. return post_url($url,$binary,$headers,$redirects);
  614. }
  615. }
  616. $a->set_curl_code($http_code);
  617. $body = substr($s,strlen($header)+4);
  618. /* one more try to make sure there are no more headers */
  619. if(strpos($body,'HTTP/') === 0) {
  620. $header = substr($body,0,strpos($body,"\r\n\r\n"));
  621. $body = substr($body,strlen($header)+4);
  622. }
  623. $a->set_curl_headers($header);
  624. curl_close($ch);
  625. return($body);
  626. }}
  627. // random hash, 64 chars
  628. if(! function_exists('random_string')) {
  629. function random_string() {
  630. return(hash('sha256',uniqid(rand(),true)));
  631. }}
  632. /**
  633. * This is our primary input filter.
  634. *
  635. * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
  636. * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
  637. * after cleansing, and angle chars with the high bit set could get through as markup.
  638. *
  639. * This is now disabled because it was interfering with some legitimate unicode sequences
  640. * and hopefully there aren't a lot of those browsers left.
  641. *
  642. * Use this on any text input where angle chars are not valid or permitted
  643. * They will be replaced with safer brackets. This may be filtered further
  644. * if these are not allowed either.
  645. *
  646. */
  647. if(! function_exists('notags')) {
  648. function notags($string) {
  649. return(str_replace(array("<",">"), array('[',']'), $string));
  650. // High-bit filter no longer used
  651. // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
  652. }}
  653. // use this on "body" or "content" input where angle chars shouldn't be removed,
  654. // and allow them to be safely displayed.
  655. if(! function_exists('escape_tags')) {
  656. function escape_tags($string) {
  657. return(htmlspecialchars($string));
  658. }}
  659. // wrapper for adding a login box. If $register == true provide a registration
  660. // link. This will most always depend on the value of $a->config['register_policy'].
  661. // returns the complete html for inserting into the page
  662. if(! function_exists('login')) {
  663. function login($register = false) {
  664. $o = "";
  665. $register_tpl = (($register) ? get_markup_template("register-link.tpl") : "");
  666. $register_html = replace_macros($register_tpl,array(
  667. '$title' => t('Create a New Account'),
  668. '$desc' => t('Register')
  669. ));
  670. $noid = get_config('system','no_openid');
  671. if($noid) {
  672. $classname = 'no-openid';
  673. $namelabel = t('Nickname or Email address: ');
  674. $passlabel = t('Password: ');
  675. $login = t('Login');
  676. }
  677. else {
  678. $classname = 'openid';
  679. $namelabel = t('Nickname/Email/OpenID: ');
  680. $passlabel = t("Password \x28if not OpenID\x29: ");
  681. $login = t('Login');
  682. }
  683. $lostpass = t('Forgot your password?');
  684. $lostlink = t('Password Reset');
  685. if(local_user()) {
  686. $tpl = get_markup_template("logout.tpl");
  687. }
  688. else {
  689. $tpl = get_markup_template("login.tpl");
  690. }
  691. $o = '<script type="text/javascript"> $(document).ready(function() { $("#login-name").focus();} );</script>';
  692. $o .= replace_macros($tpl,array(
  693. '$logout' => t('Logout'),
  694. '$register_html' => $register_html,
  695. '$classname' => $classname,
  696. '$namelabel' => $namelabel,
  697. '$passlabel' => $passlabel,
  698. '$login' => $login,
  699. '$lostpass' => $lostpass,
  700. '$lostlink' => $lostlink
  701. ));
  702. return $o;
  703. }}
  704. // generate a string that's random, but usually pronounceable.
  705. // used to generate initial passwords
  706. if(! function_exists('autoname')) {
  707. function autoname($len) {
  708. $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
  709. if(mt_rand(0,5) == 4)
  710. $vowels[] = 'y';
  711. $cons = array(
  712. 'b','bl','br',
  713. 'c','ch','cl','cr',
  714. 'd','dr',
  715. 'f','fl','fr',
  716. 'g','gh','gl','gr',
  717. 'h',
  718. 'j',
  719. 'k','kh','kl','kr',
  720. 'l',
  721. 'm',
  722. 'n',
  723. 'p','ph','pl','pr',
  724. 'qu',
  725. 'r','rh',
  726. 's','sc','sh','sm','sp','st',
  727. 't','th','tr',
  728. 'v',
  729. 'w','wh',
  730. 'x',
  731. 'z','zh'
  732. );
  733. $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
  734. 'nd','ng','nk','nt','rn','rp','rt');
  735. $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
  736. 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
  737. $start = mt_rand(0,2);
  738. if($start == 0)
  739. $table = $vowels;
  740. else
  741. $table = $cons;
  742. $word = '';
  743. for ($x = 0; $x < $len; $x ++) {
  744. $r = mt_rand(0,count($table) - 1);
  745. $word .= $table[$r];
  746. if($table == $vowels)
  747. $table = array_merge($cons,$midcons);
  748. else
  749. $table = $vowels;
  750. }
  751. $word = substr($word,0,$len);
  752. foreach($noend as $noe) {
  753. if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
  754. $word = substr($word,0,-1);
  755. break;
  756. }
  757. }
  758. if(substr($word,-1) == 'q')
  759. $word = substr($word,0,-1);
  760. return $word;
  761. }}
  762. // Used to end the current process, after saving session state.
  763. if(! function_exists('killme')) {
  764. function killme() {
  765. session_write_close();
  766. exit;
  767. }}
  768. // redirect to another URL and terminate this process.
  769. if(! function_exists('goaway')) {
  770. function goaway($s) {
  771. header("Location: $s");
  772. killme();
  773. }}
  774. // Generic XML return
  775. // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
  776. // of $st and an optional text <message> of $message and terminates the current process.
  777. if(! function_exists('xml_status')) {
  778. function xml_status($st, $message = '') {
  779. $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
  780. if($st)
  781. logger('xml_status returning non_zero: ' . $st . " message=" . $message);
  782. header( "Content-type: text/xml" );
  783. echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
  784. echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
  785. killme();
  786. }}
  787. // Returns the uid of locally logged in user or false.
  788. if(! function_exists('local_user')) {
  789. function local_user() {
  790. if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
  791. return intval($_SESSION['uid']);
  792. return false;
  793. }}
  794. // Returns contact id of authenticated site visitor or false
  795. if(! function_exists('remote_user')) {
  796. function remote_user() {
  797. if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
  798. return intval($_SESSION['visitor_id']);
  799. return false;
  800. }}
  801. // contents of $s are displayed prominently on the page the next time
  802. // a page is loaded. Usually used for errors or alerts.
  803. if(! function_exists('notice')) {
  804. function notice($s) {
  805. $a = get_app();
  806. if($a->interactive)
  807. $_SESSION['sysmsg'] .= $s;
  808. }}
  809. if(! function_exists('info')) {
  810. function info($s) {
  811. $a = get_app();
  812. if($a->interactive)
  813. $_SESSION['sysmsg_info'] .= $s;
  814. }}
  815. // wrapper around config to limit the text length of an incoming message
  816. if(! function_exists('get_max_import_size')) {
  817. function get_max_import_size() {
  818. global $a;
  819. return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
  820. }}
  821. // escape text ($str) for XML transport
  822. // returns escaped text.
  823. if(! function_exists('xmlify')) {
  824. function xmlify($str) {
  825. $buffer = '';
  826. for($x = 0; $x < strlen($str); $x ++) {
  827. $char = $str[$x];
  828. switch( $char ) {
  829. case "\r" :
  830. break;
  831. case "&" :
  832. $buffer .= '&amp;';
  833. break;
  834. case "'" :
  835. $buffer .= '&apos;';
  836. break;
  837. case "\"" :
  838. $buffer .= '&quot;';
  839. break;
  840. case '<' :
  841. $buffer .= '&lt;';
  842. break;
  843. case '>' :
  844. $buffer .= '&gt;';
  845. break;
  846. case "\n" :
  847. $buffer .= "\n";
  848. break;
  849. default :
  850. $buffer .= $char;
  851. break;
  852. }
  853. }
  854. $buffer = trim($buffer);
  855. return($buffer);
  856. }}
  857. // undo an xmlify
  858. // pass xml escaped text ($s), returns unescaped text
  859. if(! function_exists('unxmlify')) {
  860. function unxmlify($s) {
  861. $ret = str_replace('&amp;','&', $s);
  862. $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
  863. return $ret;
  864. }}
  865. // convenience wrapper, reverse the operation "bin2hex"
  866. if(! function_exists('hex2bin')) {
  867. function hex2bin($s) {
  868. if(! ctype_xdigit($s)) {
  869. logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
  870. return($s);
  871. }
  872. return(pack("H*",$s));
  873. }}
  874. // Automatic pagination.
  875. // To use, get the count of total items.
  876. // Then call $a->set_pager_total($number_items);
  877. // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
  878. // Then call paginate($a) after the end of the display loop to insert the pager block on the page
  879. // (assuming there are enough items to paginate).
  880. // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
  881. // will limit the results to the correct items for the current page.
  882. // The actual page handling is then accomplished at the application layer.
  883. if(! function_exists('paginate')) {
  884. function paginate(&$a) {
  885. $o = '';
  886. $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
  887. $stripped = str_replace('q=','',$stripped);
  888. $stripped = trim($stripped,'/');
  889. $pagenum = $a->pager['page'];
  890. $url = $a->get_baseurl() . '/' . $stripped;
  891. if($a->pager['total'] > $a->pager['itemspage']) {
  892. $o .= '<div class="pager">';
  893. if($a->pager['page'] != 1)
  894. $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
  895. $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
  896. $numpages = $a->pager['total'] / $a->pager['itemspage'];
  897. $numstart = 1;
  898. $numstop = $numpages;
  899. if($numpages > 14) {
  900. $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
  901. $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
  902. }
  903. for($i = $numstart; $i <= $numstop; $i++){
  904. if($i == $a->pager['page'])
  905. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  906. else
  907. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  908. $o .= '</span> ';
  909. }
  910. if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
  911. if($i == $a->pager['page'])
  912. $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
  913. else
  914. $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
  915. $o .= '</span> ';
  916. }
  917. $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
  918. $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
  919. if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
  920. $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
  921. $o .= '</div>'."\r\n";
  922. }
  923. return $o;
  924. }}
  925. // Turn user/group ACLs stored as angle bracketed text into arrays
  926. if(! function_exists('expand_acl')) {
  927. function expand_acl($s) {
  928. // turn string array of angle-bracketed elements into numeric array
  929. // e.g. "<1><2><3>" => array(1,2,3);
  930. $ret = array();
  931. if(strlen($s)) {
  932. $t = str_replace('<','',$s);
  933. $a = explode('>',$t);
  934. foreach($a as $aa) {
  935. if(intval($aa))
  936. $ret[] = intval($aa);
  937. }
  938. }
  939. return $ret;
  940. }}
  941. // Used to wrap ACL elements in angle brackets for storage
  942. if(! function_exists('sanitise_acl')) {
  943. function sanitise_acl(&$item) {
  944. if(intval($item))
  945. $item = '<' . intval(notags(trim($item))) . '>';
  946. else
  947. unset($item);
  948. }}
  949. // retrieve a "family" of config variables from database to cached storage
  950. if(! function_exists('load_config')) {
  951. function load_config($family) {
  952. global $a;
  953. $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
  954. dbesc($family)
  955. );
  956. if(count($r)) {
  957. foreach($r as $rr) {
  958. $k = $rr['k'];
  959. $a->config[$family][$k] = $rr['v'];
  960. }
  961. }
  962. }}
  963. // get a particular config variable given the family name
  964. // and key. Returns false if not set.
  965. // $instore is only used by the set_config function
  966. // to determine if the key already exists in the DB
  967. // If a key is found in the DB but doesn't exist in
  968. // local config cache, pull it into the cache so we don't have
  969. // to hit the DB again for this item.
  970. if(! function_exists('get_config')) {
  971. function get_config($family, $key, $instore = false) {
  972. global $a;
  973. if(! $instore) {
  974. if(isset($a->config[$family][$key])) {
  975. if($a->config[$family][$key] === '!<unset>!') {
  976. return false;
  977. }
  978. return $a->config[$family][$key];
  979. }
  980. }
  981. $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  982. dbesc($family),
  983. dbesc($key)
  984. );
  985. if(count($ret)) {
  986. $a->config[$family][$key] = $ret[0]['v'];
  987. return $ret[0]['v'];
  988. }
  989. else {
  990. $a->config[$family][$key] = '!<unset>!';
  991. }
  992. return false;
  993. }}
  994. // Store a config value ($value) in the category ($family)
  995. // under the key ($key)
  996. // Return the value, or false if the database update failed
  997. if(! function_exists('set_config')) {
  998. function set_config($family,$key,$value) {
  999. global $a;
  1000. if(get_config($family,$key,true) === false) {
  1001. $a->config[$family][$key] = $value;
  1002. $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
  1003. dbesc($family),
  1004. dbesc($key),
  1005. dbesc($value)
  1006. );
  1007. if($ret)
  1008. return $value;
  1009. return $ret;
  1010. }
  1011. $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1012. dbesc($value),
  1013. dbesc($family),
  1014. dbesc($key)
  1015. );
  1016. $a->config[$family][$key] = $value;
  1017. if($ret)
  1018. return $value;
  1019. return $ret;
  1020. }}
  1021. if(! function_exists('load_pconfig')) {
  1022. function load_pconfig($uid,$family) {
  1023. global $a;
  1024. $r = q("SELECT * FROM `pconfig` WHERE `cat` = '%s' AND `uid` = %d",
  1025. dbesc($family),
  1026. intval($uid)
  1027. );
  1028. if(count($r)) {
  1029. foreach($r as $rr) {
  1030. $k = $rr['k'];
  1031. $a->config[$uid][$family][$k] = $rr['v'];
  1032. }
  1033. }
  1034. }}
  1035. if(! function_exists('get_pconfig')) {
  1036. function get_pconfig($uid,$family, $key, $instore = false) {
  1037. global $a;
  1038. if(! $instore) {
  1039. if(isset($a->config[$uid][$family][$key])) {
  1040. if($a->config[$uid][$family][$key] === '!<unset>!') {
  1041. return false;
  1042. }
  1043. return $a->config[$uid][$family][$key];
  1044. }
  1045. }
  1046. $ret = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1047. intval($uid),
  1048. dbesc($family),
  1049. dbesc($key)
  1050. );
  1051. if(count($ret)) {
  1052. $a->config[$uid][$family][$key] = $ret[0]['v'];
  1053. return $ret[0]['v'];
  1054. }
  1055. else {
  1056. $a->config[$uid][$family][$key] = '!<unset>!';
  1057. }
  1058. return false;
  1059. }}
  1060. if(! function_exists('del_config')) {
  1061. function del_config($family,$key) {
  1062. global $a;
  1063. if(x($a->config[$family],$key))
  1064. unset($a->config[$family][$key]);
  1065. $ret = q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1066. dbesc($cat),
  1067. dbesc($key)
  1068. );
  1069. return $ret;
  1070. }}
  1071. // Same as above functions except these are for personal config storage and take an
  1072. // additional $uid argument.
  1073. if(! function_exists('set_pconfig')) {
  1074. function set_pconfig($uid,$family,$key,$value) {
  1075. global $a;
  1076. if(get_pconfig($uid,$family,$key,true) === false) {
  1077. $a->config[$uid][$family][$key] = $value;
  1078. $ret = q("INSERT INTO `pconfig` ( `uid`, `cat`, `k`, `v` ) VALUES ( %d, '%s', '%s', '%s' ) ",
  1079. intval($uid),
  1080. dbesc($family),
  1081. dbesc($key),
  1082. dbesc($value)
  1083. );
  1084. if($ret)
  1085. return $value;
  1086. return $ret;
  1087. }
  1088. $ret = q("UPDATE `pconfig` SET `v` = '%s' WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1089. dbesc($value),
  1090. intval($uid),
  1091. dbesc($family),
  1092. dbesc($key)
  1093. );
  1094. $a->config[$uid][$family][$key] = $value;
  1095. if($ret)
  1096. return $value;
  1097. return $ret;
  1098. }}
  1099. if(! function_exists('del_pconfig')) {
  1100. function del_pconfig($uid,$family,$key) {
  1101. global $a;
  1102. if(x($a->config[$uid][$family],$key))
  1103. unset($a->config[$uid][$family][$key]);
  1104. $ret = q("DELETE FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
  1105. intval($uid),
  1106. dbesc($family),
  1107. dbesc($key)
  1108. );
  1109. return $ret;
  1110. }}
  1111. // convert an XML document to a normalised, case-corrected array
  1112. // used by webfinger
  1113. if(! function_exists('convert_xml_element_to_array')) {
  1114. function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
  1115. // If we're getting too deep, bail out
  1116. if ($recursion_depth > 512) {
  1117. return(null);
  1118. }
  1119. if (!is_string($xml_element) &&
  1120. !is_array($xml_element) &&
  1121. (get_class($xml_element) == 'SimpleXMLElement')) {
  1122. $xml_element_copy = $xml_element;
  1123. $xml_element = get_object_vars($xml_element);
  1124. }
  1125. if (is_array($xml_element)) {
  1126. $result_array = array();
  1127. if (count($xml_element) <= 0) {
  1128. return (trim(strval($xml_element_copy)));
  1129. }
  1130. foreach($xml_element as $key=>$value) {
  1131. $recursion_depth++;
  1132. $result_array[strtolower($key)] =
  1133. convert_xml_element_to_array($value, $recursion_depth);
  1134. $recursion_depth--;
  1135. }
  1136. if ($recursion_depth == 0) {
  1137. $temp_array = $result_array;
  1138. $result_array = array(
  1139. strtolower($xml_element_copy->getName()) => $temp_array,
  1140. );
  1141. }
  1142. return ($result_array);
  1143. } else {
  1144. return (trim(strval($xml_element)));
  1145. }
  1146. }}
  1147. // Given an email style address, perform webfinger lookup and
  1148. // return the resulting DFRN profile URL, or if no DFRN profile URL
  1149. // is located, returns an OStatus subscription template (prefixed
  1150. // with the string 'stat:' to identify it as on OStatus template).
  1151. // If this isn't an email style address just return $s.
  1152. // Return an empty string if email-style addresses but webfinger fails,
  1153. // or if the resultant personal XRD doesn't contain a supported
  1154. // subscription/friend-request attribute.
  1155. if(! function_exists('webfinger_dfrn')) {
  1156. function webfinger_dfrn($s) {
  1157. if(! strstr($s,'@')) {
  1158. return $s;
  1159. }
  1160. $links = webfinger($s);
  1161. logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
  1162. if(count($links)) {
  1163. foreach($links as $link)
  1164. if($link['@attributes']['rel'] === NAMESPACE_DFRN)
  1165. return $link['@attributes']['href'];
  1166. foreach($links as $link)
  1167. if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
  1168. return 'stat:' . $link['@attributes']['template'];
  1169. }
  1170. return '';
  1171. }}
  1172. // Given an email style address, perform webfinger lookup and
  1173. // return the array of link attributes from the personal XRD file.
  1174. // On error/failure return an empty array.
  1175. if(! function_exists('webfinger')) {
  1176. function webfinger($s) {
  1177. $host = '';
  1178. if(strstr($s,'@')) {
  1179. $host = substr($s,strpos($s,'@') + 1);
  1180. }
  1181. if(strlen($host)) {
  1182. $tpl = fetch_lrdd_template($host);
  1183. logger('webfinger: lrdd template: ' . $tpl);
  1184. if(strlen($tpl)) {
  1185. $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
  1186. logger('webfinger: pxrd: ' . $pxrd);
  1187. $links = fetch_xrd_links($pxrd);
  1188. if(! count($links)) {
  1189. // try with double slashes
  1190. $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
  1191. logger('webfinger: pxrd: ' . $pxrd);
  1192. $links = fetch_xrd_links($pxrd);
  1193. }
  1194. return $links;
  1195. }
  1196. }
  1197. return array();
  1198. }}
  1199. if(! function_exists('lrdd')) {
  1200. function lrdd($uri) {
  1201. $a = get_app();
  1202. // default priority is host priority, host-meta first
  1203. $priority = 'host';
  1204. // All we have is an email address. Resource-priority is irrelevant
  1205. // because our URI isn't directly resolvable.
  1206. if(strstr($uri,'@')) {
  1207. return(webfinger($uri));