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.

2348 lines
69 KiB

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