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\System;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Profile;
16 use Friendica\Network\Probe;
17 use Friendica\Object\Image;
18 use Friendica\Protocol\Diaspora;
19 use Friendica\Protocol\OStatus;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Protocol\Salmon;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
25 require_once 'boot.php';
26 require_once 'include/dba.php';
27 require_once 'include/text.php';
30 * @brief functions for interacting with a contact
32 class Contact extends BaseObject
35 * @name page/profile types
37 * PAGE_NORMAL is a typical personal profile account
38 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
39 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
40 * write access to wall and comments (no email and not included in page owner's ACL lists)
41 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
45 const PAGE_NORMAL = 0;
46 const PAGE_SOAPBOX = 1;
47 const PAGE_COMMUNITY = 2;
48 const PAGE_FREELOVE = 3;
50 const PAGE_PRVGROUP = 5;
58 * ACCOUNT_TYPE_PERSON - the account belongs to a person
59 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
61 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
62 * Associated page type: PAGE_SOAPBOX
64 * ACCOUNT_TYPE_NEWS - the account is a news reflector
65 * Associated page type: PAGE_SOAPBOX
67 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
68 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
70 * ACCOUNT_TYPE_RELAY - the account is a relay
71 * This will only be assigned to contacts, not to user accounts
74 const ACCOUNT_TYPE_PERSON = 0;
75 const ACCOUNT_TYPE_ORGANISATION = 1;
76 const ACCOUNT_TYPE_NEWS = 2;
77 const ACCOUNT_TYPE_COMMUNITY = 3;
78 const ACCOUNT_TYPE_RELAY = 4;
97 * @brief Returns a list of contacts belonging in a group
102 public static function getByGroupId($gid)
107 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
109 INNER JOIN `group_member`
110 ON `contact`.`id` = `group_member`.`contact-id`
112 AND `contact`.`uid` = ?
113 AND NOT `contact`.`self`
114 AND NOT `contact`.`blocked`
115 AND NOT `contact`.`pending`
116 ORDER BY `contact`.`name` ASC',
121 if (DBA::isResult($stmt)) {
122 $return = DBA::toArray($stmt);
130 * @brief Returns the count of OStatus contacts in a group
135 public static function getOStatusCountByGroupId($gid)
139 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
141 INNER JOIN `group_member`
142 ON `contact`.`id` = `group_member`.`contact-id`
144 AND `contact`.`uid` = ?
145 AND `contact`.`network` = ?
146 AND `contact`.`notify` != ""',
151 $return = $contacts['count'];
158 * Creates the self-contact for the provided user id
161 * @return bool Operation success
163 public static function createSelfFromUserId($uid)
165 // Only create the entry if it doesn't exist yet
166 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
170 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
171 if (!DBA::isResult($user)) {
175 $return = DBA::insert('contact', [
176 'uid' => $user['uid'],
177 'created' => DateTimeFormat::utcNow(),
179 'name' => $user['username'],
180 'nick' => $user['nickname'],
181 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
182 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
183 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
186 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
187 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
188 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
189 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
190 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
191 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
192 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
193 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
194 'name-date' => DateTimeFormat::utcNow(),
195 'uri-date' => DateTimeFormat::utcNow(),
196 'avatar-date' => DateTimeFormat::utcNow(),
204 * Updates the self-contact for the provided user id
207 * @param boolean $update_avatar Force the avatar update
209 public static function updateSelfFromUserID($uid, $update_avatar = false)
211 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
212 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
213 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
214 if (!DBA::isResult($self)) {
218 $fields = ['nickname', 'page-flags', 'account-type'];
219 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
220 if (!DBA::isResult($user)) {
224 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
225 'country-name', 'gender', 'pub_keywords', 'xmpp'];
226 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
227 if (!DBA::isResult($profile)) {
231 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
232 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
233 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
234 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
235 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
237 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
238 if (DBA::isResult($avatar)) {
239 if ($update_avatar) {
240 $fields['avatar-date'] = DateTimeFormat::utcNow();
243 // Creating the path to the avatar, beginning with the file suffix
244 $types = Image::supportedTypes();
245 if (isset($types[$avatar['type']])) {
246 $file_suffix = $types[$avatar['type']];
248 $file_suffix = 'jpg';
251 // We are adding a timestamp value so that other systems won't use cached content
252 $timestamp = strtotime($fields['avatar-date']);
254 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
255 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
257 $fields['photo'] = $prefix . '4' . $suffix;
258 $fields['thumb'] = $prefix . '5' . $suffix;
259 $fields['micro'] = $prefix . '6' . $suffix;
261 // We hadn't found a photo entry, so we use the default avatar
262 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
263 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
264 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
267 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
268 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
270 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
271 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
272 $fields['nurl'] = normalise_link($fields['url']);
273 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
274 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
275 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
276 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
277 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
278 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
282 foreach ($fields as $field => $content) {
283 if (isset($self[$field]) && $self[$field] != $content) {
289 $fields['name-date'] = DateTimeFormat::utcNow();
290 DBA::update('contact', $fields, ['id' => $self['id']]);
292 // Update the public contact as well
293 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
295 // Update the profile
296 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
297 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
298 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
303 * @brief Marks a contact for removal
305 * @param int $id contact id
308 public static function remove($id)
310 // We want just to make sure that we don't delete our "self" contact
311 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
312 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
316 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
318 DBA::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
322 DBA::delete('contact', ['id' => $id]);
324 // Delete the rest in the background
325 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
329 * @brief Sends an unfriend message. Does not remove the contact
331 * @param array $user User unfriending
332 * @param array $contact Contact unfriended
335 public static function terminateFriendship(array $user, array $contact)
337 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
338 // create an unfollow slap
340 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
341 $item['follow'] = $contact["url"];
342 $slap = OStatus::salmon($item, $user);
344 if (!empty($contact['notify'])) {
345 Salmon::slapper($user, $contact['notify'], $slap);
347 } elseif ($contact['network'] == NETWORK_DIASPORA) {
348 Diaspora::sendUnshare($user, $contact);
353 * @brief Marks a contact for archival after a communication issue delay
355 * Contact has refused to recognise us as a friend. We will start a countdown.
356 * If they still don't recognise us in 32 days, the relationship is over,
357 * and we won't waste any more time trying to communicate with them.
358 * This provides for the possibility that their database is temporarily messed
359 * up or some other transient event and that there's a possibility we could recover from it.
361 * @param array $contact contact to mark for archival
364 public static function markForArchival(array $contact)
366 // Contact already archived or "self" contact? => nothing to do
367 if ($contact['archive'] || $contact['self']) {
371 if ($contact['term-date'] <= NULL_DATE) {
372 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
374 if ($contact['url'] != '') {
375 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
379 * We really should send a notification to the owner after 2-3 weeks
380 * so they won't be surprised when the contact vanishes and can take
381 * remedial action if this was a serious mistake or glitch
384 /// @todo Check for contact vitality via probing
385 $archival_days = Config::get('system', 'archival_days', 32);
387 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
388 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
389 /* Relationship is really truly dead. archive them rather than
390 * delete, though if the owner tries to unarchive them we'll start
391 * the whole process over again.
393 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
395 if ($contact['url'] != '') {
396 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
403 * @brief Cancels the archival countdown
405 * @see Contact::markForArchival()
407 * @param array $contact contact to be unmarked for archival
410 public static function unmarkForArchival(array $contact)
412 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
413 $exists = DBA::exists('contact', $condition);
415 // We don't need to update, we never marked this contact for archival
420 // It's a miracle. Our dead contact has inexplicably come back to life.
421 $fields = ['term-date' => NULL_DATE, 'archive' => false];
422 DBA::update('contact', $fields, ['id' => $contact['id']]);
424 if (!empty($contact['url'])) {
425 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
428 if (!empty($contact['batch'])) {
429 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
430 DBA::update('contact', $fields, $condition);
435 * @brief Get contact data for a given profile link
437 * The function looks at several places (contact table and gcontact table) for the contact
438 * It caches its result for the same script execution to prevent duplicate calls
440 * @param string $url The profile link
441 * @param int $uid User id
442 * @param array $default If not data was found take this data as default value
444 * @return array Contact data
446 public static function getDetailsByURL($url, $uid = -1, array $default = [])
458 if (isset($cache[$url][$uid])) {
459 return $cache[$url][$uid];
462 $ssl_url = str_replace('http://', 'https://', $url);
464 // Fetch contact data from the contact table for the given user
465 $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`,
466 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
467 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
468 $r = DBA::toArray($s);
470 // Fetch contact data from the contact table for the given user, checking with the alias
471 if (!DBA::isResult($r)) {
472 $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`,
473 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
474 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
475 $r = DBA::toArray($s);
478 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
479 if (!DBA::isResult($r)) {
480 $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`,
481 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
482 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
483 $r = DBA::toArray($s);
486 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
487 if (!DBA::isResult($r)) {
488 $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`,
489 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
490 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
491 $r = DBA::toArray($s);
494 // Fetch the data from the gcontact table
495 if (!DBA::isResult($r)) {
496 $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`,
497 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
498 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
499 $r = DBA::toArray($s);
502 if (DBA::isResult($r)) {
503 // If there is more than one entry we filter out the connector networks
505 foreach ($r as $id => $result) {
506 if ($result["network"] == NETWORK_STATUSNET) {
512 $profile = array_shift($r);
514 // "bd" always contains the upcoming birthday of a contact.
515 // "birthday" might contain the birthday including the year of birth.
516 if ($profile["birthday"] > '0001-01-01') {
517 $bd_timestamp = strtotime($profile["birthday"]);
518 $month = date("m", $bd_timestamp);
519 $day = date("d", $bd_timestamp);
521 $current_timestamp = time();
522 $current_year = date("Y", $current_timestamp);
523 $current_month = date("m", $current_timestamp);
524 $current_day = date("d", $current_timestamp);
526 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
527 $current = $current_year . "-" . $current_month . "-" . $current_day;
529 if ($profile["bd"] < $current) {
530 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
533 $profile["bd"] = '0001-01-01';
539 if (empty($profile["photo"]) && isset($default["photo"])) {
540 $profile["photo"] = $default["photo"];
543 if (empty($profile["name"]) && isset($default["name"])) {
544 $profile["name"] = $default["name"];
547 if (empty($profile["network"]) && isset($default["network"])) {
548 $profile["network"] = $default["network"];
551 if (empty($profile["thumb"]) && isset($profile["photo"])) {
552 $profile["thumb"] = $profile["photo"];
555 if (empty($profile["micro"]) && isset($profile["thumb"])) {
556 $profile["micro"] = $profile["thumb"];
559 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
560 && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
562 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
565 // Show contact details of Diaspora contacts only if connected
566 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == NETWORK_DIASPORA)) {
567 $profile["location"] = "";
568 $profile["about"] = "";
569 $profile["gender"] = "";
570 $profile["birthday"] = '0001-01-01';
573 $cache[$url][$uid] = $profile;
579 * @brief Get contact data for a given address
581 * The function looks at several places (contact table and gcontact table) for the contact
583 * @param string $addr The profile link
584 * @param int $uid User id
586 * @return array Contact data
588 public static function getDetailsByAddr($addr, $uid = -1)
600 // Fetch contact data from the contact table for the given user
601 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
602 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
603 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
607 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
608 if (!DBA::isResult($r)) {
609 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
610 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
611 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
616 // Fetch the data from the gcontact table
617 if (!DBA::isResult($r)) {
618 $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`,
619 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
620 FROM `gcontact` WHERE `addr` = '%s'",
625 if (!DBA::isResult($r)) {
626 $data = Probe::uri($addr);
628 $profile = self::getDetailsByURL($data['url'], $uid);
637 * @brief Returns the data array for the photo menu of a given contact
639 * @param array $contact contact
640 * @param int $uid optional, default 0
643 public static function photoMenu(array $contact, $uid = 0)
645 // @todo Unused, to be removed
653 $contact_drop_link = '';
660 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
662 $profile_link = self::magicLink($contact['url']);
663 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
668 // Look for our own contact if the uid doesn't match and isn't public
669 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
670 if (DBA::isResult($contact_own)) {
671 return self::photoMenu($contact_own, $uid);
673 $profile_link = self::magicLink($contact['url']);
674 $connlnk = 'follow/?url=' . $contact['url'];
676 'profile' => [L10n::t('View Profile'), $profile_link, true],
677 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
685 if (($contact['network'] === NETWORK_DFRN) && !$contact['self']) {
687 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
689 $profile_link = $contact['url'];
692 if ($profile_link === 'mailbox') {
697 $status_link = $profile_link . '?url=status';
698 $photos_link = $profile_link . '?url=photos';
699 $profile_link = $profile_link . '?url=profile';
702 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA]) && !$contact['self']) {
703 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
706 if (($contact['network'] == NETWORK_DFRN) && !$contact['self']) {
707 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
710 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
712 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
714 if (!$contact['self']) {
715 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
720 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
723 'status' => [L10n::t("View Status") , $status_link , true],
724 'profile' => [L10n::t("View Profile") , $profile_link , true],
725 'photos' => [L10n::t("View Photos") , $photos_link , true],
726 'network' => [L10n::t("Network Posts"), $posts_link , false],
727 'edit' => [L10n::t("View Contact") , $contact_url , false],
728 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
729 'pm' => [L10n::t("Send PM") , $pm_url , false],
730 'poke' => [L10n::t("Poke") , $poke_link , false],
733 $args = ['contact' => $contact, 'menu' => &$menu];
735 Addon::callHooks('contact_photo_menu', $args);
739 foreach ($menu as $menuname => $menuitem) {
740 if ($menuitem[1] != '') {
741 $menucondensed[$menuname] = $menuitem;
745 return $menucondensed;
749 * @brief Returns ungrouped contact count or list for user
751 * Returns either the total number of ungrouped contacts for the given user
752 * id or a paginated list of ungrouped contacts.
754 * @param int $uid uid
755 * @param int $start optional, default 0
756 * @param int $count optional, default 0
760 public static function getUngroupedList($uid)
769 SELECT DISTINCT(`contact-id`)
771 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
772 WHERE `group`.`uid` = %d
773 )", intval($uid), intval($uid));
777 * @brief Fetch the contact id for a given URL and user
779 * First lookup in the contact table to find a record matching either `url`, `nurl`,
782 * If there's no record and we aren't looking for a public contact, we quit.
783 * If there's one, we check that it isn't time to update the picture else we
784 * directly return the found contact id.
786 * Second, we probe the provided $url whether it's http://server.tld/profile or
787 * nick@server.tld. We quit if we can't get any info back.
789 * Third, we create the contact record if it doesn't exist
791 * Fourth, we update the existing record with the new data (avatar, alias, nick)
792 * if there's any updates
794 * @param string $url Contact URL
795 * @param integer $uid The user id for the contact (0 = public contact)
796 * @param boolean $no_update Don't update the contact
797 * @param array $default Default value for creating the contact when every else fails
799 * @return integer Contact ID
801 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
803 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
811 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
812 // We first try the nurl (http://server.tld/nick), most common case
813 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
815 // Then the addr (nick@server.tld)
816 if (!DBA::isResult($contact)) {
817 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
820 // Then the alias (which could be anything)
821 if (!DBA::isResult($contact)) {
822 // The link could be provided as http although we stored it as https
823 $ssl_url = str_replace('http://', 'https://', $url);
824 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
825 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
828 if (DBA::isResult($contact)) {
829 $contact_id = $contact["id"];
831 // Update the contact every 7 days
832 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
834 // We force the update if the avatar is empty
835 if (!x($contact, 'avatar')) {
836 $update_contact = true;
839 if (!$update_contact || $no_update) {
842 } elseif ($uid != 0) {
843 // Non-existing user-specific contact, exiting
847 $data = Probe::uri($url, "", $uid);
849 // Last try in gcontact for unsupported networks
850 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL, NETWORK_FEED])) {
855 // Get data from the gcontact table
856 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
857 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
858 if (!DBA::isResult($contact)) {
859 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
862 if (!DBA::isResult($contact)) {
863 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
864 'photo', 'keywords', 'location', 'about', 'network',
865 'priority', 'batch', 'request', 'confirm', 'poco'];
866 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
869 if (!DBA::isResult($contact)) {
870 // The link could be provided as http although we stored it as https
871 $ssl_url = str_replace('http://', 'https://', $url);
872 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
873 $contact = DBA::selectFirst('contact', $fields, $condition);
876 if (!DBA::isResult($contact)) {
877 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
878 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
879 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
880 $contact = DBA::selectFirst('fcontact', $fields, $condition);
883 if (!empty($default)) {
887 if (!DBA::isResult($contact)) {
890 $data = array_merge($data, $contact);
894 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
895 $contact_id = self::getIdForURL($data["alias"], $uid, true);
900 DBA::insert('contact', [
902 'created' => DateTimeFormat::utcNow(),
903 'url' => $data["url"],
904 'nurl' => normalise_link($data["url"]),
905 'addr' => $data["addr"],
906 'alias' => $data["alias"],
907 'notify' => $data["notify"],
908 'poll' => $data["poll"],
909 'name' => $data["name"],
910 'nick' => $data["nick"],
911 'photo' => $data["photo"],
912 'keywords' => $data["keywords"],
913 'location' => $data["location"],
914 'about' => $data["about"],
915 'network' => $data["network"],
916 'pubkey' => $data["pubkey"],
917 'rel' => self::SHARING,
918 'priority' => $data["priority"],
919 'batch' => $data["batch"],
920 'request' => $data["request"],
921 'confirm' => $data["confirm"],
922 'poco' => $data["poco"],
923 'name-date' => DateTimeFormat::utcNow(),
924 'uri-date' => DateTimeFormat::utcNow(),
925 'avatar-date' => DateTimeFormat::utcNow(),
932 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
933 $contacts = DBA::toArray($s);
934 if (!DBA::isResult($contacts)) {
938 $contact_id = $contacts[0]["id"];
940 // Update the newly created contact from data in the gcontact table
941 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
942 if (DBA::isResult($gcontact)) {
943 // Only use the information when the probing hadn't fetched these values
944 if ($data['keywords'] != '') {
945 unset($gcontact['keywords']);
947 if ($data['location'] != '') {
948 unset($gcontact['location']);
950 if ($data['about'] != '') {
951 unset($gcontact['about']);
953 DBA::update('contact', $gcontact, ['id' => $contact_id]);
956 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
957 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
958 normalise_link($data["url"]), $contact_id]);
962 self::updateAvatar($data["photo"], $uid, $contact_id);
964 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
965 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
967 // This condition should always be true
968 if (!DBA::isResult($contact)) {
972 $updated = ['addr' => $data['addr'],
973 'alias' => $data['alias'],
974 'url' => $data['url'],
975 'nurl' => normalise_link($data['url']),
976 'name' => $data['name'],
977 'nick' => $data['nick']];
979 if ($data['keywords'] != '') {
980 $updated['keywords'] = $data['keywords'];
982 if ($data['location'] != '') {
983 $updated['location'] = $data['location'];
986 // Update the technical stuff as well - if filled
987 if ($data['notify'] != '') {
988 $updated['notify'] = $data['notify'];
990 if ($data['poll'] != '') {
991 $updated['poll'] = $data['poll'];
993 if ($data['batch'] != '') {
994 $updated['batch'] = $data['batch'];
996 if ($data['request'] != '') {
997 $updated['request'] = $data['request'];
999 if ($data['confirm'] != '') {
1000 $updated['confirm'] = $data['confirm'];
1002 if ($data['poco'] != '') {
1003 $updated['poco'] = $data['poco'];
1006 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1007 if (empty($contact['pubkey'])) {
1008 $updated['pubkey'] = $data['pubkey'];
1011 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1012 $updated['uri-date'] = DateTimeFormat::utcNow();
1014 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1015 $updated['name-date'] = DateTimeFormat::utcNow();
1018 $updated['avatar-date'] = DateTimeFormat::utcNow();
1020 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1026 * @brief Checks if the contact is blocked
1028 * @param int $cid contact id
1030 * @return boolean Is the contact blocked?
1032 public static function isBlocked($cid)
1038 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1039 if (!DBA::isResult($blocked)) {
1042 return (bool) $blocked['blocked'];
1046 * @brief Checks if the contact is hidden
1048 * @param int $cid contact id
1050 * @return boolean Is the contact hidden?
1052 public static function isHidden($cid)
1058 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1059 if (!DBA::isResult($hidden)) {
1062 return (bool) $hidden['hidden'];
1066 * @brief Returns posts from a given contact url
1068 * @param string $contact_url Contact URL
1070 * @return string posts in HTML
1072 public static function getPostsFromUrl($contact_url)
1074 $a = self::getApp();
1076 require_once 'include/conversation.php';
1078 // There are no posts with "uid = 0" with connector networks
1079 // This speeds up the query a lot
1080 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1081 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1082 DBA::escape(normalise_link($contact_url))
1085 if (!DBA::isResult($r)) {
1089 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1090 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1092 $sql = "`item`.`uid` = ?";
1095 $author_id = intval($r[0]["author-id"]);
1097 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1099 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1100 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1101 $params = ['order' => ['created' => true],
1102 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1103 $r = Item::selectForUser(local_user(), [], $condition, $params);
1105 $items = Item::inArray($r);
1107 $o = conversation($a, $items, 'contact-posts', false);
1109 $o .= alt_pager($a, count($items));
1115 * @brief Returns the account type name
1117 * The function can be called with either the user or the contact array
1119 * @param array $contact contact or user array
1122 public static function getAccountType(array $contact)
1124 // There are several fields that indicate that the contact or user is a forum
1125 // "page-flags" is a field in the user table,
1126 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1127 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1128 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1129 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1130 || (isset($contact['forum']) && intval($contact['forum']))
1131 || (isset($contact['prv']) && intval($contact['prv']))
1132 || (isset($contact['community']) && intval($contact['community']))
1134 $type = self::ACCOUNT_TYPE_COMMUNITY;
1136 $type = self::ACCOUNT_TYPE_PERSON;
1139 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1140 if (isset($contact["contact-type"])) {
1141 $type = $contact["contact-type"];
1144 if (isset($contact["account-type"])) {
1145 $type = $contact["account-type"];
1149 case self::ACCOUNT_TYPE_ORGANISATION:
1150 $account_type = L10n::t("Organisation");
1153 case self::ACCOUNT_TYPE_NEWS:
1154 $account_type = L10n::t('News');
1157 case self::ACCOUNT_TYPE_COMMUNITY:
1158 $account_type = L10n::t("Forum");
1166 return $account_type;
1170 * @brief Blocks a contact
1175 public static function block($uid)
1177 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1183 * @brief Unblocks a contact
1188 public static function unblock($uid)
1190 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1196 * @brief Updates the avatar links in a contact only if needed
1198 * @param string $avatar Link to avatar picture
1199 * @param int $uid User id of contact owner
1200 * @param int $cid Contact id
1201 * @param bool $force force picture update
1203 * @return array Returns array of the different avatar sizes
1205 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1207 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1208 if (!DBA::isResult($contact)) {
1211 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1214 if (($contact["avatar"] != $avatar) || $force) {
1215 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1220 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1224 // Update the public contact (contact id = 0)
1226 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1227 if (DBA::isResult($pcontact)) {
1228 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1240 * @param integer $id contact id
1243 public static function updateFromProbe($id)
1246 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1247 This will reliably kill your communication with Friendica contacts.
1250 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1251 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1252 if (!DBA::isResult($contact)) {
1256 $ret = Probe::uri($contact["url"]);
1258 // If Probe::uri fails the network code will be different
1259 if ($ret["network"] != $contact["network"]) {
1265 // make sure to not overwrite existing values with blank entries
1266 foreach ($ret as $key => $val) {
1267 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1268 $ret[$key] = $contact[$key];
1271 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1282 'url' => $ret['url'],
1283 'nurl' => normalise_link($ret['url']),
1284 'addr' => $ret['addr'],
1285 'alias' => $ret['alias'],
1286 'batch' => $ret['batch'],
1287 'notify' => $ret['notify'],
1288 'poll' => $ret['poll'],
1289 'poco' => $ret['poco']
1294 // Update the corresponding gcontact entry
1295 PortableContact::lastUpdated($ret["url"]);
1301 * Takes a $uid and a url/handle and adds a new contact
1302 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1303 * dfrn_request page.
1305 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1308 * $return['success'] boolean true if successful
1309 * $return['message'] error text if success is false.
1311 * @brief Takes a $uid and a url/handle and adds a new contact
1313 * @param string $url
1314 * @param bool $interactive
1315 * @param string $network
1316 * @return boolean|string
1318 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1320 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1324 // remove ajax junk, e.g. Twitter
1325 $url = str_replace('/#!/', '/', $url);
1327 if (!Network::isUrlAllowed($url)) {
1328 $result['message'] = L10n::t('Disallowed profile URL.');
1332 if (Network::isUrlBlocked($url)) {
1333 $result['message'] = L10n::t('Blocked domain');
1338 $result['message'] = L10n::t('Connect URL missing.');
1342 $arr = ['url' => $url, 'contact' => []];
1344 Addon::callHooks('follow', $arr);
1347 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1351 if (x($arr['contact'], 'name')) {
1352 $ret = $arr['contact'];
1354 $ret = Probe::uri($url, $network, $uid, false);
1357 if (($network != '') && ($ret['network'] != $network)) {
1358 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1362 // check if we already have a contact
1363 // the poll url is more reliable than the profile url, as we may have
1364 // indirect links or webfinger links
1366 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1368 DBA::escape($ret['poll']),
1369 DBA::escape(normalise_link($ret['poll'])),
1370 DBA::escape($ret['network'])
1373 if (!DBA::isResult($r)) {
1374 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1376 DBA::escape(normalise_link($url)),
1377 DBA::escape($ret['network'])
1381 if (($ret['network'] === NETWORK_DFRN) && !DBA::isResult($r)) {
1383 if (strlen($a->urlpath)) {
1384 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1386 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1389 goaway($ret['request'] . "&addr=$myaddr");
1393 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != NETWORK_DFRN)) {
1394 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1395 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1399 // This extra param just confuses things, remove it
1400 if ($ret['network'] === NETWORK_DIASPORA) {
1401 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1404 // do we have enough information?
1406 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1407 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1408 if (!x($ret, 'poll')) {
1409 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1411 if (!x($ret, 'name')) {
1412 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1414 if (!x($ret, 'url')) {
1415 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1417 if (strpos($url, '@') !== false) {
1418 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1419 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1424 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1425 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1426 $ret['notify'] = '';
1429 if (!$ret['notify']) {
1430 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1433 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1435 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1437 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1439 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1443 if (DBA::isResult($r)) {
1445 $new_relation = (($r[0]['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1447 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1448 DBA::update('contact', $fields, ['id' => $r[0]['id']]);
1450 $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? self::FRIEND : self::SHARING);
1452 // create contact record
1453 DBA::insert('contact', [
1455 'created' => DateTimeFormat::utcNow(),
1456 'url' => $ret['url'],
1457 'nurl' => normalise_link($ret['url']),
1458 'addr' => $ret['addr'],
1459 'alias' => $ret['alias'],
1460 'batch' => $ret['batch'],
1461 'notify' => $ret['notify'],
1462 'poll' => $ret['poll'],
1463 'poco' => $ret['poco'],
1464 'name' => $ret['name'],
1465 'nick' => $ret['nick'],
1466 'network' => $ret['network'],
1467 'pubkey' => $ret['pubkey'],
1468 'rel' => $new_relation,
1469 'priority'=> $ret['priority'],
1470 'writable'=> $writeable,
1471 'hidden' => $hidden,
1479 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1480 if (!DBA::isResult($contact)) {
1481 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1485 $contact_id = $contact['id'];
1486 $result['cid'] = $contact_id;
1488 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1490 // Update the avatar
1491 self::updateAvatar($ret['photo'], $uid, $contact_id);
1493 // pull feed and consume it, which should subscribe to the hub.
1495 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1497 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1498 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1502 if (DBA::isResult($r)) {
1503 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
1504 // create a follow slap
1506 $item['verb'] = ACTIVITY_FOLLOW;
1507 $item['follow'] = $contact["url"];
1508 $slap = OStatus::salmon($item, $r[0]);
1509 if (!empty($contact['notify'])) {
1510 Salmon::slapper($r[0], $contact['notify'], $slap);
1512 } elseif ($contact['network'] == NETWORK_DIASPORA) {
1513 $ret = Diaspora::sendShare($a->user, $contact);
1514 logger('share returns: ' . $ret);
1518 $result['success'] = true;
1522 public static function updateSslPolicy($contact, $new_policy)
1524 $ssl_changed = false;
1525 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1526 $ssl_changed = true;
1527 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1528 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1529 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1530 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1531 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1532 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1535 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1536 $ssl_changed = true;
1537 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1538 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1539 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1540 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1541 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1542 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1546 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1547 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1548 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1549 DBA::update('contact', $fields, ['id' => $contact['id']]);
1555 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1556 $url = notags(trim($datarray['author-link']));
1557 $name = notags(trim($datarray['author-name']));
1558 $photo = notags(trim($datarray['author-avatar']));
1561 if (is_object($item)) {
1562 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1563 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1564 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1570 if (is_array($contact)) {
1571 if (($contact['rel'] == self::SHARING)
1572 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1573 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1574 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1576 // send email notification to owner?
1578 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1579 logger('ignoring duplicated connection request from pending contact ' . $url);
1583 // create contact record
1584 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1585 `blocked`, `readonly`, `pending`, `writable`)
1586 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1587 intval($importer['uid']),
1588 DBA::escape(DateTimeFormat::utcNow()),
1590 DBA::escape(normalise_link($url)),
1593 DBA::escape($photo),
1594 DBA::escape(NETWORK_OSTATUS),
1595 intval(self::FOLLOWER)
1599 'id' => DBA::lastInsertId(),
1600 'network' => NETWORK_OSTATUS,
1606 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1608 /// @TODO Encapsulate this into a function/method
1609 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1610 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1611 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1612 // create notification
1613 $hash = random_string();
1615 if (is_array($contact_record)) {
1616 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1617 'blocked' => false, 'knowyou' => false,
1618 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1621 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1623 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1624 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1627 'type' => NOTIFY_INTRO,
1628 'notify_flags' => $user['notify-flags'],
1629 'language' => $user['language'],
1630 'to_name' => $user['username'],
1631 'to_email' => $user['email'],
1632 'uid' => $user['uid'],
1633 'link' => System::baseUrl() . '/notifications/intro',
1634 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1635 'source_link' => $contact_record['url'],
1636 'source_photo' => $contact_record['photo'],
1637 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1642 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1643 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1644 intval($importer['uid']),
1651 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1653 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1654 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1656 Contact::remove($contact['id']);
1660 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1662 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1663 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1665 Contact::remove($contact['id']);
1670 * @brief Create a birthday event.
1672 * Update the year and the birthday.
1674 public static function updateBirthdays()
1676 // This only handles foreign or alien networks where a birthday has been provided.
1677 // In-network birthdays are handled within local_delivery
1679 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1680 if (DBA::isResult($r)) {
1681 foreach ($r as $rr) {
1682 logger('update_contact_birthday: ' . $rr['bd']);
1684 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1687 * Add new birthday event for this person
1689 * $bdtext is just a readable placeholder in case the event is shared
1690 * with others. We will replace it during presentation to our $importer
1691 * to contain a sparkle link and perhaps a photo.
1694 // Check for duplicates
1695 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1696 intval($rr['uid']), intval($rr['id']), DBA::escape(DateTimeFormat::utc($nextbd)), DBA::escape('birthday'));
1698 if (DBA::isResult($s)) {
1702 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1703 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1705 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1706 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1707 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1708 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1714 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1715 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1722 * Remove the unavailable contact ids from the provided list
1724 * @param array $contact_ids Contact id list
1726 public static function pruneUnavailable(array &$contact_ids)
1728 if (empty($contact_ids)) {
1732 $str = DBA::escape(implode(',', $contact_ids));
1734 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1737 while($contact = DBA::fetch($stmt)) {
1738 $return[] = $contact['id'];
1743 $contact_ids = $return;
1747 * @brief Returns a magic link to authenticate remote visitors
1749 * @param string $contact_url The address of the target contact profile
1750 * @param integer $url An url that we will be redirected to after the authentication
1752 * @return string with "redir" link
1754 public static function magicLink($contact_url, $url = '')
1756 $cid = self::getIdForURL($contact_url, 0, true);
1758 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
1761 return self::magicLinkbyId($cid, $url);
1765 * @brief Returns a magic link to authenticate remote visitors
1767 * @param integer $cid The contact id of the target contact profile
1768 * @param integer $url An url that we will be redirected to after the authentication
1770 * @return string with "redir" link
1772 public static function magicLinkbyId($cid, $url = '')
1774 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
1776 return self::magicLinkbyContact($contact, $url);
1780 * @brief Returns a magic link to authenticate remote visitors
1782 * @param array $contact The contact array with "uid", "network" and "url"
1783 * @param integer $url An url that we will be redirected to after the authentication
1785 * @return string with "redir" link
1787 public static function magicLinkbyContact($contact, $url = '')
1789 if ($contact['network'] != NETWORK_DFRN) {
1790 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
1793 // Only redirections to the same host do make sense
1794 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1798 if ($contact['uid'] != 0) {
1799 return self::magicLink($contact['url'], $url);
1802 $redirect = 'redir/' . $contact['id'];
1805 $redirect .= '?url=' . $url;