3 * @file src/Model/GlobalContact.php
4 * @brief This file includes the GlobalContact class with directory related functions
6 namespace Friendica\Model;
11 use Friendica\Core\Config;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
17 use Friendica\Network\Probe;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Protocol\PortableContact;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Util\Strings;
25 * @brief This class handles GlobalContact related functions
30 * @brief Search global contact table by nick or name
32 * @param string $search Name or nick
33 * @param string $mode Search mode (e.g. "community")
35 * @return array with search results
36 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
38 public static function searchByName($search, $mode = '')
44 // check supported networks
45 if (Config::get('system', 'diaspora_enabled')) {
46 $diaspora = Protocol::DIASPORA;
48 $diaspora = Protocol::DFRN;
51 if (!Config::get('system', 'ostatus_disabled')) {
52 $ostatus = Protocol::OSTATUS;
54 $ostatus = Protocol::DFRN;
57 // check if we search only communities or every contact
58 if ($mode === 'community') {
59 $extra_sql = ' AND `community`';
66 $results = DBA::p("SELECT `nurl` FROM `gcontact`
67 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
68 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
69 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
70 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
71 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
75 while ($result = DBA::fetch($results)) {
76 $urlparts = parse_url($result['nurl']);
78 // Ignore results that look strange.
79 // For historic reasons the gcontact table does contain some garbage.
80 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
84 $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
90 * @brief Link the gcontact entry with user, contact and global contact
92 * @param integer $gcid Global contact ID
93 * @param integer $uid User ID
94 * @param integer $cid Contact ID
95 * @param integer $zcid Global Contact ID
99 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
105 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
106 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
110 * @brief Sanitize the given gcontact data
114 * 1: Profiles on this server
115 * 2: Contacts of profiles on this server
116 * 3: Contacts of contacts of profiles on this server
119 * @param array $gcontact array with gcontact data
120 * @return array $gcontact
123 public static function sanitize($gcontact)
125 if (empty($gcontact['url'])) {
126 throw new Exception('URL is empty');
129 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
131 $urlparts = parse_url($gcontact['url']);
132 if (empty($urlparts['scheme'])) {
133 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
136 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
137 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
140 // Don't store the statusnet connector as network
141 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
142 if ($gcontact['network'] == Protocol::STATUSNET) {
143 $gcontact['network'] = '';
146 // Assure that there are no parameter fragments in the profile url
147 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
148 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
151 // The global contacts should contain the original picture, not the cached one
152 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(System::baseUrl() . '/photo/'))) {
153 $gcontact['photo'] = '';
156 if (empty($gcontact['network'])) {
157 $gcontact['network'] = '';
159 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
160 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
161 $contact = DBA::selectFirst('contact', ['network'], $condition);
162 if (DBA::isResult($contact)) {
163 $gcontact['network'] = $contact['network'];
166 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
167 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
168 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
169 $contact = DBA::selectFirst('contact', ['network'], $condition);
170 if (DBA::isResult($contact)) {
171 $gcontact['network'] = $contact['network'];
176 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
177 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
178 if (DBA::isResult($gcnt)) {
179 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
180 $gcontact['network'] = $gcnt['network'];
182 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
183 $gcontact['updated'] = $gcnt['updated'];
185 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
186 $gcontact['server_url'] = $gcnt['server_url'];
188 if (!isset($gcontact['addr'])) {
189 $gcontact['addr'] = $gcnt['addr'];
193 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
194 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
196 $data = Probe::uri($gcontact['url']);
198 if ($data['network'] == Protocol::PHANTOM) {
199 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
202 $orig_profile = $gcontact['url'];
204 $gcontact['server_url'] = $data['baseurl'];
206 $gcontact = array_merge($gcontact, $data);
209 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
210 throw new Exception('No name and photo for URL '.$gcontact['url']);
213 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
214 throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
217 if (empty($gcontact['server_url'])) {
218 // We check the server url to be sure that it is a real one
219 $server_url = Contact::getBasepath($gcontact['url']);
221 // We are now sure that it is a correct URL. So we use it in the future
222 if ($server_url != '') {
223 $gcontact['server_url'] = $server_url;
227 // The server URL doesn't seem to be valid, so we don't store it.
228 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
229 $gcontact['server_url'] = '';
236 * @param integer $uid id
237 * @param integer $cid id
241 public static function countCommonFriends($uid, $cid)
244 "SELECT count(*) as `total`
245 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
246 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
247 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
248 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
249 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
256 if (DBA::isResult($r)) {
257 return $r[0]['total'];
263 * @param integer $uid id
264 * @param integer $zcid zcid
268 public static function countCommonFriendsZcid($uid, $zcid)
271 "SELECT count(*) as `total`
272 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
273 where `glink`.`zcid` = %d
274 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
279 if (DBA::isResult($r)) {
280 return $r[0]['total'];
287 * @param integer $uid user
288 * @param integer $cid cid
289 * @param integer $start optional, default 0
290 * @param integer $limit optional, default 9999
291 * @param boolean $shuffle optional, default false
295 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
298 $sql_extra = " order by rand() ";
300 $sql_extra = " order by `gcontact`.`name` asc ";
304 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
306 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
307 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
308 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
309 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
310 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
311 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
312 $sql_extra LIMIT %d, %d",
321 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
326 * @param integer $uid user
327 * @param integer $zcid zcid
328 * @param integer $start optional, default 0
329 * @param integer $limit optional, default 9999
330 * @param boolean $shuffle optional, default false
334 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
337 $sql_extra = " order by rand() ";
339 $sql_extra = " order by `gcontact`.`name` asc ";
344 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
345 where `glink`.`zcid` = %d
346 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
347 $sql_extra limit %d, %d",
354 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
359 * @param integer $uid user
360 * @param integer $cid cid
364 public static function countAllFriends($uid, $cid)
367 "SELECT count(*) as `total`
368 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
369 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
370 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
375 if (DBA::isResult($r)) {
376 return $r[0]['total'];
383 * @param integer $uid user
384 * @param integer $cid cid
385 * @param integer $start optional, default 0
386 * @param integer $limit optional, default 80
390 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
393 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
395 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
396 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
397 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
398 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
399 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
407 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
412 * @param int $uid user
413 * @param integer $start optional, default 0
414 * @param integer $limit optional, default 80
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 public static function suggestionQuery($uid, $start = 0, $limit = 80)
424 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
426 if (Config::get('system', 'diaspora_enabled')) {
427 $network[] = Protocol::DIASPORA;
430 if (!Config::get('system', 'ostatus_disabled')) {
431 $network[] = Protocol::OSTATUS;
434 $sql_network = "'" . implode("', '", $network) . "'";
436 /// @todo This query is really slow
437 // By now we cache the data for five minutes
439 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
440 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
441 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
442 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
443 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
444 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
445 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
446 AND `gcontact`.`network` IN (%s)
447 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
458 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
463 "SELECT gcontact.* FROM gcontact
464 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
465 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
466 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
467 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
468 AND `gcontact`.`updated` >= '%s'
469 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
470 AND `gcontact`.`network` IN (%s)
471 ORDER BY rand() LIMIT %d, %d",
482 foreach ($r2 as $suggestion) {
483 $list[$suggestion['nurl']] = $suggestion;
486 foreach ($r as $suggestion) {
487 $list[$suggestion['nurl']] = $suggestion;
490 while (sizeof($list) > ($limit)) {
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 public static function updateSuggestions()
505 /// @TODO Check if it is really neccessary to poll the own server
506 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
508 $done[] = System::baseUrl() . '/poco';
510 if (strlen(Config::get('system', 'directory'))) {
511 $x = Network::fetchUrl(get_server() . '/pubsites');
513 $j = json_decode($x);
514 if (!empty($j->entries)) {
515 foreach ($j->entries as $entry) {
516 GServer::check($entry->url);
518 $url = $entry->url . '/poco';
519 if (!in_array($url, $done)) {
520 PortableContact::loadWorker(0, 0, 0, $url);
528 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
529 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
530 while ($contact = DBA::fetch($contacts)) {
531 $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
532 if (!in_array($base, $done)) {
533 PortableContact::loadWorker(0, 0, 0, $base);
539 * @brief Removes unwanted parts from a contact url
541 * @param string $url Contact url
543 * @return string Contact url with the wanted parts
546 public static function cleanContactUrl($url)
548 $parts = parse_url($url);
550 if (empty($parts['scheme']) || empty($parts['host'])) {
554 $new_url = $parts['scheme'] . '://' . $parts['host'];
556 if (!empty($parts['port'])) {
557 $new_url .= ':' . $parts['port'];
560 if (!empty($parts['path'])) {
561 $new_url .= $parts['path'];
564 if ($new_url != $url) {
565 Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
572 * @brief Fetch the gcontact id, add an entry if not existed
574 * @param array $contact contact array
576 * @return bool|int Returns false if not found, integer if contact was found
577 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
578 * @throws \ImagickException
580 public static function getId($contact)
584 $last_failure_str = '';
585 $last_contact_str = '';
587 if (empty($contact['network'])) {
588 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
592 if (in_array($contact['network'], [Protocol::PHANTOM])) {
593 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
597 if ($contact['network'] == Protocol::STATUSNET) {
598 $contact['network'] = Protocol::OSTATUS;
601 // All new contacts are hidden by default
602 if (!isset($contact['hide'])) {
603 $contact['hide'] = true;
606 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
607 if (in_array($contact['network'], Protocol::FEDERATED)) {
608 $contact['url'] = self::cleanContactUrl($contact['url']);
611 DBA::lock('gcontact');
612 $fields = ['id', 'last_contact', 'last_failure', 'network'];
613 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
614 if (DBA::isResult($gcnt)) {
615 $gcontact_id = $gcnt['id'];
617 // Update every 90 days
618 if (empty($gcnt['network']) || in_array($gcnt['network'], Protocol::FEDERATED)) {
619 $last_failure_str = $gcnt['last_failure'];
620 $last_failure = strtotime($gcnt['last_failure']);
621 $last_contact_str = $gcnt['last_contact'];
622 $last_contact = strtotime($gcnt['last_contact']);
623 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
626 $contact['location'] = $contact['location'] ?? '';
627 $contact['about'] = $contact['about'] ?? '';
628 $contact['generation'] = $contact['generation'] ?? 0;
630 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
631 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
632 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
633 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
635 DBA::insert('gcontact', $fields);
637 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
638 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
639 if (DBA::isResult($cnt)) {
640 $gcontact_id = $cnt['id'];
641 $doprobing = (empty($cnt['network']) || in_array($cnt['network'], Protocol::FEDERATED));
647 Logger::notice('Probing', ['contact' => $last_contact_str, "failure" => $last_failure_str, "checking" => $contact['url']]);
648 Worker::add(PRIORITY_LOW, 'GProbe', $contact['url']);
655 * @brief Updates the gcontact table from a given array
657 * @param array $contact contact array
659 * @return bool|int Returns false if not found, integer if contact was found
660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
661 * @throws \ImagickException
663 public static function update($contact)
665 // Check for invalid "contact-type" value
666 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
667 $contact['contact-type'] = 0;
670 /// @todo update contact table as well
672 $gcontact_id = self::getId($contact);
678 $public_contact = DBA::selectFirst('gcontact', [
679 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
680 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
681 ], ['id' => $gcontact_id]);
683 if (!DBA::isResult($public_contact)) {
687 // Get all field names
689 foreach ($public_contact as $field => $data) {
690 $fields[$field] = $data;
693 unset($fields['url']);
694 unset($fields['updated']);
695 unset($fields['hide']);
697 // Bugfix: We had an error in the storing of keywords which lead to the "0"
698 // This value is still transmitted via poco.
699 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
700 unset($contact['keywords']);
703 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
704 $public_contact['keywords'] = '';
707 // assign all unassigned fields from the database entry
708 foreach ($fields as $field => $data) {
709 if (empty($contact[$field])) {
710 $contact[$field] = $public_contact[$field];
714 if (!isset($contact['hide'])) {
715 $contact['hide'] = $public_contact['hide'];
718 $fields['hide'] = $public_contact['hide'];
720 if ($contact['network'] == Protocol::STATUSNET) {
721 $contact['network'] = Protocol::OSTATUS;
724 if (!isset($contact['updated'])) {
725 $contact['updated'] = DateTimeFormat::utcNow();
728 if ($contact['network'] == Protocol::TWITTER) {
729 $contact['server_url'] = 'http://twitter.com';
732 if (empty($contact['server_url'])) {
733 $data = Probe::uri($contact['url']);
734 if ($data['network'] != Protocol::PHANTOM) {
735 $contact['server_url'] = $data['baseurl'];
738 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
741 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
742 $hostname = str_replace('http://', '', $contact['server_url']);
743 $contact['addr'] = $contact['nick'] . '@' . $hostname;
746 // Check if any field changed
748 unset($fields['generation']);
750 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
751 foreach ($fields as $field => $data) {
752 if ($contact[$field] != $public_contact[$field]) {
753 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
758 if ($contact['generation'] < $public_contact['generation']) {
759 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
765 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
766 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
767 Strings::normaliseLink($contact['url']), $contact['generation']];
768 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
771 'photo' => $contact['photo'], 'name' => $contact['name'],
772 'nick' => $contact['nick'], 'addr' => $contact['addr'],
773 'network' => $contact['network'], 'birthday' => $contact['birthday'],
774 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
775 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
776 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
777 'notify' => $contact['notify'], 'url' => $contact['url'],
778 'location' => $contact['location'], 'about' => $contact['about'],
779 'generation' => $contact['generation'], 'updated' => $contact['updated'],
780 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
783 DBA::update('gcontact', $updated, $condition, $fields);
790 * Set the last date that the contact had posted something
792 * @param string $data Probing result
793 * @param bool $force force updating
795 public static function setLastUpdate(array $data, bool $force = false)
797 // Fetch the global contact
798 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
799 ['nurl' => Strings::normaliseLink($data['url'])]);
800 if (!DBA::isResult($gcontact)) {
804 if (!$force && !PortableContact::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
805 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
809 if (self::updateFromNoScrape($data)) {
813 if (!empty($data['outbox'])) {
814 self::updateFromOutbox($data['outbox'], $data);
815 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
816 self::updateFromOutbox($data['poll'], $data);
817 } elseif (!empty($data['poll'])) {
818 self::updateFromFeed($data);
823 * Update a global contact via the "noscrape" endpoint
825 * @param string $data Probing result
827 * @return bool 'true' if update was successful or the server was unreachable
829 private static function updateFromNoScrape(array $data)
831 // Check the 'noscrape' endpoint when it is a Friendica server
832 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
833 Strings::normaliseLink($data['baseurl'])]);
834 if (!DBA::isResult($gserver)) {
838 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
840 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
841 $noscrape = json_decode($curlResult->getBody(), true);
842 if (!empty($noscrape) && !empty($noscrape['updated'])) {
843 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
844 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
845 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
848 } elseif ($curlResult->isTimeout()) {
849 // On a timeout return the existing value, but mark the contact as failure
850 $fields = ['last_failure' => DateTimeFormat::utcNow()];
851 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
858 * Update a global contact via an ActivityPub Outbox
860 * @param string $feed
861 * @param array $data Probing result
862 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864 private static function updateFromOutbox(string $feed, array $data)
866 $outbox = ActivityPub::fetchContent($feed);
867 if (empty($outbox)) {
871 if (!empty($outbox['orderedItems'])) {
872 $items = $outbox['orderedItems'];
873 } elseif (!empty($outbox['first']['orderedItems'])) {
874 $items = $outbox['first']['orderedItems'];
875 } elseif (!empty($outbox['first']['href'])) {
876 self::updateFromOutbox($outbox['first']['href'], $data);
878 } elseif (!empty($outbox['first'])) {
879 self::updateFromOutbox($outbox['first'], $data);
886 foreach ($items as $activity) {
887 if (!empty($activity['published'])) {
888 $published = DateTimeFormat::utc($activity['published']);
889 } elseif (!empty($activity['object']['published'])) {
890 $published = DateTimeFormat::utc($activity['object']['published']);
895 if ($last_updated < $published) {
896 $last_updated = $published;
900 if (empty($last_updated)) {
904 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
905 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
909 * Update a global contact via an XML feed
911 * @param string $data Probing result
913 private static function updateFromFeed(array $data)
915 // Search for the newest entry in the feed
916 $curlResult = Network::curl($data['poll']);
917 if (!$curlResult->isSuccess()) {
918 $fields = ['last_failure' => DateTimeFormat::utcNow()];
919 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
921 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
925 $doc = new DOMDocument();
926 @$doc->loadXML($curlResult->getBody());
928 $xpath = new DOMXPath($doc);
929 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
931 $entries = $xpath->query('/atom:feed/atom:entry');
935 foreach ($entries as $entry) {
936 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
937 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
938 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
939 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
941 if (empty($published) || empty($updated)) {
942 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
946 if ($last_updated < $published) {
947 $last_updated = $published;
950 if ($last_updated < $updated) {
951 $last_updated = $updated;
955 if (empty($last_updated)) {
959 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
960 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
963 * @brief Updates the gcontact entry from a given public contact id
965 * @param integer $cid contact id
967 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
968 * @throws \ImagickException
970 public static function updateFromPublicContactID($cid)
972 self::updateFromPublicContact(['id' => $cid]);
976 * @brief Updates the gcontact entry from a given public contact url
978 * @param string $url contact url
979 * @return integer gcontact id
980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
981 * @throws \ImagickException
983 public static function updateFromPublicContactURL($url)
985 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
989 * @brief Helper function for updateFromPublicContactID and updateFromPublicContactURL
991 * @param array $condition contact condition
992 * @return integer gcontact id
993 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994 * @throws \ImagickException
996 private static function updateFromPublicContact($condition)
998 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
999 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1000 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1001 'baseurl', 'sensitive', 'unsearchable'];
1003 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1004 if (!DBA::isResult($contact)) {
1008 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
1009 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1010 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1011 'server_url', 'nsfw', 'hide', 'id'];
1013 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1014 $do_insert = !DBA::isResult($old_gcontact);
1021 // These fields are identical in both contact and gcontact
1022 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1023 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1025 foreach ($fields as $field) {
1026 $gcontact[$field] = $contact[$field];
1029 // These fields are having different names but the same content
1030 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1031 $gcontact['nsfw'] = $contact['sensitive'];
1032 $gcontact['hide'] = $contact['unsearchable'];
1033 $gcontact['archived'] = $contact['archive'];
1034 $gcontact['archive_date'] = $contact['term-date'];
1035 $gcontact['birthday'] = $contact['bd'];
1036 $gcontact['photo'] = $contact['avatar'];
1037 $gcontact['last_contact'] = $contact['success_update'];
1038 $gcontact['last_failure'] = $contact['failure_update'];
1039 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1041 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1042 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1043 unset($gcontact[$field]);
1047 if (!$gcontact['archived']) {
1048 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1051 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1052 && ($old_gcontact['created'] <= $gcontact['created'])) {
1053 unset($gcontact['created']);
1056 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1057 unset($gcontact['birthday']);
1060 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1061 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1065 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1066 return $old_gcontact['id'];
1067 } elseif (!$gcontact['archived']) {
1068 DBA::insert('gcontact', $gcontact);
1069 return DBA::lastInsertId();
1074 * @brief Updates the gcontact entry from probe
1076 * @param string $url profile link
1077 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1079 * @return boolean 'true' when contact had been updated
1081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1082 * @throws \ImagickException
1084 public static function updateFromProbe($url, $force = false)
1086 $data = Probe::uri($url, $force);
1088 if (in_array($data['network'], [Protocol::PHANTOM])) {
1089 $fields = ['last_failure' => DateTimeFormat::utcNow()];
1090 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1091 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1095 $data['server_url'] = $data['baseurl'];
1097 self::update($data);
1099 // Set the date of the latest post
1100 self::setLastUpdate($data, $force);
1106 * @brief Update the gcontact entry for a given user id
1108 * @param int $uid User ID
1110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1111 * @throws \ImagickException
1113 public static function updateForUser($uid)
1115 $profile = Profile::getByUID($uid);
1116 if (empty($profile)) {
1117 Logger::error('Cannot find profile', ['uid' => $uid]);
1121 $user = User::getOwnerDataById($uid);
1123 Logger::error('Cannot find user', ['uid' => $uid]);
1127 $userdata = array_merge($profile, $user);
1129 $location = Profile::formatLocation(
1130 ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1133 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1134 'gender' => $userdata['gender'], 'keywords' => $userdata['pub_keywords'],
1135 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1136 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1137 "hide" => ($userdata['hidewall'] || !$userdata['net-publish']),
1138 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1139 "connect" => $userdata['addr'], "server_url" => System::baseUrl(),
1140 "generation" => 1, 'network' => Protocol::DFRN];
1142 self::update($gcontact);
1146 * @brief Fetches users of given GNU Social server
1148 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1150 * @param string $server Server address
1152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1153 * @throws \ImagickException
1155 public static function fetchGsUsers($server)
1157 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1159 $url = $server . '/main/statistics';
1161 $curlResult = Network::curl($url);
1162 if (!$curlResult->isSuccess()) {
1166 $statistics = json_decode($curlResult->getBody());
1168 if (!empty($statistics->config->instance_address)) {
1169 if (!empty($statistics->config->instance_with_ssl)) {
1170 $server = 'https://';
1172 $server = 'http://';
1175 $server .= $statistics->config->instance_address;
1177 $hostname = $statistics->config->instance_address;
1178 } elseif (!empty($statistics->instance_address)) {
1179 if (!empty($statistics->instance_with_ssl)) {
1180 $server = 'https://';
1182 $server = 'http://';
1185 $server .= $statistics->instance_address;
1187 $hostname = $statistics->instance_address;
1190 if (!empty($statistics->users)) {
1191 foreach ($statistics->users as $nick => $user) {
1192 $profile_url = $server . '/' . $user->nickname;
1194 $contact = ['url' => $profile_url,
1195 'name' => $user->fullname,
1196 'addr' => $user->nickname . '@' . $hostname,
1197 'nick' => $user->nickname,
1198 "network" => Protocol::OSTATUS,
1199 'photo' => System::baseUrl() . '/images/person-300.jpg'];
1201 if (isset($user->bio)) {
1202 $contact['about'] = $user->bio;
1205 self::getId($contact);
1211 * @brief Asking GNU Social server on a regular base for their user data
1213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1214 * @throws \ImagickException
1216 public static function discoverGsUsers()
1218 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1220 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1222 $r = DBA::select('gserver', ['nurl', 'url'], [
1224 AND `last_contact` >= `last_failure`
1225 AND `last_poco_query` < ?',
1230 'order' => ['RAND()']
1233 if (!DBA::isResult($r)) {
1237 foreach ($r as $server) {
1238 self::fetchGsUsers($server['url']);
1239 DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1244 * Returns a random, global contact of the current node
1246 * @return string The profile URL
1249 public static function getRandomUrl()
1251 $r = DBA::selectFirst('gcontact', ['url'], [
1253 AND `last_contact` >= `last_failure`
1256 DateTimeFormat::utc('now - 1 month'),
1257 ], ['order' => ['RAND()']]);
1259 if (DBA::isResult($r)) {