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"];
346 $item['attach'] = '';
347 $slap = OStatus::salmon($item, $user);
349 if (!empty($contact['notify'])) {
350 Salmon::slapper($user, $contact['notify'], $slap);
352 } elseif ($contact['network'] == NETWORK_DIASPORA) {
353 Diaspora::sendUnshare($user, $contact);
358 * @brief Marks a contact for archival after a communication issue delay
360 * Contact has refused to recognise us as a friend. We will start a countdown.
361 * If they still don't recognise us in 32 days, the relationship is over,
362 * and we won't waste any more time trying to communicate with them.
363 * This provides for the possibility that their database is temporarily messed
364 * up or some other transient event and that there's a possibility we could recover from it.
366 * @param array $contact contact to mark for archival
369 public static function markForArchival(array $contact)
371 // Contact already archived or "self" contact? => nothing to do
372 if ($contact['archive'] || $contact['self']) {
376 if ($contact['term-date'] <= NULL_DATE) {
377 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
379 if ($contact['url'] != '') {
380 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
384 * We really should send a notification to the owner after 2-3 weeks
385 * so they won't be surprised when the contact vanishes and can take
386 * remedial action if this was a serious mistake or glitch
389 /// @todo Check for contact vitality via probing
390 $archival_days = Config::get('system', 'archival_days', 32);
392 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
393 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
394 /* Relationship is really truly dead. archive them rather than
395 * delete, though if the owner tries to unarchive them we'll start
396 * the whole process over again.
398 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
400 if ($contact['url'] != '') {
401 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
408 * @brief Cancels the archival countdown
410 * @see Contact::markForArchival()
412 * @param array $contact contact to be unmarked for archival
415 public static function unmarkForArchival(array $contact)
417 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
418 $exists = DBA::exists('contact', $condition);
420 // We don't need to update, we never marked this contact for archival
425 // It's a miracle. Our dead contact has inexplicably come back to life.
426 $fields = ['term-date' => NULL_DATE, 'archive' => false];
427 DBA::update('contact', $fields, ['id' => $contact['id']]);
429 if (!empty($contact['url'])) {
430 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
433 if (!empty($contact['batch'])) {
434 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
435 DBA::update('contact', $fields, $condition);
440 * @brief Get contact data for a given profile link
442 * The function looks at several places (contact table and gcontact table) for the contact
443 * It caches its result for the same script execution to prevent duplicate calls
445 * @param string $url The profile link
446 * @param int $uid User id
447 * @param array $default If not data was found take this data as default value
449 * @return array Contact data
451 public static function getDetailsByURL($url, $uid = -1, array $default = [])
463 if (isset($cache[$url][$uid])) {
464 return $cache[$url][$uid];
467 $ssl_url = str_replace('http://', 'https://', $url);
469 // Fetch contact data from the contact table for the given user
470 $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`,
471 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
472 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
473 $r = DBA::toArray($s);
475 // Fetch contact data from the contact table for the given user, checking with the alias
476 if (!DBA::isResult($r)) {
477 $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`,
478 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
479 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
480 $r = DBA::toArray($s);
483 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
484 if (!DBA::isResult($r)) {
485 $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`,
486 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
487 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
488 $r = DBA::toArray($s);
491 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
492 if (!DBA::isResult($r)) {
493 $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`,
494 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
495 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
496 $r = DBA::toArray($s);
499 // Fetch the data from the gcontact table
500 if (!DBA::isResult($r)) {
501 $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`,
502 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
503 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
504 $r = DBA::toArray($s);
507 if (DBA::isResult($r)) {
508 // If there is more than one entry we filter out the connector networks
510 foreach ($r as $id => $result) {
511 if ($result["network"] == NETWORK_STATUSNET) {
517 $profile = array_shift($r);
519 // "bd" always contains the upcoming birthday of a contact.
520 // "birthday" might contain the birthday including the year of birth.
521 if ($profile["birthday"] > '0001-01-01') {
522 $bd_timestamp = strtotime($profile["birthday"]);
523 $month = date("m", $bd_timestamp);
524 $day = date("d", $bd_timestamp);
526 $current_timestamp = time();
527 $current_year = date("Y", $current_timestamp);
528 $current_month = date("m", $current_timestamp);
529 $current_day = date("d", $current_timestamp);
531 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
532 $current = $current_year . "-" . $current_month . "-" . $current_day;
534 if ($profile["bd"] < $current) {
535 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
538 $profile["bd"] = '0001-01-01';
544 if (empty($profile["photo"]) && isset($default["photo"])) {
545 $profile["photo"] = $default["photo"];
548 if (empty($profile["name"]) && isset($default["name"])) {
549 $profile["name"] = $default["name"];
552 if (empty($profile["network"]) && isset($default["network"])) {
553 $profile["network"] = $default["network"];
556 if (empty($profile["thumb"]) && isset($profile["photo"])) {
557 $profile["thumb"] = $profile["photo"];
560 if (empty($profile["micro"]) && isset($profile["thumb"])) {
561 $profile["micro"] = $profile["thumb"];
564 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
565 && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
567 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
570 // Show contact details of Diaspora contacts only if connected
571 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == NETWORK_DIASPORA)) {
572 $profile["location"] = "";
573 $profile["about"] = "";
574 $profile["gender"] = "";
575 $profile["birthday"] = '0001-01-01';
578 $cache[$url][$uid] = $profile;
584 * @brief Get contact data for a given address
586 * The function looks at several places (contact table and gcontact table) for the contact
588 * @param string $addr The profile link
589 * @param int $uid User id
591 * @return array Contact data
593 public static function getDetailsByAddr($addr, $uid = -1)
605 // Fetch contact data from the contact table for the given user
606 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
607 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
608 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
612 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
613 if (!DBA::isResult($r)) {
614 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
615 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
616 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
621 // Fetch the data from the gcontact table
622 if (!DBA::isResult($r)) {
623 $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`,
624 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
625 FROM `gcontact` WHERE `addr` = '%s'",
630 if (!DBA::isResult($r)) {
631 $data = Probe::uri($addr);
633 $profile = self::getDetailsByURL($data['url'], $uid);
642 * @brief Returns the data array for the photo menu of a given contact
644 * @param array $contact contact
645 * @param int $uid optional, default 0
648 public static function photoMenu(array $contact, $uid = 0)
650 // @todo Unused, to be removed
658 $contact_drop_link = '';
665 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
667 $profile_link = self::magicLink($contact['url']);
668 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
673 // Look for our own contact if the uid doesn't match and isn't public
674 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
675 if (DBA::isResult($contact_own)) {
676 return self::photoMenu($contact_own, $uid);
678 $profile_link = self::magicLink($contact['url']);
679 $connlnk = 'follow/?url=' . $contact['url'];
681 'profile' => [L10n::t('View Profile'), $profile_link, true],
682 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
690 if (($contact['network'] === NETWORK_DFRN) && !$contact['self']) {
692 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
694 $profile_link = $contact['url'];
697 if ($profile_link === 'mailbox') {
702 $status_link = $profile_link . '?url=status';
703 $photos_link = $profile_link . '?url=photos';
704 $profile_link = $profile_link . '?url=profile';
707 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA]) && !$contact['self']) {
708 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
711 if (($contact['network'] == NETWORK_DFRN) && !$contact['self']) {
712 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
715 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
717 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
719 if (!$contact['self']) {
720 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
725 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
728 'status' => [L10n::t("View Status") , $status_link , true],
729 'profile' => [L10n::t("View Profile") , $profile_link , true],
730 'photos' => [L10n::t("View Photos") , $photos_link , true],
731 'network' => [L10n::t("Network Posts"), $posts_link , false],
732 'edit' => [L10n::t("View Contact") , $contact_url , false],
733 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
734 'pm' => [L10n::t("Send PM") , $pm_url , false],
735 'poke' => [L10n::t("Poke") , $poke_link , false],
738 $args = ['contact' => $contact, 'menu' => &$menu];
740 Addon::callHooks('contact_photo_menu', $args);
744 foreach ($menu as $menuname => $menuitem) {
745 if ($menuitem[1] != '') {
746 $menucondensed[$menuname] = $menuitem;
750 return $menucondensed;
754 * @brief Returns ungrouped contact count or list for user
756 * Returns either the total number of ungrouped contacts for the given user
757 * id or a paginated list of ungrouped contacts.
759 * @param int $uid uid
760 * @param int $start optional, default 0
761 * @param int $count optional, default 0
765 public static function getUngroupedList($uid)
774 SELECT DISTINCT(`contact-id`)
776 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
777 WHERE `group`.`uid` = %d
778 )", intval($uid), intval($uid));
782 * @brief Fetch the contact id for a given URL and user
784 * First lookup in the contact table to find a record matching either `url`, `nurl`,
787 * If there's no record and we aren't looking for a public contact, we quit.
788 * If there's one, we check that it isn't time to update the picture else we
789 * directly return the found contact id.
791 * Second, we probe the provided $url whether it's http://server.tld/profile or
792 * nick@server.tld. We quit if we can't get any info back.
794 * Third, we create the contact record if it doesn't exist
796 * Fourth, we update the existing record with the new data (avatar, alias, nick)
797 * if there's any updates
799 * @param string $url Contact URL
800 * @param integer $uid The user id for the contact (0 = public contact)
801 * @param boolean $no_update Don't update the contact
802 * @param array $default Default value for creating the contact when every else fails
804 * @return integer Contact ID
806 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
808 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
816 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
817 // We first try the nurl (http://server.tld/nick), most common case
818 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
820 // Then the addr (nick@server.tld)
821 if (!DBA::isResult($contact)) {
822 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
825 // Then the alias (which could be anything)
826 if (!DBA::isResult($contact)) {
827 // The link could be provided as http although we stored it as https
828 $ssl_url = str_replace('http://', 'https://', $url);
829 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
830 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
833 if (DBA::isResult($contact)) {
834 $contact_id = $contact["id"];
836 // Update the contact every 7 days
837 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
839 // We force the update if the avatar is empty
840 if (!x($contact, 'avatar')) {
841 $update_contact = true;
844 if (!$update_contact || $no_update) {
847 } elseif ($uid != 0) {
848 // Non-existing user-specific contact, exiting
852 $data = Probe::uri($url, "", $uid);
854 // Last try in gcontact for unsupported networks
855 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL, NETWORK_FEED])) {
860 // Get data from the gcontact table
861 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
862 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
863 if (!DBA::isResult($contact)) {
864 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
867 if (!DBA::isResult($contact)) {
868 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
869 'photo', 'keywords', 'location', 'about', 'network',
870 'priority', 'batch', 'request', 'confirm', 'poco'];
871 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
874 if (!DBA::isResult($contact)) {
875 // The link could be provided as http although we stored it as https
876 $ssl_url = str_replace('http://', 'https://', $url);
877 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
878 $contact = DBA::selectFirst('contact', $fields, $condition);
881 if (!DBA::isResult($contact)) {
882 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
883 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
884 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
885 $contact = DBA::selectFirst('fcontact', $fields, $condition);
888 if (!empty($default)) {
892 if (!DBA::isResult($contact)) {
895 $data = array_merge($data, $contact);
899 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
900 $contact_id = self::getIdForURL($data["alias"], $uid, true);
905 DBA::insert('contact', [
907 'created' => DateTimeFormat::utcNow(),
908 'url' => $data["url"],
909 'nurl' => normalise_link($data["url"]),
910 'addr' => $data["addr"],
911 'alias' => $data["alias"],
912 'notify' => $data["notify"],
913 'poll' => $data["poll"],
914 'name' => $data["name"],
915 'nick' => $data["nick"],
916 'photo' => $data["photo"],
917 'keywords' => $data["keywords"],
918 'location' => $data["location"],
919 'about' => $data["about"],
920 'network' => $data["network"],
921 'pubkey' => $data["pubkey"],
922 'rel' => self::SHARING,
923 'priority' => $data["priority"],
924 'batch' => $data["batch"],
925 'request' => $data["request"],
926 'confirm' => $data["confirm"],
927 'poco' => $data["poco"],
928 'name-date' => DateTimeFormat::utcNow(),
929 'uri-date' => DateTimeFormat::utcNow(),
930 'avatar-date' => DateTimeFormat::utcNow(),
937 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
938 $contacts = DBA::toArray($s);
939 if (!DBA::isResult($contacts)) {
943 $contact_id = $contacts[0]["id"];
945 // Update the newly created contact from data in the gcontact table
946 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
947 if (DBA::isResult($gcontact)) {
948 // Only use the information when the probing hadn't fetched these values
949 if ($data['keywords'] != '') {
950 unset($gcontact['keywords']);
952 if ($data['location'] != '') {
953 unset($gcontact['location']);
955 if ($data['about'] != '') {
956 unset($gcontact['about']);
958 DBA::update('contact', $gcontact, ['id' => $contact_id]);
961 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
962 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
963 normalise_link($data["url"]), $contact_id]);
967 self::updateAvatar($data["photo"], $uid, $contact_id);
969 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
970 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
972 // This condition should always be true
973 if (!DBA::isResult($contact)) {
977 $updated = ['addr' => $data['addr'],
978 'alias' => $data['alias'],
979 'url' => $data['url'],
980 'nurl' => normalise_link($data['url']),
981 'name' => $data['name'],
982 'nick' => $data['nick']];
984 if ($data['keywords'] != '') {
985 $updated['keywords'] = $data['keywords'];
987 if ($data['location'] != '') {
988 $updated['location'] = $data['location'];
991 // Update the technical stuff as well - if filled
992 if ($data['notify'] != '') {
993 $updated['notify'] = $data['notify'];
995 if ($data['poll'] != '') {
996 $updated['poll'] = $data['poll'];
998 if ($data['batch'] != '') {
999 $updated['batch'] = $data['batch'];
1001 if ($data['request'] != '') {
1002 $updated['request'] = $data['request'];
1004 if ($data['confirm'] != '') {
1005 $updated['confirm'] = $data['confirm'];
1007 if ($data['poco'] != '') {
1008 $updated['poco'] = $data['poco'];
1011 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1012 if (empty($contact['pubkey'])) {
1013 $updated['pubkey'] = $data['pubkey'];
1016 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1017 $updated['uri-date'] = DateTimeFormat::utcNow();
1019 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1020 $updated['name-date'] = DateTimeFormat::utcNow();
1023 $updated['avatar-date'] = DateTimeFormat::utcNow();
1025 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1031 * @brief Checks if the contact is blocked
1033 * @param int $cid contact id
1035 * @return boolean Is the contact blocked?
1037 public static function isBlocked($cid)
1043 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1044 if (!DBA::isResult($blocked)) {
1047 return (bool) $blocked['blocked'];
1051 * @brief Checks if the contact is hidden
1053 * @param int $cid contact id
1055 * @return boolean Is the contact hidden?
1057 public static function isHidden($cid)
1063 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1064 if (!DBA::isResult($hidden)) {
1067 return (bool) $hidden['hidden'];
1071 * @brief Returns posts from a given contact url
1073 * @param string $contact_url Contact URL
1075 * @return string posts in HTML
1077 public static function getPostsFromUrl($contact_url)
1079 $a = self::getApp();
1081 require_once 'include/conversation.php';
1083 // There are no posts with "uid = 0" with connector networks
1084 // This speeds up the query a lot
1085 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1086 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1087 DBA::escape(normalise_link($contact_url))
1090 if (!DBA::isResult($r)) {
1094 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1095 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1097 $sql = "`item`.`uid` = ?";
1100 $author_id = intval($r[0]["author-id"]);
1102 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1104 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1105 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1106 $params = ['order' => ['created' => true],
1107 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1108 $r = Item::selectForUser(local_user(), [], $condition, $params);
1110 $items = Item::inArray($r);
1112 $o = conversation($a, $items, 'contact-posts', false);
1114 $o .= alt_pager($a, count($items));
1120 * @brief Returns the account type name
1122 * The function can be called with either the user or the contact array
1124 * @param array $contact contact or user array
1127 public static function getAccountType(array $contact)
1129 // There are several fields that indicate that the contact or user is a forum
1130 // "page-flags" is a field in the user table,
1131 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1132 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1133 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1134 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1135 || (isset($contact['forum']) && intval($contact['forum']))
1136 || (isset($contact['prv']) && intval($contact['prv']))
1137 || (isset($contact['community']) && intval($contact['community']))
1139 $type = self::ACCOUNT_TYPE_COMMUNITY;
1141 $type = self::ACCOUNT_TYPE_PERSON;
1144 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1145 if (isset($contact["contact-type"])) {
1146 $type = $contact["contact-type"];
1149 if (isset($contact["account-type"])) {
1150 $type = $contact["account-type"];
1154 case self::ACCOUNT_TYPE_ORGANISATION:
1155 $account_type = L10n::t("Organisation");
1158 case self::ACCOUNT_TYPE_NEWS:
1159 $account_type = L10n::t('News');
1162 case self::ACCOUNT_TYPE_COMMUNITY:
1163 $account_type = L10n::t("Forum");
1171 return $account_type;
1175 * @brief Blocks a contact
1180 public static function block($uid)
1182 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1188 * @brief Unblocks a contact
1193 public static function unblock($uid)
1195 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1201 * @brief Updates the avatar links in a contact only if needed
1203 * @param string $avatar Link to avatar picture
1204 * @param int $uid User id of contact owner
1205 * @param int $cid Contact id
1206 * @param bool $force force picture update
1208 * @return array Returns array of the different avatar sizes
1210 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1212 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1213 if (!DBA::isResult($contact)) {
1216 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1219 if (($contact["avatar"] != $avatar) || $force) {
1220 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1225 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1229 // Update the public contact (contact id = 0)
1231 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1232 if (DBA::isResult($pcontact)) {
1233 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1245 * @param integer $id contact id
1248 public static function updateFromProbe($id)
1251 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1252 This will reliably kill your communication with Friendica contacts.
1255 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1256 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1257 if (!DBA::isResult($contact)) {
1261 $ret = Probe::uri($contact["url"]);
1263 // If Probe::uri fails the network code will be different
1264 if ($ret["network"] != $contact["network"]) {
1270 // make sure to not overwrite existing values with blank entries
1271 foreach ($ret as $key => $val) {
1272 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1273 $ret[$key] = $contact[$key];
1276 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1287 'url' => $ret['url'],
1288 'nurl' => normalise_link($ret['url']),
1289 'addr' => $ret['addr'],
1290 'alias' => $ret['alias'],
1291 'batch' => $ret['batch'],
1292 'notify' => $ret['notify'],
1293 'poll' => $ret['poll'],
1294 'poco' => $ret['poco']
1299 // Update the corresponding gcontact entry
1300 PortableContact::lastUpdated($ret["url"]);
1306 * Takes a $uid and a url/handle and adds a new contact
1307 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1308 * dfrn_request page.
1310 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1313 * $return['success'] boolean true if successful
1314 * $return['message'] error text if success is false.
1316 * @brief Takes a $uid and a url/handle and adds a new contact
1318 * @param string $url
1319 * @param bool $interactive
1320 * @param string $network
1321 * @return boolean|string
1323 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1325 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1329 // remove ajax junk, e.g. Twitter
1330 $url = str_replace('/#!/', '/', $url);
1332 if (!Network::isUrlAllowed($url)) {
1333 $result['message'] = L10n::t('Disallowed profile URL.');
1337 if (Network::isUrlBlocked($url)) {
1338 $result['message'] = L10n::t('Blocked domain');
1343 $result['message'] = L10n::t('Connect URL missing.');
1347 $arr = ['url' => $url, 'contact' => []];
1349 Addon::callHooks('follow', $arr);
1352 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1356 if (x($arr['contact'], 'name')) {
1357 $ret = $arr['contact'];
1359 $ret = Probe::uri($url, $network, $uid, false);
1362 if (($network != '') && ($ret['network'] != $network)) {
1363 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1367 // check if we already have a contact
1368 // the poll url is more reliable than the profile url, as we may have
1369 // indirect links or webfinger links
1371 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1373 DBA::escape($ret['poll']),
1374 DBA::escape(normalise_link($ret['poll'])),
1375 DBA::escape($ret['network'])
1378 if (!DBA::isResult($r)) {
1379 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1381 DBA::escape(normalise_link($url)),
1382 DBA::escape($ret['network'])
1386 if (($ret['network'] === NETWORK_DFRN) && !DBA::isResult($r)) {
1388 if (strlen($a->urlpath)) {
1389 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1391 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1394 goaway($ret['request'] . "&addr=$myaddr");
1398 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != NETWORK_DFRN)) {
1399 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1400 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1404 // This extra param just confuses things, remove it
1405 if ($ret['network'] === NETWORK_DIASPORA) {
1406 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1409 // do we have enough information?
1411 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1412 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1413 if (!x($ret, 'poll')) {
1414 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1416 if (!x($ret, 'name')) {
1417 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1419 if (!x($ret, 'url')) {
1420 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1422 if (strpos($url, '@') !== false) {
1423 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1424 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1429 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1430 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1431 $ret['notify'] = '';
1434 if (!$ret['notify']) {
1435 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1438 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1440 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1442 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1444 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1448 if (DBA::isResult($r)) {
1450 $new_relation = (($r[0]['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1452 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1453 DBA::update('contact', $fields, ['id' => $r[0]['id']]);
1455 $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? self::FRIEND : self::SHARING);
1457 // create contact record
1458 DBA::insert('contact', [
1460 'created' => DateTimeFormat::utcNow(),
1461 'url' => $ret['url'],
1462 'nurl' => normalise_link($ret['url']),
1463 'addr' => $ret['addr'],
1464 'alias' => $ret['alias'],
1465 'batch' => $ret['batch'],
1466 'notify' => $ret['notify'],
1467 'poll' => $ret['poll'],
1468 'poco' => $ret['poco'],
1469 'name' => $ret['name'],
1470 'nick' => $ret['nick'],
1471 'network' => $ret['network'],
1472 'pubkey' => $ret['pubkey'],
1473 'rel' => $new_relation,
1474 'priority'=> $ret['priority'],
1475 'writable'=> $writeable,
1476 'hidden' => $hidden,
1484 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1485 if (!DBA::isResult($contact)) {
1486 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1490 $contact_id = $contact['id'];
1491 $result['cid'] = $contact_id;
1493 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1495 // Update the avatar
1496 self::updateAvatar($ret['photo'], $uid, $contact_id);
1498 // pull feed and consume it, which should subscribe to the hub.
1500 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1502 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1503 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1507 if (DBA::isResult($r)) {
1508 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
1509 // create a follow slap
1511 $item['verb'] = ACTIVITY_FOLLOW;
1512 $item['follow'] = $contact["url"];
1514 $item['title'] = '';
1517 $item['attach'] = '';
1518 $slap = OStatus::salmon($item, $r[0]);
1519 if (!empty($contact['notify'])) {
1520 Salmon::slapper($r[0], $contact['notify'], $slap);
1522 } elseif ($contact['network'] == NETWORK_DIASPORA) {
1523 $ret = Diaspora::sendShare($a->user, $contact);
1524 logger('share returns: ' . $ret);
1528 $result['success'] = true;
1532 public static function updateSslPolicy($contact, $new_policy)
1534 $ssl_changed = false;
1535 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1536 $ssl_changed = true;
1537 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1538 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1539 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1540 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1541 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1542 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1545 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1546 $ssl_changed = true;
1547 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1548 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1549 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1550 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1551 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1552 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1556 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1557 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1558 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1559 DBA::update('contact', $fields, ['id' => $contact['id']]);
1565 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1566 $url = notags(trim($datarray['author-link']));
1567 $name = notags(trim($datarray['author-name']));
1568 $photo = notags(trim($datarray['author-avatar']));
1571 if (is_object($item)) {
1572 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1573 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1574 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1580 if (is_array($contact)) {
1581 if (($contact['rel'] == self::SHARING)
1582 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1583 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1584 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1586 // send email notification to owner?
1588 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1589 logger('ignoring duplicated connection request from pending contact ' . $url);
1593 // create contact record
1594 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1595 `blocked`, `readonly`, `pending`, `writable`)
1596 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1597 intval($importer['uid']),
1598 DBA::escape(DateTimeFormat::utcNow()),
1600 DBA::escape(normalise_link($url)),
1603 DBA::escape($photo),
1604 DBA::escape(NETWORK_OSTATUS),
1605 intval(self::FOLLOWER)
1609 'id' => DBA::lastInsertId(),
1610 'network' => NETWORK_OSTATUS,
1616 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1618 /// @TODO Encapsulate this into a function/method
1619 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1620 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1621 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1622 // create notification
1623 $hash = random_string();
1625 if (is_array($contact_record)) {
1626 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1627 'blocked' => false, 'knowyou' => false,
1628 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1631 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1633 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1634 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1637 'type' => NOTIFY_INTRO,
1638 'notify_flags' => $user['notify-flags'],
1639 'language' => $user['language'],
1640 'to_name' => $user['username'],
1641 'to_email' => $user['email'],
1642 'uid' => $user['uid'],
1643 'link' => System::baseUrl() . '/notifications/intro',
1644 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1645 'source_link' => $contact_record['url'],
1646 'source_photo' => $contact_record['photo'],
1647 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1652 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1653 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1654 intval($importer['uid']),
1661 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1663 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1664 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1666 Contact::remove($contact['id']);
1670 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1672 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1673 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1675 Contact::remove($contact['id']);
1680 * @brief Create a birthday event.
1682 * Update the year and the birthday.
1684 public static function updateBirthdays()
1686 // This only handles foreign or alien networks where a birthday has been provided.
1687 // In-network birthdays are handled within local_delivery
1689 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1690 if (DBA::isResult($r)) {
1691 foreach ($r as $rr) {
1692 logger('update_contact_birthday: ' . $rr['bd']);
1694 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1697 * Add new birthday event for this person
1699 * $bdtext is just a readable placeholder in case the event is shared
1700 * with others. We will replace it during presentation to our $importer
1701 * to contain a sparkle link and perhaps a photo.
1704 // Check for duplicates
1705 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1706 intval($rr['uid']), intval($rr['id']), DBA::escape(DateTimeFormat::utc($nextbd)), DBA::escape('birthday'));
1708 if (DBA::isResult($s)) {
1712 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1713 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1715 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1716 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1717 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1718 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1724 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1725 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1732 * Remove the unavailable contact ids from the provided list
1734 * @param array $contact_ids Contact id list
1736 public static function pruneUnavailable(array &$contact_ids)
1738 if (empty($contact_ids)) {
1742 $str = DBA::escape(implode(',', $contact_ids));
1744 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1747 while($contact = DBA::fetch($stmt)) {
1748 $return[] = $contact['id'];
1753 $contact_ids = $return;
1757 * @brief Returns a magic link to authenticate remote visitors
1759 * @param string $contact_url The address of the target contact profile
1760 * @param integer $url An url that we will be redirected to after the authentication
1762 * @return string with "redir" link
1764 public static function magicLink($contact_url, $url = '')
1766 $cid = self::getIdForURL($contact_url, 0, true);
1768 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
1771 return self::magicLinkbyId($cid, $url);
1775 * @brief Returns a magic link to authenticate remote visitors
1777 * @param integer $cid The contact id of the target contact profile
1778 * @param integer $url An url that we will be redirected to after the authentication
1780 * @return string with "redir" link
1782 public static function magicLinkbyId($cid, $url = '')
1784 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
1786 return self::magicLinkbyContact($contact, $url);
1790 * @brief Returns a magic link to authenticate remote visitors
1792 * @param array $contact The contact array with "uid", "network" and "url"
1793 * @param integer $url An url that we will be redirected to after the authentication
1795 * @return string with "redir" link
1797 public static function magicLinkbyContact($contact, $url = '')
1799 if ($contact['network'] != NETWORK_DFRN) {
1800 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
1803 // Only redirections to the same host do make sense
1804 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1808 if ($contact['uid'] != 0) {
1809 return self::magicLink($contact['url'], $url);
1812 $redirect = 'redir/' . $contact['id'];
1815 $redirect .= '?url=' . $url;