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;
114 * @param array $fields Array of selected fields, empty for all
115 * @param array $condition Array of fields for condition
116 * @param array $params Array of several parameters
120 public static function select(array $fields = [], array $condition = [], array $params = [])
122 $statement = DBA::select('contact', $fields, $condition, $params);
124 return DBA::toArray($statement);
129 * @return array|boolean Contact record if it exists, false otherwise
132 public static function getById($id)
134 return DBA::selectFirst('contact', [], ['id' => $id]);
138 * @brief Tests if the given contact is a follower
140 * @param int $cid Either public contact id or user's contact id
141 * @param int $uid User ID
143 * @return boolean is the contact id a follower?
144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
145 * @throws \ImagickException
147 public static function isFollower($cid, $uid)
149 if (self::isBlockedByUser($cid, $uid)) {
153 $cdata = self::getPublicAndUserContacID($cid, $uid);
154 if (empty($cdata['user'])) {
158 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
159 return DBA::exists('contact', $condition);
163 * @brief Get the basepath for a given contact link
164 * @todo Add functionality to store this value in the contact table
166 * @param string $url The contact link
168 * @return string basepath
169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170 * @throws \ImagickException
172 public static function getBasepath($url)
174 $data = Probe::uri($url);
175 if (!empty($data['baseurl'])) {
176 return $data['baseurl'];
179 // When we can't probe the server, we use some ugly function that does some pattern matching
180 return PortableContact::detectServer($url);
184 * Returns the public contact id of the given user id
186 * @param integer $uid User ID
188 * @return integer|boolean Public contact id for given user id
191 public static function getPublicIdByUserId($uid)
193 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
194 if (!DBA::isResult($self)) {
197 return self::getIdForURL($self['url'], 0, true);
201 * @brief Returns the contact id for the user and the public contact id for a given contact id
203 * @param int $cid Either public contact id or user's contact id
204 * @param int $uid User ID
206 * @return array with public and user's contact id
207 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208 * @throws \ImagickException
210 public static function getPublicAndUserContacID($cid, $uid)
212 if (empty($uid) || empty($cid)) {
216 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
217 if (!DBA::isResult($contact)) {
221 // We quit when the user id don't match the user id of the provided contact
222 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
226 if ($contact['uid'] != 0) {
227 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
231 $ucid = $contact['id'];
233 $pcid = $contact['id'];
234 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
237 return ['public' => $pcid, 'user' => $ucid];
241 * Returns contact details for a given contact id in combination with a user id
243 * @param int $cid A contact ID
244 * @param int $uid The User ID
245 * @param array $fields The selected fields for the contact
247 * @return array The contact details
251 public static function getContactForUser($cid, $uid, array $fields = [])
253 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
255 if (!DBA::isResult($contact)) {
263 * @brief Block contact id for user id
265 * @param int $cid Either public contact id or user's contact id
266 * @param int $uid User ID
267 * @param boolean $blocked Is the contact blocked or unblocked?
270 public static function setBlockedForUser($cid, $uid, $blocked)
272 $cdata = self::getPublicAndUserContacID($cid, $uid);
277 if ($cdata['user'] != 0) {
278 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
281 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
284 // Blocked contact can't be in any group
285 self::removeFromGroups($cid);
290 * @brief Returns "block" state for contact id and user id
292 * @param int $cid Either public contact id or user's contact id
293 * @param int $uid User ID
295 * @return boolean is the contact id blocked for the given user?
298 public static function isBlockedByUser($cid, $uid)
300 $cdata = self::getPublicAndUserContacID($cid, $uid);
305 $public_blocked = false;
307 if (!empty($cdata['public'])) {
308 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
309 if (DBA::isResult($public_contact)) {
310 $public_blocked = $public_contact['blocked'];
314 $user_blocked = $public_blocked;
316 if (!empty($cdata['user'])) {
317 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
318 if (DBA::isResult($user_contact)) {
319 $user_blocked = $user_contact['blocked'];
323 if ($user_blocked != $public_blocked) {
324 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
327 return $user_blocked;
331 * @brief Ignore contact id for user id
333 * @param int $cid Either public contact id or user's contact id
334 * @param int $uid User ID
335 * @param boolean $ignored Is the contact ignored or unignored?
338 public static function setIgnoredForUser($cid, $uid, $ignored)
340 $cdata = self::getPublicAndUserContacID($cid, $uid);
345 if ($cdata['user'] != 0) {
346 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
349 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
353 * @brief Returns "ignore" state for contact id and user id
355 * @param int $cid Either public contact id or user's contact id
356 * @param int $uid User ID
358 * @return boolean is the contact id ignored for the given user?
361 public static function isIgnoredByUser($cid, $uid)
363 $cdata = self::getPublicAndUserContacID($cid, $uid);
368 $public_ignored = false;
370 if (!empty($cdata['public'])) {
371 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
372 if (DBA::isResult($public_contact)) {
373 $public_ignored = $public_contact['ignored'];
377 $user_ignored = $public_ignored;
379 if (!empty($cdata['user'])) {
380 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
381 if (DBA::isResult($user_contact)) {
382 $user_ignored = $user_contact['readonly'];
386 if ($user_ignored != $public_ignored) {
387 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
390 return $user_ignored;
394 * @brief Set "collapsed" for contact id and user id
396 * @param int $cid Either public contact id or user's contact id
397 * @param int $uid User ID
398 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
401 public static function setCollapsedForUser($cid, $uid, $collapsed)
403 $cdata = self::getPublicAndUserContacID($cid, $uid);
408 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
412 * @brief Returns "collapsed" state for contact id and user id
414 * @param int $cid Either public contact id or user's contact id
415 * @param int $uid User ID
417 * @return boolean is the contact id blocked for the given user?
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 * @throws \ImagickException
421 public static function isCollapsedByUser($cid, $uid)
423 $cdata = self::getPublicAndUserContacID($cid, $uid);
430 if (!empty($cdata['public'])) {
431 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
432 if (DBA::isResult($public_contact)) {
433 $collapsed = $public_contact['collapsed'];
441 * @brief Returns a list of contacts belonging in a group
447 public static function getByGroupId($gid)
452 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
454 INNER JOIN `group_member`
455 ON `contact`.`id` = `group_member`.`contact-id`
457 AND `contact`.`uid` = ?
458 AND NOT `contact`.`self`
459 AND NOT `contact`.`deleted`
460 AND NOT `contact`.`blocked`
461 AND NOT `contact`.`pending`
462 ORDER BY `contact`.`name` ASC',
467 if (DBA::isResult($stmt)) {
468 $return = DBA::toArray($stmt);
476 * @brief Returns the count of OStatus contacts in a group
482 public static function getOStatusCountByGroupId($gid)
486 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
488 INNER JOIN `group_member`
489 ON `contact`.`id` = `group_member`.`contact-id`
491 AND `contact`.`uid` = ?
492 AND `contact`.`network` = ?
493 AND `contact`.`notify` != ""',
498 $return = $contacts['count'];
505 * Creates the self-contact for the provided user id
508 * @return bool Operation success
509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
511 public static function createSelfFromUserId($uid)
513 // Only create the entry if it doesn't exist yet
514 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
518 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
519 if (!DBA::isResult($user)) {
523 $return = DBA::insert('contact', [
524 'uid' => $user['uid'],
525 'created' => DateTimeFormat::utcNow(),
527 'name' => $user['username'],
528 'nick' => $user['nickname'],
529 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
530 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
531 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
534 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
535 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
536 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
537 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
538 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
539 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
540 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
541 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
542 'name-date' => DateTimeFormat::utcNow(),
543 'uri-date' => DateTimeFormat::utcNow(),
544 'avatar-date' => DateTimeFormat::utcNow(),
552 * Updates the self-contact for the provided user id
555 * @param boolean $update_avatar Force the avatar update
556 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
558 public static function updateSelfFromUserID($uid, $update_avatar = false)
560 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
561 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
562 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
563 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
564 if (!DBA::isResult($self)) {
568 $fields = ['nickname', 'page-flags', 'account-type'];
569 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
570 if (!DBA::isResult($user)) {
574 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
575 'country-name', 'gender', 'pub_keywords', 'xmpp'];
576 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
577 if (!DBA::isResult($profile)) {
581 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
582 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
583 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
584 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
585 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
587 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
588 if (DBA::isResult($avatar)) {
589 if ($update_avatar) {
590 $fields['avatar-date'] = DateTimeFormat::utcNow();
593 // Creating the path to the avatar, beginning with the file suffix
594 $types = Image::supportedTypes();
595 if (isset($types[$avatar['type']])) {
596 $file_suffix = $types[$avatar['type']];
598 $file_suffix = 'jpg';
601 // We are adding a timestamp value so that other systems won't use cached content
602 $timestamp = strtotime($fields['avatar-date']);
604 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
605 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
607 $fields['photo'] = $prefix . '4' . $suffix;
608 $fields['thumb'] = $prefix . '5' . $suffix;
609 $fields['micro'] = $prefix . '6' . $suffix;
611 // We hadn't found a photo entry, so we use the default avatar
612 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
613 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
614 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
617 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
618 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
620 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
621 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
622 $fields['nurl'] = Strings::normaliseLink($fields['url']);
623 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
624 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
625 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
626 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
627 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
628 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
632 foreach ($fields as $field => $content) {
633 if ($self[$field] != $content) {
639 if ($fields['name'] != $self['name']) {
640 $fields['name-date'] = DateTimeFormat::utcNow();
642 $fields['updated'] = DateTimeFormat::utcNow();
643 DBA::update('contact', $fields, ['id' => $self['id']]);
645 // Update the public contact as well
646 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
648 // Update the profile
649 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
650 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
651 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
656 * @brief Marks a contact for removal
658 * @param int $id contact id
660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662 public static function remove($id)
664 // We want just to make sure that we don't delete our "self" contact
665 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
666 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
670 // Archive the contact
671 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
673 // Delete it in the background
674 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
678 * @brief Sends an unfriend message. Does not remove the contact
680 * @param array $user User unfriending
681 * @param array $contact Contact unfriended
682 * @param boolean $dissolve Remove the contact on the remote side
684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
685 * @throws \ImagickException
687 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
689 if (empty($contact['network'])) {
692 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
693 DFRN::deliver($user, $contact, 'placeholder', true);
694 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
695 // create an unfollow slap
697 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
698 $item['follow'] = $contact["url"];
703 $item['attach'] = '';
704 $slap = OStatus::salmon($item, $user);
706 if (!empty($contact['notify'])) {
707 Salmon::slapper($user, $contact['notify'], $slap);
709 } elseif ($contact['network'] == Protocol::DIASPORA) {
710 Diaspora::sendUnshare($user, $contact);
711 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
712 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
715 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
721 * @brief Marks a contact for archival after a communication issue delay
723 * Contact has refused to recognise us as a friend. We will start a countdown.
724 * If they still don't recognise us in 32 days, the relationship is over,
725 * and we won't waste any more time trying to communicate with them.
726 * This provides for the possibility that their database is temporarily messed
727 * up or some other transient event and that there's a possibility we could recover from it.
729 * @param array $contact contact to mark for archival
731 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
733 public static function markForArchival(array $contact)
735 if (!isset($contact['url']) && !empty($contact['id'])) {
736 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
737 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
738 if (!DBA::isResult($contact)) {
741 } elseif (!isset($contact['url'])) {
742 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
745 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
747 // Contact already archived or "self" contact? => nothing to do
748 if ($contact['archive'] || $contact['self']) {
752 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
753 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
754 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
757 * We really should send a notification to the owner after 2-3 weeks
758 * so they won't be surprised when the contact vanishes and can take
759 * remedial action if this was a serious mistake or glitch
762 /// @todo Check for contact vitality via probing
763 $archival_days = Config::get('system', 'archival_days', 32);
765 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
766 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
767 /* Relationship is really truly dead. archive them rather than
768 * delete, though if the owner tries to unarchive them we'll start
769 * the whole process over again.
771 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
772 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
778 * @brief Cancels the archival countdown
780 * @see Contact::markForArchival()
782 * @param array $contact contact to be unmarked for archival
786 public static function unmarkForArchival(array $contact)
788 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
789 $exists = DBA::exists('contact', $condition);
791 // We don't need to update, we never marked this contact for archival
796 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
798 if (!isset($contact['url']) && !empty($contact['id'])) {
799 $fields = ['id', 'url', 'batch'];
800 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
801 if (!DBA::isResult($contact)) {
806 // It's a miracle. Our dead contact has inexplicably come back to life.
807 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
808 DBA::update('contact', $fields, ['id' => $contact['id']]);
809 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
811 if (!empty($contact['batch'])) {
812 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
813 DBA::update('contact', $fields, $condition);
818 * @brief Get contact data for a given profile link
820 * The function looks at several places (contact table and gcontact table) for the contact
821 * It caches its result for the same script execution to prevent duplicate calls
823 * @param string $url The profile link
824 * @param int $uid User id
825 * @param array $default If not data was found take this data as default value
827 * @return array Contact data
828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
830 public static function getDetailsByURL($url, $uid = -1, array $default = [])
842 if (isset($cache[$url][$uid])) {
843 return $cache[$url][$uid];
846 $ssl_url = str_replace('http://', 'https://', $url);
848 // Fetch contact data from the contact table for the given user
849 $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`,
850 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
851 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
852 $r = DBA::toArray($s);
854 // Fetch contact data from the contact table for the given user, checking with the alias
855 if (!DBA::isResult($r)) {
856 $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`,
857 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
858 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
859 $r = DBA::toArray($s);
862 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
863 if (!DBA::isResult($r)) {
864 $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`,
865 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
866 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
867 $r = DBA::toArray($s);
870 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
871 if (!DBA::isResult($r)) {
872 $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`,
873 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
874 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
875 $r = DBA::toArray($s);
878 // Fetch the data from the gcontact table
879 if (!DBA::isResult($r)) {
880 $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`,
881 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
882 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
883 $r = DBA::toArray($s);
886 if (DBA::isResult($r)) {
887 // If there is more than one entry we filter out the connector networks
889 foreach ($r as $id => $result) {
890 if ($result["network"] == Protocol::STATUSNET) {
896 $profile = array_shift($r);
898 // "bd" always contains the upcoming birthday of a contact.
899 // "birthday" might contain the birthday including the year of birth.
900 if ($profile["birthday"] > DBA::NULL_DATE) {
901 $bd_timestamp = strtotime($profile["birthday"]);
902 $month = date("m", $bd_timestamp);
903 $day = date("d", $bd_timestamp);
905 $current_timestamp = time();
906 $current_year = date("Y", $current_timestamp);
907 $current_month = date("m", $current_timestamp);
908 $current_day = date("d", $current_timestamp);
910 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
911 $current = $current_year . "-" . $current_month . "-" . $current_day;
913 if ($profile["bd"] < $current) {
914 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
917 $profile["bd"] = DBA::NULL_DATE;
923 if (empty($profile["photo"]) && isset($default["photo"])) {
924 $profile["photo"] = $default["photo"];
927 if (empty($profile["name"]) && isset($default["name"])) {
928 $profile["name"] = $default["name"];
931 if (empty($profile["network"]) && isset($default["network"])) {
932 $profile["network"] = $default["network"];
935 if (empty($profile["thumb"]) && isset($profile["photo"])) {
936 $profile["thumb"] = $profile["photo"];
939 if (empty($profile["micro"]) && isset($profile["thumb"])) {
940 $profile["micro"] = $profile["thumb"];
943 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
944 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
946 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
949 // Show contact details of Diaspora contacts only if connected
950 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
951 $profile["location"] = "";
952 $profile["about"] = "";
953 $profile["gender"] = "";
954 $profile["birthday"] = DBA::NULL_DATE;
957 $cache[$url][$uid] = $profile;
963 * @brief Get contact data for a given address
965 * The function looks at several places (contact table and gcontact table) for the contact
967 * @param string $addr The profile link
968 * @param int $uid User id
970 * @return array Contact data
971 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
972 * @throws \ImagickException
974 public static function getDetailsByAddr($addr, $uid = -1)
984 // Fetch contact data from the contact table for the given user
985 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
986 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
987 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
991 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
992 if (!DBA::isResult($r)) {
993 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
994 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
995 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1000 // Fetch the data from the gcontact table
1001 if (!DBA::isResult($r)) {
1002 $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`,
1003 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1004 FROM `gcontact` WHERE `addr` = '%s'",
1009 if (!DBA::isResult($r)) {
1010 $data = Probe::uri($addr);
1012 $profile = self::getDetailsByURL($data['url'], $uid);
1021 * @brief Returns the data array for the photo menu of a given contact
1023 * @param array $contact contact
1024 * @param int $uid optional, default 0
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 * @throws \ImagickException
1029 public static function photoMenu(array $contact, $uid = 0)
1034 $contact_drop_link = '';
1038 $uid = local_user();
1041 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1043 $profile_link = self::magicLink($contact['url']);
1044 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1049 // Look for our own contact if the uid doesn't match and isn't public
1050 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1051 if (DBA::isResult($contact_own)) {
1052 return self::photoMenu($contact_own, $uid);
1057 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1059 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1061 $profile_link = $contact['url'];
1064 if ($profile_link === 'mailbox') {
1069 $status_link = $profile_link . '?tab=status';
1070 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1071 $profile_link = $profile_link . '?tab=profile';
1074 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1075 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1078 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1079 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1082 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1084 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1086 if (!$contact['self']) {
1087 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1092 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1094 if (empty($contact['uid'])) {
1095 $connlnk = 'follow/?url=' . $contact['url'];
1097 'profile' => [L10n::t('View Profile'), $profile_link, true],
1098 'network' => [L10n::t('Network Posts'), $posts_link, false],
1099 'edit' => [L10n::t('View Contact'), $contact_url, false],
1100 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1104 'status' => [L10n::t('View Status'), $status_link, true],
1105 'profile' => [L10n::t('View Profile'), $profile_link, true],
1106 'photos' => [L10n::t('View Photos'), $photos_link, true],
1107 'network' => [L10n::t('Network Posts'), $posts_link, false],
1108 'edit' => [L10n::t('View Contact'), $contact_url, false],
1109 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1110 'pm' => [L10n::t('Send PM'), $pm_url, false],
1111 'poke' => [L10n::t('Poke'), $poke_link, false],
1115 $args = ['contact' => $contact, 'menu' => &$menu];
1117 Hook::callAll('contact_photo_menu', $args);
1119 $menucondensed = [];
1121 foreach ($menu as $menuname => $menuitem) {
1122 if ($menuitem[1] != '') {
1123 $menucondensed[$menuname] = $menuitem;
1127 return $menucondensed;
1131 * @brief Returns ungrouped contact count or list for user
1133 * Returns either the total number of ungrouped contacts for the given user
1134 * id or a paginated list of ungrouped contacts.
1136 * @param int $uid uid
1138 * @throws \Exception
1140 public static function getUngroupedList($uid)
1150 SELECT DISTINCT(`contact-id`)
1152 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1153 WHERE `group`.`uid` = %d
1154 )", intval($uid), intval($uid));
1158 * Have a look at all contact tables for a given profile url.
1159 * This function works as a replacement for probing the contact.
1161 * @param string $url Contact URL
1162 * @param integer $cid Contact ID
1164 * @return array Contact array in the "probe" structure
1166 private static function getProbeDataFromDatabase($url, $cid = null)
1168 // The link could be provided as http although we stored it as https
1169 $ssl_url = str_replace('http://', 'https://', $url);
1171 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1172 'photo', 'keywords', 'location', 'about', 'network',
1173 'priority', 'batch', 'request', 'confirm', 'poco'];
1176 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1177 if (DBA::isResult($data)) {
1182 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1184 if (!DBA::isResult($data)) {
1185 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1186 $data = DBA::selectFirst('contact', $fields, $condition);
1189 if (DBA::isResult($data)) {
1190 // For security reasons we don't fetch key data from our users
1191 $data["pubkey"] = '';
1195 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1196 'photo', 'keywords', 'location', 'about', 'network'];
1197 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1199 if (!DBA::isResult($data)) {
1200 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1201 $data = DBA::selectFirst('contact', $fields, $condition);
1204 if (DBA::isResult($data)) {
1205 $data["pubkey"] = '';
1207 $data["priority"] = 0;
1208 $data["batch"] = '';
1209 $data["request"] = '';
1210 $data["confirm"] = '';
1215 $data = ActivityPub::probeProfile($url, false);
1216 if (!empty($data)) {
1220 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1221 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1222 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1224 if (!DBA::isResult($data)) {
1225 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1226 $data = DBA::selectFirst('contact', $fields, $condition);
1229 if (DBA::isResult($data)) {
1230 $data["pubkey"] = '';
1231 $data["keywords"] = '';
1232 $data["location"] = '';
1233 $data["about"] = '';
1242 * @brief Fetch the contact id for a given URL and user
1244 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1245 * `addr` or `alias`.
1247 * If there's no record and we aren't looking for a public contact, we quit.
1248 * If there's one, we check that it isn't time to update the picture else we
1249 * directly return the found contact id.
1251 * Second, we probe the provided $url whether it's http://server.tld/profile or
1252 * nick@server.tld. We quit if we can't get any info back.
1254 * Third, we create the contact record if it doesn't exist
1256 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1257 * if there's any updates
1259 * @param string $url Contact URL
1260 * @param integer $uid The user id for the contact (0 = public contact)
1261 * @param boolean $no_update Don't update the contact
1262 * @param array $default Default value for creating the contact when every else fails
1263 * @param boolean $in_loop Internally used variable to prevent an endless loop
1265 * @return integer Contact ID
1266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1267 * @throws \ImagickException
1269 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1271 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1279 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1280 // We first try the nurl (http://server.tld/nick), most common case
1281 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1283 // Then the addr (nick@server.tld)
1284 if (!DBA::isResult($contact)) {
1285 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1288 // Then the alias (which could be anything)
1289 if (!DBA::isResult($contact)) {
1290 // The link could be provided as http although we stored it as https
1291 $ssl_url = str_replace('http://', 'https://', $url);
1292 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1293 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1296 if (DBA::isResult($contact)) {
1297 $contact_id = $contact["id"];
1299 // Update the contact every 7 days
1300 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1302 // We force the update if the avatar is empty
1303 if (empty($contact['avatar'])) {
1304 $update_contact = true;
1307 // Update the contact in the background if needed but it is called by the frontend
1308 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1309 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1312 if (!$update_contact || $no_update) {
1315 } elseif ($uid != 0) {
1316 // Non-existing user-specific contact, exiting
1320 // When we don't want to update, we look if we know this contact in any way
1321 if ($no_update && empty($default)) {
1322 $data = self::getProbeDataFromDatabase($url, $contact_id);
1323 $background_update = true;
1326 $background_update = false;
1330 $data = Probe::uri($url, "", $uid);
1332 // Ensure that there is a gserver entry
1333 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1334 PortableContact::checkServer($data['baseurl']);
1338 // Last try in gcontact for unsupported networks
1339 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1344 $contact = array_merge(self::getProbeDataFromDatabase($url, $contact_id), $default);
1345 if (empty($contact)) {
1349 $data = array_merge($data, $contact);
1356 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1357 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1363 'created' => DateTimeFormat::utcNow(),
1364 'url' => $data['url'],
1365 'nurl' => Strings::normaliseLink($data['url']),
1366 'addr' => defaults($data, 'addr', ''),
1367 'alias' => defaults($data, 'alias', ''),
1368 'notify' => defaults($data, 'notify', ''),
1369 'poll' => defaults($data, 'poll', ''),
1370 'name' => defaults($data, 'name', ''),
1371 'nick' => defaults($data, 'nick', ''),
1372 'photo' => defaults($data, 'photo', ''),
1373 'keywords' => defaults($data, 'keywords', ''),
1374 'location' => defaults($data, 'location', ''),
1375 'about' => defaults($data, 'about', ''),
1376 'network' => $data['network'],
1377 'pubkey' => defaults($data, 'pubkey', ''),
1378 'rel' => self::SHARING,
1379 'priority' => defaults($data, 'priority', 0),
1380 'batch' => defaults($data, 'batch', ''),
1381 'request' => defaults($data, 'request', ''),
1382 'confirm' => defaults($data, 'confirm', ''),
1383 'poco' => defaults($data, 'poco', ''),
1384 'name-date' => DateTimeFormat::utcNow(),
1385 'uri-date' => DateTimeFormat::utcNow(),
1386 'avatar-date' => DateTimeFormat::utcNow(),
1392 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1394 DBA::update('contact', $fields, $condition, true);
1396 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1397 $contacts = DBA::toArray($s);
1398 if (!DBA::isResult($contacts)) {
1402 $contact_id = $contacts[0]["id"];
1404 // Update in the background when we fetched the data solely from the database
1405 if ($background_update) {
1406 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1409 // Update the newly created contact from data in the gcontact table
1410 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1411 if (DBA::isResult($gcontact)) {
1412 // Only use the information when the probing hadn't fetched these values
1413 if (!empty($data['keywords'])) {
1414 unset($gcontact['keywords']);
1416 if (!empty($data['location'])) {
1417 unset($gcontact['location']);
1419 if (!empty($data['about'])) {
1420 unset($gcontact['about']);
1422 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1425 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1426 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1427 Strings::normaliseLink($data["url"]), 0, $contact_id];
1428 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1429 DBA::delete('contact', $condition);
1433 if (!empty($data['photo'])) {
1434 self::updateAvatar($data['photo'], $uid, $contact_id);
1437 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1438 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1440 // This condition should always be true
1441 if (!DBA::isResult($contact)) {
1445 $updated = ['addr' => $data['addr'],
1446 'alias' => defaults($data, 'alias', ''),
1447 'url' => $data['url'],
1448 'nurl' => Strings::normaliseLink($data['url']),
1449 'name' => $data['name'],
1450 'nick' => $data['nick']];
1452 if (!empty($data['keywords'])) {
1453 $updated['keywords'] = $data['keywords'];
1455 if (!empty($data['location'])) {
1456 $updated['location'] = $data['location'];
1459 // Update the technical stuff as well - if filled
1460 if (!empty($data['notify'])) {
1461 $updated['notify'] = $data['notify'];
1463 if (!empty($data['poll'])) {
1464 $updated['poll'] = $data['poll'];
1466 if (!empty($data['batch'])) {
1467 $updated['batch'] = $data['batch'];
1469 if (!empty($data['request'])) {
1470 $updated['request'] = $data['request'];
1472 if (!empty($data['confirm'])) {
1473 $updated['confirm'] = $data['confirm'];
1475 if (!empty($data['poco'])) {
1476 $updated['poco'] = $data['poco'];
1479 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1480 if (empty($contact['pubkey'])) {
1481 $updated['pubkey'] = $data['pubkey'];
1484 if (($data['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1485 $updated['uri-date'] = DateTimeFormat::utcNow();
1487 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1488 $updated['name-date'] = DateTimeFormat::utcNow();
1491 $updated['updated'] = DateTimeFormat::utcNow();
1493 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1499 * @brief Checks if the contact is blocked
1501 * @param int $cid contact id
1503 * @return boolean Is the contact blocked?
1504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1506 public static function isBlocked($cid)
1512 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1513 if (!DBA::isResult($blocked)) {
1517 if (Network::isUrlBlocked($blocked['url'])) {
1521 return (bool) $blocked['blocked'];
1525 * @brief Checks if the contact is hidden
1527 * @param int $cid contact id
1529 * @return boolean Is the contact hidden?
1530 * @throws \Exception
1532 public static function isHidden($cid)
1538 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1539 if (!DBA::isResult($hidden)) {
1542 return (bool) $hidden['hidden'];
1546 * @brief Returns posts from a given contact url
1548 * @param string $contact_url Contact URL
1550 * @param bool $thread_mode
1551 * @param int $update
1552 * @return string posts in HTML
1553 * @throws \Exception
1555 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1557 $a = self::getApp();
1559 $cid = self::getIdForURL($contact_url);
1561 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1562 if (!DBA::isResult($contact)) {
1566 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1567 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1569 $sql = "`item`.`uid` = ?";
1572 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1575 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1576 $cid, GRAVITY_PARENT, local_user()];
1578 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1579 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1582 $pager = new Pager($a->query_string);
1584 $params = ['order' => ['created' => true],
1585 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1588 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1590 $items = Item::inArray($r);
1592 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1594 $r = Item::selectForUser(local_user(), [], $condition, $params);
1596 $items = Item::inArray($r);
1598 $o = conversation($a, $items, $pager, 'contact-posts', false);
1602 $o .= $pager->renderMinimal(count($items));
1609 * @brief Returns the account type name
1611 * The function can be called with either the user or the contact array
1613 * @param array $contact contact or user array
1616 public static function getAccountType(array $contact)
1618 // There are several fields that indicate that the contact or user is a forum
1619 // "page-flags" is a field in the user table,
1620 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1621 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1622 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1623 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1624 || (isset($contact['forum']) && intval($contact['forum']))
1625 || (isset($contact['prv']) && intval($contact['prv']))
1626 || (isset($contact['community']) && intval($contact['community']))
1628 $type = self::TYPE_COMMUNITY;
1630 $type = self::TYPE_PERSON;
1633 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1634 if (isset($contact["contact-type"])) {
1635 $type = $contact["contact-type"];
1638 if (isset($contact["account-type"])) {
1639 $type = $contact["account-type"];
1643 case self::TYPE_ORGANISATION:
1644 $account_type = L10n::t("Organisation");
1647 case self::TYPE_NEWS:
1648 $account_type = L10n::t('News');
1651 case self::TYPE_COMMUNITY:
1652 $account_type = L10n::t("Forum");
1660 return $account_type;
1664 * @brief Blocks a contact
1668 * @throws \Exception
1670 public static function block($uid)
1672 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1678 * @brief Unblocks a contact
1682 * @throws \Exception
1684 public static function unblock($uid)
1686 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1692 * @brief Updates the avatar links in a contact only if needed
1694 * @param string $avatar Link to avatar picture
1695 * @param int $uid User id of contact owner
1696 * @param int $cid Contact id
1697 * @param bool $force force picture update
1699 * @return array Returns array of the different avatar sizes
1700 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1701 * @throws \ImagickException
1703 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1705 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1706 if (!DBA::isResult($contact)) {
1709 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1712 if (($contact["avatar"] != $avatar) || $force) {
1713 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1718 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1722 // Update the public contact (contact id = 0)
1724 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1725 if (DBA::isResult($pcontact)) {
1726 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1738 * @param integer $id contact id
1739 * @param string $network Optional network we are probing for
1740 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1742 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1743 * @throws \ImagickException
1745 public static function updateFromProbe($id, $network = '', $force = false)
1748 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1749 This will reliably kill your communication with Friendica contacts.
1752 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1753 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1754 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1755 if (!DBA::isResult($contact)) {
1759 $uid = $contact['uid'];
1760 unset($contact['uid']);
1762 $contact['photo'] = $contact['avatar'];
1763 unset($contact['avatar']);
1765 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1767 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1768 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1772 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT)) {
1778 // make sure to not overwrite existing values with blank entries
1779 foreach ($ret as $key => $val) {
1780 if (!isset($contact[$key])) {
1782 } elseif (($contact[$key] != '') && ($val == '')) {
1783 $ret[$key] = $contact[$key];
1784 } elseif ($ret[$key] != $contact[$key]) {
1793 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1794 $ret['updated'] = DateTimeFormat::utcNow();
1796 self::updateAvatar($ret['photo'], $uid, $id, true);
1798 unset($ret['photo']);
1799 DBA::update('contact', $ret, ['id' => $id]);
1801 // Update the corresponding gcontact entry
1802 PortableContact::lastUpdated($ret["url"]);
1808 * Takes a $uid and a url/handle and adds a new contact
1809 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1810 * dfrn_request page.
1812 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1815 * $return['success'] boolean true if successful
1816 * $return['message'] error text if success is false.
1818 * @brief Takes a $uid and a url/handle and adds a new contact
1820 * @param string $url
1821 * @param bool $interactive
1822 * @param string $network
1824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1825 * @throws \ImagickException
1827 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1829 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1833 // remove ajax junk, e.g. Twitter
1834 $url = str_replace('/#!/', '/', $url);
1836 if (!Network::isUrlAllowed($url)) {
1837 $result['message'] = L10n::t('Disallowed profile URL.');
1841 if (Network::isUrlBlocked($url)) {
1842 $result['message'] = L10n::t('Blocked domain');
1847 $result['message'] = L10n::t('Connect URL missing.');
1851 $arr = ['url' => $url, 'contact' => []];
1853 Hook::callAll('follow', $arr);
1856 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1860 if (!empty($arr['contact']['name'])) {
1861 $ret = $arr['contact'];
1863 $ret = Probe::uri($url, $network, $uid, false);
1866 if (($network != '') && ($ret['network'] != $network)) {
1867 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1871 // check if we already have a contact
1872 // the poll url is more reliable than the profile url, as we may have
1873 // indirect links or webfinger links
1875 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1876 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1877 if (!DBA::isResult($contact)) {
1878 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1879 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1882 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1884 if (strlen($a->getURLPath())) {
1885 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1887 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1890 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1894 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1895 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1896 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1900 // This extra param just confuses things, remove it
1901 if ($ret['network'] === Protocol::DIASPORA) {
1902 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1905 // do we have enough information?
1906 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1907 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1908 if (empty($ret['poll'])) {
1909 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1911 if (empty($ret['name'])) {
1912 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1914 if (empty($ret['url'])) {
1915 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1917 if (strpos($url, '@') !== false) {
1918 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1919 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1924 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1925 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1926 $ret['notify'] = '';
1929 if (!$ret['notify']) {
1930 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1933 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1935 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1937 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1939 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1941 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1945 if (DBA::isResult($contact)) {
1947 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1949 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1950 DBA::update('contact', $fields, ['id' => $contact['id']]);
1952 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1954 // create contact record
1955 DBA::insert('contact', [
1957 'created' => DateTimeFormat::utcNow(),
1958 'url' => $ret['url'],
1959 'nurl' => Strings::normaliseLink($ret['url']),
1960 'addr' => $ret['addr'],
1961 'alias' => $ret['alias'],
1962 'batch' => $ret['batch'],
1963 'notify' => $ret['notify'],
1964 'poll' => $ret['poll'],
1965 'poco' => $ret['poco'],
1966 'name' => $ret['name'],
1967 'nick' => $ret['nick'],
1968 'network' => $ret['network'],
1969 'pubkey' => $ret['pubkey'],
1970 'rel' => $new_relation,
1971 'priority'=> $ret['priority'],
1972 'writable'=> $writeable,
1973 'hidden' => $hidden,
1976 'pending' => $pending,
1981 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1982 if (!DBA::isResult($contact)) {
1983 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1987 $contact_id = $contact['id'];
1988 $result['cid'] = $contact_id;
1990 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1992 // Update the avatar
1993 self::updateAvatar($ret['photo'], $uid, $contact_id);
1995 // pull feed and consume it, which should subscribe to the hub.
1997 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1999 $owner = User::getOwnerDataById($uid);
2001 if (DBA::isResult($owner)) {
2002 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
2003 // create a follow slap
2005 $item['verb'] = ACTIVITY_FOLLOW;
2006 $item['follow'] = $contact["url"];
2008 $item['title'] = '';
2011 $item['attach'] = '';
2013 $slap = OStatus::salmon($item, $owner);
2015 if (!empty($contact['notify'])) {
2016 Salmon::slapper($owner, $contact['notify'], $slap);
2018 } elseif ($contact['network'] == Protocol::DIASPORA) {
2019 $ret = Diaspora::sendShare($a->user, $contact);
2020 Logger::log('share returns: ' . $ret);
2021 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
2022 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2023 if (empty($activity_id)) {
2024 // This really should never happen
2028 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2029 Logger::log('Follow returns: ' . $ret);
2033 $result['success'] = true;
2038 * @brief Updated contact's SSL policy
2040 * @param array $contact Contact array
2041 * @param string $new_policy New policy, valid: self,full
2043 * @return array Contact array with updated values
2044 * @throws \Exception
2046 public static function updateSslPolicy(array $contact, $new_policy)
2048 $ssl_changed = false;
2049 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2050 $ssl_changed = true;
2051 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2052 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2053 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2054 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2055 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2056 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2059 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2060 $ssl_changed = true;
2061 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2062 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2063 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2064 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2065 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2066 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2070 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2071 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2072 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2073 DBA::update('contact', $fields, ['id' => $contact['id']]);
2079 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
2080 // Should always be set
2081 if (empty($datarray['author-id'])) {
2085 $fields = ['url', 'name', 'nick', 'photo', 'network'];
2086 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2087 if (!DBA::isResult($pub_contact)) {
2088 // Should never happen
2092 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2093 $name = $pub_contact['name'];
2094 $photo = $pub_contact['photo'];
2095 $nick = $pub_contact['nick'];
2096 $network = $pub_contact['network'];
2098 if (is_array($contact)) {
2099 if (($contact['rel'] == self::SHARING)
2100 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2101 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
2102 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2105 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2106 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2109 // send email notification to owner?
2111 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2112 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2115 // create contact record
2116 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2117 `blocked`, `readonly`, `pending`, `writable`)
2118 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
2119 intval($importer['uid']),
2120 DBA::escape(DateTimeFormat::utcNow()),
2122 DBA::escape(Strings::normaliseLink($url)),
2125 DBA::escape($photo),
2126 DBA::escape($network),
2127 intval(self::FOLLOWER)
2131 'id' => DBA::lastInsertId(),
2132 'network' => $network,
2138 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2140 /// @TODO Encapsulate this into a function/method
2141 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2142 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2143 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2144 // create notification
2145 $hash = Strings::getRandomHex();
2147 if (is_array($contact_record)) {
2148 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2149 'blocked' => false, 'knowyou' => false,
2150 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2153 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2155 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2156 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2159 'type' => NOTIFY_INTRO,
2160 'notify_flags' => $user['notify-flags'],
2161 'language' => $user['language'],
2162 'to_name' => $user['username'],
2163 'to_email' => $user['email'],
2164 'uid' => $user['uid'],
2165 'link' => System::baseUrl() . '/notifications/intro',
2166 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2167 'source_link' => $contact_record['url'],
2168 'source_photo' => $contact_record['photo'],
2169 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2174 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2175 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2176 DBA::update('contact', ['pending' => false], $condition);
2178 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2180 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2181 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2187 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2189 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2190 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2192 Contact::remove($contact['id']);
2196 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2198 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2199 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2201 Contact::remove($contact['id']);
2206 * @brief Create a birthday event.
2208 * Update the year and the birthday.
2210 public static function updateBirthdays()
2214 AND `bd` > "0001-01-01"
2215 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2216 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2217 AND NOT `contact`.`pending`
2218 AND NOT `contact`.`hidden`
2219 AND NOT `contact`.`blocked`
2220 AND NOT `contact`.`archive`
2221 AND NOT `contact`.`deleted`',
2226 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2228 while ($contact = DBA::fetch($contacts)) {
2229 Logger::log('update_contact_birthday: ' . $contact['bd']);
2231 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2233 if (Event::createBirthday($contact, $nextbd)) {
2237 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2238 ['id' => $contact['id']]
2245 * Remove the unavailable contact ids from the provided list
2247 * @param array $contact_ids Contact id list
2248 * @throws \Exception
2250 public static function pruneUnavailable(array &$contact_ids)
2252 if (empty($contact_ids)) {
2256 $str = DBA::escape(implode(',', $contact_ids));
2258 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2261 while($contact = DBA::fetch($stmt)) {
2262 $return[] = $contact['id'];
2267 $contact_ids = $return;
2271 * @brief Returns a magic link to authenticate remote visitors
2273 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2275 * @param string $contact_url The address of the target contact profile
2276 * @param string $url An url that we will be redirected to after the authentication
2278 * @return string with "redir" link
2279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2280 * @throws \ImagickException
2282 public static function magicLink($contact_url, $url = '')
2284 if (!local_user() && !remote_user()) {
2285 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2288 $data = self::getProbeDataFromDatabase($contact_url);
2290 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2293 return self::magicLinkByContact($data, $contact_url);
2297 * @brief Returns a magic link to authenticate remote visitors
2299 * @param integer $cid The contact id of the target contact profile
2300 * @param string $url An url that we will be redirected to after the authentication
2302 * @return string with "redir" link
2303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2304 * @throws \ImagickException
2306 public static function magicLinkbyId($cid, $url = '')
2308 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2310 return self::magicLinkByContact($contact, $url);
2314 * @brief Returns a magic link to authenticate remote visitors
2316 * @param array $contact The contact array with "uid", "network" and "url"
2317 * @param string $url An url that we will be redirected to after the authentication
2319 * @return string with "redir" link
2320 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2321 * @throws \ImagickException
2323 public static function magicLinkByContact($contact, $url = '')
2325 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2326 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2329 // Only redirections to the same host do make sense
2330 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2334 if ($contact['uid'] != 0) {
2335 return self::magicLink($contact['url'], $url);
2338 $redirect = 'redir/' . $contact['id'];
2341 $redirect .= '?url=' . $url;
2348 * Remove a contact from all groups
2350 * @param integer $contact_id
2352 * @return boolean Success
2354 public static function removeFromGroups($contact_id)
2356 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2360 * Is the contact a forum?
2362 * @param integer $contactid ID of the contact
2364 * @return boolean "true" if it is a forum
2366 public static function isForum($contactid)
2368 $fields = ['forum', 'prv'];
2369 $condition = ['id' => $contactid];
2370 $contact = DBA::selectFirst('contact', $fields, $condition);
2371 if (!DBA::isResult($contact)) {
2376 return ($contact['forum'] || $contact['prv']);