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 a list of contacts belonging in a group
103 public static function getByGroupId($gid)
108 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
110 INNER JOIN `group_member`
111 ON `contact`.`id` = `group_member`.`contact-id`
113 AND `contact`.`uid` = ?
114 AND NOT `contact`.`self`
115 AND NOT `contact`.`blocked`
116 AND NOT `contact`.`pending`
117 ORDER BY `contact`.`name` ASC',
122 if (DBA::isResult($stmt)) {
123 $return = DBA::toArray($stmt);
131 * @brief Returns the count of OStatus contacts in a group
136 public static function getOStatusCountByGroupId($gid)
140 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
142 INNER JOIN `group_member`
143 ON `contact`.`id` = `group_member`.`contact-id`
145 AND `contact`.`uid` = ?
146 AND `contact`.`network` = ?
147 AND `contact`.`notify` != ""',
152 $return = $contacts['count'];
159 * Creates the self-contact for the provided user id
162 * @return bool Operation success
164 public static function createSelfFromUserId($uid)
166 // Only create the entry if it doesn't exist yet
167 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
171 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
172 if (!DBA::isResult($user)) {
176 $return = DBA::insert('contact', [
177 'uid' => $user['uid'],
178 'created' => DateTimeFormat::utcNow(),
180 'name' => $user['username'],
181 'nick' => $user['nickname'],
182 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
183 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
184 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
187 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
188 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
189 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
190 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
191 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
192 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
193 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
194 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
195 'name-date' => DateTimeFormat::utcNow(),
196 'uri-date' => DateTimeFormat::utcNow(),
197 'avatar-date' => DateTimeFormat::utcNow(),
205 * Updates the self-contact for the provided user id
208 * @param boolean $update_avatar Force the avatar update
210 public static function updateSelfFromUserID($uid, $update_avatar = false)
212 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
213 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
214 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
215 if (!DBA::isResult($self)) {
219 $fields = ['nickname', 'page-flags', 'account-type'];
220 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
221 if (!DBA::isResult($user)) {
225 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
226 'country-name', 'gender', 'pub_keywords', 'xmpp'];
227 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
228 if (!DBA::isResult($profile)) {
232 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
233 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
234 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
235 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
236 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
238 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
239 if (DBA::isResult($avatar)) {
240 if ($update_avatar) {
241 $fields['avatar-date'] = DateTimeFormat::utcNow();
244 // Creating the path to the avatar, beginning with the file suffix
245 $types = Image::supportedTypes();
246 if (isset($types[$avatar['type']])) {
247 $file_suffix = $types[$avatar['type']];
249 $file_suffix = 'jpg';
252 // We are adding a timestamp value so that other systems won't use cached content
253 $timestamp = strtotime($fields['avatar-date']);
255 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
256 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
258 $fields['photo'] = $prefix . '4' . $suffix;
259 $fields['thumb'] = $prefix . '5' . $suffix;
260 $fields['micro'] = $prefix . '6' . $suffix;
262 // We hadn't found a photo entry, so we use the default avatar
263 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
264 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
265 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
268 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
269 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
271 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
272 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
273 $fields['nurl'] = normalise_link($fields['url']);
274 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
275 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
276 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
277 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
278 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
279 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
283 foreach ($fields as $field => $content) {
284 if (isset($self[$field]) && $self[$field] != $content) {
290 $fields['name-date'] = DateTimeFormat::utcNow();
291 DBA::update('contact', $fields, ['id' => $self['id']]);
293 // Update the public contact as well
294 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
296 // Update the profile
297 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
298 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
299 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
304 * @brief Marks a contact for removal
306 * @param int $id contact id
309 public static function remove($id)
311 // We want just to make sure that we don't delete our "self" contact
312 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
313 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
317 // Archive the contact
318 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM], ['id' => $id]);
320 // Delete it in the background
321 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
325 * @brief Sends an unfriend message. Does not remove the contact
327 * @param array $user User unfriending
328 * @param array $contact Contact unfriended
331 public static function terminateFriendship(array $user, array $contact)
333 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
334 // create an unfollow slap
336 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
337 $item['follow'] = $contact["url"];
342 $item['attach'] = '';
343 $slap = OStatus::salmon($item, $user);
345 if (!empty($contact['notify'])) {
346 Salmon::slapper($user, $contact['notify'], $slap);
348 } elseif ($contact['network'] == Protocol::DIASPORA) {
349 Diaspora::sendUnshare($user, $contact);
354 * @brief Marks a contact for archival after a communication issue delay
356 * Contact has refused to recognise us as a friend. We will start a countdown.
357 * If they still don't recognise us in 32 days, the relationship is over,
358 * and we won't waste any more time trying to communicate with them.
359 * This provides for the possibility that their database is temporarily messed
360 * up or some other transient event and that there's a possibility we could recover from it.
362 * @param array $contact contact to mark for archival
365 public static function markForArchival(array $contact)
367 // Contact already archived or "self" contact? => nothing to do
368 if ($contact['archive'] || $contact['self']) {
372 if ($contact['term-date'] <= NULL_DATE) {
373 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
375 if ($contact['url'] != '') {
376 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
380 * We really should send a notification to the owner after 2-3 weeks
381 * so they won't be surprised when the contact vanishes and can take
382 * remedial action if this was a serious mistake or glitch
385 /// @todo Check for contact vitality via probing
386 $archival_days = Config::get('system', 'archival_days', 32);
388 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
389 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
390 /* Relationship is really truly dead. archive them rather than
391 * delete, though if the owner tries to unarchive them we'll start
392 * the whole process over again.
394 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
396 if ($contact['url'] != '') {
397 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
404 * @brief Cancels the archival countdown
406 * @see Contact::markForArchival()
408 * @param array $contact contact to be unmarked for archival
411 public static function unmarkForArchival(array $contact)
413 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
414 $exists = DBA::exists('contact', $condition);
416 // We don't need to update, we never marked this contact for archival
421 // It's a miracle. Our dead contact has inexplicably come back to life.
422 $fields = ['term-date' => NULL_DATE, 'archive' => false];
423 DBA::update('contact', $fields, ['id' => $contact['id']]);
425 if (!empty($contact['url'])) {
426 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
429 if (!empty($contact['batch'])) {
430 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
431 DBA::update('contact', $fields, $condition);
436 * @brief Get contact data for a given profile link
438 * The function looks at several places (contact table and gcontact table) for the contact
439 * It caches its result for the same script execution to prevent duplicate calls
441 * @param string $url The profile link
442 * @param int $uid User id
443 * @param array $default If not data was found take this data as default value
445 * @return array Contact data
447 public static function getDetailsByURL($url, $uid = -1, array $default = [])
459 if (isset($cache[$url][$uid])) {
460 return $cache[$url][$uid];
463 $ssl_url = str_replace('http://', 'https://', $url);
465 // Fetch contact data from the contact table for the given user
466 $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`,
467 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
468 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
469 $r = DBA::toArray($s);
471 // Fetch contact data from the contact table for the given user, checking with the alias
472 if (!DBA::isResult($r)) {
473 $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`,
474 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
475 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
476 $r = DBA::toArray($s);
479 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
480 if (!DBA::isResult($r)) {
481 $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`,
482 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
483 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
484 $r = DBA::toArray($s);
487 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
488 if (!DBA::isResult($r)) {
489 $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`,
490 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
491 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
492 $r = DBA::toArray($s);
495 // Fetch the data from the gcontact table
496 if (!DBA::isResult($r)) {
497 $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`,
498 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
499 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
500 $r = DBA::toArray($s);
503 if (DBA::isResult($r)) {
504 // If there is more than one entry we filter out the connector networks
506 foreach ($r as $id => $result) {
507 if ($result["network"] == Protocol::STATUSNET) {
513 $profile = array_shift($r);
515 // "bd" always contains the upcoming birthday of a contact.
516 // "birthday" might contain the birthday including the year of birth.
517 if ($profile["birthday"] > '0001-01-01') {
518 $bd_timestamp = strtotime($profile["birthday"]);
519 $month = date("m", $bd_timestamp);
520 $day = date("d", $bd_timestamp);
522 $current_timestamp = time();
523 $current_year = date("Y", $current_timestamp);
524 $current_month = date("m", $current_timestamp);
525 $current_day = date("d", $current_timestamp);
527 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
528 $current = $current_year . "-" . $current_month . "-" . $current_day;
530 if ($profile["bd"] < $current) {
531 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
534 $profile["bd"] = '0001-01-01';
540 if (empty($profile["photo"]) && isset($default["photo"])) {
541 $profile["photo"] = $default["photo"];
544 if (empty($profile["name"]) && isset($default["name"])) {
545 $profile["name"] = $default["name"];
548 if (empty($profile["network"]) && isset($default["network"])) {
549 $profile["network"] = $default["network"];
552 if (empty($profile["thumb"]) && isset($profile["photo"])) {
553 $profile["thumb"] = $profile["photo"];
556 if (empty($profile["micro"]) && isset($profile["thumb"])) {
557 $profile["micro"] = $profile["thumb"];
560 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
561 && in_array($profile["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
563 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
566 // Show contact details of Diaspora contacts only if connected
567 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
568 $profile["location"] = "";
569 $profile["about"] = "";
570 $profile["gender"] = "";
571 $profile["birthday"] = '0001-01-01';
574 $cache[$url][$uid] = $profile;
580 * @brief Get contact data for a given address
582 * The function looks at several places (contact table and gcontact table) for the contact
584 * @param string $addr The profile link
585 * @param int $uid User id
587 * @return array Contact data
589 public static function getDetailsByAddr($addr, $uid = -1)
601 // Fetch contact data from the contact table for the given user
602 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
603 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
604 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
608 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
609 if (!DBA::isResult($r)) {
610 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
611 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
612 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
617 // Fetch the data from the gcontact table
618 if (!DBA::isResult($r)) {
619 $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`,
620 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
621 FROM `gcontact` WHERE `addr` = '%s'",
626 if (!DBA::isResult($r)) {
627 $data = Probe::uri($addr);
629 $profile = self::getDetailsByURL($data['url'], $uid);
638 * @brief Returns the data array for the photo menu of a given contact
640 * @param array $contact contact
641 * @param int $uid optional, default 0
644 public static function photoMenu(array $contact, $uid = 0)
646 // @todo Unused, to be removed
654 $contact_drop_link = '';
661 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
663 $profile_link = self::magicLink($contact['url']);
664 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
669 // Look for our own contact if the uid doesn't match and isn't public
670 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
671 if (DBA::isResult($contact_own)) {
672 return self::photoMenu($contact_own, $uid);
674 $profile_link = self::magicLink($contact['url']);
675 $connlnk = 'follow/?url=' . $contact['url'];
677 'profile' => [L10n::t('View Profile'), $profile_link, true],
678 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
686 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
688 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
690 $profile_link = $contact['url'];
693 if ($profile_link === 'mailbox') {
698 $status_link = $profile_link . '?url=status';
699 $photos_link = $profile_link . '?url=photos';
700 $profile_link = $profile_link . '?url=profile';
703 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
704 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
707 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
708 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
711 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
713 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
715 if (!$contact['self']) {
716 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
721 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
724 'status' => [L10n::t("View Status") , $status_link , true],
725 'profile' => [L10n::t("View Profile") , $profile_link , true],
726 'photos' => [L10n::t("View Photos") , $photos_link , true],
727 'network' => [L10n::t("Network Posts"), $posts_link , false],
728 'edit' => [L10n::t("View Contact") , $contact_url , false],
729 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
730 'pm' => [L10n::t("Send PM") , $pm_url , false],
731 'poke' => [L10n::t("Poke") , $poke_link , false],
734 $args = ['contact' => $contact, 'menu' => &$menu];
736 Addon::callHooks('contact_photo_menu', $args);
740 foreach ($menu as $menuname => $menuitem) {
741 if ($menuitem[1] != '') {
742 $menucondensed[$menuname] = $menuitem;
746 return $menucondensed;
750 * @brief Returns ungrouped contact count or list for user
752 * Returns either the total number of ungrouped contacts for the given user
753 * id or a paginated list of ungrouped contacts.
755 * @param int $uid uid
756 * @param int $start optional, default 0
757 * @param int $count optional, default 0
761 public static function getUngroupedList($uid)
770 SELECT DISTINCT(`contact-id`)
772 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
773 WHERE `group`.`uid` = %d
774 )", intval($uid), intval($uid));
778 * @brief Fetch the contact id for a given URL and user
780 * First lookup in the contact table to find a record matching either `url`, `nurl`,
783 * If there's no record and we aren't looking for a public contact, we quit.
784 * If there's one, we check that it isn't time to update the picture else we
785 * directly return the found contact id.
787 * Second, we probe the provided $url whether it's http://server.tld/profile or
788 * nick@server.tld. We quit if we can't get any info back.
790 * Third, we create the contact record if it doesn't exist
792 * Fourth, we update the existing record with the new data (avatar, alias, nick)
793 * if there's any updates
795 * @param string $url Contact URL
796 * @param integer $uid The user id for the contact (0 = public contact)
797 * @param boolean $no_update Don't update the contact
798 * @param array $default Default value for creating the contact when every else fails
800 * @return integer Contact ID
802 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
804 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
812 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
813 // We first try the nurl (http://server.tld/nick), most common case
814 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
816 // Then the addr (nick@server.tld)
817 if (!DBA::isResult($contact)) {
818 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
821 // Then the alias (which could be anything)
822 if (!DBA::isResult($contact)) {
823 // The link could be provided as http although we stored it as https
824 $ssl_url = str_replace('http://', 'https://', $url);
825 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
826 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
829 if (DBA::isResult($contact)) {
830 $contact_id = $contact["id"];
832 // Update the contact every 7 days
833 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
835 // We force the update if the avatar is empty
836 if (!x($contact, 'avatar')) {
837 $update_contact = true;
840 if (!$update_contact || $no_update) {
843 } elseif ($uid != 0) {
844 // Non-existing user-specific contact, exiting
848 // When we don't want to update, we look if some of our users already know this contact
850 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
851 'photo', 'keywords', 'location', 'about', 'network',
852 'priority', 'batch', 'request', 'confirm', 'poco'];
853 $data = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
855 if (DBA::isResult($data)) {
856 // For security reasons we don't fetch key data from our users
857 $data["pubkey"] = '';
864 $data = Probe::uri($url, "", $uid);
867 // Last try in gcontact for unsupported networks
868 if (!in_array($data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
873 // Get data from the gcontact table
874 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
875 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
876 if (!DBA::isResult($contact)) {
877 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
880 if (!DBA::isResult($contact)) {
881 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
882 'photo', 'keywords', 'location', 'about', 'network',
883 'priority', 'batch', 'request', 'confirm', 'poco'];
884 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
887 if (!DBA::isResult($contact)) {
888 // The link could be provided as http although we stored it as https
889 $ssl_url = str_replace('http://', 'https://', $url);
890 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
891 $contact = DBA::selectFirst('contact', $fields, $condition);
894 if (!DBA::isResult($contact)) {
895 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
896 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
897 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
898 $contact = DBA::selectFirst('fcontact', $fields, $condition);
901 if (!empty($default)) {
905 if (!DBA::isResult($contact)) {
908 $data = array_merge($data, $contact);
912 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
913 $contact_id = self::getIdForURL($data["alias"], $uid, true);
918 DBA::insert('contact', [
920 'created' => DateTimeFormat::utcNow(),
921 'url' => $data["url"],
922 'nurl' => normalise_link($data["url"]),
923 'addr' => $data["addr"],
924 'alias' => $data["alias"],
925 'notify' => $data["notify"],
926 'poll' => $data["poll"],
927 'name' => $data["name"],
928 'nick' => $data["nick"],
929 'photo' => $data["photo"],
930 'keywords' => $data["keywords"],
931 'location' => $data["location"],
932 'about' => $data["about"],
933 'network' => $data["network"],
934 'pubkey' => $data["pubkey"],
935 'rel' => self::SHARING,
936 'priority' => $data["priority"],
937 'batch' => $data["batch"],
938 'request' => $data["request"],
939 'confirm' => $data["confirm"],
940 'poco' => $data["poco"],
941 'name-date' => DateTimeFormat::utcNow(),
942 'uri-date' => DateTimeFormat::utcNow(),
943 'avatar-date' => DateTimeFormat::utcNow(),
950 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
951 $contacts = DBA::toArray($s);
952 if (!DBA::isResult($contacts)) {
956 $contact_id = $contacts[0]["id"];
958 // Update the newly created contact from data in the gcontact table
959 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
960 if (DBA::isResult($gcontact)) {
961 // Only use the information when the probing hadn't fetched these values
962 if ($data['keywords'] != '') {
963 unset($gcontact['keywords']);
965 if ($data['location'] != '') {
966 unset($gcontact['location']);
968 if ($data['about'] != '') {
969 unset($gcontact['about']);
971 DBA::update('contact', $gcontact, ['id' => $contact_id]);
974 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
975 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
976 normalise_link($data["url"]), $contact_id]);
980 self::updateAvatar($data["photo"], $uid, $contact_id);
982 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
983 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
985 // This condition should always be true
986 if (!DBA::isResult($contact)) {
990 $updated = ['addr' => $data['addr'],
991 'alias' => $data['alias'],
992 'url' => $data['url'],
993 'nurl' => normalise_link($data['url']),
994 'name' => $data['name'],
995 'nick' => $data['nick']];
997 if ($data['keywords'] != '') {
998 $updated['keywords'] = $data['keywords'];
1000 if ($data['location'] != '') {
1001 $updated['location'] = $data['location'];
1004 // Update the technical stuff as well - if filled
1005 if ($data['notify'] != '') {
1006 $updated['notify'] = $data['notify'];
1008 if ($data['poll'] != '') {
1009 $updated['poll'] = $data['poll'];
1011 if ($data['batch'] != '') {
1012 $updated['batch'] = $data['batch'];
1014 if ($data['request'] != '') {
1015 $updated['request'] = $data['request'];
1017 if ($data['confirm'] != '') {
1018 $updated['confirm'] = $data['confirm'];
1020 if ($data['poco'] != '') {
1021 $updated['poco'] = $data['poco'];
1024 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1025 if (empty($contact['pubkey'])) {
1026 $updated['pubkey'] = $data['pubkey'];
1029 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1030 $updated['uri-date'] = DateTimeFormat::utcNow();
1032 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1033 $updated['name-date'] = DateTimeFormat::utcNow();
1036 $updated['avatar-date'] = DateTimeFormat::utcNow();
1038 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1044 * @brief Checks if the contact is blocked
1046 * @param int $cid contact id
1048 * @return boolean Is the contact blocked?
1050 public static function isBlocked($cid)
1056 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1057 if (!DBA::isResult($blocked)) {
1060 return (bool) $blocked['blocked'];
1064 * @brief Checks if the contact is hidden
1066 * @param int $cid contact id
1068 * @return boolean Is the contact hidden?
1070 public static function isHidden($cid)
1076 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1077 if (!DBA::isResult($hidden)) {
1080 return (bool) $hidden['hidden'];
1084 * @brief Returns posts from a given contact url
1086 * @param string $contact_url Contact URL
1088 * @return string posts in HTML
1090 public static function getPostsFromUrl($contact_url)
1092 $a = self::getApp();
1094 require_once 'include/conversation.php';
1096 // There are no posts with "uid = 0" with connector networks
1097 // This speeds up the query a lot
1098 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1099 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1100 DBA::escape(normalise_link($contact_url))
1103 if (!DBA::isResult($r)) {
1107 if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1108 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1110 $sql = "`item`.`uid` = ?";
1113 $author_id = intval($r[0]["author-id"]);
1115 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1117 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1118 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1119 $params = ['order' => ['created' => true],
1120 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1121 $r = Item::selectForUser(local_user(), [], $condition, $params);
1123 $items = Item::inArray($r);
1125 $o = conversation($a, $items, 'contact-posts', false);
1127 $o .= alt_pager($a, count($items));
1133 * @brief Returns the account type name
1135 * The function can be called with either the user or the contact array
1137 * @param array $contact contact or user array
1140 public static function getAccountType(array $contact)
1142 // There are several fields that indicate that the contact or user is a forum
1143 // "page-flags" is a field in the user table,
1144 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1145 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1146 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1147 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1148 || (isset($contact['forum']) && intval($contact['forum']))
1149 || (isset($contact['prv']) && intval($contact['prv']))
1150 || (isset($contact['community']) && intval($contact['community']))
1152 $type = self::ACCOUNT_TYPE_COMMUNITY;
1154 $type = self::ACCOUNT_TYPE_PERSON;
1157 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1158 if (isset($contact["contact-type"])) {
1159 $type = $contact["contact-type"];
1162 if (isset($contact["account-type"])) {
1163 $type = $contact["account-type"];
1167 case self::ACCOUNT_TYPE_ORGANISATION:
1168 $account_type = L10n::t("Organisation");
1171 case self::ACCOUNT_TYPE_NEWS:
1172 $account_type = L10n::t('News');
1175 case self::ACCOUNT_TYPE_COMMUNITY:
1176 $account_type = L10n::t("Forum");
1184 return $account_type;
1188 * @brief Blocks a contact
1193 public static function block($uid)
1195 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1201 * @brief Unblocks a contact
1206 public static function unblock($uid)
1208 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1214 * @brief Updates the avatar links in a contact only if needed
1216 * @param string $avatar Link to avatar picture
1217 * @param int $uid User id of contact owner
1218 * @param int $cid Contact id
1219 * @param bool $force force picture update
1221 * @return array Returns array of the different avatar sizes
1223 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1225 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1226 if (!DBA::isResult($contact)) {
1229 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1232 if (($contact["avatar"] != $avatar) || $force) {
1233 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1238 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1242 // Update the public contact (contact id = 0)
1244 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1245 if (DBA::isResult($pcontact)) {
1246 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1258 * @param integer $id contact id
1261 public static function updateFromProbe($id)
1264 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1265 This will reliably kill your communication with Friendica contacts.
1268 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1269 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1270 if (!DBA::isResult($contact)) {
1274 $ret = Probe::uri($contact["url"]);
1276 // If Probe::uri fails the network code will be different
1277 if ($ret["network"] != $contact["network"]) {
1283 // make sure to not overwrite existing values with blank entries
1284 foreach ($ret as $key => $val) {
1285 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1286 $ret[$key] = $contact[$key];
1289 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1300 'url' => $ret['url'],
1301 'nurl' => normalise_link($ret['url']),
1302 'addr' => $ret['addr'],
1303 'alias' => $ret['alias'],
1304 'batch' => $ret['batch'],
1305 'notify' => $ret['notify'],
1306 'poll' => $ret['poll'],
1307 'poco' => $ret['poco']
1312 // Update the corresponding gcontact entry
1313 PortableContact::lastUpdated($ret["url"]);
1319 * Takes a $uid and a url/handle and adds a new contact
1320 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1321 * dfrn_request page.
1323 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1326 * $return['success'] boolean true if successful
1327 * $return['message'] error text if success is false.
1329 * @brief Takes a $uid and a url/handle and adds a new contact
1331 * @param string $url
1332 * @param bool $interactive
1333 * @param string $network
1334 * @return boolean|string
1336 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1338 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1342 // remove ajax junk, e.g. Twitter
1343 $url = str_replace('/#!/', '/', $url);
1345 if (!Network::isUrlAllowed($url)) {
1346 $result['message'] = L10n::t('Disallowed profile URL.');
1350 if (Network::isUrlBlocked($url)) {
1351 $result['message'] = L10n::t('Blocked domain');
1356 $result['message'] = L10n::t('Connect URL missing.');
1360 $arr = ['url' => $url, 'contact' => []];
1362 Addon::callHooks('follow', $arr);
1365 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1369 if (x($arr['contact'], 'name')) {
1370 $ret = $arr['contact'];
1372 $ret = Probe::uri($url, $network, $uid, false);
1375 if (($network != '') && ($ret['network'] != $network)) {
1376 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1380 // check if we already have a contact
1381 // the poll url is more reliable than the profile url, as we may have
1382 // indirect links or webfinger links
1384 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1386 DBA::escape($ret['poll']),
1387 DBA::escape(normalise_link($ret['poll'])),
1388 DBA::escape($ret['network'])
1391 if (!DBA::isResult($r)) {
1392 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1394 DBA::escape(normalise_link($url)),
1395 DBA::escape($ret['network'])
1399 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($r)) {
1401 if (strlen($a->urlpath)) {
1402 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1404 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1407 goaway($ret['request'] . "&addr=$myaddr");
1411 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1412 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1413 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1417 // This extra param just confuses things, remove it
1418 if ($ret['network'] === Protocol::DIASPORA) {
1419 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1422 // do we have enough information?
1424 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1425 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1426 if (!x($ret, 'poll')) {
1427 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1429 if (!x($ret, 'name')) {
1430 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1432 if (!x($ret, 'url')) {
1433 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1435 if (strpos($url, '@') !== false) {
1436 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1437 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1442 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1443 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1444 $ret['notify'] = '';
1447 if (!$ret['notify']) {
1448 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1451 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1453 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1455 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1457 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA])) {
1461 if (DBA::isResult($r)) {
1463 $new_relation = (($r[0]['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1465 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1466 DBA::update('contact', $fields, ['id' => $r[0]['id']]);
1468 $new_relation = ((in_array($ret['network'], [Protocol::MAIL])) ? self::FRIEND : self::SHARING);
1470 // create contact record
1471 DBA::insert('contact', [
1473 'created' => DateTimeFormat::utcNow(),
1474 'url' => $ret['url'],
1475 'nurl' => normalise_link($ret['url']),
1476 'addr' => $ret['addr'],
1477 'alias' => $ret['alias'],
1478 'batch' => $ret['batch'],
1479 'notify' => $ret['notify'],
1480 'poll' => $ret['poll'],
1481 'poco' => $ret['poco'],
1482 'name' => $ret['name'],
1483 'nick' => $ret['nick'],
1484 'network' => $ret['network'],
1485 'pubkey' => $ret['pubkey'],
1486 'rel' => $new_relation,
1487 'priority'=> $ret['priority'],
1488 'writable'=> $writeable,
1489 'hidden' => $hidden,
1497 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1498 if (!DBA::isResult($contact)) {
1499 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1503 $contact_id = $contact['id'];
1504 $result['cid'] = $contact_id;
1506 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1508 // Update the avatar
1509 self::updateAvatar($ret['photo'], $uid, $contact_id);
1511 // pull feed and consume it, which should subscribe to the hub.
1513 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1515 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1516 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1520 if (DBA::isResult($r)) {
1521 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1522 // create a follow slap
1524 $item['verb'] = ACTIVITY_FOLLOW;
1525 $item['follow'] = $contact["url"];
1527 $item['title'] = '';
1530 $item['attach'] = '';
1531 $slap = OStatus::salmon($item, $r[0]);
1532 if (!empty($contact['notify'])) {
1533 Salmon::slapper($r[0], $contact['notify'], $slap);
1535 } elseif ($contact['network'] == Protocol::DIASPORA) {
1536 $ret = Diaspora::sendShare($a->user, $contact);
1537 logger('share returns: ' . $ret);
1541 $result['success'] = true;
1545 public static function updateSslPolicy($contact, $new_policy)
1547 $ssl_changed = false;
1548 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1549 $ssl_changed = true;
1550 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1551 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1552 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1553 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1554 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1555 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1558 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1559 $ssl_changed = true;
1560 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1561 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1562 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1563 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1564 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1565 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1569 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1570 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1571 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1572 DBA::update('contact', $fields, ['id' => $contact['id']]);
1578 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1579 // Should always be set
1580 if (empty($datarray['author-id'])) {
1584 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1585 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1586 if (!DBA::isResult($pub_contact)) {
1587 // Should never happen
1591 $url = $pub_contact['url'];
1592 $name = $pub_contact['name'];
1593 $photo = $pub_contact['photo'];
1594 $nick = $pub_contact['nick'];
1595 $network = $pub_contact['network'];
1597 if (is_array($contact)) {
1598 if (($contact['rel'] == self::SHARING)
1599 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1600 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1601 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1603 // send email notification to owner?
1605 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1606 logger('ignoring duplicated connection request from pending contact ' . $url);
1610 // create contact record
1611 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1612 `blocked`, `readonly`, `pending`, `writable`)
1613 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1614 intval($importer['uid']),
1615 DBA::escape(DateTimeFormat::utcNow()),
1617 DBA::escape(normalise_link($url)),
1620 DBA::escape($photo),
1621 DBA::escape($network),
1622 intval(self::FOLLOWER)
1626 'id' => DBA::lastInsertId(),
1627 'network' => $network,
1633 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1635 /// @TODO Encapsulate this into a function/method
1636 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1637 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1638 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1639 // create notification
1640 $hash = random_string();
1642 if (is_array($contact_record)) {
1643 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1644 'blocked' => false, 'knowyou' => false,
1645 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1648 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1650 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1651 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1654 'type' => NOTIFY_INTRO,
1655 'notify_flags' => $user['notify-flags'],
1656 'language' => $user['language'],
1657 'to_name' => $user['username'],
1658 'to_email' => $user['email'],
1659 'uid' => $user['uid'],
1660 'link' => System::baseUrl() . '/notifications/intro',
1661 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1662 'source_link' => $contact_record['url'],
1663 'source_photo' => $contact_record['photo'],
1664 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1669 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1670 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1671 intval($importer['uid']),
1678 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1680 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1681 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1683 Contact::remove($contact['id']);
1687 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1689 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1690 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1692 Contact::remove($contact['id']);
1697 * @brief Create a birthday event.
1699 * Update the year and the birthday.
1701 public static function updateBirthdays()
1703 // This only handles foreign or alien networks where a birthday has been provided.
1704 // In-network birthdays are handled within local_delivery
1706 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1707 if (DBA::isResult($r)) {
1708 foreach ($r as $rr) {
1709 logger('update_contact_birthday: ' . $rr['bd']);
1711 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1714 * Add new birthday event for this person
1716 * $bdtext is just a readable placeholder in case the event is shared
1717 * with others. We will replace it during presentation to our $importer
1718 * to contain a sparkle link and perhaps a photo.
1721 // Check for duplicates
1722 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1723 intval($rr['uid']), intval($rr['id']), DBA::escape(DateTimeFormat::utc($nextbd)), DBA::escape('birthday'));
1725 if (DBA::isResult($s)) {
1729 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1730 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1732 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1733 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1734 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1735 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1741 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1742 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1749 * Remove the unavailable contact ids from the provided list
1751 * @param array $contact_ids Contact id list
1753 public static function pruneUnavailable(array &$contact_ids)
1755 if (empty($contact_ids)) {
1759 $str = DBA::escape(implode(',', $contact_ids));
1761 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1764 while($contact = DBA::fetch($stmt)) {
1765 $return[] = $contact['id'];
1770 $contact_ids = $return;
1774 * @brief Returns a magic link to authenticate remote visitors
1776 * @param string $contact_url The address of the target contact profile
1777 * @param integer $url An url that we will be redirected to after the authentication
1779 * @return string with "redir" link
1781 public static function magicLink($contact_url, $url = '')
1783 $cid = self::getIdForURL($contact_url, 0, true);
1785 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
1788 return self::magicLinkbyId($cid, $url);
1792 * @brief Returns a magic link to authenticate remote visitors
1794 * @param integer $cid The contact id of the target contact profile
1795 * @param integer $url An url that we will be redirected to after the authentication
1797 * @return string with "redir" link
1799 public static function magicLinkbyId($cid, $url = '')
1801 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
1803 return self::magicLinkbyContact($contact, $url);
1807 * @brief Returns a magic link to authenticate remote visitors
1809 * @param array $contact The contact array with "uid", "network" and "url"
1810 * @param integer $url An url that we will be redirected to after the authentication
1812 * @return string with "redir" link
1814 public static function magicLinkbyContact($contact, $url = '')
1816 if ($contact['network'] != Protocol::DFRN) {
1817 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
1820 // Only redirections to the same host do make sense
1821 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1825 if ($contact['uid'] != 0) {
1826 return self::magicLink($contact['url'], $url);
1829 $redirect = 'redir/' . $contact['id'];
1832 $redirect .= '?url=' . $url;