3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Profile;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Protocol\PortableContact;
22 use Friendica\Protocol\Salmon;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
26 require_once 'boot.php';
27 require_once 'include/dba.php';
28 require_once 'include/text.php';
31 * @brief functions for interacting with a contact
33 class Contact extends BaseObject
36 * @name page/profile types
38 * PAGE_NORMAL is a typical personal profile account
39 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
40 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
41 * write access to wall and comments (no email and not included in page owner's ACL lists)
42 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
46 const PAGE_NORMAL = 0;
47 const PAGE_SOAPBOX = 1;
48 const PAGE_COMMUNITY = 2;
49 const PAGE_FREELOVE = 3;
51 const PAGE_PRVGROUP = 5;
59 * ACCOUNT_TYPE_PERSON - the account belongs to a person
60 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
62 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
63 * Associated page type: PAGE_SOAPBOX
65 * ACCOUNT_TYPE_NEWS - the account is a news reflector
66 * Associated page type: PAGE_SOAPBOX
68 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
69 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
71 * ACCOUNT_TYPE_RELAY - the account is a relay
72 * This will only be assigned to contacts, not to user accounts
75 const ACCOUNT_TYPE_PERSON = 0;
76 const ACCOUNT_TYPE_ORGANISATION = 1;
77 const ACCOUNT_TYPE_NEWS = 2;
78 const ACCOUNT_TYPE_COMMUNITY = 3;
79 const ACCOUNT_TYPE_RELAY = 4;
98 * @brief Returns the contact id for the user and the public contact id for a given contact id
100 * @param int $cid Either public contact id or user's contact id
101 * @param int $uid User ID
103 * @return array with public and user's contact id
105 private static function getPublicAndUserContacID($cid, $uid)
107 if (empty($uid) || empty($cid)) {
111 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
112 if (!DBA::isResult($contact)) {
116 // We quit when the user id don't match the user id of the provided contact
117 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
121 if ($contact['uid'] != 0) {
122 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
126 $ucid = $contact['id'];
128 $pcid = $contact['id'];
129 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
132 return ['public' => $pcid, 'user' => $ucid];
136 * @brief Block contact id for user id
138 * @param int $cid Either public contact id or user's contact id
139 * @param int $uid User ID
140 * @param boolean $blocked Is the contact blocked or unblocked?
142 public static function setBlockedForUser($cid, $uid, $blocked)
144 $cdata = self::getPublicAndUserContacID($cid, $uid);
149 if ($cdata['user'] != 0) {
150 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
153 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
157 * @brief Returns "block" state for contact id and user id
159 * @param int $cid Either public contact id or user's contact id
160 * @param int $uid User ID
162 * @return boolean is the contact id blocked for the given user?
164 public static function isBlockedByUser($cid, $uid)
166 $cdata = self::getPublicAndUserContacID($cid, $uid);
171 $public_blocked = false;
173 if (!empty($cdata['public'])) {
174 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
175 if (DBA::isResult($public_contact)) {
176 $public_blocked = $public_contact['blocked'];
180 $user_blocked = $public_blocked;
182 if (!empty($cdata['user'])) {
183 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
184 if (DBA::isResult($user_contact)) {
185 $user_blocked = $user_contact['blocked'];
189 if ($user_blocked != $public_blocked) {
190 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
193 return $user_blocked;
197 * @brief Ignore contact id for user id
199 * @param int $cid Either public contact id or user's contact id
200 * @param int $uid User ID
201 * @param boolean $ignored Is the contact ignored or unignored?
203 public static function setIgnoredForUser($cid, $uid, $ignored)
205 $cdata = self::getPublicAndUserContacID($cid, $uid);
210 if ($cdata['user'] != 0) {
211 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
214 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
218 * @brief Returns "ignore" state for contact id and user id
220 * @param int $cid Either public contact id or user's contact id
221 * @param int $uid User ID
223 * @return boolean is the contact id ignored for the given user?
225 public static function isIgnoredByUser($cid, $uid)
227 $cdata = self::getPublicAndUserContacID($cid, $uid);
232 $public_ignored = false;
234 if (!empty($cdata['public'])) {
235 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
236 if (DBA::isResult($public_contact)) {
237 $public_ignored = $public_contact['ignored'];
241 $user_ignored = $public_ignored;
243 if (!empty($cdata['user'])) {
244 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
245 if (DBA::isResult($user_contact)) {
246 $user_ignored = $user_contact['readonly'];
250 if ($user_ignored != $public_ignored) {
251 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
254 return $user_ignored;
258 * @brief Set "collapsed" for contact id and user id
260 * @param int $cid Either public contact id or user's contact id
261 * @param int $uid User ID
262 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
264 public static function setCollapsedForUser($cid, $uid, $collapsed)
266 $cdata = self::getPublicAndUserContacID($cid, $uid);
271 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
275 * @brief Returns "collapsed" state for contact id and user id
277 * @param int $cid Either public contact id or user's contact id
278 * @param int $uid User ID
280 * @return boolean is the contact id blocked for the given user?
282 public static function isCollapsedByUser($cid, $uid)
284 $cdata = self::getPublicAndUserContacID($cid, $uid);
291 if (!empty($cdata['public'])) {
292 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
293 if (DBA::isResult($public_contact)) {
294 $collapsed = $public_contact['collapsed'];
302 * @brief Returns a list of contacts belonging in a group
307 public static function getByGroupId($gid)
312 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
314 INNER JOIN `group_member`
315 ON `contact`.`id` = `group_member`.`contact-id`
317 AND `contact`.`uid` = ?
318 AND NOT `contact`.`self`
319 AND NOT `contact`.`blocked`
320 AND NOT `contact`.`pending`
321 ORDER BY `contact`.`name` ASC',
326 if (DBA::isResult($stmt)) {
327 $return = DBA::toArray($stmt);
335 * @brief Returns the count of OStatus contacts in a group
340 public static function getOStatusCountByGroupId($gid)
344 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
346 INNER JOIN `group_member`
347 ON `contact`.`id` = `group_member`.`contact-id`
349 AND `contact`.`uid` = ?
350 AND `contact`.`network` = ?
351 AND `contact`.`notify` != ""',
356 $return = $contacts['count'];
363 * Creates the self-contact for the provided user id
366 * @return bool Operation success
368 public static function createSelfFromUserId($uid)
370 // Only create the entry if it doesn't exist yet
371 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
375 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
376 if (!DBA::isResult($user)) {
380 $return = DBA::insert('contact', [
381 'uid' => $user['uid'],
382 'created' => DateTimeFormat::utcNow(),
384 'name' => $user['username'],
385 'nick' => $user['nickname'],
386 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
387 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
388 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
391 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
392 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
393 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
394 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
395 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
396 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
397 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
398 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
399 'name-date' => DateTimeFormat::utcNow(),
400 'uri-date' => DateTimeFormat::utcNow(),
401 'avatar-date' => DateTimeFormat::utcNow(),
409 * Updates the self-contact for the provided user id
412 * @param boolean $update_avatar Force the avatar update
414 public static function updateSelfFromUserID($uid, $update_avatar = false)
416 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
417 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
418 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
419 if (!DBA::isResult($self)) {
423 $fields = ['nickname', 'page-flags', 'account-type'];
424 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
425 if (!DBA::isResult($user)) {
429 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
430 'country-name', 'gender', 'pub_keywords', 'xmpp'];
431 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
432 if (!DBA::isResult($profile)) {
436 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
437 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
438 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
439 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
440 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
442 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
443 if (DBA::isResult($avatar)) {
444 if ($update_avatar) {
445 $fields['avatar-date'] = DateTimeFormat::utcNow();
448 // Creating the path to the avatar, beginning with the file suffix
449 $types = Image::supportedTypes();
450 if (isset($types[$avatar['type']])) {
451 $file_suffix = $types[$avatar['type']];
453 $file_suffix = 'jpg';
456 // We are adding a timestamp value so that other systems won't use cached content
457 $timestamp = strtotime($fields['avatar-date']);
459 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
460 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
462 $fields['photo'] = $prefix . '4' . $suffix;
463 $fields['thumb'] = $prefix . '5' . $suffix;
464 $fields['micro'] = $prefix . '6' . $suffix;
466 // We hadn't found a photo entry, so we use the default avatar
467 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
468 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
469 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
472 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
473 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
475 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
476 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
477 $fields['nurl'] = normalise_link($fields['url']);
478 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
479 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
480 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
481 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
482 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
483 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
487 foreach ($fields as $field => $content) {
488 if (isset($self[$field]) && $self[$field] != $content) {
494 $fields['name-date'] = DateTimeFormat::utcNow();
495 DBA::update('contact', $fields, ['id' => $self['id']]);
497 // Update the public contact as well
498 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
500 // Update the profile
501 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
502 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
503 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
508 * @brief Marks a contact for removal
510 * @param int $id contact id
513 public static function remove($id)
515 // We want just to make sure that we don't delete our "self" contact
516 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
517 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
521 // Archive the contact
522 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM], ['id' => $id]);
524 // Delete it in the background
525 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
529 * @brief Sends an unfriend message. Does not remove the contact
531 * @param array $user User unfriending
532 * @param array $contact Contact unfriended
535 public static function terminateFriendship(array $user, array $contact)
537 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
538 // create an unfollow slap
540 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
541 $item['follow'] = $contact["url"];
546 $item['attach'] = '';
547 $slap = OStatus::salmon($item, $user);
549 if (!empty($contact['notify'])) {
550 Salmon::slapper($user, $contact['notify'], $slap);
552 } elseif ($contact['network'] == Protocol::DIASPORA) {
553 Diaspora::sendUnshare($user, $contact);
558 * @brief Marks a contact for archival after a communication issue delay
560 * Contact has refused to recognise us as a friend. We will start a countdown.
561 * If they still don't recognise us in 32 days, the relationship is over,
562 * and we won't waste any more time trying to communicate with them.
563 * This provides for the possibility that their database is temporarily messed
564 * up or some other transient event and that there's a possibility we could recover from it.
566 * @param array $contact contact to mark for archival
569 public static function markForArchival(array $contact)
571 if (!isset($contact['url']) && !empty($contact['id'])) {
572 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
573 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
574 if (!DBA::isResult($contact)) {
577 } elseif (!isset($contact['url'])) {
578 logger('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), LOGGER_DEBUG);
581 // Contact already archived or "self" contact? => nothing to do
582 if ($contact['archive'] || $contact['self']) {
586 if ($contact['term-date'] <= NULL_DATE) {
587 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
588 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
591 * We really should send a notification to the owner after 2-3 weeks
592 * so they won't be surprised when the contact vanishes and can take
593 * remedial action if this was a serious mistake or glitch
596 /// @todo Check for contact vitality via probing
597 $archival_days = Config::get('system', 'archival_days', 32);
599 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
600 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
601 /* Relationship is really truly dead. archive them rather than
602 * delete, though if the owner tries to unarchive them we'll start
603 * the whole process over again.
605 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
606 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
612 * @brief Cancels the archival countdown
614 * @see Contact::markForArchival()
616 * @param array $contact contact to be unmarked for archival
619 public static function unmarkForArchival(array $contact)
621 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
622 $exists = DBA::exists('contact', $condition);
624 // We don't need to update, we never marked this contact for archival
629 if (!isset($contact['url']) && !empty($contact['id'])) {
630 $fields = ['id', 'url', 'batch'];
631 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
632 if (!DBA::isResult($contact)) {
637 // It's a miracle. Our dead contact has inexplicably come back to life.
638 $fields = ['term-date' => NULL_DATE, 'archive' => false];
639 DBA::update('contact', $fields, ['id' => $contact['id']]);
640 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
642 if (!empty($contact['batch'])) {
643 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
644 DBA::update('contact', $fields, $condition);
649 * @brief Get contact data for a given profile link
651 * The function looks at several places (contact table and gcontact table) for the contact
652 * It caches its result for the same script execution to prevent duplicate calls
654 * @param string $url The profile link
655 * @param int $uid User id
656 * @param array $default If not data was found take this data as default value
658 * @return array Contact data
660 public static function getDetailsByURL($url, $uid = -1, array $default = [])
672 if (isset($cache[$url][$uid])) {
673 return $cache[$url][$uid];
676 $ssl_url = str_replace('http://', 'https://', $url);
678 // Fetch contact data from the contact table for the given user
679 $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`,
680 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
681 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
682 $r = DBA::toArray($s);
684 // Fetch contact data from the contact table for the given user, checking with the alias
685 if (!DBA::isResult($r)) {
686 $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`,
687 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
688 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
689 $r = DBA::toArray($s);
692 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
693 if (!DBA::isResult($r)) {
694 $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`,
695 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
696 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
697 $r = DBA::toArray($s);
700 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
701 if (!DBA::isResult($r)) {
702 $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`,
703 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
704 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
705 $r = DBA::toArray($s);
708 // Fetch the data from the gcontact table
709 if (!DBA::isResult($r)) {
710 $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`,
711 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
712 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
713 $r = DBA::toArray($s);
716 if (DBA::isResult($r)) {
717 // If there is more than one entry we filter out the connector networks
719 foreach ($r as $id => $result) {
720 if ($result["network"] == Protocol::STATUSNET) {
726 $profile = array_shift($r);
728 // "bd" always contains the upcoming birthday of a contact.
729 // "birthday" might contain the birthday including the year of birth.
730 if ($profile["birthday"] > '0001-01-01') {
731 $bd_timestamp = strtotime($profile["birthday"]);
732 $month = date("m", $bd_timestamp);
733 $day = date("d", $bd_timestamp);
735 $current_timestamp = time();
736 $current_year = date("Y", $current_timestamp);
737 $current_month = date("m", $current_timestamp);
738 $current_day = date("d", $current_timestamp);
740 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
741 $current = $current_year . "-" . $current_month . "-" . $current_day;
743 if ($profile["bd"] < $current) {
744 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
747 $profile["bd"] = '0001-01-01';
753 if (empty($profile["photo"]) && isset($default["photo"])) {
754 $profile["photo"] = $default["photo"];
757 if (empty($profile["name"]) && isset($default["name"])) {
758 $profile["name"] = $default["name"];
761 if (empty($profile["network"]) && isset($default["network"])) {
762 $profile["network"] = $default["network"];
765 if (empty($profile["thumb"]) && isset($profile["photo"])) {
766 $profile["thumb"] = $profile["photo"];
769 if (empty($profile["micro"]) && isset($profile["thumb"])) {
770 $profile["micro"] = $profile["thumb"];
773 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
774 && in_array($profile["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
776 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
779 // Show contact details of Diaspora contacts only if connected
780 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
781 $profile["location"] = "";
782 $profile["about"] = "";
783 $profile["gender"] = "";
784 $profile["birthday"] = '0001-01-01';
787 $cache[$url][$uid] = $profile;
793 * @brief Get contact data for a given address
795 * The function looks at several places (contact table and gcontact table) for the contact
797 * @param string $addr The profile link
798 * @param int $uid User id
800 * @return array Contact data
802 public static function getDetailsByAddr($addr, $uid = -1)
814 // Fetch contact data from the contact table for the given user
815 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
816 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
817 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
821 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
822 if (!DBA::isResult($r)) {
823 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
824 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
825 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
830 // Fetch the data from the gcontact table
831 if (!DBA::isResult($r)) {
832 $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`,
833 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
834 FROM `gcontact` WHERE `addr` = '%s'",
839 if (!DBA::isResult($r)) {
840 $data = Probe::uri($addr);
842 $profile = self::getDetailsByURL($data['url'], $uid);
851 * @brief Returns the data array for the photo menu of a given contact
853 * @param array $contact contact
854 * @param int $uid optional, default 0
857 public static function photoMenu(array $contact, $uid = 0)
859 // @todo Unused, to be removed
867 $contact_drop_link = '';
874 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
876 $profile_link = self::magicLink($contact['url']);
877 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
882 // Look for our own contact if the uid doesn't match and isn't public
883 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
884 if (DBA::isResult($contact_own)) {
885 return self::photoMenu($contact_own, $uid);
890 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
892 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
894 $profile_link = $contact['url'];
897 if ($profile_link === 'mailbox') {
902 $status_link = $profile_link . '?url=status';
903 $photos_link = $profile_link . '?url=photos';
904 $profile_link = $profile_link . '?url=profile';
907 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
908 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
911 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
912 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
915 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
917 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/conversations';
919 if (!$contact['self']) {
920 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
925 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
927 if (empty($contact['uid'])) {
928 $connlnk = 'follow/?url=' . $contact['url'];
930 'profile' => [L10n::t('View Profile'), $profile_link, true],
931 'network' => [L10n::t('Network Posts'), $posts_link, false],
932 'edit' => [L10n::t('View Contact'), $contact_url, false],
933 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
937 'status' => [L10n::t('View Status'), $status_link, true],
938 'profile' => [L10n::t('View Profile'), $profile_link, true],
939 'photos' => [L10n::t('View Photos'), $photos_link, true],
940 'network' => [L10n::t('Network Posts'), $posts_link, false],
941 'edit' => [L10n::t('View Contact'), $contact_url, false],
942 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
943 'pm' => [L10n::t('Send PM'), $pm_url, false],
944 'poke' => [L10n::t('Poke'), $poke_link, false],
948 $args = ['contact' => $contact, 'menu' => &$menu];
950 Addon::callHooks('contact_photo_menu', $args);
954 foreach ($menu as $menuname => $menuitem) {
955 if ($menuitem[1] != '') {
956 $menucondensed[$menuname] = $menuitem;
960 return $menucondensed;
964 * @brief Returns ungrouped contact count or list for user
966 * Returns either the total number of ungrouped contacts for the given user
967 * id or a paginated list of ungrouped contacts.
969 * @param int $uid uid
970 * @param int $start optional, default 0
971 * @param int $count optional, default 0
975 public static function getUngroupedList($uid)
984 SELECT DISTINCT(`contact-id`)
986 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
987 WHERE `group`.`uid` = %d
988 )", intval($uid), intval($uid));
992 * @brief Fetch the contact id for a given URL and user
994 * First lookup in the contact table to find a record matching either `url`, `nurl`,
997 * If there's no record and we aren't looking for a public contact, we quit.
998 * If there's one, we check that it isn't time to update the picture else we
999 * directly return the found contact id.
1001 * Second, we probe the provided $url whether it's http://server.tld/profile or
1002 * nick@server.tld. We quit if we can't get any info back.
1004 * Third, we create the contact record if it doesn't exist
1006 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1007 * if there's any updates
1009 * @param string $url Contact URL
1010 * @param integer $uid The user id for the contact (0 = public contact)
1011 * @param boolean $no_update Don't update the contact
1012 * @param array $default Default value for creating the contact when every else fails
1014 * @return integer Contact ID
1016 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
1018 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
1026 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1027 // We first try the nurl (http://server.tld/nick), most common case
1028 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
1030 // Then the addr (nick@server.tld)
1031 if (!DBA::isResult($contact)) {
1032 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
1035 // Then the alias (which could be anything)
1036 if (!DBA::isResult($contact)) {
1037 // The link could be provided as http although we stored it as https
1038 $ssl_url = str_replace('http://', 'https://', $url);
1039 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
1040 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1043 if (DBA::isResult($contact)) {
1044 $contact_id = $contact["id"];
1046 // Update the contact every 7 days
1047 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1049 // We force the update if the avatar is empty
1050 if (!x($contact, 'avatar')) {
1051 $update_contact = true;
1054 if (!$update_contact || $no_update) {
1057 } elseif ($uid != 0) {
1058 // Non-existing user-specific contact, exiting
1062 // When we don't want to update, we look if some of our users already know this contact
1064 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1065 'photo', 'keywords', 'location', 'about', 'network',
1066 'priority', 'batch', 'request', 'confirm', 'poco'];
1067 $data = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1069 if (DBA::isResult($data)) {
1070 // For security reasons we don't fetch key data from our users
1071 $data["pubkey"] = '';
1078 $data = Probe::uri($url, "", $uid);
1080 // Ensure that there is a gserver entry
1081 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1082 PortableContact::checkServer($data['baseurl']);
1086 // Last try in gcontact for unsupported networks
1087 if (!in_array($data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1092 // Get data from the gcontact table
1093 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1094 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
1095 if (!DBA::isResult($contact)) {
1096 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1099 if (!DBA::isResult($contact)) {
1100 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1101 'photo', 'keywords', 'location', 'about', 'network',
1102 'priority', 'batch', 'request', 'confirm', 'poco'];
1103 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1106 if (!DBA::isResult($contact)) {
1107 // The link could be provided as http although we stored it as https
1108 $ssl_url = str_replace('http://', 'https://', $url);
1109 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
1110 $contact = DBA::selectFirst('contact', $fields, $condition);
1113 if (!DBA::isResult($contact)) {
1114 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1115 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1116 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
1117 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1120 if (!empty($default)) {
1121 $contact = $default;
1124 if (!DBA::isResult($contact)) {
1127 $data = array_merge($data, $contact);
1131 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
1132 $contact_id = self::getIdForURL($data["alias"], $uid, true);
1135 $url = $data["url"];
1137 DBA::insert('contact', [
1139 'created' => DateTimeFormat::utcNow(),
1140 'url' => $data["url"],
1141 'nurl' => normalise_link($data["url"]),
1142 'addr' => $data["addr"],
1143 'alias' => $data["alias"],
1144 'notify' => $data["notify"],
1145 'poll' => $data["poll"],
1146 'name' => $data["name"],
1147 'nick' => $data["nick"],
1148 'photo' => $data["photo"],
1149 'keywords' => $data["keywords"],
1150 'location' => $data["location"],
1151 'about' => $data["about"],
1152 'network' => $data["network"],
1153 'pubkey' => $data["pubkey"],
1154 'rel' => self::SHARING,
1155 'priority' => $data["priority"],
1156 'batch' => $data["batch"],
1157 'request' => $data["request"],
1158 'confirm' => $data["confirm"],
1159 'poco' => $data["poco"],
1160 'name-date' => DateTimeFormat::utcNow(),
1161 'uri-date' => DateTimeFormat::utcNow(),
1162 'avatar-date' => DateTimeFormat::utcNow(),
1169 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
1170 $contacts = DBA::toArray($s);
1171 if (!DBA::isResult($contacts)) {
1175 $contact_id = $contacts[0]["id"];
1177 // Update the newly created contact from data in the gcontact table
1178 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
1179 if (DBA::isResult($gcontact)) {
1180 // Only use the information when the probing hadn't fetched these values
1181 if ($data['keywords'] != '') {
1182 unset($gcontact['keywords']);
1184 if ($data['location'] != '') {
1185 unset($gcontact['location']);
1187 if ($data['about'] != '') {
1188 unset($gcontact['about']);
1190 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1193 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1194 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
1195 normalise_link($data["url"]), $contact_id]);
1199 self::updateAvatar($data["photo"], $uid, $contact_id);
1201 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1202 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1204 // This condition should always be true
1205 if (!DBA::isResult($contact)) {
1209 $updated = ['addr' => $data['addr'],
1210 'alias' => $data['alias'],
1211 'url' => $data['url'],
1212 'nurl' => normalise_link($data['url']),
1213 'name' => $data['name'],
1214 'nick' => $data['nick']];
1216 if ($data['keywords'] != '') {
1217 $updated['keywords'] = $data['keywords'];
1219 if ($data['location'] != '') {
1220 $updated['location'] = $data['location'];
1223 // Update the technical stuff as well - if filled
1224 if ($data['notify'] != '') {
1225 $updated['notify'] = $data['notify'];
1227 if ($data['poll'] != '') {
1228 $updated['poll'] = $data['poll'];
1230 if ($data['batch'] != '') {
1231 $updated['batch'] = $data['batch'];
1233 if ($data['request'] != '') {
1234 $updated['request'] = $data['request'];
1236 if ($data['confirm'] != '') {
1237 $updated['confirm'] = $data['confirm'];
1239 if ($data['poco'] != '') {
1240 $updated['poco'] = $data['poco'];
1243 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1244 if (empty($contact['pubkey'])) {
1245 $updated['pubkey'] = $data['pubkey'];
1248 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1249 $updated['uri-date'] = DateTimeFormat::utcNow();
1251 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1252 $updated['name-date'] = DateTimeFormat::utcNow();
1255 $updated['avatar-date'] = DateTimeFormat::utcNow();
1257 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1263 * @brief Checks if the contact is blocked
1265 * @param int $cid contact id
1267 * @return boolean Is the contact blocked?
1269 public static function isBlocked($cid)
1275 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1276 if (!DBA::isResult($blocked)) {
1279 return (bool) $blocked['blocked'];
1283 * @brief Checks if the contact is hidden
1285 * @param int $cid contact id
1287 * @return boolean Is the contact hidden?
1289 public static function isHidden($cid)
1295 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1296 if (!DBA::isResult($hidden)) {
1299 return (bool) $hidden['hidden'];
1303 * @brief Returns posts from a given contact url
1305 * @param string $contact_url Contact URL
1307 * @return string posts in HTML
1309 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1311 $a = self::getApp();
1313 require_once 'include/conversation.php';
1315 // There are no posts with "uid = 0" with connector networks
1316 // This speeds up the query a lot
1317 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1318 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1319 DBA::escape(normalise_link($contact_url))
1322 if (!DBA::isResult($r)) {
1326 if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1327 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1329 $sql = "`item`.`uid` = ?";
1332 $author_id = intval($r[0]["author-id"]);
1334 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1337 $condition = ["`$contact` = ? AND `gravity` = ? AND " . $sql,
1338 $author_id, GRAVITY_PARENT, local_user()];
1340 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1341 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1344 $params = ['order' => ['created' => true],
1345 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1348 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1350 $items = Item::inArray($r);
1352 $o = conversation($a, $items, 'contacts', $update);
1354 $r = Item::selectForUser(local_user(), [], $condition, $params);
1356 $items = Item::inArray($r);
1358 $o = conversation($a, $items, 'contact-posts', false);
1362 $o .= alt_pager($a, count($items));
1369 * @brief Returns the account type name
1371 * The function can be called with either the user or the contact array
1373 * @param array $contact contact or user array
1376 public static function getAccountType(array $contact)
1378 // There are several fields that indicate that the contact or user is a forum
1379 // "page-flags" is a field in the user table,
1380 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1381 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1382 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1383 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1384 || (isset($contact['forum']) && intval($contact['forum']))
1385 || (isset($contact['prv']) && intval($contact['prv']))
1386 || (isset($contact['community']) && intval($contact['community']))
1388 $type = self::ACCOUNT_TYPE_COMMUNITY;
1390 $type = self::ACCOUNT_TYPE_PERSON;
1393 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1394 if (isset($contact["contact-type"])) {
1395 $type = $contact["contact-type"];
1398 if (isset($contact["account-type"])) {
1399 $type = $contact["account-type"];
1403 case self::ACCOUNT_TYPE_ORGANISATION:
1404 $account_type = L10n::t("Organisation");
1407 case self::ACCOUNT_TYPE_NEWS:
1408 $account_type = L10n::t('News');
1411 case self::ACCOUNT_TYPE_COMMUNITY:
1412 $account_type = L10n::t("Forum");
1420 return $account_type;
1424 * @brief Blocks a contact
1429 public static function block($uid)
1431 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1437 * @brief Unblocks a contact
1442 public static function unblock($uid)
1444 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1450 * @brief Updates the avatar links in a contact only if needed
1452 * @param string $avatar Link to avatar picture
1453 * @param int $uid User id of contact owner
1454 * @param int $cid Contact id
1455 * @param bool $force force picture update
1457 * @return array Returns array of the different avatar sizes
1459 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1461 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1462 if (!DBA::isResult($contact)) {
1465 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1468 if (($contact["avatar"] != $avatar) || $force) {
1469 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1474 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1478 // Update the public contact (contact id = 0)
1480 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1481 if (DBA::isResult($pcontact)) {
1482 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1494 * @param integer $id contact id
1497 public static function updateFromProbe($id)
1500 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1501 This will reliably kill your communication with Friendica contacts.
1504 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1505 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1506 if (!DBA::isResult($contact)) {
1510 $ret = Probe::uri($contact["url"]);
1512 // If Probe::uri fails the network code will be different
1513 if ($ret["network"] != $contact["network"]) {
1519 // make sure to not overwrite existing values with blank entries
1520 foreach ($ret as $key => $val) {
1521 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1522 $ret[$key] = $contact[$key];
1525 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1536 'url' => $ret['url'],
1537 'nurl' => normalise_link($ret['url']),
1538 'addr' => $ret['addr'],
1539 'alias' => $ret['alias'],
1540 'batch' => $ret['batch'],
1541 'notify' => $ret['notify'],
1542 'poll' => $ret['poll'],
1543 'poco' => $ret['poco']
1548 // Update the corresponding gcontact entry
1549 PortableContact::lastUpdated($ret["url"]);
1555 * Takes a $uid and a url/handle and adds a new contact
1556 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1557 * dfrn_request page.
1559 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1562 * $return['success'] boolean true if successful
1563 * $return['message'] error text if success is false.
1565 * @brief Takes a $uid and a url/handle and adds a new contact
1567 * @param string $url
1568 * @param bool $interactive
1569 * @param string $network
1570 * @return boolean|string
1572 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1574 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1578 // remove ajax junk, e.g. Twitter
1579 $url = str_replace('/#!/', '/', $url);
1581 if (!Network::isUrlAllowed($url)) {
1582 $result['message'] = L10n::t('Disallowed profile URL.');
1586 if (Network::isUrlBlocked($url)) {
1587 $result['message'] = L10n::t('Blocked domain');
1592 $result['message'] = L10n::t('Connect URL missing.');
1596 $arr = ['url' => $url, 'contact' => []];
1598 Addon::callHooks('follow', $arr);
1601 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1605 if (x($arr['contact'], 'name')) {
1606 $ret = $arr['contact'];
1608 $ret = Probe::uri($url, $network, $uid, false);
1611 if (($network != '') && ($ret['network'] != $network)) {
1612 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1616 // check if we already have a contact
1617 // the poll url is more reliable than the profile url, as we may have
1618 // indirect links or webfinger links
1620 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1621 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1622 if (!DBA::isResult($contact)) {
1623 $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
1624 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1627 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1629 if (strlen($a->urlpath)) {
1630 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1632 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1635 goaway($ret['request'] . "&addr=$myaddr");
1639 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1640 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1641 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1645 // This extra param just confuses things, remove it
1646 if ($ret['network'] === Protocol::DIASPORA) {
1647 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1650 // do we have enough information?
1652 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1653 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1654 if (!x($ret, 'poll')) {
1655 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1657 if (!x($ret, 'name')) {
1658 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1660 if (!x($ret, 'url')) {
1661 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1663 if (strpos($url, '@') !== false) {
1664 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1665 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1670 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1671 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1672 $ret['notify'] = '';
1675 if (!$ret['notify']) {
1676 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1679 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1681 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1683 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1685 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA])) {
1689 if (DBA::isResult($contact)) {
1691 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1693 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1694 DBA::update('contact', $fields, ['id' => $contact['id']]);
1696 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1698 // create contact record
1699 DBA::insert('contact', [
1701 'created' => DateTimeFormat::utcNow(),
1702 'url' => $ret['url'],
1703 'nurl' => normalise_link($ret['url']),
1704 'addr' => $ret['addr'],
1705 'alias' => $ret['alias'],
1706 'batch' => $ret['batch'],
1707 'notify' => $ret['notify'],
1708 'poll' => $ret['poll'],
1709 'poco' => $ret['poco'],
1710 'name' => $ret['name'],
1711 'nick' => $ret['nick'],
1712 'network' => $ret['network'],
1713 'pubkey' => $ret['pubkey'],
1714 'rel' => $new_relation,
1715 'priority'=> $ret['priority'],
1716 'writable'=> $writeable,
1717 'hidden' => $hidden,
1725 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1726 if (!DBA::isResult($contact)) {
1727 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1731 $contact_id = $contact['id'];
1732 $result['cid'] = $contact_id;
1734 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1736 // Update the avatar
1737 self::updateAvatar($ret['photo'], $uid, $contact_id);
1739 // pull feed and consume it, which should subscribe to the hub.
1741 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1743 $owner = User::getOwnerDataById($uid);
1745 if (DBA::isResult($owner)) {
1746 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1747 // create a follow slap
1749 $item['verb'] = ACTIVITY_FOLLOW;
1750 $item['follow'] = $contact["url"];
1752 $item['title'] = '';
1755 $item['attach'] = '';
1757 $slap = OStatus::salmon($item, $owner);
1759 if (!empty($contact['notify'])) {
1760 Salmon::slapper($owner, $contact['notify'], $slap);
1762 } elseif ($contact['network'] == Protocol::DIASPORA) {
1763 $ret = Diaspora::sendShare($a->user, $contact);
1764 logger('share returns: ' . $ret);
1768 $result['success'] = true;
1773 * @brief Updated contact's SSL policy
1775 * @param array $contact Contact array
1776 * @param string $new_policy New policy, valid: self,full
1778 * @return array Contact array with updated values
1780 public static function updateSslPolicy(array $contact, $new_policy)
1782 $ssl_changed = false;
1783 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1784 $ssl_changed = true;
1785 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1786 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1787 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1788 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1789 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1790 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1793 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1794 $ssl_changed = true;
1795 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1796 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1797 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1798 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1799 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1800 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1804 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1805 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1806 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1807 DBA::update('contact', $fields, ['id' => $contact['id']]);
1813 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1814 // Should always be set
1815 if (empty($datarray['author-id'])) {
1819 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1820 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1821 if (!DBA::isResult($pub_contact)) {
1822 // Should never happen
1826 $url = $pub_contact['url'];
1827 $name = $pub_contact['name'];
1828 $photo = $pub_contact['photo'];
1829 $nick = $pub_contact['nick'];
1830 $network = $pub_contact['network'];
1832 if (is_array($contact)) {
1833 if (($contact['rel'] == self::SHARING)
1834 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1835 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1836 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1838 // send email notification to owner?
1840 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1841 logger('ignoring duplicated connection request from pending contact ' . $url);
1845 // create contact record
1846 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1847 `blocked`, `readonly`, `pending`, `writable`)
1848 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1849 intval($importer['uid']),
1850 DBA::escape(DateTimeFormat::utcNow()),
1852 DBA::escape(normalise_link($url)),
1855 DBA::escape($photo),
1856 DBA::escape($network),
1857 intval(self::FOLLOWER)
1861 'id' => DBA::lastInsertId(),
1862 'network' => $network,
1868 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1870 /// @TODO Encapsulate this into a function/method
1871 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1872 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1873 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1874 // create notification
1875 $hash = random_string();
1877 if (is_array($contact_record)) {
1878 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1879 'blocked' => false, 'knowyou' => false,
1880 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1883 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1885 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1886 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1889 'type' => NOTIFY_INTRO,
1890 'notify_flags' => $user['notify-flags'],
1891 'language' => $user['language'],
1892 'to_name' => $user['username'],
1893 'to_email' => $user['email'],
1894 'uid' => $user['uid'],
1895 'link' => System::baseUrl() . '/notifications/intro',
1896 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1897 'source_link' => $contact_record['url'],
1898 'source_photo' => $contact_record['photo'],
1899 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1904 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1905 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1906 DBA::update('contact', ['pending' => false], $condition);
1911 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1913 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1914 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1916 Contact::remove($contact['id']);
1920 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1922 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1923 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1925 Contact::remove($contact['id']);
1930 * @brief Create a birthday event.
1932 * Update the year and the birthday.
1934 public static function updateBirthdays()
1936 // This only handles foreign or alien networks where a birthday has been provided.
1937 // In-network birthdays are handled within local_delivery
1939 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1940 if (DBA::isResult($r)) {
1941 foreach ($r as $rr) {
1942 logger('update_contact_birthday: ' . $rr['bd']);
1944 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1947 * Add new birthday event for this person
1949 * $bdtext is just a readable placeholder in case the event is shared
1950 * with others. We will replace it during presentation to our $importer
1951 * to contain a sparkle link and perhaps a photo.
1954 // Check for duplicates
1955 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1956 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1957 if (DBA::exists('event', $condition)) {
1961 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1962 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1964 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1965 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1966 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1967 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1972 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1973 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1980 * Remove the unavailable contact ids from the provided list
1982 * @param array $contact_ids Contact id list
1984 public static function pruneUnavailable(array &$contact_ids)
1986 if (empty($contact_ids)) {
1990 $str = DBA::escape(implode(',', $contact_ids));
1992 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1995 while($contact = DBA::fetch($stmt)) {
1996 $return[] = $contact['id'];
2001 $contact_ids = $return;
2005 * @brief Returns a magic link to authenticate remote visitors
2007 * @param string $contact_url The address of the target contact profile
2008 * @param integer $url An url that we will be redirected to after the authentication
2010 * @return string with "redir" link
2012 public static function magicLink($contact_url, $url = '')
2014 $cid = self::getIdForURL($contact_url, 0, true);
2016 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2019 return self::magicLinkbyId($cid, $url);
2023 * @brief Returns a magic link to authenticate remote visitors
2025 * @param integer $cid The contact id of the target contact profile
2026 * @param integer $url An url that we will be redirected to after the authentication
2028 * @return string with "redir" link
2030 public static function magicLinkbyId($cid, $url = '')
2032 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2034 return self::magicLinkbyContact($contact, $url);
2038 * @brief Returns a magic link to authenticate remote visitors
2040 * @param array $contact The contact array with "uid", "network" and "url"
2041 * @param integer $url An url that we will be redirected to after the authentication
2043 * @return string with "redir" link
2045 public static function magicLinkbyContact($contact, $url = '')
2047 if ($contact['network'] != Protocol::DFRN) {
2048 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2051 // Only redirections to the same host do make sense
2052 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2056 if ($contact['uid'] != 0) {
2057 return self::magicLink($contact['url'], $url);
2060 $redirect = 'redir/' . $contact['id'];
2063 $redirect .= '?url=' . $url;