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\Database\DBM;
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 * @brief Returns a list of contacts belonging in a group
40 public static function getByGroupId($gid)
44 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
46 INNER JOIN `group_member`
47 ON `contact`.`id` = `group_member`.`contact-id`
49 AND `contact`.`uid` = ?
50 AND NOT `contact`.`self`
51 AND NOT `contact`.`blocked`
52 AND NOT `contact`.`pending`
53 ORDER BY `contact`.`name` ASC',
57 if (DBM::is_result($stmt)) {
58 $return = DBA::toArray($stmt);
66 * @brief Returns the count of OStatus contacts in a group
71 public static function getOStatusCountByGroupId($gid)
75 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
77 INNER JOIN `group_member`
78 ON `contact`.`id` = `group_member`.`contact-id`
80 AND `contact`.`uid` = ?
81 AND `contact`.`network` = ?
82 AND `contact`.`notify` != ""',
87 $return = $contacts['count'];
94 * Creates the self-contact for the provided user id
97 * @return bool Operation success
99 public static function createSelfFromUserId($uid)
101 // Only create the entry if it doesn't exist yet
102 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
106 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
107 if (!DBM::is_result($user)) {
111 $return = DBA::insert('contact', [
112 'uid' => $user['uid'],
113 'created' => DateTimeFormat::utcNow(),
115 'name' => $user['username'],
116 'nick' => $user['nickname'],
117 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
118 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
119 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
122 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
123 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
124 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
125 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
126 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
127 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
128 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
129 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
130 'name-date' => DateTimeFormat::utcNow(),
131 'uri-date' => DateTimeFormat::utcNow(),
132 'avatar-date' => DateTimeFormat::utcNow(),
140 * Updates the self-contact for the provided user id
143 * @param boolean $update_avatar Force the avatar update
145 public static function updateSelfFromUserID($uid, $update_avatar = false)
147 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
148 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
149 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
150 if (!DBM::is_result($self)) {
154 $fields = ['nickname', 'page-flags', 'account-type'];
155 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
156 if (!DBM::is_result($user)) {
160 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
161 'country-name', 'gender', 'pub_keywords', 'xmpp'];
162 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
163 if (!DBM::is_result($profile)) {
167 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
168 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
169 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
170 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
171 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
173 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
174 if (DBM::is_result($avatar)) {
175 if ($update_avatar) {
176 $fields['avatar-date'] = DateTimeFormat::utcNow();
179 // Creating the path to the avatar, beginning with the file suffix
180 $types = Image::supportedTypes();
181 if (isset($types[$avatar['type']])) {
182 $file_suffix = $types[$avatar['type']];
184 $file_suffix = 'jpg';
187 // We are adding a timestamp value so that other systems won't use cached content
188 $timestamp = strtotime($fields['avatar-date']);
190 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
191 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
193 $fields['photo'] = $prefix . '4' . $suffix;
194 $fields['thumb'] = $prefix . '5' . $suffix;
195 $fields['micro'] = $prefix . '6' . $suffix;
197 // We hadn't found a photo entry, so we use the default avatar
198 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
199 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
200 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
203 $fields['forum'] = $user['page-flags'] == PAGE_COMMUNITY;
204 $fields['prv'] = $user['page-flags'] == PAGE_PRVGROUP;
206 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
207 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
208 $fields['nurl'] = normalise_link($fields['url']);
209 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
210 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
211 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
212 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
213 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
214 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
218 foreach ($fields as $field => $content) {
219 if (isset($self[$field]) && $self[$field] != $content) {
225 $fields['name-date'] = DateTimeFormat::utcNow();
226 DBA::update('contact', $fields, ['id' => $self['id']]);
228 // Update the public contact as well
229 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
231 // Update the profile
232 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
233 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
234 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
239 * @brief Marks a contact for removal
241 * @param int $id contact id
244 public static function remove($id)
246 // We want just to make sure that we don't delete our "self" contact
247 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
248 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
252 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
254 DBA::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
258 DBA::delete('contact', ['id' => $id]);
260 // Delete the rest in the background
261 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
265 * @brief Sends an unfriend message. Does not remove the contact
267 * @param array $user User unfriending
268 * @param array $contact Contact unfriended
271 public static function terminateFriendship(array $user, array $contact)
273 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
274 // create an unfollow slap
276 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
277 $item['follow'] = $contact["url"];
278 $slap = OStatus::salmon($item, $user);
280 if (!empty($contact['notify'])) {
281 Salmon::slapper($user, $contact['notify'], $slap);
283 } elseif ($contact['network'] == NETWORK_DIASPORA) {
284 Diaspora::sendUnshare($user, $contact);
289 * @brief Marks a contact for archival after a communication issue delay
291 * Contact has refused to recognise us as a friend. We will start a countdown.
292 * If they still don't recognise us in 32 days, the relationship is over,
293 * and we won't waste any more time trying to communicate with them.
294 * This provides for the possibility that their database is temporarily messed
295 * up or some other transient event and that there's a possibility we could recover from it.
297 * @param array $contact contact to mark for archival
300 public static function markForArchival(array $contact)
302 // Contact already archived or "self" contact? => nothing to do
303 if ($contact['archive'] || $contact['self']) {
307 if ($contact['term-date'] <= NULL_DATE) {
308 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
310 if ($contact['url'] != '') {
311 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
315 * We really should send a notification to the owner after 2-3 weeks
316 * so they won't be surprised when the contact vanishes and can take
317 * remedial action if this was a serious mistake or glitch
320 /// @todo Check for contact vitality via probing
321 $archival_days = Config::get('system', 'archival_days', 32);
323 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
324 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
325 /* Relationship is really truly dead. archive them rather than
326 * delete, though if the owner tries to unarchive them we'll start
327 * the whole process over again.
329 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
331 if ($contact['url'] != '') {
332 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
339 * @brief Cancels the archival countdown
341 * @see Contact::markForArchival()
343 * @param array $contact contact to be unmarked for archival
346 public static function unmarkForArchival(array $contact)
348 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
349 $exists = DBA::exists('contact', $condition);
351 // We don't need to update, we never marked this contact for archival
356 // It's a miracle. Our dead contact has inexplicably come back to life.
357 $fields = ['term-date' => NULL_DATE, 'archive' => false];
358 DBA::update('contact', $fields, ['id' => $contact['id']]);
360 if (!empty($contact['url'])) {
361 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
364 if (!empty($contact['batch'])) {
365 $condition = ['batch' => $contact['batch'], 'contact-type' => ACCOUNT_TYPE_RELAY];
366 DBA::update('contact', $fields, $condition);
371 * @brief Get contact data for a given profile link
373 * The function looks at several places (contact table and gcontact table) for the contact
374 * It caches its result for the same script execution to prevent duplicate calls
376 * @param string $url The profile link
377 * @param int $uid User id
378 * @param array $default If not data was found take this data as default value
380 * @return array Contact data
382 public static function getDetailsByURL($url, $uid = -1, array $default = [])
394 if (isset($cache[$url][$uid])) {
395 return $cache[$url][$uid];
398 $ssl_url = str_replace('http://', 'https://', $url);
400 // Fetch contact data from the contact table for the given user
401 $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`,
402 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
403 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
404 $r = DBA::toArray($s);
406 // Fetch contact data from the contact table for the given user, checking with the alias
407 if (!DBM::is_result($r)) {
408 $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`,
409 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
410 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
411 $r = DBA::toArray($s);
414 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
415 if (!DBM::is_result($r)) {
416 $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`,
417 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
418 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
419 $r = DBA::toArray($s);
422 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
423 if (!DBM::is_result($r)) {
424 $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`,
425 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
426 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
427 $r = DBA::toArray($s);
430 // Fetch the data from the gcontact table
431 if (!DBM::is_result($r)) {
432 $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`,
433 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
434 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
435 $r = DBA::toArray($s);
438 if (DBM::is_result($r)) {
439 // If there is more than one entry we filter out the connector networks
441 foreach ($r as $id => $result) {
442 if ($result["network"] == NETWORK_STATUSNET) {
448 $profile = array_shift($r);
450 // "bd" always contains the upcoming birthday of a contact.
451 // "birthday" might contain the birthday including the year of birth.
452 if ($profile["birthday"] > '0001-01-01') {
453 $bd_timestamp = strtotime($profile["birthday"]);
454 $month = date("m", $bd_timestamp);
455 $day = date("d", $bd_timestamp);
457 $current_timestamp = time();
458 $current_year = date("Y", $current_timestamp);
459 $current_month = date("m", $current_timestamp);
460 $current_day = date("d", $current_timestamp);
462 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
463 $current = $current_year . "-" . $current_month . "-" . $current_day;
465 if ($profile["bd"] < $current) {
466 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
469 $profile["bd"] = '0001-01-01';
475 if (empty($profile["photo"]) && isset($default["photo"])) {
476 $profile["photo"] = $default["photo"];
479 if (empty($profile["name"]) && isset($default["name"])) {
480 $profile["name"] = $default["name"];
483 if (empty($profile["network"]) && isset($default["network"])) {
484 $profile["network"] = $default["network"];
487 if (empty($profile["thumb"]) && isset($profile["photo"])) {
488 $profile["thumb"] = $profile["photo"];
491 if (empty($profile["micro"]) && isset($profile["thumb"])) {
492 $profile["micro"] = $profile["thumb"];
495 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
496 && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
498 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
501 // Show contact details of Diaspora contacts only if connected
502 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == NETWORK_DIASPORA)) {
503 $profile["location"] = "";
504 $profile["about"] = "";
505 $profile["gender"] = "";
506 $profile["birthday"] = '0001-01-01';
509 $cache[$url][$uid] = $profile;
515 * @brief Get contact data for a given address
517 * The function looks at several places (contact table and gcontact table) for the contact
519 * @param string $addr The profile link
520 * @param int $uid User id
522 * @return array Contact data
524 public static function getDetailsByAddr($addr, $uid = -1)
536 // Fetch contact data from the contact table for the given user
537 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
538 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
539 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
543 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
544 if (!DBM::is_result($r)) {
545 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
546 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
547 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
552 // Fetch the data from the gcontact table
553 if (!DBM::is_result($r)) {
554 $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`,
555 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
556 FROM `gcontact` WHERE `addr` = '%s'",
561 if (!DBM::is_result($r)) {
562 $data = Probe::uri($addr);
564 $profile = self::getDetailsByURL($data['url'], $uid);
573 * @brief Returns the data array for the photo menu of a given contact
575 * @param array $contact contact
576 * @param int $uid optional, default 0
579 public static function photoMenu(array $contact, $uid = 0)
581 // @todo Unused, to be removed
589 $contact_drop_link = '';
596 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
598 $profile_link = self::magicLink($contact['url']);
599 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
604 // Look for our own contact if the uid doesn't match and isn't public
605 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
606 if (DBM::is_result($contact_own)) {
607 return self::photoMenu($contact_own, $uid);
609 $profile_link = self::magicLink($contact['url']);
610 $connlnk = 'follow/?url=' . $contact['url'];
612 'profile' => [L10n::t('View Profile'), $profile_link, true],
613 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
621 if (($contact['network'] === NETWORK_DFRN) && !$contact['self']) {
623 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
625 $profile_link = $contact['url'];
628 if ($profile_link === 'mailbox') {
633 $status_link = $profile_link . '?url=status';
634 $photos_link = $profile_link . '?url=photos';
635 $profile_link = $profile_link . '?url=profile';
638 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA]) && !$contact['self']) {
639 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
642 if (($contact['network'] == NETWORK_DFRN) && !$contact['self']) {
643 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
646 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
648 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
650 if (!$contact['self']) {
651 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
656 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
659 'status' => [L10n::t("View Status") , $status_link , true],
660 'profile' => [L10n::t("View Profile") , $profile_link , true],
661 'photos' => [L10n::t("View Photos") , $photos_link , true],
662 'network' => [L10n::t("Network Posts"), $posts_link , false],
663 'edit' => [L10n::t("View Contact") , $contact_url , false],
664 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
665 'pm' => [L10n::t("Send PM") , $pm_url , false],
666 'poke' => [L10n::t("Poke") , $poke_link , false],
669 $args = ['contact' => $contact, 'menu' => &$menu];
671 Addon::callHooks('contact_photo_menu', $args);
675 foreach ($menu as $menuname => $menuitem) {
676 if ($menuitem[1] != '') {
677 $menucondensed[$menuname] = $menuitem;
681 return $menucondensed;
685 * @brief Returns ungrouped contact count or list for user
687 * Returns either the total number of ungrouped contacts for the given user
688 * id or a paginated list of ungrouped contacts.
690 * @param int $uid uid
691 * @param int $start optional, default 0
692 * @param int $count optional, default 0
696 public static function getUngroupedList($uid)
705 SELECT DISTINCT(`contact-id`)
707 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
708 WHERE `group`.`uid` = %d
709 )", intval($uid), intval($uid));
713 * @brief Fetch the contact id for a given URL and user
715 * First lookup in the contact table to find a record matching either `url`, `nurl`,
718 * If there's no record and we aren't looking for a public contact, we quit.
719 * If there's one, we check that it isn't time to update the picture else we
720 * directly return the found contact id.
722 * Second, we probe the provided $url whether it's http://server.tld/profile or
723 * nick@server.tld. We quit if we can't get any info back.
725 * Third, we create the contact record if it doesn't exist
727 * Fourth, we update the existing record with the new data (avatar, alias, nick)
728 * if there's any updates
730 * @param string $url Contact URL
731 * @param integer $uid The user id for the contact (0 = public contact)
732 * @param boolean $no_update Don't update the contact
733 * @param array $default Default value for creating the contact when every else fails
735 * @return integer Contact ID
737 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
739 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
747 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
748 // We first try the nurl (http://server.tld/nick), most common case
749 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
751 // Then the addr (nick@server.tld)
752 if (!DBM::is_result($contact)) {
753 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
756 // Then the alias (which could be anything)
757 if (!DBM::is_result($contact)) {
758 // The link could be provided as http although we stored it as https
759 $ssl_url = str_replace('http://', 'https://', $url);
760 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
761 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
764 if (DBM::is_result($contact)) {
765 $contact_id = $contact["id"];
767 // Update the contact every 7 days
768 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
770 // We force the update if the avatar is empty
771 if (!x($contact, 'avatar')) {
772 $update_contact = true;
775 if (!$update_contact || $no_update) {
778 } elseif ($uid != 0) {
779 // Non-existing user-specific contact, exiting
783 $data = Probe::uri($url, "", $uid);
785 // Last try in gcontact for unsupported networks
786 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL, NETWORK_FEED])) {
791 // Get data from the gcontact table
792 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
793 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
794 if (!DBM::is_result($contact)) {
795 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
798 if (!DBM::is_result($contact)) {
799 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
800 'photo', 'keywords', 'location', 'about', 'network',
801 'priority', 'batch', 'request', 'confirm', 'poco'];
802 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
805 if (!DBM::is_result($contact)) {
806 // The link could be provided as http although we stored it as https
807 $ssl_url = str_replace('http://', 'https://', $url);
808 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
809 $contact = DBA::selectFirst('contact', $fields, $condition);
812 if (!DBM::is_result($contact)) {
813 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
814 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
815 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
816 $contact = DBA::selectFirst('fcontact', $fields, $condition);
819 if (!empty($default)) {
823 if (!DBM::is_result($contact)) {
826 $data = array_merge($data, $contact);
830 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
831 $contact_id = self::getIdForURL($data["alias"], $uid, true);
836 DBA::insert('contact', [
838 'created' => DateTimeFormat::utcNow(),
839 'url' => $data["url"],
840 'nurl' => normalise_link($data["url"]),
841 'addr' => $data["addr"],
842 'alias' => $data["alias"],
843 'notify' => $data["notify"],
844 'poll' => $data["poll"],
845 'name' => $data["name"],
846 'nick' => $data["nick"],
847 'photo' => $data["photo"],
848 'keywords' => $data["keywords"],
849 'location' => $data["location"],
850 'about' => $data["about"],
851 'network' => $data["network"],
852 'pubkey' => $data["pubkey"],
853 'rel' => CONTACT_IS_SHARING,
854 'priority' => $data["priority"],
855 'batch' => $data["batch"],
856 'request' => $data["request"],
857 'confirm' => $data["confirm"],
858 'poco' => $data["poco"],
859 'name-date' => DateTimeFormat::utcNow(),
860 'uri-date' => DateTimeFormat::utcNow(),
861 'avatar-date' => DateTimeFormat::utcNow(),
868 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
869 $contacts = DBA::toArray($s);
870 if (!DBM::is_result($contacts)) {
874 $contact_id = $contacts[0]["id"];
876 // Update the newly created contact from data in the gcontact table
877 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
878 if (DBM::is_result($gcontact)) {
879 // Only use the information when the probing hadn't fetched these values
880 if ($data['keywords'] != '') {
881 unset($gcontact['keywords']);
883 if ($data['location'] != '') {
884 unset($gcontact['location']);
886 if ($data['about'] != '') {
887 unset($gcontact['about']);
889 DBA::update('contact', $gcontact, ['id' => $contact_id]);
892 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
893 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
894 normalise_link($data["url"]), $contact_id]);
898 self::updateAvatar($data["photo"], $uid, $contact_id);
900 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
901 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
903 // This condition should always be true
904 if (!DBM::is_result($contact)) {
908 $updated = ['addr' => $data['addr'],
909 'alias' => $data['alias'],
910 'url' => $data['url'],
911 'nurl' => normalise_link($data['url']),
912 'name' => $data['name'],
913 'nick' => $data['nick']];
915 if ($data['keywords'] != '') {
916 $updated['keywords'] = $data['keywords'];
918 if ($data['location'] != '') {
919 $updated['location'] = $data['location'];
922 // Update the technical stuff as well - if filled
923 if ($data['notify'] != '') {
924 $updated['notify'] = $data['notify'];
926 if ($data['poll'] != '') {
927 $updated['poll'] = $data['poll'];
929 if ($data['batch'] != '') {
930 $updated['batch'] = $data['batch'];
932 if ($data['request'] != '') {
933 $updated['request'] = $data['request'];
935 if ($data['confirm'] != '') {
936 $updated['confirm'] = $data['confirm'];
938 if ($data['poco'] != '') {
939 $updated['poco'] = $data['poco'];
942 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
943 if (empty($contact['pubkey'])) {
944 $updated['pubkey'] = $data['pubkey'];
947 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
948 $updated['uri-date'] = DateTimeFormat::utcNow();
950 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
951 $updated['name-date'] = DateTimeFormat::utcNow();
954 $updated['avatar-date'] = DateTimeFormat::utcNow();
956 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
962 * @brief Checks if the contact is blocked
964 * @param int $cid contact id
966 * @return boolean Is the contact blocked?
968 public static function isBlocked($cid)
974 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
975 if (!DBM::is_result($blocked)) {
978 return (bool) $blocked['blocked'];
982 * @brief Checks if the contact is hidden
984 * @param int $cid contact id
986 * @return boolean Is the contact hidden?
988 public static function isHidden($cid)
994 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
995 if (!DBM::is_result($hidden)) {
998 return (bool) $hidden['hidden'];
1002 * @brief Returns posts from a given contact url
1004 * @param string $contact_url Contact URL
1006 * @return string posts in HTML
1008 public static function getPostsFromUrl($contact_url)
1010 $a = self::getApp();
1012 require_once 'include/conversation.php';
1014 // There are no posts with "uid = 0" with connector networks
1015 // This speeds up the query a lot
1016 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1017 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1018 dbesc(normalise_link($contact_url))
1021 if (!DBM::is_result($r)) {
1025 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1026 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1028 $sql = "`item`.`uid` = ?";
1031 $author_id = intval($r[0]["author-id"]);
1033 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1035 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1036 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1037 $params = ['order' => ['created' => true],
1038 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1039 $r = Item::selectForUser(local_user(), [], $condition, $params);
1041 $items = Item::inArray($r);
1043 $o = conversation($a, $items, 'contact-posts', false);
1045 $o .= alt_pager($a, count($items));
1051 * @brief Returns the account type name
1053 * The function can be called with either the user or the contact array
1055 * @param array $contact contact or user array
1058 public static function getAccountType(array $contact)
1060 // There are several fields that indicate that the contact or user is a forum
1061 // "page-flags" is a field in the user table,
1062 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
1063 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
1064 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
1065 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
1066 || (isset($contact['forum']) && intval($contact['forum']))
1067 || (isset($contact['prv']) && intval($contact['prv']))
1068 || (isset($contact['community']) && intval($contact['community']))
1070 $type = ACCOUNT_TYPE_COMMUNITY;
1072 $type = ACCOUNT_TYPE_PERSON;
1075 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1076 if (isset($contact["contact-type"])) {
1077 $type = $contact["contact-type"];
1080 if (isset($contact["account-type"])) {
1081 $type = $contact["account-type"];
1085 case ACCOUNT_TYPE_ORGANISATION:
1086 $account_type = L10n::t("Organisation");
1088 case ACCOUNT_TYPE_NEWS:
1089 $account_type = L10n::t('News');
1091 case ACCOUNT_TYPE_COMMUNITY:
1092 $account_type = L10n::t("Forum");
1099 return $account_type;
1103 * @brief Blocks a contact
1108 public static function block($uid)
1110 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1116 * @brief Unblocks a contact
1121 public static function unblock($uid)
1123 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1129 * @brief Updates the avatar links in a contact only if needed
1131 * @param string $avatar Link to avatar picture
1132 * @param int $uid User id of contact owner
1133 * @param int $cid Contact id
1134 * @param bool $force force picture update
1136 * @return array Returns array of the different avatar sizes
1138 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1140 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1141 if (!DBM::is_result($contact)) {
1144 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1147 if (($contact["avatar"] != $avatar) || $force) {
1148 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1153 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1157 // Update the public contact (contact id = 0)
1159 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1160 if (DBM::is_result($pcontact)) {
1161 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1173 * @param integer $id contact id
1176 public static function updateFromProbe($id)
1179 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1180 This will reliably kill your communication with Friendica contacts.
1183 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1184 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1185 if (!DBM::is_result($contact)) {
1189 $ret = Probe::uri($contact["url"]);
1191 // If Probe::uri fails the network code will be different
1192 if ($ret["network"] != $contact["network"]) {
1198 // make sure to not overwrite existing values with blank entries
1199 foreach ($ret as $key => $val) {
1200 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1201 $ret[$key] = $contact[$key];
1204 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1215 'url' => $ret['url'],
1216 'nurl' => normalise_link($ret['url']),
1217 'addr' => $ret['addr'],
1218 'alias' => $ret['alias'],
1219 'batch' => $ret['batch'],
1220 'notify' => $ret['notify'],
1221 'poll' => $ret['poll'],
1222 'poco' => $ret['poco']
1227 // Update the corresponding gcontact entry
1228 PortableContact::lastUpdated($ret["url"]);
1234 * Takes a $uid and a url/handle and adds a new contact
1235 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1236 * dfrn_request page.
1238 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1241 * $return['success'] boolean true if successful
1242 * $return['message'] error text if success is false.
1244 * @brief Takes a $uid and a url/handle and adds a new contact
1246 * @param string $url
1247 * @param bool $interactive
1248 * @param string $network
1249 * @return boolean|string
1251 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1253 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1257 // remove ajax junk, e.g. Twitter
1258 $url = str_replace('/#!/', '/', $url);
1260 if (!Network::isUrlAllowed($url)) {
1261 $result['message'] = L10n::t('Disallowed profile URL.');
1265 if (Network::isUrlBlocked($url)) {
1266 $result['message'] = L10n::t('Blocked domain');
1271 $result['message'] = L10n::t('Connect URL missing.');
1275 $arr = ['url' => $url, 'contact' => []];
1277 Addon::callHooks('follow', $arr);
1280 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1284 if (x($arr['contact'], 'name')) {
1285 $ret = $arr['contact'];
1287 $ret = Probe::uri($url, $network, $uid, false);
1290 if (($network != '') && ($ret['network'] != $network)) {
1291 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1295 // check if we already have a contact
1296 // the poll url is more reliable than the profile url, as we may have
1297 // indirect links or webfinger links
1299 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1301 dbesc($ret['poll']),
1302 dbesc(normalise_link($ret['poll'])),
1303 dbesc($ret['network'])
1306 if (!DBM::is_result($r)) {
1307 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1309 dbesc(normalise_link($url)),
1310 dbesc($ret['network'])
1314 if (($ret['network'] === NETWORK_DFRN) && !DBM::is_result($r)) {
1316 if (strlen($a->urlpath)) {
1317 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1319 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1322 goaway($ret['request'] . "&addr=$myaddr");
1326 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != NETWORK_DFRN)) {
1327 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1328 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1332 // This extra param just confuses things, remove it
1333 if ($ret['network'] === NETWORK_DIASPORA) {
1334 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1337 // do we have enough information?
1339 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1340 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1341 if (!x($ret, 'poll')) {
1342 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1344 if (!x($ret, 'name')) {
1345 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1347 if (!x($ret, 'url')) {
1348 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1350 if (strpos($url, '@') !== false) {
1351 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1352 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1357 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1358 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1359 $ret['notify'] = '';
1362 if (!$ret['notify']) {
1363 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1366 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1368 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1370 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1372 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1376 if (DBM::is_result($r)) {
1378 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1380 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1381 DBA::update('contact', $fields, ['id' => $r[0]['id']]);
1383 $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1385 // create contact record
1386 DBA::insert('contact', [
1388 'created' => DateTimeFormat::utcNow(),
1389 'url' => $ret['url'],
1390 'nurl' => normalise_link($ret['url']),
1391 'addr' => $ret['addr'],
1392 'alias' => $ret['alias'],
1393 'batch' => $ret['batch'],
1394 'notify' => $ret['notify'],
1395 'poll' => $ret['poll'],
1396 'poco' => $ret['poco'],
1397 'name' => $ret['name'],
1398 'nick' => $ret['nick'],
1399 'network' => $ret['network'],
1400 'pubkey' => $ret['pubkey'],
1401 'rel' => $new_relation,
1402 'priority'=> $ret['priority'],
1403 'writable'=> $writeable,
1404 'hidden' => $hidden,
1412 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1413 if (!DBM::is_result($contact)) {
1414 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1418 $contact_id = $contact['id'];
1419 $result['cid'] = $contact_id;
1421 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1423 // Update the avatar
1424 self::updateAvatar($ret['photo'], $uid, $contact_id);
1426 // pull feed and consume it, which should subscribe to the hub.
1428 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1430 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1431 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1435 if (DBM::is_result($r)) {
1436 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
1437 // create a follow slap
1439 $item['verb'] = ACTIVITY_FOLLOW;
1440 $item['follow'] = $contact["url"];
1441 $slap = OStatus::salmon($item, $r[0]);
1442 if (!empty($contact['notify'])) {
1443 Salmon::slapper($r[0], $contact['notify'], $slap);
1445 } elseif ($contact['network'] == NETWORK_DIASPORA) {
1446 $ret = Diaspora::sendShare($a->user, $contact);
1447 logger('share returns: ' . $ret);
1451 $result['success'] = true;
1455 public static function updateSslPolicy($contact, $new_policy)
1457 $ssl_changed = false;
1458 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1459 $ssl_changed = true;
1460 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1461 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1462 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1463 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1464 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1465 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1468 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1469 $ssl_changed = true;
1470 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1471 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1472 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1473 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1474 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1475 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1479 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1480 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1481 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1482 DBA::update('contact', $fields, ['id' => $contact['id']]);
1488 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1489 $url = notags(trim($datarray['author-link']));
1490 $name = notags(trim($datarray['author-name']));
1491 $photo = notags(trim($datarray['author-avatar']));
1494 if (is_object($item)) {
1495 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1496 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1497 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1503 if (is_array($contact)) {
1504 if (($contact['rel'] == CONTACT_IS_SHARING)
1505 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1506 DBA::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1507 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1509 // send email notification to owner?
1511 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1512 logger('ignoring duplicated connection request from pending contact ' . $url);
1516 // create contact record
1517 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1518 `blocked`, `readonly`, `pending`, `writable`)
1519 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1520 intval($importer['uid']),
1521 dbesc(DateTimeFormat::utcNow()),
1523 dbesc(normalise_link($url)),
1527 dbesc(NETWORK_OSTATUS),
1528 intval(CONTACT_IS_FOLLOWER)
1532 'id' => DBA::lastInsertId(),
1533 'network' => NETWORK_OSTATUS,
1539 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1541 /// @TODO Encapsulate this into a function/method
1542 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1543 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1544 if (DBM::is_result($user) && !in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1545 // create notification
1546 $hash = random_string();
1548 if (is_array($contact_record)) {
1549 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1550 'blocked' => false, 'knowyou' => false,
1551 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1554 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1556 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1557 in_array($user['page-flags'], [PAGE_NORMAL])) {
1560 'type' => NOTIFY_INTRO,
1561 'notify_flags' => $user['notify-flags'],
1562 'language' => $user['language'],
1563 'to_name' => $user['username'],
1564 'to_email' => $user['email'],
1565 'uid' => $user['uid'],
1566 'link' => System::baseUrl() . '/notifications/intro',
1567 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1568 'source_link' => $contact_record['url'],
1569 'source_photo' => $contact_record['photo'],
1570 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1575 } elseif (DBM::is_result($user) && in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1576 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1577 intval($importer['uid']),
1584 public static function removeFollower($importer, $contact, array $datarray = [], $item = "") {
1586 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1587 DBA::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1589 Contact::remove($contact['id']);
1593 public static function removeSharer($importer, $contact, array $datarray = [], $item = "") {
1595 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1596 DBA::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1598 Contact::remove($contact['id']);
1603 * @brief Create a birthday event.
1605 * Update the year and the birthday.
1607 public static function updateBirthdays()
1609 // This only handles foreign or alien networks where a birthday has been provided.
1610 // In-network birthdays are handled within local_delivery
1612 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1613 if (DBM::is_result($r)) {
1614 foreach ($r as $rr) {
1615 logger('update_contact_birthday: ' . $rr['bd']);
1617 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1620 * Add new birthday event for this person
1622 * $bdtext is just a readable placeholder in case the event is shared
1623 * with others. We will replace it during presentation to our $importer
1624 * to contain a sparkle link and perhaps a photo.
1627 // Check for duplicates
1628 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1629 intval($rr['uid']), intval($rr['id']), dbesc(DateTimeFormat::utc($nextbd)), dbesc('birthday'));
1631 if (DBM::is_result($s)) {
1635 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1636 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1638 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1639 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1640 dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utc($nextbd)),
1641 dbesc(DateTimeFormat::utc($nextbd . ' + 1 day ')), dbesc($bdtext), dbesc($bdtext2), dbesc('birthday'),
1647 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(substr($nextbd, 0, 4)),
1648 dbesc($nextbd), intval($rr['uid']), intval($rr['id'])
1655 * Remove the unavailable contact ids from the provided list
1657 * @param array $contact_ids Contact id list
1659 public static function pruneUnavailable(array &$contact_ids)
1661 if (empty($contact_ids)) {
1665 $str = dbesc(implode(',', $contact_ids));
1667 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1670 while($contact = DBA::fetch($stmt)) {
1671 $return[] = $contact['id'];
1676 $contact_ids = $return;
1680 * @brief Returns a magic link to authenticate remote visitors
1682 * @param string $contact_url The address of the target contact profile
1683 * @param integer $url An url that we will be redirected to after the authentication
1685 * @return string with "redir" link
1687 public static function magicLink($contact_url, $url = '')
1689 $cid = self::getIdForURL($contact_url, 0, true);
1691 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
1694 return self::magicLinkbyId($cid, $url);
1698 * @brief Returns a magic link to authenticate remote visitors
1700 * @param integer $cid The contact id of the target contact profile
1701 * @param integer $url An url that we will be redirected to after the authentication
1703 * @return string with "redir" link
1705 public static function magicLinkbyId($cid, $url = '')
1707 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
1709 return self::magicLinkbyContact($contact, $url);
1713 * @brief Returns a magic link to authenticate remote visitors
1715 * @param array $contact The contact array with "uid", "network" and "url"
1716 * @param integer $url An url that we will be redirected to after the authentication
1718 * @return string with "redir" link
1720 public static function magicLinkbyContact($contact, $url = '')
1722 if ($contact['network'] != NETWORK_DFRN) {
1723 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
1726 // Only redirections to the same host do make sense
1727 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1731 if ($contact['uid'] != 0) {
1732 return self::magicLink($contact['url'], $url);
1735 $redirect = 'redir/' . $contact['id'];
1738 $redirect .= '?url=' . $url;