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\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
30 * @brief functions for interacting with a contact
32 class Contact extends BaseObject
35 * @deprecated since version 2019.03
36 * @see User::PAGE_FLAGS_NORMAL
38 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
40 * @deprecated since version 2019.03
41 * @see User::PAGE_FLAGS_SOAPBOX
43 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
45 * @deprecated since version 2019.03
46 * @see User::PAGE_FLAGS_COMMUNITY
48 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
50 * @deprecated since version 2019.03
51 * @see User::PAGE_FLAGS_FREELOVE
53 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
55 * @deprecated since version 2019.03
56 * @see User::PAGE_FLAGS_BLOG
58 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
60 * @deprecated since version 2019.03
61 * @see User::PAGE_FLAGS_PRVGROUP
63 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
71 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
73 * TYPE_PERSON - the account belongs to a person
74 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
76 * TYPE_ORGANISATION - the account belongs to an organisation
77 * Associated page type: PAGE_SOAPBOX
79 * TYPE_NEWS - the account is a news reflector
80 * Associated page type: PAGE_SOAPBOX
82 * TYPE_COMMUNITY - the account is community forum
83 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
85 * TYPE_RELAY - the account is a relay
86 * This will only be assigned to contacts, not to user accounts
89 const TYPE_UNKNOWN = -1;
90 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
91 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
92 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
93 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
94 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
113 * @brief Tests if the given contact is a follower
115 * @param int $cid Either public contact id or user's contact id
116 * @param int $uid User ID
118 * @return boolean is the contact id a follower?
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120 * @throws \ImagickException
122 public static function isFollower($cid, $uid)
124 if (self::isBlockedByUser($cid, $uid)) {
128 $cdata = self::getPublicAndUserContacID($cid, $uid);
129 if (empty($cdata['user'])) {
133 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
134 return DBA::exists('contact', $condition);
138 * @brief Get the basepath for a given contact link
139 * @todo Add functionality to store this value in the contact table
141 * @param string $url The contact link
143 * @return string basepath
144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
145 * @throws \ImagickException
147 public static function getBasepath($url)
149 $data = Probe::uri($url);
150 if (!empty($data['baseurl'])) {
151 return $data['baseurl'];
154 // When we can't probe the server, we use some ugly function that does some pattern matching
155 return PortableContact::detectServer($url);
159 * @brief Returns the contact id for the user and the public contact id for a given contact id
161 * @param int $cid Either public contact id or user's contact id
162 * @param int $uid User ID
164 * @return array with public and user's contact id
165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
166 * @throws \ImagickException
168 public static function getPublicAndUserContacID($cid, $uid)
170 if (empty($uid) || empty($cid)) {
174 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
175 if (!DBA::isResult($contact)) {
179 // We quit when the user id don't match the user id of the provided contact
180 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
184 if ($contact['uid'] != 0) {
185 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
189 $ucid = $contact['id'];
191 $pcid = $contact['id'];
192 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
195 return ['public' => $pcid, 'user' => $ucid];
199 * @brief Block contact id for user id
201 * @param int $cid Either public contact id or user's contact id
202 * @param int $uid User ID
203 * @param boolean $blocked Is the contact blocked or unblocked?
206 public static function setBlockedForUser($cid, $uid, $blocked)
208 $cdata = self::getPublicAndUserContacID($cid, $uid);
213 if ($cdata['user'] != 0) {
214 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
217 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
221 * @brief Returns "block" state for contact id and user id
223 * @param int $cid Either public contact id or user's contact id
224 * @param int $uid User ID
226 * @return boolean is the contact id blocked for the given user?
229 public static function isBlockedByUser($cid, $uid)
231 $cdata = self::getPublicAndUserContacID($cid, $uid);
236 $public_blocked = false;
238 if (!empty($cdata['public'])) {
239 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
240 if (DBA::isResult($public_contact)) {
241 $public_blocked = $public_contact['blocked'];
245 $user_blocked = $public_blocked;
247 if (!empty($cdata['user'])) {
248 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
249 if (DBA::isResult($user_contact)) {
250 $user_blocked = $user_contact['blocked'];
254 if ($user_blocked != $public_blocked) {
255 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
258 return $user_blocked;
262 * @brief Ignore contact id for user id
264 * @param int $cid Either public contact id or user's contact id
265 * @param int $uid User ID
266 * @param boolean $ignored Is the contact ignored or unignored?
269 public static function setIgnoredForUser($cid, $uid, $ignored)
271 $cdata = self::getPublicAndUserContacID($cid, $uid);
276 if ($cdata['user'] != 0) {
277 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
280 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
284 * @brief Returns "ignore" state for contact id and user id
286 * @param int $cid Either public contact id or user's contact id
287 * @param int $uid User ID
289 * @return boolean is the contact id ignored for the given user?
292 public static function isIgnoredByUser($cid, $uid)
294 $cdata = self::getPublicAndUserContacID($cid, $uid);
299 $public_ignored = false;
301 if (!empty($cdata['public'])) {
302 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
303 if (DBA::isResult($public_contact)) {
304 $public_ignored = $public_contact['ignored'];
308 $user_ignored = $public_ignored;
310 if (!empty($cdata['user'])) {
311 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
312 if (DBA::isResult($user_contact)) {
313 $user_ignored = $user_contact['readonly'];
317 if ($user_ignored != $public_ignored) {
318 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
321 return $user_ignored;
325 * @brief Set "collapsed" for contact id and user id
327 * @param int $cid Either public contact id or user's contact id
328 * @param int $uid User ID
329 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
332 public static function setCollapsedForUser($cid, $uid, $collapsed)
334 $cdata = self::getPublicAndUserContacID($cid, $uid);
339 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
343 * @brief Returns "collapsed" state for contact id and user id
345 * @param int $cid Either public contact id or user's contact id
346 * @param int $uid User ID
348 * @return boolean is the contact id blocked for the given user?
349 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
350 * @throws \ImagickException
352 public static function isCollapsedByUser($cid, $uid)
354 $cdata = self::getPublicAndUserContacID($cid, $uid);
361 if (!empty($cdata['public'])) {
362 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
363 if (DBA::isResult($public_contact)) {
364 $collapsed = $public_contact['collapsed'];
372 * @brief Returns a list of contacts belonging in a group
378 public static function getByGroupId($gid)
383 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
385 INNER JOIN `group_member`
386 ON `contact`.`id` = `group_member`.`contact-id`
388 AND `contact`.`uid` = ?
389 AND NOT `contact`.`self`
390 AND NOT `contact`.`deleted`
391 AND NOT `contact`.`blocked`
392 AND NOT `contact`.`pending`
393 ORDER BY `contact`.`name` ASC',
398 if (DBA::isResult($stmt)) {
399 $return = DBA::toArray($stmt);
407 * @brief Returns the count of OStatus contacts in a group
413 public static function getOStatusCountByGroupId($gid)
417 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
419 INNER JOIN `group_member`
420 ON `contact`.`id` = `group_member`.`contact-id`
422 AND `contact`.`uid` = ?
423 AND `contact`.`network` = ?
424 AND `contact`.`notify` != ""',
429 $return = $contacts['count'];
436 * Creates the self-contact for the provided user id
439 * @return bool Operation success
440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442 public static function createSelfFromUserId($uid)
444 // Only create the entry if it doesn't exist yet
445 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
449 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
450 if (!DBA::isResult($user)) {
454 $return = DBA::insert('contact', [
455 'uid' => $user['uid'],
456 'created' => DateTimeFormat::utcNow(),
458 'name' => $user['username'],
459 'nick' => $user['nickname'],
460 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
461 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
462 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
465 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
466 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
467 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
468 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
469 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
470 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
471 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
472 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
473 'name-date' => DateTimeFormat::utcNow(),
474 'uri-date' => DateTimeFormat::utcNow(),
475 'avatar-date' => DateTimeFormat::utcNow(),
483 * Updates the self-contact for the provided user id
486 * @param boolean $update_avatar Force the avatar update
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 public static function updateSelfFromUserID($uid, $update_avatar = false)
491 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
492 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
493 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
494 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
495 if (!DBA::isResult($self)) {
499 $fields = ['nickname', 'page-flags', 'account-type'];
500 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
501 if (!DBA::isResult($user)) {
505 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
506 'country-name', 'gender', 'pub_keywords', 'xmpp'];
507 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
508 if (!DBA::isResult($profile)) {
512 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
513 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
514 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
515 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
516 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
518 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
519 if (DBA::isResult($avatar)) {
520 if ($update_avatar) {
521 $fields['avatar-date'] = DateTimeFormat::utcNow();
524 // Creating the path to the avatar, beginning with the file suffix
525 $types = Image::supportedTypes();
526 if (isset($types[$avatar['type']])) {
527 $file_suffix = $types[$avatar['type']];
529 $file_suffix = 'jpg';
532 // We are adding a timestamp value so that other systems won't use cached content
533 $timestamp = strtotime($fields['avatar-date']);
535 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
536 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
538 $fields['photo'] = $prefix . '4' . $suffix;
539 $fields['thumb'] = $prefix . '5' . $suffix;
540 $fields['micro'] = $prefix . '6' . $suffix;
542 // We hadn't found a photo entry, so we use the default avatar
543 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
544 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
545 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
548 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
549 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
551 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
552 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
553 $fields['nurl'] = Strings::normaliseLink($fields['url']);
554 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
555 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
556 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
557 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
558 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
559 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
563 foreach ($fields as $field => $content) {
564 if ($self[$field] != $content) {
570 $fields['name-date'] = DateTimeFormat::utcNow();
571 DBA::update('contact', $fields, ['id' => $self['id']]);
573 // Update the public contact as well
574 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
576 // Update the profile
577 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
578 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
579 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
584 * @brief Marks a contact for removal
586 * @param int $id contact id
588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
590 public static function remove($id)
592 // We want just to make sure that we don't delete our "self" contact
593 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
594 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
598 // Archive the contact
599 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
601 // Delete it in the background
602 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
606 * @brief Sends an unfriend message. Does not remove the contact
608 * @param array $user User unfriending
609 * @param array $contact Contact unfriended
610 * @param boolean $dissolve Remove the contact on the remote side
612 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
613 * @throws \ImagickException
615 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
617 if (empty($contact['network'])) {
620 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
621 DFRN::deliver($user, $contact, 'placeholder', true);
622 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
623 // create an unfollow slap
625 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
626 $item['follow'] = $contact["url"];
631 $item['attach'] = '';
632 $slap = OStatus::salmon($item, $user);
634 if (!empty($contact['notify'])) {
635 Salmon::slapper($user, $contact['notify'], $slap);
637 } elseif ($contact['network'] == Protocol::DIASPORA) {
638 Diaspora::sendUnshare($user, $contact);
639 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
640 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
643 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
649 * @brief Marks a contact for archival after a communication issue delay
651 * Contact has refused to recognise us as a friend. We will start a countdown.
652 * If they still don't recognise us in 32 days, the relationship is over,
653 * and we won't waste any more time trying to communicate with them.
654 * This provides for the possibility that their database is temporarily messed
655 * up or some other transient event and that there's a possibility we could recover from it.
657 * @param array $contact contact to mark for archival
659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
661 public static function markForArchival(array $contact)
663 if (!isset($contact['url']) && !empty($contact['id'])) {
664 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
665 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
666 if (!DBA::isResult($contact)) {
669 } elseif (!isset($contact['url'])) {
670 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
673 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
675 // Contact already archived or "self" contact? => nothing to do
676 if ($contact['archive'] || $contact['self']) {
680 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
681 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
682 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
685 * We really should send a notification to the owner after 2-3 weeks
686 * so they won't be surprised when the contact vanishes and can take
687 * remedial action if this was a serious mistake or glitch
690 /// @todo Check for contact vitality via probing
691 $archival_days = Config::get('system', 'archival_days', 32);
693 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
694 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
695 /* Relationship is really truly dead. archive them rather than
696 * delete, though if the owner tries to unarchive them we'll start
697 * the whole process over again.
699 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
700 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
706 * @brief Cancels the archival countdown
708 * @see Contact::markForArchival()
710 * @param array $contact contact to be unmarked for archival
714 public static function unmarkForArchival(array $contact)
716 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
717 $exists = DBA::exists('contact', $condition);
719 // We don't need to update, we never marked this contact for archival
724 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
726 if (!isset($contact['url']) && !empty($contact['id'])) {
727 $fields = ['id', 'url', 'batch'];
728 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
729 if (!DBA::isResult($contact)) {
734 // It's a miracle. Our dead contact has inexplicably come back to life.
735 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
736 DBA::update('contact', $fields, ['id' => $contact['id']]);
737 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
739 if (!empty($contact['batch'])) {
740 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
741 DBA::update('contact', $fields, $condition);
746 * @brief Get contact data for a given profile link
748 * The function looks at several places (contact table and gcontact table) for the contact
749 * It caches its result for the same script execution to prevent duplicate calls
751 * @param string $url The profile link
752 * @param int $uid User id
753 * @param array $default If not data was found take this data as default value
755 * @return array Contact data
756 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
758 public static function getDetailsByURL($url, $uid = -1, array $default = [])
770 if (isset($cache[$url][$uid])) {
771 return $cache[$url][$uid];
774 $ssl_url = str_replace('http://', 'https://', $url);
776 // Fetch contact data from the contact table for the given user
777 $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`,
778 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
779 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
780 $r = DBA::toArray($s);
782 // Fetch contact data from the contact table for the given user, checking with the alias
783 if (!DBA::isResult($r)) {
784 $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`,
785 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
786 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
787 $r = DBA::toArray($s);
790 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
791 if (!DBA::isResult($r)) {
792 $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`,
793 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
794 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
795 $r = DBA::toArray($s);
798 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
799 if (!DBA::isResult($r)) {
800 $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`,
801 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
802 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
803 $r = DBA::toArray($s);
806 // Fetch the data from the gcontact table
807 if (!DBA::isResult($r)) {
808 $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`,
809 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
810 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
811 $r = DBA::toArray($s);
814 if (DBA::isResult($r)) {
815 // If there is more than one entry we filter out the connector networks
817 foreach ($r as $id => $result) {
818 if ($result["network"] == Protocol::STATUSNET) {
824 $profile = array_shift($r);
826 // "bd" always contains the upcoming birthday of a contact.
827 // "birthday" might contain the birthday including the year of birth.
828 if ($profile["birthday"] > DBA::NULL_DATE) {
829 $bd_timestamp = strtotime($profile["birthday"]);
830 $month = date("m", $bd_timestamp);
831 $day = date("d", $bd_timestamp);
833 $current_timestamp = time();
834 $current_year = date("Y", $current_timestamp);
835 $current_month = date("m", $current_timestamp);
836 $current_day = date("d", $current_timestamp);
838 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
839 $current = $current_year . "-" . $current_month . "-" . $current_day;
841 if ($profile["bd"] < $current) {
842 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
845 $profile["bd"] = DBA::NULL_DATE;
851 if (empty($profile["photo"]) && isset($default["photo"])) {
852 $profile["photo"] = $default["photo"];
855 if (empty($profile["name"]) && isset($default["name"])) {
856 $profile["name"] = $default["name"];
859 if (empty($profile["network"]) && isset($default["network"])) {
860 $profile["network"] = $default["network"];
863 if (empty($profile["thumb"]) && isset($profile["photo"])) {
864 $profile["thumb"] = $profile["photo"];
867 if (empty($profile["micro"]) && isset($profile["thumb"])) {
868 $profile["micro"] = $profile["thumb"];
871 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
872 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
874 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
877 // Show contact details of Diaspora contacts only if connected
878 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
879 $profile["location"] = "";
880 $profile["about"] = "";
881 $profile["gender"] = "";
882 $profile["birthday"] = DBA::NULL_DATE;
885 $cache[$url][$uid] = $profile;
891 * @brief Get contact data for a given address
893 * The function looks at several places (contact table and gcontact table) for the contact
895 * @param string $addr The profile link
896 * @param int $uid User id
898 * @return array Contact data
899 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
900 * @throws \ImagickException
902 public static function getDetailsByAddr($addr, $uid = -1)
912 // Fetch contact data from the contact table for the given user
913 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
914 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
915 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
919 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
920 if (!DBA::isResult($r)) {
921 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
922 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
923 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
928 // Fetch the data from the gcontact table
929 if (!DBA::isResult($r)) {
930 $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`,
931 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
932 FROM `gcontact` WHERE `addr` = '%s'",
937 if (!DBA::isResult($r)) {
938 $data = Probe::uri($addr);
940 $profile = self::getDetailsByURL($data['url'], $uid);
949 * @brief Returns the data array for the photo menu of a given contact
951 * @param array $contact contact
952 * @param int $uid optional, default 0
954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
955 * @throws \ImagickException
957 public static function photoMenu(array $contact, $uid = 0)
962 $contact_drop_link = '';
969 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
971 $profile_link = self::magicLink($contact['url']);
972 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
977 // Look for our own contact if the uid doesn't match and isn't public
978 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
979 if (DBA::isResult($contact_own)) {
980 return self::photoMenu($contact_own, $uid);
985 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
987 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
989 $profile_link = $contact['url'];
992 if ($profile_link === 'mailbox') {
997 $status_link = $profile_link . '?url=status';
998 $photos_link = $profile_link . '?url=photos';
999 $profile_link = $profile_link . '?url=profile';
1002 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1003 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1006 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1007 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1010 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1012 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1014 if (!$contact['self']) {
1015 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1020 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1022 if (empty($contact['uid'])) {
1023 $connlnk = 'follow/?url=' . $contact['url'];
1025 'profile' => [L10n::t('View Profile'), $profile_link, true],
1026 'network' => [L10n::t('Network Posts'), $posts_link, false],
1027 'edit' => [L10n::t('View Contact'), $contact_url, false],
1028 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1032 'status' => [L10n::t('View Status'), $status_link, true],
1033 'profile' => [L10n::t('View Profile'), $profile_link, true],
1034 'photos' => [L10n::t('View Photos'), $photos_link, true],
1035 'network' => [L10n::t('Network Posts'), $posts_link, false],
1036 'edit' => [L10n::t('View Contact'), $contact_url, false],
1037 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1038 'pm' => [L10n::t('Send PM'), $pm_url, false],
1039 'poke' => [L10n::t('Poke'), $poke_link, false],
1043 $args = ['contact' => $contact, 'menu' => &$menu];
1045 Hook::callAll('contact_photo_menu', $args);
1047 $menucondensed = [];
1049 foreach ($menu as $menuname => $menuitem) {
1050 if ($menuitem[1] != '') {
1051 $menucondensed[$menuname] = $menuitem;
1055 return $menucondensed;
1059 * @brief Returns ungrouped contact count or list for user
1061 * Returns either the total number of ungrouped contacts for the given user
1062 * id or a paginated list of ungrouped contacts.
1064 * @param int $uid uid
1066 * @throws \Exception
1068 public static function getUngroupedList($uid)
1078 SELECT DISTINCT(`contact-id`)
1080 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1081 WHERE `group`.`uid` = %d
1082 )", intval($uid), intval($uid));
1086 * @brief Fetch the contact id for a given URL and user
1088 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1089 * `addr` or `alias`.
1091 * If there's no record and we aren't looking for a public contact, we quit.
1092 * If there's one, we check that it isn't time to update the picture else we
1093 * directly return the found contact id.
1095 * Second, we probe the provided $url whether it's http://server.tld/profile or
1096 * nick@server.tld. We quit if we can't get any info back.
1098 * Third, we create the contact record if it doesn't exist
1100 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1101 * if there's any updates
1103 * @param string $url Contact URL
1104 * @param integer $uid The user id for the contact (0 = public contact)
1105 * @param boolean $no_update Don't update the contact
1106 * @param array $default Default value for creating the contact when every else fails
1107 * @param boolean $in_loop Internally used variable to prevent an endless loop
1109 * @return integer Contact ID
1110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1111 * @throws \ImagickException
1113 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1115 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1123 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1124 // We first try the nurl (http://server.tld/nick), most common case
1125 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1127 // Then the addr (nick@server.tld)
1128 if (!DBA::isResult($contact)) {
1129 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1132 // Then the alias (which could be anything)
1133 if (!DBA::isResult($contact)) {
1134 // The link could be provided as http although we stored it as https
1135 $ssl_url = str_replace('http://', 'https://', $url);
1136 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1137 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1140 if (DBA::isResult($contact)) {
1141 $contact_id = $contact["id"];
1143 // Update the contact every 7 days
1144 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1146 // We force the update if the avatar is empty
1147 if (empty($contact['avatar'])) {
1148 $update_contact = true;
1150 if (!$update_contact || $no_update) {
1153 } elseif ($uid != 0) {
1154 // Non-existing user-specific contact, exiting
1158 // When we don't want to update, we look if some of our users already know this contact
1160 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1161 'photo', 'keywords', 'location', 'about', 'network',
1162 'priority', 'batch', 'request', 'confirm', 'poco'];
1163 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1165 if (DBA::isResult($data)) {
1166 // For security reasons we don't fetch key data from our users
1167 $data["pubkey"] = '';
1174 $data = Probe::uri($url, "", $uid);
1176 // Ensure that there is a gserver entry
1177 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1178 PortableContact::checkServer($data['baseurl']);
1182 // Last try in gcontact for unsupported networks
1183 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1188 // Get data from the gcontact table
1189 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1190 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1191 if (!DBA::isResult($contact)) {
1192 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1195 if (!DBA::isResult($contact)) {
1196 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1197 'photo', 'keywords', 'location', 'about', 'network',
1198 'priority', 'batch', 'request', 'confirm', 'poco'];
1199 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1202 // The link could be provided as http although we stored it as https
1203 $ssl_url = str_replace('http://', 'https://', $url);
1205 if (!DBA::isResult($contact)) {
1206 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1207 $contact = DBA::selectFirst('contact', $fields, $condition);
1210 if (!DBA::isResult($contact)) {
1211 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1212 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1213 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1214 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1217 if (!empty($default)) {
1218 $contact = $default;
1221 if (!DBA::isResult($contact)) {
1224 $data = array_merge($data, $contact);
1228 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1229 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1235 'created' => DateTimeFormat::utcNow(),
1236 'url' => $data["url"],
1237 'nurl' => Strings::normaliseLink($data["url"]),
1238 'addr' => $data["addr"],
1239 'alias' => $data["alias"],
1240 'notify' => $data["notify"],
1241 'poll' => $data["poll"],
1242 'name' => $data["name"],
1243 'nick' => $data["nick"],
1244 'photo' => $data["photo"],
1245 'keywords' => $data["keywords"],
1246 'location' => $data["location"],
1247 'about' => $data["about"],
1248 'network' => $data["network"],
1249 'pubkey' => $data["pubkey"],
1250 'rel' => self::SHARING,
1251 'priority' => $data["priority"],
1252 'batch' => $data["batch"],
1253 'request' => $data["request"],
1254 'confirm' => $data["confirm"],
1255 'poco' => $data["poco"],
1256 'name-date' => DateTimeFormat::utcNow(),
1257 'uri-date' => DateTimeFormat::utcNow(),
1258 'avatar-date' => DateTimeFormat::utcNow(),
1264 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1266 DBA::update('contact', $fields, $condition, true);
1268 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1269 $contacts = DBA::toArray($s);
1270 if (!DBA::isResult($contacts)) {
1274 $contact_id = $contacts[0]["id"];
1276 // Update the newly created contact from data in the gcontact table
1277 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1278 if (DBA::isResult($gcontact)) {
1279 // Only use the information when the probing hadn't fetched these values
1280 if ($data['keywords'] != '') {
1281 unset($gcontact['keywords']);
1283 if ($data['location'] != '') {
1284 unset($gcontact['location']);
1286 if ($data['about'] != '') {
1287 unset($gcontact['about']);
1289 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1292 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1293 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1294 Strings::normaliseLink($data["url"]), 0, $contact_id];
1295 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1296 DBA::delete('contact', $condition);
1300 self::updateAvatar($data["photo"], $uid, $contact_id);
1302 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1303 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1305 // This condition should always be true
1306 if (!DBA::isResult($contact)) {
1310 $updated = ['addr' => $data['addr'],
1311 'alias' => $data['alias'],
1312 'url' => $data['url'],
1313 'nurl' => Strings::normaliseLink($data['url']),
1314 'name' => $data['name'],
1315 'nick' => $data['nick']];
1317 if ($data['keywords'] != '') {
1318 $updated['keywords'] = $data['keywords'];
1320 if ($data['location'] != '') {
1321 $updated['location'] = $data['location'];
1324 // Update the technical stuff as well - if filled
1325 if ($data['notify'] != '') {
1326 $updated['notify'] = $data['notify'];
1328 if ($data['poll'] != '') {
1329 $updated['poll'] = $data['poll'];
1331 if ($data['batch'] != '') {
1332 $updated['batch'] = $data['batch'];
1334 if ($data['request'] != '') {
1335 $updated['request'] = $data['request'];
1337 if ($data['confirm'] != '') {
1338 $updated['confirm'] = $data['confirm'];
1340 if ($data['poco'] != '') {
1341 $updated['poco'] = $data['poco'];
1344 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1345 if (empty($contact['pubkey'])) {
1346 $updated['pubkey'] = $data['pubkey'];
1349 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1350 $updated['uri-date'] = DateTimeFormat::utcNow();
1352 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1353 $updated['name-date'] = DateTimeFormat::utcNow();
1356 $updated['avatar-date'] = DateTimeFormat::utcNow();
1358 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1364 * @brief Checks if the contact is blocked
1366 * @param int $cid contact id
1368 * @return boolean Is the contact blocked?
1369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1371 public static function isBlocked($cid)
1377 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1378 if (!DBA::isResult($blocked)) {
1382 if (Network::isUrlBlocked($blocked['url'])) {
1386 return (bool) $blocked['blocked'];
1390 * @brief Checks if the contact is hidden
1392 * @param int $cid contact id
1394 * @return boolean Is the contact hidden?
1395 * @throws \Exception
1397 public static function isHidden($cid)
1403 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1404 if (!DBA::isResult($hidden)) {
1407 return (bool) $hidden['hidden'];
1411 * @brief Returns posts from a given contact url
1413 * @param string $contact_url Contact URL
1415 * @param bool $thread_mode
1416 * @param int $update
1417 * @return string posts in HTML
1418 * @throws \Exception
1420 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1422 $a = self::getApp();
1424 $cid = self::getIdForURL($contact_url);
1426 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1427 if (!DBA::isResult($contact)) {
1431 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1432 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1434 $sql = "`item`.`uid` = ?";
1437 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1440 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1441 $cid, GRAVITY_PARENT, local_user()];
1443 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1444 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1447 $pager = new Pager($a->query_string);
1449 $params = ['order' => ['created' => true],
1450 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1453 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1455 $items = Item::inArray($r);
1457 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1459 $r = Item::selectForUser(local_user(), [], $condition, $params);
1461 $items = Item::inArray($r);
1463 $o = conversation($a, $items, $pager, 'contact-posts', false);
1467 $o .= $pager->renderMinimal(count($items));
1474 * @brief Returns the account type name
1476 * The function can be called with either the user or the contact array
1478 * @param array $contact contact or user array
1481 public static function getAccountType(array $contact)
1483 // There are several fields that indicate that the contact or user is a forum
1484 // "page-flags" is a field in the user table,
1485 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1486 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1487 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1488 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1489 || (isset($contact['forum']) && intval($contact['forum']))
1490 || (isset($contact['prv']) && intval($contact['prv']))
1491 || (isset($contact['community']) && intval($contact['community']))
1493 $type = self::TYPE_COMMUNITY;
1495 $type = self::TYPE_PERSON;
1498 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1499 if (isset($contact["contact-type"])) {
1500 $type = $contact["contact-type"];
1503 if (isset($contact["account-type"])) {
1504 $type = $contact["account-type"];
1508 case self::TYPE_ORGANISATION:
1509 $account_type = L10n::t("Organisation");
1512 case self::TYPE_NEWS:
1513 $account_type = L10n::t('News');
1516 case self::TYPE_COMMUNITY:
1517 $account_type = L10n::t("Forum");
1525 return $account_type;
1529 * @brief Blocks a contact
1533 * @throws \Exception
1535 public static function block($uid)
1537 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1543 * @brief Unblocks a contact
1547 * @throws \Exception
1549 public static function unblock($uid)
1551 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1557 * @brief Updates the avatar links in a contact only if needed
1559 * @param string $avatar Link to avatar picture
1560 * @param int $uid User id of contact owner
1561 * @param int $cid Contact id
1562 * @param bool $force force picture update
1564 * @return array Returns array of the different avatar sizes
1565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1566 * @throws \ImagickException
1568 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1570 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1571 if (!DBA::isResult($contact)) {
1574 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1577 if (($contact["avatar"] != $avatar) || $force) {
1578 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1583 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1587 // Update the public contact (contact id = 0)
1589 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1590 if (DBA::isResult($pcontact)) {
1591 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1603 * @param integer $id contact id
1604 * @param string $network Optional network we are probing for
1606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1607 * @throws \ImagickException
1609 public static function updateFromProbe($id, $network = '')
1612 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1613 This will reliably kill your communication with Friendica contacts.
1616 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1617 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1618 if (!DBA::isResult($contact)) {
1622 $ret = Probe::uri($contact["url"], $network);
1624 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1625 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, $network])) {
1631 // make sure to not overwrite existing values with blank entries
1632 foreach ($ret as $key => $val) {
1633 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1634 $ret[$key] = $contact[$key];
1637 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1648 'url' => $ret['url'],
1649 'nurl' => Strings::normaliseLink($ret['url']),
1650 'network' => $ret['network'],
1651 'addr' => $ret['addr'],
1652 'alias' => $ret['alias'],
1653 'batch' => $ret['batch'],
1654 'notify' => $ret['notify'],
1655 'poll' => $ret['poll'],
1656 'poco' => $ret['poco']
1661 // Update the corresponding gcontact entry
1662 PortableContact::lastUpdated($ret["url"]);
1668 * Takes a $uid and a url/handle and adds a new contact
1669 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1670 * dfrn_request page.
1672 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1675 * $return['success'] boolean true if successful
1676 * $return['message'] error text if success is false.
1678 * @brief Takes a $uid and a url/handle and adds a new contact
1680 * @param string $url
1681 * @param bool $interactive
1682 * @param string $network
1684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1685 * @throws \ImagickException
1687 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1689 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1693 // remove ajax junk, e.g. Twitter
1694 $url = str_replace('/#!/', '/', $url);
1696 if (!Network::isUrlAllowed($url)) {
1697 $result['message'] = L10n::t('Disallowed profile URL.');
1701 if (Network::isUrlBlocked($url)) {
1702 $result['message'] = L10n::t('Blocked domain');
1707 $result['message'] = L10n::t('Connect URL missing.');
1711 $arr = ['url' => $url, 'contact' => []];
1713 Hook::callAll('follow', $arr);
1716 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1720 if (!empty($arr['contact']['name'])) {
1721 $ret = $arr['contact'];
1723 $ret = Probe::uri($url, $network, $uid, false);
1726 if (($network != '') && ($ret['network'] != $network)) {
1727 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1731 // check if we already have a contact
1732 // the poll url is more reliable than the profile url, as we may have
1733 // indirect links or webfinger links
1735 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1736 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1737 if (!DBA::isResult($contact)) {
1738 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1739 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1742 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1744 if (strlen($a->getURLPath())) {
1745 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1747 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1750 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1754 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1755 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1756 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1760 // This extra param just confuses things, remove it
1761 if ($ret['network'] === Protocol::DIASPORA) {
1762 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1765 // do we have enough information?
1766 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1767 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1768 if (empty($ret['poll'])) {
1769 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1771 if (empty($ret['name'])) {
1772 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1774 if (empty($ret['url'])) {
1775 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1777 if (strpos($url, '@') !== false) {
1778 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1779 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1784 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1785 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1786 $ret['notify'] = '';
1789 if (!$ret['notify']) {
1790 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1793 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1795 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1797 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1799 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1801 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1805 if (DBA::isResult($contact)) {
1807 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1809 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1810 DBA::update('contact', $fields, ['id' => $contact['id']]);
1812 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1814 // create contact record
1815 DBA::insert('contact', [
1817 'created' => DateTimeFormat::utcNow(),
1818 'url' => $ret['url'],
1819 'nurl' => Strings::normaliseLink($ret['url']),
1820 'addr' => $ret['addr'],
1821 'alias' => $ret['alias'],
1822 'batch' => $ret['batch'],
1823 'notify' => $ret['notify'],
1824 'poll' => $ret['poll'],
1825 'poco' => $ret['poco'],
1826 'name' => $ret['name'],
1827 'nick' => $ret['nick'],
1828 'network' => $ret['network'],
1829 'pubkey' => $ret['pubkey'],
1830 'rel' => $new_relation,
1831 'priority'=> $ret['priority'],
1832 'writable'=> $writeable,
1833 'hidden' => $hidden,
1836 'pending' => $pending,
1841 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1842 if (!DBA::isResult($contact)) {
1843 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1847 $contact_id = $contact['id'];
1848 $result['cid'] = $contact_id;
1850 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1852 // Update the avatar
1853 self::updateAvatar($ret['photo'], $uid, $contact_id);
1855 // pull feed and consume it, which should subscribe to the hub.
1857 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1859 $owner = User::getOwnerDataById($uid);
1861 if (DBA::isResult($owner)) {
1862 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1863 // create a follow slap
1865 $item['verb'] = ACTIVITY_FOLLOW;
1866 $item['follow'] = $contact["url"];
1868 $item['title'] = '';
1871 $item['attach'] = '';
1873 $slap = OStatus::salmon($item, $owner);
1875 if (!empty($contact['notify'])) {
1876 Salmon::slapper($owner, $contact['notify'], $slap);
1878 } elseif ($contact['network'] == Protocol::DIASPORA) {
1879 $ret = Diaspora::sendShare($a->user, $contact);
1880 Logger::log('share returns: ' . $ret);
1881 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1882 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1883 if (empty($activity_id)) {
1884 // This really should never happen
1888 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1889 Logger::log('Follow returns: ' . $ret);
1893 $result['success'] = true;
1898 * @brief Updated contact's SSL policy
1900 * @param array $contact Contact array
1901 * @param string $new_policy New policy, valid: self,full
1903 * @return array Contact array with updated values
1904 * @throws \Exception
1906 public static function updateSslPolicy(array $contact, $new_policy)
1908 $ssl_changed = false;
1909 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1910 $ssl_changed = true;
1911 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1912 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1913 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1914 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1915 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1916 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1919 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1920 $ssl_changed = true;
1921 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1922 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1923 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1924 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1925 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1926 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1930 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1931 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1932 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1933 DBA::update('contact', $fields, ['id' => $contact['id']]);
1939 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1940 // Should always be set
1941 if (empty($datarray['author-id'])) {
1945 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1946 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1947 if (!DBA::isResult($pub_contact)) {
1948 // Should never happen
1952 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1953 $name = $pub_contact['name'];
1954 $photo = $pub_contact['photo'];
1955 $nick = $pub_contact['nick'];
1956 $network = $pub_contact['network'];
1958 if (is_array($contact)) {
1959 if (($contact['rel'] == self::SHARING)
1960 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1961 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1962 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1965 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1966 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1969 // send email notification to owner?
1971 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1972 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1975 // create contact record
1976 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1977 `blocked`, `readonly`, `pending`, `writable`)
1978 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1979 intval($importer['uid']),
1980 DBA::escape(DateTimeFormat::utcNow()),
1982 DBA::escape(Strings::normaliseLink($url)),
1985 DBA::escape($photo),
1986 DBA::escape($network),
1987 intval(self::FOLLOWER)
1991 'id' => DBA::lastInsertId(),
1992 'network' => $network,
1998 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2000 /// @TODO Encapsulate this into a function/method
2001 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2002 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2003 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2004 // create notification
2005 $hash = Strings::getRandomHex();
2007 if (is_array($contact_record)) {
2008 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2009 'blocked' => false, 'knowyou' => false,
2010 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2013 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2015 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2016 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2019 'type' => NOTIFY_INTRO,
2020 'notify_flags' => $user['notify-flags'],
2021 'language' => $user['language'],
2022 'to_name' => $user['username'],
2023 'to_email' => $user['email'],
2024 'uid' => $user['uid'],
2025 'link' => System::baseUrl() . '/notifications/intro',
2026 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2027 'source_link' => $contact_record['url'],
2028 'source_photo' => $contact_record['photo'],
2029 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2034 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2035 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2036 DBA::update('contact', ['pending' => false], $condition);
2038 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2040 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2041 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2047 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2049 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2050 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2052 Contact::remove($contact['id']);
2056 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2058 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2059 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2061 Contact::remove($contact['id']);
2066 * @brief Create a birthday event.
2068 * Update the year and the birthday.
2070 public static function updateBirthdays()
2074 AND `bd` > "0001-01-01"
2075 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2076 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2077 AND NOT `contact`.`pending`
2078 AND NOT `contact`.`hidden`
2079 AND NOT `contact`.`blocked`
2080 AND NOT `contact`.`archive`
2081 AND NOT `contact`.`deleted`',
2086 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2088 while ($contact = DBA::fetch($contacts)) {
2089 Logger::log('update_contact_birthday: ' . $contact['bd']);
2091 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2093 if (Event::createBirthday($contact, $nextbd)) {
2097 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2098 ['id' => $contact['id']]
2105 * Remove the unavailable contact ids from the provided list
2107 * @param array $contact_ids Contact id list
2108 * @throws \Exception
2110 public static function pruneUnavailable(array &$contact_ids)
2112 if (empty($contact_ids)) {
2116 $str = DBA::escape(implode(',', $contact_ids));
2118 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2121 while($contact = DBA::fetch($stmt)) {
2122 $return[] = $contact['id'];
2127 $contact_ids = $return;
2131 * @brief Returns a magic link to authenticate remote visitors
2133 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2135 * @param string $contact_url The address of the target contact profile
2136 * @param string $url An url that we will be redirected to after the authentication
2138 * @return string with "redir" link
2139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2140 * @throws \ImagickException
2142 public static function magicLink($contact_url, $url = '')
2144 if (!local_user() && !remote_user()) {
2145 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2148 $cid = self::getIdForURL($contact_url, 0, true);
2150 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2153 return self::magicLinkbyId($cid, $url);
2157 * @brief Returns a magic link to authenticate remote visitors
2159 * @param integer $cid The contact id of the target contact profile
2160 * @param string $url An url that we will be redirected to after the authentication
2162 * @return string with "redir" link
2163 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2164 * @throws \ImagickException
2166 public static function magicLinkbyId($cid, $url = '')
2168 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2170 return self::magicLinkbyContact($contact, $url);
2174 * @brief Returns a magic link to authenticate remote visitors
2176 * @param array $contact The contact array with "uid", "network" and "url"
2177 * @param string $url An url that we will be redirected to after the authentication
2179 * @return string with "redir" link
2180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2181 * @throws \ImagickException
2183 public static function magicLinkbyContact($contact, $url = '')
2185 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2186 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2189 // Only redirections to the same host do make sense
2190 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2194 if ($contact['uid'] != 0) {
2195 return self::magicLink($contact['url'], $url);
2198 $redirect = 'redir/' . $contact['id'];
2201 $redirect .= '?url=' . $url;