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 $avatar = dba::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
172 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
173 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
174 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
175 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
176 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
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 $fields['forum'] = $user['page-flags'] == PAGE_COMMUNITY;
201 $fields['prv'] = $user['page-flags'] == PAGE_PRVGROUP;
205 foreach ($fields as $field => $content) {
206 if ($self[$field] != $content) {
212 $fields['name-date'] = DateTimeFormat::utcNow();
213 dba::update('contact', $fields, ['id' => $self['id']]);
215 // Update the public contact as well
216 dba::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
221 * @brief Marks a contact for removal
223 * @param int $id contact id
226 public static function remove($id)
228 // We want just to make sure that we don't delete our "self" contact
229 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
230 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
234 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
236 dba::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
240 dba::delete('contact', ['id' => $id]);
242 // Delete the rest in the background
243 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
247 * @brief Sends an unfriend message. Does not remove the contact
249 * @param array $user User unfriending
250 * @param array $contact Contact unfriended
253 public static function terminateFriendship(array $user, array $contact)
255 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
256 // create an unfollow slap
258 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
259 $item['follow'] = $contact["url"];
260 $slap = OStatus::salmon($item, $user);
262 if (!empty($contact['notify'])) {
263 Salmon::slapper($user, $contact['notify'], $slap);
265 } elseif ($contact['network'] == NETWORK_DIASPORA) {
266 Diaspora::sendUnshare($user, $contact);
271 * @brief Marks a contact for archival after a communication issue delay
273 * Contact has refused to recognise us as a friend. We will start a countdown.
274 * If they still don't recognise us in 32 days, the relationship is over,
275 * and we won't waste any more time trying to communicate with them.
276 * This provides for the possibility that their database is temporarily messed
277 * up or some other transient event and that there's a possibility we could recover from it.
279 * @param array $contact contact to mark for archival
282 public static function markForArchival(array $contact)
284 // Contact already archived or "self" contact? => nothing to do
285 if ($contact['archive'] || $contact['self']) {
289 if ($contact['term-date'] <= NULL_DATE) {
290 dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
292 if ($contact['url'] != '') {
293 dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
297 * We really should send a notification to the owner after 2-3 weeks
298 * so they won't be surprised when the contact vanishes and can take
299 * remedial action if this was a serious mistake or glitch
302 /// @todo Check for contact vitality via probing
303 $expiry = $contact['term-date'] . ' + 32 days ';
304 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
305 /* Relationship is really truly dead. archive them rather than
306 * delete, though if the owner tries to unarchive them we'll start
307 * the whole process over again.
309 dba::update('contact', ['archive' => 1], ['id' => $contact['id']]);
311 if ($contact['url'] != '') {
312 dba::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
319 * @brief Cancels the archival countdown
321 * @see Contact::markForArchival()
323 * @param array $contact contact to be unmarked for archival
326 public static function unmarkForArchival(array $contact)
328 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
329 $exists = dba::exists('contact', $condition);
331 // We don't need to update, we never marked this contact for archival
336 // It's a miracle. Our dead contact has inexplicably come back to life.
337 $fields = ['term-date' => NULL_DATE, 'archive' => false];
338 dba::update('contact', $fields, ['id' => $contact['id']]);
340 if ($contact['url'] != '') {
341 dba::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
346 * @brief Get contact data for a given profile link
348 * The function looks at several places (contact table and gcontact table) for the contact
349 * It caches its result for the same script execution to prevent duplicate calls
351 * @param string $url The profile link
352 * @param int $uid User id
353 * @param array $default If not data was found take this data as default value
355 * @return array Contact data
357 public static function getDetailsByURL($url, $uid = -1, array $default = [])
369 if (isset($cache[$url][$uid])) {
370 return $cache[$url][$uid];
373 $ssl_url = str_replace('http://', 'https://', $url);
375 // Fetch contact data from the contact table for the given user
376 $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`,
377 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
378 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
379 $r = dba::inArray($s);
381 // Fetch contact data from the contact table for the given user, checking with the alias
382 if (!DBM::is_result($r)) {
383 $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`,
384 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
385 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
386 $r = dba::inArray($s);
389 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
390 if (!DBM::is_result($r)) {
391 $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`,
392 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
393 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
394 $r = dba::inArray($s);
397 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
398 if (!DBM::is_result($r)) {
399 $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`,
400 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
401 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
402 $r = dba::inArray($s);
405 // Fetch the data from the gcontact table
406 if (!DBM::is_result($r)) {
407 $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`,
408 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
409 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
410 $r = dba::inArray($s);
413 if (DBM::is_result($r)) {
414 // If there is more than one entry we filter out the connector networks
416 foreach ($r as $id => $result) {
417 if ($result["network"] == NETWORK_STATUSNET) {
423 $profile = array_shift($r);
425 // "bd" always contains the upcoming birthday of a contact.
426 // "birthday" might contain the birthday including the year of birth.
427 if ($profile["birthday"] > '0001-01-01') {
428 $bd_timestamp = strtotime($profile["birthday"]);
429 $month = date("m", $bd_timestamp);
430 $day = date("d", $bd_timestamp);
432 $current_timestamp = time();
433 $current_year = date("Y", $current_timestamp);
434 $current_month = date("m", $current_timestamp);
435 $current_day = date("d", $current_timestamp);
437 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
438 $current = $current_year . "-" . $current_month . "-" . $current_day;
440 if ($profile["bd"] < $current) {
441 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
444 $profile["bd"] = '0001-01-01';
450 if (($profile["photo"] == "") && isset($default["photo"])) {
451 $profile["photo"] = $default["photo"];
454 if (($profile["name"] == "") && isset($default["name"])) {
455 $profile["name"] = $default["name"];
458 if (($profile["network"] == "") && isset($default["network"])) {
459 $profile["network"] = $default["network"];
462 if (($profile["thumb"] == "") && isset($profile["photo"])) {
463 $profile["thumb"] = $profile["photo"];
466 if (($profile["micro"] == "") && isset($profile["thumb"])) {
467 $profile["micro"] = $profile["thumb"];
470 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
471 && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
473 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
476 // Show contact details of Diaspora contacts only if connected
477 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
478 $profile["location"] = "";
479 $profile["about"] = "";
480 $profile["gender"] = "";
481 $profile["birthday"] = '0001-01-01';
484 $cache[$url][$uid] = $profile;
490 * @brief Get contact data for a given address
492 * The function looks at several places (contact table and gcontact table) for the contact
494 * @param string $addr The profile link
495 * @param int $uid User id
497 * @return array Contact data
499 public static function getDetailsByAddr($addr, $uid = -1)
511 // Fetch contact data from the contact table for the given user
512 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
513 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
514 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
518 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
519 if (!DBM::is_result($r)) {
520 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
521 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
522 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
527 // Fetch the data from the gcontact table
528 if (!DBM::is_result($r)) {
529 $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`,
530 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
531 FROM `gcontact` WHERE `addr` = '%s'",
536 if (!DBM::is_result($r)) {
537 $data = Probe::uri($addr);
539 $profile = self::getDetailsByURL($data['url'], $uid);
548 * @brief Returns the data array for the photo menu of a given contact
550 * @param array $contact contact
551 * @param int $uid optional, default 0
554 public static function photoMenu(array $contact, $uid = 0)
556 // @todo Unused, to be removed
564 $contact_drop_link = '';
571 if ($contact['uid'] != $uid) {
573 $profile_link = Profile::zrl($contact['url']);
574 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
579 // Look for our own contact if the uid doesn't match and isn't public
580 $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
581 if (DBM::is_result($contact_own)) {
582 return self::photoMenu($contact_own, $uid);
584 $profile_link = Profile::zrl($contact['url']);
585 $connlnk = 'follow/?url=' . $contact['url'];
587 'profile' => [L10n::t('View Profile'), $profile_link, true],
588 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
596 if (($contact['network'] === NETWORK_DFRN) && !$contact['self']) {
598 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
600 $profile_link = $contact['url'];
603 if ($profile_link === 'mailbox') {
608 $status_link = $profile_link . '?url=status';
609 $photos_link = $profile_link . '?url=photos';
610 $profile_link = $profile_link . '?url=profile';
613 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA]) && !$contact['self']) {
614 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
617 if (($contact['network'] == NETWORK_DFRN) && !$contact['self']) {
618 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
621 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
623 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
625 if (!$contact['self']) {
626 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
631 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
634 'status' => [L10n::t("View Status") , $status_link , true],
635 'profile' => [L10n::t("View Profile") , $profile_link , true],
636 'photos' => [L10n::t("View Photos") , $photos_link , true],
637 'network' => [L10n::t("Network Posts"), $posts_link , false],
638 'edit' => [L10n::t("View Contact") , $contact_url , false],
639 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
640 'pm' => [L10n::t("Send PM") , $pm_url , false],
641 'poke' => [L10n::t("Poke") , $poke_link , false],
644 $args = ['contact' => $contact, 'menu' => &$menu];
646 Addon::callHooks('contact_photo_menu', $args);
650 foreach ($menu as $menuname => $menuitem) {
651 if ($menuitem[1] != '') {
652 $menucondensed[$menuname] = $menuitem;
656 return $menucondensed;
660 * @brief Returns ungrouped contact count or list for user
662 * Returns either the total number of ungrouped contacts for the given user
663 * id or a paginated list of ungrouped contacts.
665 * @param int $uid uid
666 * @param int $start optional, default 0
667 * @param int $count optional, default 0
671 public static function getUngroupedList($uid, $start = 0, $count = 0)
675 "SELECT COUNT(*) AS `total`
682 SELECT DISTINCT(`contact-id`)
701 SELECT DISTINCT(`contact-id`)
703 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
704 WHERE `group`.`uid` = %d
717 * @brief Fetch the contact id for a given URL and user
719 * First lookup in the contact table to find a record matching either `url`, `nurl`,
722 * If there's no record and we aren't looking for a public contact, we quit.
723 * If there's one, we check that it isn't time to update the picture else we
724 * directly return the found contact id.
726 * Second, we probe the provided $url whether it's http://server.tld/profile or
727 * nick@server.tld. We quit if we can't get any info back.
729 * Third, we create the contact record if it doesn't exist
731 * Fourth, we update the existing record with the new data (avatar, alias, nick)
732 * if there's any updates
734 * @param string $url Contact URL
735 * @param integer $uid The user id for the contact (0 = public contact)
736 * @param boolean $no_update Don't update the contact
738 * @return integer Contact ID
740 public static function getIdForURL($url, $uid = 0, $no_update = false)
742 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
750 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
751 // We first try the nurl (http://server.tld/nick), most common case
752 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
754 // Then the addr (nick@server.tld)
755 if (!DBM::is_result($contact)) {
756 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
759 // Then the alias (which could be anything)
760 if (!DBM::is_result($contact)) {
761 // The link could be provided as http although we stored it as https
762 $ssl_url = str_replace('http://', 'https://', $url);
763 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
764 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
767 if (DBM::is_result($contact)) {
768 $contact_id = $contact["id"];
770 // Update the contact every 7 days
771 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
773 // We force the update if the avatar is empty
774 if (!x($contact, 'avatar')) {
775 $update_contact = true;
778 if (!$update_contact || $no_update) {
781 } elseif ($uid != 0) {
782 // Non-existing user-specific contact, exiting
786 $data = Probe::uri($url, "", $uid);
788 // Last try in gcontact for unsupported networks
789 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL])) {
794 // Get data from the gcontact table
795 $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
796 if (!DBM::is_result($gcontact)) {
800 $data = array_merge($data, $gcontact);
803 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
804 $contact_id = self::getIdForURL($data["alias"], $uid, true);
809 dba::insert('contact', [
811 'created' => DateTimeFormat::utcNow(),
812 'url' => $data["url"],
813 'nurl' => normalise_link($data["url"]),
814 'addr' => $data["addr"],
815 'alias' => $data["alias"],
816 'notify' => $data["notify"],
817 'poll' => $data["poll"],
818 'name' => $data["name"],
819 'nick' => $data["nick"],
820 'photo' => $data["photo"],
821 'keywords' => $data["keywords"],
822 'location' => $data["location"],
823 'about' => $data["about"],
824 'network' => $data["network"],
825 'pubkey' => $data["pubkey"],
826 'rel' => CONTACT_IS_SHARING,
827 'priority' => $data["priority"],
828 'batch' => $data["batch"],
829 'request' => $data["request"],
830 'confirm' => $data["confirm"],
831 'poco' => $data["poco"],
832 'name-date' => DateTimeFormat::utcNow(),
833 'uri-date' => DateTimeFormat::utcNow(),
834 'avatar-date' => DateTimeFormat::utcNow(),
841 $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
842 $contacts = dba::inArray($s);
843 if (!DBM::is_result($contacts)) {
847 $contact_id = $contacts[0]["id"];
849 // Update the newly created contact from data in the gcontact table
850 $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
851 if (DBM::is_result($gcontact)) {
852 // Only use the information when the probing hadn't fetched these values
853 if ($data['keywords'] != '') {
854 unset($gcontact['keywords']);
856 if ($data['location'] != '') {
857 unset($gcontact['location']);
859 if ($data['about'] != '') {
860 unset($gcontact['about']);
862 dba::update('contact', $gcontact, ['id' => $contact_id]);
865 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
866 dba::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
867 normalise_link($data["url"]), $contact_id]);
871 self::updateAvatar($data["photo"], $uid, $contact_id);
873 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
874 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
876 // This condition should always be true
877 if (!DBM::is_result($contact)) {
881 $updated = ['addr' => $data['addr'],
882 'alias' => $data['alias'],
883 'url' => $data['url'],
884 'nurl' => normalise_link($data['url']),
885 'name' => $data['name'],
886 'nick' => $data['nick']];
888 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
889 if (!empty($contact['pubkey'])) {
890 unset($contact['pubkey']);
892 $updated['pubkey'] = $data['pubkey'];
895 if ($data['keywords'] != '') {
896 $updated['keywords'] = $data['keywords'];
898 if ($data['location'] != '') {
899 $updated['location'] = $data['location'];
901 if ($data['about'] != '') {
902 $updated['about'] = $data['about'];
905 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
906 $updated['uri-date'] = DateTimeFormat::utcNow();
908 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
909 $updated['name-date'] = DateTimeFormat::utcNow();
912 $updated['avatar-date'] = DateTimeFormat::utcNow();
914 dba::update('contact', $updated, ['id' => $contact_id], $contact);
920 * @brief Checks if the contact is blocked
922 * @param int $cid contact id
924 * @return boolean Is the contact blocked?
926 public static function isBlocked($cid)
932 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
933 if (!DBM::is_result($blocked)) {
936 return (bool) $blocked['blocked'];
940 * @brief Checks if the contact is hidden
942 * @param int $cid contact id
944 * @return boolean Is the contact hidden?
946 public static function isHidden($cid)
952 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
953 if (!DBM::is_result($hidden)) {
956 return (bool) $hidden['hidden'];
960 * @brief Returns posts from a given contact url
962 * @param string $contact_url Contact URL
964 * @return string posts in HTML
966 public static function getPostsFromUrl($contact_url)
970 require_once 'include/conversation.php';
972 // There are no posts with "uid = 0" with connector networks
973 // This speeds up the query a lot
974 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
975 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
976 dbesc(normalise_link($contact_url))
979 if (!DBM::is_result($r)) {
983 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
984 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
986 $sql = "`item`.`uid` = %d";
989 $author_id = intval($r[0]["author-id"]);
991 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
993 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
994 " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
995 intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
996 intval($a->pager['start']), intval($a->pager['itemspage'])
999 $o = conversation($a, $r, 'contact-posts', false);
1001 $o .= alt_pager($a, count($r));
1007 * @brief Returns the account type name
1009 * The function can be called with either the user or the contact array
1011 * @param array $contact contact or user array
1014 public static function getAccountType(array $contact)
1016 // There are several fields that indicate that the contact or user is a forum
1017 // "page-flags" is a field in the user table,
1018 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
1019 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
1020 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
1021 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
1022 || (isset($contact['forum']) && intval($contact['forum']))
1023 || (isset($contact['prv']) && intval($contact['prv']))
1024 || (isset($contact['community']) && intval($contact['community']))
1026 $type = ACCOUNT_TYPE_COMMUNITY;
1028 $type = ACCOUNT_TYPE_PERSON;
1031 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1032 if (isset($contact["contact-type"])) {
1033 $type = $contact["contact-type"];
1036 if (isset($contact["account-type"])) {
1037 $type = $contact["account-type"];
1041 case ACCOUNT_TYPE_ORGANISATION:
1042 $account_type = L10n::t("Organisation");
1044 case ACCOUNT_TYPE_NEWS:
1045 $account_type = L10n::t('News');
1047 case ACCOUNT_TYPE_COMMUNITY:
1048 $account_type = L10n::t("Forum");
1055 return $account_type;
1059 * @brief Blocks a contact
1064 public static function block($uid)
1066 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
1072 * @brief Unblocks a contact
1077 public static function unblock($uid)
1079 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
1085 * @brief Updates the avatar links in a contact only if needed
1087 * @param string $avatar Link to avatar picture
1088 * @param int $uid User id of contact owner
1089 * @param int $cid Contact id
1090 * @param bool $force force picture update
1092 * @return array Returns array of the different avatar sizes
1094 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1096 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1097 if (!DBM::is_result($contact)) {
1100 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1103 if (($contact["avatar"] != $avatar) || $force) {
1104 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1109 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1113 // Update the public contact (contact id = 0)
1115 $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1116 if (DBM::is_result($pcontact)) {
1117 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1129 * @param integer $id contact id
1132 public static function updateFromProbe($id)
1135 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1136 This will reliably kill your communication with Friendica contacts.
1139 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1140 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1141 if (!DBM::is_result($contact)) {
1145 $ret = Probe::uri($contact["url"]);
1147 // If Probe::uri fails the network code will be different
1148 if ($ret["network"] != $contact["network"]) {
1154 // make sure to not overwrite existing values with blank entries
1155 foreach ($ret as $key => $val) {
1156 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1157 $ret[$key] = $contact[$key];
1160 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1171 'url' => $ret['url'],
1172 'nurl' => normalise_link($ret['url']),
1173 'addr' => $ret['addr'],
1174 'alias' => $ret['alias'],
1175 'batch' => $ret['batch'],
1176 'notify' => $ret['notify'],
1177 'poll' => $ret['poll'],
1178 'poco' => $ret['poco']
1183 // Update the corresponding gcontact entry
1184 PortableContact::lastUpdated($ret["url"]);
1190 * Takes a $uid and a url/handle and adds a new contact
1191 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1192 * dfrn_request page.
1194 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1197 * $return['success'] boolean true if successful
1198 * $return['message'] error text if success is false.
1200 * @brief Takes a $uid and a url/handle and adds a new contact
1202 * @param string $url
1203 * @param bool $interactive
1204 * @param string $network
1205 * @return boolean|string
1207 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1209 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1213 // remove ajax junk, e.g. Twitter
1214 $url = str_replace('/#!/', '/', $url);
1216 if (!Network::isUrlAllowed($url)) {
1217 $result['message'] = L10n::t('Disallowed profile URL.');
1221 if (Network::isUrlBlocked($url)) {
1222 $result['message'] = L10n::t('Blocked domain');
1227 $result['message'] = L10n::t('Connect URL missing.');
1231 $arr = ['url' => $url, 'contact' => []];
1233 Addon::callHooks('follow', $arr);
1236 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1240 if (x($arr['contact'], 'name')) {
1241 $ret = $arr['contact'];
1243 $ret = Probe::uri($url, $network, $uid, false);
1246 if (($network != '') && ($ret['network'] != $network)) {
1247 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1251 // check if we already have a contact
1252 // the poll url is more reliable than the profile url, as we may have
1253 // indirect links or webfinger links
1255 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1257 dbesc($ret['poll']),
1258 dbesc(normalise_link($ret['poll'])),
1259 dbesc($ret['network'])
1262 if (!DBM::is_result($r)) {
1263 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1265 dbesc(normalise_link($url)),
1266 dbesc($ret['network'])
1270 if (($ret['network'] === NETWORK_DFRN) && !DBM::is_result($r)) {
1272 if (strlen($a->path)) {
1273 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1275 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1278 goaway($ret['request'] . "&addr=$myaddr");
1282 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != NETWORK_DFRN)) {
1283 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1284 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1288 // This extra param just confuses things, remove it
1289 if ($ret['network'] === NETWORK_DIASPORA) {
1290 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1293 // do we have enough information?
1295 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1296 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1297 if (!x($ret, 'poll')) {
1298 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1300 if (!x($ret, 'name')) {
1301 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1303 if (!x($ret, 'url')) {
1304 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1306 if (strpos($url, '@') !== false) {
1307 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1308 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1313 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1314 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1315 $ret['notify'] = '';
1318 if (!$ret['notify']) {
1319 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1322 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1324 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1326 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1328 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1332 if (DBM::is_result($r)) {
1334 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1336 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1337 dba::update('contact', $fields, ['id' => $r[0]['id']]);
1339 $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1341 // create contact record
1342 dba::insert('contact', [
1344 'created' => DateTimeFormat::utcNow(),
1345 'url' => $ret['url'],
1346 'nurl' => normalise_link($ret['url']),
1347 'addr' => $ret['addr'],
1348 'alias' => $ret['alias'],
1349 'batch' => $ret['batch'],
1350 'notify' => $ret['notify'],
1351 'poll' => $ret['poll'],
1352 'poco' => $ret['poco'],
1353 'name' => $ret['name'],
1354 'nick' => $ret['nick'],
1355 'network' => $ret['network'],
1356 'pubkey' => $ret['pubkey'],
1357 'rel' => $new_relation,
1358 'priority'=> $ret['priority'],
1359 'writable'=> $writeable,
1360 'hidden' => $hidden,
1368 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1369 if (!DBM::is_result($contact)) {
1370 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1374 $contact_id = $contact['id'];
1375 $result['cid'] = $contact_id;
1377 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1379 // Update the avatar
1380 self::updateAvatar($ret['photo'], $uid, $contact_id);
1382 // pull feed and consume it, which should subscribe to the hub.
1384 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1386 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1387 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1391 if (DBM::is_result($r)) {
1392 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
1393 // create a follow slap
1395 $item['verb'] = ACTIVITY_FOLLOW;
1396 $item['follow'] = $contact["url"];
1397 $slap = OStatus::salmon($item, $r[0]);
1398 if (!empty($contact['notify'])) {
1399 Salmon::slapper($r[0], $contact['notify'], $slap);
1401 } elseif ($contact['network'] == NETWORK_DIASPORA) {
1402 $ret = Diaspora::sendShare($a->user, $contact);
1403 logger('share returns: ' . $ret);
1407 $result['success'] = true;
1411 public static function updateSslPolicy($contact, $new_policy)
1413 $ssl_changed = false;
1414 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1415 $ssl_changed = true;
1416 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1417 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1418 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1419 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1420 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1421 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1424 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1425 $ssl_changed = true;
1426 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1427 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1428 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1429 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1430 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1431 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1435 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1436 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1437 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1438 dba::update('contact', $fields, ['id' => $contact['id']]);
1444 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1445 $url = notags(trim($datarray['author-link']));
1446 $name = notags(trim($datarray['author-name']));
1447 $photo = notags(trim($datarray['author-avatar']));
1450 if (is_object($item)) {
1451 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1452 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1453 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1459 if (is_array($contact)) {
1460 if (($contact['rel'] == CONTACT_IS_SHARING)
1461 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1462 dba::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1463 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1465 // send email notification to owner?
1467 // create contact record
1468 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1469 `blocked`, `readonly`, `pending`, `writable`)
1470 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1471 intval($importer['uid']),
1472 dbesc(DateTimeFormat::utcNow()),
1474 dbesc(normalise_link($url)),
1478 dbesc(NETWORK_OSTATUS),
1479 intval(CONTACT_IS_FOLLOWER)
1483 'id' => dba::lastInsertId(),
1484 'network' => NETWORK_OSTATUS
1486 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1488 /// @TODO Encapsulate this into a function/method
1489 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1490 $user = dba::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1491 if (DBM::is_result($user) && !in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1492 // create notification
1493 $hash = random_string();
1495 if (is_array($contact_record)) {
1496 dba::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1497 'blocked' => false, 'knowyou' => false,
1498 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1501 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1503 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1504 in_array($user['page-flags'], [PAGE_NORMAL])) {
1507 'type' => NOTIFY_INTRO,
1508 'notify_flags' => $user['notify-flags'],
1509 'language' => $user['language'],
1510 'to_name' => $user['username'],
1511 'to_email' => $user['email'],
1512 'uid' => $user['uid'],
1513 'link' => System::baseUrl() . '/notifications/intro',
1514 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1515 'source_link' => $contact_record['url'],
1516 'source_photo' => $contact_record['photo'],
1517 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1522 } elseif (DBM::is_result($user) && in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1523 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1524 intval($importer['uid']),
1531 public static function removeFollower($importer, $contact, array $datarray = [], $item = "") {
1533 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1534 dba::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1536 Contact::remove($contact['id']);
1540 public static function removeSharer($importer, $contact, array $datarray = [], $item = "") {
1542 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1543 dba::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1545 Contact::remove($contact['id']);
1550 * @brief Create a birthday event.
1552 * Update the year and the birthday.
1554 public static function updateBirthdays()
1556 // This only handles foreign or alien networks where a birthday has been provided.
1557 // In-network birthdays are handled within local_delivery
1559 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1560 if (DBM::is_result($r)) {
1561 foreach ($r as $rr) {
1562 logger('update_contact_birthday: ' . $rr['bd']);
1564 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1567 * Add new birthday event for this person
1569 * $bdtext is just a readable placeholder in case the event is shared
1570 * with others. We will replace it during presentation to our $importer
1571 * to contain a sparkle link and perhaps a photo.
1574 // Check for duplicates
1575 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1576 intval($rr['uid']), intval($rr['id']), dbesc(DateTimeFormat::utc($nextbd)), dbesc('birthday'));
1578 if (DBM::is_result($s)) {
1582 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1583 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1585 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1586 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1587 dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utc($nextbd)),
1588 dbesc(DateTimeFormat::utc($nextbd . ' + 1 day ')), dbesc($bdtext), dbesc($bdtext2), dbesc('birthday'),
1594 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(substr($nextbd, 0, 4)),
1595 dbesc($nextbd), intval($rr['uid']), intval($rr['id'])
1602 * Remove the unavailable contact ids from the provided list
1604 * @param array $contact_ids Contact id list
1606 public static function pruneUnavailable(array &$contact_ids)
1608 if (empty($contact_ids)) {
1612 $str = dbesc(implode(',', $contact_ids));
1614 $stmt = dba::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1617 while($contact = dba::fetch($stmt)) {
1618 $return[] = $contact['id'];
1623 $contact_ids = $return;