3 * @file src/Model/GlobalContact.php
4 * @brief This file includes the GlobalContact class with directory related functions
6 namespace Friendica\Model;
8 use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Core\Worker;
11 use Friendica\Database\DBM;
12 use Friendica\Network\Probe;
13 use Friendica\Object\Profile;
14 use Friendica\Protocol\PortableContact;
18 require_once 'include/datetime.php';
19 require_once 'include/network.php';
20 require_once 'include/html2bbcode.php';
21 require_once 'include/Photo.php';
24 * @brief This class handles GlobalContact related functions
29 * @brief Search global contact table by nick or name
31 * @param string $search Name or nick
32 * @param string $mode Search mode (e.g. "community")
34 * @return array with search results
36 public static function searchByName($search, $mode = '')
39 // check supported networks
40 if (Config::get('system', 'diaspora_enabled')) {
41 $diaspora = NETWORK_DIASPORA;
43 $diaspora = NETWORK_DFRN;
46 if (!Config::get('system', 'ostatus_disabled')) {
47 $ostatus = NETWORK_OSTATUS;
49 $ostatus = NETWORK_DFRN;
52 // check if we search only communities or every contact
53 if ($mode === "community") {
54 $extra_sql = " AND `community`";
62 "SELECT `contact`.`id` AS `cid`, `gcontact`.`url`, `gcontact`.`name`, `gcontact`.`nick`, `gcontact`.`photo`,
63 `gcontact`.`network`, `gcontact`.`keywords`, `gcontact`.`addr`, `gcontact`.`community`
65 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl`
66 AND `contact`.`uid` = %d AND NOT `contact`.`blocked`
67 AND NOT `contact`.`pending` AND `contact`.`rel` IN ('%s', '%s')
68 WHERE (`contact`.`id` > 0 OR (NOT `gcontact`.`hide` AND `gcontact`.`network` IN ('%s', '%s', '%s') AND
69 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
70 (`gcontact`.`updated` >= `gcontact`.`last_failure`)))) AND
71 (`gcontact`.`addr` LIKE '%s' OR `gcontact`.`name` LIKE '%s' OR `gcontact`.`nick` LIKE '%s') $extra_sql
72 GROUP BY `gcontact`.`nurl`
73 ORDER BY `gcontact`.`nurl` DESC
76 dbesc(CONTACT_IS_SHARING),
77 dbesc(CONTACT_IS_FRIEND),
81 dbesc(escape_tags($search)),
82 dbesc(escape_tags($search)),
83 dbesc(escape_tags($search))
91 * @brief Link the gcontact entry with user, contact and global contact
93 * @param integer $gcid Global contact ID
94 * @param integer $uid User ID
95 * @param integer $cid Contact ID
96 * @param integer $zcid Global Contact ID
98 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
105 "SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
112 if (!DBM::is_result($r)) {
114 "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
119 dbesc(datetime_convert())
123 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
124 dbesc(datetime_convert()),
134 * @brief Sanitize the given gcontact data
136 * @param array $gcontact array with gcontact data
141 * 1: Profiles on this server
142 * 2: Contacts of profiles on this server
143 * 3: Contacts of contacts of profiles on this server
146 public static function sanitize($gcontact)
148 if ($gcontact['url'] == "") {
149 throw new Exception('URL is empty');
152 $urlparts = parse_url($gcontact['url']);
153 if (!isset($urlparts["scheme"])) {
154 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
157 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"))) {
158 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
161 // Don't store the statusnet connector as network
162 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
163 if ($gcontact['network'] == NETWORK_STATUSNET) {
164 $gcontact['network'] = "";
167 // Assure that there are no parameter fragments in the profile url
168 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
169 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
172 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
174 // The global contacts should contain the original picture, not the cached one
175 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
176 $gcontact['photo'] = "";
179 if (!isset($gcontact['network'])) {
181 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
182 dbesc(normalise_link($gcontact['url'])),
183 dbesc(NETWORK_STATUSNET)
185 if (DBM::is_result($r)) {
186 $gcontact['network'] = $r[0]["network"];
189 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
191 "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
192 dbesc($gcontact['url']),
193 dbesc(normalise_link($gcontact['url'])),
194 dbesc(NETWORK_STATUSNET)
196 if (DBM::is_result($r)) {
197 $gcontact['network'] = $r[0]["network"];
202 $gcontact['server_url'] = '';
203 $gcontact['network'] = '';
206 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
207 dbesc(normalise_link($gcontact['url']))
210 if (DBM::is_result($x)) {
211 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
212 $gcontact['network'] = $x[0]["network"];
214 if ($gcontact['updated'] <= NULL_DATE) {
215 $gcontact['updated'] = $x[0]["updated"];
217 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
218 $gcontact['server_url'] = $x[0]["server_url"];
220 if (!isset($gcontact['addr'])) {
221 $gcontact['addr'] = $x[0]["addr"];
225 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
226 && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
228 $data = Probe::uri($gcontact['url']);
230 if ($data["network"] == NETWORK_PHANTOM) {
231 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
234 $orig_profile = $gcontact['url'];
236 $gcontact["server_url"] = $data["baseurl"];
238 $gcontact = array_merge($gcontact, $data);
240 if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
241 // Delete the old entry - if it exists
242 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
243 if (DBM::is_result($r)) {
244 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
245 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
250 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
251 throw new Exception('No name and photo for URL '.$gcontact['url']);
254 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
255 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
258 if (!isset($gcontact['server_url'])) {
259 // We check the server url to be sure that it is a real one
260 $server_url = PortableContact::detectServer($gcontact['url']);
262 // We are now sure that it is a correct URL. So we use it in the future
263 if ($server_url != "") {
264 $gcontact['server_url'] = $server_url;
268 // The server URL doesn't seem to be valid, so we don't store it.
269 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
270 $gcontact['server_url'] = "";
276 public static function countCommonFriends($uid, $cid)
279 "SELECT count(*) as `total`
280 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
281 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
282 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
283 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
284 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
291 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
292 if (DBM::is_result($r)) {
293 return $r[0]['total'];
298 public static function countCommonFriendsZcid($uid, $zcid)
301 "SELECT count(*) as `total`
302 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
303 where `glink`.`zcid` = %d
304 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
309 if (DBM::is_result($r)) {
310 return $r[0]['total'];
316 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
319 $sql_extra = " order by rand() ";
321 $sql_extra = " order by `gcontact`.`name` asc ";
325 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
327 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
328 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
329 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
330 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
331 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
332 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
333 $sql_extra LIMIT %d, %d",
342 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
346 function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
349 $sql_extra = " order by rand() ";
351 $sql_extra = " order by `gcontact`.`name` asc ";
356 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
357 where `glink`.`zcid` = %d
358 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
359 $sql_extra limit %d, %d",
366 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
370 public static function countAllFriends($uid, $cid)
373 "SELECT count(*) as `total`
374 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
375 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
376 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
381 if (DBM::is_result($r)) {
382 return $r[0]['total'];
389 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
392 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
394 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
395 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
396 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
397 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
398 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
406 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
410 public static function suggestionQuery($uid, $start = 0, $limit = 80)
417 * Uncommented because the result of the queries are to big to store it in the cache.
418 * We need to decide if we want to change the db column type or if we want to delete it.
420 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
421 //if (!is_null($list)) {
425 $network = array(NETWORK_DFRN);
427 if (Config::get('system', 'diaspora_enabled')) {
428 $network[] = NETWORK_DIASPORA;
431 if (!Config::get('system', 'ostatus_disabled')) {
432 $network[] = NETWORK_OSTATUS;
435 $sql_network = implode("', '", $network);
436 $sql_network = "'".$sql_network."'";
438 /// @todo This query is really slow
439 // By now we cache the data for five minutes
441 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
442 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
443 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
444 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
445 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
446 AND `gcontact`.`updated` >= '%s'
447 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
448 AND `gcontact`.`network` IN (%s)
449 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
460 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
462 * Uncommented because the result of the queries are to big to store it in the cache.
463 * We need to decide if we want to change the db column type or if we want to delete it.
465 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
471 "SELECT gcontact.* FROM gcontact
472 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
473 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
474 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
475 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
476 AND `gcontact`.`updated` >= '%s'
477 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
478 AND `gcontact`.`network` IN (%s)
479 ORDER BY rand() LIMIT %d, %d",
490 foreach ($r2 as $suggestion) {
491 $list[$suggestion["nurl"]] = $suggestion;
494 foreach ($r as $suggestion) {
495 $list[$suggestion["nurl"]] = $suggestion;
498 while (sizeof($list) > ($limit)) {
503 * Uncommented because the result of the queries are to big to store it in the cache.
504 * We need to decide if we want to change the db column type or if we want to delete it.
506 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
510 public static function updateSuggestions()
516 /// @TODO Check if it is really neccessary to poll the own server
517 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
519 $done[] = System::baseUrl() . '/poco';
521 if (strlen(Config::get('system', 'directory'))) {
522 $x = fetch_url(get_server()."/pubsites");
524 $j = json_decode($x);
526 foreach ($j->entries as $entry) {
527 PortableContact::checkServer($entry->url);
529 $url = $entry->url . '/poco';
530 if (! in_array($url, $done)) {
531 PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
538 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
540 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
542 dbesc(NETWORK_DIASPORA)
545 if (DBM::is_result($r)) {
546 foreach ($r as $rr) {
547 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
548 if (! in_array($base, $done)) {
549 PortableContact::loadWorker(0, 0, 0, $base);
556 * @brief Removes unwanted parts from a contact url
558 * @param string $url Contact url
560 * @return string Contact url with the wanted parts
562 public static function cleanContactUrl($url)
564 $parts = parse_url($url);
566 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
570 $new_url = $parts["scheme"]."://".$parts["host"];
572 if (isset($parts["port"])) {
573 $new_url .= ":".$parts["port"];
576 if (isset($parts["path"])) {
577 $new_url .= $parts["path"];
580 if ($new_url != $url) {
581 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
588 * @brief Replace alternate OStatus user format with the primary one
590 * @param arr $contact contact array (called by reference)
592 public static function fixAlternateContactAddress(&$contact)
594 if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
595 $data = Probe::uri($contact["url"]);
596 if ($contact["network"] == NETWORK_OSTATUS) {
597 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
598 $contact["url"] = $data["url"];
599 $contact["addr"] = $data["addr"];
600 $contact["alias"] = $data["alias"];
601 $contact["server_url"] = $data["baseurl"];
607 * @brief Fetch the gcontact id, add an entry if not existed
609 * @param arr $contact contact array
611 * @return bool|int Returns false if not found, integer if contact was found
613 public static function getId($contact)
618 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
619 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
623 if ($contact["network"] == NETWORK_STATUSNET) {
624 $contact["network"] = NETWORK_OSTATUS;
627 // All new contacts are hidden by default
628 if (!isset($contact["hide"])) {
629 $contact["hide"] = true;
632 // Replace alternate OStatus user format with the primary one
633 self::fixAlternateContactAddress($contact);
635 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
636 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
637 $contact["url"] = self::cleanContactUrl($contact["url"]);
640 dba::lock('gcontact');
642 "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
643 dbesc(normalise_link($contact["url"]))
646 if (DBM::is_result($r)) {
647 $gcontact_id = $r[0]["id"];
649 // Update every 90 days
650 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
651 $last_failure_str = $r[0]["last_failure"];
652 $last_failure = strtotime($r[0]["last_failure"]);
653 $last_contact_str = $r[0]["last_contact"];
654 $last_contact = strtotime($r[0]["last_contact"]);
655 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
659 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
660 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
661 dbesc($contact["name"]),
662 dbesc($contact["nick"]),
663 dbesc($contact["addr"]),
664 dbesc($contact["network"]),
665 dbesc($contact["url"]),
666 dbesc(normalise_link($contact["url"])),
667 dbesc($contact["photo"]),
668 dbesc(datetime_convert()),
669 dbesc(datetime_convert()),
670 dbesc($contact["location"]),
671 dbesc($contact["about"]),
672 intval($contact["hide"]),
673 intval($contact["generation"])
677 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
678 dbesc(normalise_link($contact["url"]))
681 if (DBM::is_result($r)) {
682 $gcontact_id = $r[0]["id"];
684 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
690 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
691 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
698 * @brief Updates the gcontact table from a given array
700 * @param arr $contact contact array
702 * @return bool|int Returns false if not found, integer if contact was found
704 public static function update($contact)
706 // Check for invalid "contact-type" value
707 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
708 $contact['contact-type'] = 0;
711 /// @todo update contact table as well
713 $gcontact_id = self::getId($contact);
720 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
721 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
722 FROM `gcontact` WHERE `id` = %d LIMIT 1",
726 // Get all field names
728 foreach ($r[0] as $field => $data) {
729 $fields[$field] = $data;
732 unset($fields["url"]);
733 unset($fields["updated"]);
734 unset($fields["hide"]);
736 // Bugfix: We had an error in the storing of keywords which lead to the "0"
737 // This value is still transmitted via poco.
738 if ($contact["keywords"] == "0") {
739 unset($contact["keywords"]);
742 if ($r[0]["keywords"] == "0") {
743 $r[0]["keywords"] = "";
746 // assign all unassigned fields from the database entry
747 foreach ($fields as $field => $data) {
748 if (!isset($contact[$field]) || ($contact[$field] == "")) {
749 $contact[$field] = $r[0][$field];
753 if (!isset($contact["hide"])) {
754 $contact["hide"] = $r[0]["hide"];
757 $fields["hide"] = $r[0]["hide"];
759 if ($contact["network"] == NETWORK_STATUSNET) {
760 $contact["network"] = NETWORK_OSTATUS;
763 // Replace alternate OStatus user format with the primary one
764 self::fixAlternateContactAddress($contact);
766 if (!isset($contact["updated"])) {
767 $contact["updated"] = DBM::date();
770 if ($contact["network"] == NETWORK_TWITTER) {
771 $contact["server_url"] = 'http://twitter.com';
774 if ($contact["server_url"] == "") {
775 $data = Probe::uri($contact["url"]);
776 if ($data["network"] != NETWORK_PHANTOM) {
777 $contact["server_url"] = $data['baseurl'];
780 $contact["server_url"] = normalise_link($contact["server_url"]);
783 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
784 $hostname = str_replace("http://", "", $contact["server_url"]);
785 $contact["addr"] = $contact["nick"]."@".$hostname;
788 // Check if any field changed
790 unset($fields["generation"]);
792 if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
793 foreach ($fields as $field => $data) {
794 if ($contact[$field] != $r[0][$field]) {
795 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
800 if ($contact["generation"] < $r[0]["generation"]) {
801 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
807 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
808 $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
809 normalise_link($contact["url"]), $contact["generation"]);
810 $contact["updated"] = DBM::date($contact["updated"]);
812 $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
813 'nick' => $contact['nick'], 'addr' => $contact['addr'],
814 'network' => $contact['network'], 'birthday' => $contact['birthday'],
815 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
816 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
817 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
818 'notify' => $contact['notify'], 'url' => $contact['url'],
819 'location' => $contact['location'], 'about' => $contact['about'],
820 'generation' => $contact['generation'], 'updated' => $contact['updated'],
821 'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
823 dba::update('gcontact', $updated, $condition, $fields);
825 // Now update the contact entry with the user id "0" as well.
826 // This is used for the shadow copies of public items.
828 "SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
829 dbesc(normalise_link($contact["url"]))
832 if (DBM::is_result($r)) {
833 logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
835 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
837 $fields = array('name', 'nick', 'addr',
838 'network', 'bd', 'gender',
839 'keywords', 'alias', 'contact-type',
840 'url', 'location', 'about');
841 $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
843 // Update it with the current values
844 $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
845 'addr' => $contact['addr'], 'network' => $contact['network'],
846 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
847 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
848 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
849 'location' => $contact['location'], 'about' => $contact['about']);
851 dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
859 * @brief Updates the gcontact entry from probe
861 * @param str $url profile link
863 public static function updateFromProbe($url)
865 $data = Probe::uri($url);
867 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
868 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
872 $data["server_url"] = $data["baseurl"];
878 * @brief Update the gcontact entry for a given user id
880 * @param int $uid User ID
882 public static function updateForUser($uid)
885 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
886 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
887 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
888 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
889 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
891 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
892 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
893 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
897 $location = Profile::formatLocation(
898 array("locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"])
901 // The "addr" field was added in 3.4.3 so it can be empty for older users
902 if ($r[0]["addr"] != "") {
903 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
905 $addr = $r[0]["addr"];
908 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
909 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
910 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
911 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
912 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
913 "nick" => $r[0]["nickname"], "addr" => $addr,
914 "connect" => $addr, "server_url" => System::baseUrl(),
915 "generation" => 1, "network" => NETWORK_DFRN);
917 self::update($gcontact);
921 * @brief Fetches users of given GNU Social server
923 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
925 * @param str $server Server address
927 public static function fetchGsUsers($server)
929 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
931 $url = $server."/main/statistics";
933 $result = z_fetch_url($url);
934 if (!$result["success"]) {
938 $statistics = json_decode($result["body"]);
940 if (is_object($statistics->config)) {
941 if ($statistics->config->instance_with_ssl) {
942 $server = "https://";
947 $server .= $statistics->config->instance_address;
949 $hostname = $statistics->config->instance_address;
951 /// @TODO is_object() above means here no object, still $statistics is being used as object
952 if ($statistics->instance_with_ssl) {
953 $server = "https://";
958 $server .= $statistics->instance_address;
960 $hostname = $statistics->instance_address;
963 if (is_object($statistics->users)) {
964 foreach ($statistics->users as $nick => $user) {
965 $profile_url = $server."/".$user->nickname;
967 $contact = array("url" => $profile_url,
968 "name" => $user->fullname,
969 "addr" => $user->nickname."@".$hostname,
970 "nick" => $user->nickname,
971 "about" => $user->bio,
972 "network" => NETWORK_OSTATUS,
973 "photo" => System::baseUrl()."/images/person-175.jpg");
974 self::getId($contact);
980 * @brief Asking GNU Social server on a regular base for their user data
983 public static function discoverGsUsers()
985 $requery_days = intval(Config::get("system", "poco_requery_days"));
987 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
990 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
991 dbesc(NETWORK_OSTATUS),
995 if (!DBM::is_result($r)) {
999 foreach ($r as $server) {
1000 self::fetchGsUsers($server["url"]);
1001 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1005 public static function getRandomUrl() {
1006 $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1007 AND `last_contact` >= `last_failure`
1008 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1009 ORDER BY rand() LIMIT 1",
1010 dbesc(NETWORK_DFRN));
1012 if (DBM::is_result($r))
1013 return dirname($r[0]['url']);