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.

2349 lines
69KB

  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. require_once('include/datetime.php');
  12. require_once("include/Scrape.php");
  13. require_once("include/network.php");
  14. require_once("include/html2bbcode.php");
  15. require_once("include/Contact.php");
  16. require_once("include/Photo.php");
  17. /**
  18. * @brief Fetch POCO data
  19. *
  20. * @param integer $cid Contact ID
  21. * @param integer $uid User ID
  22. * @param integer $zcid Global Contact ID
  23. * @param integer $url POCO address that should be polled
  24. *
  25. * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
  26. * and add the entries to the gcontact (Global Contact) table, or update existing entries
  27. * if anything (name or photo) has changed.
  28. * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
  29. *
  30. * Once the global contact is stored add (if necessary) the contact linkage which associates
  31. * the given uid, cid to the global contact entry. There can be many uid/cid combinations
  32. * pointing to the same global contact id.
  33. *
  34. */
  35. function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
  36. // Call the function "poco_load_worker" via the worker
  37. proc_run(PRIORITY_LOW, "include/discover_poco.php", "poco_load", intval($cid), intval($uid), intval($zcid), base64_encode($url));
  38. }
  39. /**
  40. * @brief Fetch POCO data from the worker
  41. *
  42. * @param integer $cid Contact ID
  43. * @param integer $uid User ID
  44. * @param integer $zcid Global Contact ID
  45. * @param integer $url POCO address that should be polled
  46. *
  47. */
  48. function poco_load_worker($cid, $uid, $zcid, $url) {
  49. $a = get_app();
  50. if($cid) {
  51. if((! $url) || (! $uid)) {
  52. $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
  53. intval($cid)
  54. );
  55. if (dbm::is_result($r)) {
  56. $url = $r[0]['poco'];
  57. $uid = $r[0]['uid'];
  58. }
  59. }
  60. if(! $uid)
  61. return;
  62. }
  63. if(! $url)
  64. return;
  65. $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') ;
  66. logger('poco_load: ' . $url, LOGGER_DEBUG);
  67. $s = fetch_url($url);
  68. logger('poco_load: returns ' . $s, LOGGER_DATA);
  69. logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
  70. if(($a->get_curl_code() > 299) || (! $s))
  71. return;
  72. $j = json_decode($s);
  73. logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
  74. if(! isset($j->entry))
  75. return;
  76. $total = 0;
  77. foreach($j->entry as $entry) {
  78. $total ++;
  79. $profile_url = '';
  80. $profile_photo = '';
  81. $connect_url = '';
  82. $name = '';
  83. $network = '';
  84. $updated = NULL_DATE;
  85. $location = '';
  86. $about = '';
  87. $keywords = '';
  88. $gender = '';
  89. $contact_type = -1;
  90. $generation = 0;
  91. $name = $entry->displayName;
  92. if (isset($entry->urls)) {
  93. foreach ($entry->urls as $url) {
  94. if ($url->type == 'profile') {
  95. $profile_url = $url->value;
  96. continue;
  97. }
  98. if ($url->type == 'webfinger') {
  99. $connect_url = str_replace('acct:' , '', $url->value);
  100. continue;
  101. }
  102. }
  103. }
  104. if (isset($entry->photos)) {
  105. foreach ($entry->photos as $photo) {
  106. if ($photo->type == 'profile') {
  107. $profile_photo = $photo->value;
  108. continue;
  109. }
  110. }
  111. }
  112. if (isset($entry->updated)) {
  113. $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
  114. }
  115. if (isset($entry->network)) {
  116. $network = $entry->network;
  117. }
  118. if (isset($entry->currentLocation)) {
  119. $location = $entry->currentLocation;
  120. }
  121. if (isset($entry->aboutMe)) {
  122. $about = html2bbcode($entry->aboutMe);
  123. }
  124. if (isset($entry->gender)) {
  125. $gender = $entry->gender;
  126. }
  127. if (isset($entry->generation) AND ($entry->generation > 0)) {
  128. $generation = ++$entry->generation;
  129. }
  130. if (isset($entry->tags)) {
  131. foreach($entry->tags as $tag) {
  132. $keywords = implode(", ", $tag);
  133. }
  134. }
  135. if (isset($entry->contactType) AND ($entry->contactType >= 0))
  136. $contact_type = $entry->contactType;
  137. $gcontact = array("url" => $profile_url,
  138. "name" => $name,
  139. "network" => $network,
  140. "photo" => $profile_photo,
  141. "about" => $about,
  142. "location" => $location,
  143. "gender" => $gender,
  144. "keywords" => $keywords,
  145. "connect" => $connect_url,
  146. "updated" => $updated,
  147. "contact-type" => $contact_type,
  148. "generation" => $generation);
  149. try {
  150. $gcontact = sanitize_gcontact($gcontact);
  151. $gcid = update_gcontact($gcontact);
  152. link_gcontact($gcid, $uid, $cid, $zcid);
  153. } catch (Exception $e) {
  154. logger($e->getMessage(), LOGGER_DEBUG);
  155. }
  156. }
  157. logger("poco_load: loaded $total entries",LOGGER_DEBUG);
  158. q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
  159. intval($cid),
  160. intval($uid),
  161. intval($zcid)
  162. );
  163. }
  164. /**
  165. * @brief Sanitize the given gcontact data
  166. *
  167. * @param array $gcontact array with gcontact data
  168. * @throw Exception
  169. *
  170. * Generation:
  171. * 0: No definition
  172. * 1: Profiles on this server
  173. * 2: Contacts of profiles on this server
  174. * 3: Contacts of contacts of profiles on this server
  175. * 4: ...
  176. *
  177. */
  178. function sanitize_gcontact($gcontact) {
  179. if ($gcontact['url'] == "") {
  180. throw new Exception('URL is empty');
  181. }
  182. $urlparts = parse_url($gcontact['url']);
  183. if (!isset($urlparts["scheme"])) {
  184. throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
  185. }
  186. if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
  187. "identi.ca", "alpha.app.net"))) {
  188. throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
  189. }
  190. // Don't store the statusnet connector as network
  191. // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
  192. if ($gcontact['network'] == NETWORK_STATUSNET) {
  193. $gcontact['network'] = "";
  194. }
  195. // Assure that there are no parameter fragments in the profile url
  196. if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
  197. $gcontact['url'] = clean_contact_url($gcontact['url']);
  198. }
  199. $alternate = poco_alternate_ostatus_url($gcontact['url']);
  200. // The global contacts should contain the original picture, not the cached one
  201. if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
  202. $gcontact['photo'] = "";
  203. }
  204. if (!isset($gcontact['network'])) {
  205. $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
  206. dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
  207. );
  208. if (dbm::is_result($r)) {
  209. $gcontact['network'] = $r[0]["network"];
  210. }
  211. if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
  212. $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
  213. dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
  214. );
  215. if (dbm::is_result($r)) {
  216. $gcontact['network'] = $r[0]["network"];
  217. }
  218. }
  219. }
  220. $gcontact['server_url'] = '';
  221. $gcontact['network'] = '';
  222. $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
  223. dbesc(normalise_link($gcontact['url']))
  224. );
  225. if (count($x)) {
  226. if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
  227. $gcontact['network'] = $x[0]["network"];
  228. }
  229. if ($gcontact['updated'] <= NULL_DATE) {
  230. $gcontact['updated'] = $x[0]["updated"];
  231. }
  232. if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
  233. $gcontact['server_url'] = $x[0]["server_url"];
  234. }
  235. if (!isset($gcontact['addr'])) {
  236. $gcontact['addr'] = $x[0]["addr"];
  237. }
  238. }
  239. if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
  240. AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
  241. $data = Probe::uri($gcontact['url']);
  242. if ($data["network"] == NETWORK_PHANTOM) {
  243. throw new Exception('Probing for URL '.$gcontact['url'].' failed');
  244. }
  245. $orig_profile = $gcontact['url'];
  246. $gcontact["server_url"] = $data["baseurl"];
  247. $gcontact = array_merge($gcontact, $data);
  248. if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
  249. // Delete the old entry - if it exists
  250. $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
  251. if ($r) {
  252. q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
  253. q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
  254. }
  255. }
  256. }
  257. if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
  258. throw new Exception('No name and photo for URL '.$gcontact['url']);
  259. }
  260. if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
  261. throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
  262. }
  263. if (!isset($gcontact['server_url'])) {
  264. // We check the server url to be sure that it is a real one
  265. $server_url = poco_detect_server($gcontact['url']);
  266. // We are now sure that it is a correct URL. So we use it in the future
  267. if ($server_url != "") {
  268. $gcontact['server_url'] = $server_url;
  269. }
  270. }
  271. // The server URL doesn't seem to be valid, so we don't store it.
  272. if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
  273. $gcontact['server_url'] = "";
  274. }
  275. return $gcontact;
  276. }
  277. /**
  278. * @brief Link the gcontact entry with user, contact and global contact
  279. *
  280. * @param integer $gcid Global contact ID
  281. * @param integer $cid Contact ID
  282. * @param integer $uid User ID
  283. * @param integer $zcid Global Contact ID
  284. * *
  285. */
  286. function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
  287. if ($gcid <= 0) {
  288. return;
  289. }
  290. $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
  291. intval($cid),
  292. intval($uid),
  293. intval($gcid),
  294. intval($zcid)
  295. );
  296. if (!dbm::is_result($r)) {
  297. q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
  298. intval($cid),
  299. intval($uid),
  300. intval($gcid),
  301. intval($zcid),
  302. dbesc(datetime_convert())
  303. );
  304. } else {
  305. q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
  306. dbesc(datetime_convert()),
  307. intval($cid),
  308. intval($uid),
  309. intval($gcid),
  310. intval($zcid)
  311. );
  312. }
  313. }
  314. function poco_reachable($profile, $server = "", $network = "", $force = false) {
  315. if ($server == "")
  316. $server = poco_detect_server($profile);
  317. if ($server == "")
  318. return true;
  319. return poco_check_server($server, $network, $force);
  320. }
  321. function poco_detect_server($profile) {
  322. // Try to detect the server path based upon some known standard paths
  323. $server_url = "";
  324. if ($server_url == "") {
  325. $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
  326. if ($friendica != $profile) {
  327. $server_url = $friendica;
  328. $network = NETWORK_DFRN;
  329. }
  330. }
  331. if ($server_url == "") {
  332. $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
  333. if ($diaspora != $profile) {
  334. $server_url = $diaspora;
  335. $network = NETWORK_DIASPORA;
  336. }
  337. }
  338. if ($server_url == "") {
  339. $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
  340. if ($red != $profile) {
  341. $server_url = $red;
  342. $network = NETWORK_DIASPORA;
  343. }
  344. }
  345. // Mastodon
  346. if ($server_url == "") {
  347. $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
  348. if ($mastodon != $profile) {
  349. $server_url = $mastodon;
  350. $network = NETWORK_OSTATUS;
  351. }
  352. }
  353. // Numeric OStatus variant
  354. if ($server_url == "") {
  355. $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
  356. if ($ostatus != $profile) {
  357. $server_url = $ostatus;
  358. $network = NETWORK_OSTATUS;
  359. }
  360. }
  361. // Wild guess
  362. if ($server_url == "") {
  363. $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
  364. if ($base != $profile) {
  365. $server_url = $base;
  366. $network = NETWORK_PHANTOM;
  367. }
  368. }
  369. if ($server_url == "") {
  370. return "";
  371. }
  372. $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
  373. dbesc(normalise_link($server_url)));
  374. if (dbm::is_result($r)) {
  375. return $server_url;
  376. }
  377. // Fetch the host-meta to check if this really is a server
  378. $serverret = z_fetch_url($server_url."/.well-known/host-meta");
  379. if (!$serverret["success"]) {
  380. return "";
  381. }
  382. return $server_url;
  383. }
  384. function poco_alternate_ostatus_url($url) {
  385. return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
  386. }
  387. function poco_last_updated($profile, $force = false) {
  388. $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
  389. dbesc(normalise_link($profile)));
  390. if (!dbm::is_result($gcontacts)) {
  391. return false;
  392. }
  393. $contact = array("url" => $profile);
  394. if ($gcontacts[0]["created"] <= NULL_DATE) {
  395. $contact['created'] = datetime_convert();
  396. }
  397. if ($force) {
  398. $server_url = normalise_link(poco_detect_server($profile));
  399. }
  400. if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
  401. $server_url = $gcontacts[0]["server_url"];
  402. }
  403. if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
  404. $server_url = normalise_link(poco_detect_server($profile));
  405. }
  406. if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
  407. logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
  408. return false;
  409. }
  410. if ($server_url != "") {
  411. if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
  412. if ($force) {
  413. q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
  414. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  415. }
  416. logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
  417. return false;
  418. }
  419. $contact['server_url'] = $server_url;
  420. }
  421. if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
  422. $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
  423. dbesc(normalise_link($server_url)));
  424. if ($server) {
  425. $contact['network'] = $server[0]["network"];
  426. } else {
  427. return false;
  428. }
  429. }
  430. // noscrape is really fast so we don't cache the call.
  431. if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
  432. // Use noscrape if possible
  433. $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
  434. if ($server) {
  435. $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
  436. if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
  437. $noscrape = json_decode($noscraperet["body"], true);
  438. if (is_array($noscrape)) {
  439. $contact["network"] = $server[0]["network"];
  440. if (isset($noscrape["fn"])) {
  441. $contact["name"] = $noscrape["fn"];
  442. }
  443. if (isset($noscrape["comm"])) {
  444. $contact["community"] = $noscrape["comm"];
  445. }
  446. if (isset($noscrape["tags"])) {
  447. $keywords = implode(" ", $noscrape["tags"]);
  448. if ($keywords != "") {
  449. $contact["keywords"] = $keywords;
  450. }
  451. }
  452. $location = formatted_location($noscrape);
  453. if ($location) {
  454. $contact["location"] = $location;
  455. }
  456. if (isset($noscrape["dfrn-notify"])) {
  457. $contact["notify"] = $noscrape["dfrn-notify"];
  458. }
  459. // Remove all fields that are not present in the gcontact table
  460. unset($noscrape["fn"]);
  461. unset($noscrape["key"]);
  462. unset($noscrape["homepage"]);
  463. unset($noscrape["comm"]);
  464. unset($noscrape["tags"]);
  465. unset($noscrape["locality"]);
  466. unset($noscrape["region"]);
  467. unset($noscrape["country-name"]);
  468. unset($noscrape["contacts"]);
  469. unset($noscrape["dfrn-request"]);
  470. unset($noscrape["dfrn-confirm"]);
  471. unset($noscrape["dfrn-notify"]);
  472. unset($noscrape["dfrn-poll"]);
  473. // Set the date of the last contact
  474. /// @todo By now the function "update_gcontact" doesn't work with this field
  475. //$contact["last_contact"] = datetime_convert();
  476. $contact = array_merge($contact, $noscrape);
  477. update_gcontact($contact);
  478. if (trim($noscrape["updated"]) != "") {
  479. q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
  480. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  481. logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
  482. return $noscrape["updated"];
  483. }
  484. }
  485. }
  486. }
  487. }
  488. // If we only can poll the feed, then we only do this once a while
  489. if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
  490. logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
  491. update_gcontact($contact);
  492. return $gcontacts[0]["updated"];
  493. }
  494. $data = Probe::uri($profile);
  495. // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
  496. // Then check the other link and delete this one
  497. if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
  498. (normalise_link($profile) == normalise_link($data["alias"])) AND
  499. (normalise_link($profile) != normalise_link($data["url"]))) {
  500. // Delete the old entry
  501. q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
  502. q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
  503. $gcontact = array_merge($gcontacts[0], $data);
  504. $gcontact["server_url"] = $data["baseurl"];
  505. try {
  506. $gcontact = sanitize_gcontact($gcontact);
  507. update_gcontact($gcontact);
  508. poco_last_updated($data["url"], $force);
  509. } catch (Exception $e) {
  510. logger($e->getMessage(), LOGGER_DEBUG);
  511. }
  512. logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
  513. return false;
  514. }
  515. if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
  516. q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
  517. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  518. logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
  519. return false;
  520. }
  521. $contact = array_merge($contact, $data);
  522. $contact["server_url"] = $data["baseurl"];
  523. update_gcontact($contact);
  524. $feedret = z_fetch_url($data["poll"]);
  525. if (!$feedret["success"]) {
  526. q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
  527. dbesc(datetime_convert()), dbesc(normalise_link($profile)));
  528. logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
  529. return false;
  530. }
  531. $doc = new DOMDocument();
  532. @$doc->loadXML($feedret["body"]);
  533. $xpath = new DomXPath($doc);
  534. $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
  535. $entries = $xpath->query('/atom:feed/atom:entry');
  536. $last_updated = "";
  537. foreach ($entries AS $entry) {
  538. $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
  539. $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
  540. if ($last_updated < $published)
  541. $last_updated = $published;
  542. if ($last_updated < $updated)
  543. $last_updated = $updated;
  544. }
  545. // Maybe there aren't any entries. Then check if it is a valid feed
  546. if ($last_updated == "") {
  547. if ($xpath->query('/atom:feed')->length > 0) {
  548. $last_updated = NULL_DATE;
  549. }
  550. }
  551. q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
  552. dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
  553. if (($gcontacts[0]["generation"] == 0)) {
  554. q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
  555. dbesc(normalise_link($profile)));
  556. }
  557. logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
  558. return($last_updated);
  559. }
  560. function poco_do_update($created, $updated, $last_failure, $last_contact) {
  561. $now = strtotime(datetime_convert());
  562. if ($updated > $last_contact)
  563. $contact_time = strtotime($updated);
  564. else
  565. $contact_time = strtotime($last_contact);
  566. $failure_time = strtotime($last_failure);
  567. $created_time = strtotime($created);
  568. // If there is no "created" time then use the current time
  569. if ($created_time <= 0)
  570. $created_time = $now;
  571. // If the last contact was less than 24 hours then don't update
  572. if (($now - $contact_time) < (60 * 60 * 24))
  573. return false;
  574. // If the last failure was less than 24 hours then don't update
  575. if (($now - $failure_time) < (60 * 60 * 24))
  576. return false;
  577. // If the last contact was less than a week ago and the last failure is older than a week then don't update
  578. //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
  579. // return false;
  580. // 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
  581. if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
  582. return false;
  583. // 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
  584. if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
  585. return false;
  586. return true;
  587. }
  588. function poco_to_boolean($val) {
  589. if (($val == "true") OR ($val == 1))
  590. return(true);
  591. if (($val == "false") OR ($val == 0))
  592. return(false);
  593. return ($val);
  594. }
  595. /**
  596. * @brief Detect server type (Hubzilla or Friendica) via the poco data
  597. *
  598. * @param object $data POCO data
  599. * @return array Server data
  600. */
  601. function poco_detect_poco_data($data) {
  602. $server = false;
  603. if (!isset($data->entry)) {
  604. return false;
  605. }
  606. if (count($data->entry) == 0) {
  607. return false;
  608. }
  609. if (!isset($data->entry[0]->urls)) {
  610. return false;
  611. }
  612. if (count($data->entry[0]->urls) == 0) {
  613. return false;
  614. }
  615. foreach ($data->entry[0]->urls AS $url) {
  616. if ($url->type == 'zot') {
  617. $server = array();
  618. $server["platform"] = 'Hubzilla';
  619. $server["network"] = NETWORK_DIASPORA;
  620. return $server;
  621. }
  622. }
  623. return false;
  624. }
  625. /**
  626. * @brief Detect server type by using the nodeinfo data
  627. *
  628. * @param string $server_url address of the server
  629. * @return array Server data
  630. */
  631. function poco_fetch_nodeinfo($server_url) {
  632. $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
  633. if (!$serverret["success"]) {
  634. return false;
  635. }
  636. $nodeinfo = json_decode($serverret['body']);
  637. if (!is_object($nodeinfo)) {
  638. return false;
  639. }
  640. if (!is_array($nodeinfo->links)) {
  641. return false;
  642. }
  643. $nodeinfo_url = '';
  644. foreach ($nodeinfo->links AS $link) {
  645. if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
  646. $nodeinfo_url = $link->href;
  647. }
  648. }
  649. if ($nodeinfo_url == '') {
  650. return false;
  651. }
  652. $serverret = z_fetch_url($nodeinfo_url);
  653. if (!$serverret["success"]) {
  654. return false;
  655. }
  656. $nodeinfo = json_decode($serverret['body']);
  657. if (!is_object($nodeinfo)) {
  658. return false;
  659. }
  660. $server = array();
  661. $server['register_policy'] = REGISTER_CLOSED;
  662. if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
  663. $server['register_policy'] = REGISTER_OPEN;
  664. }
  665. if (is_object($nodeinfo->software)) {
  666. if (isset($nodeinfo->software->name)) {
  667. $server['platform'] = $nodeinfo->software->name;
  668. }
  669. if (isset($nodeinfo->software->version)) {
  670. $server['version'] = $nodeinfo->software->version;
  671. // Version numbers on Nodeinfo are presented with additional info, e.g.:
  672. // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
  673. $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
  674. }
  675. }
  676. if (is_object($nodeinfo->metadata)) {
  677. if (isset($nodeinfo->metadata->nodeName)) {
  678. $server['site_name'] = $nodeinfo->metadata->nodeName;
  679. }
  680. }
  681. $diaspora = false;
  682. $friendica = false;
  683. $gnusocial = false;
  684. if (is_array($nodeinfo->protocols->inbound)) {
  685. foreach ($nodeinfo->protocols->inbound AS $inbound) {
  686. if ($inbound == 'diaspora') {
  687. $diaspora = true;
  688. }
  689. if ($inbound == 'friendica') {
  690. $friendica = true;
  691. }
  692. if ($inbound == 'gnusocial') {
  693. $gnusocial = true;
  694. }
  695. }
  696. }
  697. if ($gnusocial) {
  698. $server['network'] = NETWORK_OSTATUS;
  699. }
  700. if ($diaspora) {
  701. $server['network'] = NETWORK_DIASPORA;
  702. }
  703. if ($friendica) {
  704. $server['network'] = NETWORK_DFRN;
  705. }
  706. if (!$server) {
  707. return false;
  708. }
  709. return $server;
  710. }
  711. /**
  712. * @brief Detect server type (Hubzilla or Friendica) via the front page body
  713. *
  714. * @param string $body Front page of the server
  715. * @return array Server data
  716. */
  717. function poco_detect_server_type($body) {
  718. $server = false;
  719. $doc = new \DOMDocument();
  720. @$doc->loadHTML($body);
  721. $xpath = new \DomXPath($doc);
  722. $list = $xpath->query("//meta[@name]");
  723. foreach ($list as $node) {
  724. $attr = array();
  725. if ($node->attributes->length) {
  726. foreach ($node->attributes as $attribute) {
  727. $attr[$attribute->name] = $attribute->value;
  728. }
  729. }
  730. if ($attr['name'] == 'generator') {
  731. $version_part = explode(" ", $attr['content']);
  732. if (count($version_part) == 2) {
  733. if (in_array($version_part[0], array("Friendika", "Friendica"))) {
  734. $server = array();
  735. $server["platform"] = $version_part[0];
  736. $server["version"] = $version_part[1];
  737. $server["network"] = NETWORK_DFRN;
  738. }
  739. }
  740. }
  741. }
  742. if (!$server) {
  743. $list = $xpath->query("//meta[@property]");
  744. foreach ($list as $node) {
  745. $attr = array();
  746. if ($node->attributes->length) {
  747. foreach ($node->attributes as $attribute) {
  748. $attr[$attribute->name] = $attribute->value;
  749. }
  750. }
  751. if ($attr['property'] == 'generator') {
  752. if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
  753. $server = array();
  754. $server["platform"] = $attr['content'];
  755. $server["version"] = "";
  756. $server["network"] = NETWORK_DIASPORA;
  757. }
  758. }
  759. }
  760. }
  761. if (!$server) {
  762. return false;
  763. }
  764. $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
  765. return $server;
  766. }
  767. function poco_check_server($server_url, $network = "", $force = false) {
  768. // Unify the server address
  769. $server_url = trim($server_url, "/");
  770. $server_url = str_replace("/index.php", "", $server_url);
  771. if ($server_url == "")
  772. return false;
  773. $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
  774. if (dbm::is_result($servers)) {
  775. if ($servers[0]["created"] <= NULL_DATE) {
  776. q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
  777. dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
  778. }
  779. $poco = $servers[0]["poco"];
  780. $noscrape = $servers[0]["noscrape"];
  781. if ($network == "")
  782. $network = $servers[0]["network"];
  783. $last_contact = $servers[0]["last_contact"];
  784. $last_failure = $servers[0]["last_failure"];
  785. $version = $servers[0]["version"];
  786. $platform = $servers[0]["platform"];
  787. $site_name = $servers[0]["site_name"];
  788. $info = $servers[0]["info"];
  789. $register_policy = $servers[0]["register_policy"];
  790. if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
  791. logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
  792. return ($last_contact >= $last_failure);
  793. }
  794. } else {
  795. $poco = "";
  796. $noscrape = "";
  797. $version = "";
  798. $platform = "";
  799. $site_name = "";
  800. $info = "";
  801. $register_policy = -1;
  802. $last_contact = NULL_DATE;
  803. $last_failure = NULL_DATE;
  804. }
  805. logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
  806. $failure = false;
  807. $possible_failure = false;
  808. $orig_last_failure = $last_failure;
  809. $orig_last_contact = $last_contact;
  810. // Check if the page is accessible via SSL.
  811. $orig_server_url = $server_url;
  812. $server_url = str_replace("http://", "https://", $server_url);
  813. // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
  814. $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
  815. // Quit if there is a timeout.
  816. // But we want to make sure to only quit if we are mostly sure that this server url fits.
  817. if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
  818. ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
  819. logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
  820. return false;
  821. }
  822. // Maybe the page is unencrypted only?
  823. $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
  824. if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
  825. $server_url = str_replace("https://", "http://", $server_url);
  826. // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
  827. $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
  828. // Quit if there is a timeout
  829. if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
  830. logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
  831. return false;
  832. }
  833. $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
  834. }
  835. if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
  836. // Workaround for bad configured servers (known nginx problem)
  837. if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
  838. $last_failure = datetime_convert();
  839. $failure = true;
  840. }
  841. $possible_failure = true;
  842. } elseif ($network == NETWORK_DIASPORA)
  843. $last_contact = datetime_convert();
  844. // If the server has no possible failure we reset the cached data
  845. if (!$possible_failure) {
  846. $version = "";
  847. $platform = "";
  848. $site_name = "";
  849. $info = "";
  850. $register_policy = -1;
  851. }
  852. // Look for poco
  853. if (!$failure) {
  854. $serverret = z_fetch_url($server_url."/poco");
  855. if ($serverret["success"]) {
  856. $data = json_decode($serverret["body"]);
  857. if (isset($data->totalResults)) {
  858. $poco = $server_url."/poco";
  859. $last_contact = datetime_convert();
  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. $last_failure = datetime_convert();
  875. $failure = true;
  876. } else {
  877. $server = poco_detect_server_type($serverret["body"]);
  878. if ($server) {
  879. $platform = $server['platform'];
  880. $network = $server['network'];
  881. $version = $server['version'];
  882. $site_name = $server['site_name'];
  883. $last_contact = datetime_convert();
  884. }
  885. $lines = explode("\n",$serverret["header"]);
  886. if(count($lines)) {
  887. foreach($lines as $line) {
  888. $line = trim($line);
  889. if(stristr($line,'X-Diaspora-Version:')) {
  890. $platform = "Diaspora";
  891. $version = trim(str_replace("X-Diaspora-Version:", "", $line));
  892. $version = trim(str_replace("x-diaspora-version:", "", $version));
  893. $network = NETWORK_DIASPORA;
  894. $versionparts = explode("-", $version);
  895. $version = $versionparts[0];
  896. $last_contact = datetime_convert();
  897. }
  898. if(stristr($line,'Server: Mastodon')) {
  899. $platform = "Mastodon";
  900. $network = NETWORK_OSTATUS;
  901. // Mastodon doesn't reveal version numbers
  902. $version = "";
  903. $last_contact = datetime_convert();
  904. }
  905. }
  906. }
  907. }
  908. }
  909. if (!$failure AND ($poco == "")) {
  910. // Test for Statusnet
  911. // Will also return data for Friendica and GNU Social - but it will be overwritten later
  912. // The "not implemented" is a special treatment for really, really old Friendica versions
  913. $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
  914. if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
  915. ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
  916. $platform = "StatusNet";
  917. // Remove junk that some GNU Social servers return
  918. $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
  919. $version = trim($version, '"');
  920. $network = NETWORK_OSTATUS;
  921. $last_contact = datetime_convert();
  922. }
  923. // Test for GNU Social
  924. $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
  925. if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
  926. ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
  927. $platform = "GNU Social";
  928. // Remove junk that some GNU Social servers return
  929. $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
  930. $version = trim($version, '"');
  931. $network = NETWORK_OSTATUS;
  932. $last_contact = datetime_convert();
  933. }
  934. }
  935. if (!$failure) {
  936. // Test for Hubzilla, Redmatrix or Friendica
  937. $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
  938. if ($serverret["success"]) {
  939. $data = json_decode($serverret["body"]);
  940. if (isset($data->site->server)) {
  941. $last_contact = datetime_convert();
  942. if (isset($data->site->platform)) {
  943. $platform = $data->site->platform->PLATFORM_NAME;
  944. $version = $data->site->platform->STD_VERSION;
  945. $network = NETWORK_DIASPORA;
  946. }
  947. if (isset($data->site->BlaBlaNet)) {
  948. $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
  949. $version = $data->site->BlaBlaNet->STD_VERSION;
  950. $network = NETWORK_DIASPORA;
  951. }
  952. if (isset($data->site->hubzilla)) {
  953. $platform = $data->site->hubzilla->PLATFORM_NAME;
  954. $version = $data->site->hubzilla->RED_VERSION;
  955. $network = NETWORK_DIASPORA;
  956. }
  957. if (isset($data->site->redmatrix)) {
  958. if (isset($data->site->redmatrix->PLATFORM_NAME))
  959. $platform = $data->site->redmatrix->PLATFORM_NAME;
  960. elseif (isset($data->site->redmatrix->RED_PLATFORM))
  961. $platform = $data->site->redmatrix->RED_PLATFORM;
  962. $version = $data->site->redmatrix->RED_VERSION;
  963. $network = NETWORK_DIASPORA;
  964. }
  965. if (isset($data->site->friendica)) {
  966. $platform = $data->site->friendica->FRIENDICA_PLATFORM;
  967. $version = $data->site->friendica->FRIENDICA_VERSION;
  968. $network = NETWORK_DFRN;
  969. }
  970. $site_name = $data->site->name;
  971. $data->site->closed = poco_to_boolean($data->site->closed);
  972. $data->site->private = poco_to_boolean($data->site->private);
  973. $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
  974. if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
  975. $register_policy = REGISTER_APPROVE;
  976. elseif (!$data->site->closed AND !$data->site->private)
  977. $register_policy = REGISTER_OPEN;
  978. else
  979. $register_policy = REGISTER_CLOSED;
  980. }
  981. }
  982. }
  983. // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
  984. if (!$failure) {
  985. $serverret = z_fetch_url($server_url."/statistics.json");
  986. if ($serverret["success"]) {
  987. $data = json_decode($serverret["body"]);
  988. if (isset($data->version)) {
  989. $version = $data->version;
  990. // Version numbers on statistics.json are presented with additional info, e.g.:
  991. // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
  992. $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
  993. }
  994. $site_name = $data->name;
  995. if (isset($data->network)) {
  996. $platform = $data->network;
  997. }
  998. if ($platform == "Diaspora") {
  999. $network = NETWORK_DIASPORA;
  1000. }
  1001. if ($data->registrations_open) {
  1002. $register_policy = REGISTER_OPEN;
  1003. } else {
  1004. $register_policy = REGISTER_CLOSED;
  1005. }
  1006. if (isset($data->version))
  1007. $last_contact = datetime_convert();
  1008. }
  1009. }
  1010. // Query nodeinfo. Working for (at least) Diaspora and Friendica.
  1011. if (!$failure) {
  1012. $server = poco_fetch_nodeinfo($server_url);
  1013. if ($server) {
  1014. $register_policy = $server['register_policy'];
  1015. if (isset($server['platform'])) {
  1016. $platform = $server['platform'];
  1017. }
  1018. if (isset($server['network'])) {
  1019. $network = $server['network'];
  1020. }
  1021. if (isset($server['version'])) {
  1022. $version = $server['version'];
  1023. }
  1024. if (isset($server['site_name'])) {
  1025. $site_name = $server['site_name'];
  1026. }
  1027. $last_contact = datetime_convert();
  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. $last_contact = datetime_convert();
  1040. $network = NETWORK_DFRN;
  1041. $noscrape = $data->no_scrape_url;
  1042. $version = $data->version;
  1043. $site_name = $data->site_name;
  1044. $info = $data->info;
  1045. $register_policy_str = $data->register_policy;
  1046. $platform = $data->platform;
  1047. switch ($register_policy_str) {
  1048. case "REGISTER_CLOSED":
  1049. $register_policy = REGISTER_CLOSED;
  1050. break;
  1051. case "REGISTER_APPROVE":
  1052. $register_policy = REGISTER_APPROVE;
  1053. break;
  1054. case "REGISTER_OPEN":
  1055. $register_policy = REGISTER_OPEN;
  1056. break;
  1057. }
  1058. }
  1059. }
  1060. }
  1061. if ($possible_failure AND !$failure) {
  1062. $last_failure = datetime_convert();
  1063. $failure = true;
  1064. }
  1065. if ($failure) {
  1066. $last_contact = $orig_last_contact;
  1067. } else {
  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"]));
  1424. return false;
  1425. }
  1426. }
  1427. function poco_discover($complete = false) {
  1428. // Update the server list
  1429. poco_discover_federation();
  1430. $no_of_queries = 5;
  1431. $requery_days = intval(get_config("system", "poco_requery_days"));
  1432. if ($requery_days == 0) {
  1433. $requery_days = 7;
  1434. }
  1435. $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
  1436. $r = q("SELECT `id`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
  1437. if (dbm::is_result($r)) {
  1438. foreach ($r AS $server) {
  1439. if (!poco_check_server($server["url"], $server["network"])) {
  1440. // The server is not reachable? Okay, then we will try it later
  1441. q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
  1442. continue;
  1443. }
  1444. logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
  1445. proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
  1446. if (!$complete AND (--$no_of_queries == 0)) {
  1447. break;
  1448. }
  1449. }
  1450. }
  1451. }
  1452. function poco_discover_server_users($data, $server) {
  1453. if (!isset($data->entry))
  1454. return;
  1455. foreach ($data->entry AS $entry) {
  1456. $username = "";
  1457. if (isset($entry->urls)) {
  1458. foreach($entry->urls as $url)
  1459. if ($url->type == 'profile') {
  1460. $profile_url = $url->value;
  1461. $urlparts = parse_url($profile_url);
  1462. $username = end(explode("/", $urlparts["path"]));
  1463. }
  1464. }
  1465. if ($username != "") {
  1466. logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
  1467. // Fetch all contacts from a given user from the other server
  1468. $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
  1469. $retdata = z_fetch_url($url);
  1470. if ($retdata["success"])
  1471. poco_discover_server(json_decode($retdata["body"]), 3);
  1472. }
  1473. }
  1474. }
  1475. function poco_discover_server($data, $default_generation = 0) {
  1476. if (!isset($data->entry) OR !count($data->entry))
  1477. return false;
  1478. $success = false;
  1479. foreach ($data->entry AS $entry) {
  1480. $profile_url = '';
  1481. $profile_photo = '';
  1482. $connect_url = '';
  1483. $name = '';
  1484. $network = '';
  1485. $updated = NULL_DATE;
  1486. $location = '';
  1487. $about = '';
  1488. $keywords = '';
  1489. $gender = '';
  1490. $contact_type = -1;
  1491. $generation = $default_generation;
  1492. $name = $entry->displayName;
  1493. if (isset($entry->urls)) {
  1494. foreach($entry->urls as $url) {
  1495. if ($url->type == 'profile') {
  1496. $profile_url = $url->value;
  1497. continue;
  1498. }
  1499. if ($url->type == 'webfinger') {
  1500. $connect_url = str_replace('acct:' , '', $url->value);
  1501. continue;
  1502. }
  1503. }
  1504. }
  1505. if (isset($entry->photos)) {
  1506. foreach ($entry->photos as $photo) {
  1507. if ($photo->type == 'profile') {
  1508. $profile_photo = $photo->value;
  1509. continue;
  1510. }
  1511. }
  1512. }
  1513. if (isset($entry->updated)) {
  1514. $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
  1515. }
  1516. if(isset($entry->network)) {
  1517. $network = $entry->network;
  1518. }
  1519. if(isset($entry->currentLocation)) {
  1520. $location = $entry->currentLocation;
  1521. }
  1522. if(isset($entry->aboutMe)) {
  1523. $about = html2bbcode($entry->aboutMe);
  1524. }
  1525. if(isset($entry->gender)) {
  1526. $gender = $entry->gender;
  1527. }
  1528. if(isset($entry->generation) AND ($entry->generation > 0)) {
  1529. $generation = ++$entry->generation;
  1530. }
  1531. if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
  1532. $contact_type = $entry->contactType;
  1533. }
  1534. if(isset($entry->tags)) {
  1535. foreach ($entry->tags as $tag) {
  1536. $keywords = implode(", ", $tag);
  1537. }
  1538. }
  1539. if ($generation > 0) {
  1540. $success = true;
  1541. logger("Store profile ".$profile_url, LOGGER_DEBUG);
  1542. $gcontact = array("url" => $profile_url,
  1543. "name" => $name,
  1544. "network" => $network,
  1545. "photo" => $profile_photo,
  1546. "about" => $about,
  1547. "location" => $location,
  1548. "gender" => $gender,
  1549. "keywords" => $keywords,
  1550. "connect" => $connect_url,
  1551. "updated" => $updated,
  1552. "contact-type" => $contact_type,
  1553. "generation" => $generation);
  1554. try {
  1555. $gcontact = sanitize_gcontact($gcontact);
  1556. update_gcontact($gcontact);
  1557. } catch (Exception $e) {
  1558. logger($e->getMessage(), LOGGER_DEBUG);
  1559. }
  1560. logger("Done for profile ".$profile_url, LOGGER_DEBUG);
  1561. }
  1562. }
  1563. return $success;
  1564. }
  1565. /**
  1566. * @brief Removes unwanted parts from a contact url
  1567. *
  1568. * @param string $url Contact url
  1569. * @return string Contact url with the wanted parts
  1570. */
  1571. function clean_contact_url($url) {
  1572. $parts = parse_url($url);
  1573. if (!isset($parts["scheme"]) OR !isset($parts["host"]))
  1574. return $url;
  1575. $new_url = $parts["scheme"]."://".$parts["host"];
  1576. if (isset($parts["port"]))
  1577. $new_url .= ":".$parts["port"];
  1578. if (isset($parts["path"]))
  1579. $new_url .= $parts["path"];
  1580. if ($new_url != $url)
  1581. logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
  1582. return $new_url;
  1583. }
  1584. /**
  1585. * @brief Replace alternate OStatus user format with the primary one
  1586. *
  1587. * @param arr $contact contact array (called by reference)
  1588. */
  1589. function fix_alternate_contact_address(&$contact) {
  1590. if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
  1591. $data = probe_url($contact["url"]);
  1592. if ($contact["network"] == NETWORK_OSTATUS) {
  1593. logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
  1594. $contact["url"] = $data["url"];
  1595. $contact["addr"] = $data["addr"];
  1596. $contact["alias"] = $data["alias"];
  1597. $contact["server_url"] = $data["baseurl"];
  1598. }
  1599. }
  1600. }
  1601. /**
  1602. * @brief Fetch the gcontact id, add an entry if not existed
  1603. *
  1604. * @param arr $contact contact array
  1605. * @return bool|int Returns false if not found, integer if contact was found
  1606. */
  1607. function get_gcontact_id($contact) {
  1608. $gcontact_id = 0;
  1609. $doprobing = false;
  1610. if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
  1611. logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
  1612. return false;
  1613. }
  1614. if ($contact["network"] == NETWORK_STATUSNET)
  1615. $contact["network"] = NETWORK_OSTATUS;
  1616. // All new contacts are hidden by default
  1617. if (!isset($contact["hide"]))
  1618. $contact["hide"] = true;
  1619. // Replace alternate OStatus user format with the primary one
  1620. fix_alternate_contact_address($contact);
  1621. // Remove unwanted parts from the contact url (e.g. "?zrl=...")
  1622. if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
  1623. $contact["url"] = clean_contact_url($contact["url"]);
  1624. $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
  1625. dbesc(normalise_link($contact["url"])));
  1626. if ($r) {
  1627. $gcontact_id = $r[0]["id"];
  1628. // Update every 90 days
  1629. if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
  1630. $last_failure_str = $r[0]["last_failure"];
  1631. $last_failure = strtotime($r[0]["last_failure"]);
  1632. $last_contact_str = $r[0]["last_contact"];
  1633. $last_contact = strtotime($r[0]["last_contact"]);
  1634. $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
  1635. }
  1636. } else {
  1637. q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
  1638. VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
  1639. dbesc($contact["name"]),
  1640. dbesc($contact["nick"]),
  1641. dbesc($contact["addr"]),
  1642. dbesc($contact["network"]),
  1643. dbesc($contact["url"]),
  1644. dbesc(normalise_link($contact["url"])),
  1645. dbesc($contact["photo"]),
  1646. dbesc(datetime_convert()),
  1647. dbesc(datetime_convert()),
  1648. dbesc($contact["location"]),
  1649. dbesc($contact["about"]),
  1650. intval($contact["hide"]),
  1651. intval($contact["generation"])
  1652. );
  1653. $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
  1654. dbesc(normalise_link($contact["url"])));
  1655. if ($r) {
  1656. $gcontact_id = $r[0]["id"];
  1657. $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
  1658. }
  1659. }
  1660. if ($doprobing) {
  1661. logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
  1662. proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
  1663. }
  1664. if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
  1665. q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
  1666. dbesc(normalise_link($contact["url"])),
  1667. intval($gcontact_id));
  1668. return $gcontact_id;
  1669. }
  1670. /**
  1671. * @brief Updates the gcontact table from a given array
  1672. *
  1673. * @param arr $contact contact array
  1674. * @return bool|int Returns false if not found, integer if contact was found
  1675. */
  1676. function update_gcontact($contact) {
  1677. // Check for invalid "contact-type" value
  1678. if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
  1679. $contact['contact-type'] = 0;
  1680. }
  1681. /// @todo update contact table as well
  1682. $gcontact_id = get_gcontact_id($contact);
  1683. if (!$gcontact_id)
  1684. return false;
  1685. $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
  1686. `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
  1687. FROM `gcontact` WHERE `id` = %d LIMIT 1",
  1688. intval($gcontact_id));
  1689. // Get all field names
  1690. $fields = array();
  1691. foreach ($r[0] AS $field => $data)
  1692. $fields[$field] = $data;
  1693. unset($fields["url"]);
  1694. unset($fields["updated"]);
  1695. unset($fields["hide"]);
  1696. // Bugfix: We had an error in the storing of keywords which lead to the "0"
  1697. // This value is still transmitted via poco.
  1698. if ($contact["keywords"] == "0")
  1699. unset($contact["keywords"]);
  1700. if ($r[0]["keywords"] == "0")
  1701. $r[0]["keywords"] = "";
  1702. // assign all unassigned fields from the database entry
  1703. foreach ($fields AS $field => $data)
  1704. if (!isset($contact[$field]) OR ($contact[$field] == ""))
  1705. $contact[$field] = $r[0][$field];
  1706. if (!isset($contact["hide"]))
  1707. $contact["hide"] = $r[0]["hide"];
  1708. $fields["hide"] = $r[0]["hide"];
  1709. if ($contact["network"] == NETWORK_STATUSNET)
  1710. $contact["network"] = NETWORK_OSTATUS;
  1711. // Replace alternate OStatus user format with the primary one
  1712. fix_alternate_contact_address($contact);
  1713. if (!isset($contact["updated"]))
  1714. $contact["updated"] = dbm::date();
  1715. if ($contact["server_url"] == "") {
  1716. $server_url = $contact["url"];
  1717. $server_url = matching_url($server_url, $contact["alias"]);
  1718. if ($server_url != "")
  1719. $contact["server_url"] = $server_url;
  1720. $server_url = matching_url($server_url, $contact["photo"]);
  1721. if ($server_url != "")
  1722. $contact["server_url"] = $server_url;
  1723. $server_url = matching_url($server_url, $contact["notify"]);
  1724. if ($server_url != "")
  1725. $contact["server_url"] = $server_url;
  1726. } else
  1727. $contact["server_url"] = normalise_link($contact["server_url"]);
  1728. if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
  1729. $hostname = str_replace("http://", "", $contact["server_url"]);
  1730. $contact["addr"] = $contact["nick"]."@".$hostname;
  1731. }
  1732. // Check if any field changed
  1733. $update = false;
  1734. unset($fields["generation"]);
  1735. if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
  1736. foreach ($fields AS $field => $data)
  1737. if ($contact[$field] != $r[0][$field]) {
  1738. logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
  1739. $update = true;
  1740. }
  1741. if ($contact["generation"] < $r[0]["generation"]) {
  1742. logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
  1743. $update = true;
  1744. }
  1745. }
  1746. if ($update) {
  1747. logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
  1748. q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
  1749. `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
  1750. `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
  1751. `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
  1752. `server_url` = '%s', `connect` = '%s'
  1753. WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
  1754. dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
  1755. dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
  1756. dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
  1757. intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
  1758. dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
  1759. dbesc($contact["about"]), intval($contact["generation"]), dbesc(dbm::date($contact["updated"])),
  1760. dbesc($contact["server_url"]), dbesc($contact["connect"]),
  1761. dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
  1762. // Now update the contact entry with the user id "0" as well.
  1763. // This is used for the shadow copies of public items.
  1764. $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
  1765. dbesc(normalise_link($contact["url"])));
  1766. if ($r) {
  1767. logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
  1768. update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
  1769. q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
  1770. `network` = '%s', `bd` = '%s', `gender` = '%s',
  1771. `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
  1772. `url` = '%s', `location` = '%s', `about` = '%s'
  1773. WHERE `id` = %d",
  1774. dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
  1775. dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
  1776. dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
  1777. dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
  1778. intval($r[0]["id"]));
  1779. }
  1780. }
  1781. return $gcontact_id;
  1782. }
  1783. /**
  1784. * @brief Updates the gcontact entry from probe
  1785. *
  1786. * @param str $url profile link
  1787. */
  1788. function update_gcontact_from_probe($url) {
  1789. $data = probe_url($url);
  1790. if (in_array($data["network"], array(NETWORK_PHANTOM))) {
  1791. logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
  1792. return;
  1793. }
  1794. $data["server_url"] = $data["baseurl"];
  1795. update_gcontact($data);
  1796. }
  1797. /**
  1798. * @brief Update the gcontact entry for a given user id
  1799. *
  1800. * @param int $uid User ID
  1801. */
  1802. function update_gcontact_for_user($uid) {
  1803. $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
  1804. `profile`.`name`, `profile`.`about`, `profile`.`gender`,
  1805. `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
  1806. `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
  1807. `contact`.`notify`, `contact`.`url`, `contact`.`addr`
  1808. FROM `profile`
  1809. INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
  1810. INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
  1811. WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
  1812. intval($uid));
  1813. $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
  1814. "country-name" => $r[0]["country-name"]));
  1815. // The "addr" field was added in 3.4.3 so it can be empty for older users
  1816. if ($r[0]["addr"] != "")
  1817. $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
  1818. else
  1819. $addr = $r[0]["addr"];
  1820. $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
  1821. "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
  1822. "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
  1823. "notify" => $r[0]["notify"], "url" => $r[0]["url"],
  1824. "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
  1825. "nick" => $r[0]["nickname"], "addr" => $addr,
  1826. "connect" => $addr, "server_url" => App::get_baseurl(),
  1827. "generation" => 1, "network" => NETWORK_DFRN);
  1828. update_gcontact($gcontact);
  1829. }
  1830. /**
  1831. * @brief Fetches users of given GNU Social server
  1832. *
  1833. * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
  1834. *
  1835. * @param str $server Server address
  1836. */
  1837. function gs_fetch_users($server) {
  1838. logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
  1839. $url = $server."/main/statistics";
  1840. $result = z_fetch_url($url);
  1841. if (!$result["success"])
  1842. return false;
  1843. $statistics = json_decode($result["body"]);
  1844. if (is_object($statistics->config)) {
  1845. if ($statistics->config->instance_with_ssl)
  1846. $server = "https://";
  1847. else
  1848. $server = "http://";
  1849. $server .= $statistics->config->instance_address;
  1850. $hostname = $statistics->config->instance_address;
  1851. } else {
  1852. if ($statistics->instance_with_ssl)
  1853. $server = "https://";
  1854. else
  1855. $server = "http://";
  1856. $server .= $statistics->instance_address;
  1857. $hostname = $statistics->instance_address;
  1858. }
  1859. if (is_object($statistics->users))
  1860. foreach ($statistics->users AS $nick => $user) {
  1861. $profile_url = $server."/".$user->nickname;
  1862. $contact = array("url" => $profile_url,
  1863. "name" => $user->fullname,
  1864. "addr" => $user->nickname."@".$hostname,
  1865. "nick" => $user->nickname,
  1866. "about" => $user->bio,
  1867. "network" => NETWORK_OSTATUS,
  1868. "photo" => App::get_baseurl()."/images/person-175.jpg");
  1869. get_gcontact_id($contact);
  1870. }
  1871. }
  1872. /**
  1873. * @brief Asking GNU Social server on a regular base for their user data
  1874. *
  1875. */
  1876. function gs_discover() {
  1877. $requery_days = intval(get_config("system", "poco_requery_days"));
  1878. $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
  1879. $r = q("SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
  1880. dbesc(NETWORK_OSTATUS), dbesc($last_update));
  1881. if (!$r)
  1882. return;
  1883. foreach ($r AS $server) {
  1884. gs_fetch_users($server["url"]);
  1885. q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
  1886. }
  1887. }
  1888. /**
  1889. * @brief Returns a list of all known servers
  1890. * @return array List of server urls
  1891. */
  1892. function poco_serverlist() {
  1893. $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
  1894. WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
  1895. ORDER BY `last_contact`
  1896. LIMIT 1000",
  1897. dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
  1898. if (!dbm::is_result($r)) {
  1899. return false;
  1900. }
  1901. return $r;
  1902. }