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\Network\Probe;
16 use Friendica\Object\Image;
17 use Friendica\Protocol\Diaspora;
18 use Friendica\Protocol\OStatus;
19 use Friendica\Protocol\PortableContact;
20 use Friendica\Protocol\Salmon;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
24 require_once 'boot.php';
25 require_once 'include/dba.php';
26 require_once 'include/text.php';
29 * @brief functions for interacting with a contact
31 class Contact extends BaseObject
34 * @brief Returns a list of contacts belonging in a group
39 public static function getByGroupId($gid)
43 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
45 INNER JOIN `group_member`
46 ON `contact`.`id` = `group_member`.`contact-id`
48 AND `contact`.`uid` = ?
49 AND NOT `contact`.`self`
50 AND NOT `contact`.`blocked`
51 AND NOT `contact`.`pending`
52 ORDER BY `contact`.`name` ASC',
56 if (DBA::isResult($stmt)) {
57 $return = DBA::toArray($stmt);
65 * @brief Returns the count of OStatus contacts in a group
70 public static function getOStatusCountByGroupId($gid)
74 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
76 INNER JOIN `group_member`
77 ON `contact`.`id` = `group_member`.`contact-id`
79 AND `contact`.`uid` = ?
80 AND `contact`.`network` = ?
81 AND `contact`.`notify` != ""',
86 $return = $contacts['count'];
93 * Creates the self-contact for the provided user id
96 * @return bool Operation success
98 public static function createSelfFromUserId($uid)
100 // Only create the entry if it doesn't exist yet
101 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
105 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
106 if (!DBA::isResult($user)) {
110 $return = DBA::insert('contact', [
111 'uid' => $user['uid'],
112 'created' => DateTimeFormat::utcNow(),
114 'name' => $user['username'],
115 'nick' => $user['nickname'],
116 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
117 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
118 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
121 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
122 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
123 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
124 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
125 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
126 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
127 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
128 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
129 'name-date' => DateTimeFormat::utcNow(),
130 'uri-date' => DateTimeFormat::utcNow(),
131 'avatar-date' => DateTimeFormat::utcNow(),
139 * Updates the self-contact for the provided user id
142 * @param boolean $update_avatar Force the avatar update
144 public static function updateSelfFromUserID($uid, $update_avatar = false)
146 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
147 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
148 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
149 if (!DBA::isResult($self)) {
153 $fields = ['nickname', 'page-flags', 'account-type'];
154 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
155 if (!DBA::isResult($user)) {
159 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
160 'country-name', 'gender', 'pub_keywords', 'xmpp'];
161 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
162 if (!DBA::isResult($profile)) {
166 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
167 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
168 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
169 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
170 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
172 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
173 if (DBA::isResult($avatar)) {
174 if ($update_avatar) {
175 $fields['avatar-date'] = DateTimeFormat::utcNow();
178 // Creating the path to the avatar, beginning with the file suffix
179 $types = Image::supportedTypes();
180 if (isset($types[$avatar['type']])) {
181 $file_suffix = $types[$avatar['type']];
183 $file_suffix = 'jpg';
186 // We are adding a timestamp value so that other systems won't use cached content
187 $timestamp = strtotime($fields['avatar-date']);
189 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
190 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
192 $fields['photo'] = $prefix . '4' . $suffix;
193 $fields['thumb'] = $prefix . '5' . $suffix;
194 $fields['micro'] = $prefix . '6' . $suffix;
196 // We hadn't found a photo entry, so we use the default avatar
197 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
198 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
199 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
202 $fields['forum'] = $user['page-flags'] == PAGE_COMMUNITY;
203 $fields['prv'] = $user['page-flags'] == PAGE_PRVGROUP;
205 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
206 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
207 $fields['nurl'] = normalise_link($fields['url']);
208 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
209 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
210 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
211 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
212 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
213 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
217 foreach ($fields as $field => $content) {
218 if (isset($self[$field]) && $self[$field] != $content) {
224 $fields['name-date'] = DateTimeFormat::utcNow();
225 DBA::update('contact', $fields, ['id' => $self['id']]);
227 // Update the public contact as well
228 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
230 // Update the profile
231 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
232 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
233 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
238 * @brief Marks a contact for removal
240 * @param int $id contact id
243 public static function remove($id)
245 // We want just to make sure that we don't delete our "self" contact
246 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
247 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
251 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
253 DBA::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
257 DBA::delete('contact', ['id' => $id]);
259 // Delete the rest in the background
260 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
264 * @brief Sends an unfriend message. Does not remove the contact
266 * @param array $user User unfriending
267 * @param array $contact Contact unfriended
270 public static function terminateFriendship(array $user, array $contact)
272 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
273 // create an unfollow slap
275 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
276 $item['follow'] = $contact["url"];
277 $slap = OStatus::salmon($item, $user);
279 if (!empty($contact['notify'])) {
280 Salmon::slapper($user, $contact['notify'], $slap);
282 } elseif ($contact['network'] == NETWORK_DIASPORA) {
283 Diaspora::sendUnshare($user, $contact);
288 * @brief Marks a contact for archival after a communication issue delay
290 * Contact has refused to recognise us as a friend. We will start a countdown.
291 * If they still don't recognise us in 32 days, the relationship is over,
292 * and we won't waste any more time trying to communicate with them.
293 * This provides for the possibility that their database is temporarily messed
294 * up or some other transient event and that there's a possibility we could recover from it.
296 * @param array $contact contact to mark for archival
299 public static function markForArchival(array $contact)
301 // Contact already archived or "self" contact? => nothing to do
302 if ($contact['archive'] || $contact['self']) {
306 if ($contact['term-date'] <= NULL_DATE) {
307 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
309 if ($contact['url'] != '') {
310 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
314 * We really should send a notification to the owner after 2-3 weeks
315 * so they won't be surprised when the contact vanishes and can take
316 * remedial action if this was a serious mistake or glitch
319 /// @todo Check for contact vitality via probing
320 $archival_days = Config::get('system', 'archival_days', 32);
322 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
323 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
324 /* Relationship is really truly dead. archive them rather than
325 * delete, though if the owner tries to unarchive them we'll start
326 * the whole process over again.
328 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
330 if ($contact['url'] != '') {
331 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
338 * @brief Cancels the archival countdown
340 * @see Contact::markForArchival()
342 * @param array $contact contact to be unmarked for archival
345 public static function unmarkForArchival(array $contact)
347 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
348 $exists = DBA::exists('contact', $condition);
350 // We don't need to update, we never marked this contact for archival
355 // It's a miracle. Our dead contact has inexplicably come back to life.
356 $fields = ['term-date' => NULL_DATE, 'archive' => false];
357 DBA::update('contact', $fields, ['id' => $contact['id']]);
359 if (!empty($contact['url'])) {
360 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
363 if (!empty($contact['batch'])) {
364 $condition = ['batch' => $contact['batch'], 'contact-type' => ACCOUNT_TYPE_RELAY];
365 DBA::update('contact', $fields, $condition);
370 * @brief Get contact data for a given profile link
372 * The function looks at several places (contact table and gcontact table) for the contact
373 * It caches its result for the same script execution to prevent duplicate calls
375 * @param string $url The profile link
376 * @param int $uid User id
377 * @param array $default If not data was found take this data as default value
379 * @return array Contact data
381 public static function getDetailsByURL($url, $uid = -1, array $default = [])
393 if (isset($cache[$url][$uid])) {
394 return $cache[$url][$uid];
397 $ssl_url = str_replace('http://', 'https://', $url);
399 // Fetch contact data from the contact table for the given user
400 $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`,
401 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
402 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
403 $r = DBA::toArray($s);
405 // Fetch contact data from the contact table for the given user, checking with the alias
406 if (!DBA::isResult($r)) {
407 $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`,
408 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
409 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
410 $r = DBA::toArray($s);
413 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
414 if (!DBA::isResult($r)) {
415 $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`,
416 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
417 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
418 $r = DBA::toArray($s);
421 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
422 if (!DBA::isResult($r)) {
423 $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`,
424 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
425 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
426 $r = DBA::toArray($s);
429 // Fetch the data from the gcontact table
430 if (!DBA::isResult($r)) {
431 $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`,
432 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
433 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
434 $r = DBA::toArray($s);
437 if (DBA::isResult($r)) {
438 // If there is more than one entry we filter out the connector networks
440 foreach ($r as $id => $result) {
441 if ($result["network"] == NETWORK_STATUSNET) {
447 $profile = array_shift($r);
449 // "bd" always contains the upcoming birthday of a contact.
450 // "birthday" might contain the birthday including the year of birth.
451 if ($profile["birthday"] > '0001-01-01') {
452 $bd_timestamp = strtotime($profile["birthday"]);
453 $month = date("m", $bd_timestamp);
454 $day = date("d", $bd_timestamp);
456 $current_timestamp = time();
457 $current_year = date("Y", $current_timestamp);
458 $current_month = date("m", $current_timestamp);
459 $current_day = date("d", $current_timestamp);
461 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
462 $current = $current_year . "-" . $current_month . "-" . $current_day;
464 if ($profile["bd"] < $current) {
465 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
468 $profile["bd"] = '0001-01-01';
474 if (empty($profile["photo"]) && isset($default["photo"])) {
475 $profile["photo"] = $default["photo"];
478 if (empty($profile["name"]) && isset($default["name"])) {
479 $profile["name"] = $default["name"];
482 if (empty($profile["network"]) && isset($default["network"])) {
483 $profile["network"] = $default["network"];
486 if (empty($profile["thumb"]) && isset($profile["photo"])) {
487 $profile["thumb"] = $profile["photo"];
490 if (empty($profile["micro"]) && isset($profile["thumb"])) {
491 $profile["micro"] = $profile["thumb"];
494 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
495 && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
497 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
500 // Show contact details of Diaspora contacts only if connected
501 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == NETWORK_DIASPORA)) {
502 $profile["location"] = "";
503 $profile["about"] = "";
504 $profile["gender"] = "";
505 $profile["birthday"] = '0001-01-01';
508 $cache[$url][$uid] = $profile;
514 * @brief Get contact data for a given address
516 * The function looks at several places (contact table and gcontact table) for the contact
518 * @param string $addr The profile link
519 * @param int $uid User id
521 * @return array Contact data
523 public static function getDetailsByAddr($addr, $uid = -1)
535 // Fetch contact data from the contact table for the given user
536 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
537 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
538 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
542 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
543 if (!DBA::isResult($r)) {
544 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
545 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
546 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
551 // Fetch the data from the gcontact table
552 if (!DBA::isResult($r)) {
553 $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`,
554 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
555 FROM `gcontact` WHERE `addr` = '%s'",
560 if (!DBA::isResult($r)) {
561 $data = Probe::uri($addr);
563 $profile = self::getDetailsByURL($data['url'], $uid);
572 * @brief Returns the data array for the photo menu of a given contact
574 * @param array $contact contact
575 * @param int $uid optional, default 0
578 public static function photoMenu(array $contact, $uid = 0)
580 // @todo Unused, to be removed
588 $contact_drop_link = '';
595 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
597 $profile_link = self::magicLink($contact['url']);
598 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
603 // Look for our own contact if the uid doesn't match and isn't public
604 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
605 if (DBA::isResult($contact_own)) {
606 return self::photoMenu($contact_own, $uid);
608 $profile_link = self::magicLink($contact['url']);
609 $connlnk = 'follow/?url=' . $contact['url'];
611 'profile' => [L10n::t('View Profile'), $profile_link, true],
612 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
620 if (($contact['network'] === NETWORK_DFRN) && !$contact['self']) {
622 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
624 $profile_link = $contact['url'];
627 if ($profile_link === 'mailbox') {
632 $status_link = $profile_link . '?url=status';
633 $photos_link = $profile_link . '?url=photos';
634 $profile_link = $profile_link . '?url=profile';
637 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA]) && !$contact['self']) {
638 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
641 if (($contact['network'] == NETWORK_DFRN) && !$contact['self']) {
642 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
645 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
647 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
649 if (!$contact['self']) {
650 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
655 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
658 'status' => [L10n::t("View Status") , $status_link , true],
659 'profile' => [L10n::t("View Profile") , $profile_link , true],
660 'photos' => [L10n::t("View Photos") , $photos_link , true],
661 'network' => [L10n::t("Network Posts"), $posts_link , false],
662 'edit' => [L10n::t("View Contact") , $contact_url , false],
663 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
664 'pm' => [L10n::t("Send PM") , $pm_url , false],
665 'poke' => [L10n::t("Poke") , $poke_link , false],
668 $args = ['contact' => $contact, 'menu' => &$menu];
670 Addon::callHooks('contact_photo_menu', $args);
674 foreach ($menu as $menuname => $menuitem) {
675 if ($menuitem[1] != '') {
676 $menucondensed[$menuname] = $menuitem;
680 return $menucondensed;
684 * @brief Returns ungrouped contact count or list for user
686 * Returns either the total number of ungrouped contacts for the given user
687 * id or a paginated list of ungrouped contacts.
689 * @param int $uid uid
690 * @param int $start optional, default 0
691 * @param int $count optional, default 0
695 public static function getUngroupedList($uid)
704 SELECT DISTINCT(`contact-id`)
706 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
707 WHERE `group`.`uid` = %d
708 )", intval($uid), intval($uid));
712 * @brief Fetch the contact id for a given URL and user
714 * First lookup in the contact table to find a record matching either `url`, `nurl`,
717 * If there's no record and we aren't looking for a public contact, we quit.
718 * If there's one, we check that it isn't time to update the picture else we
719 * directly return the found contact id.
721 * Second, we probe the provided $url whether it's http://server.tld/profile or
722 * nick@server.tld. We quit if we can't get any info back.
724 * Third, we create the contact record if it doesn't exist
726 * Fourth, we update the existing record with the new data (avatar, alias, nick)
727 * if there's any updates
729 * @param string $url Contact URL
730 * @param integer $uid The user id for the contact (0 = public contact)
731 * @param boolean $no_update Don't update the contact
732 * @param array $default Default value for creating the contact when every else fails
734 * @return integer Contact ID
736 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
738 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
746 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
747 // We first try the nurl (http://server.tld/nick), most common case
748 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
750 // Then the addr (nick@server.tld)
751 if (!DBA::isResult($contact)) {
752 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
755 // Then the alias (which could be anything)
756 if (!DBA::isResult($contact)) {
757 // The link could be provided as http although we stored it as https
758 $ssl_url = str_replace('http://', 'https://', $url);
759 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
760 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
763 if (DBA::isResult($contact)) {
764 $contact_id = $contact["id"];
766 // Update the contact every 7 days
767 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
769 // We force the update if the avatar is empty
770 if (!x($contact, 'avatar')) {
771 $update_contact = true;
774 if (!$update_contact || $no_update) {
777 } elseif ($uid != 0) {
778 // Non-existing user-specific contact, exiting
782 $data = Probe::uri($url, "", $uid);
784 // Last try in gcontact for unsupported networks
785 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL, NETWORK_FEED])) {
790 // Get data from the gcontact table
791 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
792 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
793 if (!DBA::isResult($contact)) {
794 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
797 if (!DBA::isResult($contact)) {
798 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
799 'photo', 'keywords', 'location', 'about', 'network',
800 'priority', 'batch', 'request', 'confirm', 'poco'];
801 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
804 if (!DBA::isResult($contact)) {
805 // The link could be provided as http although we stored it as https
806 $ssl_url = str_replace('http://', 'https://', $url);
807 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
808 $contact = DBA::selectFirst('contact', $fields, $condition);
811 if (!DBA::isResult($contact)) {
812 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
813 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
814 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
815 $contact = DBA::selectFirst('fcontact', $fields, $condition);
818 if (!empty($default)) {
822 if (!DBA::isResult($contact)) {
825 $data = array_merge($data, $contact);
829 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
830 $contact_id = self::getIdForURL($data["alias"], $uid, true);
835 DBA::insert('contact', [
837 'created' => DateTimeFormat::utcNow(),
838 'url' => $data["url"],
839 'nurl' => normalise_link($data["url"]),
840 'addr' => $data["addr"],
841 'alias' => $data["alias"],
842 'notify' => $data["notify"],
843 'poll' => $data["poll"],
844 'name' => $data["name"],
845 'nick' => $data["nick"],
846 'photo' => $data["photo"],
847 'keywords' => $data["keywords"],
848 'location' => $data["location"],
849 'about' => $data["about"],
850 'network' => $data["network"],
851 'pubkey' => $data["pubkey"],
852 'rel' => CONTACT_IS_SHARING,
853 'priority' => $data["priority"],
854 'batch' => $data["batch"],
855 'request' => $data["request"],
856 'confirm' => $data["confirm"],
857 'poco' => $data["poco"],
858 'name-date' => DateTimeFormat::utcNow(),
859 'uri-date' => DateTimeFormat::utcNow(),
860 'avatar-date' => DateTimeFormat::utcNow(),
867 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
868 $contacts = DBA::toArray($s);
869 if (!DBA::isResult($contacts)) {
873 $contact_id = $contacts[0]["id"];
875 // Update the newly created contact from data in the gcontact table
876 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
877 if (DBA::isResult($gcontact)) {
878 // Only use the information when the probing hadn't fetched these values
879 if ($data['keywords'] != '') {
880 unset($gcontact['keywords']);
882 if ($data['location'] != '') {
883 unset($gcontact['location']);
885 if ($data['about'] != '') {
886 unset($gcontact['about']);
888 DBA::update('contact', $gcontact, ['id' => $contact_id]);
891 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
892 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
893 normalise_link($data["url"]), $contact_id]);
897 self::updateAvatar($data["photo"], $uid, $contact_id);
899 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
900 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
902 // This condition should always be true
903 if (!DBA::isResult($contact)) {
907 $updated = ['addr' => $data['addr'],
908 'alias' => $data['alias'],
909 'url' => $data['url'],
910 'nurl' => normalise_link($data['url']),
911 'name' => $data['name'],
912 'nick' => $data['nick']];
914 if ($data['keywords'] != '') {
915 $updated['keywords'] = $data['keywords'];
917 if ($data['location'] != '') {
918 $updated['location'] = $data['location'];
921 // Update the technical stuff as well - if filled
922 if ($data['notify'] != '') {
923 $updated['notify'] = $data['notify'];
925 if ($data['poll'] != '') {
926 $updated['poll'] = $data['poll'];
928 if ($data['batch'] != '') {
929 $updated['batch'] = $data['batch'];
931 if ($data['request'] != '') {
932 $updated['request'] = $data['request'];
934 if ($data['confirm'] != '') {
935 $updated['confirm'] = $data['confirm'];
937 if ($data['poco'] != '') {
938 $updated['poco'] = $data['poco'];
941 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
942 if (empty($contact['pubkey'])) {
943 $updated['pubkey'] = $data['pubkey'];
946 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
947 $updated['uri-date'] = DateTimeFormat::utcNow();
949 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
950 $updated['name-date'] = DateTimeFormat::utcNow();
953 $updated['avatar-date'] = DateTimeFormat::utcNow();
955 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
961 * @brief Checks if the contact is blocked
963 * @param int $cid contact id
965 * @return boolean Is the contact blocked?
967 public static function isBlocked($cid)
973 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
974 if (!DBA::isResult($blocked)) {
977 return (bool) $blocked['blocked'];
981 * @brief Checks if the contact is hidden
983 * @param int $cid contact id
985 * @return boolean Is the contact hidden?
987 public static function isHidden($cid)
993 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
994 if (!DBA::isResult($hidden)) {
997 return (bool) $hidden['hidden'];
1001 * @brief Returns posts from a given contact url
1003 * @param string $contact_url Contact URL
1005 * @return string posts in HTML
1007 public static function getPostsFromUrl($contact_url)
1009 $a = self::getApp();
1011 require_once 'include/conversation.php';
1013 // There are no posts with "uid = 0" with connector networks
1014 // This speeds up the query a lot
1015 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1016 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1017 DBA::escape(normalise_link($contact_url))
1020 if (!DBA::isResult($r)) {
1024 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1025 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1027 $sql = "`item`.`uid` = ?";
1030 $author_id = intval($r[0]["author-id"]);
1032 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1034 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1035 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1036 $params = ['order' => ['created' => true],
1037 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1038 $r = Item::selectForUser(local_user(), [], $condition, $params);
1040 $items = Item::inArray($r);
1042 $o = conversation($a, $items, 'contact-posts', false);
1044 $o .= alt_pager($a, count($items));
1050 * @brief Returns the account type name
1052 * The function can be called with either the user or the contact array
1054 * @param array $contact contact or user array
1057 public static function getAccountType(array $contact)
1059 // There are several fields that indicate that the contact or user is a forum
1060 // "page-flags" is a field in the user table,
1061 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
1062 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
1063 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
1064 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
1065 || (isset($contact['forum']) && intval($contact['forum']))
1066 || (isset($contact['prv']) && intval($contact['prv']))
1067 || (isset($contact['community']) && intval($contact['community']))
1069 $type = ACCOUNT_TYPE_COMMUNITY;
1071 $type = ACCOUNT_TYPE_PERSON;
1074 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1075 if (isset($contact["contact-type"])) {
1076 $type = $contact["contact-type"];
1079 if (isset($contact["account-type"])) {
1080 $type = $contact["account-type"];
1084 case ACCOUNT_TYPE_ORGANISATION:
1085 $account_type = L10n::t("Organisation");
1087 case ACCOUNT_TYPE_NEWS:
1088 $account_type = L10n::t('News');
1090 case ACCOUNT_TYPE_COMMUNITY:
1091 $account_type = L10n::t("Forum");
1098 return $account_type;
1102 * @brief Blocks a contact
1107 public static function block($uid)
1109 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1115 * @brief Unblocks a contact
1120 public static function unblock($uid)
1122 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1128 * @brief Updates the avatar links in a contact only if needed
1130 * @param string $avatar Link to avatar picture
1131 * @param int $uid User id of contact owner
1132 * @param int $cid Contact id
1133 * @param bool $force force picture update
1135 * @return array Returns array of the different avatar sizes
1137 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1139 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1140 if (!DBA::isResult($contact)) {
1143 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1146 if (($contact["avatar"] != $avatar) || $force) {
1147 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1152 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1156 // Update the public contact (contact id = 0)
1158 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1159 if (DBA::isResult($pcontact)) {
1160 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1172 * @param integer $id contact id
1175 public static function updateFromProbe($id)
1178 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1179 This will reliably kill your communication with Friendica contacts.
1182 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1183 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1184 if (!DBA::isResult($contact)) {
1188 $ret = Probe::uri($contact["url"]);
1190 // If Probe::uri fails the network code will be different
1191 if ($ret["network"] != $contact["network"]) {
1197 // make sure to not overwrite existing values with blank entries
1198 foreach ($ret as $key => $val) {
1199 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1200 $ret[$key] = $contact[$key];
1203 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1214 'url' => $ret['url'],
1215 'nurl' => normalise_link($ret['url']),
1216 'addr' => $ret['addr'],
1217 'alias' => $ret['alias'],
1218 'batch' => $ret['batch'],
1219 'notify' => $ret['notify'],
1220 'poll' => $ret['poll'],
1221 'poco' => $ret['poco']
1226 // Update the corresponding gcontact entry
1227 PortableContact::lastUpdated($ret["url"]);
1233 * Takes a $uid and a url/handle and adds a new contact
1234 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1235 * dfrn_request page.
1237 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1240 * $return['success'] boolean true if successful
1241 * $return['message'] error text if success is false.
1243 * @brief Takes a $uid and a url/handle and adds a new contact
1245 * @param string $url
1246 * @param bool $interactive
1247 * @param string $network
1248 * @return boolean|string
1250 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1252 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1256 // remove ajax junk, e.g. Twitter
1257 $url = str_replace('/#!/', '/', $url);
1259 if (!Network::isUrlAllowed($url)) {
1260 $result['message'] = L10n::t('Disallowed profile URL.');
1264 if (Network::isUrlBlocked($url)) {
1265 $result['message'] = L10n::t('Blocked domain');
1270 $result['message'] = L10n::t('Connect URL missing.');
1274 $arr = ['url' => $url, 'contact' => []];
1276 Addon::callHooks('follow', $arr);
1279 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1283 if (x($arr['contact'], 'name')) {
1284 $ret = $arr['contact'];
1286 $ret = Probe::uri($url, $network, $uid, false);
1289 if (($network != '') && ($ret['network'] != $network)) {
1290 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1294 // check if we already have a contact
1295 // the poll url is more reliable than the profile url, as we may have
1296 // indirect links or webfinger links
1298 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1300 DBA::escape($ret['poll']),
1301 DBA::escape(normalise_link($ret['poll'])),
1302 DBA::escape($ret['network'])
1305 if (!DBA::isResult($r)) {
1306 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1308 DBA::escape(normalise_link($url)),
1309 DBA::escape($ret['network'])
1313 if (($ret['network'] === NETWORK_DFRN) && !DBA::isResult($r)) {
1315 if (strlen($a->urlpath)) {
1316 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1318 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1321 goaway($ret['request'] . "&addr=$myaddr");
1325 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != NETWORK_DFRN)) {
1326 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1327 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1331 // This extra param just confuses things, remove it
1332 if ($ret['network'] === NETWORK_DIASPORA) {
1333 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1336 // do we have enough information?
1338 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1339 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1340 if (!x($ret, 'poll')) {
1341 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1343 if (!x($ret, 'name')) {
1344 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1346 if (!x($ret, 'url')) {
1347 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1349 if (strpos($url, '@') !== false) {
1350 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1351 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1356 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1357 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1358 $ret['notify'] = '';
1361 if (!$ret['notify']) {
1362 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1365 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1367 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1369 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1371 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1375 if (DBA::isResult($r)) {
1377 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1379 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1380 DBA::update('contact', $fields, ['id' => $r[0]['id']]);
1382 $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1384 // create contact record
1385 DBA::insert('contact', [
1387 'created' => DateTimeFormat::utcNow(),
1388 'url' => $ret['url'],
1389 'nurl' => normalise_link($ret['url']),
1390 'addr' => $ret['addr'],
1391 'alias' => $ret['alias'],
1392 'batch' => $ret['batch'],
1393 'notify' => $ret['notify'],
1394 'poll' => $ret['poll'],
1395 'poco' => $ret['poco'],
1396 'name' => $ret['name'],
1397 'nick' => $ret['nick'],
1398 'network' => $ret['network'],
1399 'pubkey' => $ret['pubkey'],
1400 'rel' => $new_relation,
1401 'priority'=> $ret['priority'],
1402 'writable'=> $writeable,
1403 'hidden' => $hidden,
1411 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1412 if (!DBA::isResult($contact)) {
1413 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1417 $contact_id = $contact['id'];
1418 $result['cid'] = $contact_id;
1420 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1422 // Update the avatar
1423 self::updateAvatar($ret['photo'], $uid, $contact_id);
1425 // pull feed and consume it, which should subscribe to the hub.
1427 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1429 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1430 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1434 if (DBA::isResult($r)) {
1435 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
1436 // create a follow slap
1438 $item['verb'] = ACTIVITY_FOLLOW;
1439 $item['follow'] = $contact["url"];
1440 $slap = OStatus::salmon($item, $r[0]);
1441 if (!empty($contact['notify'])) {
1442 Salmon::slapper($r[0], $contact['notify'], $slap);
1444 } elseif ($contact['network'] == NETWORK_DIASPORA) {
1445 $ret = Diaspora::sendShare($a->user, $contact);
1446 logger('share returns: ' . $ret);
1450 $result['success'] = true;
1454 public static function updateSslPolicy($contact, $new_policy)
1456 $ssl_changed = false;
1457 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1458 $ssl_changed = true;
1459 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1460 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1461 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1462 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1463 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1464 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1467 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1468 $ssl_changed = true;
1469 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1470 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1471 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1472 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1473 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1474 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1478 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1479 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1480 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1481 DBA::update('contact', $fields, ['id' => $contact['id']]);
1487 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1488 $url = notags(trim($datarray['author-link']));
1489 $name = notags(trim($datarray['author-name']));
1490 $photo = notags(trim($datarray['author-avatar']));
1493 if (is_object($item)) {
1494 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1495 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1496 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1502 if (is_array($contact)) {
1503 if (($contact['rel'] == CONTACT_IS_SHARING)
1504 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1505 DBA::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1506 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1508 // send email notification to owner?
1510 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1511 logger('ignoring duplicated connection request from pending contact ' . $url);
1515 // create contact record
1516 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1517 `blocked`, `readonly`, `pending`, `writable`)
1518 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1519 intval($importer['uid']),
1520 DBA::escape(DateTimeFormat::utcNow()),
1522 DBA::escape(normalise_link($url)),
1525 DBA::escape($photo),
1526 DBA::escape(NETWORK_OSTATUS),
1527 intval(CONTACT_IS_FOLLOWER)
1531 'id' => DBA::lastInsertId(),
1532 'network' => NETWORK_OSTATUS,
1538 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1540 /// @TODO Encapsulate this into a function/method
1541 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1542 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1543 if (DBA::isResult($user) && !in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1544 // create notification
1545 $hash = random_string();
1547 if (is_array($contact_record)) {
1548 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1549 'blocked' => false, 'knowyou' => false,
1550 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1553 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1555 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1556 in_array($user['page-flags'], [PAGE_NORMAL])) {
1559 'type' => NOTIFY_INTRO,
1560 'notify_flags' => $user['notify-flags'],
1561 'language' => $user['language'],
1562 'to_name' => $user['username'],
1563 'to_email' => $user['email'],
1564 'uid' => $user['uid'],
1565 'link' => System::baseUrl() . '/notifications/intro',
1566 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1567 'source_link' => $contact_record['url'],
1568 'source_photo' => $contact_record['photo'],
1569 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1574 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1575 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1576 intval($importer['uid']),
1583 public static function removeFollower($importer, $contact, array $datarray = [], $item = "") {
1585 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1586 DBA::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1588 Contact::remove($contact['id']);
1592 public static function removeSharer($importer, $contact, array $datarray = [], $item = "") {
1594 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1595 DBA::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1597 Contact::remove($contact['id']);
1602 * @brief Create a birthday event.
1604 * Update the year and the birthday.
1606 public static function updateBirthdays()
1608 // This only handles foreign or alien networks where a birthday has been provided.
1609 // In-network birthdays are handled within local_delivery
1611 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1612 if (DBA::isResult($r)) {
1613 foreach ($r as $rr) {
1614 logger('update_contact_birthday: ' . $rr['bd']);
1616 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1619 * Add new birthday event for this person
1621 * $bdtext is just a readable placeholder in case the event is shared
1622 * with others. We will replace it during presentation to our $importer
1623 * to contain a sparkle link and perhaps a photo.
1626 // Check for duplicates
1627 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1628 intval($rr['uid']), intval($rr['id']), DBA::escape(DateTimeFormat::utc($nextbd)), DBA::escape('birthday'));
1630 if (DBA::isResult($s)) {
1634 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1635 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1637 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1638 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1639 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1640 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1646 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1647 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1654 * Remove the unavailable contact ids from the provided list
1656 * @param array $contact_ids Contact id list
1658 public static function pruneUnavailable(array &$contact_ids)
1660 if (empty($contact_ids)) {
1664 $str = DBA::escape(implode(',', $contact_ids));
1666 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1669 while($contact = DBA::fetch($stmt)) {
1670 $return[] = $contact['id'];
1675 $contact_ids = $return;
1679 * @brief Returns a magic link to authenticate remote visitors
1681 * @param string $contact_url The address of the target contact profile
1682 * @param integer $url An url that we will be redirected to after the authentication
1684 * @return string with "redir" link
1686 public static function magicLink($contact_url, $url = '')
1688 $cid = self::getIdForURL($contact_url, 0, true);
1690 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
1693 return self::magicLinkbyId($cid, $url);
1697 * @brief Returns a magic link to authenticate remote visitors
1699 * @param integer $cid The contact id of the target contact profile
1700 * @param integer $url An url that we will be redirected to after the authentication
1702 * @return string with "redir" link
1704 public static function magicLinkbyId($cid, $url = '')
1706 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
1708 return self::magicLinkbyContact($contact, $url);
1712 * @brief Returns a magic link to authenticate remote visitors
1714 * @param array $contact The contact array with "uid", "network" and "url"
1715 * @param integer $url An url that we will be redirected to after the authentication
1717 * @return string with "redir" link
1719 public static function magicLinkbyContact($contact, $url = '')
1721 if ($contact['network'] != NETWORK_DFRN) {
1722 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
1725 // Only redirections to the same host do make sense
1726 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1730 if ($contact['uid'] != 0) {
1731 return self::magicLink($contact['url'], $url);
1734 $redirect = 'redir/' . $contact['id'];
1737 $redirect .= '?url=' . $url;