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;
31 * @brief functions for interacting with a contact
33 class Contact extends BaseObject
36 * @name page/profile types
38 * PAGE_NORMAL is a typical personal profile account
39 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
40 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
41 * write access to wall and comments (no email and not included in page owner's ACL lists)
42 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
46 const PAGE_NORMAL = 0;
47 const PAGE_SOAPBOX = 1;
48 const PAGE_COMMUNITY = 2;
49 const PAGE_FREELOVE = 3;
51 const PAGE_PRVGROUP = 5;
59 * ACCOUNT_TYPE_PERSON - the account belongs to a person
60 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
62 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
63 * Associated page type: PAGE_SOAPBOX
65 * ACCOUNT_TYPE_NEWS - the account is a news reflector
66 * Associated page type: PAGE_SOAPBOX
68 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
69 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
71 * ACCOUNT_TYPE_RELAY - the account is a relay
72 * This will only be assigned to contacts, not to user accounts
75 const ACCOUNT_TYPE_PERSON = 0;
76 const ACCOUNT_TYPE_ORGANISATION = 1;
77 const ACCOUNT_TYPE_NEWS = 2;
78 const ACCOUNT_TYPE_COMMUNITY = 3;
79 const ACCOUNT_TYPE_RELAY = 4;
98 * @brief Tests if the given contact is a follower
100 * @param int $cid Either public contact id or user's contact id
101 * @param int $uid User ID
103 * @return boolean is the contact id a follower?
105 public static function isFollower($cid, $uid)
107 if (self::isBlockedByUser($cid, $uid)) {
111 $cdata = self::getPublicAndUserContacID($cid, $uid);
112 if (empty($cdata['user'])) {
116 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
117 return DBA::exists('contact', $condition);
121 * @brief Get the basepath for a given contact link
122 * @todo Add functionality to store this value in the contact table
124 * @param string $url The contact link
126 * @return string basepath
128 public static function getBasepath($url)
130 $data = Probe::uri($url);
131 if (!empty($data['baseurl'])) {
132 return $data['baseurl'];
135 // When we can't probe the server, we use some ugly function that does some pattern matching
136 return PortableContact::detectServer($url);
140 * @brief Returns the contact id for the user and the public contact id for a given contact id
142 * @param int $cid Either public contact id or user's contact id
143 * @param int $uid User ID
145 * @return array with public and user's contact id
147 public static function getPublicAndUserContacID($cid, $uid)
149 if (empty($uid) || empty($cid)) {
153 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
154 if (!DBA::isResult($contact)) {
158 // We quit when the user id don't match the user id of the provided contact
159 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
163 if ($contact['uid'] != 0) {
164 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
168 $ucid = $contact['id'];
170 $pcid = $contact['id'];
171 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
174 return ['public' => $pcid, 'user' => $ucid];
178 * @brief Block contact id for user id
180 * @param int $cid Either public contact id or user's contact id
181 * @param int $uid User ID
182 * @param boolean $blocked Is the contact blocked or unblocked?
184 public static function setBlockedForUser($cid, $uid, $blocked)
186 $cdata = self::getPublicAndUserContacID($cid, $uid);
191 if ($cdata['user'] != 0) {
192 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
195 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
199 * @brief Returns "block" state for contact id and user id
201 * @param int $cid Either public contact id or user's contact id
202 * @param int $uid User ID
204 * @return boolean is the contact id blocked for the given user?
206 public static function isBlockedByUser($cid, $uid)
208 $cdata = self::getPublicAndUserContacID($cid, $uid);
213 $public_blocked = false;
215 if (!empty($cdata['public'])) {
216 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
217 if (DBA::isResult($public_contact)) {
218 $public_blocked = $public_contact['blocked'];
222 $user_blocked = $public_blocked;
224 if (!empty($cdata['user'])) {
225 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
226 if (DBA::isResult($user_contact)) {
227 $user_blocked = $user_contact['blocked'];
231 if ($user_blocked != $public_blocked) {
232 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
235 return $user_blocked;
239 * @brief Ignore contact id for user id
241 * @param int $cid Either public contact id or user's contact id
242 * @param int $uid User ID
243 * @param boolean $ignored Is the contact ignored or unignored?
245 public static function setIgnoredForUser($cid, $uid, $ignored)
247 $cdata = self::getPublicAndUserContacID($cid, $uid);
252 if ($cdata['user'] != 0) {
253 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
256 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
260 * @brief Returns "ignore" state for contact id and user id
262 * @param int $cid Either public contact id or user's contact id
263 * @param int $uid User ID
265 * @return boolean is the contact id ignored for the given user?
267 public static function isIgnoredByUser($cid, $uid)
269 $cdata = self::getPublicAndUserContacID($cid, $uid);
274 $public_ignored = false;
276 if (!empty($cdata['public'])) {
277 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
278 if (DBA::isResult($public_contact)) {
279 $public_ignored = $public_contact['ignored'];
283 $user_ignored = $public_ignored;
285 if (!empty($cdata['user'])) {
286 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
287 if (DBA::isResult($user_contact)) {
288 $user_ignored = $user_contact['readonly'];
292 if ($user_ignored != $public_ignored) {
293 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
296 return $user_ignored;
300 * @brief Set "collapsed" for contact id and user id
302 * @param int $cid Either public contact id or user's contact id
303 * @param int $uid User ID
304 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
306 public static function setCollapsedForUser($cid, $uid, $collapsed)
308 $cdata = self::getPublicAndUserContacID($cid, $uid);
313 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
317 * @brief Returns "collapsed" state for contact id and user id
319 * @param int $cid Either public contact id or user's contact id
320 * @param int $uid User ID
322 * @return boolean is the contact id blocked for the given user?
324 public static function isCollapsedByUser($cid, $uid)
326 $cdata = self::getPublicAndUserContacID($cid, $uid);
333 if (!empty($cdata['public'])) {
334 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
335 if (DBA::isResult($public_contact)) {
336 $collapsed = $public_contact['collapsed'];
344 * @brief Returns a list of contacts belonging in a group
349 public static function getByGroupId($gid)
354 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
356 INNER JOIN `group_member`
357 ON `contact`.`id` = `group_member`.`contact-id`
359 AND `contact`.`uid` = ?
360 AND NOT `contact`.`self`
361 AND NOT `contact`.`deleted`
362 AND NOT `contact`.`blocked`
363 AND NOT `contact`.`pending`
364 ORDER BY `contact`.`name` ASC',
369 if (DBA::isResult($stmt)) {
370 $return = DBA::toArray($stmt);
378 * @brief Returns the count of OStatus contacts in a group
383 public static function getOStatusCountByGroupId($gid)
387 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
389 INNER JOIN `group_member`
390 ON `contact`.`id` = `group_member`.`contact-id`
392 AND `contact`.`uid` = ?
393 AND `contact`.`network` = ?
394 AND `contact`.`notify` != ""',
399 $return = $contacts['count'];
406 * Creates the self-contact for the provided user id
409 * @return bool Operation success
411 public static function createSelfFromUserId($uid)
413 // Only create the entry if it doesn't exist yet
414 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
418 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
419 if (!DBA::isResult($user)) {
423 $return = DBA::insert('contact', [
424 'uid' => $user['uid'],
425 'created' => DateTimeFormat::utcNow(),
427 'name' => $user['username'],
428 'nick' => $user['nickname'],
429 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
430 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
431 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
434 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
435 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
436 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
437 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
438 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
439 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
440 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
441 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
442 'name-date' => DateTimeFormat::utcNow(),
443 'uri-date' => DateTimeFormat::utcNow(),
444 'avatar-date' => DateTimeFormat::utcNow(),
452 * Updates the self-contact for the provided user id
455 * @param boolean $update_avatar Force the avatar update
457 public static function updateSelfFromUserID($uid, $update_avatar = false)
459 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
460 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
461 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
462 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
463 if (!DBA::isResult($self)) {
467 $fields = ['nickname', 'page-flags', 'account-type'];
468 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
469 if (!DBA::isResult($user)) {
473 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
474 'country-name', 'gender', 'pub_keywords', 'xmpp'];
475 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
476 if (!DBA::isResult($profile)) {
480 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
481 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
482 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
483 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
484 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
486 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
487 if (DBA::isResult($avatar)) {
488 if ($update_avatar) {
489 $fields['avatar-date'] = DateTimeFormat::utcNow();
492 // Creating the path to the avatar, beginning with the file suffix
493 $types = Image::supportedTypes();
494 if (isset($types[$avatar['type']])) {
495 $file_suffix = $types[$avatar['type']];
497 $file_suffix = 'jpg';
500 // We are adding a timestamp value so that other systems won't use cached content
501 $timestamp = strtotime($fields['avatar-date']);
503 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
504 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
506 $fields['photo'] = $prefix . '4' . $suffix;
507 $fields['thumb'] = $prefix . '5' . $suffix;
508 $fields['micro'] = $prefix . '6' . $suffix;
510 // We hadn't found a photo entry, so we use the default avatar
511 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
512 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
513 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
516 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
517 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
519 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
520 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
521 $fields['nurl'] = Strings::normaliseLink($fields['url']);
522 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
523 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
524 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
525 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
526 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
527 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
531 foreach ($fields as $field => $content) {
532 if ($self[$field] != $content) {
538 $fields['name-date'] = DateTimeFormat::utcNow();
539 DBA::update('contact', $fields, ['id' => $self['id']]);
541 // Update the public contact as well
542 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
544 // Update the profile
545 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
546 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
547 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
552 * @brief Marks a contact for removal
554 * @param int $id contact id
557 public static function remove($id)
559 // We want just to make sure that we don't delete our "self" contact
560 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
561 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
565 // Archive the contact
566 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
568 // Delete it in the background
569 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
573 * @brief Sends an unfriend message. Does not remove the contact
575 * @param array $user User unfriending
576 * @param array $contact Contact unfriended
577 * @param boolean $dissolve Remove the contact on the remote side
580 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
582 if (empty($contact['network'])) {
585 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
586 DFRN::deliver($user, $contact, 'placeholder', true);
587 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
588 // create an unfollow slap
590 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
591 $item['follow'] = $contact["url"];
596 $item['attach'] = '';
597 $slap = OStatus::salmon($item, $user);
599 if (!empty($contact['notify'])) {
600 Salmon::slapper($user, $contact['notify'], $slap);
602 } elseif ($contact['network'] == Protocol::DIASPORA) {
603 Diaspora::sendUnshare($user, $contact);
604 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
605 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
608 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
614 * @brief Marks a contact for archival after a communication issue delay
616 * Contact has refused to recognise us as a friend. We will start a countdown.
617 * If they still don't recognise us in 32 days, the relationship is over,
618 * and we won't waste any more time trying to communicate with them.
619 * This provides for the possibility that their database is temporarily messed
620 * up or some other transient event and that there's a possibility we could recover from it.
622 * @param array $contact contact to mark for archival
625 public static function markForArchival(array $contact)
627 if (!isset($contact['url']) && !empty($contact['id'])) {
628 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
629 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
630 if (!DBA::isResult($contact)) {
633 } elseif (!isset($contact['url'])) {
634 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
637 // Contact already archived or "self" contact? => nothing to do
638 if ($contact['archive'] || $contact['self']) {
642 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
643 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
644 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
647 * We really should send a notification to the owner after 2-3 weeks
648 * so they won't be surprised when the contact vanishes and can take
649 * remedial action if this was a serious mistake or glitch
652 /// @todo Check for contact vitality via probing
653 $archival_days = Config::get('system', 'archival_days', 32);
655 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
656 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
657 /* Relationship is really truly dead. archive them rather than
658 * delete, though if the owner tries to unarchive them we'll start
659 * the whole process over again.
661 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
662 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
668 * @brief Cancels the archival countdown
670 * @see Contact::markForArchival()
672 * @param array $contact contact to be unmarked for archival
675 public static function unmarkForArchival(array $contact)
677 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
678 $exists = DBA::exists('contact', $condition);
680 // We don't need to update, we never marked this contact for archival
685 if (!isset($contact['url']) && !empty($contact['id'])) {
686 $fields = ['id', 'url', 'batch'];
687 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
688 if (!DBA::isResult($contact)) {
693 // It's a miracle. Our dead contact has inexplicably come back to life.
694 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
695 DBA::update('contact', $fields, ['id' => $contact['id']]);
696 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
698 if (!empty($contact['batch'])) {
699 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
700 DBA::update('contact', $fields, $condition);
705 * @brief Get contact data for a given profile link
707 * The function looks at several places (contact table and gcontact table) for the contact
708 * It caches its result for the same script execution to prevent duplicate calls
710 * @param string $url The profile link
711 * @param int $uid User id
712 * @param array $default If not data was found take this data as default value
714 * @return array Contact data
716 public static function getDetailsByURL($url, $uid = -1, array $default = [])
728 if (isset($cache[$url][$uid])) {
729 return $cache[$url][$uid];
732 $ssl_url = str_replace('http://', 'https://', $url);
734 // Fetch contact data from the contact table for the given user
735 $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`,
736 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
737 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
738 $r = DBA::toArray($s);
740 // Fetch contact data from the contact table for the given user, checking with the alias
741 if (!DBA::isResult($r)) {
742 $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`,
743 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
744 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
745 $r = DBA::toArray($s);
748 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
749 if (!DBA::isResult($r)) {
750 $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`,
751 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
752 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
753 $r = DBA::toArray($s);
756 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
757 if (!DBA::isResult($r)) {
758 $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`,
759 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
760 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
761 $r = DBA::toArray($s);
764 // Fetch the data from the gcontact table
765 if (!DBA::isResult($r)) {
766 $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`,
767 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
768 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
769 $r = DBA::toArray($s);
772 if (DBA::isResult($r)) {
773 // If there is more than one entry we filter out the connector networks
775 foreach ($r as $id => $result) {
776 if ($result["network"] == Protocol::STATUSNET) {
782 $profile = array_shift($r);
784 // "bd" always contains the upcoming birthday of a contact.
785 // "birthday" might contain the birthday including the year of birth.
786 if ($profile["birthday"] > DBA::NULL_DATE) {
787 $bd_timestamp = strtotime($profile["birthday"]);
788 $month = date("m", $bd_timestamp);
789 $day = date("d", $bd_timestamp);
791 $current_timestamp = time();
792 $current_year = date("Y", $current_timestamp);
793 $current_month = date("m", $current_timestamp);
794 $current_day = date("d", $current_timestamp);
796 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
797 $current = $current_year . "-" . $current_month . "-" . $current_day;
799 if ($profile["bd"] < $current) {
800 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
803 $profile["bd"] = DBA::NULL_DATE;
809 if (empty($profile["photo"]) && isset($default["photo"])) {
810 $profile["photo"] = $default["photo"];
813 if (empty($profile["name"]) && isset($default["name"])) {
814 $profile["name"] = $default["name"];
817 if (empty($profile["network"]) && isset($default["network"])) {
818 $profile["network"] = $default["network"];
821 if (empty($profile["thumb"]) && isset($profile["photo"])) {
822 $profile["thumb"] = $profile["photo"];
825 if (empty($profile["micro"]) && isset($profile["thumb"])) {
826 $profile["micro"] = $profile["thumb"];
829 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
830 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
832 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
835 // Show contact details of Diaspora contacts only if connected
836 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
837 $profile["location"] = "";
838 $profile["about"] = "";
839 $profile["gender"] = "";
840 $profile["birthday"] = DBA::NULL_DATE;
843 $cache[$url][$uid] = $profile;
849 * @brief Get contact data for a given address
851 * The function looks at several places (contact table and gcontact table) for the contact
853 * @param string $addr The profile link
854 * @param int $uid User id
856 * @return array Contact data
858 public static function getDetailsByAddr($addr, $uid = -1)
870 // Fetch contact data from the contact table for the given user
871 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
872 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
873 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
877 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
878 if (!DBA::isResult($r)) {
879 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
880 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
881 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
886 // Fetch the data from the gcontact table
887 if (!DBA::isResult($r)) {
888 $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`,
889 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
890 FROM `gcontact` WHERE `addr` = '%s'",
895 if (!DBA::isResult($r)) {
896 $data = Probe::uri($addr);
898 $profile = self::getDetailsByURL($data['url'], $uid);
907 * @brief Returns the data array for the photo menu of a given contact
909 * @param array $contact contact
910 * @param int $uid optional, default 0
913 public static function photoMenu(array $contact, $uid = 0)
915 // @todo Unused, to be removed
923 $contact_drop_link = '';
930 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
932 $profile_link = self::magicLink($contact['url']);
933 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
938 // Look for our own contact if the uid doesn't match and isn't public
939 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
940 if (DBA::isResult($contact_own)) {
941 return self::photoMenu($contact_own, $uid);
946 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
948 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
950 $profile_link = $contact['url'];
953 if ($profile_link === 'mailbox') {
958 $status_link = $profile_link . '?url=status';
959 $photos_link = $profile_link . '?url=photos';
960 $profile_link = $profile_link . '?url=profile';
963 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
964 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
967 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
968 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
971 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
973 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
975 if (!$contact['self']) {
976 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
981 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
983 if (empty($contact['uid'])) {
984 $connlnk = 'follow/?url=' . $contact['url'];
986 'profile' => [L10n::t('View Profile'), $profile_link, true],
987 'network' => [L10n::t('Network Posts'), $posts_link, false],
988 'edit' => [L10n::t('View Contact'), $contact_url, false],
989 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
993 'status' => [L10n::t('View Status'), $status_link, true],
994 'profile' => [L10n::t('View Profile'), $profile_link, true],
995 'photos' => [L10n::t('View Photos'), $photos_link, true],
996 'network' => [L10n::t('Network Posts'), $posts_link, false],
997 'edit' => [L10n::t('View Contact'), $contact_url, false],
998 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
999 'pm' => [L10n::t('Send PM'), $pm_url, false],
1000 'poke' => [L10n::t('Poke'), $poke_link, false],
1004 $args = ['contact' => $contact, 'menu' => &$menu];
1006 Addon::callHooks('contact_photo_menu', $args);
1008 $menucondensed = [];
1010 foreach ($menu as $menuname => $menuitem) {
1011 if ($menuitem[1] != '') {
1012 $menucondensed[$menuname] = $menuitem;
1016 return $menucondensed;
1020 * @brief Returns ungrouped contact count or list for user
1022 * Returns either the total number of ungrouped contacts for the given user
1023 * id or a paginated list of ungrouped contacts.
1025 * @param int $uid uid
1026 * @param int $start optional, default 0
1027 * @param int $count optional, default 0
1031 public static function getUngroupedList($uid)
1041 SELECT DISTINCT(`contact-id`)
1043 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1044 WHERE `group`.`uid` = %d
1045 )", intval($uid), intval($uid));
1049 * @brief Fetch the contact id for a given URL and user
1051 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1052 * `addr` or `alias`.
1054 * If there's no record and we aren't looking for a public contact, we quit.
1055 * If there's one, we check that it isn't time to update the picture else we
1056 * directly return the found contact id.
1058 * Second, we probe the provided $url whether it's http://server.tld/profile or
1059 * nick@server.tld. We quit if we can't get any info back.
1061 * Third, we create the contact record if it doesn't exist
1063 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1064 * if there's any updates
1066 * @param string $url Contact URL
1067 * @param integer $uid The user id for the contact (0 = public contact)
1068 * @param boolean $no_update Don't update the contact
1069 * @param array $default Default value for creating the contact when every else fails
1070 * @param boolean $in_loop Internally used variable to prevent an endless loop
1072 * @return integer Contact ID
1074 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1076 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1084 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1085 // We first try the nurl (http://server.tld/nick), most common case
1086 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1088 // Then the addr (nick@server.tld)
1089 if (!DBA::isResult($contact)) {
1090 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1093 // Then the alias (which could be anything)
1094 if (!DBA::isResult($contact)) {
1095 // The link could be provided as http although we stored it as https
1096 $ssl_url = str_replace('http://', 'https://', $url);
1097 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1098 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1101 if (DBA::isResult($contact)) {
1102 $contact_id = $contact["id"];
1104 // Update the contact every 7 days
1105 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1107 // We force the update if the avatar is empty
1108 if (empty($contact['avatar'])) {
1109 $update_contact = true;
1111 if (!$update_contact || $no_update) {
1114 } elseif ($uid != 0) {
1115 // Non-existing user-specific contact, exiting
1119 // When we don't want to update, we look if some of our users already know this contact
1121 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1122 'photo', 'keywords', 'location', 'about', 'network',
1123 'priority', 'batch', 'request', 'confirm', 'poco'];
1124 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1126 if (DBA::isResult($data)) {
1127 // For security reasons we don't fetch key data from our users
1128 $data["pubkey"] = '';
1135 $data = Probe::uri($url, "", $uid);
1137 // Ensure that there is a gserver entry
1138 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1139 PortableContact::checkServer($data['baseurl']);
1143 // Last try in gcontact for unsupported networks
1144 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1149 // Get data from the gcontact table
1150 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1151 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1152 if (!DBA::isResult($contact)) {
1153 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1156 if (!DBA::isResult($contact)) {
1157 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1158 'photo', 'keywords', 'location', 'about', 'network',
1159 'priority', 'batch', 'request', 'confirm', 'poco'];
1160 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1163 if (!DBA::isResult($contact)) {
1164 // The link could be provided as http although we stored it as https
1165 $ssl_url = str_replace('http://', 'https://', $url);
1166 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1167 $contact = DBA::selectFirst('contact', $fields, $condition);
1170 if (!DBA::isResult($contact)) {
1171 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1172 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1173 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1174 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1177 if (!empty($default)) {
1178 $contact = $default;
1181 if (!DBA::isResult($contact)) {
1184 $data = array_merge($data, $contact);
1188 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1189 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1192 $url = $data["url"];
1196 'created' => DateTimeFormat::utcNow(),
1197 'url' => $data["url"],
1198 'nurl' => Strings::normaliseLink($data["url"]),
1199 'addr' => $data["addr"],
1200 'alias' => $data["alias"],
1201 'notify' => $data["notify"],
1202 'poll' => $data["poll"],
1203 'name' => $data["name"],
1204 'nick' => $data["nick"],
1205 'photo' => $data["photo"],
1206 'keywords' => $data["keywords"],
1207 'location' => $data["location"],
1208 'about' => $data["about"],
1209 'network' => $data["network"],
1210 'pubkey' => $data["pubkey"],
1211 'rel' => self::SHARING,
1212 'priority' => $data["priority"],
1213 'batch' => $data["batch"],
1214 'request' => $data["request"],
1215 'confirm' => $data["confirm"],
1216 'poco' => $data["poco"],
1217 'name-date' => DateTimeFormat::utcNow(),
1218 'uri-date' => DateTimeFormat::utcNow(),
1219 'avatar-date' => DateTimeFormat::utcNow(),
1225 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1227 DBA::update('contact', $fields, $condition, true);
1229 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1230 $contacts = DBA::toArray($s);
1231 if (!DBA::isResult($contacts)) {
1235 $contact_id = $contacts[0]["id"];
1237 // Update the newly created contact from data in the gcontact table
1238 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1239 if (DBA::isResult($gcontact)) {
1240 // Only use the information when the probing hadn't fetched these values
1241 if ($data['keywords'] != '') {
1242 unset($gcontact['keywords']);
1244 if ($data['location'] != '') {
1245 unset($gcontact['location']);
1247 if ($data['about'] != '') {
1248 unset($gcontact['about']);
1250 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1253 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1254 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1255 Strings::normaliseLink($data["url"]), 0, $contact_id];
1256 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1257 DBA::delete('contact', $condition);
1261 self::updateAvatar($data["photo"], $uid, $contact_id);
1263 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1264 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1266 // This condition should always be true
1267 if (!DBA::isResult($contact)) {
1271 $updated = ['addr' => $data['addr'],
1272 'alias' => $data['alias'],
1273 'url' => $data['url'],
1274 'nurl' => Strings::normaliseLink($data['url']),
1275 'name' => $data['name'],
1276 'nick' => $data['nick']];
1278 if ($data['keywords'] != '') {
1279 $updated['keywords'] = $data['keywords'];
1281 if ($data['location'] != '') {
1282 $updated['location'] = $data['location'];
1285 // Update the technical stuff as well - if filled
1286 if ($data['notify'] != '') {
1287 $updated['notify'] = $data['notify'];
1289 if ($data['poll'] != '') {
1290 $updated['poll'] = $data['poll'];
1292 if ($data['batch'] != '') {
1293 $updated['batch'] = $data['batch'];
1295 if ($data['request'] != '') {
1296 $updated['request'] = $data['request'];
1298 if ($data['confirm'] != '') {
1299 $updated['confirm'] = $data['confirm'];
1301 if ($data['poco'] != '') {
1302 $updated['poco'] = $data['poco'];
1305 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1306 if (empty($contact['pubkey'])) {
1307 $updated['pubkey'] = $data['pubkey'];
1310 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1311 $updated['uri-date'] = DateTimeFormat::utcNow();
1313 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1314 $updated['name-date'] = DateTimeFormat::utcNow();
1317 $updated['avatar-date'] = DateTimeFormat::utcNow();
1319 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1325 * @brief Checks if the contact is blocked
1327 * @param int $cid contact id
1329 * @return boolean Is the contact blocked?
1331 public static function isBlocked($cid)
1337 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1338 if (!DBA::isResult($blocked)) {
1342 if (Network::isUrlBlocked($blocked['url'])) {
1346 return (bool) $blocked['blocked'];
1350 * @brief Checks if the contact is hidden
1352 * @param int $cid contact id
1354 * @return boolean Is the contact hidden?
1356 public static function isHidden($cid)
1362 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1363 if (!DBA::isResult($hidden)) {
1366 return (bool) $hidden['hidden'];
1370 * @brief Returns posts from a given contact url
1372 * @param string $contact_url Contact URL
1374 * @return string posts in HTML
1376 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1378 $a = self::getApp();
1380 $cid = Self::getIdForURL($contact_url);
1382 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1383 if (!DBA::isResult($contact)) {
1387 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1388 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1390 $sql = "`item`.`uid` = ?";
1393 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1396 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1397 $cid, GRAVITY_PARENT, local_user()];
1399 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1400 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1403 $pager = new Pager($a->query_string);
1405 $params = ['order' => ['created' => true],
1406 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1409 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1411 $items = Item::inArray($r);
1413 $o = conversation($a, $items, $pager, 'contacts', $update);
1415 $r = Item::selectForUser(local_user(), [], $condition, $params);
1417 $items = Item::inArray($r);
1419 $o = conversation($a, $items, $pager, 'contact-posts', false);
1423 $o .= $pager->renderMinimal(count($items));
1430 * @brief Returns the account type name
1432 * The function can be called with either the user or the contact array
1434 * @param array $contact contact or user array
1437 public static function getAccountType(array $contact)
1439 // There are several fields that indicate that the contact or user is a forum
1440 // "page-flags" is a field in the user table,
1441 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1442 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1443 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1444 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1445 || (isset($contact['forum']) && intval($contact['forum']))
1446 || (isset($contact['prv']) && intval($contact['prv']))
1447 || (isset($contact['community']) && intval($contact['community']))
1449 $type = self::ACCOUNT_TYPE_COMMUNITY;
1451 $type = self::ACCOUNT_TYPE_PERSON;
1454 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1455 if (isset($contact["contact-type"])) {
1456 $type = $contact["contact-type"];
1459 if (isset($contact["account-type"])) {
1460 $type = $contact["account-type"];
1464 case self::ACCOUNT_TYPE_ORGANISATION:
1465 $account_type = L10n::t("Organisation");
1468 case self::ACCOUNT_TYPE_NEWS:
1469 $account_type = L10n::t('News');
1472 case self::ACCOUNT_TYPE_COMMUNITY:
1473 $account_type = L10n::t("Forum");
1481 return $account_type;
1485 * @brief Blocks a contact
1490 public static function block($uid)
1492 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1498 * @brief Unblocks a contact
1503 public static function unblock($uid)
1505 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1511 * @brief Updates the avatar links in a contact only if needed
1513 * @param string $avatar Link to avatar picture
1514 * @param int $uid User id of contact owner
1515 * @param int $cid Contact id
1516 * @param bool $force force picture update
1518 * @return array Returns array of the different avatar sizes
1520 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1522 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1523 if (!DBA::isResult($contact)) {
1526 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1529 if (($contact["avatar"] != $avatar) || $force) {
1530 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1535 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1539 // Update the public contact (contact id = 0)
1541 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1542 if (DBA::isResult($pcontact)) {
1543 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1555 * @param integer $id contact id
1556 * @param string $network Optional network we are probing for
1559 public static function updateFromProbe($id, $network = '')
1562 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1563 This will reliably kill your communication with Friendica contacts.
1566 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1567 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1568 if (!DBA::isResult($contact)) {
1572 $ret = Probe::uri($contact["url"], $network);
1574 // If Probe::uri fails the network code will be different
1575 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
1581 // make sure to not overwrite existing values with blank entries
1582 foreach ($ret as $key => $val) {
1583 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1584 $ret[$key] = $contact[$key];
1587 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1598 'url' => $ret['url'],
1599 'nurl' => Strings::normaliseLink($ret['url']),
1600 'network' => $ret['network'],
1601 'addr' => $ret['addr'],
1602 'alias' => $ret['alias'],
1603 'batch' => $ret['batch'],
1604 'notify' => $ret['notify'],
1605 'poll' => $ret['poll'],
1606 'poco' => $ret['poco']
1611 // Update the corresponding gcontact entry
1612 PortableContact::lastUpdated($ret["url"]);
1618 * Takes a $uid and a url/handle and adds a new contact
1619 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1620 * dfrn_request page.
1622 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1625 * $return['success'] boolean true if successful
1626 * $return['message'] error text if success is false.
1628 * @brief Takes a $uid and a url/handle and adds a new contact
1630 * @param string $url
1631 * @param bool $interactive
1632 * @param string $network
1633 * @return boolean|string
1635 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1637 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1641 // remove ajax junk, e.g. Twitter
1642 $url = str_replace('/#!/', '/', $url);
1644 if (!Network::isUrlAllowed($url)) {
1645 $result['message'] = L10n::t('Disallowed profile URL.');
1649 if (Network::isUrlBlocked($url)) {
1650 $result['message'] = L10n::t('Blocked domain');
1655 $result['message'] = L10n::t('Connect URL missing.');
1659 $arr = ['url' => $url, 'contact' => []];
1661 Hook::callAll('follow', $arr);
1664 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1668 if (!empty($arr['contact']['name'])) {
1669 $ret = $arr['contact'];
1671 $ret = Probe::uri($url, $network, $uid, false);
1674 if (($network != '') && ($ret['network'] != $network)) {
1675 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1679 // check if we already have a contact
1680 // the poll url is more reliable than the profile url, as we may have
1681 // indirect links or webfinger links
1683 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1684 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1685 if (!DBA::isResult($contact)) {
1686 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1687 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1690 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1692 if (strlen($a->getURLPath())) {
1693 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1695 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1698 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1702 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1703 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1704 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1708 // This extra param just confuses things, remove it
1709 if ($ret['network'] === Protocol::DIASPORA) {
1710 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1713 // do we have enough information?
1714 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1715 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1716 if (empty($ret['poll'])) {
1717 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1719 if (empty($ret['name'])) {
1720 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1722 if (empty($ret['url'])) {
1723 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1725 if (strpos($url, '@') !== false) {
1726 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1727 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1732 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1733 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1734 $ret['notify'] = '';
1737 if (!$ret['notify']) {
1738 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1741 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1743 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1745 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1747 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1749 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1753 if (DBA::isResult($contact)) {
1755 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1757 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1758 DBA::update('contact', $fields, ['id' => $contact['id']]);
1760 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1762 // create contact record
1763 DBA::insert('contact', [
1765 'created' => DateTimeFormat::utcNow(),
1766 'url' => $ret['url'],
1767 'nurl' => Strings::normaliseLink($ret['url']),
1768 'addr' => $ret['addr'],
1769 'alias' => $ret['alias'],
1770 'batch' => $ret['batch'],
1771 'notify' => $ret['notify'],
1772 'poll' => $ret['poll'],
1773 'poco' => $ret['poco'],
1774 'name' => $ret['name'],
1775 'nick' => $ret['nick'],
1776 'network' => $ret['network'],
1777 'pubkey' => $ret['pubkey'],
1778 'rel' => $new_relation,
1779 'priority'=> $ret['priority'],
1780 'writable'=> $writeable,
1781 'hidden' => $hidden,
1784 'pending' => $pending,
1789 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1790 if (!DBA::isResult($contact)) {
1791 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1795 $contact_id = $contact['id'];
1796 $result['cid'] = $contact_id;
1798 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1800 // Update the avatar
1801 self::updateAvatar($ret['photo'], $uid, $contact_id);
1803 // pull feed and consume it, which should subscribe to the hub.
1805 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1807 $owner = User::getOwnerDataById($uid);
1809 if (DBA::isResult($owner)) {
1810 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1811 // create a follow slap
1813 $item['verb'] = ACTIVITY_FOLLOW;
1814 $item['follow'] = $contact["url"];
1816 $item['title'] = '';
1819 $item['attach'] = '';
1821 $slap = OStatus::salmon($item, $owner);
1823 if (!empty($contact['notify'])) {
1824 Salmon::slapper($owner, $contact['notify'], $slap);
1826 } elseif ($contact['network'] == Protocol::DIASPORA) {
1827 $ret = Diaspora::sendShare($a->user, $contact);
1828 Logger::log('share returns: ' . $ret);
1829 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1830 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1831 if (empty($activity_id)) {
1832 // This really should never happen
1836 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1837 Logger::log('Follow returns: ' . $ret);
1841 $result['success'] = true;
1846 * @brief Updated contact's SSL policy
1848 * @param array $contact Contact array
1849 * @param string $new_policy New policy, valid: self,full
1851 * @return array Contact array with updated values
1853 public static function updateSslPolicy(array $contact, $new_policy)
1855 $ssl_changed = false;
1856 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1857 $ssl_changed = true;
1858 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1859 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1860 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1861 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1862 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1863 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1866 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1867 $ssl_changed = true;
1868 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1869 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1870 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1871 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1872 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1873 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1877 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1878 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1879 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1880 DBA::update('contact', $fields, ['id' => $contact['id']]);
1886 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1887 // Should always be set
1888 if (empty($datarray['author-id'])) {
1892 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1893 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1894 if (!DBA::isResult($pub_contact)) {
1895 // Should never happen
1899 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1900 $name = $pub_contact['name'];
1901 $photo = $pub_contact['photo'];
1902 $nick = $pub_contact['nick'];
1903 $network = $pub_contact['network'];
1905 if (is_array($contact)) {
1906 if (($contact['rel'] == self::SHARING)
1907 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1908 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1909 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1912 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1913 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1916 // send email notification to owner?
1918 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1919 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1922 // create contact record
1923 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1924 `blocked`, `readonly`, `pending`, `writable`)
1925 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1926 intval($importer['uid']),
1927 DBA::escape(DateTimeFormat::utcNow()),
1929 DBA::escape(Strings::normaliseLink($url)),
1932 DBA::escape($photo),
1933 DBA::escape($network),
1934 intval(self::FOLLOWER)
1938 'id' => DBA::lastInsertId(),
1939 'network' => $network,
1945 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1947 /// @TODO Encapsulate this into a function/method
1948 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1949 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1950 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1951 // create notification
1952 $hash = Strings::getRandomHex();
1954 if (is_array($contact_record)) {
1955 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1956 'blocked' => false, 'knowyou' => false,
1957 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1960 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1962 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1963 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1966 'type' => NOTIFY_INTRO,
1967 'notify_flags' => $user['notify-flags'],
1968 'language' => $user['language'],
1969 'to_name' => $user['username'],
1970 'to_email' => $user['email'],
1971 'uid' => $user['uid'],
1972 'link' => System::baseUrl() . '/notifications/intro',
1973 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1974 'source_link' => $contact_record['url'],
1975 'source_photo' => $contact_record['photo'],
1976 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1981 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1982 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1983 DBA::update('contact', ['pending' => false], $condition);
1985 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1987 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1988 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1994 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1996 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1997 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1999 Contact::remove($contact['id']);
2003 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2005 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2006 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2008 Contact::remove($contact['id']);
2013 * @brief Create a birthday event.
2015 * Update the year and the birthday.
2017 public static function updateBirthdays()
2021 AND `bd` > "0001-01-01"
2022 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2023 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2024 AND NOT `contact`.`pending`
2025 AND NOT `contact`.`hidden`
2026 AND NOT `contact`.`blocked`
2027 AND NOT `contact`.`archive`
2028 AND NOT `contact`.`deleted`',
2033 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2035 while ($contact = DBA::fetch($contacts)) {
2036 Logger::log('update_contact_birthday: ' . $contact['bd']);
2038 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2040 if (Event::createBirthday($contact, $nextbd)) {
2044 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2045 ['id' => $contact['id']]
2052 * Remove the unavailable contact ids from the provided list
2054 * @param array $contact_ids Contact id list
2056 public static function pruneUnavailable(array &$contact_ids)
2058 if (empty($contact_ids)) {
2062 $str = DBA::escape(implode(',', $contact_ids));
2064 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2067 while($contact = DBA::fetch($stmt)) {
2068 $return[] = $contact['id'];
2073 $contact_ids = $return;
2077 * @brief Returns a magic link to authenticate remote visitors
2079 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2081 * @param string $contact_url The address of the target contact profile
2082 * @param string $url An url that we will be redirected to after the authentication
2084 * @return string with "redir" link
2086 public static function magicLink($contact_url, $url = '')
2088 if (!local_user() && remote_user()) {
2089 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2092 $cid = self::getIdForURL($contact_url, 0, true);
2094 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2097 return self::magicLinkbyId($cid, $url);
2101 * @brief Returns a magic link to authenticate remote visitors
2103 * @param integer $cid The contact id of the target contact profile
2104 * @param integer $url An url that we will be redirected to after the authentication
2106 * @return string with "redir" link
2108 public static function magicLinkbyId($cid, $url = '')
2110 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2112 return self::magicLinkbyContact($contact, $url);
2116 * @brief Returns a magic link to authenticate remote visitors
2118 * @param array $contact The contact array with "uid", "network" and "url"
2119 * @param string $url An url that we will be redirected to after the authentication
2121 * @return string with "redir" link
2123 public static function magicLinkbyContact($contact, $url = '')
2125 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2126 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2129 // Only redirections to the same host do make sense
2130 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2134 if ($contact['uid'] != 0) {
2135 return self::magicLink($contact['url'], $url);
2138 $redirect = 'redir/' . $contact['id'];
2141 $redirect .= '?url=' . $url;