+
+ /**
+ * Search contact table by nick or name
+ *
+ * @param string $search Name or nick
+ * @param string $mode Search mode (e.g. "community")
+ *
+ * @return array with search results
+ * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ */
+ public static function searchByName($search, $mode = '')
+ {
+ if (empty($search)) {
+ return [];
+ }
+
+ // check supported networks
+ if (DI::config()->get('system', 'diaspora_enabled')) {
+ $diaspora = Protocol::DIASPORA;
+ } else {
+ $diaspora = Protocol::DFRN;
+ }
+
+ if (!DI::config()->get('system', 'ostatus_disabled')) {
+ $ostatus = Protocol::OSTATUS;
+ } else {
+ $ostatus = Protocol::DFRN;
+ }
+
+ // check if we search only communities or every contact
+ if ($mode === 'community') {
+ $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
+ } else {
+ $extra_sql = '';
+ }
+
+ $search .= '%';
+
+ $results = DBA::p("SELECT * FROM `contact`
+ WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
+ NOT `failed` AND `uid` = ? AND
+ (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
+ ORDER BY `nurl` DESC LIMIT 1000",
+ Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
+ );
+
+ $contacts = DBA::toArray($results);
+ return $contacts;
+ }
+
+ /**
+ * @param int $uid user
+ * @param int $start optional, default 0
+ * @param int $limit optional, default 80
+ * @return array
+ */
+ static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
+ {
+ $cid = self::getPublicIdByUserId($uid);
+ $totallimit = $start + $limit;
+ $contacts = [];
+
+ Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
+
+ $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
+ $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
+
+ // The query returns contacts where contacts interacted with whom the given user follows.
+ // Contacts who already are in the user's contact table are ignored.
+ $results = DBA::select('contact', [],
+ ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
+ (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
+ AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
+ (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
+ AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
+ $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
+ Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
+ ['order' => ['last-item' => true], 'limit' => $totallimit]
+ );
+
+ while ($contact = DBA::fetch($results)) {
+ $contacts[$contact['id']] = $contact;
+ }
+ DBA::close($results);
+
+ Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
+
+ if (count($contacts) >= $totallimit) {
+ return array_slice($contacts, $start, $limit);
+ }
+
+ // The query returns contacts where contacts interacted with whom also interacted with the given user.
+ // Contacts who already are in the user's contact table are ignored.
+ $results = DBA::select('contact', [],
+ ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
+ (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
+ AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
+ (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
+ AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
+ $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
+ Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
+ ['order' => ['last-item' => true], 'limit' => $totallimit]
+ );
+
+ while ($contact = DBA::fetch($results)) {
+ $contacts[$contact['id']] = $contact;
+ }
+ DBA::close($results);
+
+ Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
+
+ if (count($contacts) >= $totallimit) {
+ return array_slice($contacts, $start, $limit);
+ }
+
+ // The query returns contacts that follow the given user but aren't followed by that user.
+ $results = DBA::select('contact', [],
+ ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
+ AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
+ $uid, Contact::FOLLOWER, 0,
+ Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
+ ['order' => ['last-item' => true], 'limit' => $totallimit]
+ );
+
+ while ($contact = DBA::fetch($results)) {
+ $contacts[$contact['id']] = $contact;
+ }
+ DBA::close($results);
+
+ Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
+
+ if (count($contacts) >= $totallimit) {
+ return array_slice($contacts, $start, $limit);
+ }
+
+ // The query returns any contact that isn't followed by that user.
+ $results = DBA::select('contact', [],
+ ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
+ AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
+ $uid, Contact::FRIEND, Contact::SHARING, 0,
+ Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
+ ['order' => ['last-item' => true], 'limit' => $totallimit]
+ );
+
+ while ($contact = DBA::fetch($results)) {
+ $contacts[$contact['id']] = $contact;
+ }
+ DBA::close($results);
+
+ Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
+
+ return array_slice($contacts, $start, $limit);
+ }
+
+ /**
+ * Returns a list of all common friends between two given public contact ids.
+ *
+ * @param int $cid1 first public contact id
+ * @param int $cid2 second public contact id
+ * @return int
+ */
+ public static function countContactsOfContact(int $cid)
+ {
+ return DBA::count('contact',
+ ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
+ OR `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
+ $cid, $cid]
+ );
+ }
+
+ /**
+ * Returns a list of all contacts of a given public contact id.
+ *
+ * @param int $cid public contact id
+ * @param int $start optional, default 0
+ * @param int $limit optional, default 80
+ * @return array
+ */
+ public static function getContactsOfContact(int $cid, int $start = 0, int $limit = 80)
+ {
+ return DBA::selectToArray('contact', [],
+ ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
+ OR `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
+ $cid, $cid],
+ ['limit' => [$start, $limit]]
+ );
+ }
+
+ /**
+ * Add public contacts from an array
+ *
+ * @param array $urls
+ * @return array result "count", "added" and "updated"
+ */
+ public static function addByUrls(array $urls)
+ {
+ $added = 0;
+ $updated = 0;
+ $count = 0;
+
+ foreach ($urls as $url) {
+ $contact = Contact::getByURL($url, false, ['id']);
+ if (empty($contact['id'])) {
+ Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
+ ++$added;
+ } else {
+ Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
+ ++$updated;
+ }
+ ++$count;
+ }
+
+ return ['count' => $count, 'added' => $added, 'updated' => $updated];
+ }
+
+ /**
+ * Set the last date that the contact had posted something
+ *
+ * This functionality is currently unused
+ *
+ * @param string $data probing result
+ * @param bool $force force updating
+ */
+ private static function setLastUpdate(array $data, bool $force = false)
+ {
+ $contact = self::getByURL($data['url'], false, []);
+ if (empty($contact)) {
+ return;
+ }
+ if (!$force && !GServer::updateNeeded($contact['created'], $contact['updated'], $contact['last_failure'], $contact['last_contact'])) {
+ Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $contact['updated']]);
+ return;
+ }
+
+ if (self::updateFromNoScrape($data)) {
+ return;
+ }
+
+ if (!empty($data['outbox'])) {
+ self::updateFromOutbox($data['outbox'], $data);
+ } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
+ self::updateFromOutbox($data['poll'], $data);
+ } elseif (!empty($data['poll'])) {
+ self::updateFromFeed($data);
+ }
+ }
+
+ /**
+ * Update a global contact via the "noscrape" endpoint
+ *
+ * @param string $data Probing result
+ *
+ * @return bool 'true' if update was successful or the server was unreachable
+ */
+ private static function updateFromNoScrape(array $data)
+ {
+ // Check the 'noscrape' endpoint when it is a Friendica server
+ $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
+ Strings::normaliseLink($data['baseurl'])]);
+ if (!DBA::isResult($gserver)) {
+ return false;
+ }
+
+ $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
+
+ if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
+ $noscrape = json_decode($curlResult->getBody(), true);
+ if (!empty($noscrape) && !empty($noscrape['updated'])) {
+ $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
+ $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
+ DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
+ return true;
+ }
+ } elseif ($curlResult->isTimeout()) {
+ // On a timeout return the existing value, but mark the contact as failure
+ $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
+ DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Update a global contact via an ActivityPub Outbox
+ *
+ * @param string $feed
+ * @param array $data Probing result
+ * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ */
+ private static function updateFromOutbox(string $feed, array $data)
+ {
+ $outbox = ActivityPub::fetchContent($feed);
+ if (empty($outbox)) {
+ return;
+ }
+
+ if (!empty($outbox['orderedItems'])) {
+ $items = $outbox['orderedItems'];
+ } elseif (!empty($outbox['first']['orderedItems'])) {
+ $items = $outbox['first']['orderedItems'];
+ } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
+ self::updateFromOutbox($outbox['first']['href'], $data);
+ return;
+ } elseif (!empty($outbox['first'])) {
+ if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
+ self::updateFromOutbox($outbox['first'], $data);
+ } else {
+ Logger::warning('Unexpected data', ['outbox' => $outbox]);
+ }
+ return;
+ } else {
+ $items = [];
+ }
+
+ $last_updated = '';
+ foreach ($items as $activity) {
+ if (!empty($activity['published'])) {
+ $published = DateTimeFormat::utc($activity['published']);
+ } elseif (!empty($activity['object']['published'])) {
+ $published = DateTimeFormat::utc($activity['object']['published']);
+ } else {
+ continue;
+ }
+
+ if ($last_updated < $published) {
+ $last_updated = $published;
+ }
+ }
+
+ if (empty($last_updated)) {
+ return;
+ }
+
+ $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
+ DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
+ }
+
+ /**
+ * Update a global contact via an XML feed
+ *
+ * @param string $data Probing result
+ */
+ private static function updateFromFeed(array $data)
+ {
+ // Search for the newest entry in the feed
+ $curlResult = DI::httpRequest()->get($data['poll']);
+ if (!$curlResult->isSuccess()) {
+ $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
+ DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
+
+ Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
+ return;
+ }
+
+ $doc = new DOMDocument();
+ @$doc->loadXML($curlResult->getBody());
+
+ $xpath = new DOMXPath($doc);
+ $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
+
+ $entries = $xpath->query('/atom:feed/atom:entry');
+
+ $last_updated = '';
+
+ foreach ($entries as $entry) {
+ $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
+ $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
+ $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
+ $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
+
+ if (empty($published) || empty($updated)) {
+ Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
+ continue;
+ }
+
+ if ($last_updated < $published) {
+ $last_updated = $published;
+ }
+
+ if ($last_updated < $updated) {
+ $last_updated = $updated;
+ }
+ }
+
+ if (empty($last_updated)) {
+ return;
+ }
+
+ $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
+ DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
+ }
+
+ /**
+ * Returns a random, global contact of the current node
+ *
+ * @return string The profile URL
+ * @throws Exception
+ */
+ public static function getRandomUrl()
+ {
+ $r = DBA::selectFirst('contact', ['url'], [
+ "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
+ 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
+ ], ['order' => ['RAND()']]);
+
+ if (DBA::isResult($r)) {
+ return $r['url'];
+ }
+
+ return '';
+ }