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)
368 if (!isset($contact['url'])) {
369 logger('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), LOGGER_DEBUG);
372 // Contact already archived or "self" contact? => nothing to do
373 if ($contact['archive'] || $contact['self']) {
377 if ($contact['term-date'] <= NULL_DATE) {
378 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
380 if ($contact['url'] != '') {
381 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
385 * We really should send a notification to the owner after 2-3 weeks
386 * so they won't be surprised when the contact vanishes and can take
387 * remedial action if this was a serious mistake or glitch
390 /// @todo Check for contact vitality via probing
391 $archival_days = Config::get('system', 'archival_days', 32);
393 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
394 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
395 /* Relationship is really truly dead. archive them rather than
396 * delete, though if the owner tries to unarchive them we'll start
397 * the whole process over again.
399 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
401 if ($contact['url'] != '') {
402 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
409 * @brief Cancels the archival countdown
411 * @see Contact::markForArchival()
413 * @param array $contact contact to be unmarked for archival
416 public static function unmarkForArchival(array $contact)
418 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
419 $exists = DBA::exists('contact', $condition);
421 // We don't need to update, we never marked this contact for archival
426 // It's a miracle. Our dead contact has inexplicably come back to life.
427 $fields = ['term-date' => NULL_DATE, 'archive' => false];
428 DBA::update('contact', $fields, ['id' => $contact['id']]);
430 if (!empty($contact['url'])) {
431 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
434 if (!empty($contact['batch'])) {
435 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
436 DBA::update('contact', $fields, $condition);
441 * @brief Get contact data for a given profile link
443 * The function looks at several places (contact table and gcontact table) for the contact
444 * It caches its result for the same script execution to prevent duplicate calls
446 * @param string $url The profile link
447 * @param int $uid User id
448 * @param array $default If not data was found take this data as default value
450 * @return array Contact data
452 public static function getDetailsByURL($url, $uid = -1, array $default = [])
464 if (isset($cache[$url][$uid])) {
465 return $cache[$url][$uid];
468 $ssl_url = str_replace('http://', 'https://', $url);
470 // Fetch contact data from the contact table for the given user
471 $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`,
472 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
473 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
474 $r = DBA::toArray($s);
476 // Fetch contact data from the contact table for the given user, checking with the alias
477 if (!DBA::isResult($r)) {
478 $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`,
479 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
480 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
481 $r = DBA::toArray($s);
484 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
485 if (!DBA::isResult($r)) {
486 $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`,
487 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
488 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
489 $r = DBA::toArray($s);
492 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
493 if (!DBA::isResult($r)) {
494 $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`,
495 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
496 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
497 $r = DBA::toArray($s);
500 // Fetch the data from the gcontact table
501 if (!DBA::isResult($r)) {
502 $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`,
503 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
504 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
505 $r = DBA::toArray($s);
508 if (DBA::isResult($r)) {
509 // If there is more than one entry we filter out the connector networks
511 foreach ($r as $id => $result) {
512 if ($result["network"] == Protocol::STATUSNET) {
518 $profile = array_shift($r);
520 // "bd" always contains the upcoming birthday of a contact.
521 // "birthday" might contain the birthday including the year of birth.
522 if ($profile["birthday"] > '0001-01-01') {
523 $bd_timestamp = strtotime($profile["birthday"]);
524 $month = date("m", $bd_timestamp);
525 $day = date("d", $bd_timestamp);
527 $current_timestamp = time();
528 $current_year = date("Y", $current_timestamp);
529 $current_month = date("m", $current_timestamp);
530 $current_day = date("d", $current_timestamp);
532 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
533 $current = $current_year . "-" . $current_month . "-" . $current_day;
535 if ($profile["bd"] < $current) {
536 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
539 $profile["bd"] = '0001-01-01';
545 if (empty($profile["photo"]) && isset($default["photo"])) {
546 $profile["photo"] = $default["photo"];
549 if (empty($profile["name"]) && isset($default["name"])) {
550 $profile["name"] = $default["name"];
553 if (empty($profile["network"]) && isset($default["network"])) {
554 $profile["network"] = $default["network"];
557 if (empty($profile["thumb"]) && isset($profile["photo"])) {
558 $profile["thumb"] = $profile["photo"];
561 if (empty($profile["micro"]) && isset($profile["thumb"])) {
562 $profile["micro"] = $profile["thumb"];
565 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
566 && in_array($profile["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
568 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
571 // Show contact details of Diaspora contacts only if connected
572 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
573 $profile["location"] = "";
574 $profile["about"] = "";
575 $profile["gender"] = "";
576 $profile["birthday"] = '0001-01-01';
579 $cache[$url][$uid] = $profile;
585 * @brief Get contact data for a given address
587 * The function looks at several places (contact table and gcontact table) for the contact
589 * @param string $addr The profile link
590 * @param int $uid User id
592 * @return array Contact data
594 public static function getDetailsByAddr($addr, $uid = -1)
606 // Fetch contact data from the contact table for the given user
607 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
608 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
609 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
613 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
614 if (!DBA::isResult($r)) {
615 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
616 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
617 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
622 // Fetch the data from the gcontact table
623 if (!DBA::isResult($r)) {
624 $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`,
625 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
626 FROM `gcontact` WHERE `addr` = '%s'",
631 if (!DBA::isResult($r)) {
632 $data = Probe::uri($addr);
634 $profile = self::getDetailsByURL($data['url'], $uid);
643 * @brief Returns the data array for the photo menu of a given contact
645 * @param array $contact contact
646 * @param int $uid optional, default 0
649 public static function photoMenu(array $contact, $uid = 0)
651 // @todo Unused, to be removed
659 $contact_drop_link = '';
666 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
668 $profile_link = self::magicLink($contact['url']);
669 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
674 // Look for our own contact if the uid doesn't match and isn't public
675 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
676 if (DBA::isResult($contact_own)) {
677 return self::photoMenu($contact_own, $uid);
679 $profile_link = self::magicLink($contact['url']);
680 $connlnk = 'follow/?url=' . $contact['url'];
682 'profile' => [L10n::t('View Profile'), $profile_link, true],
683 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
691 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
693 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
695 $profile_link = $contact['url'];
698 if ($profile_link === 'mailbox') {
703 $status_link = $profile_link . '?url=status';
704 $photos_link = $profile_link . '?url=photos';
705 $profile_link = $profile_link . '?url=profile';
708 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
709 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
712 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
713 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
716 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
718 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
720 if (!$contact['self']) {
721 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
726 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
729 'status' => [L10n::t("View Status") , $status_link , true],
730 'profile' => [L10n::t("View Profile") , $profile_link , true],
731 'photos' => [L10n::t("View Photos") , $photos_link , true],
732 'network' => [L10n::t("Network Posts"), $posts_link , false],
733 'edit' => [L10n::t("View Contact") , $contact_url , false],
734 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
735 'pm' => [L10n::t("Send PM") , $pm_url , false],
736 'poke' => [L10n::t("Poke") , $poke_link , false],
739 $args = ['contact' => $contact, 'menu' => &$menu];
741 Addon::callHooks('contact_photo_menu', $args);
745 foreach ($menu as $menuname => $menuitem) {
746 if ($menuitem[1] != '') {
747 $menucondensed[$menuname] = $menuitem;
751 return $menucondensed;
755 * @brief Returns ungrouped contact count or list for user
757 * Returns either the total number of ungrouped contacts for the given user
758 * id or a paginated list of ungrouped contacts.
760 * @param int $uid uid
761 * @param int $start optional, default 0
762 * @param int $count optional, default 0
766 public static function getUngroupedList($uid)
775 SELECT DISTINCT(`contact-id`)
777 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
778 WHERE `group`.`uid` = %d
779 )", intval($uid), intval($uid));
783 * @brief Fetch the contact id for a given URL and user
785 * First lookup in the contact table to find a record matching either `url`, `nurl`,
788 * If there's no record and we aren't looking for a public contact, we quit.
789 * If there's one, we check that it isn't time to update the picture else we
790 * directly return the found contact id.
792 * Second, we probe the provided $url whether it's http://server.tld/profile or
793 * nick@server.tld. We quit if we can't get any info back.
795 * Third, we create the contact record if it doesn't exist
797 * Fourth, we update the existing record with the new data (avatar, alias, nick)
798 * if there's any updates
800 * @param string $url Contact URL
801 * @param integer $uid The user id for the contact (0 = public contact)
802 * @param boolean $no_update Don't update the contact
803 * @param array $default Default value for creating the contact when every else fails
805 * @return integer Contact ID
807 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
809 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
817 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
818 // We first try the nurl (http://server.tld/nick), most common case
819 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
821 // Then the addr (nick@server.tld)
822 if (!DBA::isResult($contact)) {
823 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
826 // Then the alias (which could be anything)
827 if (!DBA::isResult($contact)) {
828 // The link could be provided as http although we stored it as https
829 $ssl_url = str_replace('http://', 'https://', $url);
830 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
831 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
834 if (DBA::isResult($contact)) {
835 $contact_id = $contact["id"];
837 // Update the contact every 7 days
838 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
840 // We force the update if the avatar is empty
841 if (!x($contact, 'avatar')) {
842 $update_contact = true;
845 if (!$update_contact || $no_update) {
848 } elseif ($uid != 0) {
849 // Non-existing user-specific contact, exiting
853 // When we don't want to update, we look if some of our users already know this contact
855 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
856 'photo', 'keywords', 'location', 'about', 'network',
857 'priority', 'batch', 'request', 'confirm', 'poco'];
858 $data = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
860 if (DBA::isResult($data)) {
861 // For security reasons we don't fetch key data from our users
862 $data["pubkey"] = '';
869 $data = Probe::uri($url, "", $uid);
872 // Last try in gcontact for unsupported networks
873 if (!in_array($data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
878 // Get data from the gcontact table
879 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
880 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
881 if (!DBA::isResult($contact)) {
882 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
885 if (!DBA::isResult($contact)) {
886 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
887 'photo', 'keywords', 'location', 'about', 'network',
888 'priority', 'batch', 'request', 'confirm', 'poco'];
889 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
892 if (!DBA::isResult($contact)) {
893 // The link could be provided as http although we stored it as https
894 $ssl_url = str_replace('http://', 'https://', $url);
895 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
896 $contact = DBA::selectFirst('contact', $fields, $condition);
899 if (!DBA::isResult($contact)) {
900 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
901 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
902 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
903 $contact = DBA::selectFirst('fcontact', $fields, $condition);
906 if (!empty($default)) {
910 if (!DBA::isResult($contact)) {
913 $data = array_merge($data, $contact);
917 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
918 $contact_id = self::getIdForURL($data["alias"], $uid, true);
923 DBA::insert('contact', [
925 'created' => DateTimeFormat::utcNow(),
926 'url' => $data["url"],
927 'nurl' => normalise_link($data["url"]),
928 'addr' => $data["addr"],
929 'alias' => $data["alias"],
930 'notify' => $data["notify"],
931 'poll' => $data["poll"],
932 'name' => $data["name"],
933 'nick' => $data["nick"],
934 'photo' => $data["photo"],
935 'keywords' => $data["keywords"],
936 'location' => $data["location"],
937 'about' => $data["about"],
938 'network' => $data["network"],
939 'pubkey' => $data["pubkey"],
940 'rel' => self::SHARING,
941 'priority' => $data["priority"],
942 'batch' => $data["batch"],
943 'request' => $data["request"],
944 'confirm' => $data["confirm"],
945 'poco' => $data["poco"],
946 'name-date' => DateTimeFormat::utcNow(),
947 'uri-date' => DateTimeFormat::utcNow(),
948 'avatar-date' => DateTimeFormat::utcNow(),
955 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
956 $contacts = DBA::toArray($s);
957 if (!DBA::isResult($contacts)) {
961 $contact_id = $contacts[0]["id"];
963 // Update the newly created contact from data in the gcontact table
964 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
965 if (DBA::isResult($gcontact)) {
966 // Only use the information when the probing hadn't fetched these values
967 if ($data['keywords'] != '') {
968 unset($gcontact['keywords']);
970 if ($data['location'] != '') {
971 unset($gcontact['location']);
973 if ($data['about'] != '') {
974 unset($gcontact['about']);
976 DBA::update('contact', $gcontact, ['id' => $contact_id]);
979 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
980 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
981 normalise_link($data["url"]), $contact_id]);
985 self::updateAvatar($data["photo"], $uid, $contact_id);
987 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
988 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
990 // This condition should always be true
991 if (!DBA::isResult($contact)) {
995 $updated = ['addr' => $data['addr'],
996 'alias' => $data['alias'],
997 'url' => $data['url'],
998 'nurl' => normalise_link($data['url']),
999 'name' => $data['name'],
1000 'nick' => $data['nick']];
1002 if ($data['keywords'] != '') {
1003 $updated['keywords'] = $data['keywords'];
1005 if ($data['location'] != '') {
1006 $updated['location'] = $data['location'];
1009 // Update the technical stuff as well - if filled
1010 if ($data['notify'] != '') {
1011 $updated['notify'] = $data['notify'];
1013 if ($data['poll'] != '') {
1014 $updated['poll'] = $data['poll'];
1016 if ($data['batch'] != '') {
1017 $updated['batch'] = $data['batch'];
1019 if ($data['request'] != '') {
1020 $updated['request'] = $data['request'];
1022 if ($data['confirm'] != '') {
1023 $updated['confirm'] = $data['confirm'];
1025 if ($data['poco'] != '') {
1026 $updated['poco'] = $data['poco'];
1029 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1030 if (empty($contact['pubkey'])) {
1031 $updated['pubkey'] = $data['pubkey'];
1034 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1035 $updated['uri-date'] = DateTimeFormat::utcNow();
1037 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1038 $updated['name-date'] = DateTimeFormat::utcNow();
1041 $updated['avatar-date'] = DateTimeFormat::utcNow();
1043 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1049 * @brief Checks if the contact is blocked
1051 * @param int $cid contact id
1053 * @return boolean Is the contact blocked?
1055 public static function isBlocked($cid)
1061 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1062 if (!DBA::isResult($blocked)) {
1065 return (bool) $blocked['blocked'];
1069 * @brief Checks if the contact is hidden
1071 * @param int $cid contact id
1073 * @return boolean Is the contact hidden?
1075 public static function isHidden($cid)
1081 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1082 if (!DBA::isResult($hidden)) {
1085 return (bool) $hidden['hidden'];
1089 * @brief Returns posts from a given contact url
1091 * @param string $contact_url Contact URL
1093 * @return string posts in HTML
1095 public static function getPostsFromUrl($contact_url)
1097 $a = self::getApp();
1099 require_once 'include/conversation.php';
1101 // There are no posts with "uid = 0" with connector networks
1102 // This speeds up the query a lot
1103 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1104 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1105 DBA::escape(normalise_link($contact_url))
1108 if (!DBA::isResult($r)) {
1112 if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1113 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1115 $sql = "`item`.`uid` = ?";
1118 $author_id = intval($r[0]["author-id"]);
1120 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1122 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1123 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1124 $params = ['order' => ['created' => true],
1125 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1126 $r = Item::selectForUser(local_user(), [], $condition, $params);
1128 $items = Item::inArray($r);
1130 $o = conversation($a, $items, 'contact-posts', false);
1132 $o .= alt_pager($a, count($items));
1138 * @brief Returns the account type name
1140 * The function can be called with either the user or the contact array
1142 * @param array $contact contact or user array
1145 public static function getAccountType(array $contact)
1147 // There are several fields that indicate that the contact or user is a forum
1148 // "page-flags" is a field in the user table,
1149 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1150 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1151 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1152 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1153 || (isset($contact['forum']) && intval($contact['forum']))
1154 || (isset($contact['prv']) && intval($contact['prv']))
1155 || (isset($contact['community']) && intval($contact['community']))
1157 $type = self::ACCOUNT_TYPE_COMMUNITY;
1159 $type = self::ACCOUNT_TYPE_PERSON;
1162 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1163 if (isset($contact["contact-type"])) {
1164 $type = $contact["contact-type"];
1167 if (isset($contact["account-type"])) {
1168 $type = $contact["account-type"];
1172 case self::ACCOUNT_TYPE_ORGANISATION:
1173 $account_type = L10n::t("Organisation");
1176 case self::ACCOUNT_TYPE_NEWS:
1177 $account_type = L10n::t('News');
1180 case self::ACCOUNT_TYPE_COMMUNITY:
1181 $account_type = L10n::t("Forum");
1189 return $account_type;
1193 * @brief Blocks a contact
1198 public static function block($uid)
1200 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1206 * @brief Unblocks a contact
1211 public static function unblock($uid)
1213 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1219 * @brief Updates the avatar links in a contact only if needed
1221 * @param string $avatar Link to avatar picture
1222 * @param int $uid User id of contact owner
1223 * @param int $cid Contact id
1224 * @param bool $force force picture update
1226 * @return array Returns array of the different avatar sizes
1228 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1230 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1231 if (!DBA::isResult($contact)) {
1234 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1237 if (($contact["avatar"] != $avatar) || $force) {
1238 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1243 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1247 // Update the public contact (contact id = 0)
1249 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1250 if (DBA::isResult($pcontact)) {
1251 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1263 * @param integer $id contact id
1266 public static function updateFromProbe($id)
1269 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1270 This will reliably kill your communication with Friendica contacts.
1273 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1274 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1275 if (!DBA::isResult($contact)) {
1279 $ret = Probe::uri($contact["url"]);
1281 // If Probe::uri fails the network code will be different
1282 if ($ret["network"] != $contact["network"]) {
1288 // make sure to not overwrite existing values with blank entries
1289 foreach ($ret as $key => $val) {
1290 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1291 $ret[$key] = $contact[$key];
1294 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1305 'url' => $ret['url'],
1306 'nurl' => normalise_link($ret['url']),
1307 'addr' => $ret['addr'],
1308 'alias' => $ret['alias'],
1309 'batch' => $ret['batch'],
1310 'notify' => $ret['notify'],
1311 'poll' => $ret['poll'],
1312 'poco' => $ret['poco']
1317 // Update the corresponding gcontact entry
1318 PortableContact::lastUpdated($ret["url"]);
1324 * Takes a $uid and a url/handle and adds a new contact
1325 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1326 * dfrn_request page.
1328 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1331 * $return['success'] boolean true if successful
1332 * $return['message'] error text if success is false.
1334 * @brief Takes a $uid and a url/handle and adds a new contact
1336 * @param string $url
1337 * @param bool $interactive
1338 * @param string $network
1339 * @return boolean|string
1341 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1343 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1347 // remove ajax junk, e.g. Twitter
1348 $url = str_replace('/#!/', '/', $url);
1350 if (!Network::isUrlAllowed($url)) {
1351 $result['message'] = L10n::t('Disallowed profile URL.');
1355 if (Network::isUrlBlocked($url)) {
1356 $result['message'] = L10n::t('Blocked domain');
1361 $result['message'] = L10n::t('Connect URL missing.');
1365 $arr = ['url' => $url, 'contact' => []];
1367 Addon::callHooks('follow', $arr);
1370 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1374 if (x($arr['contact'], 'name')) {
1375 $ret = $arr['contact'];
1377 $ret = Probe::uri($url, $network, $uid, false);
1380 if (($network != '') && ($ret['network'] != $network)) {
1381 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1385 // check if we already have a contact
1386 // the poll url is more reliable than the profile url, as we may have
1387 // indirect links or webfinger links
1389 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1390 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1391 if (!DBA::isResult($contact)) {
1392 $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
1393 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1396 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1398 if (strlen($a->urlpath)) {
1399 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1401 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1404 goaway($ret['request'] . "&addr=$myaddr");
1408 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1409 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1410 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1414 // This extra param just confuses things, remove it
1415 if ($ret['network'] === Protocol::DIASPORA) {
1416 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1419 // do we have enough information?
1421 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1422 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1423 if (!x($ret, 'poll')) {
1424 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1426 if (!x($ret, 'name')) {
1427 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1429 if (!x($ret, 'url')) {
1430 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1432 if (strpos($url, '@') !== false) {
1433 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1434 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1439 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1440 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1441 $ret['notify'] = '';
1444 if (!$ret['notify']) {
1445 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1448 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1450 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1452 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1454 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA])) {
1458 if (DBA::isResult($contact)) {
1460 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1462 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1463 DBA::update('contact', $fields, ['id' => $contact['id']]);
1465 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1467 // create contact record
1468 DBA::insert('contact', [
1470 'created' => DateTimeFormat::utcNow(),
1471 'url' => $ret['url'],
1472 'nurl' => normalise_link($ret['url']),
1473 'addr' => $ret['addr'],
1474 'alias' => $ret['alias'],
1475 'batch' => $ret['batch'],
1476 'notify' => $ret['notify'],
1477 'poll' => $ret['poll'],
1478 'poco' => $ret['poco'],
1479 'name' => $ret['name'],
1480 'nick' => $ret['nick'],
1481 'network' => $ret['network'],
1482 'pubkey' => $ret['pubkey'],
1483 'rel' => $new_relation,
1484 'priority'=> $ret['priority'],
1485 'writable'=> $writeable,
1486 'hidden' => $hidden,
1494 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1495 if (!DBA::isResult($contact)) {
1496 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1500 $contact_id = $contact['id'];
1501 $result['cid'] = $contact_id;
1503 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1505 // Update the avatar
1506 self::updateAvatar($ret['photo'], $uid, $contact_id);
1508 // pull feed and consume it, which should subscribe to the hub.
1510 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1512 $owner = User::getOwnerDataById($uid);
1514 if (DBA::isResult($owner)) {
1515 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1516 // create a follow slap
1518 $item['verb'] = ACTIVITY_FOLLOW;
1519 $item['follow'] = $contact["url"];
1521 $item['title'] = '';
1524 $item['attach'] = '';
1525 $slap = OStatus::salmon($item, $owner);
1526 if (!empty($contact['notify'])) {
1527 Salmon::slapper($owner, $contact['notify'], $slap);
1529 } elseif ($contact['network'] == Protocol::DIASPORA) {
1530 $ret = Diaspora::sendShare($a->user, $contact);
1531 logger('share returns: ' . $ret);
1535 $result['success'] = true;
1539 public static function updateSslPolicy($contact, $new_policy)
1541 $ssl_changed = false;
1542 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1543 $ssl_changed = true;
1544 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1545 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1546 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1547 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1548 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1549 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1552 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1553 $ssl_changed = true;
1554 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1555 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1556 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1557 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1558 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1559 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1563 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1564 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1565 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1566 DBA::update('contact', $fields, ['id' => $contact['id']]);
1572 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1573 // Should always be set
1574 if (empty($datarray['author-id'])) {
1578 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1579 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1580 if (!DBA::isResult($pub_contact)) {
1581 // Should never happen
1585 $url = $pub_contact['url'];
1586 $name = $pub_contact['name'];
1587 $photo = $pub_contact['photo'];
1588 $nick = $pub_contact['nick'];
1589 $network = $pub_contact['network'];
1591 if (is_array($contact)) {
1592 if (($contact['rel'] == self::SHARING)
1593 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1594 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1595 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1597 // send email notification to owner?
1599 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1600 logger('ignoring duplicated connection request from pending contact ' . $url);
1604 // create contact record
1605 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1606 `blocked`, `readonly`, `pending`, `writable`)
1607 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1608 intval($importer['uid']),
1609 DBA::escape(DateTimeFormat::utcNow()),
1611 DBA::escape(normalise_link($url)),
1614 DBA::escape($photo),
1615 DBA::escape($network),
1616 intval(self::FOLLOWER)
1620 'id' => DBA::lastInsertId(),
1621 'network' => $network,
1627 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1629 /// @TODO Encapsulate this into a function/method
1630 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1631 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1632 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1633 // create notification
1634 $hash = random_string();
1636 if (is_array($contact_record)) {
1637 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1638 'blocked' => false, 'knowyou' => false,
1639 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1642 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1644 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1645 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1648 'type' => NOTIFY_INTRO,
1649 'notify_flags' => $user['notify-flags'],
1650 'language' => $user['language'],
1651 'to_name' => $user['username'],
1652 'to_email' => $user['email'],
1653 'uid' => $user['uid'],
1654 'link' => System::baseUrl() . '/notifications/intro',
1655 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1656 'source_link' => $contact_record['url'],
1657 'source_photo' => $contact_record['photo'],
1658 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1663 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1664 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1665 DBA::update('contact', ['pending' => false], $condition);
1670 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1672 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1673 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1675 Contact::remove($contact['id']);
1679 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1681 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1682 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1684 Contact::remove($contact['id']);
1689 * @brief Create a birthday event.
1691 * Update the year and the birthday.
1693 public static function updateBirthdays()
1695 // This only handles foreign or alien networks where a birthday has been provided.
1696 // In-network birthdays are handled within local_delivery
1698 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1699 if (DBA::isResult($r)) {
1700 foreach ($r as $rr) {
1701 logger('update_contact_birthday: ' . $rr['bd']);
1703 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1706 * Add new birthday event for this person
1708 * $bdtext is just a readable placeholder in case the event is shared
1709 * with others. We will replace it during presentation to our $importer
1710 * to contain a sparkle link and perhaps a photo.
1713 // Check for duplicates
1714 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1715 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1716 if (DBA::exists('event', $condition)) {
1720 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1721 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1723 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1724 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1725 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1726 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1731 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1732 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1739 * Remove the unavailable contact ids from the provided list
1741 * @param array $contact_ids Contact id list
1743 public static function pruneUnavailable(array &$contact_ids)
1745 if (empty($contact_ids)) {
1749 $str = DBA::escape(implode(',', $contact_ids));
1751 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1754 while($contact = DBA::fetch($stmt)) {
1755 $return[] = $contact['id'];
1760 $contact_ids = $return;
1764 * @brief Returns a magic link to authenticate remote visitors
1766 * @param string $contact_url The address of the target contact profile
1767 * @param integer $url An url that we will be redirected to after the authentication
1769 * @return string with "redir" link
1771 public static function magicLink($contact_url, $url = '')
1773 $cid = self::getIdForURL($contact_url, 0, true);
1775 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
1778 return self::magicLinkbyId($cid, $url);
1782 * @brief Returns a magic link to authenticate remote visitors
1784 * @param integer $cid The contact id of the target contact profile
1785 * @param integer $url An url that we will be redirected to after the authentication
1787 * @return string with "redir" link
1789 public static function magicLinkbyId($cid, $url = '')
1791 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
1793 return self::magicLinkbyContact($contact, $url);
1797 * @brief Returns a magic link to authenticate remote visitors
1799 * @param array $contact The contact array with "uid", "network" and "url"
1800 * @param integer $url An url that we will be redirected to after the authentication
1802 * @return string with "redir" link
1804 public static function magicLinkbyContact($contact, $url = '')
1806 if ($contact['network'] != Protocol::DFRN) {
1807 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
1810 // Only redirections to the same host do make sense
1811 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1815 if ($contact['uid'] != 0) {
1816 return self::magicLink($contact['url'], $url);
1819 $redirect = 'redir/' . $contact['id'];
1822 $redirect .= '?url=' . $url;