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 if ($fields['name'] != $self['name']) {
604 $fields['name-date'] = DateTimeFormat::utcNow();
606 $fields['updated'] = DateTimeFormat::utcNow();
607 DBA::update('contact', $fields, ['id' => $self['id']]);
609 // Update the public contact as well
610 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
612 // Update the profile
613 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
614 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
615 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
620 * @brief Marks a contact for removal
622 * @param int $id contact id
624 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
626 public static function remove($id)
628 // We want just to make sure that we don't delete our "self" contact
629 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
630 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
634 // Archive the contact
635 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
637 // Delete it in the background
638 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
642 * @brief Sends an unfriend message. Does not remove the contact
644 * @param array $user User unfriending
645 * @param array $contact Contact unfriended
646 * @param boolean $dissolve Remove the contact on the remote side
648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
649 * @throws \ImagickException
651 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
653 if (empty($contact['network'])) {
656 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
657 DFRN::deliver($user, $contact, 'placeholder', true);
658 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
659 // create an unfollow slap
661 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
662 $item['follow'] = $contact["url"];
667 $item['attach'] = '';
668 $slap = OStatus::salmon($item, $user);
670 if (!empty($contact['notify'])) {
671 Salmon::slapper($user, $contact['notify'], $slap);
673 } elseif ($contact['network'] == Protocol::DIASPORA) {
674 Diaspora::sendUnshare($user, $contact);
675 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
676 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
679 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
685 * @brief Marks a contact for archival after a communication issue delay
687 * Contact has refused to recognise us as a friend. We will start a countdown.
688 * If they still don't recognise us in 32 days, the relationship is over,
689 * and we won't waste any more time trying to communicate with them.
690 * This provides for the possibility that their database is temporarily messed
691 * up or some other transient event and that there's a possibility we could recover from it.
693 * @param array $contact contact to mark for archival
695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
697 public static function markForArchival(array $contact)
699 if (!isset($contact['url']) && !empty($contact['id'])) {
700 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
701 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
702 if (!DBA::isResult($contact)) {
705 } elseif (!isset($contact['url'])) {
706 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
709 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
711 // Contact already archived or "self" contact? => nothing to do
712 if ($contact['archive'] || $contact['self']) {
716 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
717 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
718 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
721 * We really should send a notification to the owner after 2-3 weeks
722 * so they won't be surprised when the contact vanishes and can take
723 * remedial action if this was a serious mistake or glitch
726 /// @todo Check for contact vitality via probing
727 $archival_days = Config::get('system', 'archival_days', 32);
729 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
730 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
731 /* Relationship is really truly dead. archive them rather than
732 * delete, though if the owner tries to unarchive them we'll start
733 * the whole process over again.
735 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
736 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
742 * @brief Cancels the archival countdown
744 * @see Contact::markForArchival()
746 * @param array $contact contact to be unmarked for archival
750 public static function unmarkForArchival(array $contact)
752 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
753 $exists = DBA::exists('contact', $condition);
755 // We don't need to update, we never marked this contact for archival
760 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
762 if (!isset($contact['url']) && !empty($contact['id'])) {
763 $fields = ['id', 'url', 'batch'];
764 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
765 if (!DBA::isResult($contact)) {
770 // It's a miracle. Our dead contact has inexplicably come back to life.
771 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
772 DBA::update('contact', $fields, ['id' => $contact['id']]);
773 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
775 if (!empty($contact['batch'])) {
776 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
777 DBA::update('contact', $fields, $condition);
782 * @brief Get contact data for a given profile link
784 * The function looks at several places (contact table and gcontact table) for the contact
785 * It caches its result for the same script execution to prevent duplicate calls
787 * @param string $url The profile link
788 * @param int $uid User id
789 * @param array $default If not data was found take this data as default value
791 * @return array Contact data
792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
794 public static function getDetailsByURL($url, $uid = -1, array $default = [])
806 if (isset($cache[$url][$uid])) {
807 return $cache[$url][$uid];
810 $ssl_url = str_replace('http://', 'https://', $url);
812 // Fetch contact data from the contact table for the given user
813 $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`,
814 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
815 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
816 $r = DBA::toArray($s);
818 // Fetch contact data from the contact table for the given user, checking with the alias
819 if (!DBA::isResult($r)) {
820 $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`,
821 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
822 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
823 $r = DBA::toArray($s);
826 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
827 if (!DBA::isResult($r)) {
828 $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`,
829 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
830 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
831 $r = DBA::toArray($s);
834 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
835 if (!DBA::isResult($r)) {
836 $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`,
837 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
838 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
839 $r = DBA::toArray($s);
842 // Fetch the data from the gcontact table
843 if (!DBA::isResult($r)) {
844 $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`,
845 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
846 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
847 $r = DBA::toArray($s);
850 if (DBA::isResult($r)) {
851 // If there is more than one entry we filter out the connector networks
853 foreach ($r as $id => $result) {
854 if ($result["network"] == Protocol::STATUSNET) {
860 $profile = array_shift($r);
862 // "bd" always contains the upcoming birthday of a contact.
863 // "birthday" might contain the birthday including the year of birth.
864 if ($profile["birthday"] > DBA::NULL_DATE) {
865 $bd_timestamp = strtotime($profile["birthday"]);
866 $month = date("m", $bd_timestamp);
867 $day = date("d", $bd_timestamp);
869 $current_timestamp = time();
870 $current_year = date("Y", $current_timestamp);
871 $current_month = date("m", $current_timestamp);
872 $current_day = date("d", $current_timestamp);
874 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
875 $current = $current_year . "-" . $current_month . "-" . $current_day;
877 if ($profile["bd"] < $current) {
878 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
881 $profile["bd"] = DBA::NULL_DATE;
887 if (empty($profile["photo"]) && isset($default["photo"])) {
888 $profile["photo"] = $default["photo"];
891 if (empty($profile["name"]) && isset($default["name"])) {
892 $profile["name"] = $default["name"];
895 if (empty($profile["network"]) && isset($default["network"])) {
896 $profile["network"] = $default["network"];
899 if (empty($profile["thumb"]) && isset($profile["photo"])) {
900 $profile["thumb"] = $profile["photo"];
903 if (empty($profile["micro"]) && isset($profile["thumb"])) {
904 $profile["micro"] = $profile["thumb"];
907 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
908 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
910 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
913 // Show contact details of Diaspora contacts only if connected
914 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
915 $profile["location"] = "";
916 $profile["about"] = "";
917 $profile["gender"] = "";
918 $profile["birthday"] = DBA::NULL_DATE;
921 $cache[$url][$uid] = $profile;
927 * @brief Get contact data for a given address
929 * The function looks at several places (contact table and gcontact table) for the contact
931 * @param string $addr The profile link
932 * @param int $uid User id
934 * @return array Contact data
935 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936 * @throws \ImagickException
938 public static function getDetailsByAddr($addr, $uid = -1)
948 // Fetch contact data from the contact table for the given user
949 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
950 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
951 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
955 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
956 if (!DBA::isResult($r)) {
957 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
958 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
959 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
964 // Fetch the data from the gcontact table
965 if (!DBA::isResult($r)) {
966 $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`,
967 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
968 FROM `gcontact` WHERE `addr` = '%s'",
973 if (!DBA::isResult($r)) {
974 $data = Probe::uri($addr);
976 $profile = self::getDetailsByURL($data['url'], $uid);
985 * @brief Returns the data array for the photo menu of a given contact
987 * @param array $contact contact
988 * @param int $uid optional, default 0
990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
991 * @throws \ImagickException
993 public static function photoMenu(array $contact, $uid = 0)
998 $contact_drop_link = '';
1002 $uid = local_user();
1005 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1007 $profile_link = self::magicLink($contact['url']);
1008 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1013 // Look for our own contact if the uid doesn't match and isn't public
1014 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1015 if (DBA::isResult($contact_own)) {
1016 return self::photoMenu($contact_own, $uid);
1021 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1023 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1025 $profile_link = $contact['url'];
1028 if ($profile_link === 'mailbox') {
1033 $status_link = $profile_link . '?tab=status';
1034 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1035 $profile_link = $profile_link . '?tab=profile';
1038 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1039 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1042 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1043 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1046 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1048 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1050 if (!$contact['self']) {
1051 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1056 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1058 if (empty($contact['uid'])) {
1059 $connlnk = 'follow/?url=' . $contact['url'];
1061 'profile' => [L10n::t('View Profile'), $profile_link, true],
1062 'network' => [L10n::t('Network Posts'), $posts_link, false],
1063 'edit' => [L10n::t('View Contact'), $contact_url, false],
1064 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1068 'status' => [L10n::t('View Status'), $status_link, true],
1069 'profile' => [L10n::t('View Profile'), $profile_link, true],
1070 'photos' => [L10n::t('View Photos'), $photos_link, true],
1071 'network' => [L10n::t('Network Posts'), $posts_link, false],
1072 'edit' => [L10n::t('View Contact'), $contact_url, false],
1073 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1074 'pm' => [L10n::t('Send PM'), $pm_url, false],
1075 'poke' => [L10n::t('Poke'), $poke_link, false],
1079 $args = ['contact' => $contact, 'menu' => &$menu];
1081 Hook::callAll('contact_photo_menu', $args);
1083 $menucondensed = [];
1085 foreach ($menu as $menuname => $menuitem) {
1086 if ($menuitem[1] != '') {
1087 $menucondensed[$menuname] = $menuitem;
1091 return $menucondensed;
1095 * @brief Returns ungrouped contact count or list for user
1097 * Returns either the total number of ungrouped contacts for the given user
1098 * id or a paginated list of ungrouped contacts.
1100 * @param int $uid uid
1102 * @throws \Exception
1104 public static function getUngroupedList($uid)
1114 SELECT DISTINCT(`contact-id`)
1116 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1117 WHERE `group`.`uid` = %d
1118 )", intval($uid), intval($uid));
1122 * Have a look at all contact tables for a given profile url.
1123 * This function works as a replacement for probing the contact.
1125 * @param string $url Contact URL
1126 * @param integer $cid Contact ID
1128 * @return array Contact array in the "probe" structure
1130 private static function getProbeDataFromDatabase($url, $cid)
1132 // The link could be provided as http although we stored it as https
1133 $ssl_url = str_replace('http://', 'https://', $url);
1135 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1136 'photo', 'keywords', 'location', 'about', 'network',
1137 'priority', 'batch', 'request', 'confirm', 'poco'];
1140 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1141 if (DBA::isResult($data)) {
1146 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1148 if (!DBA::isResult($data)) {
1149 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1150 $data = DBA::selectFirst('contact', $fields, $condition);
1153 if (DBA::isResult($data)) {
1154 // For security reasons we don't fetch key data from our users
1155 $data["pubkey"] = '';
1159 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1160 'photo', 'keywords', 'location', 'about', 'network'];
1161 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1163 if (!DBA::isResult($data)) {
1164 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1165 $data = DBA::selectFirst('contact', $fields, $condition);
1168 if (DBA::isResult($data)) {
1169 $data["pubkey"] = '';
1171 $data["priority"] = 0;
1172 $data["batch"] = '';
1173 $data["request"] = '';
1174 $data["confirm"] = '';
1179 $data = ActivityPub::probeProfile($url, false);
1180 if (!empty($data)) {
1184 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1185 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1186 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1188 if (!DBA::isResult($data)) {
1189 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1190 $data = DBA::selectFirst('contact', $fields, $condition);
1193 if (DBA::isResult($data)) {
1194 $data["pubkey"] = '';
1195 $data["keywords"] = '';
1196 $data["location"] = '';
1197 $data["about"] = '';
1206 * @brief Fetch the contact id for a given URL and user
1208 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1209 * `addr` or `alias`.
1211 * If there's no record and we aren't looking for a public contact, we quit.
1212 * If there's one, we check that it isn't time to update the picture else we
1213 * directly return the found contact id.
1215 * Second, we probe the provided $url whether it's http://server.tld/profile or
1216 * nick@server.tld. We quit if we can't get any info back.
1218 * Third, we create the contact record if it doesn't exist
1220 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1221 * if there's any updates
1223 * @param string $url Contact URL
1224 * @param integer $uid The user id for the contact (0 = public contact)
1225 * @param boolean $no_update Don't update the contact
1226 * @param array $default Default value for creating the contact when every else fails
1227 * @param boolean $in_loop Internally used variable to prevent an endless loop
1229 * @return integer Contact ID
1230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1231 * @throws \ImagickException
1233 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1235 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1243 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1244 // We first try the nurl (http://server.tld/nick), most common case
1245 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1247 // Then the addr (nick@server.tld)
1248 if (!DBA::isResult($contact)) {
1249 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1252 // Then the alias (which could be anything)
1253 if (!DBA::isResult($contact)) {
1254 // The link could be provided as http although we stored it as https
1255 $ssl_url = str_replace('http://', 'https://', $url);
1256 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1257 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1260 if (DBA::isResult($contact)) {
1261 $contact_id = $contact["id"];
1263 // Update the contact every 7 days
1264 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1266 // We force the update if the avatar is empty
1267 if (empty($contact['avatar'])) {
1268 $update_contact = true;
1271 // Update the contact in the background if needed but it is called by the frontend
1272 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1273 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1276 if (!$update_contact || $no_update) {
1279 } elseif ($uid != 0) {
1280 // Non-existing user-specific contact, exiting
1284 // When we don't want to update, we look if we know this contact in any way
1285 if ($no_update && empty($default)) {
1286 $data = self::getProbeDataFromDatabase($url, $contact_id);
1287 $background_update = true;
1290 $background_update = false;
1294 $data = Probe::uri($url, "", $uid);
1296 // Ensure that there is a gserver entry
1297 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1298 PortableContact::checkServer($data['baseurl']);
1302 // Last try in gcontact for unsupported networks
1303 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1308 $contact = array_merge(self::getProbeDataFromDatabase($url, $contact_id), $default);
1309 if (empty($contact)) {
1313 $data = array_merge($data, $contact);
1320 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1321 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1327 'created' => DateTimeFormat::utcNow(),
1328 'url' => $data['url'],
1329 'nurl' => Strings::normaliseLink($data['url']),
1330 'addr' => defaults($data, 'addr', ''),
1331 'alias' => defaults($data, 'alias', ''),
1332 'notify' => defaults($data, 'notify', ''),
1333 'poll' => defaults($data, 'poll', ''),
1334 'name' => defaults($data, 'name', ''),
1335 'nick' => defaults($data, 'nick', ''),
1336 'photo' => defaults($data, 'photo', ''),
1337 'keywords' => defaults($data, 'keywords', ''),
1338 'location' => defaults($data, 'location', ''),
1339 'about' => defaults($data, 'about', ''),
1340 'network' => $data['network'],
1341 'pubkey' => defaults($data, 'pubkey', ''),
1342 'rel' => self::SHARING,
1343 'priority' => defaults($data, 'priority', 0),
1344 'batch' => defaults($data, 'batch', ''),
1345 'request' => defaults($data, 'request', ''),
1346 'confirm' => defaults($data, 'confirm', ''),
1347 'poco' => defaults($data, 'poco', ''),
1348 'name-date' => DateTimeFormat::utcNow(),
1349 'uri-date' => DateTimeFormat::utcNow(),
1350 'avatar-date' => DateTimeFormat::utcNow(),
1356 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1358 DBA::update('contact', $fields, $condition, true);
1360 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1361 $contacts = DBA::toArray($s);
1362 if (!DBA::isResult($contacts)) {
1366 $contact_id = $contacts[0]["id"];
1368 // Update in the background when we fetched the data solely from the database
1369 if ($background_update) {
1370 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1373 // Update the newly created contact from data in the gcontact table
1374 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1375 if (DBA::isResult($gcontact)) {
1376 // Only use the information when the probing hadn't fetched these values
1377 if (!empty($data['keywords'])) {
1378 unset($gcontact['keywords']);
1380 if (!empty($data['location'])) {
1381 unset($gcontact['location']);
1383 if (!empty($data['about'])) {
1384 unset($gcontact['about']);
1386 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1389 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1390 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1391 Strings::normaliseLink($data["url"]), 0, $contact_id];
1392 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1393 DBA::delete('contact', $condition);
1397 if (!empty($data['photo'])) {
1398 self::updateAvatar($data['photo'], $uid, $contact_id);
1401 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1402 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1404 // This condition should always be true
1405 if (!DBA::isResult($contact)) {
1409 $updated = ['addr' => $data['addr'],
1410 'alias' => defaults($data, 'alias', ''),
1411 'url' => $data['url'],
1412 'nurl' => Strings::normaliseLink($data['url']),
1413 'name' => $data['name'],
1414 'nick' => $data['nick']];
1416 if (!empty($data['keywords'])) {
1417 $updated['keywords'] = $data['keywords'];
1419 if (!empty($data['location'])) {
1420 $updated['location'] = $data['location'];
1423 // Update the technical stuff as well - if filled
1424 if (!empty($data['notify'])) {
1425 $updated['notify'] = $data['notify'];
1427 if (!empty($data['poll'])) {
1428 $updated['poll'] = $data['poll'];
1430 if (!empty($data['batch'])) {
1431 $updated['batch'] = $data['batch'];
1433 if (!empty($data['request'])) {
1434 $updated['request'] = $data['request'];
1436 if (!empty($data['confirm'])) {
1437 $updated['confirm'] = $data['confirm'];
1439 if (!empty($data['poco'])) {
1440 $updated['poco'] = $data['poco'];
1443 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1444 if (empty($contact['pubkey'])) {
1445 $updated['pubkey'] = $data['pubkey'];
1448 if (($data['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1449 $updated['uri-date'] = DateTimeFormat::utcNow();
1451 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1452 $updated['name-date'] = DateTimeFormat::utcNow();
1455 $updated['updated'] = DateTimeFormat::utcNow();
1457 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1463 * @brief Checks if the contact is blocked
1465 * @param int $cid contact id
1467 * @return boolean Is the contact blocked?
1468 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1470 public static function isBlocked($cid)
1476 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1477 if (!DBA::isResult($blocked)) {
1481 if (Network::isUrlBlocked($blocked['url'])) {
1485 return (bool) $blocked['blocked'];
1489 * @brief Checks if the contact is hidden
1491 * @param int $cid contact id
1493 * @return boolean Is the contact hidden?
1494 * @throws \Exception
1496 public static function isHidden($cid)
1502 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1503 if (!DBA::isResult($hidden)) {
1506 return (bool) $hidden['hidden'];
1510 * @brief Returns posts from a given contact url
1512 * @param string $contact_url Contact URL
1514 * @param bool $thread_mode
1515 * @param int $update
1516 * @return string posts in HTML
1517 * @throws \Exception
1519 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1521 $a = self::getApp();
1523 $cid = self::getIdForURL($contact_url);
1525 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1526 if (!DBA::isResult($contact)) {
1530 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1531 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1533 $sql = "`item`.`uid` = ?";
1536 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1539 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1540 $cid, GRAVITY_PARENT, local_user()];
1542 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1543 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1546 $pager = new Pager($a->query_string);
1548 $params = ['order' => ['created' => true],
1549 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1552 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1554 $items = Item::inArray($r);
1556 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1558 $r = Item::selectForUser(local_user(), [], $condition, $params);
1560 $items = Item::inArray($r);
1562 $o = conversation($a, $items, $pager, 'contact-posts', false);
1566 $o .= $pager->renderMinimal(count($items));
1573 * @brief Returns the account type name
1575 * The function can be called with either the user or the contact array
1577 * @param array $contact contact or user array
1580 public static function getAccountType(array $contact)
1582 // There are several fields that indicate that the contact or user is a forum
1583 // "page-flags" is a field in the user table,
1584 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1585 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1586 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1587 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1588 || (isset($contact['forum']) && intval($contact['forum']))
1589 || (isset($contact['prv']) && intval($contact['prv']))
1590 || (isset($contact['community']) && intval($contact['community']))
1592 $type = self::TYPE_COMMUNITY;
1594 $type = self::TYPE_PERSON;
1597 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1598 if (isset($contact["contact-type"])) {
1599 $type = $contact["contact-type"];
1602 if (isset($contact["account-type"])) {
1603 $type = $contact["account-type"];
1607 case self::TYPE_ORGANISATION:
1608 $account_type = L10n::t("Organisation");
1611 case self::TYPE_NEWS:
1612 $account_type = L10n::t('News');
1615 case self::TYPE_COMMUNITY:
1616 $account_type = L10n::t("Forum");
1624 return $account_type;
1628 * @brief Blocks a contact
1632 * @throws \Exception
1634 public static function block($uid)
1636 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1642 * @brief Unblocks a contact
1646 * @throws \Exception
1648 public static function unblock($uid)
1650 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1656 * @brief Updates the avatar links in a contact only if needed
1658 * @param string $avatar Link to avatar picture
1659 * @param int $uid User id of contact owner
1660 * @param int $cid Contact id
1661 * @param bool $force force picture update
1663 * @return array Returns array of the different avatar sizes
1664 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1665 * @throws \ImagickException
1667 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1669 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1670 if (!DBA::isResult($contact)) {
1673 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1676 if (($contact["avatar"] != $avatar) || $force) {
1677 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1682 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1686 // Update the public contact (contact id = 0)
1688 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1689 if (DBA::isResult($pcontact)) {
1690 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1702 * @param integer $id contact id
1703 * @param string $network Optional network we are probing for
1704 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1706 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1707 * @throws \ImagickException
1709 public static function updateFromProbe($id, $network = '', $force = false)
1712 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1713 This will reliably kill your communication with Friendica contacts.
1716 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1717 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1718 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1719 if (!DBA::isResult($contact)) {
1723 $uid = $contact['uid'];
1724 unset($contact['uid']);
1726 $contact['photo'] = $contact['avatar'];
1727 unset($contact['avatar']);
1729 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1731 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1732 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1736 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT)) {
1742 // make sure to not overwrite existing values with blank entries
1743 foreach ($ret as $key => $val) {
1744 if (!isset($contact[$key])) {
1746 } elseif (($contact[$key] != '') && ($val == '')) {
1747 $ret[$key] = $contact[$key];
1748 } elseif ($ret[$key] != $contact[$key]) {
1757 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1758 $ret['updated'] = DateTimeFormat::utcNow();
1760 self::updateAvatar($ret['photo'], $uid, $id, true);
1762 unset($ret['photo']);
1763 DBA::update('contact', $ret, ['id' => $id]);
1765 // Update the corresponding gcontact entry
1766 PortableContact::lastUpdated($ret["url"]);
1772 * Takes a $uid and a url/handle and adds a new contact
1773 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1774 * dfrn_request page.
1776 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1779 * $return['success'] boolean true if successful
1780 * $return['message'] error text if success is false.
1782 * @brief Takes a $uid and a url/handle and adds a new contact
1784 * @param string $url
1785 * @param bool $interactive
1786 * @param string $network
1788 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1789 * @throws \ImagickException
1791 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1793 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1797 // remove ajax junk, e.g. Twitter
1798 $url = str_replace('/#!/', '/', $url);
1800 if (!Network::isUrlAllowed($url)) {
1801 $result['message'] = L10n::t('Disallowed profile URL.');
1805 if (Network::isUrlBlocked($url)) {
1806 $result['message'] = L10n::t('Blocked domain');
1811 $result['message'] = L10n::t('Connect URL missing.');
1815 $arr = ['url' => $url, 'contact' => []];
1817 Hook::callAll('follow', $arr);
1820 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1824 if (!empty($arr['contact']['name'])) {
1825 $ret = $arr['contact'];
1827 $ret = Probe::uri($url, $network, $uid, false);
1830 if (($network != '') && ($ret['network'] != $network)) {
1831 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1835 // check if we already have a contact
1836 // the poll url is more reliable than the profile url, as we may have
1837 // indirect links or webfinger links
1839 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1840 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1841 if (!DBA::isResult($contact)) {
1842 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1843 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1846 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1848 if (strlen($a->getURLPath())) {
1849 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1851 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1854 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1858 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1859 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1860 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1864 // This extra param just confuses things, remove it
1865 if ($ret['network'] === Protocol::DIASPORA) {
1866 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1869 // do we have enough information?
1870 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1871 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1872 if (empty($ret['poll'])) {
1873 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1875 if (empty($ret['name'])) {
1876 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1878 if (empty($ret['url'])) {
1879 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1881 if (strpos($url, '@') !== false) {
1882 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1883 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1888 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1889 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1890 $ret['notify'] = '';
1893 if (!$ret['notify']) {
1894 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1897 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1899 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1901 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1903 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1905 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1909 if (DBA::isResult($contact)) {
1911 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1913 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1914 DBA::update('contact', $fields, ['id' => $contact['id']]);
1916 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1918 // create contact record
1919 DBA::insert('contact', [
1921 'created' => DateTimeFormat::utcNow(),
1922 'url' => $ret['url'],
1923 'nurl' => Strings::normaliseLink($ret['url']),
1924 'addr' => $ret['addr'],
1925 'alias' => $ret['alias'],
1926 'batch' => $ret['batch'],
1927 'notify' => $ret['notify'],
1928 'poll' => $ret['poll'],
1929 'poco' => $ret['poco'],
1930 'name' => $ret['name'],
1931 'nick' => $ret['nick'],
1932 'network' => $ret['network'],
1933 'pubkey' => $ret['pubkey'],
1934 'rel' => $new_relation,
1935 'priority'=> $ret['priority'],
1936 'writable'=> $writeable,
1937 'hidden' => $hidden,
1940 'pending' => $pending,
1945 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1946 if (!DBA::isResult($contact)) {
1947 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1951 $contact_id = $contact['id'];
1952 $result['cid'] = $contact_id;
1954 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1956 // Update the avatar
1957 self::updateAvatar($ret['photo'], $uid, $contact_id);
1959 // pull feed and consume it, which should subscribe to the hub.
1961 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1963 $owner = User::getOwnerDataById($uid);
1965 if (DBA::isResult($owner)) {
1966 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1967 // create a follow slap
1969 $item['verb'] = ACTIVITY_FOLLOW;
1970 $item['follow'] = $contact["url"];
1972 $item['title'] = '';
1975 $item['attach'] = '';
1977 $slap = OStatus::salmon($item, $owner);
1979 if (!empty($contact['notify'])) {
1980 Salmon::slapper($owner, $contact['notify'], $slap);
1982 } elseif ($contact['network'] == Protocol::DIASPORA) {
1983 $ret = Diaspora::sendShare($a->user, $contact);
1984 Logger::log('share returns: ' . $ret);
1985 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1986 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1987 if (empty($activity_id)) {
1988 // This really should never happen
1992 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1993 Logger::log('Follow returns: ' . $ret);
1997 $result['success'] = true;
2002 * @brief Updated contact's SSL policy
2004 * @param array $contact Contact array
2005 * @param string $new_policy New policy, valid: self,full
2007 * @return array Contact array with updated values
2008 * @throws \Exception
2010 public static function updateSslPolicy(array $contact, $new_policy)
2012 $ssl_changed = false;
2013 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2014 $ssl_changed = true;
2015 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2016 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2017 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2018 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2019 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2020 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2023 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2024 $ssl_changed = true;
2025 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2026 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2027 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2028 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2029 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2030 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2034 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2035 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2036 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2037 DBA::update('contact', $fields, ['id' => $contact['id']]);
2043 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
2044 // Should always be set
2045 if (empty($datarray['author-id'])) {
2049 $fields = ['url', 'name', 'nick', 'photo', 'network'];
2050 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2051 if (!DBA::isResult($pub_contact)) {
2052 // Should never happen
2056 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2057 $name = $pub_contact['name'];
2058 $photo = $pub_contact['photo'];
2059 $nick = $pub_contact['nick'];
2060 $network = $pub_contact['network'];
2062 if (is_array($contact)) {
2063 if (($contact['rel'] == self::SHARING)
2064 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2065 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
2066 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2069 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2070 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2073 // send email notification to owner?
2075 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2076 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2079 // create contact record
2080 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2081 `blocked`, `readonly`, `pending`, `writable`)
2082 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
2083 intval($importer['uid']),
2084 DBA::escape(DateTimeFormat::utcNow()),
2086 DBA::escape(Strings::normaliseLink($url)),
2089 DBA::escape($photo),
2090 DBA::escape($network),
2091 intval(self::FOLLOWER)
2095 'id' => DBA::lastInsertId(),
2096 'network' => $network,
2102 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2104 /// @TODO Encapsulate this into a function/method
2105 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2106 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2107 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2108 // create notification
2109 $hash = Strings::getRandomHex();
2111 if (is_array($contact_record)) {
2112 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2113 'blocked' => false, 'knowyou' => false,
2114 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2117 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2119 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2120 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2123 'type' => NOTIFY_INTRO,
2124 'notify_flags' => $user['notify-flags'],
2125 'language' => $user['language'],
2126 'to_name' => $user['username'],
2127 'to_email' => $user['email'],
2128 'uid' => $user['uid'],
2129 'link' => System::baseUrl() . '/notifications/intro',
2130 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2131 'source_link' => $contact_record['url'],
2132 'source_photo' => $contact_record['photo'],
2133 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2138 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2139 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2140 DBA::update('contact', ['pending' => false], $condition);
2142 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2144 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2145 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2151 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2153 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2154 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2156 Contact::remove($contact['id']);
2160 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2162 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2163 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2165 Contact::remove($contact['id']);
2170 * @brief Create a birthday event.
2172 * Update the year and the birthday.
2174 public static function updateBirthdays()
2178 AND `bd` > "0001-01-01"
2179 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2180 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2181 AND NOT `contact`.`pending`
2182 AND NOT `contact`.`hidden`
2183 AND NOT `contact`.`blocked`
2184 AND NOT `contact`.`archive`
2185 AND NOT `contact`.`deleted`',
2190 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2192 while ($contact = DBA::fetch($contacts)) {
2193 Logger::log('update_contact_birthday: ' . $contact['bd']);
2195 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2197 if (Event::createBirthday($contact, $nextbd)) {
2201 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2202 ['id' => $contact['id']]
2209 * Remove the unavailable contact ids from the provided list
2211 * @param array $contact_ids Contact id list
2212 * @throws \Exception
2214 public static function pruneUnavailable(array &$contact_ids)
2216 if (empty($contact_ids)) {
2220 $str = DBA::escape(implode(',', $contact_ids));
2222 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2225 while($contact = DBA::fetch($stmt)) {
2226 $return[] = $contact['id'];
2231 $contact_ids = $return;
2235 * @brief Returns a magic link to authenticate remote visitors
2237 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2239 * @param string $contact_url The address of the target contact profile
2240 * @param string $url An url that we will be redirected to after the authentication
2242 * @return string with "redir" link
2243 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2244 * @throws \ImagickException
2246 public static function magicLink($contact_url, $url = '')
2248 if (!local_user() && !remote_user()) {
2249 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2252 $cid = self::getIdForURL($contact_url, 0, true);
2254 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2257 return self::magicLinkbyId($cid, $url);
2261 * @brief Returns a magic link to authenticate remote visitors
2263 * @param integer $cid The contact id of the target contact profile
2264 * @param string $url An url that we will be redirected to after the authentication
2266 * @return string with "redir" link
2267 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2268 * @throws \ImagickException
2270 public static function magicLinkbyId($cid, $url = '')
2272 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2274 return self::magicLinkByContact($contact, $url);
2278 * @brief Returns a magic link to authenticate remote visitors
2280 * @param array $contact The contact array with "uid", "network" and "url"
2281 * @param string $url An url that we will be redirected to after the authentication
2283 * @return string with "redir" link
2284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2285 * @throws \ImagickException
2287 public static function magicLinkByContact($contact, $url = '')
2289 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2290 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2293 // Only redirections to the same host do make sense
2294 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2298 if ($contact['uid'] != 0) {
2299 return self::magicLink($contact['url'], $url);
2302 $redirect = 'redir/' . $contact['id'];
2305 $redirect .= '?url=' . $url;
2312 * Remove a contact from all groups
2314 * @param integer $contact_id
2316 * @return boolean Success
2318 public static function removeFromGroups($contact_id)
2320 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2324 * Is the contact a forum?
2326 * @param integer $contactid ID of the contact
2328 * @return boolean "true" if it is a forum
2330 public static function isForum($contactid)
2332 $fields = ['forum', 'prv'];
2333 $condition = ['id' => $contactid];
2334 $contact = DBA::selectFirst('contact', $fields, $condition);
2335 if (!DBA::isResult($contact)) {
2340 return ($contact['forum'] || $contact['prv']);