3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Network\Probe;
19 use Friendica\Object\Image;
20 use Friendica\Protocol\ActivityPub;
21 use Friendica\Protocol\DFRN;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\PortableContact;
25 use Friendica\Protocol\Salmon;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
30 require_once 'boot.php';
31 require_once 'include/dba.php';
32 require_once 'include/text.php';
35 * @brief functions for interacting with a contact
37 class Contact extends BaseObject
40 * @name page/profile types
42 * PAGE_NORMAL is a typical personal profile account
43 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
44 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
45 * write access to wall and comments (no email and not included in page owner's ACL lists)
46 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
50 const PAGE_NORMAL = 0;
51 const PAGE_SOAPBOX = 1;
52 const PAGE_COMMUNITY = 2;
53 const PAGE_FREELOVE = 3;
55 const PAGE_PRVGROUP = 5;
63 * ACCOUNT_TYPE_PERSON - the account belongs to a person
64 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
66 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
67 * Associated page type: PAGE_SOAPBOX
69 * ACCOUNT_TYPE_NEWS - the account is a news reflector
70 * Associated page type: PAGE_SOAPBOX
72 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
73 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
75 * ACCOUNT_TYPE_RELAY - the account is a relay
76 * This will only be assigned to contacts, not to user accounts
79 const ACCOUNT_TYPE_PERSON = 0;
80 const ACCOUNT_TYPE_ORGANISATION = 1;
81 const ACCOUNT_TYPE_NEWS = 2;
82 const ACCOUNT_TYPE_COMMUNITY = 3;
83 const ACCOUNT_TYPE_RELAY = 4;
102 * @brief Returns the contact id for the user and the public contact id for a given contact id
104 * @param int $cid Either public contact id or user's contact id
105 * @param int $uid User ID
107 * @return array with public and user's contact id
109 private static function getPublicAndUserContacID($cid, $uid)
111 if (empty($uid) || empty($cid)) {
115 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
116 if (!DBA::isResult($contact)) {
120 // We quit when the user id don't match the user id of the provided contact
121 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
125 if ($contact['uid'] != 0) {
126 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
130 $ucid = $contact['id'];
132 $pcid = $contact['id'];
133 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
136 return ['public' => $pcid, 'user' => $ucid];
140 * @brief Block contact id for user id
142 * @param int $cid Either public contact id or user's contact id
143 * @param int $uid User ID
144 * @param boolean $blocked Is the contact blocked or unblocked?
146 public static function setBlockedForUser($cid, $uid, $blocked)
148 $cdata = self::getPublicAndUserContacID($cid, $uid);
153 if ($cdata['user'] != 0) {
154 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
157 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
161 * @brief Returns "block" state for contact id and user id
163 * @param int $cid Either public contact id or user's contact id
164 * @param int $uid User ID
166 * @return boolean is the contact id blocked for the given user?
168 public static function isBlockedByUser($cid, $uid)
170 $cdata = self::getPublicAndUserContacID($cid, $uid);
175 $public_blocked = false;
177 if (!empty($cdata['public'])) {
178 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
179 if (DBA::isResult($public_contact)) {
180 $public_blocked = $public_contact['blocked'];
184 $user_blocked = $public_blocked;
186 if (!empty($cdata['user'])) {
187 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
188 if (DBA::isResult($user_contact)) {
189 $user_blocked = $user_contact['blocked'];
193 if ($user_blocked != $public_blocked) {
194 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
197 return $user_blocked;
201 * @brief Ignore contact id for user id
203 * @param int $cid Either public contact id or user's contact id
204 * @param int $uid User ID
205 * @param boolean $ignored Is the contact ignored or unignored?
207 public static function setIgnoredForUser($cid, $uid, $ignored)
209 $cdata = self::getPublicAndUserContacID($cid, $uid);
214 if ($cdata['user'] != 0) {
215 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
218 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
222 * @brief Returns "ignore" state for contact id and user id
224 * @param int $cid Either public contact id or user's contact id
225 * @param int $uid User ID
227 * @return boolean is the contact id ignored for the given user?
229 public static function isIgnoredByUser($cid, $uid)
231 $cdata = self::getPublicAndUserContacID($cid, $uid);
236 $public_ignored = false;
238 if (!empty($cdata['public'])) {
239 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
240 if (DBA::isResult($public_contact)) {
241 $public_ignored = $public_contact['ignored'];
245 $user_ignored = $public_ignored;
247 if (!empty($cdata['user'])) {
248 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
249 if (DBA::isResult($user_contact)) {
250 $user_ignored = $user_contact['readonly'];
254 if ($user_ignored != $public_ignored) {
255 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
258 return $user_ignored;
262 * @brief Set "collapsed" for contact id and user id
264 * @param int $cid Either public contact id or user's contact id
265 * @param int $uid User ID
266 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
268 public static function setCollapsedForUser($cid, $uid, $collapsed)
270 $cdata = self::getPublicAndUserContacID($cid, $uid);
275 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
279 * @brief Returns "collapsed" state for contact id and user id
281 * @param int $cid Either public contact id or user's contact id
282 * @param int $uid User ID
284 * @return boolean is the contact id blocked for the given user?
286 public static function isCollapsedByUser($cid, $uid)
288 $cdata = self::getPublicAndUserContacID($cid, $uid);
295 if (!empty($cdata['public'])) {
296 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
297 if (DBA::isResult($public_contact)) {
298 $collapsed = $public_contact['collapsed'];
306 * @brief Returns a list of contacts belonging in a group
311 public static function getByGroupId($gid)
316 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
318 INNER JOIN `group_member`
319 ON `contact`.`id` = `group_member`.`contact-id`
321 AND `contact`.`uid` = ?
322 AND NOT `contact`.`self`
323 AND NOT `contact`.`blocked`
324 AND NOT `contact`.`pending`
325 ORDER BY `contact`.`name` ASC',
330 if (DBA::isResult($stmt)) {
331 $return = DBA::toArray($stmt);
339 * @brief Returns the count of OStatus contacts in a group
344 public static function getOStatusCountByGroupId($gid)
348 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
350 INNER JOIN `group_member`
351 ON `contact`.`id` = `group_member`.`contact-id`
353 AND `contact`.`uid` = ?
354 AND `contact`.`network` = ?
355 AND `contact`.`notify` != ""',
360 $return = $contacts['count'];
367 * Creates the self-contact for the provided user id
370 * @return bool Operation success
372 public static function createSelfFromUserId($uid)
374 // Only create the entry if it doesn't exist yet
375 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
379 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
380 if (!DBA::isResult($user)) {
384 $return = DBA::insert('contact', [
385 'uid' => $user['uid'],
386 'created' => DateTimeFormat::utcNow(),
388 'name' => $user['username'],
389 'nick' => $user['nickname'],
390 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
391 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
392 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
395 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
396 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
397 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
398 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
399 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
400 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
401 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
402 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
403 'name-date' => DateTimeFormat::utcNow(),
404 'uri-date' => DateTimeFormat::utcNow(),
405 'avatar-date' => DateTimeFormat::utcNow(),
413 * Updates the self-contact for the provided user id
416 * @param boolean $update_avatar Force the avatar update
418 public static function updateSelfFromUserID($uid, $update_avatar = false)
420 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
421 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
422 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
423 if (!DBA::isResult($self)) {
427 $fields = ['nickname', 'page-flags', 'account-type'];
428 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
429 if (!DBA::isResult($user)) {
433 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
434 'country-name', 'gender', 'pub_keywords', 'xmpp'];
435 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
436 if (!DBA::isResult($profile)) {
440 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
441 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
442 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
443 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
444 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
446 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
447 if (DBA::isResult($avatar)) {
448 if ($update_avatar) {
449 $fields['avatar-date'] = DateTimeFormat::utcNow();
452 // Creating the path to the avatar, beginning with the file suffix
453 $types = Image::supportedTypes();
454 if (isset($types[$avatar['type']])) {
455 $file_suffix = $types[$avatar['type']];
457 $file_suffix = 'jpg';
460 // We are adding a timestamp value so that other systems won't use cached content
461 $timestamp = strtotime($fields['avatar-date']);
463 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
464 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
466 $fields['photo'] = $prefix . '4' . $suffix;
467 $fields['thumb'] = $prefix . '5' . $suffix;
468 $fields['micro'] = $prefix . '6' . $suffix;
470 // We hadn't found a photo entry, so we use the default avatar
471 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
472 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
473 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
476 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
477 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
479 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
480 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
481 $fields['nurl'] = Strings::normaliseLink($fields['url']);
482 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
483 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
484 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
485 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
486 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
487 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
491 foreach ($fields as $field => $content) {
492 if (isset($self[$field]) && $self[$field] != $content) {
498 $fields['name-date'] = DateTimeFormat::utcNow();
499 DBA::update('contact', $fields, ['id' => $self['id']]);
501 // Update the public contact as well
502 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
504 // Update the profile
505 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
506 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
507 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
512 * @brief Marks a contact for removal
514 * @param int $id contact id
517 public static function remove($id)
519 // We want just to make sure that we don't delete our "self" contact
520 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
521 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
525 // Archive the contact
526 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
528 // Delete it in the background
529 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
533 * @brief Sends an unfriend message. Does not remove the contact
535 * @param array $user User unfriending
536 * @param array $contact Contact unfriended
537 * @param boolean $dissolve Remove the contact on the remote side
540 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
542 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
543 DFRN::deliver($user, $contact, 'placeholder', true);
544 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
545 // create an unfollow slap
547 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
548 $item['follow'] = $contact["url"];
553 $item['attach'] = '';
554 $slap = OStatus::salmon($item, $user);
556 if (!empty($contact['notify'])) {
557 Salmon::slapper($user, $contact['notify'], $slap);
559 } elseif ($contact['network'] == Protocol::DIASPORA) {
560 Diaspora::sendUnshare($user, $contact);
561 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
562 ActivityPub\Transmitter::sendContactUndo($contact['url'], $user['uid']);
565 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
571 * @brief Marks a contact for archival after a communication issue delay
573 * Contact has refused to recognise us as a friend. We will start a countdown.
574 * If they still don't recognise us in 32 days, the relationship is over,
575 * and we won't waste any more time trying to communicate with them.
576 * This provides for the possibility that their database is temporarily messed
577 * up or some other transient event and that there's a possibility we could recover from it.
579 * @param array $contact contact to mark for archival
582 public static function markForArchival(array $contact)
584 if (!isset($contact['url']) && !empty($contact['id'])) {
585 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
586 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
587 if (!DBA::isResult($contact)) {
590 } elseif (!isset($contact['url'])) {
591 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
594 // Contact already archived or "self" contact? => nothing to do
595 if ($contact['archive'] || $contact['self']) {
599 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
600 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
601 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
604 * We really should send a notification to the owner after 2-3 weeks
605 * so they won't be surprised when the contact vanishes and can take
606 * remedial action if this was a serious mistake or glitch
609 /// @todo Check for contact vitality via probing
610 $archival_days = Config::get('system', 'archival_days', 32);
612 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
613 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
614 /* Relationship is really truly dead. archive them rather than
615 * delete, though if the owner tries to unarchive them we'll start
616 * the whole process over again.
618 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
619 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
625 * @brief Cancels the archival countdown
627 * @see Contact::markForArchival()
629 * @param array $contact contact to be unmarked for archival
632 public static function unmarkForArchival(array $contact)
634 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
635 $exists = DBA::exists('contact', $condition);
637 // We don't need to update, we never marked this contact for archival
642 if (!isset($contact['url']) && !empty($contact['id'])) {
643 $fields = ['id', 'url', 'batch'];
644 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
645 if (!DBA::isResult($contact)) {
650 // It's a miracle. Our dead contact has inexplicably come back to life.
651 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
652 DBA::update('contact', $fields, ['id' => $contact['id']]);
653 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
655 if (!empty($contact['batch'])) {
656 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
657 DBA::update('contact', $fields, $condition);
662 * @brief Get contact data for a given profile link
664 * The function looks at several places (contact table and gcontact table) for the contact
665 * It caches its result for the same script execution to prevent duplicate calls
667 * @param string $url The profile link
668 * @param int $uid User id
669 * @param array $default If not data was found take this data as default value
671 * @return array Contact data
673 public static function getDetailsByURL($url, $uid = -1, array $default = [])
685 if (isset($cache[$url][$uid])) {
686 return $cache[$url][$uid];
689 $ssl_url = str_replace('http://', 'https://', $url);
691 // Fetch contact data from the contact table for the given user
692 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
693 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
694 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
695 $r = DBA::toArray($s);
697 // Fetch contact data from the contact table for the given user, checking with the alias
698 if (!DBA::isResult($r)) {
699 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
700 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
701 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
702 $r = DBA::toArray($s);
705 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
706 if (!DBA::isResult($r)) {
707 $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
708 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
709 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
710 $r = DBA::toArray($s);
713 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
714 if (!DBA::isResult($r)) {
715 $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
716 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
717 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
718 $r = DBA::toArray($s);
721 // Fetch the data from the gcontact table
722 if (!DBA::isResult($r)) {
723 $s = DBA::p("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
724 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
725 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
726 $r = DBA::toArray($s);
729 if (DBA::isResult($r)) {
730 // If there is more than one entry we filter out the connector networks
732 foreach ($r as $id => $result) {
733 if ($result["network"] == Protocol::STATUSNET) {
739 $profile = array_shift($r);
741 // "bd" always contains the upcoming birthday of a contact.
742 // "birthday" might contain the birthday including the year of birth.
743 if ($profile["birthday"] > '0001-01-01') {
744 $bd_timestamp = strtotime($profile["birthday"]);
745 $month = date("m", $bd_timestamp);
746 $day = date("d", $bd_timestamp);
748 $current_timestamp = time();
749 $current_year = date("Y", $current_timestamp);
750 $current_month = date("m", $current_timestamp);
751 $current_day = date("d", $current_timestamp);
753 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
754 $current = $current_year . "-" . $current_month . "-" . $current_day;
756 if ($profile["bd"] < $current) {
757 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
760 $profile["bd"] = '0001-01-01';
766 if (empty($profile["photo"]) && isset($default["photo"])) {
767 $profile["photo"] = $default["photo"];
770 if (empty($profile["name"]) && isset($default["name"])) {
771 $profile["name"] = $default["name"];
774 if (empty($profile["network"]) && isset($default["network"])) {
775 $profile["network"] = $default["network"];
778 if (empty($profile["thumb"]) && isset($profile["photo"])) {
779 $profile["thumb"] = $profile["photo"];
782 if (empty($profile["micro"]) && isset($profile["thumb"])) {
783 $profile["micro"] = $profile["thumb"];
786 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
787 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
789 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
792 // Show contact details of Diaspora contacts only if connected
793 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
794 $profile["location"] = "";
795 $profile["about"] = "";
796 $profile["gender"] = "";
797 $profile["birthday"] = '0001-01-01';
800 $cache[$url][$uid] = $profile;
806 * @brief Get contact data for a given address
808 * The function looks at several places (contact table and gcontact table) for the contact
810 * @param string $addr The profile link
811 * @param int $uid User id
813 * @return array Contact data
815 public static function getDetailsByAddr($addr, $uid = -1)
827 // Fetch contact data from the contact table for the given user
828 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
829 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
830 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
834 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
835 if (!DBA::isResult($r)) {
836 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
837 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
838 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
843 // Fetch the data from the gcontact table
844 if (!DBA::isResult($r)) {
845 $r = q("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
846 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
847 FROM `gcontact` WHERE `addr` = '%s'",
852 if (!DBA::isResult($r)) {
853 $data = Probe::uri($addr);
855 $profile = self::getDetailsByURL($data['url'], $uid);
864 * @brief Returns the data array for the photo menu of a given contact
866 * @param array $contact contact
867 * @param int $uid optional, default 0
870 public static function photoMenu(array $contact, $uid = 0)
872 // @todo Unused, to be removed
880 $contact_drop_link = '';
887 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
889 $profile_link = self::magicLink($contact['url']);
890 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
895 // Look for our own contact if the uid doesn't match and isn't public
896 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
897 if (DBA::isResult($contact_own)) {
898 return self::photoMenu($contact_own, $uid);
903 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
905 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
907 $profile_link = $contact['url'];
910 if ($profile_link === 'mailbox') {
915 $status_link = $profile_link . '?url=status';
916 $photos_link = $profile_link . '?url=photos';
917 $profile_link = $profile_link . '?url=profile';
920 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
921 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
924 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
925 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
928 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
930 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
932 if (!$contact['self']) {
933 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
938 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
940 if (empty($contact['uid'])) {
941 $connlnk = 'follow/?url=' . $contact['url'];
943 'profile' => [L10n::t('View Profile'), $profile_link, true],
944 'network' => [L10n::t('Network Posts'), $posts_link, false],
945 'edit' => [L10n::t('View Contact'), $contact_url, false],
946 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
950 'status' => [L10n::t('View Status'), $status_link, true],
951 'profile' => [L10n::t('View Profile'), $profile_link, true],
952 'photos' => [L10n::t('View Photos'), $photos_link, true],
953 'network' => [L10n::t('Network Posts'), $posts_link, false],
954 'edit' => [L10n::t('View Contact'), $contact_url, false],
955 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
956 'pm' => [L10n::t('Send PM'), $pm_url, false],
957 'poke' => [L10n::t('Poke'), $poke_link, false],
961 $args = ['contact' => $contact, 'menu' => &$menu];
963 Addon::callHooks('contact_photo_menu', $args);
967 foreach ($menu as $menuname => $menuitem) {
968 if ($menuitem[1] != '') {
969 $menucondensed[$menuname] = $menuitem;
973 return $menucondensed;
977 * @brief Returns ungrouped contact count or list for user
979 * Returns either the total number of ungrouped contacts for the given user
980 * id or a paginated list of ungrouped contacts.
982 * @param int $uid uid
983 * @param int $start optional, default 0
984 * @param int $count optional, default 0
988 public static function getUngroupedList($uid)
997 SELECT DISTINCT(`contact-id`)
999 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1000 WHERE `group`.`uid` = %d
1001 )", intval($uid), intval($uid));
1005 * @brief Fetch the contact id for a given URL and user
1007 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1008 * `addr` or `alias`.
1010 * If there's no record and we aren't looking for a public contact, we quit.
1011 * If there's one, we check that it isn't time to update the picture else we
1012 * directly return the found contact id.
1014 * Second, we probe the provided $url whether it's http://server.tld/profile or
1015 * nick@server.tld. We quit if we can't get any info back.
1017 * Third, we create the contact record if it doesn't exist
1019 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1020 * if there's any updates
1022 * @param string $url Contact URL
1023 * @param integer $uid The user id for the contact (0 = public contact)
1024 * @param boolean $no_update Don't update the contact
1025 * @param array $default Default value for creating the contact when every else fails
1026 * @param boolean $in_loop Internally used variable to prevent an endless loop
1028 * @return integer Contact ID
1030 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1032 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1040 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1041 // We first try the nurl (http://server.tld/nick), most common case
1042 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1044 // Then the addr (nick@server.tld)
1045 if (!DBA::isResult($contact)) {
1046 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1049 // Then the alias (which could be anything)
1050 if (!DBA::isResult($contact)) {
1051 // The link could be provided as http although we stored it as https
1052 $ssl_url = str_replace('http://', 'https://', $url);
1053 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1054 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1057 if (DBA::isResult($contact)) {
1058 $contact_id = $contact["id"];
1060 // Update the contact every 7 days
1061 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1063 // We force the update if the avatar is empty
1064 if (!x($contact, 'avatar')) {
1065 $update_contact = true;
1067 if (!$update_contact || $no_update) {
1070 } elseif ($uid != 0) {
1071 // Non-existing user-specific contact, exiting
1075 // When we don't want to update, we look if some of our users already know this contact
1077 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1078 'photo', 'keywords', 'location', 'about', 'network',
1079 'priority', 'batch', 'request', 'confirm', 'poco'];
1080 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1082 if (DBA::isResult($data)) {
1083 // For security reasons we don't fetch key data from our users
1084 $data["pubkey"] = '';
1091 $data = Probe::uri($url, "", $uid);
1093 // Ensure that there is a gserver entry
1094 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1095 PortableContact::checkServer($data['baseurl']);
1099 // Last try in gcontact for unsupported networks
1100 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1105 // Get data from the gcontact table
1106 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1107 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1108 if (!DBA::isResult($contact)) {
1109 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1112 if (!DBA::isResult($contact)) {
1113 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1114 'photo', 'keywords', 'location', 'about', 'network',
1115 'priority', 'batch', 'request', 'confirm', 'poco'];
1116 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1119 if (!DBA::isResult($contact)) {
1120 // The link could be provided as http although we stored it as https
1121 $ssl_url = str_replace('http://', 'https://', $url);
1122 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1123 $contact = DBA::selectFirst('contact', $fields, $condition);
1126 if (!DBA::isResult($contact)) {
1127 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1128 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1129 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1130 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1133 if (!empty($default)) {
1134 $contact = $default;
1137 if (!DBA::isResult($contact)) {
1140 $data = array_merge($data, $contact);
1144 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1145 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1148 $url = $data["url"];
1150 DBA::insert('contact', [
1152 'created' => DateTimeFormat::utcNow(),
1153 'url' => $data["url"],
1154 'nurl' => Strings::normaliseLink($data["url"]),
1155 'addr' => $data["addr"],
1156 'alias' => $data["alias"],
1157 'notify' => $data["notify"],
1158 'poll' => $data["poll"],
1159 'name' => $data["name"],
1160 'nick' => $data["nick"],
1161 'photo' => $data["photo"],
1162 'keywords' => $data["keywords"],
1163 'location' => $data["location"],
1164 'about' => $data["about"],
1165 'network' => $data["network"],
1166 'pubkey' => $data["pubkey"],
1167 'rel' => self::SHARING,
1168 'priority' => $data["priority"],
1169 'batch' => $data["batch"],
1170 'request' => $data["request"],
1171 'confirm' => $data["confirm"],
1172 'poco' => $data["poco"],
1173 'name-date' => DateTimeFormat::utcNow(),
1174 'uri-date' => DateTimeFormat::utcNow(),
1175 'avatar-date' => DateTimeFormat::utcNow(),
1182 $s = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
1183 $contacts = DBA::toArray($s);
1184 if (!DBA::isResult($contacts)) {
1188 $contact_id = $contacts[0]["id"];
1190 // Update the newly created contact from data in the gcontact table
1191 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1192 if (DBA::isResult($gcontact)) {
1193 // Only use the information when the probing hadn't fetched these values
1194 if ($data['keywords'] != '') {
1195 unset($gcontact['keywords']);
1197 if ($data['location'] != '') {
1198 unset($gcontact['location']);
1200 if ($data['about'] != '') {
1201 unset($gcontact['about']);
1203 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1206 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1207 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
1208 Strings::normaliseLink($data["url"]), $contact_id]);
1212 self::updateAvatar($data["photo"], $uid, $contact_id);
1214 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1215 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1217 // This condition should always be true
1218 if (!DBA::isResult($contact)) {
1222 $updated = ['addr' => $data['addr'],
1223 'alias' => $data['alias'],
1224 'url' => $data['url'],
1225 'nurl' => Strings::normaliseLink($data['url']),
1226 'name' => $data['name'],
1227 'nick' => $data['nick']];
1229 if ($data['keywords'] != '') {
1230 $updated['keywords'] = $data['keywords'];
1232 if ($data['location'] != '') {
1233 $updated['location'] = $data['location'];
1236 // Update the technical stuff as well - if filled
1237 if ($data['notify'] != '') {
1238 $updated['notify'] = $data['notify'];
1240 if ($data['poll'] != '') {
1241 $updated['poll'] = $data['poll'];
1243 if ($data['batch'] != '') {
1244 $updated['batch'] = $data['batch'];
1246 if ($data['request'] != '') {
1247 $updated['request'] = $data['request'];
1249 if ($data['confirm'] != '') {
1250 $updated['confirm'] = $data['confirm'];
1252 if ($data['poco'] != '') {
1253 $updated['poco'] = $data['poco'];
1256 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1257 if (empty($contact['pubkey'])) {
1258 $updated['pubkey'] = $data['pubkey'];
1261 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1262 $updated['uri-date'] = DateTimeFormat::utcNow();
1264 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1265 $updated['name-date'] = DateTimeFormat::utcNow();
1268 $updated['avatar-date'] = DateTimeFormat::utcNow();
1270 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1276 * @brief Checks if the contact is blocked
1278 * @param int $cid contact id
1280 * @return boolean Is the contact blocked?
1282 public static function isBlocked($cid)
1288 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1289 if (!DBA::isResult($blocked)) {
1292 return (bool) $blocked['blocked'];
1296 * @brief Checks if the contact is hidden
1298 * @param int $cid contact id
1300 * @return boolean Is the contact hidden?
1302 public static function isHidden($cid)
1308 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1309 if (!DBA::isResult($hidden)) {
1312 return (bool) $hidden['hidden'];
1316 * @brief Returns posts from a given contact url
1318 * @param string $contact_url Contact URL
1320 * @return string posts in HTML
1322 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1324 $a = self::getApp();
1326 require_once 'include/conversation.php';
1328 $cid = Self::getIdForURL($contact_url);
1330 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1331 if (!DBA::isResult($contact)) {
1335 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1336 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1338 $sql = "`item`.`uid` = ?";
1341 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1344 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1345 $cid, GRAVITY_PARENT, local_user()];
1347 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1348 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1351 $pager = new Pager($a->query_string);
1353 $params = ['order' => ['created' => true],
1354 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1357 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1359 $items = Item::inArray($r);
1361 $o = conversation($a, $items, $pager, 'contacts', $update);
1363 $r = Item::selectForUser(local_user(), [], $condition, $params);
1365 $items = Item::inArray($r);
1367 $o = conversation($a, $items, $pager, 'contact-posts', false);
1371 $o .= $pager->renderMinimal(count($items));
1378 * @brief Returns the account type name
1380 * The function can be called with either the user or the contact array
1382 * @param array $contact contact or user array
1385 public static function getAccountType(array $contact)
1387 // There are several fields that indicate that the contact or user is a forum
1388 // "page-flags" is a field in the user table,
1389 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1390 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1391 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1392 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1393 || (isset($contact['forum']) && intval($contact['forum']))
1394 || (isset($contact['prv']) && intval($contact['prv']))
1395 || (isset($contact['community']) && intval($contact['community']))
1397 $type = self::ACCOUNT_TYPE_COMMUNITY;
1399 $type = self::ACCOUNT_TYPE_PERSON;
1402 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1403 if (isset($contact["contact-type"])) {
1404 $type = $contact["contact-type"];
1407 if (isset($contact["account-type"])) {
1408 $type = $contact["account-type"];
1412 case self::ACCOUNT_TYPE_ORGANISATION:
1413 $account_type = L10n::t("Organisation");
1416 case self::ACCOUNT_TYPE_NEWS:
1417 $account_type = L10n::t('News');
1420 case self::ACCOUNT_TYPE_COMMUNITY:
1421 $account_type = L10n::t("Forum");
1429 return $account_type;
1433 * @brief Blocks a contact
1438 public static function block($uid)
1440 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1446 * @brief Unblocks a contact
1451 public static function unblock($uid)
1453 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1459 * @brief Updates the avatar links in a contact only if needed
1461 * @param string $avatar Link to avatar picture
1462 * @param int $uid User id of contact owner
1463 * @param int $cid Contact id
1464 * @param bool $force force picture update
1466 * @return array Returns array of the different avatar sizes
1468 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1470 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1471 if (!DBA::isResult($contact)) {
1474 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1477 if (($contact["avatar"] != $avatar) || $force) {
1478 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1483 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1487 // Update the public contact (contact id = 0)
1489 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1490 if (DBA::isResult($pcontact)) {
1491 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1503 * @param integer $id contact id
1504 * @param string $network Optional network we are probing for
1507 public static function updateFromProbe($id, $network = '')
1510 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1511 This will reliably kill your communication with Friendica contacts.
1514 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1515 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1516 if (!DBA::isResult($contact)) {
1520 $ret = Probe::uri($contact["url"], $network);
1522 // If Probe::uri fails the network code will be different
1523 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
1529 // make sure to not overwrite existing values with blank entries
1530 foreach ($ret as $key => $val) {
1531 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1532 $ret[$key] = $contact[$key];
1535 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1546 'url' => $ret['url'],
1547 'nurl' => Strings::normaliseLink($ret['url']),
1548 'network' => $ret['network'],
1549 'addr' => $ret['addr'],
1550 'alias' => $ret['alias'],
1551 'batch' => $ret['batch'],
1552 'notify' => $ret['notify'],
1553 'poll' => $ret['poll'],
1554 'poco' => $ret['poco']
1559 // Update the corresponding gcontact entry
1560 PortableContact::lastUpdated($ret["url"]);
1566 * Takes a $uid and a url/handle and adds a new contact
1567 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1568 * dfrn_request page.
1570 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1573 * $return['success'] boolean true if successful
1574 * $return['message'] error text if success is false.
1576 * @brief Takes a $uid and a url/handle and adds a new contact
1578 * @param string $url
1579 * @param bool $interactive
1580 * @param string $network
1581 * @return boolean|string
1583 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1585 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1589 // remove ajax junk, e.g. Twitter
1590 $url = str_replace('/#!/', '/', $url);
1592 if (!Network::isUrlAllowed($url)) {
1593 $result['message'] = L10n::t('Disallowed profile URL.');
1597 if (Network::isUrlBlocked($url)) {
1598 $result['message'] = L10n::t('Blocked domain');
1603 $result['message'] = L10n::t('Connect URL missing.');
1607 $arr = ['url' => $url, 'contact' => []];
1609 Hook::callAll('follow', $arr);
1612 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1616 if (x($arr['contact'], 'name')) {
1617 $ret = $arr['contact'];
1619 $ret = Probe::uri($url, $network, $uid, false);
1622 if (($network != '') && ($ret['network'] != $network)) {
1623 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1627 // check if we already have a contact
1628 // the poll url is more reliable than the profile url, as we may have
1629 // indirect links or webfinger links
1631 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1632 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1633 if (!DBA::isResult($contact)) {
1634 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1635 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1638 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1640 if (strlen($a->getURLPath())) {
1641 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1643 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1646 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1650 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1651 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1652 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1656 // This extra param just confuses things, remove it
1657 if ($ret['network'] === Protocol::DIASPORA) {
1658 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1661 // do we have enough information?
1663 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1664 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1665 if (!x($ret, 'poll')) {
1666 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1668 if (!x($ret, 'name')) {
1669 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1671 if (!x($ret, 'url')) {
1672 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1674 if (strpos($url, '@') !== false) {
1675 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1676 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1681 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1682 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1683 $ret['notify'] = '';
1686 if (!$ret['notify']) {
1687 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1690 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1692 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1694 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1696 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1700 if (DBA::isResult($contact)) {
1702 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1704 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1705 DBA::update('contact', $fields, ['id' => $contact['id']]);
1707 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1709 // create contact record
1710 DBA::insert('contact', [
1712 'created' => DateTimeFormat::utcNow(),
1713 'url' => $ret['url'],
1714 'nurl' => Strings::normaliseLink($ret['url']),
1715 'addr' => $ret['addr'],
1716 'alias' => $ret['alias'],
1717 'batch' => $ret['batch'],
1718 'notify' => $ret['notify'],
1719 'poll' => $ret['poll'],
1720 'poco' => $ret['poco'],
1721 'name' => $ret['name'],
1722 'nick' => $ret['nick'],
1723 'network' => $ret['network'],
1724 'pubkey' => $ret['pubkey'],
1725 'rel' => $new_relation,
1726 'priority'=> $ret['priority'],
1727 'writable'=> $writeable,
1728 'hidden' => $hidden,
1736 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1737 if (!DBA::isResult($contact)) {
1738 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1742 $contact_id = $contact['id'];
1743 $result['cid'] = $contact_id;
1745 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1747 // Update the avatar
1748 self::updateAvatar($ret['photo'], $uid, $contact_id);
1750 // pull feed and consume it, which should subscribe to the hub.
1752 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1754 $owner = User::getOwnerDataById($uid);
1756 if (DBA::isResult($owner)) {
1757 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1758 // create a follow slap
1760 $item['verb'] = ACTIVITY_FOLLOW;
1761 $item['follow'] = $contact["url"];
1763 $item['title'] = '';
1766 $item['attach'] = '';
1768 $slap = OStatus::salmon($item, $owner);
1770 if (!empty($contact['notify'])) {
1771 Salmon::slapper($owner, $contact['notify'], $slap);
1773 } elseif ($contact['network'] == Protocol::DIASPORA) {
1774 $ret = Diaspora::sendShare($a->user, $contact);
1775 Logger::log('share returns: ' . $ret);
1776 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1777 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
1778 Logger::log('Follow returns: ' . $ret);
1782 $result['success'] = true;
1787 * @brief Updated contact's SSL policy
1789 * @param array $contact Contact array
1790 * @param string $new_policy New policy, valid: self,full
1792 * @return array Contact array with updated values
1794 public static function updateSslPolicy(array $contact, $new_policy)
1796 $ssl_changed = false;
1797 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1798 $ssl_changed = true;
1799 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1800 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1801 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1802 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1803 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1804 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1807 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1808 $ssl_changed = true;
1809 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1810 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1811 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1812 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1813 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1814 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1818 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1819 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1820 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1821 DBA::update('contact', $fields, ['id' => $contact['id']]);
1827 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1828 // Should always be set
1829 if (empty($datarray['author-id'])) {
1833 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1834 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1835 if (!DBA::isResult($pub_contact)) {
1836 // Should never happen
1840 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1841 $name = $pub_contact['name'];
1842 $photo = $pub_contact['photo'];
1843 $nick = $pub_contact['nick'];
1844 $network = $pub_contact['network'];
1846 if (is_array($contact)) {
1847 if (($contact['rel'] == self::SHARING)
1848 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1849 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1850 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1853 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1854 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1857 // send email notification to owner?
1859 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1860 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1863 // create contact record
1864 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1865 `blocked`, `readonly`, `pending`, `writable`)
1866 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1867 intval($importer['uid']),
1868 DBA::escape(DateTimeFormat::utcNow()),
1870 DBA::escape(Strings::normaliseLink($url)),
1873 DBA::escape($photo),
1874 DBA::escape($network),
1875 intval(self::FOLLOWER)
1879 'id' => DBA::lastInsertId(),
1880 'network' => $network,
1886 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1888 /// @TODO Encapsulate this into a function/method
1889 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1890 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1891 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1892 // create notification
1893 $hash = Strings::getRandomHex();
1895 if (is_array($contact_record)) {
1896 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1897 'blocked' => false, 'knowyou' => false,
1898 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1901 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1903 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1904 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1907 'type' => NOTIFY_INTRO,
1908 'notify_flags' => $user['notify-flags'],
1909 'language' => $user['language'],
1910 'to_name' => $user['username'],
1911 'to_email' => $user['email'],
1912 'uid' => $user['uid'],
1913 'link' => System::baseUrl() . '/notifications/intro',
1914 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1915 'source_link' => $contact_record['url'],
1916 'source_photo' => $contact_record['photo'],
1917 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1922 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1923 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1924 DBA::update('contact', ['pending' => false], $condition);
1926 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1928 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1929 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1935 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1937 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1938 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1940 Contact::remove($contact['id']);
1944 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1946 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1947 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1949 Contact::remove($contact['id']);
1954 * @brief Create a birthday event.
1956 * Update the year and the birthday.
1958 public static function updateBirthdays()
1960 // This only handles foreign or alien networks where a birthday has been provided.
1961 // In-network birthdays are handled within local_delivery
1963 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1964 if (DBA::isResult($r)) {
1965 foreach ($r as $rr) {
1966 Logger::log('update_contact_birthday: ' . $rr['bd']);
1968 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1971 * Add new birthday event for this person
1973 * $bdtext is just a readable placeholder in case the event is shared
1974 * with others. We will replace it during presentation to our $importer
1975 * to contain a sparkle link and perhaps a photo.
1978 // Check for duplicates
1979 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1980 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1981 if (DBA::exists('event', $condition)) {
1985 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1986 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1988 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1989 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1990 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1991 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1996 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1997 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
2004 * Remove the unavailable contact ids from the provided list
2006 * @param array $contact_ids Contact id list
2008 public static function pruneUnavailable(array &$contact_ids)
2010 if (empty($contact_ids)) {
2014 $str = DBA::escape(implode(',', $contact_ids));
2016 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2019 while($contact = DBA::fetch($stmt)) {
2020 $return[] = $contact['id'];
2025 $contact_ids = $return;
2029 * @brief Returns a magic link to authenticate remote visitors
2031 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2033 * @param string $contact_url The address of the target contact profile
2034 * @param string $url An url that we will be redirected to after the authentication
2036 * @return string with "redir" link
2038 public static function magicLink($contact_url, $url = '')
2040 $cid = self::getIdForURL($contact_url, 0, true);
2042 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2045 return self::magicLinkbyId($cid, $url);
2049 * @brief Returns a magic link to authenticate remote visitors
2051 * @param integer $cid The contact id of the target contact profile
2052 * @param integer $url An url that we will be redirected to after the authentication
2054 * @return string with "redir" link
2056 public static function magicLinkbyId($cid, $url = '')
2058 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2060 return self::magicLinkbyContact($contact, $url);
2064 * @brief Returns a magic link to authenticate remote visitors
2066 * @param array $contact The contact array with "uid", "network" and "url"
2067 * @param string $url An url that we will be redirected to after the authentication
2069 * @return string with "redir" link
2071 public static function magicLinkbyContact($contact, $url = '')
2073 if ($contact['network'] != Protocol::DFRN) {
2074 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2077 // Only redirections to the same host do make sense
2078 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2082 if ($contact['uid'] != 0) {
2083 return self::magicLink($contact['url'], $url);
2086 $redirect = 'redir/' . $contact['id'];
2089 $redirect .= '?url=' . $url;