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\DBM;
15 use Friendica\Model\Photo;
16 use Friendica\Model\Profile;
17 use Friendica\Network\Probe;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Protocol\PortableContact;
22 use Friendica\Protocol\Salmon;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
25 use Friendica\Object\Image;
28 require_once 'boot.php';
29 require_once 'include/dba.php';
30 require_once 'include/text.php';
33 * @brief functions for interacting with a contact
35 class Contact extends BaseObject
38 * @brief Returns a list of contacts belonging in a group
43 public static function getByGroupId($gid)
47 $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
49 INNER JOIN `group_member`
50 ON `contact`.`id` = `group_member`.`contact-id`
52 AND `contact`.`uid` = ?
53 AND NOT `contact`.`self`
54 AND NOT `contact`.`blocked`
55 AND NOT `contact`.`pending`
56 ORDER BY `contact`.`name` ASC',
60 if (DBM::is_result($stmt)) {
61 $return = dba::inArray($stmt);
69 * @brief Returns the count of OStatus contacts in a group
74 public static function getOStatusCountByGroupId($gid)
78 $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
80 INNER JOIN `group_member`
81 ON `contact`.`id` = `group_member`.`contact-id`
83 AND `contact`.`uid` = ?
84 AND `contact`.`network` = ?
85 AND `contact`.`notify` != ""',
90 $return = $contacts['count'];
97 * Creates the self-contact for the provided user id
100 * @return bool Operation success
102 public static function createSelfFromUserId($uid)
104 // Only create the entry if it doesn't exist yet
105 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
109 $user = dba::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
110 if (!DBM::is_result($user)) {
114 $return = dba::insert('contact', [
115 'uid' => $user['uid'],
116 'created' => DateTimeFormat::utcNow(),
118 'name' => $user['username'],
119 'nick' => $user['nickname'],
120 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
121 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
122 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
125 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
126 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
127 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
128 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
129 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
130 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
131 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
132 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
133 'name-date' => DateTimeFormat::utcNow(),
134 'uri-date' => DateTimeFormat::utcNow(),
135 'avatar-date' => DateTimeFormat::utcNow(),
143 * Updates the self-contact for the provided user id
146 * @param boolean $update_avatar Force the avatar update
148 public static function updateSelfFromUserID($uid, $update_avatar = false)
150 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
151 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
152 $self = dba::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
153 if (!DBM::is_result($self)) {
157 $fields = ['nickname', 'page-flags', 'account-type'];
158 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
159 if (!DBM::is_result($user)) {
163 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
164 'country-name', 'gender', 'pub_keywords', 'xmpp'];
165 $profile = dba::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
166 if (!DBM::is_result($profile)) {
170 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
171 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
172 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
173 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
174 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
176 $avatar = dba::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
177 if (DBM::is_result($avatar)) {
178 if ($update_avatar) {
179 $fields['avatar-date'] = DateTimeFormat::utcNow();
182 // Creating the path to the avatar, beginning with the file suffix
183 $types = Image::supportedTypes();
184 if (isset($types[$avatar['type']])) {
185 $file_suffix = $types[$avatar['type']];
187 $file_suffix = 'jpg';
190 // We are adding a timestamp value so that other systems won't use cached content
191 $timestamp = strtotime($fields['avatar-date']);
193 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
194 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
196 $fields['photo'] = $prefix . '4' . $suffix;
197 $fields['thumb'] = $prefix . '5' . $suffix;
198 $fields['micro'] = $prefix . '6' . $suffix;
200 // We hadn't found a photo entry, so we use the default avatar
201 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
202 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
203 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
206 $fields['forum'] = $user['page-flags'] == PAGE_COMMUNITY;
207 $fields['prv'] = $user['page-flags'] == PAGE_PRVGROUP;
209 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
210 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
211 $fields['nurl'] = normalise_link($fields['url']);
212 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
213 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
214 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
215 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
216 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
217 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
221 foreach ($fields as $field => $content) {
222 if ($self[$field] != $content) {
228 $fields['name-date'] = DateTimeFormat::utcNow();
229 dba::update('contact', $fields, ['id' => $self['id']]);
231 // Update the public contact as well
232 dba::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
234 // Update the profile
235 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
236 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
237 dba::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
242 * @brief Marks a contact for removal
244 * @param int $id contact id
247 public static function remove($id)
249 // We want just to make sure that we don't delete our "self" contact
250 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
251 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
255 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
257 dba::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
261 dba::delete('contact', ['id' => $id]);
263 // Delete the rest in the background
264 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
268 * @brief Sends an unfriend message. Does not remove the contact
270 * @param array $user User unfriending
271 * @param array $contact Contact unfriended
274 public static function terminateFriendship(array $user, array $contact)
276 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
277 // create an unfollow slap
279 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
280 $item['follow'] = $contact["url"];
281 $slap = OStatus::salmon($item, $user);
283 if (!empty($contact['notify'])) {
284 Salmon::slapper($user, $contact['notify'], $slap);
286 } elseif ($contact['network'] == NETWORK_DIASPORA) {
287 Diaspora::sendUnshare($user, $contact);
292 * @brief Marks a contact for archival after a communication issue delay
294 * Contact has refused to recognise us as a friend. We will start a countdown.
295 * If they still don't recognise us in 32 days, the relationship is over,
296 * and we won't waste any more time trying to communicate with them.
297 * This provides for the possibility that their database is temporarily messed
298 * up or some other transient event and that there's a possibility we could recover from it.
300 * @param array $contact contact to mark for archival
303 public static function markForArchival(array $contact)
305 // Contact already archived or "self" contact? => nothing to do
306 if ($contact['archive'] || $contact['self']) {
310 if ($contact['term-date'] <= NULL_DATE) {
311 dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
313 if ($contact['url'] != '') {
314 dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
318 * We really should send a notification to the owner after 2-3 weeks
319 * so they won't be surprised when the contact vanishes and can take
320 * remedial action if this was a serious mistake or glitch
323 /// @todo Check for contact vitality via probing
324 $archival_days = Config::get('system', 'archival_days', 32);
326 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
327 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
328 /* Relationship is really truly dead. archive them rather than
329 * delete, though if the owner tries to unarchive them we'll start
330 * the whole process over again.
332 dba::update('contact', ['archive' => 1], ['id' => $contact['id']]);
334 if ($contact['url'] != '') {
335 dba::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
342 * @brief Cancels the archival countdown
344 * @see Contact::markForArchival()
346 * @param array $contact contact to be unmarked for archival
349 public static function unmarkForArchival(array $contact)
351 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
352 $exists = dba::exists('contact', $condition);
354 // We don't need to update, we never marked this contact for archival
359 // It's a miracle. Our dead contact has inexplicably come back to life.
360 $fields = ['term-date' => NULL_DATE, 'archive' => false];
361 dba::update('contact', $fields, ['id' => $contact['id']]);
363 if (!empty($contact['url'])) {
364 dba::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
367 if (!empty($contact['batch'])) {
368 $condition = ['batch' => $contact['batch'], 'contact-type' => ACCOUNT_TYPE_RELAY];
369 dba::update('contact', $fields, $condition);
374 * @brief Get contact data for a given profile link
376 * The function looks at several places (contact table and gcontact table) for the contact
377 * It caches its result for the same script execution to prevent duplicate calls
379 * @param string $url The profile link
380 * @param int $uid User id
381 * @param array $default If not data was found take this data as default value
383 * @return array Contact data
385 public static function getDetailsByURL($url, $uid = -1, array $default = [])
397 if (isset($cache[$url][$uid])) {
398 return $cache[$url][$uid];
401 $ssl_url = str_replace('http://', 'https://', $url);
403 // Fetch contact data from the contact table for the given user
404 $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`,
405 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
406 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
407 $r = dba::inArray($s);
409 // Fetch contact data from the contact table for the given user, checking with the alias
410 if (!DBM::is_result($r)) {
411 $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`,
412 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
413 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
414 $r = dba::inArray($s);
417 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
418 if (!DBM::is_result($r)) {
419 $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`,
420 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
421 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
422 $r = dba::inArray($s);
425 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
426 if (!DBM::is_result($r)) {
427 $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`,
428 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
429 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
430 $r = dba::inArray($s);
433 // Fetch the data from the gcontact table
434 if (!DBM::is_result($r)) {
435 $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`,
436 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
437 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
438 $r = dba::inArray($s);
441 if (DBM::is_result($r)) {
442 // If there is more than one entry we filter out the connector networks
444 foreach ($r as $id => $result) {
445 if ($result["network"] == NETWORK_STATUSNET) {
451 $profile = array_shift($r);
453 // "bd" always contains the upcoming birthday of a contact.
454 // "birthday" might contain the birthday including the year of birth.
455 if ($profile["birthday"] > '0001-01-01') {
456 $bd_timestamp = strtotime($profile["birthday"]);
457 $month = date("m", $bd_timestamp);
458 $day = date("d", $bd_timestamp);
460 $current_timestamp = time();
461 $current_year = date("Y", $current_timestamp);
462 $current_month = date("m", $current_timestamp);
463 $current_day = date("d", $current_timestamp);
465 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
466 $current = $current_year . "-" . $current_month . "-" . $current_day;
468 if ($profile["bd"] < $current) {
469 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
472 $profile["bd"] = '0001-01-01';
478 if (($profile["photo"] == "") && isset($default["photo"])) {
479 $profile["photo"] = $default["photo"];
482 if (($profile["name"] == "") && isset($default["name"])) {
483 $profile["name"] = $default["name"];
486 if (($profile["network"] == "") && isset($default["network"])) {
487 $profile["network"] = $default["network"];
490 if (($profile["thumb"] == "") && isset($profile["photo"])) {
491 $profile["thumb"] = $profile["photo"];
494 if (($profile["micro"] == "") && isset($profile["thumb"])) {
495 $profile["micro"] = $profile["thumb"];
498 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
499 && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
501 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
504 // Show contact details of Diaspora contacts only if connected
505 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
506 $profile["location"] = "";
507 $profile["about"] = "";
508 $profile["gender"] = "";
509 $profile["birthday"] = '0001-01-01';
512 $cache[$url][$uid] = $profile;
518 * @brief Get contact data for a given address
520 * The function looks at several places (contact table and gcontact table) for the contact
522 * @param string $addr The profile link
523 * @param int $uid User id
525 * @return array Contact data
527 public static function getDetailsByAddr($addr, $uid = -1)
539 // Fetch contact data from the contact table for the given user
540 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
541 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
542 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
546 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
547 if (!DBM::is_result($r)) {
548 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
549 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
550 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
555 // Fetch the data from the gcontact table
556 if (!DBM::is_result($r)) {
557 $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`,
558 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
559 FROM `gcontact` WHERE `addr` = '%s'",
564 if (!DBM::is_result($r)) {
565 $data = Probe::uri($addr);
567 $profile = self::getDetailsByURL($data['url'], $uid);
576 * @brief Returns the data array for the photo menu of a given contact
578 * @param array $contact contact
579 * @param int $uid optional, default 0
582 public static function photoMenu(array $contact, $uid = 0)
584 // @todo Unused, to be removed
592 $contact_drop_link = '';
599 if ($contact['uid'] != $uid) {
601 $profile_link = self::magicLink($contact['url']);
602 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
607 // Look for our own contact if the uid doesn't match and isn't public
608 $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
609 if (DBM::is_result($contact_own)) {
610 return self::photoMenu($contact_own, $uid);
612 $profile_link = self::magicLink($contact['url']);
613 $connlnk = 'follow/?url=' . $contact['url'];
615 'profile' => [L10n::t('View Profile'), $profile_link, true],
616 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
624 if (($contact['network'] === NETWORK_DFRN) && !$contact['self']) {
626 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
628 $profile_link = $contact['url'];
631 if ($profile_link === 'mailbox') {
636 $status_link = $profile_link . '?url=status';
637 $photos_link = $profile_link . '?url=photos';
638 $profile_link = $profile_link . '?url=profile';
641 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA]) && !$contact['self']) {
642 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
645 if (($contact['network'] == NETWORK_DFRN) && !$contact['self']) {
646 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
649 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
651 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
653 if (!$contact['self']) {
654 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
659 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
662 'status' => [L10n::t("View Status") , $status_link , true],
663 'profile' => [L10n::t("View Profile") , $profile_link , true],
664 'photos' => [L10n::t("View Photos") , $photos_link , true],
665 'network' => [L10n::t("Network Posts"), $posts_link , false],
666 'edit' => [L10n::t("View Contact") , $contact_url , false],
667 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
668 'pm' => [L10n::t("Send PM") , $pm_url , false],
669 'poke' => [L10n::t("Poke") , $poke_link , false],
672 $args = ['contact' => $contact, 'menu' => &$menu];
674 Addon::callHooks('contact_photo_menu', $args);
678 foreach ($menu as $menuname => $menuitem) {
679 if ($menuitem[1] != '') {
680 $menucondensed[$menuname] = $menuitem;
684 return $menucondensed;
688 * @brief Returns ungrouped contact count or list for user
690 * Returns either the total number of ungrouped contacts for the given user
691 * id or a paginated list of ungrouped contacts.
693 * @param int $uid uid
694 * @param int $start optional, default 0
695 * @param int $count optional, default 0
699 public static function getUngroupedList($uid, $start = 0, $count = 0)
703 "SELECT COUNT(*) AS `total`
710 SELECT DISTINCT(`contact-id`)
729 SELECT DISTINCT(`contact-id`)
731 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
732 WHERE `group`.`uid` = %d
745 * @brief Fetch the contact id for a given URL and user
747 * First lookup in the contact table to find a record matching either `url`, `nurl`,
750 * If there's no record and we aren't looking for a public contact, we quit.
751 * If there's one, we check that it isn't time to update the picture else we
752 * directly return the found contact id.
754 * Second, we probe the provided $url whether it's http://server.tld/profile or
755 * nick@server.tld. We quit if we can't get any info back.
757 * Third, we create the contact record if it doesn't exist
759 * Fourth, we update the existing record with the new data (avatar, alias, nick)
760 * if there's any updates
762 * @param string $url Contact URL
763 * @param integer $uid The user id for the contact (0 = public contact)
764 * @param boolean $no_update Don't update the contact
765 * @param array $default Default value for creating the contact when every else fails
767 * @return integer Contact ID
769 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
771 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
779 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
780 // We first try the nurl (http://server.tld/nick), most common case
781 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
783 // Then the addr (nick@server.tld)
784 if (!DBM::is_result($contact)) {
785 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
788 // Then the alias (which could be anything)
789 if (!DBM::is_result($contact)) {
790 // The link could be provided as http although we stored it as https
791 $ssl_url = str_replace('http://', 'https://', $url);
792 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
793 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
796 if (DBM::is_result($contact)) {
797 $contact_id = $contact["id"];
799 // Update the contact every 7 days
800 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
802 // We force the update if the avatar is empty
803 if (!x($contact, 'avatar')) {
804 $update_contact = true;
807 if (!$update_contact || $no_update) {
810 } elseif ($uid != 0) {
811 // Non-existing user-specific contact, exiting
815 $data = Probe::uri($url, "", $uid);
817 // Last try in gcontact for unsupported networks
818 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL, NETWORK_FEED])) {
823 // Get data from the gcontact table
824 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
825 $contact = dba::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
826 if (!DBM::is_result($contact)) {
827 $contact = dba::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
830 if (!DBM::is_result($contact)) {
831 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
832 'photo', 'keywords', 'location', 'about', 'network',
833 'priority', 'batch', 'request', 'confirm', 'poco'];
834 $contact = dba::selectFirst('contact', $fields, ['addr' => $url]);
837 if (!DBM::is_result($contact)) {
838 // The link could be provided as http although we stored it as https
839 $ssl_url = str_replace('http://', 'https://', $url);
840 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
841 $contact = dba::selectFirst('contact', $fields, $condition);
844 if (!DBM::is_result($contact)) {
845 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
846 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
847 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
848 $contact = dba::selectFirst('fcontact', $fields, $condition);
851 if (!empty($default)) {
855 if (!DBM::is_result($contact)) {
858 $data = array_merge($data, $contact);
862 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
863 $contact_id = self::getIdForURL($data["alias"], $uid, true);
868 dba::insert('contact', [
870 'created' => DateTimeFormat::utcNow(),
871 'url' => $data["url"],
872 'nurl' => normalise_link($data["url"]),
873 'addr' => $data["addr"],
874 'alias' => $data["alias"],
875 'notify' => $data["notify"],
876 'poll' => $data["poll"],
877 'name' => $data["name"],
878 'nick' => $data["nick"],
879 'photo' => $data["photo"],
880 'keywords' => $data["keywords"],
881 'location' => $data["location"],
882 'about' => $data["about"],
883 'network' => $data["network"],
884 'pubkey' => $data["pubkey"],
885 'rel' => CONTACT_IS_SHARING,
886 'priority' => $data["priority"],
887 'batch' => $data["batch"],
888 'request' => $data["request"],
889 'confirm' => $data["confirm"],
890 'poco' => $data["poco"],
891 'name-date' => DateTimeFormat::utcNow(),
892 'uri-date' => DateTimeFormat::utcNow(),
893 'avatar-date' => DateTimeFormat::utcNow(),
900 $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
901 $contacts = dba::inArray($s);
902 if (!DBM::is_result($contacts)) {
906 $contact_id = $contacts[0]["id"];
908 // Update the newly created contact from data in the gcontact table
909 $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
910 if (DBM::is_result($gcontact)) {
911 // Only use the information when the probing hadn't fetched these values
912 if ($data['keywords'] != '') {
913 unset($gcontact['keywords']);
915 if ($data['location'] != '') {
916 unset($gcontact['location']);
918 if ($data['about'] != '') {
919 unset($gcontact['about']);
921 dba::update('contact', $gcontact, ['id' => $contact_id]);
924 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
925 dba::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
926 normalise_link($data["url"]), $contact_id]);
930 self::updateAvatar($data["photo"], $uid, $contact_id);
932 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
933 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
935 // This condition should always be true
936 if (!DBM::is_result($contact)) {
940 $updated = ['addr' => $data['addr'],
941 'alias' => $data['alias'],
942 'url' => $data['url'],
943 'nurl' => normalise_link($data['url']),
944 'name' => $data['name'],
945 'nick' => $data['nick']];
947 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
948 if (!empty($contact['pubkey'])) {
949 unset($contact['pubkey']);
951 $updated['pubkey'] = $data['pubkey'];
954 if ($data['keywords'] != '') {
955 $updated['keywords'] = $data['keywords'];
957 if ($data['location'] != '') {
958 $updated['location'] = $data['location'];
960 if ($data['about'] != '') {
961 $updated['about'] = $data['about'];
964 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
965 $updated['uri-date'] = DateTimeFormat::utcNow();
967 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
968 $updated['name-date'] = DateTimeFormat::utcNow();
971 $updated['avatar-date'] = DateTimeFormat::utcNow();
973 dba::update('contact', $updated, ['id' => $contact_id], $contact);
979 * @brief Checks if the contact is blocked
981 * @param int $cid contact id
983 * @return boolean Is the contact blocked?
985 public static function isBlocked($cid)
991 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
992 if (!DBM::is_result($blocked)) {
995 return (bool) $blocked['blocked'];
999 * @brief Checks if the contact is hidden
1001 * @param int $cid contact id
1003 * @return boolean Is the contact hidden?
1005 public static function isHidden($cid)
1011 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
1012 if (!DBM::is_result($hidden)) {
1015 return (bool) $hidden['hidden'];
1019 * @brief Returns posts from a given contact url
1021 * @param string $contact_url Contact URL
1023 * @return string posts in HTML
1025 public static function getPostsFromUrl($contact_url)
1027 $a = self::getApp();
1029 require_once 'include/conversation.php';
1031 // There are no posts with "uid = 0" with connector networks
1032 // This speeds up the query a lot
1033 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1034 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1035 dbesc(normalise_link($contact_url))
1038 if (!DBM::is_result($r)) {
1042 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1043 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
1045 $sql = "`item`.`uid` = %d";
1048 $author_id = intval($r[0]["author-id"]);
1050 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1052 $r = q(item_query(local_user()) . " AND `item`.`" . $contact . "` = %d AND " . $sql .
1053 " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
1054 intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
1055 intval($a->pager['start']), intval($a->pager['itemspage'])
1058 $o = conversation($a, $r, 'contact-posts', false);
1060 $o .= alt_pager($a, count($r));
1066 * @brief Returns the account type name
1068 * The function can be called with either the user or the contact array
1070 * @param array $contact contact or user array
1073 public static function getAccountType(array $contact)
1075 // There are several fields that indicate that the contact or user is a forum
1076 // "page-flags" is a field in the user table,
1077 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
1078 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
1079 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
1080 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
1081 || (isset($contact['forum']) && intval($contact['forum']))
1082 || (isset($contact['prv']) && intval($contact['prv']))
1083 || (isset($contact['community']) && intval($contact['community']))
1085 $type = ACCOUNT_TYPE_COMMUNITY;
1087 $type = ACCOUNT_TYPE_PERSON;
1090 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1091 if (isset($contact["contact-type"])) {
1092 $type = $contact["contact-type"];
1095 if (isset($contact["account-type"])) {
1096 $type = $contact["account-type"];
1100 case ACCOUNT_TYPE_ORGANISATION:
1101 $account_type = L10n::t("Organisation");
1103 case ACCOUNT_TYPE_NEWS:
1104 $account_type = L10n::t('News');
1106 case ACCOUNT_TYPE_COMMUNITY:
1107 $account_type = L10n::t("Forum");
1114 return $account_type;
1118 * @brief Blocks a contact
1123 public static function block($uid)
1125 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
1131 * @brief Unblocks a contact
1136 public static function unblock($uid)
1138 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
1144 * @brief Updates the avatar links in a contact only if needed
1146 * @param string $avatar Link to avatar picture
1147 * @param int $uid User id of contact owner
1148 * @param int $cid Contact id
1149 * @param bool $force force picture update
1151 * @return array Returns array of the different avatar sizes
1153 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1155 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1156 if (!DBM::is_result($contact)) {
1159 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1162 if (($contact["avatar"] != $avatar) || $force) {
1163 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1168 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1172 // Update the public contact (contact id = 0)
1174 $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1175 if (DBM::is_result($pcontact)) {
1176 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1188 * @param integer $id contact id
1191 public static function updateFromProbe($id)
1194 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1195 This will reliably kill your communication with Friendica contacts.
1198 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1199 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1200 if (!DBM::is_result($contact)) {
1204 $ret = Probe::uri($contact["url"]);
1206 // If Probe::uri fails the network code will be different
1207 if ($ret["network"] != $contact["network"]) {
1213 // make sure to not overwrite existing values with blank entries
1214 foreach ($ret as $key => $val) {
1215 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1216 $ret[$key] = $contact[$key];
1219 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1230 'url' => $ret['url'],
1231 'nurl' => normalise_link($ret['url']),
1232 'addr' => $ret['addr'],
1233 'alias' => $ret['alias'],
1234 'batch' => $ret['batch'],
1235 'notify' => $ret['notify'],
1236 'poll' => $ret['poll'],
1237 'poco' => $ret['poco']
1242 // Update the corresponding gcontact entry
1243 PortableContact::lastUpdated($ret["url"]);
1249 * Takes a $uid and a url/handle and adds a new contact
1250 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1251 * dfrn_request page.
1253 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1256 * $return['success'] boolean true if successful
1257 * $return['message'] error text if success is false.
1259 * @brief Takes a $uid and a url/handle and adds a new contact
1261 * @param string $url
1262 * @param bool $interactive
1263 * @param string $network
1264 * @return boolean|string
1266 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1268 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1272 // remove ajax junk, e.g. Twitter
1273 $url = str_replace('/#!/', '/', $url);
1275 if (!Network::isUrlAllowed($url)) {
1276 $result['message'] = L10n::t('Disallowed profile URL.');
1280 if (Network::isUrlBlocked($url)) {
1281 $result['message'] = L10n::t('Blocked domain');
1286 $result['message'] = L10n::t('Connect URL missing.');
1290 $arr = ['url' => $url, 'contact' => []];
1292 Addon::callHooks('follow', $arr);
1295 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1299 if (x($arr['contact'], 'name')) {
1300 $ret = $arr['contact'];
1302 $ret = Probe::uri($url, $network, $uid, false);
1305 if (($network != '') && ($ret['network'] != $network)) {
1306 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1310 // check if we already have a contact
1311 // the poll url is more reliable than the profile url, as we may have
1312 // indirect links or webfinger links
1314 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1316 dbesc($ret['poll']),
1317 dbesc(normalise_link($ret['poll'])),
1318 dbesc($ret['network'])
1321 if (!DBM::is_result($r)) {
1322 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1324 dbesc(normalise_link($url)),
1325 dbesc($ret['network'])
1329 if (($ret['network'] === NETWORK_DFRN) && !DBM::is_result($r)) {
1331 if (strlen($a->path)) {
1332 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1334 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1337 goaway($ret['request'] . "&addr=$myaddr");
1341 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != NETWORK_DFRN)) {
1342 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1343 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1347 // This extra param just confuses things, remove it
1348 if ($ret['network'] === NETWORK_DIASPORA) {
1349 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1352 // do we have enough information?
1354 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1355 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1356 if (!x($ret, 'poll')) {
1357 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1359 if (!x($ret, 'name')) {
1360 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1362 if (!x($ret, 'url')) {
1363 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1365 if (strpos($url, '@') !== false) {
1366 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1367 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1372 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1373 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1374 $ret['notify'] = '';
1377 if (!$ret['notify']) {
1378 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1381 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1383 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1385 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1387 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1391 if (DBM::is_result($r)) {
1393 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1395 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1396 dba::update('contact', $fields, ['id' => $r[0]['id']]);
1398 $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1400 // create contact record
1401 dba::insert('contact', [
1403 'created' => DateTimeFormat::utcNow(),
1404 'url' => $ret['url'],
1405 'nurl' => normalise_link($ret['url']),
1406 'addr' => $ret['addr'],
1407 'alias' => $ret['alias'],
1408 'batch' => $ret['batch'],
1409 'notify' => $ret['notify'],
1410 'poll' => $ret['poll'],
1411 'poco' => $ret['poco'],
1412 'name' => $ret['name'],
1413 'nick' => $ret['nick'],
1414 'network' => $ret['network'],
1415 'pubkey' => $ret['pubkey'],
1416 'rel' => $new_relation,
1417 'priority'=> $ret['priority'],
1418 'writable'=> $writeable,
1419 'hidden' => $hidden,
1427 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1428 if (!DBM::is_result($contact)) {
1429 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1433 $contact_id = $contact['id'];
1434 $result['cid'] = $contact_id;
1436 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1438 // Update the avatar
1439 self::updateAvatar($ret['photo'], $uid, $contact_id);
1441 // pull feed and consume it, which should subscribe to the hub.
1443 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1445 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1446 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1450 if (DBM::is_result($r)) {
1451 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
1452 // create a follow slap
1454 $item['verb'] = ACTIVITY_FOLLOW;
1455 $item['follow'] = $contact["url"];
1456 $slap = OStatus::salmon($item, $r[0]);
1457 if (!empty($contact['notify'])) {
1458 Salmon::slapper($r[0], $contact['notify'], $slap);
1460 } elseif ($contact['network'] == NETWORK_DIASPORA) {
1461 $ret = Diaspora::sendShare($a->user, $contact);
1462 logger('share returns: ' . $ret);
1466 $result['success'] = true;
1470 public static function updateSslPolicy($contact, $new_policy)
1472 $ssl_changed = false;
1473 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1474 $ssl_changed = true;
1475 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1476 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1477 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1478 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1479 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1480 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1483 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1484 $ssl_changed = true;
1485 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1486 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1487 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1488 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1489 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1490 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1494 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1495 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1496 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1497 dba::update('contact', $fields, ['id' => $contact['id']]);
1503 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1504 $url = notags(trim($datarray['author-link']));
1505 $name = notags(trim($datarray['author-name']));
1506 $photo = notags(trim($datarray['author-avatar']));
1509 if (is_object($item)) {
1510 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1511 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1512 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1518 if (is_array($contact)) {
1519 if (($contact['rel'] == CONTACT_IS_SHARING)
1520 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1521 dba::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1522 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1524 // send email notification to owner?
1526 if (dba::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1527 logger('ignoring duplicated connection request from pending contact ' . $url);
1531 // create contact record
1532 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1533 `blocked`, `readonly`, `pending`, `writable`)
1534 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1535 intval($importer['uid']),
1536 dbesc(DateTimeFormat::utcNow()),
1538 dbesc(normalise_link($url)),
1542 dbesc(NETWORK_OSTATUS),
1543 intval(CONTACT_IS_FOLLOWER)
1547 'id' => dba::lastInsertId(),
1548 'network' => NETWORK_OSTATUS
1550 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1552 /// @TODO Encapsulate this into a function/method
1553 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1554 $user = dba::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1555 if (DBM::is_result($user) && !in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1556 // create notification
1557 $hash = random_string();
1559 if (is_array($contact_record)) {
1560 dba::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1561 'blocked' => false, 'knowyou' => false,
1562 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1565 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1567 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1568 in_array($user['page-flags'], [PAGE_NORMAL])) {
1571 'type' => NOTIFY_INTRO,
1572 'notify_flags' => $user['notify-flags'],
1573 'language' => $user['language'],
1574 'to_name' => $user['username'],
1575 'to_email' => $user['email'],
1576 'uid' => $user['uid'],
1577 'link' => System::baseUrl() . '/notifications/intro',
1578 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1579 'source_link' => $contact_record['url'],
1580 'source_photo' => $contact_record['photo'],
1581 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1586 } elseif (DBM::is_result($user) && in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1587 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1588 intval($importer['uid']),
1595 public static function removeFollower($importer, $contact, array $datarray = [], $item = "") {
1597 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1598 dba::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1600 Contact::remove($contact['id']);
1604 public static function removeSharer($importer, $contact, array $datarray = [], $item = "") {
1606 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1607 dba::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1609 Contact::remove($contact['id']);
1614 * @brief Create a birthday event.
1616 * Update the year and the birthday.
1618 public static function updateBirthdays()
1620 // This only handles foreign or alien networks where a birthday has been provided.
1621 // In-network birthdays are handled within local_delivery
1623 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1624 if (DBM::is_result($r)) {
1625 foreach ($r as $rr) {
1626 logger('update_contact_birthday: ' . $rr['bd']);
1628 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1631 * Add new birthday event for this person
1633 * $bdtext is just a readable placeholder in case the event is shared
1634 * with others. We will replace it during presentation to our $importer
1635 * to contain a sparkle link and perhaps a photo.
1638 // Check for duplicates
1639 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1640 intval($rr['uid']), intval($rr['id']), dbesc(DateTimeFormat::utc($nextbd)), dbesc('birthday'));
1642 if (DBM::is_result($s)) {
1646 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1647 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1649 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1650 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1651 dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utc($nextbd)),
1652 dbesc(DateTimeFormat::utc($nextbd . ' + 1 day ')), dbesc($bdtext), dbesc($bdtext2), dbesc('birthday'),
1658 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(substr($nextbd, 0, 4)),
1659 dbesc($nextbd), intval($rr['uid']), intval($rr['id'])
1666 * Remove the unavailable contact ids from the provided list
1668 * @param array $contact_ids Contact id list
1670 public static function pruneUnavailable(array &$contact_ids)
1672 if (empty($contact_ids)) {
1676 $str = dbesc(implode(',', $contact_ids));
1678 $stmt = dba::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1681 while($contact = dba::fetch($stmt)) {
1682 $return[] = $contact['id'];
1687 $contact_ids = $return;
1691 * @brief Returns a magic link to authenticate remote visitors
1693 * @param string $contact_url The address of the target contact profile
1694 * @param integer $url An url that we will be redirected to after the authentication
1696 * @return string with "redir" link
1698 public static function magicLink($contact_url, $url = '')
1700 $cid = self::getIdForURL($contact_url, 0, true);
1702 return ($url != '') ? $url : $contact_url;
1705 return self::magicLinkbyId($cid, $url);
1709 * @brief Returns a magic link to authenticate remote visitors
1711 * @param integer $cid The contact id of the target contact profile
1712 * @param integer $url An url that we will be redirected to after the authentication
1714 * @return string with "redir" link
1716 public static function magicLinkbyId($cid, $url = '')
1718 $contact = dba::selectFirst('contact', ['network', 'url', 'uid'], ['id' => $cid]);
1720 if ($contact['network'] != NETWORK_DFRN) {
1721 return ($url != '') ? $url : $contact['url'];
1724 // Only redirections to the same host do make sense
1725 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
1729 if ($contact['uid'] != 0) {
1730 return self::magicLink($contact['url'], $url);
1733 $redirect = 'redir/' . $cid;
1736 $redirect .= '?url=' . $url;