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.

1843 lines
57KB

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