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 if (!isset($contact['url']) && !empty($contact['id'])) {
368 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
369 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
370 if (!DBA::isResult($contact)) {
373 } elseif (!isset($contact['url'])) {
374 logger('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), LOGGER_DEBUG);
377 // Contact already archived or "self" contact? => nothing to do
378 if ($contact['archive'] || $contact['self']) {
382 if ($contact['term-date'] <= NULL_DATE) {
383 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
384 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
387 * We really should send a notification to the owner after 2-3 weeks
388 * so they won't be surprised when the contact vanishes and can take
389 * remedial action if this was a serious mistake or glitch
392 /// @todo Check for contact vitality via probing
393 $archival_days = Config::get('system', 'archival_days', 32);
395 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
396 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
397 /* Relationship is really truly dead. archive them rather than
398 * delete, though if the owner tries to unarchive them we'll start
399 * the whole process over again.
401 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
402 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
408 * @brief Cancels the archival countdown
410 * @see Contact::markForArchival()
412 * @param array $contact contact to be unmarked for archival
415 public static function unmarkForArchival(array $contact)
417 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
418 $exists = DBA::exists('contact', $condition);
420 // We don't need to update, we never marked this contact for archival
425 if (!isset($contact['url']) && !empty($contact['id'])) {
426 $fields = ['id', 'url', 'batch'];
427 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
428 if (!DBA::isResult($contact)) {
433 // It's a miracle. Our dead contact has inexplicably come back to life.
434 $fields = ['term-date' => NULL_DATE, 'archive' => false];
435 DBA::update('contact', $fields, ['id' => $contact['id']]);
436 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
438 if (!empty($contact['batch'])) {
439 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
440 DBA::update('contact', $fields, $condition);
445 * @brief Get contact data for a given profile link
447 * The function looks at several places (contact table and gcontact table) for the contact
448 * It caches its result for the same script execution to prevent duplicate calls
450 * @param string $url The profile link
451 * @param int $uid User id
452 * @param array $default If not data was found take this data as default value
454 * @return array Contact data
456 public static function getDetailsByURL($url, $uid = -1, array $default = [])
468 if (isset($cache[$url][$uid])) {
469 return $cache[$url][$uid];
472 $ssl_url = str_replace('http://', 'https://', $url);
474 // Fetch contact data from the contact table for the given user
475 $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`,
476 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
477 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
478 $r = DBA::toArray($s);
480 // Fetch contact data from the contact table for the given user, checking with the alias
481 if (!DBA::isResult($r)) {
482 $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`,
483 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
484 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
485 $r = DBA::toArray($s);
488 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
489 if (!DBA::isResult($r)) {
490 $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`,
491 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
492 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
493 $r = DBA::toArray($s);
496 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
497 if (!DBA::isResult($r)) {
498 $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`,
499 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
500 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
501 $r = DBA::toArray($s);
504 // Fetch the data from the gcontact table
505 if (!DBA::isResult($r)) {
506 $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`,
507 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
508 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
509 $r = DBA::toArray($s);
512 if (DBA::isResult($r)) {
513 // If there is more than one entry we filter out the connector networks
515 foreach ($r as $id => $result) {
516 if ($result["network"] == Protocol::STATUSNET) {
522 $profile = array_shift($r);
524 // "bd" always contains the upcoming birthday of a contact.
525 // "birthday" might contain the birthday including the year of birth.
526 if ($profile["birthday"] > '0001-01-01') {
527 $bd_timestamp = strtotime($profile["birthday"]);
528 $month = date("m", $bd_timestamp);
529 $day = date("d", $bd_timestamp);
531 $current_timestamp = time();
532 $current_year = date("Y", $current_timestamp);
533 $current_month = date("m", $current_timestamp);
534 $current_day = date("d", $current_timestamp);
536 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
537 $current = $current_year . "-" . $current_month . "-" . $current_day;
539 if ($profile["bd"] < $current) {
540 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
543 $profile["bd"] = '0001-01-01';
549 if (empty($profile["photo"]) && isset($default["photo"])) {
550 $profile["photo"] = $default["photo"];
553 if (empty($profile["name"]) && isset($default["name"])) {
554 $profile["name"] = $default["name"];
557 if (empty($profile["network"]) && isset($default["network"])) {
558 $profile["network"] = $default["network"];
561 if (empty($profile["thumb"]) && isset($profile["photo"])) {
562 $profile["thumb"] = $profile["photo"];
565 if (empty($profile["micro"]) && isset($profile["thumb"])) {
566 $profile["micro"] = $profile["thumb"];
569 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
570 && in_array($profile["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
572 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
575 // Show contact details of Diaspora contacts only if connected
576 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
577 $profile["location"] = "";
578 $profile["about"] = "";
579 $profile["gender"] = "";
580 $profile["birthday"] = '0001-01-01';
583 $cache[$url][$uid] = $profile;
589 * @brief Get contact data for a given address
591 * The function looks at several places (contact table and gcontact table) for the contact
593 * @param string $addr The profile link
594 * @param int $uid User id
596 * @return array Contact data
598 public static function getDetailsByAddr($addr, $uid = -1)
610 // Fetch contact data from the contact table for the given user
611 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
612 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
613 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
617 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
618 if (!DBA::isResult($r)) {
619 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
620 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
621 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
626 // Fetch the data from the gcontact table
627 if (!DBA::isResult($r)) {
628 $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`,
629 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
630 FROM `gcontact` WHERE `addr` = '%s'",
635 if (!DBA::isResult($r)) {
636 $data = Probe::uri($addr);
638 $profile = self::getDetailsByURL($data['url'], $uid);
647 * @brief Returns the data array for the photo menu of a given contact
649 * @param array $contact contact
650 * @param int $uid optional, default 0
653 public static function photoMenu(array $contact, $uid = 0)
655 // @todo Unused, to be removed
663 $contact_drop_link = '';
670 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
672 $profile_link = self::magicLink($contact['url']);
673 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
678 // Look for our own contact if the uid doesn't match and isn't public
679 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
680 if (DBA::isResult($contact_own)) {
681 return self::photoMenu($contact_own, $uid);
683 $profile_link = self::magicLink($contact['url']);
684 $connlnk = 'follow/?url=' . $contact['url'];
686 'profile' => [L10n::t('View Profile'), $profile_link, true],
687 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
695 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
697 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
699 $profile_link = $contact['url'];
702 if ($profile_link === 'mailbox') {
707 $status_link = $profile_link . '?url=status';
708 $photos_link = $profile_link . '?url=photos';
709 $profile_link = $profile_link . '?url=profile';
712 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
713 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
716 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
717 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
720 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
722 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
724 if (!$contact['self']) {
725 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
730 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
733 'status' => [L10n::t("View Status") , $status_link , true],
734 'profile' => [L10n::t("View Profile") , $profile_link , true],
735 'photos' => [L10n::t("View Photos") , $photos_link , true],
736 'network' => [L10n::t("Network Posts"), $posts_link , false],
737 'edit' => [L10n::t("View Contact") , $contact_url , false],
738 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
739 'pm' => [L10n::t("Send PM") , $pm_url , false],
740 'poke' => [L10n::t("Poke") , $poke_link , false],
743 $args = ['contact' => $contact, 'menu' => &$menu];
745 Addon::callHooks('contact_photo_menu', $args);
749 foreach ($menu as $menuname => $menuitem) {
750 if ($menuitem[1] != '') {
751 $menucondensed[$menuname] = $menuitem;
755 return $menucondensed;
759 * @brief Returns ungrouped contact count or list for user
761 * Returns either the total number of ungrouped contacts for the given user
762 * id or a paginated list of ungrouped contacts.
764 * @param int $uid uid
765 * @param int $start optional, default 0
766 * @param int $count optional, default 0
770 public static function getUngroupedList($uid)
779 SELECT DISTINCT(`contact-id`)
781 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
782 WHERE `group`.`uid` = %d
783 )", intval($uid), intval($uid));
787 * @brief Fetch the contact id for a given URL and user
789 * First lookup in the contact table to find a record matching either `url`, `nurl`,
792 * If there's no record and we aren't looking for a public contact, we quit.
793 * If there's one, we check that it isn't time to update the picture else we
794 * directly return the found contact id.
796 * Second, we probe the provided $url whether it's http://server.tld/profile or
797 * nick@server.tld. We quit if we can't get any info back.
799 * Third, we create the contact record if it doesn't exist
801 * Fourth, we update the existing record with the new data (avatar, alias, nick)
802 * if there's any updates
804 * @param string $url Contact URL
805 * @param integer $uid The user id for the contact (0 = public contact)
806 * @param boolean $no_update Don't update the contact
807 * @param array $default Default value for creating the contact when every else fails
809 * @return integer Contact ID
811 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
813 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
821 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
822 // We first try the nurl (http://server.tld/nick), most common case
823 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
825 // Then the addr (nick@server.tld)
826 if (!DBA::isResult($contact)) {
827 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
830 // Then the alias (which could be anything)
831 if (!DBA::isResult($contact)) {
832 // The link could be provided as http although we stored it as https
833 $ssl_url = str_replace('http://', 'https://', $url);
834 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
835 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
838 if (DBA::isResult($contact)) {
839 $contact_id = $contact["id"];
841 // Update the contact every 7 days
842 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
844 // We force the update if the avatar is empty
845 if (!x($contact, 'avatar')) {
846 $update_contact = true;
849 if (!$update_contact || $no_update) {
852 } elseif ($uid != 0) {
853 // Non-existing user-specific contact, exiting
857 // When we don't want to update, we look if some of our users already know this contact
859 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
860 'photo', 'keywords', 'location', 'about', 'network',
861 'priority', 'batch', 'request', 'confirm', 'poco'];
862 $data = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
864 if (DBA::isResult($data)) {
865 // For security reasons we don't fetch key data from our users
866 $data["pubkey"] = '';
873 $data = Probe::uri($url, "", $uid);
876 // Last try in gcontact for unsupported networks
877 if (!in_array($data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
882 // Get data from the gcontact table
883 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
884 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
885 if (!DBA::isResult($contact)) {
886 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
889 if (!DBA::isResult($contact)) {
890 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
891 'photo', 'keywords', 'location', 'about', 'network',
892 'priority', 'batch', 'request', 'confirm', 'poco'];
893 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
896 if (!DBA::isResult($contact)) {
897 // The link could be provided as http although we stored it as https
898 $ssl_url = str_replace('http://', 'https://', $url);
899 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
900 $contact = DBA::selectFirst('contact', $fields, $condition);
903 if (!DBA::isResult($contact)) {
904 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
905 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
906 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
907 $contact = DBA::selectFirst('fcontact', $fields, $condition);
910 if (!empty($default)) {
914 if (!DBA::isResult($contact)) {
917 $data = array_merge($data, $contact);
921 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
922 $contact_id = self::getIdForURL($data["alias"], $uid, true);
927 DBA::insert('contact', [
929 'created' => DateTimeFormat::utcNow(),
930 'url' => $data["url"],
931 'nurl' => normalise_link($data["url"]),
932 'addr' => $data["addr"],
933 'alias' => $data["alias"],
934 'notify' => $data["notify"],
935 'poll' => $data["poll"],
936 'name' => $data["name"],
937 'nick' => $data["nick"],
938 'photo' => $data["photo"],
939 'keywords' => $data["keywords"],
940 'location' => $data["location"],
941 'about' => $data["about"],
942 'network' => $data["network"],
943 'pubkey' => $data["pubkey"],
944 'rel' => self::SHARING,
945 'priority' => $data["priority"],
946 'batch' => $data["batch"],
947 'request' => $data["request"],
948 'confirm' => $data["confirm"],
949 'poco' => $data["poco"],
950 'name-date' => DateTimeFormat::utcNow(),
951 'uri-date' => DateTimeFormat::utcNow(),
952 'avatar-date' => DateTimeFormat::utcNow(),
959 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
960 $contacts = DBA::toArray($s);
961 if (!DBA::isResult($contacts)) {
965 $contact_id = $contacts[0]["id"];
967 // Update the newly created contact from data in the gcontact table
968 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
969 if (DBA::isResult($gcontact)) {
970 // Only use the information when the probing hadn't fetched these values
971 if ($data['keywords'] != '') {
972 unset($gcontact['keywords']);
974 if ($data['location'] != '') {
975 unset($gcontact['location']);
977 if ($data['about'] != '') {
978 unset($gcontact['about']);
980 DBA::update('contact', $gcontact, ['id' => $contact_id]);
983 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
984 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
985 normalise_link($data["url"]), $contact_id]);
989 self::updateAvatar($data["photo"], $uid, $contact_id);
991 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
992 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
994 // This condition should always be true
995 if (!DBA::isResult($contact)) {
999 $updated = ['addr' => $data['addr'],
1000 'alias' => $data['alias'],
1001 'url' => $data['url'],
1002 'nurl' => normalise_link($data['url']),
1003 'name' => $data['name'],
1004 'nick' => $data['nick']];
1006 if ($data['keywords'] != '') {
1007 $updated['keywords'] = $data['keywords'];
1009 if ($data['location'] != '') {
1010 $updated['location'] = $data['location'];
1013 // Update the technical stuff as well - if filled
1014 if ($data['notify'] != '') {
1015 $updated['notify'] = $data['notify'];
1017 if ($data['poll'] != '') {
1018 $updated['poll'] = $data['poll'];
1020 if ($data['batch'] != '') {
1021 $updated['batch'] = $data['batch'];
1023 if ($data['request'] != '') {
1024 $updated['request'] = $data['request'];
1026 if ($data['confirm'] != '') {
1027 $updated['confirm'] = $data['confirm'];
1029 if ($data['poco'] != '') {
1030 $updated['poco'] = $data['poco'];
1033 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1034 if (empty($contact['pubkey'])) {
1035 $updated['pubkey'] = $data['pubkey'];
1038 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1039 $updated['uri-date'] = DateTimeFormat::utcNow();
1041 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1042 $updated['name-date'] = DateTimeFormat::utcNow();
1045 $updated['avatar-date'] = DateTimeFormat::utcNow();
1047 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1053 * @brief Checks if the contact is blocked
1055 * @param int $cid contact id
1057 * @return boolean Is the contact blocked?
1059 public static function isBlocked($cid)
1065 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1066 if (!DBA::isResult($blocked)) {
1069 return (bool) $blocked['blocked'];
1073 * @brief Checks if the contact is hidden
1075 * @param int $cid contact id
1077 * @return boolean Is the contact hidden?
1079 public static function isHidden($cid)
1085 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1086 if (!DBA::isResult($hidden)) {
1089 return (bool) $hidden['hidden'];
1093 * @brief Returns posts from a given contact url
1095 * @param string $contact_url Contact URL
1097 * @return string posts in HTML
1099 public static function getPostsFromUrl($contact_url)
1101 $a = self::getApp();
1103 require_once 'include/conversation.php';
1105 // There are no posts with "uid = 0" with connector networks
1106 // This speeds up the query a lot
1107 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1108 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1109 DBA::escape(normalise_link($contact_url))
1112 if (!DBA::isResult($r)) {
1116 if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1117 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1119 $sql = "`item`.`uid` = ?";
1122 $author_id = intval($r[0]["author-id"]);
1124 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1126 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1127 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1128 $params = ['order' => ['created' => true],
1129 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1130 $r = Item::selectForUser(local_user(), [], $condition, $params);
1132 $items = Item::inArray($r);
1134 $o = conversation($a, $items, 'contact-posts', false);
1136 $o .= alt_pager($a, count($items));
1142 * @brief Returns the account type name
1144 * The function can be called with either the user or the contact array
1146 * @param array $contact contact or user array
1149 public static function getAccountType(array $contact)
1151 // There are several fields that indicate that the contact or user is a forum
1152 // "page-flags" is a field in the user table,
1153 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1154 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1155 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1156 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1157 || (isset($contact['forum']) && intval($contact['forum']))
1158 || (isset($contact['prv']) && intval($contact['prv']))
1159 || (isset($contact['community']) && intval($contact['community']))
1161 $type = self::ACCOUNT_TYPE_COMMUNITY;
1163 $type = self::ACCOUNT_TYPE_PERSON;
1166 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1167 if (isset($contact["contact-type"])) {
1168 $type = $contact["contact-type"];
1171 if (isset($contact["account-type"])) {
1172 $type = $contact["account-type"];
1176 case self::ACCOUNT_TYPE_ORGANISATION:
1177 $account_type = L10n::t("Organisation");
1180 case self::ACCOUNT_TYPE_NEWS:
1181 $account_type = L10n::t('News');
1184 case self::ACCOUNT_TYPE_COMMUNITY:
1185 $account_type = L10n::t("Forum");
1193 return $account_type;
1197 * @brief Blocks a contact
1202 public static function block($uid)
1204 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1210 * @brief Unblocks a contact
1215 public static function unblock($uid)
1217 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1223 * @brief Updates the avatar links in a contact only if needed
1225 * @param string $avatar Link to avatar picture
1226 * @param int $uid User id of contact owner
1227 * @param int $cid Contact id
1228 * @param bool $force force picture update
1230 * @return array Returns array of the different avatar sizes
1232 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1234 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1235 if (!DBA::isResult($contact)) {
1238 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1241 if (($contact["avatar"] != $avatar) || $force) {
1242 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1247 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1251 // Update the public contact (contact id = 0)
1253 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1254 if (DBA::isResult($pcontact)) {
1255 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1267 * @param integer $id contact id
1270 public static function updateFromProbe($id)
1273 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1274 This will reliably kill your communication with Friendica contacts.
1277 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1278 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1279 if (!DBA::isResult($contact)) {
1283 $ret = Probe::uri($contact["url"]);
1285 // If Probe::uri fails the network code will be different
1286 if ($ret["network"] != $contact["network"]) {
1292 // make sure to not overwrite existing values with blank entries
1293 foreach ($ret as $key => $val) {
1294 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1295 $ret[$key] = $contact[$key];
1298 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1309 'url' => $ret['url'],
1310 'nurl' => normalise_link($ret['url']),
1311 'addr' => $ret['addr'],
1312 'alias' => $ret['alias'],
1313 'batch' => $ret['batch'],
1314 'notify' => $ret['notify'],
1315 'poll' => $ret['poll'],
1316 'poco' => $ret['poco']
1321 // Update the corresponding gcontact entry
1322 PortableContact::lastUpdated($ret["url"]);
1328 * Takes a $uid and a url/handle and adds a new contact
1329 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1330 * dfrn_request page.
1332 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1335 * $return['success'] boolean true if successful
1336 * $return['message'] error text if success is false.
1338 * @brief Takes a $uid and a url/handle and adds a new contact
1340 * @param string $url
1341 * @param bool $interactive
1342 * @param string $network
1343 * @return boolean|string
1345 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1347 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1351 // remove ajax junk, e.g. Twitter
1352 $url = str_replace('/#!/', '/', $url);
1354 if (!Network::isUrlAllowed($url)) {
1355 $result['message'] = L10n::t('Disallowed profile URL.');
1359 if (Network::isUrlBlocked($url)) {
1360 $result['message'] = L10n::t('Blocked domain');
1365 $result['message'] = L10n::t('Connect URL missing.');
1369 $arr = ['url' => $url, 'contact' => []];
1371 Addon::callHooks('follow', $arr);
1374 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1378 if (x($arr['contact'], 'name')) {
1379 $ret = $arr['contact'];
1381 $ret = Probe::uri($url, $network, $uid, false);
1384 if (($network != '') && ($ret['network'] != $network)) {
1385 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1389 // check if we already have a contact
1390 // the poll url is more reliable than the profile url, as we may have
1391 // indirect links or webfinger links
1393 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1394 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1395 if (!DBA::isResult($contact)) {
1396 $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
1397 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1400 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1402 if (strlen($a->urlpath)) {
1403 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1405 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1408 goaway($ret['request'] . "&addr=$myaddr");
1412 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1413 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1414 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1418 // This extra param just confuses things, remove it
1419 if ($ret['network'] === Protocol::DIASPORA) {
1420 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1423 // do we have enough information?
1425 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1426 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1427 if (!x($ret, 'poll')) {
1428 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1430 if (!x($ret, 'name')) {
1431 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1433 if (!x($ret, 'url')) {
1434 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1436 if (strpos($url, '@') !== false) {
1437 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1438 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1443 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1444 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1445 $ret['notify'] = '';
1448 if (!$ret['notify']) {
1449 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1452 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1454 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1456 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1458 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA])) {
1462 if (DBA::isResult($contact)) {
1464 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1466 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1467 DBA::update('contact', $fields, ['id' => $contact['id']]);
1469 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1471 // create contact record
1472 DBA::insert('contact', [
1474 'created' => DateTimeFormat::utcNow(),
1475 'url' => $ret['url'],
1476 'nurl' => normalise_link($ret['url']),
1477 'addr' => $ret['addr'],
1478 'alias' => $ret['alias'],
1479 'batch' => $ret['batch'],
1480 'notify' => $ret['notify'],
1481 'poll' => $ret['poll'],
1482 'poco' => $ret['poco'],
1483 'name' => $ret['name'],
1484 'nick' => $ret['nick'],
1485 'network' => $ret['network'],
1486 'pubkey' => $ret['pubkey'],
1487 'rel' => $new_relation,
1488 'priority'=> $ret['priority'],
1489 'writable'=> $writeable,
1490 'hidden' => $hidden,
1498 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1499 if (!DBA::isResult($contact)) {
1500 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1504 $contact_id = $contact['id'];
1505 $result['cid'] = $contact_id;
1507 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1509 // Update the avatar
1510 self::updateAvatar($ret['photo'], $uid, $contact_id);
1512 // pull feed and consume it, which should subscribe to the hub.
1514 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1516 $owner = User::getOwnerDataById($uid);
1518 if (DBA::isResult($owner)) {
1519 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1520 // create a follow slap
1522 $item['verb'] = ACTIVITY_FOLLOW;
1523 $item['follow'] = $contact["url"];
1525 $item['title'] = '';
1528 $item['attach'] = '';
1529 $slap = OStatus::salmon($item, $owner);
1530 if (!empty($contact['notify'])) {
1531 Salmon::slapper($owner, $contact['notify'], $slap);
1533 } elseif ($contact['network'] == Protocol::DIASPORA) {
1534 $ret = Diaspora::sendShare($a->user, $contact);
1535 logger('share returns: ' . $ret);
1539 $result['success'] = true;
1543 public static function updateSslPolicy($contact, $new_policy)
1545 $ssl_changed = false;
1546 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1547 $ssl_changed = true;
1548 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1549 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1550 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1551 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1552 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1553 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1556 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1557 $ssl_changed = true;
1558 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1559 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1560 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1561 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1562 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1563 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1567 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1568 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1569 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1570 DBA::update('contact', $fields, ['id' => $contact['id']]);
1576 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1577 // Should always be set
1578 if (empty($datarray['author-id'])) {
1582 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1583 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1584 if (!DBA::isResult($pub_contact)) {
1585 // Should never happen
1589 $url = $pub_contact['url'];
1590 $name = $pub_contact['name'];
1591 $photo = $pub_contact['photo'];
1592 $nick = $pub_contact['nick'];
1593 $network = $pub_contact['network'];
1595 if (is_array($contact)) {
1596 if (($contact['rel'] == self::SHARING)
1597 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1598 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1599 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1601 // send email notification to owner?
1603 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1604 logger('ignoring duplicated connection request from pending contact ' . $url);
1608 // create contact record
1609 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1610 `blocked`, `readonly`, `pending`, `writable`)
1611 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1612 intval($importer['uid']),
1613 DBA::escape(DateTimeFormat::utcNow()),
1615 DBA::escape(normalise_link($url)),
1618 DBA::escape($photo),
1619 DBA::escape($network),
1620 intval(self::FOLLOWER)
1624 'id' => DBA::lastInsertId(),
1625 'network' => $network,
1631 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1633 /// @TODO Encapsulate this into a function/method
1634 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1635 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1636 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1637 // create notification
1638 $hash = random_string();
1640 if (is_array($contact_record)) {
1641 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1642 'blocked' => false, 'knowyou' => false,
1643 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1646 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1648 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1649 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1652 'type' => NOTIFY_INTRO,
1653 'notify_flags' => $user['notify-flags'],
1654 'language' => $user['language'],
1655 'to_name' => $user['username'],
1656 'to_email' => $user['email'],
1657 'uid' => $user['uid'],
1658 'link' => System::baseUrl() . '/notifications/intro',
1659 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1660 'source_link' => $contact_record['url'],
1661 'source_photo' => $contact_record['photo'],
1662 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1667 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1668 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1669 DBA::update('contact', ['pending' => false], $condition);
1674 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1676 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1677 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1679 Contact::remove($contact['id']);
1683 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1685 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1686 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1688 Contact::remove($contact['id']);
1693 * @brief Create a birthday event.
1695 * Update the year and the birthday.
1697 public static function updateBirthdays()
1699 // This only handles foreign or alien networks where a birthday has been provided.
1700 // In-network birthdays are handled within local_delivery
1702 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1703 if (DBA::isResult($r)) {
1704 foreach ($r as $rr) {
1705 logger('update_contact_birthday: ' . $rr['bd']);
1707 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1710 * Add new birthday event for this person
1712 * $bdtext is just a readable placeholder in case the event is shared
1713 * with others. We will replace it during presentation to our $importer
1714 * to contain a sparkle link and perhaps a photo.
1717 // Check for duplicates
1718 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1719 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1720 if (DBA::exists('event', $condition)) {
1724 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1725 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1727 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1728 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1729 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1730 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1735 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1736 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1743 * Remove the unavailable contact ids from the provided list
1745 * @param array $contact_ids Contact id list
1747 public static function pruneUnavailable(array &$contact_ids)
1749 if (empty($contact_ids)) {
1753 $str = DBA::escape(implode(',', $contact_ids));
1755 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1758 while($contact = DBA::fetch($stmt)) {
1759 $return[] = $contact['id'];
1764 $contact_ids = $return;
1768 * @brief Returns a magic link to authenticate remote visitors
1770 * @param string $contact_url The address of the target contact profile
1771 * @param integer $url An url that we will be redirected to after the authentication
1773 * @return string with "redir" link
1775 public static function magicLink($contact_url, $url = '')
1777 $cid = self::getIdForURL($contact_url, 0, true);
1779 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
1782 return self::magicLinkbyId($cid, $url);
1786 * @brief Returns a magic link to authenticate remote visitors
1788 * @param integer $cid The contact id of the target contact profile
1789 * @param integer $url An url that we will be redirected to after the authentication
1791 * @return string with "redir" link
1793 public static function magicLinkbyId($cid, $url = '')
1795 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
1797 return self::magicLinkbyContact($contact, $url);
1801 * @brief Returns a magic link to authenticate remote visitors
1803 * @param array $contact The contact array with "uid", "network" and "url"
1804 * @param integer $url An url that we will be redirected to after the authentication
1806 * @return string with "redir" link
1808 public static function magicLinkbyContact($contact, $url = '')
1810 if ($contact['network'] != Protocol::DFRN) {
1811 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
1814 // Only redirections to the same host do make sense
1815 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1819 if ($contact['uid'] != 0) {
1820 return self::magicLink($contact['url'], $url);
1823 $redirect = 'redir/' . $contact['id'];
1826 $redirect .= '?url=' . $url;