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.

2332 lines
68 KiB

10 years ago
10 years ago
10 years ago
10 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
5 years ago
  1. <?php
  2. /**
  3. * @file include/socgraph.php
  4. *
  5. * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
  6. * @todo Fetch profile data from profile page for Redmatrix users
  7. * @todo Detect if it is a forum
  8. */
  9. require_once('include/datetime.php');
  10. require_once("include/Scrape.php");
  11. require_once("include/network.php");
  12. require_once("include/html2bbcode.php");
  13. require_once("include/Contact.php");
  14. require_once("include/Photo.php");
  15. /**
  16. * @brief Fetch POCO data
  17. *
  18. * @param integer $cid Contact ID
  19. * @param integer $uid User ID
  20. * @param integer $zcid Global Contact ID
  21. * @param integer $url POCO address that should be polled
  22. *
  23. * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
  24. * and add the entries to the gcontact (Global Contact) table, or update existing entries
  25. * if anything (name or photo) has changed.
  26. * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
  27. *
  28. * Once the global contact is stored add (if necessary) the contact linkage which associates
  29. * the given uid, cid to the global contact entry. There can be many uid/cid combinations
  30. * pointing to the same global contact id.
  31. *
  32. */
  33. function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
  34. // Call the function "poco_load_worker" via the worker
  35. proc_run(PRIORITY_LOW, "include/discover_poco.php", "poco_load", intval($cid), intval($uid), intval($zcid), base64_encode($url));
  36. }
  37. /**
  38. * @brief Fetch POCO data from the worker
  39. *
  40. * @param integer $cid Contact ID
  41. * @param integer $uid User ID
  42. * @param integer $zcid Global Contact ID
  43. * @param integer $url POCO address that should be polled
  44. *
  45. */
  46. function poco_load_worker($cid, $uid, $zcid, $url) {
  47. $a = get_app();
  48. if($cid) {
  49. if((! $url) || (! $uid)) {
  50. $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
  51. intval($cid)
  52. );
  53. if (dbm::is_result($r)) {
  54. $url = $r[0]['poco'];
  55. $uid = $r[0]['uid'];
  56. }
  57. }
  58. if(! $uid)
  59. return;
  60. }
  61. if(! $url)
  62. return;
  63. $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
  64. logger('poco_load: ' . $url, LOGGER_DEBUG);
  65. $s = fetch_url($url);
  66. logger('poco_load: returns ' . $s, LOGGER_DATA);
  67. logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
  68. if(($a->get_curl_code() > 299) || (! $s))
  69. return;
  70. $j = json_decode($s);
  71. logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
  72. if(! isset($j->entry))
  73. return;
  74. $total = 0;
  75. foreach($j->entry as $entry) {
  76. $total ++;
  77. $profile_url = '';
  78. $profile_photo = '';
  79. $connect_url = '';
  80. $name = '';
  81. $network = '';
  82. $updated = NULL_DATE;
  83. $location = '';
  84. $about = '';
  85. $keywords = '';
  86. $gender = '';
  87. $contact_type = -1;
  88. $generation = 0;
  89. $name = $entry->displayName;
  90. if (isset($entry->urls)) {
  91. foreach ($entry->urls as $url) {
  92. if ($url->type == 'profile') {
  93. $profile_url = $url->value;
  94. continue;
  95. }
  96. if ($url->type == 'webfinger') {
  97. $connect_url = str_replace('acct:' , '', $url->value);
  98. continue;
  99. }
  100. }
  101. }
  102. if (isset($entry->photos)) {
  103. foreach ($entry->photos as $photo) {
  104. if ($photo->type == 'profile') {
  105. $profile_photo = $photo->value;
  106. continue;
  107. }
  108. }
  109. }
  110. if (isset($entry->updated)) {
  111. $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
  112. }
  113. if (isset($entry->network)) {
  114. $network = $entry->network;
  115. }
  116. if (isset($entry->currentLocation)) {
  117. $location = $entry->currentLocation;
  118. }
  119. if (isset($entry->aboutMe)) {
  120. $about = html2bbcode($entry->aboutMe);
  121. }
  122. if (isset($entry->gender)) {
  123. $gender = $entry->gender;
  124. }
  125. if (isset($entry->generation) AND ($entry->generation > 0)) {
  126. $generation = ++$entry->generation;
  127. }
  128. if (isset($entry->tags)) {
  129. foreach($entry->tags as $tag) {
  130. $keywords = implode(", ", $tag);
  131. }
  132. }
  133. if (isset($entry->contactType) AND ($entry->contactType >= 0))
  134. $contact_type = $entry->contactType;
  135. $gcontact = array("url" => $profile_url,
  136. "name" => $name,
  137. "network" => $network,
  138. "photo" => $profile_photo,
  139. "about" => $about,
  140. "location" => $location,
  141. "gender" => $gender,
  142. "keywords" => $keywords,
  143. "connect" => $connect_url,
  144. "updated" => $updated,
  145. "contact-type" => $contact_type,
  146. "generation" => $generation);
  147. try {
  148. $gcontact = sanitize_gcontact($gcontact);
  149. $gcid = update_gcontact($gcontact);
  150. link_gcontact($gcid, $uid, $cid, $zcid);
  151. } catch (Exception $e) {
  152. logger($e->getMessage(), LOGGER_DEBUG);
  153. }
  154. }
  155. logger("poco_load: loaded $total entries",LOGGER_DEBUG);
  156. q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
  157. intval($cid),
  158. intval($uid),
  159. intval($zcid)
  160. );
  161. }
  162. /**
  163. * @brief Sanitize the given gcontact data
  164. *
  165. * @param array $gcontact array with gcontact data
  166. * @throw Exception
  167. *
  168. * Generation:
  169. * 0: No definition
  170. * 1: Profiles on this server
  171. * 2: Contacts of profiles on this server
  172. * 3: Contacts of contacts of profiles on this server
  173. * 4: ...
  174. *
  175. */
  176. function sanitize_gcontact($gcontact) {
  177. if ($gcontact['url'] == "") {
  178. throw new Exception('URL is empty');
  179. }
  180. $urlparts = parse_url($gcontact['url']);
  181. if (!isset($urlparts["scheme"])) {
  182. throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
  183. }
  184. if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
  185. "identi.ca", "alpha.app.net"))) {
  186. throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
  187. }
  188. // Don't store the statusnet connector as network
  189. // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
  190. if ($gcontact['network'] == NETWORK_STATUSNET) {
  191. $gcontact['network'] = "";
  192. }
  193. // Assure that there are no parameter fragments in the profile url
  194. if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
  195. $gcontact['url'] = clean_contact_url($gcontact['url']);
  196. }
  197. $alternate = poco_alternate_ostatus_url($gcontact['url']);
  198. // The global contacts should contain the original picture, not the cached one
  199. if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
  200. $gcontact['photo'] = "";
  201. }
  202. if (!isset($gcontact['network'])) {
  203. $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
  204. dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
  205. );
  206. if (dbm::is_result($r)) {
  207. $gcontact['network'] = $r[0]["network"];
  208. }
  209. if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
  210. $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
  211. dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
  212. );
  213. if (dbm::is_result($r)) {
  214. $gcontact['network'] = $r[0]["network"];
  215. }
  216. }
  217. }
  218. $gcontact['server_url'] = '';
  219. $gcontact['network'] = '';
  220. $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
  221. dbesc(normalise_link($gcontact['url']))
  222. );
  223. if (count($x)) {
  224. if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
  225. $gcontact['network'] = $x[0]["network"];
  226. }
  227. if ($gcontact['updated'] <= NULL_DATE) {
  228. $gcontact['updated'] = $x[0]["updated"];
  229. }
  230. if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
  231. $gcontact['server_url'] = $x[0]["server_url"];
  232. }
  233. if (!isset($gcontact['addr'])) {
  234. $gcontact['addr'] = $x[0]["addr"];
  235. }
  236. }
  237. if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
  238. AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
  239. $data = Probe::uri($gcontact['url']);
  240. if ($data["network"] == NETWORK_PHANTOM) {
  241. throw new Exception('Probing for URL '.$gcontact['url'].' failed');
  242. }
  243. $orig_profile = $gcontact['url'];
  244. $gcontact["server_url"] = $data["baseurl"];
  245. $gcontact = array_merge($gcontact, $data);
  246. if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
  247. // Delete the old entry - if it exists
  248. $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
  249. if ($r) {
  250. q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
  251. q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
  252. }
  253. }
  254. }
  255. if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
  256. throw new Exception('No name and photo for URL '.$gcontact['url']);
  257. }
  258. if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
  259. throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
  260. }
  261. if (!isset($gcontact['server_url'])) {
  262. // We check the server url to be sure that it is a real one
  263. $server_url = poco_detect_server($gcontact['url']);
  264. // We are now sure that it is a correct URL. So we use it in the future
  265. if ($server_url != "") {
  266. $gcontact['server_url'] = $server_url;
  267. }
  268. }
  269. // The server URL doesn't seem to be valid, so we don't store it.
  270. if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
  271. $gcontact['server_url'] = "";
  272. }
  273. return $gcontact;
  274. }
  275. /**
  276. * @brief Link the gcontact entry with user, contact and global contact
  277. *
  278. * @param integer $gcid Global contact ID
  279. * @param integer $cid Contact ID
  280. * @param integer $uid User ID
  281. * @param integer $zcid Global Contact ID
  282. * *
  283. */
  284. function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
  285. if ($gcid <= 0) {
  286. return;
  287. }
  288. $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
  289. intval($cid),
  290. intval($uid),
  291. intval($gcid),
  292. intval($zcid)
  293. );
  294. if (!dbm::is_result($r)) {
  295. q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
  296. intval($cid),
  297. intval($uid),
  298. intval($gcid),
  299. intval($zcid),
  300. dbesc(datetime_convert())
  301. );
  302. } else {
  303. q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
  304. dbesc(datetime_convert()),
  305. intval($cid),
  306. intval($uid),
  307. intval($gcid),
  308. intval($zcid)
  309. );
  310. }
  311. }
  312. function poco_reachable($profile, $server = "", $network = "", $force = false) {
  313. if ($server == "")
  314. $server = poco_detect_server($profile);
  315. if ($server == "")
  316. return true;
  317. return poco_check_server($server, $network, $force);
  318. }
  319. function poco_detect_server($profile) {
  320. // Try to detect the server path based upon some known standard paths
  321. $server_url = "";
  322. if ($server_url == "") {
  323. $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
  324. if ($friendica != $profile) {
  325. $server_url = $friendica;
  326. $network = NETWORK_DFRN;
  327. }
  328. }
  329. if ($server_url == "") {
  330. $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
  331. if ($diaspora != $profile) {
  332. $server_url = $diaspora;
  333. $network = NETWORK_DIASPORA;
  334. }
  335. }
  336. if ($server_url == "") {
  337. $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
  338. if ($red != $profile) {
  339. $server_url = $red;
  340. $network = NETWORK_DIASPORA;
  341. }
  342. }
  343. // Mastodon
  344. if ($server_url == "") {
  345. $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
  346. if ($mastodon != $profile) {
  347. $server_url = $mastodon;
  348. $network = NETWORK_OSTATUS;
  349. }
  350. }
  351. // Numeric OStatus variant
  352. if ($server_url == "") {
  353. $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
  354. if ($ostatus != $profile) {
  355. $server_url = $ostatus;
  356. $network = NETWORK_OSTATUS;
  357. }
  358. }
  359. // Wild guess
  360. if ($server_url == "") {
  361. $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
  362. if ($base != $profile) {
  363. $server_url = $base;
  364. $network = NETWORK_PHANTOM;
  365. }
  366. }
  367. if ($server_url == "") {
  368. return "";
  369. }
  370. $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
  371. dbesc(normalise_link($server_url)));
  372. if (dbm::is_result($r)) {
  373. return $server_url;
  374. }
  375. // Fetch the host-meta to check if this really is a server
  376. $serverret = z_fetch_url($server_url."/.well-known/host-meta");
  377. if (!$serverret["success"]) {
  378. return "";
  379. }
  380. return $server_url;
  381. }
  382. function poco_alternate_ostatus_url($url) {
  383. return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
  384. }
  385. function poco_last_updated($profile, $force = false) {
  386. $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
  387. dbesc(normalise_link($profile)));
  388. if (!dbm::is_result($gcontacts)) {
  389. return false;
  390. }
  391. $contact = array("url" => $profile);
  392. if ($gcontacts[0]["created"] <= NULL_DATE) {
  393. $contact['created'] = datetime_convert();
  394. }
  395. if ($force) {
  396. $server_url = normalise_link(poco_detect_server($profile));
  397. }
  398. if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
  399. $server_url = $gcontacts[0]["server_url"];
  400. }
  401. if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
  402. $server_url = normalise_link(poco_detect_server($profile));
  403. }
  404. if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
  405. logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
  406. return false;
  407. }
  408. if ($server_url != "") {
  409. if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
  410. if ($force) {
  411. q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
  412. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  413. }
  414. logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
  415. return false;
  416. }
  417. $contact['server_url'] = $server_url;
  418. }
  419. if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
  420. $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
  421. dbesc(normalise_link($server_url)));
  422. if ($server) {
  423. $contact['network'] = $server[0]["network"];
  424. } else {
  425. return false;
  426. }
  427. }
  428. // noscrape is really fast so we don't cache the call.
  429. if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
  430. // Use noscrape if possible
  431. $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
  432. if ($server) {
  433. $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
  434. if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
  435. $noscrape = json_decode($noscraperet["body"], true);
  436. if (is_array($noscrape)) {
  437. $contact["network"] = $server[0]["network"];
  438. if (isset($noscrape["fn"])) {
  439. $contact["name"] = $noscrape["fn"];
  440. }
  441. if (isset($noscrape["comm"])) {
  442. $contact["community"] = $noscrape["comm"];
  443. }
  444. if (isset($noscrape["tags"])) {
  445. $keywords = implode(" ", $noscrape["tags"]);
  446. if ($keywords != "") {
  447. $contact["keywords"] = $keywords;
  448. }
  449. }
  450. $location = formatted_location($noscrape);
  451. if ($location) {
  452. $contact["location"] = $location;
  453. }
  454. if (isset($noscrape["dfrn-notify"])) {
  455. $contact["notify"] = $noscrape["dfrn-notify"];
  456. }
  457. // Remove all fields that are not present in the gcontact table
  458. unset($noscrape["fn"]);
  459. unset($noscrape["key"]);
  460. unset($noscrape["homepage"]);
  461. unset($noscrape["comm"]);
  462. unset($noscrape["tags"]);
  463. unset($noscrape["locality"]);
  464. unset($noscrape["region"]);
  465. unset($noscrape["country-name"]);
  466. unset($noscrape["contacts"]);
  467. unset($noscrape["dfrn-request"]);
  468. unset($noscrape["dfrn-confirm"]);
  469. unset($noscrape["dfrn-notify"]);
  470. unset($noscrape["dfrn-poll"]);
  471. // Set the date of the last contact
  472. /// @todo By now the function "update_gcontact" doesn't work with this field
  473. //$contact["last_contact"] = datetime_convert();
  474. $contact = array_merge($contact, $noscrape);
  475. update_gcontact($contact);
  476. if (trim($noscrape["updated"]) != "") {
  477. q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
  478. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  479. logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
  480. return $noscrape["updated"];
  481. }
  482. }
  483. }
  484. }
  485. }
  486. // If we only can poll the feed, then we only do this once a while
  487. if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
  488. logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
  489. update_gcontact($contact);
  490. return $gcontacts[0]["updated"];
  491. }
  492. $data = Probe::uri($profile);
  493. // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
  494. // Then check the other link and delete this one
  495. if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
  496. (normalise_link($profile) == normalise_link($data["alias"])) AND
  497. (normalise_link($profile) != normalise_link($data["url"]))) {
  498. // Delete the old entry
  499. q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
  500. q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
  501. $gcontact = array_merge($gcontacts[0], $data);
  502. $gcontact["server_url"] = $data["baseurl"];
  503. try {
  504. $gcontact = sanitize_gcontact($gcontact);
  505. update_gcontact($gcontact);
  506. poco_last_updated($data["url"], $force);
  507. } catch (Exception $e) {
  508. logger($e->getMessage(), LOGGER_DEBUG);
  509. }
  510. logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
  511. return false;
  512. }
  513. if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
  514. q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
  515. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  516. logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
  517. return false;
  518. }
  519. $contact = array_merge($contact, $data);
  520. $contact["server_url"] = $data["baseurl"];
  521. update_gcontact($contact);
  522. $feedret = z_fetch_url($data["poll"]);
  523. if (!$feedret["success"]) {
  524. q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
  525. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  526. logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
  527. return false;
  528. }
  529. $doc = new DOMDocument();
  530. @$doc->loadXML($feedret["body"]);
  531. $xpath = new DomXPath($doc);
  532. $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
  533. $entries = $xpath->query('/atom:feed/atom:entry');
  534. $last_updated = "";
  535. foreach ($entries AS $entry) {
  536. $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
  537. $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
  538. if ($last_updated < $published)
  539. $last_updated = $published;
  540. if ($last_updated < $updated)
  541. $last_updated = $updated;
  542. }
  543. // Maybe there aren't any entries. Then check if it is a valid feed
  544. if ($last_updated == "") {
  545. if ($xpath->query('/atom:feed')->length > 0) {
  546. $last_updated = NULL_DATE;
  547. }
  548. }
  549. q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
  550. dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
  551. if (($gcontacts[0]["generation"] == 0)) {
  552. q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
  553. dbesc(normalise_link($profile)));
  554. }
  555. logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
  556. return($last_updated);
  557. }
  558. function poco_do_update($created, $updated, $last_failure, $last_contact) {
  559. $now = strtotime(datetime_convert());
  560. if ($updated > $last_contact)
  561. $contact_time = strtotime($updated);
  562. else
  563. $contact_time = strtotime($last_contact);
  564. $failure_time = strtotime($last_failure);
  565. $created_time = strtotime($created);
  566. // If there is no "created" time then use the current time
  567. if ($created_time <= 0)
  568. $created_time = $now;
  569. // If the last contact was less than 24 hours then don't update
  570. if (($now - $contact_time) < (60 * 60 * 24))
  571. return false;
  572. // If the last failure was less than 24 hours then don't update
  573. if (($now - $failure_time) < (60 * 60 * 24))
  574. return false;
  575. // If the last contact was less than a week ago and the last failure is older than a week then don't update
  576. //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
  577. // return false;
  578. // If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
  579. if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
  580. return false;
  581. // If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
  582. if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
  583. return false;
  584. return true;
  585. }
  586. function poco_to_boolean($val) {
  587. if (($val == "true") OR ($val == 1))
  588. return(true);
  589. if (($val == "false") OR ($val == 0))
  590. return(false);
  591. return ($val);
  592. }
  593. /**
  594. * @brief Detect server type (Hubzilla or Friendica) via the poco data
  595. *
  596. * @param object $data POCO data
  597. * @return array Server data
  598. */
  599. function poco_detect_poco_data($data) {
  600. $server = false;
  601. if (!isset($data->entry)) {
  602. return false;
  603. }
  604. if (count($data->entry) == 0) {
  605. return false;
  606. }
  607. if (!isset($data->entry[0]->urls)) {
  608. return false;
  609. }
  610. if (count($data->entry[0]->urls) == 0) {
  611. return false;
  612. }
  613. foreach ($data->entry[0]->urls AS $url) {
  614. if ($url->type == 'zot') {
  615. $server = array();
  616. $server["platform"] = 'Hubzilla';
  617. $server["network"] = NETWORK_DIASPORA;
  618. return $server;
  619. }
  620. }
  621. return false;
  622. }
  623. /**
  624. * @brief Detect server type by using the nodeinfo data
  625. *
  626. * @param string $server_url address of the server
  627. * @return array Server data
  628. */
  629. function poco_fetch_nodeinfo($server_url) {
  630. $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
  631. if (!$serverret["success"]) {
  632. return false;
  633. }
  634. $nodeinfo = json_decode($serverret['body']);
  635. if (!is_object($nodeinfo)) {
  636. return false;
  637. }
  638. if (!is_array($nodeinfo->links)) {
  639. return false;
  640. }
  641. $nodeinfo_url = '';
  642. foreach ($nodeinfo->links AS $link) {
  643. if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
  644. $nodeinfo_url = $link->href;
  645. }
  646. }
  647. if ($nodeinfo_url == '') {
  648. return false;
  649. }
  650. $serverret = z_fetch_url($nodeinfo_url);
  651. if (!$serverret["success"]) {
  652. return false;
  653. }
  654. $nodeinfo = json_decode($serverret['body']);
  655. if (!is_object($nodeinfo)) {
  656. return false;
  657. }
  658. $server = array();
  659. $server['register_policy'] = REGISTER_CLOSED;
  660. if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
  661. $server['register_policy'] = REGISTER_OPEN;
  662. }
  663. if (is_object($nodeinfo->software)) {
  664. if (isset($nodeinfo->software->name)) {
  665. $server['platform'] = $nodeinfo->software->name;
  666. }
  667. if (isset($nodeinfo->software->version)) {
  668. $server['version'] = $nodeinfo->software->version;
  669. // Version numbers on Nodeinfo are presented with additional info, e.g.:
  670. // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
  671. $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
  672. }
  673. }
  674. if (is_object($nodeinfo->metadata)) {
  675. if (isset($nodeinfo->metadata->nodeName)) {
  676. $server['site_name'] = $nodeinfo->metadata->nodeName;
  677. }
  678. }
  679. $diaspora = false;
  680. $friendica = false;
  681. $gnusocial = false;
  682. if (is_array($nodeinfo->protocols->inbound)) {
  683. foreach ($nodeinfo->protocols->inbound AS $inbound) {
  684. if ($inbound == 'diaspora') {
  685. $diaspora = true;
  686. }
  687. if ($inbound == 'friendica') {
  688. $friendica = true;
  689. }
  690. if ($inbound == 'gnusocial') {
  691. $gnusocial = true;
  692. }
  693. }
  694. }
  695. if ($gnusocial) {
  696. $server['network'] = NETWORK_OSTATUS;
  697. }
  698. if ($diaspora) {
  699. $server['network'] = NETWORK_DIASPORA;
  700. }
  701. if ($friendica) {
  702. $server['network'] = NETWORK_DFRN;
  703. }
  704. if (!$server) {
  705. return false;
  706. }
  707. return $server;
  708. }
  709. /**
  710. * @brief Detect server type (Hubzilla or Friendica) via the front page body
  711. *
  712. * @param string $body Front page of the server
  713. * @return array Server data
  714. */
  715. function poco_detect_server_type($body) {
  716. $server = false;
  717. $doc = new \DOMDocument();
  718. @$doc->loadHTML($body);
  719. $xpath = new \DomXPath($doc);
  720. $list = $xpath->query("//meta[@name]");
  721. foreach ($list as $node) {
  722. $attr = array();
  723. if ($node->attributes->length) {
  724. foreach ($node->attributes as $attribute) {
  725. $attr[$attribute->name] = $attribute->value;
  726. }
  727. }
  728. if ($attr['name'] == 'generator') {
  729. $version_part = explode(" ", $attr['content']);
  730. if (count($version_part) == 2) {
  731. if (in_array($version_part[0], array("Friendika", "Friendica"))) {
  732. $server = array();
  733. $server["platform"] = $version_part[0];
  734. $server["version"] = $version_part[1];
  735. $server["network"] = NETWORK_DFRN;
  736. }
  737. }
  738. }
  739. }
  740. if (!$server) {
  741. $list = $xpath->query("//meta[@property]");
  742. foreach ($list as $node) {
  743. $attr = array();
  744. if ($node->attributes->length) {
  745. foreach ($node->attributes as $attribute) {
  746. $attr[$attribute->name] = $attribute->value;
  747. }
  748. }
  749. if ($attr['property'] == 'generator') {
  750. if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
  751. $server = array();
  752. $server["platform"] = $attr['content'];
  753. $server["version"] = "";
  754. $server["network"] = NETWORK_DIASPORA;
  755. }
  756. }
  757. }
  758. }
  759. if (!$server) {
  760. return false;
  761. }
  762. $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
  763. return $server;
  764. }
  765. function poco_check_server($server_url, $network = "", $force = false) {
  766. // Unify the server address
  767. $server_url = trim($server_url, "/");
  768. $server_url = str_replace("/index.php", "", $server_url);
  769. if ($server_url == "")
  770. return false;
  771. $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
  772. if (dbm::is_result($servers)) {
  773. if ($servers[0]["created"] <= NULL_DATE) {
  774. q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
  775. dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
  776. }
  777. $poco = $servers[0]["poco"];
  778. $noscrape = $servers[0]["noscrape"];
  779. if ($network == "")
  780. $network = $servers[0]["network"];
  781. $last_contact = $servers[0]["last_contact"];
  782. $last_failure = $servers[0]["last_failure"];
  783. $version = $servers[0]["version"];
  784. $platform = $servers[0]["platform"];
  785. $site_name = $servers[0]["site_name"];
  786. $info = $servers[0]["info"];
  787. $register_policy = $servers[0]["register_policy"];
  788. if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
  789. logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
  790. return ($last_contact >= $last_failure);
  791. }
  792. } else {
  793. $poco = "";
  794. $noscrape = "";
  795. $version = "";
  796. $platform = "";
  797. $site_name = "";
  798. $info = "";
  799. $register_policy = -1;
  800. $last_contact = NULL_DATE;
  801. $last_failure = NULL_DATE;
  802. }
  803. logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
  804. $failure = false;
  805. $possible_failure = false;
  806. $orig_last_failure = $last_failure;
  807. $orig_last_contact = $last_contact;
  808. // Check if the page is accessible via SSL.
  809. $orig_server_url = $server_url;
  810. $server_url = str_replace("http://", "https://", $server_url);
  811. // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
  812. $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
  813. // Quit if there is a timeout.
  814. // But we want to make sure to only quit if we are mostly sure that this server url fits.
  815. if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
  816. ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
  817. logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
  818. return false;
  819. }
  820. // Maybe the page is unencrypted only?
  821. $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
  822. if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
  823. $server_url = str_replace("https://", "http://", $server_url);
  824. // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
  825. $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
  826. // Quit if there is a timeout
  827. if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
  828. logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
  829. return false;
  830. }
  831. $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
  832. }
  833. if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
  834. // Workaround for bad configured servers (known nginx problem)
  835. if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
  836. $last_failure = datetime_convert();
  837. $failure = true;
  838. }
  839. $possible_failure = true;
  840. } elseif ($network == NETWORK_DIASPORA)
  841. $last_contact = datetime_convert();
  842. // If the server has no possible failure we reset the cached data
  843. if (!$possible_failure) {
  844. $version = "";
  845. $platform = "";
  846. $site_name = "";
  847. $info = "";
  848. $register_policy = -1;
  849. }
  850. // Look for poco
  851. if (!$failure) {
  852. $serverret = z_fetch_url($server_url."/poco");
  853. if ($serverret["success"]) {
  854. $data = json_decode($serverret["body"]);
  855. if (isset($data->totalResults)) {
  856. $poco = $server_url."/poco";
  857. $last_contact = datetime_convert();
  858. $server = poco_detect_poco_data($data);
  859. if ($server) {
  860. $platform = $server['platform'];
  861. $network = $server['network'];
  862. $version = '';
  863. $site_name = '';
  864. }
  865. }
  866. }
  867. }
  868. if (!$failure) {
  869. // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
  870. $serverret = z_fetch_url($server_url);
  871. if (!$serverret["success"] OR ($serverret["body"] == "")) {
  872. $last_failure = datetime_convert();
  873. $failure = true;
  874. } else {
  875. $server = poco_detect_server_type($serverret["body"]);
  876. if ($server) {
  877. $platform = $server['platform'];
  878. $network = $server['network'];
  879. $version = $server['version'];
  880. $site_name = $server['site_name'];
  881. $last_contact = datetime_convert();
  882. }
  883. $lines = explode("\n",$serverret["header"]);
  884. if(count($lines)) {
  885. foreach($lines as $line) {
  886. $line = trim($line);
  887. if(stristr($line,'X-Diaspora-Version:')) {
  888. $platform = "Diaspora";
  889. $version = trim(str_replace("X-Diaspora-Version:", "", $line));
  890. $version = trim(str_replace("x-diaspora-version:", "", $version));
  891. $network = NETWORK_DIASPORA;
  892. $versionparts = explode("-", $version);
  893. $version = $versionparts[0];
  894. $last_contact = datetime_convert();
  895. }
  896. if(stristr($line,'Server: Mastodon')) {
  897. $platform = "Mastodon";
  898. $network = NETWORK_OSTATUS;
  899. // Mastodon doesn't reveal version numbers
  900. $version = "";
  901. $last_contact = datetime_convert();
  902. }
  903. }
  904. }
  905. }
  906. }
  907. if (!$failure AND ($poco == "")) {
  908. // Test for Statusnet
  909. // Will also return data for Friendica and GNU Social - but it will be overwritten later
  910. // The "not implemented" is a special treatment for really, really old Friendica versions
  911. $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
  912. if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
  913. ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
  914. $platform = "StatusNet";
  915. // Remove junk that some GNU Social servers return
  916. $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
  917. $version = trim($version, '"');
  918. $network = NETWORK_OSTATUS;
  919. $last_contact = datetime_convert();
  920. }
  921. // Test for GNU Social
  922. $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
  923. if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
  924. ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
  925. $platform = "GNU Social";
  926. // Remove junk that some GNU Social servers return
  927. $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
  928. $version = trim($version, '"');
  929. $network = NETWORK_OSTATUS;
  930. $last_contact = datetime_convert();
  931. }
  932. }
  933. if (!$failure) {
  934. // Test for Hubzilla, Redmatrix or Friendica
  935. $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
  936. if ($serverret["success"]) {
  937. $data = json_decode($serverret["body"]);
  938. if (isset($data->site->server)) {
  939. $last_contact = datetime_convert();
  940. if (isset($data->site->platform)) {
  941. $platform = $data->site->platform->PLATFORM_NAME;
  942. $version = $data->site->platform->STD_VERSION;
  943. $network = NETWORK_DIASPORA;
  944. }
  945. if (isset($data->site->BlaBlaNet)) {
  946. $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
  947. $version = $data->site->BlaBlaNet->STD_VERSION;
  948. $network = NETWORK_DIASPORA;
  949. }
  950. if (isset($data->site->hubzilla)) {
  951. $platform = $data->site->hubzilla->PLATFORM_NAME;
  952. $version = $data->site->hubzilla->RED_VERSION;
  953. $network = NETWORK_DIASPORA;
  954. }
  955. if (isset($data->site->redmatrix)) {
  956. if (isset($data->site->redmatrix->PLATFORM_NAME))
  957. $platform = $data->site->redmatrix->PLATFORM_NAME;
  958. elseif (isset($data->site->redmatrix->RED_PLATFORM))
  959. $platform = $data->site->redmatrix->RED_PLATFORM;
  960. $version = $data->site->redmatrix->RED_VERSION;
  961. $network = NETWORK_DIASPORA;
  962. }
  963. if (isset($data->site->friendica)) {
  964. $platform = $data->site->friendica->FRIENDICA_PLATFORM;
  965. $version = $data->site->friendica->FRIENDICA_VERSION;
  966. $network = NETWORK_DFRN;
  967. }
  968. $site_name = $data->site->name;
  969. $data->site->closed = poco_to_boolean($data->site->closed);
  970. $data->site->private = poco_to_boolean($data->site->private);
  971. $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
  972. if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
  973. $register_policy = REGISTER_APPROVE;
  974. elseif (!$data->site->closed AND !$data->site->private)
  975. $register_policy = REGISTER_OPEN;
  976. else
  977. $register_policy = REGISTER_CLOSED;
  978. }
  979. }
  980. }
  981. // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
  982. if (!$failure) {
  983. $serverret = z_fetch_url($server_url."/statistics.json");
  984. if ($serverret["success"]) {
  985. $data = json_decode($serverret["body"]);
  986. if (isset($data->version)) {
  987. $version = $data->version;
  988. // Version numbers on statistics.json are presented with additional info, e.g.:
  989. // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
  990. $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
  991. }
  992. $site_name = $data->name;
  993. if (isset($data->network)) {
  994. $platform = $data->network;
  995. }
  996. if ($platform == "Diaspora") {
  997. $network = NETWORK_DIASPORA;
  998. }
  999. if ($data->registrations_open) {
  1000. $register_policy = REGISTER_OPEN;
  1001. } else {
  1002. $register_policy = REGISTER_CLOSED;
  1003. }
  1004. if (isset($data->version))
  1005. $last_contact = datetime_convert();
  1006. }
  1007. }
  1008. // Query nodeinfo. Working for (at least) Diaspora and Friendica.
  1009. if (!$failure) {
  1010. $server = poco_fetch_nodeinfo($server_url);
  1011. if ($server) {
  1012. $register_policy = $server['register_policy'];
  1013. if (isset($server['platform'])) {
  1014. $platform = $server['platform'];
  1015. }
  1016. if (isset($server['network'])) {
  1017. $network = $server['network'];
  1018. }
  1019. if (isset($server['version'])) {
  1020. $version = $server['version'];
  1021. }
  1022. if (isset($server['site_name'])) {
  1023. $site_name = $server['site_name'];
  1024. }
  1025. $last_contact = datetime_convert();
  1026. }
  1027. }
  1028. // Check for noscrape
  1029. // Friendica servers could be detected as OStatus servers
  1030. if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
  1031. $serverret = z_fetch_url($server_url."/friendica/json");
  1032. if (!$serverret["success"])
  1033. $serverret = z_fetch_url($server_url."/friendika/json");
  1034. if ($serverret["success"]) {
  1035. $data = json_decode($serverret["body"]);
  1036. if (isset($data->version)) {
  1037. $last_contact = datetime_convert();
  1038. $network = NETWORK_DFRN;
  1039. $noscrape = $data->no_scrape_url;
  1040. $version = $data->version;
  1041. $site_name = $data->site_name;
  1042. $info = $data->info;
  1043. $register_policy_str = $data->register_policy;
  1044. $platform = $data->platform;
  1045. switch ($register_policy_str) {
  1046. case "REGISTER_CLOSED":
  1047. $register_policy = REGISTER_CLOSED;
  1048. break;
  1049. case "REGISTER_APPROVE":
  1050. $register_policy = REGISTER_APPROVE;
  1051. break;
  1052. case "REGISTER_OPEN":
  1053. $register_policy = REGISTER_OPEN;
  1054. break;
  1055. }
  1056. }
  1057. }
  1058. }
  1059. if ($possible_failure AND !$failure) {
  1060. $last_failure = datetime_convert();
  1061. $failure = true;
  1062. }
  1063. if ($failure) {
  1064. $last_contact = $orig_last_contact;
  1065. } else {
  1066. $last_failure = $orig_last_failure;
  1067. }
  1068. if (($last_contact <= $last_failure) AND !$failure) {
  1069. logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
  1070. } else if (($last_contact >= $last_failure) AND $failure) {
  1071. logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
  1072. }
  1073. // Check again if the server exists
  1074. $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
  1075. $version = strip_tags($version);
  1076. $site_name = strip_tags($site_name);
  1077. $info = strip_tags($info);
  1078. $platform = strip_tags($platform);
  1079. if ($servers) {
  1080. q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
  1081. `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
  1082. dbesc($server_url),
  1083. dbesc($version),
  1084. dbesc($site_name),
  1085. dbesc($info),
  1086. intval($register_policy),
  1087. dbesc($poco),
  1088. dbesc($noscrape),
  1089. dbesc($network),
  1090. dbesc($platform),
  1091. dbesc($last_contact),
  1092. dbesc($last_failure),
  1093. dbesc(normalise_link($server_url))
  1094. );
  1095. } elseif (!$failure) {
  1096. q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
  1097. VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
  1098. dbesc($server_url),
  1099. dbesc(normalise_link($server_url)),
  1100. dbesc($version),
  1101. dbesc($site_name),
  1102. dbesc($info),
  1103. intval($register_policy),
  1104. dbesc($poco),
  1105. dbesc($noscrape),
  1106. dbesc($network),
  1107. dbesc($platform),
  1108. dbesc(datetime_convert()),
  1109. dbesc($last_contact),
  1110. dbesc($last_failure),
  1111. dbesc(datetime_convert())
  1112. );
  1113. }
  1114. logger("End discovery for server ".$server_url, LOGGER_DEBUG);
  1115. return !$failure;
  1116. }
  1117. function count_common_friends($uid,$cid) {
  1118. $r = q("SELECT count(*) as `total`
  1119. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  1120. WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
  1121. ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
  1122. AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
  1123. intval($cid),
  1124. intval($uid),
  1125. intval($uid),
  1126. intval($cid)
  1127. );
  1128. // logger("count_common_friends: $uid $cid {$r[0]['total']}");
  1129. if (dbm::is_result($r))
  1130. return $r[0]['total'];
  1131. return 0;
  1132. }
  1133. function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
  1134. if($shuffle)
  1135. $sql_extra = " order by rand() ";
  1136. else
  1137. $sql_extra = " order by `gcontact`.`name` asc ";
  1138. $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
  1139. FROM `glink`
  1140. INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
  1141. INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
  1142. WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
  1143. AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
  1144. AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
  1145. AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
  1146. $sql_extra LIMIT %d, %d",
  1147. intval($cid),
  1148. intval($uid),
  1149. intval($uid),
  1150. intval($cid),
  1151. intval($start),
  1152. intval($limit)
  1153. );
  1154. return $r;
  1155. }
  1156. function count_common_friends_zcid($uid,$zcid) {
  1157. $r = q("SELECT count(*) as `total`
  1158. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  1159. where `glink`.`zcid` = %d
  1160. and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
  1161. intval($zcid),
  1162. intval($uid)
  1163. );
  1164. if (dbm::is_result($r))
  1165. return $r[0]['total'];
  1166. return 0;
  1167. }
  1168. function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
  1169. if($shuffle)
  1170. $sql_extra = " order by rand() ";
  1171. else
  1172. $sql_extra = " order by `gcontact`.`name` asc ";
  1173. $r = q("SELECT `gcontact`.*
  1174. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  1175. where `glink`.`zcid` = %d
  1176. and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
  1177. $sql_extra limit %d, %d",
  1178. intval($zcid),
  1179. intval($uid),
  1180. intval($start),
  1181. intval($limit)
  1182. );
  1183. return $r;
  1184. }
  1185. function count_all_friends($uid,$cid) {
  1186. $r = q("SELECT count(*) as `total`
  1187. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  1188. where `glink`.`cid` = %d and `glink`.`uid` = %d AND
  1189. ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
  1190. intval($cid),
  1191. intval($uid)
  1192. );
  1193. if (dbm::is_result($r))
  1194. return $r[0]['total'];
  1195. return 0;
  1196. }
  1197. function all_friends($uid,$cid,$start = 0, $limit = 80) {
  1198. $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
  1199. FROM `glink`
  1200. INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  1201. LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
  1202. WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
  1203. ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
  1204. ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
  1205. intval($uid),
  1206. intval($cid),
  1207. intval($uid),
  1208. intval($start),
  1209. intval($limit)
  1210. );
  1211. return $r;
  1212. }
  1213. function suggestion_query($uid, $start = 0, $limit = 80) {
  1214. if (!$uid) {
  1215. return array();
  1216. }
  1217. // Uncommented because the result of the queries are to big to store it in the cache.
  1218. // We need to decide if we want to change the db column type or if we want to delete it.
  1219. // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
  1220. // if (!is_null($list)) {
  1221. // return $list;
  1222. // }
  1223. $network = array(NETWORK_DFRN);
  1224. if (get_config('system','diaspora_enabled'))
  1225. $network[] = NETWORK_DIASPORA;
  1226. if (!get_config('system','ostatus_disabled'))
  1227. $network[] = NETWORK_OSTATUS;
  1228. $sql_network = implode("', '", $network);
  1229. $sql_network = "'".$sql_network."'";
  1230. /// @todo This query is really slow
  1231. // By now we cache the data for five minutes
  1232. $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
  1233. INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
  1234. where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
  1235. AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
  1236. AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
  1237. AND `gcontact`.`updated` >= '%s'
  1238. AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
  1239. AND `gcontact`.`network` IN (%s)
  1240. GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
  1241. intval($uid),
  1242. intval($uid),
  1243. intval($uid),
  1244. intval($uid),
  1245. dbesc(NULL_DATE),
  1246. $sql_network,
  1247. intval($start),
  1248. intval($limit)
  1249. );
  1250. if (dbm::is_result($r) && count($r) >= ($limit -1)) {
  1251. // Uncommented because the result of the queries are to big to store it in the cache.
  1252. // We need to decide if we want to change the db column type or if we want to delete it.
  1253. // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
  1254. return $r;
  1255. }
  1256. $r2 = q("SELECT gcontact.* FROM gcontact
  1257. INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
  1258. WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
  1259. AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
  1260. AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
  1261. AND `gcontact`.`updated` >= '%s'
  1262. AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
  1263. AND `gcontact`.`network` IN (%s)
  1264. ORDER BY rand() LIMIT %d, %d",
  1265. intval($uid),
  1266. intval($uid),
  1267. intval($uid),
  1268. dbesc(NULL_DATE),
  1269. $sql_network,
  1270. intval($start),
  1271. intval($limit)
  1272. );
  1273. $list = array();
  1274. foreach ($r2 AS $suggestion)
  1275. $list[$suggestion["nurl"]] = $suggestion;
  1276. foreach ($r AS $suggestion)
  1277. $list[$suggestion["nurl"]] = $suggestion;
  1278. while (sizeof($list) > ($limit))
  1279. array_pop($list);
  1280. // Uncommented because the result of the queries are to big to store it in the cache.
  1281. // We need to decide if we want to change the db column type or if we want to delete it.
  1282. // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
  1283. return $list;
  1284. }
  1285. function update_suggestions() {
  1286. $a = get_app();
  1287. $done = array();
  1288. /// @TODO Check if it is really neccessary to poll the own server
  1289. poco_load(0,0,0,App::get_baseurl() . '/poco');
  1290. $done[] = App::get_baseurl() . '/poco';
  1291. if (strlen(get_config('system','directory'))) {
  1292. $x = fetch_url(get_server()."/pubsites");
  1293. if ($x) {
  1294. $j = json_decode($x);
  1295. if ($j->entries) {
  1296. foreach ($j->entries as $entry) {
  1297. poco_check_server($entry->url);
  1298. $url = $entry->url . '/poco';
  1299. if (! in_array($url,$done)) {
  1300. poco_load(0,0,0,$entry->url . '/poco');
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
  1307. $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
  1308. dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
  1309. );
  1310. if (dbm::is_result($r)) {
  1311. foreach ($r as $rr) {
  1312. $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
  1313. if(! in_array($base,$done))
  1314. poco_load(0,0,0,$base);
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * @brief Fetch server list from remote servers and adds them when they are new.
  1320. *
  1321. * @param string $poco URL to the POCO endpoint
  1322. */
  1323. function poco_fetch_serverlist($poco) {
  1324. $serverret = z_fetch_url($poco."/@server");
  1325. if (!$serverret["success"]) {
  1326. return;
  1327. }
  1328. $serverlist = json_decode($serverret['body']);
  1329. if (!is_array($serverlist)) {
  1330. return;
  1331. }
  1332. foreach ($serverlist AS $server) {
  1333. $server_url = str_replace("/index.php", "", $server->url);
  1334. $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
  1335. if (!dbm::is_result($r)) {
  1336. logger("Call server check for server ".$server_url, LOGGER_DEBUG);
  1337. proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
  1338. }
  1339. }
  1340. }
  1341. function poco_discover_federation() {
  1342. $last = get_config('poco','last_federation_discovery');
  1343. if ($last) {
  1344. $next = $last + (24 * 60 * 60);
  1345. if($next > time())
  1346. return;
  1347. }
  1348. // Discover Friendica, Hubzilla and Diaspora servers
  1349. $serverdata = fetch_url("http://the-federation.info/pods.json");
  1350. if ($serverdata) {
  1351. $servers = json_decode($serverdata);
  1352. foreach ($servers->pods AS $server) {
  1353. proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
  1354. }
  1355. }
  1356. // Currently disabled, since the service isn't available anymore.
  1357. // It is not removed since I hope that there will be a successor.
  1358. // Discover GNU Social Servers.
  1359. //if (!get_config('system','ostatus_disabled')) {
  1360. // $serverdata = "http://gstools.org/api/get_open_instances/";
  1361. // $result = z_fetch_url($serverdata);
  1362. // if ($result["success"]) {
  1363. // $servers = json_decode($result["body"]);
  1364. // foreach($servers->data AS $server)
  1365. // poco_check_server($server->instance_address);
  1366. // }
  1367. //}
  1368. set_config('poco','last_federation_discovery', time());
  1369. }
  1370. function poco_discover_single_server($id) {
  1371. $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
  1372. if (!dbm::is_result($r)) {
  1373. return false;
  1374. }
  1375. $server = $r[0];
  1376. // Discover new servers out there (Works from Friendica version 3.5.2)
  1377. poco_fetch_serverlist($server["poco"]);
  1378. // Fetch all users from the other server
  1379. $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
  1380. logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
  1381. $retdata = z_fetch_url($url);
  1382. if ($retdata["success"]) {
  1383. $data = json_decode($retdata["body"]);
  1384. poco_discover_server($data, 2);
  1385. if (get_config('system','poco_discovery') > 1) {
  1386. $timeframe = get_config('system','poco_discovery_since');
  1387. if ($timeframe == 0) {
  1388. $timeframe = 30;
  1389. }
  1390. $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
  1391. // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
  1392. $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
  1393. $success = false;
  1394. $retdata = z_fetch_url($url);
  1395. if ($retdata["success"]) {
  1396. logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
  1397. $success = poco_discover_server(json_decode($retdata["body"]));
  1398. }
  1399. if (!$success AND (get_config('system','poco_discovery') > 2)) {
  1400. logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
  1401. poco_discover_server_users($data, $server);
  1402. }
  1403. }
  1404. q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
  1405. return true;
  1406. } else {
  1407. // If the server hadn't replied correctly, then force a sanity check
  1408. poco_check_server($server["url"], $server["network"], true);
  1409. // If we couldn't reach the server, we will try it some time later
  1410. q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
  1411. return false;
  1412. }
  1413. }
  1414. function poco_discover($complete = false) {
  1415. // Update the server list
  1416. poco_discover_federation();
  1417. $no_of_queries = 5;
  1418. $requery_days = intval(get_config("system", "poco_requery_days"));
  1419. if ($requery_days == 0) {
  1420. $requery_days = 7;
  1421. }
  1422. $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
  1423. $r = q("SELECT `id`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
  1424. if (dbm::is_result($r)) {
  1425. foreach ($r AS $server) {
  1426. if (!poco_check_server($server["url"], $server["network"])) {
  1427. // The server is not reachable? Okay, then we will try it later
  1428. q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
  1429. continue;
  1430. }
  1431. logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
  1432. proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
  1433. if (!$complete AND (--$no_of_queries == 0)) {
  1434. break;
  1435. }
  1436. }
  1437. }
  1438. }
  1439. function poco_discover_server_users($data, $server) {
  1440. if (!isset($data->entry))