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.

2341 lines
69 KiB

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