3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\DFRN;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Protocol\OStatus;
23 use Friendica\Protocol\PortableContact;
24 use Friendica\Protocol\Salmon;
25 use Friendica\Util\BaseURL;
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 * @deprecated since version 2019.03
37 * @see User::PAGE_FLAGS_NORMAL
39 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
41 * @deprecated since version 2019.03
42 * @see User::PAGE_FLAGS_SOAPBOX
44 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
46 * @deprecated since version 2019.03
47 * @see User::PAGE_FLAGS_COMMUNITY
49 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
51 * @deprecated since version 2019.03
52 * @see User::PAGE_FLAGS_FREELOVE
54 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
56 * @deprecated since version 2019.03
57 * @see User::PAGE_FLAGS_BLOG
59 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
61 * @deprecated since version 2019.03
62 * @see User::PAGE_FLAGS_PRVGROUP
64 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
72 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
74 * TYPE_PERSON - the account belongs to a person
75 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
77 * TYPE_ORGANISATION - the account belongs to an organisation
78 * Associated page type: PAGE_SOAPBOX
80 * TYPE_NEWS - the account is a news reflector
81 * Associated page type: PAGE_SOAPBOX
83 * TYPE_COMMUNITY - the account is community forum
84 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
86 * TYPE_RELAY - the account is a relay
87 * This will only be assigned to contacts, not to user accounts
90 const TYPE_UNKNOWN = -1;
91 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
92 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
93 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
94 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
95 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
115 * @return array|boolean Contact record if it exists, false otherwise
118 public static function getById($id)
120 return DBA::selectFirst('contact', [], ['id' => $id]);
124 * @brief Tests if the given contact is a follower
126 * @param int $cid Either public contact id or user's contact id
127 * @param int $uid User ID
129 * @return boolean is the contact id a follower?
130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
131 * @throws \ImagickException
133 public static function isFollower($cid, $uid)
135 if (self::isBlockedByUser($cid, $uid)) {
139 $cdata = self::getPublicAndUserContacID($cid, $uid);
140 if (empty($cdata['user'])) {
144 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
145 return DBA::exists('contact', $condition);
149 * @brief Get the basepath for a given contact link
150 * @todo Add functionality to store this value in the contact table
152 * @param string $url The contact link
154 * @return string basepath
155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
156 * @throws \ImagickException
158 public static function getBasepath($url)
160 $data = Probe::uri($url);
161 if (!empty($data['baseurl'])) {
162 return $data['baseurl'];
165 // When we can't probe the server, we use some ugly function that does some pattern matching
166 return PortableContact::detectServer($url);
170 * Returns the public contact id of the given user id
172 * @param integer $uid User ID
174 * @return integer|boolean Public contact id for given user id
177 public static function getPublicIdByUserId($uid)
179 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
180 if (!DBA::isResult($self)) {
183 return self::getIdForURL($self['url'], 0, true);
187 * @brief Returns the contact id for the user and the public contact id for a given contact id
189 * @param int $cid Either public contact id or user's contact id
190 * @param int $uid User ID
192 * @return array with public and user's contact id
193 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
194 * @throws \ImagickException
196 public static function getPublicAndUserContacID($cid, $uid)
198 if (empty($uid) || empty($cid)) {
202 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
203 if (!DBA::isResult($contact)) {
207 // We quit when the user id don't match the user id of the provided contact
208 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
212 if ($contact['uid'] != 0) {
213 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
217 $ucid = $contact['id'];
219 $pcid = $contact['id'];
220 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
223 return ['public' => $pcid, 'user' => $ucid];
227 * @brief Block contact id for user id
229 * @param int $cid Either public contact id or user's contact id
230 * @param int $uid User ID
231 * @param boolean $blocked Is the contact blocked or unblocked?
234 public static function setBlockedForUser($cid, $uid, $blocked)
236 $cdata = self::getPublicAndUserContacID($cid, $uid);
241 if ($cdata['user'] != 0) {
242 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
245 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
248 // Blocked contact can't be in any group
249 self::removeFromGroups($cid);
254 * @brief Returns "block" state for contact id and user id
256 * @param int $cid Either public contact id or user's contact id
257 * @param int $uid User ID
259 * @return boolean is the contact id blocked for the given user?
262 public static function isBlockedByUser($cid, $uid)
264 $cdata = self::getPublicAndUserContacID($cid, $uid);
269 $public_blocked = false;
271 if (!empty($cdata['public'])) {
272 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
273 if (DBA::isResult($public_contact)) {
274 $public_blocked = $public_contact['blocked'];
278 $user_blocked = $public_blocked;
280 if (!empty($cdata['user'])) {
281 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
282 if (DBA::isResult($user_contact)) {
283 $user_blocked = $user_contact['blocked'];
287 if ($user_blocked != $public_blocked) {
288 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
291 return $user_blocked;
295 * @brief Ignore contact id for user id
297 * @param int $cid Either public contact id or user's contact id
298 * @param int $uid User ID
299 * @param boolean $ignored Is the contact ignored or unignored?
302 public static function setIgnoredForUser($cid, $uid, $ignored)
304 $cdata = self::getPublicAndUserContacID($cid, $uid);
309 if ($cdata['user'] != 0) {
310 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
313 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
317 * @brief Returns "ignore" 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 ignored for the given user?
325 public static function isIgnoredByUser($cid, $uid)
327 $cdata = self::getPublicAndUserContacID($cid, $uid);
332 $public_ignored = false;
334 if (!empty($cdata['public'])) {
335 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
336 if (DBA::isResult($public_contact)) {
337 $public_ignored = $public_contact['ignored'];
341 $user_ignored = $public_ignored;
343 if (!empty($cdata['user'])) {
344 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
345 if (DBA::isResult($user_contact)) {
346 $user_ignored = $user_contact['readonly'];
350 if ($user_ignored != $public_ignored) {
351 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
354 return $user_ignored;
358 * @brief Set "collapsed" for contact id and user id
360 * @param int $cid Either public contact id or user's contact id
361 * @param int $uid User ID
362 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
365 public static function setCollapsedForUser($cid, $uid, $collapsed)
367 $cdata = self::getPublicAndUserContacID($cid, $uid);
372 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
376 * @brief Returns "collapsed" state for contact id and user id
378 * @param int $cid Either public contact id or user's contact id
379 * @param int $uid User ID
381 * @return boolean is the contact id blocked for the given user?
382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
383 * @throws \ImagickException
385 public static function isCollapsedByUser($cid, $uid)
387 $cdata = self::getPublicAndUserContacID($cid, $uid);
394 if (!empty($cdata['public'])) {
395 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
396 if (DBA::isResult($public_contact)) {
397 $collapsed = $public_contact['collapsed'];
405 * @brief Returns a list of contacts belonging in a group
411 public static function getByGroupId($gid)
416 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
418 INNER JOIN `group_member`
419 ON `contact`.`id` = `group_member`.`contact-id`
421 AND `contact`.`uid` = ?
422 AND NOT `contact`.`self`
423 AND NOT `contact`.`deleted`
424 AND NOT `contact`.`blocked`
425 AND NOT `contact`.`pending`
426 ORDER BY `contact`.`name` ASC',
431 if (DBA::isResult($stmt)) {
432 $return = DBA::toArray($stmt);
440 * @brief Returns the count of OStatus contacts in a group
446 public static function getOStatusCountByGroupId($gid)
450 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
452 INNER JOIN `group_member`
453 ON `contact`.`id` = `group_member`.`contact-id`
455 AND `contact`.`uid` = ?
456 AND `contact`.`network` = ?
457 AND `contact`.`notify` != ""',
462 $return = $contacts['count'];
469 * Creates the self-contact for the provided user id
472 * @return bool Operation success
473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
475 public static function createSelfFromUserId($uid)
477 // Only create the entry if it doesn't exist yet
478 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
482 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
483 if (!DBA::isResult($user)) {
487 $return = DBA::insert('contact', [
488 'uid' => $user['uid'],
489 'created' => DateTimeFormat::utcNow(),
491 'name' => $user['username'],
492 'nick' => $user['nickname'],
493 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
494 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
495 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
498 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
499 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
500 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
501 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
502 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
503 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
504 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
505 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
506 'name-date' => DateTimeFormat::utcNow(),
507 'uri-date' => DateTimeFormat::utcNow(),
508 'avatar-date' => DateTimeFormat::utcNow(),
516 * Updates the self-contact for the provided user id
519 * @param boolean $update_avatar Force the avatar update
520 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
522 public static function updateSelfFromUserID($uid, $update_avatar = false)
524 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
525 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
526 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
527 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
528 if (!DBA::isResult($self)) {
532 $fields = ['nickname', 'page-flags', 'account-type'];
533 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
534 if (!DBA::isResult($user)) {
538 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
539 'country-name', 'gender', 'pub_keywords', 'xmpp'];
540 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
541 if (!DBA::isResult($profile)) {
545 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
546 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
547 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
548 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
549 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
551 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
552 if (DBA::isResult($avatar)) {
553 if ($update_avatar) {
554 $fields['avatar-date'] = DateTimeFormat::utcNow();
557 // Creating the path to the avatar, beginning with the file suffix
558 $types = Image::supportedTypes();
559 if (isset($types[$avatar['type']])) {
560 $file_suffix = $types[$avatar['type']];
562 $file_suffix = 'jpg';
565 // We are adding a timestamp value so that other systems won't use cached content
566 $timestamp = strtotime($fields['avatar-date']);
568 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
569 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
571 $fields['photo'] = $prefix . '4' . $suffix;
572 $fields['thumb'] = $prefix . '5' . $suffix;
573 $fields['micro'] = $prefix . '6' . $suffix;
575 // We hadn't found a photo entry, so we use the default avatar
576 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
577 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
578 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
581 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
582 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
584 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
585 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
586 $fields['nurl'] = Strings::normaliseLink($fields['url']);
587 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
588 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
589 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
590 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
591 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
592 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
596 foreach ($fields as $field => $content) {
597 if ($self[$field] != $content) {
603 $fields['name-date'] = DateTimeFormat::utcNow();
604 DBA::update('contact', $fields, ['id' => $self['id']]);
606 // Update the public contact as well
607 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
609 // Update the profile
610 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
611 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
612 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
617 * @brief Marks a contact for removal
619 * @param int $id contact id
621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
623 public static function remove($id)
625 // We want just to make sure that we don't delete our "self" contact
626 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
627 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
631 // Archive the contact
632 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
634 // Delete it in the background
635 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
639 * @brief Sends an unfriend message. Does not remove the contact
641 * @param array $user User unfriending
642 * @param array $contact Contact unfriended
643 * @param boolean $dissolve Remove the contact on the remote side
645 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
646 * @throws \ImagickException
648 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
650 if (empty($contact['network'])) {
653 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
654 DFRN::deliver($user, $contact, 'placeholder', true);
655 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
656 // create an unfollow slap
658 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
659 $item['follow'] = $contact["url"];
664 $item['attach'] = '';
665 $slap = OStatus::salmon($item, $user);
667 if (!empty($contact['notify'])) {
668 Salmon::slapper($user, $contact['notify'], $slap);
670 } elseif ($contact['network'] == Protocol::DIASPORA) {
671 Diaspora::sendUnshare($user, $contact);
672 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
673 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
676 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
682 * @brief Marks a contact for archival after a communication issue delay
684 * Contact has refused to recognise us as a friend. We will start a countdown.
685 * If they still don't recognise us in 32 days, the relationship is over,
686 * and we won't waste any more time trying to communicate with them.
687 * This provides for the possibility that their database is temporarily messed
688 * up or some other transient event and that there's a possibility we could recover from it.
690 * @param array $contact contact to mark for archival
692 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
694 public static function markForArchival(array $contact)
696 if (!isset($contact['url']) && !empty($contact['id'])) {
697 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
698 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
699 if (!DBA::isResult($contact)) {
702 } elseif (!isset($contact['url'])) {
703 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
706 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
708 // Contact already archived or "self" contact? => nothing to do
709 if ($contact['archive'] || $contact['self']) {
713 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
714 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
715 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
718 * We really should send a notification to the owner after 2-3 weeks
719 * so they won't be surprised when the contact vanishes and can take
720 * remedial action if this was a serious mistake or glitch
723 /// @todo Check for contact vitality via probing
724 $archival_days = Config::get('system', 'archival_days', 32);
726 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
727 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
728 /* Relationship is really truly dead. archive them rather than
729 * delete, though if the owner tries to unarchive them we'll start
730 * the whole process over again.
732 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
733 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
739 * @brief Cancels the archival countdown
741 * @see Contact::markForArchival()
743 * @param array $contact contact to be unmarked for archival
747 public static function unmarkForArchival(array $contact)
749 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
750 $exists = DBA::exists('contact', $condition);
752 // We don't need to update, we never marked this contact for archival
757 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
759 if (!isset($contact['url']) && !empty($contact['id'])) {
760 $fields = ['id', 'url', 'batch'];
761 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
762 if (!DBA::isResult($contact)) {
767 // It's a miracle. Our dead contact has inexplicably come back to life.
768 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
769 DBA::update('contact', $fields, ['id' => $contact['id']]);
770 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
772 if (!empty($contact['batch'])) {
773 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
774 DBA::update('contact', $fields, $condition);
779 * @brief Get contact data for a given profile link
781 * The function looks at several places (contact table and gcontact table) for the contact
782 * It caches its result for the same script execution to prevent duplicate calls
784 * @param string $url The profile link
785 * @param int $uid User id
786 * @param array $default If not data was found take this data as default value
788 * @return array Contact data
789 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
791 public static function getDetailsByURL($url, $uid = -1, array $default = [])
803 if (isset($cache[$url][$uid])) {
804 return $cache[$url][$uid];
807 $ssl_url = str_replace('http://', 'https://', $url);
809 // Fetch contact data from the contact table for the given user
810 $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`,
811 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
812 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
813 $r = DBA::toArray($s);
815 // Fetch contact data from the contact table for the given user, checking with the alias
816 if (!DBA::isResult($r)) {
817 $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`,
818 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
819 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
820 $r = DBA::toArray($s);
823 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
824 if (!DBA::isResult($r)) {
825 $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`,
826 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
827 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
828 $r = DBA::toArray($s);
831 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
832 if (!DBA::isResult($r)) {
833 $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`,
834 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
835 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
836 $r = DBA::toArray($s);
839 // Fetch the data from the gcontact table
840 if (!DBA::isResult($r)) {
841 $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`,
842 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
843 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
844 $r = DBA::toArray($s);
847 if (DBA::isResult($r)) {
848 // If there is more than one entry we filter out the connector networks
850 foreach ($r as $id => $result) {
851 if ($result["network"] == Protocol::STATUSNET) {
857 $profile = array_shift($r);
859 // "bd" always contains the upcoming birthday of a contact.
860 // "birthday" might contain the birthday including the year of birth.
861 if ($profile["birthday"] > DBA::NULL_DATE) {
862 $bd_timestamp = strtotime($profile["birthday"]);
863 $month = date("m", $bd_timestamp);
864 $day = date("d", $bd_timestamp);
866 $current_timestamp = time();
867 $current_year = date("Y", $current_timestamp);
868 $current_month = date("m", $current_timestamp);
869 $current_day = date("d", $current_timestamp);
871 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
872 $current = $current_year . "-" . $current_month . "-" . $current_day;
874 if ($profile["bd"] < $current) {
875 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
878 $profile["bd"] = DBA::NULL_DATE;
884 if (empty($profile["photo"]) && isset($default["photo"])) {
885 $profile["photo"] = $default["photo"];
888 if (empty($profile["name"]) && isset($default["name"])) {
889 $profile["name"] = $default["name"];
892 if (empty($profile["network"]) && isset($default["network"])) {
893 $profile["network"] = $default["network"];
896 if (empty($profile["thumb"]) && isset($profile["photo"])) {
897 $profile["thumb"] = $profile["photo"];
900 if (empty($profile["micro"]) && isset($profile["thumb"])) {
901 $profile["micro"] = $profile["thumb"];
904 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
905 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
907 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
910 // Show contact details of Diaspora contacts only if connected
911 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
912 $profile["location"] = "";
913 $profile["about"] = "";
914 $profile["gender"] = "";
915 $profile["birthday"] = DBA::NULL_DATE;
918 $cache[$url][$uid] = $profile;
924 * @brief Get contact data for a given address
926 * The function looks at several places (contact table and gcontact table) for the contact
928 * @param string $addr The profile link
929 * @param int $uid User id
931 * @return array Contact data
932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
933 * @throws \ImagickException
935 public static function getDetailsByAddr($addr, $uid = -1)
945 // Fetch contact data from the contact table for the given user
946 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
947 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
948 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
952 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
953 if (!DBA::isResult($r)) {
954 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
955 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
956 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
961 // Fetch the data from the gcontact table
962 if (!DBA::isResult($r)) {
963 $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`,
964 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
965 FROM `gcontact` WHERE `addr` = '%s'",
970 if (!DBA::isResult($r)) {
971 $data = Probe::uri($addr);
973 $profile = self::getDetailsByURL($data['url'], $uid);
982 * @brief Returns the data array for the photo menu of a given contact
984 * @param array $contact contact
985 * @param int $uid optional, default 0
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988 * @throws \ImagickException
990 public static function photoMenu(array $contact, $uid = 0)
995 $contact_drop_link = '';
1002 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1004 $profile_link = self::magicLink($contact['url']);
1005 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1010 // Look for our own contact if the uid doesn't match and isn't public
1011 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1012 if (DBA::isResult($contact_own)) {
1013 return self::photoMenu($contact_own, $uid);
1018 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1020 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1022 $profile_link = $contact['url'];
1025 if ($profile_link === 'mailbox') {
1030 $status_link = $profile_link . '?tab=status';
1031 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1032 $profile_link = $profile_link . '?tab=profile';
1035 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1036 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1039 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1040 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1043 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1045 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1047 if (!$contact['self']) {
1048 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1053 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1055 if (empty($contact['uid'])) {
1056 $connlnk = 'follow/?url=' . $contact['url'];
1058 'profile' => [L10n::t('View Profile'), $profile_link, true],
1059 'network' => [L10n::t('Network Posts'), $posts_link, false],
1060 'edit' => [L10n::t('View Contact'), $contact_url, false],
1061 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1065 'status' => [L10n::t('View Status'), $status_link, true],
1066 'profile' => [L10n::t('View Profile'), $profile_link, true],
1067 'photos' => [L10n::t('View Photos'), $photos_link, true],
1068 'network' => [L10n::t('Network Posts'), $posts_link, false],
1069 'edit' => [L10n::t('View Contact'), $contact_url, false],
1070 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1071 'pm' => [L10n::t('Send PM'), $pm_url, false],
1072 'poke' => [L10n::t('Poke'), $poke_link, false],
1076 $args = ['contact' => $contact, 'menu' => &$menu];
1078 Hook::callAll('contact_photo_menu', $args);
1080 $menucondensed = [];
1082 foreach ($menu as $menuname => $menuitem) {
1083 if ($menuitem[1] != '') {
1084 $menucondensed[$menuname] = $menuitem;
1088 return $menucondensed;
1092 * @brief Returns ungrouped contact count or list for user
1094 * Returns either the total number of ungrouped contacts for the given user
1095 * id or a paginated list of ungrouped contacts.
1097 * @param int $uid uid
1099 * @throws \Exception
1101 public static function getUngroupedList($uid)
1111 SELECT DISTINCT(`contact-id`)
1113 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1114 WHERE `group`.`uid` = %d
1115 )", intval($uid), intval($uid));
1119 * @brief Fetch the contact id for a given URL and user
1121 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1122 * `addr` or `alias`.
1124 * If there's no record and we aren't looking for a public contact, we quit.
1125 * If there's one, we check that it isn't time to update the picture else we
1126 * directly return the found contact id.
1128 * Second, we probe the provided $url whether it's http://server.tld/profile or
1129 * nick@server.tld. We quit if we can't get any info back.
1131 * Third, we create the contact record if it doesn't exist
1133 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1134 * if there's any updates
1136 * @param string $url Contact URL
1137 * @param integer $uid The user id for the contact (0 = public contact)
1138 * @param boolean $no_update Don't update the contact
1139 * @param array $default Default value for creating the contact when every else fails
1140 * @param boolean $in_loop Internally used variable to prevent an endless loop
1142 * @return integer Contact ID
1143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1144 * @throws \ImagickException
1146 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1148 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1156 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1157 // We first try the nurl (http://server.tld/nick), most common case
1158 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1160 // Then the addr (nick@server.tld)
1161 if (!DBA::isResult($contact)) {
1162 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1165 // Then the alias (which could be anything)
1166 if (!DBA::isResult($contact)) {
1167 // The link could be provided as http although we stored it as https
1168 $ssl_url = str_replace('http://', 'https://', $url);
1169 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1170 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1173 if (DBA::isResult($contact)) {
1174 $contact_id = $contact["id"];
1176 // Update the contact every 7 days
1177 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1179 // We force the update if the avatar is empty
1180 if (empty($contact['avatar'])) {
1181 $update_contact = true;
1183 if (!$update_contact || $no_update) {
1186 } elseif ($uid != 0) {
1187 // Non-existing user-specific contact, exiting
1191 // When we don't want to update, we look if some of our users already know this contact
1193 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1194 'photo', 'keywords', 'location', 'about', 'network',
1195 'priority', 'batch', 'request', 'confirm', 'poco'];
1196 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1198 if (DBA::isResult($data)) {
1199 // For security reasons we don't fetch key data from our users
1200 $data["pubkey"] = '';
1207 $data = Probe::uri($url, "", $uid);
1209 // Ensure that there is a gserver entry
1210 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1211 PortableContact::checkServer($data['baseurl']);
1215 // Last try in gcontact for unsupported networks
1216 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1221 // Get data from the gcontact table
1222 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1223 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1224 if (!DBA::isResult($contact)) {
1225 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1228 if (!DBA::isResult($contact)) {
1229 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1230 'photo', 'keywords', 'location', 'about', 'network',
1231 'priority', 'batch', 'request', 'confirm', 'poco'];
1232 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1235 // The link could be provided as http although we stored it as https
1236 $ssl_url = str_replace('http://', 'https://', $url);
1238 if (!DBA::isResult($contact)) {
1239 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1240 $contact = DBA::selectFirst('contact', $fields, $condition);
1243 if (!DBA::isResult($contact)) {
1244 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1245 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1246 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1247 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1250 if (!empty($default)) {
1251 $contact = $default;
1254 if (!DBA::isResult($contact)) {
1257 $data = array_merge($data, $contact);
1261 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1262 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1268 'created' => DateTimeFormat::utcNow(),
1269 'url' => $data["url"],
1270 'nurl' => Strings::normaliseLink($data["url"]),
1271 'addr' => $data["addr"],
1272 'alias' => $data["alias"],
1273 'notify' => $data["notify"],
1274 'poll' => $data["poll"],
1275 'name' => $data["name"],
1276 'nick' => $data["nick"],
1277 'photo' => $data["photo"],
1278 'keywords' => $data["keywords"],
1279 'location' => $data["location"],
1280 'about' => $data["about"],
1281 'network' => $data["network"],
1282 'pubkey' => $data["pubkey"],
1283 'rel' => self::SHARING,
1284 'priority' => $data["priority"],
1285 'batch' => $data["batch"],
1286 'request' => $data["request"],
1287 'confirm' => $data["confirm"],
1288 'poco' => $data["poco"],
1289 'name-date' => DateTimeFormat::utcNow(),
1290 'uri-date' => DateTimeFormat::utcNow(),
1291 'avatar-date' => DateTimeFormat::utcNow(),
1297 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1299 DBA::update('contact', $fields, $condition, true);
1301 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1302 $contacts = DBA::toArray($s);
1303 if (!DBA::isResult($contacts)) {
1307 $contact_id = $contacts[0]["id"];
1309 // Update the newly created contact from data in the gcontact table
1310 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1311 if (DBA::isResult($gcontact)) {
1312 // Only use the information when the probing hadn't fetched these values
1313 if ($data['keywords'] != '') {
1314 unset($gcontact['keywords']);
1316 if ($data['location'] != '') {
1317 unset($gcontact['location']);
1319 if ($data['about'] != '') {
1320 unset($gcontact['about']);
1322 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1325 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1326 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1327 Strings::normaliseLink($data["url"]), 0, $contact_id];
1328 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1329 DBA::delete('contact', $condition);
1333 self::updateAvatar($data["photo"], $uid, $contact_id);
1335 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1336 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1338 // This condition should always be true
1339 if (!DBA::isResult($contact)) {
1343 $updated = ['addr' => $data['addr'],
1344 'alias' => $data['alias'],
1345 'url' => $data['url'],
1346 'nurl' => Strings::normaliseLink($data['url']),
1347 'name' => $data['name'],
1348 'nick' => $data['nick']];
1350 if ($data['keywords'] != '') {
1351 $updated['keywords'] = $data['keywords'];
1353 if ($data['location'] != '') {
1354 $updated['location'] = $data['location'];
1357 // Update the technical stuff as well - if filled
1358 if ($data['notify'] != '') {
1359 $updated['notify'] = $data['notify'];
1361 if ($data['poll'] != '') {
1362 $updated['poll'] = $data['poll'];
1364 if ($data['batch'] != '') {
1365 $updated['batch'] = $data['batch'];
1367 if ($data['request'] != '') {
1368 $updated['request'] = $data['request'];
1370 if ($data['confirm'] != '') {
1371 $updated['confirm'] = $data['confirm'];
1373 if ($data['poco'] != '') {
1374 $updated['poco'] = $data['poco'];
1377 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1378 if (empty($contact['pubkey'])) {
1379 $updated['pubkey'] = $data['pubkey'];
1382 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1383 $updated['uri-date'] = DateTimeFormat::utcNow();
1385 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1386 $updated['name-date'] = DateTimeFormat::utcNow();
1389 $updated['avatar-date'] = DateTimeFormat::utcNow();
1391 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1397 * @brief Checks if the contact is blocked
1399 * @param int $cid contact id
1401 * @return boolean Is the contact blocked?
1402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1404 public static function isBlocked($cid)
1410 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1411 if (!DBA::isResult($blocked)) {
1415 if (Network::isUrlBlocked($blocked['url'])) {
1419 return (bool) $blocked['blocked'];
1423 * @brief Checks if the contact is hidden
1425 * @param int $cid contact id
1427 * @return boolean Is the contact hidden?
1428 * @throws \Exception
1430 public static function isHidden($cid)
1436 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1437 if (!DBA::isResult($hidden)) {
1440 return (bool) $hidden['hidden'];
1444 * @brief Returns posts from a given contact url
1446 * @param string $contact_url Contact URL
1448 * @param bool $thread_mode
1449 * @param int $update
1450 * @return string posts in HTML
1451 * @throws \Exception
1453 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1455 $a = self::getApp();
1457 $cid = self::getIdForURL($contact_url);
1459 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1460 if (!DBA::isResult($contact)) {
1464 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1465 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1467 $sql = "`item`.`uid` = ?";
1470 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1473 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1474 $cid, GRAVITY_PARENT, local_user()];
1476 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1477 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1480 $pager = new Pager($a->query_string);
1482 $params = ['order' => ['created' => true],
1483 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1486 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1488 $items = Item::inArray($r);
1490 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1492 $r = Item::selectForUser(local_user(), [], $condition, $params);
1494 $items = Item::inArray($r);
1496 $o = conversation($a, $items, $pager, 'contact-posts', false);
1500 $o .= $pager->renderMinimal(count($items));
1507 * @brief Returns the account type name
1509 * The function can be called with either the user or the contact array
1511 * @param array $contact contact or user array
1514 public static function getAccountType(array $contact)
1516 // There are several fields that indicate that the contact or user is a forum
1517 // "page-flags" is a field in the user table,
1518 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1519 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1520 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1521 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1522 || (isset($contact['forum']) && intval($contact['forum']))
1523 || (isset($contact['prv']) && intval($contact['prv']))
1524 || (isset($contact['community']) && intval($contact['community']))
1526 $type = self::TYPE_COMMUNITY;
1528 $type = self::TYPE_PERSON;
1531 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1532 if (isset($contact["contact-type"])) {
1533 $type = $contact["contact-type"];
1536 if (isset($contact["account-type"])) {
1537 $type = $contact["account-type"];
1541 case self::TYPE_ORGANISATION:
1542 $account_type = L10n::t("Organisation");
1545 case self::TYPE_NEWS:
1546 $account_type = L10n::t('News');
1549 case self::TYPE_COMMUNITY:
1550 $account_type = L10n::t("Forum");
1558 return $account_type;
1562 * @brief Blocks a contact
1566 * @throws \Exception
1568 public static function block($uid)
1570 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1576 * @brief Unblocks a contact
1580 * @throws \Exception
1582 public static function unblock($uid)
1584 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1590 * @brief Updates the avatar links in a contact only if needed
1592 * @param string $avatar Link to avatar picture
1593 * @param int $uid User id of contact owner
1594 * @param int $cid Contact id
1595 * @param bool $force force picture update
1597 * @return array Returns array of the different avatar sizes
1598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1599 * @throws \ImagickException
1601 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1603 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1604 if (!DBA::isResult($contact)) {
1607 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1610 if (($contact["avatar"] != $avatar) || $force) {
1611 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1616 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1620 // Update the public contact (contact id = 0)
1622 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1623 if (DBA::isResult($pcontact)) {
1624 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1636 * @param integer $id contact id
1637 * @param string $network Optional network we are probing for
1638 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1640 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1641 * @throws \ImagickException
1643 public static function updateFromProbe($id, $network = '', $force = false)
1646 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1647 This will reliably kill your communication with Friendica contacts.
1650 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1651 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1652 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1653 if (!DBA::isResult($contact)) {
1657 $uid = $contact['uid'];
1658 unset($contact['uid']);
1660 $contact['photo'] = $contact['avatar'];
1661 unset($contact['avatar']);
1663 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1665 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1666 if ((in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM])) && ($ret['network'] != $contact['network'])) {
1672 // make sure to not overwrite existing values with blank entries
1673 foreach ($ret as $key => $val) {
1674 if (!isset($contact[$key])) {
1676 } elseif (($contact[$key] != '') && ($val == '')) {
1677 $ret[$key] = $contact[$key];
1678 } elseif ($ret[$key] != $contact[$key]) {
1687 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1689 self::updateAvatar($ret['photo'], $uid, $id, true);
1691 unset($ret['photo']);
1692 DBA::update('contact', $ret, ['id' => $id]);
1694 // Update the corresponding gcontact entry
1695 PortableContact::lastUpdated($ret["url"]);
1701 * Takes a $uid and a url/handle and adds a new contact
1702 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1703 * dfrn_request page.
1705 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1708 * $return['success'] boolean true if successful
1709 * $return['message'] error text if success is false.
1711 * @brief Takes a $uid and a url/handle and adds a new contact
1713 * @param string $url
1714 * @param bool $interactive
1715 * @param string $network
1717 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1718 * @throws \ImagickException
1720 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1722 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1726 // remove ajax junk, e.g. Twitter
1727 $url = str_replace('/#!/', '/', $url);
1729 if (!Network::isUrlAllowed($url)) {
1730 $result['message'] = L10n::t('Disallowed profile URL.');
1734 if (Network::isUrlBlocked($url)) {
1735 $result['message'] = L10n::t('Blocked domain');
1740 $result['message'] = L10n::t('Connect URL missing.');
1744 $arr = ['url' => $url, 'contact' => []];
1746 Hook::callAll('follow', $arr);
1749 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1753 if (!empty($arr['contact']['name'])) {
1754 $ret = $arr['contact'];
1756 $ret = Probe::uri($url, $network, $uid, false);
1759 if (($network != '') && ($ret['network'] != $network)) {
1760 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1764 // check if we already have a contact
1765 // the poll url is more reliable than the profile url, as we may have
1766 // indirect links or webfinger links
1768 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1769 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1770 if (!DBA::isResult($contact)) {
1771 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1772 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1775 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1777 if (strlen($a->getURLPath())) {
1778 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1780 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1783 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1787 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1788 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1789 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1793 // This extra param just confuses things, remove it
1794 if ($ret['network'] === Protocol::DIASPORA) {
1795 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1798 // do we have enough information?
1799 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1800 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1801 if (empty($ret['poll'])) {
1802 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1804 if (empty($ret['name'])) {
1805 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1807 if (empty($ret['url'])) {
1808 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1810 if (strpos($url, '@') !== false) {
1811 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1812 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1817 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1818 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1819 $ret['notify'] = '';
1822 if (!$ret['notify']) {
1823 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1826 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1828 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1830 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1832 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1834 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1838 if (DBA::isResult($contact)) {
1840 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1842 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1843 DBA::update('contact', $fields, ['id' => $contact['id']]);
1845 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1847 // create contact record
1848 DBA::insert('contact', [
1850 'created' => DateTimeFormat::utcNow(),
1851 'url' => $ret['url'],
1852 'nurl' => Strings::normaliseLink($ret['url']),
1853 'addr' => $ret['addr'],
1854 'alias' => $ret['alias'],
1855 'batch' => $ret['batch'],
1856 'notify' => $ret['notify'],
1857 'poll' => $ret['poll'],
1858 'poco' => $ret['poco'],
1859 'name' => $ret['name'],
1860 'nick' => $ret['nick'],
1861 'network' => $ret['network'],
1862 'pubkey' => $ret['pubkey'],
1863 'rel' => $new_relation,
1864 'priority'=> $ret['priority'],
1865 'writable'=> $writeable,
1866 'hidden' => $hidden,
1869 'pending' => $pending,
1874 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1875 if (!DBA::isResult($contact)) {
1876 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1880 $contact_id = $contact['id'];
1881 $result['cid'] = $contact_id;
1883 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1885 // Update the avatar
1886 self::updateAvatar($ret['photo'], $uid, $contact_id);
1888 // pull feed and consume it, which should subscribe to the hub.
1890 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1892 $owner = User::getOwnerDataById($uid);
1894 if (DBA::isResult($owner)) {
1895 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1896 // create a follow slap
1898 $item['verb'] = ACTIVITY_FOLLOW;
1899 $item['follow'] = $contact["url"];
1901 $item['title'] = '';
1904 $item['attach'] = '';
1906 $slap = OStatus::salmon($item, $owner);
1908 if (!empty($contact['notify'])) {
1909 Salmon::slapper($owner, $contact['notify'], $slap);
1911 } elseif ($contact['network'] == Protocol::DIASPORA) {
1912 $ret = Diaspora::sendShare($a->user, $contact);
1913 Logger::log('share returns: ' . $ret);
1914 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1915 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1916 if (empty($activity_id)) {
1917 // This really should never happen
1921 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1922 Logger::log('Follow returns: ' . $ret);
1926 $result['success'] = true;
1931 * @brief Updated contact's SSL policy
1933 * @param array $contact Contact array
1934 * @param string $new_policy New policy, valid: self,full
1936 * @return array Contact array with updated values
1937 * @throws \Exception
1939 public static function updateSslPolicy(array $contact, $new_policy)
1941 $ssl_changed = false;
1942 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1943 $ssl_changed = true;
1944 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1945 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1946 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1947 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1948 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1949 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1952 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1953 $ssl_changed = true;
1954 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1955 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1956 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1957 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1958 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1959 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1963 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1964 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1965 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1966 DBA::update('contact', $fields, ['id' => $contact['id']]);
1972 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1973 // Should always be set
1974 if (empty($datarray['author-id'])) {
1978 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1979 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1980 if (!DBA::isResult($pub_contact)) {
1981 // Should never happen
1985 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1986 $name = $pub_contact['name'];
1987 $photo = $pub_contact['photo'];
1988 $nick = $pub_contact['nick'];
1989 $network = $pub_contact['network'];
1991 if (is_array($contact)) {
1992 if (($contact['rel'] == self::SHARING)
1993 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1994 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1995 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1998 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1999 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2002 // send email notification to owner?
2004 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2005 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2008 // create contact record
2009 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2010 `blocked`, `readonly`, `pending`, `writable`)
2011 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
2012 intval($importer['uid']),
2013 DBA::escape(DateTimeFormat::utcNow()),
2015 DBA::escape(Strings::normaliseLink($url)),
2018 DBA::escape($photo),
2019 DBA::escape($network),
2020 intval(self::FOLLOWER)
2024 'id' => DBA::lastInsertId(),
2025 'network' => $network,
2031 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2033 /// @TODO Encapsulate this into a function/method
2034 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2035 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2036 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2037 // create notification
2038 $hash = Strings::getRandomHex();
2040 if (is_array($contact_record)) {
2041 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2042 'blocked' => false, 'knowyou' => false,
2043 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2046 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2048 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2049 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2052 'type' => NOTIFY_INTRO,
2053 'notify_flags' => $user['notify-flags'],
2054 'language' => $user['language'],
2055 'to_name' => $user['username'],
2056 'to_email' => $user['email'],
2057 'uid' => $user['uid'],
2058 'link' => System::baseUrl() . '/notifications/intro',
2059 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2060 'source_link' => $contact_record['url'],
2061 'source_photo' => $contact_record['photo'],
2062 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2067 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2068 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2069 DBA::update('contact', ['pending' => false], $condition);
2071 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2073 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2074 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2080 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2082 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2083 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2085 Contact::remove($contact['id']);
2089 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2091 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2092 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2094 Contact::remove($contact['id']);
2099 * @brief Create a birthday event.
2101 * Update the year and the birthday.
2103 public static function updateBirthdays()
2107 AND `bd` > "0001-01-01"
2108 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2109 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2110 AND NOT `contact`.`pending`
2111 AND NOT `contact`.`hidden`
2112 AND NOT `contact`.`blocked`
2113 AND NOT `contact`.`archive`
2114 AND NOT `contact`.`deleted`',
2119 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2121 while ($contact = DBA::fetch($contacts)) {
2122 Logger::log('update_contact_birthday: ' . $contact['bd']);
2124 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2126 if (Event::createBirthday($contact, $nextbd)) {
2130 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2131 ['id' => $contact['id']]
2138 * Remove the unavailable contact ids from the provided list
2140 * @param array $contact_ids Contact id list
2141 * @throws \Exception
2143 public static function pruneUnavailable(array &$contact_ids)
2145 if (empty($contact_ids)) {
2149 $str = DBA::escape(implode(',', $contact_ids));
2151 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2154 while($contact = DBA::fetch($stmt)) {
2155 $return[] = $contact['id'];
2160 $contact_ids = $return;
2164 * @brief Returns a magic link to authenticate remote visitors
2166 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2168 * @param string $contact_url The address of the target contact profile
2169 * @param string $url An url that we will be redirected to after the authentication
2171 * @return string with "redir" link
2172 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2173 * @throws \ImagickException
2175 public static function magicLink($contact_url, $url = '')
2177 if (!local_user() && !remote_user()) {
2178 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2181 $cid = self::getIdForURL($contact_url, 0, true);
2183 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2186 return self::magicLinkbyId($cid, $url);
2190 * @brief Returns a magic link to authenticate remote visitors
2192 * @param integer $cid The contact id of the target contact profile
2193 * @param string $url An url that we will be redirected to after the authentication
2195 * @return string with "redir" link
2196 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2197 * @throws \ImagickException
2199 public static function magicLinkbyId($cid, $url = '')
2201 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2203 return self::magicLinkByContact($contact, $url);
2207 * @brief Returns a magic link to authenticate remote visitors
2209 * @param array $contact The contact array with "uid", "network" and "url"
2210 * @param string $url An url that we will be redirected to after the authentication
2212 * @return string with "redir" link
2213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2214 * @throws \ImagickException
2216 public static function magicLinkByContact($contact, $url = '')
2218 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2219 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2222 // Only redirections to the same host do make sense
2223 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2227 if ($contact['uid'] != 0) {
2228 return self::magicLink($contact['url'], $url);
2231 $redirect = 'redir/' . $contact['id'];
2234 $redirect .= '?url=' . $url;
2241 * Remove a contact from all groups
2243 * @param integer $contact_id
2245 * @return boolean Success
2247 public static function removeFromGroups($contact_id)
2249 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2253 * Is the contact a forum?
2255 * @param integer $contactid ID of the contact
2257 * @return boolean "true" if it is a forum
2259 public static function isForum($contactid)
2261 $fields = ['forum', 'prv'];
2262 $condition = ['id' => $contactid];
2263 $contact = DBA::selectFirst('contact', $fields, $condition);
2264 if (!DBA::isResult($contact)) {
2269 return ($contact['forum'] || $contact['prv']);