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;
27 require_once 'boot.php';
28 require_once 'include/dba.php';
29 require_once 'include/text.php';
32 * @brief functions for interacting with a contact
34 class Contact extends BaseObject
37 * @brief Returns a list of contacts belonging in a group
42 public static function getByGroupId($gid)
46 $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
48 INNER JOIN `group_member`
49 ON `contact`.`id` = `group_member`.`contact-id`
51 AND `contact`.`uid` = ?
52 AND NOT `contact`.`self`
53 AND NOT `contact`.`blocked`
54 AND NOT `contact`.`pending`
55 ORDER BY `contact`.`name` ASC',
59 if (DBM::is_result($stmt)) {
60 $return = dba::inArray($stmt);
68 * @brief Returns the count of OStatus contacts in a group
73 public static function getOStatusCountByGroupId($gid)
77 $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
79 INNER JOIN `group_member`
80 ON `contact`.`id` = `group_member`.`contact-id`
82 AND `contact`.`uid` = ?
83 AND `contact`.`network` = ?
84 AND `contact`.`notify` != ""',
89 $return = $contacts['count'];
96 * Creates the self-contact for the provided user id
99 * @return bool Operation success
101 public static function createSelfFromUserId($uid)
103 // Only create the entry if it doesn't exist yet
104 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
108 $user = dba::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
109 if (!DBM::is_result($user)) {
113 $return = dba::insert('contact', [
114 'uid' => $user['uid'],
115 'created' => DateTimeFormat::utcNow(),
117 'name' => $user['username'],
118 'nick' => $user['nickname'],
119 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
120 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
121 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
124 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
125 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
126 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
127 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
128 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
129 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
130 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
131 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
132 'name-date' => DateTimeFormat::utcNow(),
133 'uri-date' => DateTimeFormat::utcNow(),
134 'avatar-date' => DateTimeFormat::utcNow(),
142 * Updates the self-contact for the provided user id
145 * @param boolean $update_avatar Force the avatar update
147 public static function updateSelfFromUserID($uid, $update_avatar = false)
149 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
150 'xmpp', 'contact-type', 'forum', 'prv'];
151 $self = dba::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
152 if (!DBM::is_result($self)) {
156 $fields = ['nickname', 'page-flags', 'account-type'];
157 $user = dba::selectFirst('user', $fields, ['uid' => $uid]);
158 if (!DBM::is_result($user)) {
162 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
163 'country-name', 'gender', 'pub_keywords', 'xmpp'];
164 $profile = dba::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
165 if (!DBM::is_result($profile)) {
169 $avatar_resource = dba::selectFirst('photo', ['resource-id'], ['uid' => $uid, 'profile' => true]);
171 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
172 'location' => Profile::formatLocation($profile),
173 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
174 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
175 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
178 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
179 - dbesc(System::baseUrl() . '/photo/' . $base_image['resource-id'] . '-4.' . $Image->getExt()),
180 - dbesc(System::baseUrl() . '/photo/' . $base_image['resource-id'] . '-5.' . $Image->getExt()),
181 - dbesc(System::baseUrl() . '/photo/' . $base_image['resource-id'] . '-6.' . $Image->getExt()),
182 - intval(local_user())
186 $fields['forum'] = $user['page-flags'] == PAGE_COMMUNITY;
187 $fields['prv'] = $user['page-flags'] == PAGE_PRVGROUP;
191 foreach ($fields as $field => $content) {
192 if ($self[$field] != $content) {
198 $fields['name-date'] = DateTimeFormat::utcNow();
199 dba::update('contact', $fields, ['id' => $self['id']]);
202 Contact::updateAvatar($fields['avatar'], $uid, $self['id'], $update_avatar);
206 * @brief Marks a contact for removal
208 * @param int $id contact id
211 public static function remove($id)
213 // We want just to make sure that we don't delete our "self" contact
214 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
215 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
219 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
221 dba::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
225 dba::delete('contact', ['id' => $id]);
227 // Delete the rest in the background
228 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
232 * @brief Sends an unfriend message. Does not remove the contact
234 * @param array $user User unfriending
235 * @param array $contact Contact unfriended
238 public static function terminateFriendship(array $user, array $contact)
240 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
241 // create an unfollow slap
243 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
244 $item['follow'] = $contact["url"];
245 $slap = OStatus::salmon($item, $user);
247 if (!empty($contact['notify'])) {
248 Salmon::slapper($user, $contact['notify'], $slap);
250 } elseif ($contact['network'] == NETWORK_DIASPORA) {
251 Diaspora::sendUnshare($user, $contact);
256 * @brief Marks a contact for archival after a communication issue delay
258 * Contact has refused to recognise us as a friend. We will start a countdown.
259 * If they still don't recognise us in 32 days, the relationship is over,
260 * and we won't waste any more time trying to communicate with them.
261 * This provides for the possibility that their database is temporarily messed
262 * up or some other transient event and that there's a possibility we could recover from it.
264 * @param array $contact contact to mark for archival
267 public static function markForArchival(array $contact)
269 // Contact already archived or "self" contact? => nothing to do
270 if ($contact['archive'] || $contact['self']) {
274 if ($contact['term-date'] <= NULL_DATE) {
275 dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
277 if ($contact['url'] != '') {
278 dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
282 * We really should send a notification to the owner after 2-3 weeks
283 * so they won't be surprised when the contact vanishes and can take
284 * remedial action if this was a serious mistake or glitch
287 /// @todo Check for contact vitality via probing
288 $expiry = $contact['term-date'] . ' + 32 days ';
289 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
290 /* Relationship is really truly dead. archive them rather than
291 * delete, though if the owner tries to unarchive them we'll start
292 * the whole process over again.
294 dba::update('contact', ['archive' => 1], ['id' => $contact['id']]);
296 if ($contact['url'] != '') {
297 dba::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
304 * @brief Cancels the archival countdown
306 * @see Contact::markForArchival()
308 * @param array $contact contact to be unmarked for archival
311 public static function unmarkForArchival(array $contact)
313 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
314 $exists = dba::exists('contact', $condition);
316 // We don't need to update, we never marked this contact for archival
321 // It's a miracle. Our dead contact has inexplicably come back to life.
322 $fields = ['term-date' => NULL_DATE, 'archive' => false];
323 dba::update('contact', $fields, ['id' => $contact['id']]);
325 if ($contact['url'] != '') {
326 dba::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
331 * @brief Get contact data for a given profile link
333 * The function looks at several places (contact table and gcontact table) for the contact
334 * It caches its result for the same script execution to prevent duplicate calls
336 * @param string $url The profile link
337 * @param int $uid User id
338 * @param array $default If not data was found take this data as default value
340 * @return array Contact data
342 public static function getDetailsByURL($url, $uid = -1, array $default = [])
354 if (isset($cache[$url][$uid])) {
355 return $cache[$url][$uid];
358 $ssl_url = str_replace('http://', 'https://', $url);
360 // Fetch contact data from the contact table for the given user
361 $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`,
362 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
363 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
364 $r = dba::inArray($s);
366 // Fetch contact data from the contact table for the given user, checking with the alias
367 if (!DBM::is_result($r)) {
368 $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`,
369 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
370 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
371 $r = dba::inArray($s);
374 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
375 if (!DBM::is_result($r)) {
376 $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`,
377 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
378 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
379 $r = dba::inArray($s);
382 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
383 if (!DBM::is_result($r)) {
384 $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`,
385 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
386 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
387 $r = dba::inArray($s);
390 // Fetch the data from the gcontact table
391 if (!DBM::is_result($r)) {
392 $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`,
393 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
394 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
395 $r = dba::inArray($s);
398 if (DBM::is_result($r)) {
399 // If there is more than one entry we filter out the connector networks
401 foreach ($r as $id => $result) {
402 if ($result["network"] == NETWORK_STATUSNET) {
408 $profile = array_shift($r);
410 // "bd" always contains the upcoming birthday of a contact.
411 // "birthday" might contain the birthday including the year of birth.
412 if ($profile["birthday"] > '0001-01-01') {
413 $bd_timestamp = strtotime($profile["birthday"]);
414 $month = date("m", $bd_timestamp);
415 $day = date("d", $bd_timestamp);
417 $current_timestamp = time();
418 $current_year = date("Y", $current_timestamp);
419 $current_month = date("m", $current_timestamp);
420 $current_day = date("d", $current_timestamp);
422 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
423 $current = $current_year . "-" . $current_month . "-" . $current_day;
425 if ($profile["bd"] < $current) {
426 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
429 $profile["bd"] = '0001-01-01';
435 if (($profile["photo"] == "") && isset($default["photo"])) {
436 $profile["photo"] = $default["photo"];
439 if (($profile["name"] == "") && isset($default["name"])) {
440 $profile["name"] = $default["name"];
443 if (($profile["network"] == "") && isset($default["network"])) {
444 $profile["network"] = $default["network"];
447 if (($profile["thumb"] == "") && isset($profile["photo"])) {
448 $profile["thumb"] = $profile["photo"];
451 if (($profile["micro"] == "") && isset($profile["thumb"])) {
452 $profile["micro"] = $profile["thumb"];
455 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
456 && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
458 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
461 // Show contact details of Diaspora contacts only if connected
462 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
463 $profile["location"] = "";
464 $profile["about"] = "";
465 $profile["gender"] = "";
466 $profile["birthday"] = '0001-01-01';
469 $cache[$url][$uid] = $profile;
475 * @brief Get contact data for a given address
477 * The function looks at several places (contact table and gcontact table) for the contact
479 * @param string $addr The profile link
480 * @param int $uid User id
482 * @return array Contact data
484 public static function getDetailsByAddr($addr, $uid = -1)
496 // Fetch contact data from the contact table for the given user
497 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
498 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
499 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
503 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
504 if (!DBM::is_result($r)) {
505 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
506 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
507 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
512 // Fetch the data from the gcontact table
513 if (!DBM::is_result($r)) {
514 $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`,
515 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
516 FROM `gcontact` WHERE `addr` = '%s'",
521 if (!DBM::is_result($r)) {
522 $data = Probe::uri($addr);
524 $profile = self::getDetailsByURL($data['url'], $uid);
533 * @brief Returns the data array for the photo menu of a given contact
535 * @param array $contact contact
536 * @param int $uid optional, default 0
539 public static function photoMenu(array $contact, $uid = 0)
541 // @todo Unused, to be removed
549 $contact_drop_link = '';
556 if ($contact['uid'] != $uid) {
558 $profile_link = Profile::zrl($contact['url']);
559 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
564 // Look for our own contact if the uid doesn't match and isn't public
565 $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
566 if (DBM::is_result($contact_own)) {
567 return self::photoMenu($contact_own, $uid);
569 $profile_link = Profile::zrl($contact['url']);
570 $connlnk = 'follow/?url=' . $contact['url'];
572 'profile' => [L10n::t('View Profile'), $profile_link, true],
573 'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
581 if (($contact['network'] === NETWORK_DFRN) && !$contact['self']) {
583 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
585 $profile_link = $contact['url'];
588 if ($profile_link === 'mailbox') {
593 $status_link = $profile_link . '?url=status';
594 $photos_link = $profile_link . '?url=photos';
595 $profile_link = $profile_link . '?url=profile';
598 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA]) && !$contact['self']) {
599 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
602 if (($contact['network'] == NETWORK_DFRN) && !$contact['self']) {
603 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
606 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
608 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
610 if (!$contact['self']) {
611 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
616 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
619 'status' => [L10n::t("View Status") , $status_link , true],
620 'profile' => [L10n::t("View Profile") , $profile_link , true],
621 'photos' => [L10n::t("View Photos") , $photos_link , true],
622 'network' => [L10n::t("Network Posts"), $posts_link , false],
623 'edit' => [L10n::t("View Contact") , $contact_url , false],
624 'drop' => [L10n::t("Drop Contact") , $contact_drop_link, false],
625 'pm' => [L10n::t("Send PM") , $pm_url , false],
626 'poke' => [L10n::t("Poke") , $poke_link , false],
629 $args = ['contact' => $contact, 'menu' => &$menu];
631 Addon::callHooks('contact_photo_menu', $args);
635 foreach ($menu as $menuname => $menuitem) {
636 if ($menuitem[1] != '') {
637 $menucondensed[$menuname] = $menuitem;
641 return $menucondensed;
645 * @brief Returns ungrouped contact count or list for user
647 * Returns either the total number of ungrouped contacts for the given user
648 * id or a paginated list of ungrouped contacts.
650 * @param int $uid uid
651 * @param int $start optional, default 0
652 * @param int $count optional, default 0
656 public static function getUngroupedList($uid, $start = 0, $count = 0)
660 "SELECT COUNT(*) AS `total`
667 SELECT DISTINCT(`contact-id`)
686 SELECT DISTINCT(`contact-id`)
688 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
689 WHERE `group`.`uid` = %d
702 * @brief Fetch the contact id for a given URL and user
704 * First lookup in the contact table to find a record matching either `url`, `nurl`,
707 * If there's no record and we aren't looking for a public contact, we quit.
708 * If there's one, we check that it isn't time to update the picture else we
709 * directly return the found contact id.
711 * Second, we probe the provided $url whether it's http://server.tld/profile or
712 * nick@server.tld. We quit if we can't get any info back.
714 * Third, we create the contact record if it doesn't exist
716 * Fourth, we update the existing record with the new data (avatar, alias, nick)
717 * if there's any updates
719 * @param string $url Contact URL
720 * @param integer $uid The user id for the contact (0 = public contact)
721 * @param boolean $no_update Don't update the contact
723 * @return integer Contact ID
725 public static function getIdForURL($url, $uid = 0, $no_update = false)
727 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
735 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
736 // We first try the nurl (http://server.tld/nick), most common case
737 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
739 // Then the addr (nick@server.tld)
740 if (!DBM::is_result($contact)) {
741 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
744 // Then the alias (which could be anything)
745 if (!DBM::is_result($contact)) {
746 // The link could be provided as http although we stored it as https
747 $ssl_url = str_replace('http://', 'https://', $url);
748 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
749 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
752 if (DBM::is_result($contact)) {
753 $contact_id = $contact["id"];
755 // Update the contact every 7 days
756 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
758 // We force the update if the avatar is empty
759 if (!x($contact, 'avatar')) {
760 $update_contact = true;
763 if (!$update_contact || $no_update) {
766 } elseif ($uid != 0) {
767 // Non-existing user-specific contact, exiting
771 $data = Probe::uri($url, "", $uid);
773 // Last try in gcontact for unsupported networks
774 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL])) {
779 // Get data from the gcontact table
780 $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
781 if (!DBM::is_result($gcontact)) {
785 $data = array_merge($data, $gcontact);
788 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
789 $contact_id = self::getIdForURL($data["alias"], $uid, true);
794 dba::insert('contact', [
796 'created' => DateTimeFormat::utcNow(),
797 'url' => $data["url"],
798 'nurl' => normalise_link($data["url"]),
799 'addr' => $data["addr"],
800 'alias' => $data["alias"],
801 'notify' => $data["notify"],
802 'poll' => $data["poll"],
803 'name' => $data["name"],
804 'nick' => $data["nick"],
805 'photo' => $data["photo"],
806 'keywords' => $data["keywords"],
807 'location' => $data["location"],
808 'about' => $data["about"],
809 'network' => $data["network"],
810 'pubkey' => $data["pubkey"],
811 'rel' => CONTACT_IS_SHARING,
812 'priority' => $data["priority"],
813 'batch' => $data["batch"],
814 'request' => $data["request"],
815 'confirm' => $data["confirm"],
816 'poco' => $data["poco"],
817 'name-date' => DateTimeFormat::utcNow(),
818 'uri-date' => DateTimeFormat::utcNow(),
819 'avatar-date' => DateTimeFormat::utcNow(),
826 $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
827 $contacts = dba::inArray($s);
828 if (!DBM::is_result($contacts)) {
832 $contact_id = $contacts[0]["id"];
834 // Update the newly created contact from data in the gcontact table
835 $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
836 if (DBM::is_result($gcontact)) {
837 // Only use the information when the probing hadn't fetched these values
838 if ($data['keywords'] != '') {
839 unset($gcontact['keywords']);
841 if ($data['location'] != '') {
842 unset($gcontact['location']);
844 if ($data['about'] != '') {
845 unset($gcontact['about']);
847 dba::update('contact', $gcontact, ['id' => $contact_id]);
850 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
851 dba::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
852 normalise_link($data["url"]), $contact_id]);
856 self::updateAvatar($data["photo"], $uid, $contact_id);
858 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
859 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
861 // This condition should always be true
862 if (!DBM::is_result($contact)) {
866 $updated = ['addr' => $data['addr'],
867 'alias' => $data['alias'],
868 'url' => $data['url'],
869 'nurl' => normalise_link($data['url']),
870 'name' => $data['name'],
871 'nick' => $data['nick']];
873 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
874 if (!empty($contact['pubkey'])) {
875 unset($contact['pubkey']);
877 $updated['pubkey'] = $data['pubkey'];
880 if ($data['keywords'] != '') {
881 $updated['keywords'] = $data['keywords'];
883 if ($data['location'] != '') {
884 $updated['location'] = $data['location'];
886 if ($data['about'] != '') {
887 $updated['about'] = $data['about'];
890 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
891 $updated['uri-date'] = DateTimeFormat::utcNow();
893 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
894 $updated['name-date'] = DateTimeFormat::utcNow();
897 $updated['avatar-date'] = DateTimeFormat::utcNow();
899 dba::update('contact', $updated, ['id' => $contact_id], $contact);
905 * @brief Checks if the contact is blocked
907 * @param int $cid contact id
909 * @return boolean Is the contact blocked?
911 public static function isBlocked($cid)
917 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
918 if (!DBM::is_result($blocked)) {
921 return (bool) $blocked['blocked'];
925 * @brief Checks if the contact is hidden
927 * @param int $cid contact id
929 * @return boolean Is the contact hidden?
931 public static function isHidden($cid)
937 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
938 if (!DBM::is_result($hidden)) {
941 return (bool) $hidden['hidden'];
945 * @brief Returns posts from a given contact url
947 * @param string $contact_url Contact URL
949 * @return string posts in HTML
951 public static function getPostsFromUrl($contact_url)
955 require_once 'include/conversation.php';
957 // There are no posts with "uid = 0" with connector networks
958 // This speeds up the query a lot
959 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
960 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
961 dbesc(normalise_link($contact_url))
964 if (!DBM::is_result($r)) {
968 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
969 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
971 $sql = "`item`.`uid` = %d";
974 $author_id = intval($r[0]["author-id"]);
976 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
978 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
979 " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
980 intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
981 intval($a->pager['start']), intval($a->pager['itemspage'])
984 $o = conversation($a, $r, 'contact-posts', false);
986 $o .= alt_pager($a, count($r));
992 * @brief Returns the account type name
994 * The function can be called with either the user or the contact array
996 * @param array $contact contact or user array
999 public static function getAccountType(array $contact)
1001 // There are several fields that indicate that the contact or user is a forum
1002 // "page-flags" is a field in the user table,
1003 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
1004 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
1005 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
1006 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
1007 || (isset($contact['forum']) && intval($contact['forum']))
1008 || (isset($contact['prv']) && intval($contact['prv']))
1009 || (isset($contact['community']) && intval($contact['community']))
1011 $type = ACCOUNT_TYPE_COMMUNITY;
1013 $type = ACCOUNT_TYPE_PERSON;
1016 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1017 if (isset($contact["contact-type"])) {
1018 $type = $contact["contact-type"];
1021 if (isset($contact["account-type"])) {
1022 $type = $contact["account-type"];
1026 case ACCOUNT_TYPE_ORGANISATION:
1027 $account_type = L10n::t("Organisation");
1029 case ACCOUNT_TYPE_NEWS:
1030 $account_type = L10n::t('News');
1032 case ACCOUNT_TYPE_COMMUNITY:
1033 $account_type = L10n::t("Forum");
1040 return $account_type;
1044 * @brief Blocks a contact
1049 public static function block($uid)
1051 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
1057 * @brief Unblocks a contact
1062 public static function unblock($uid)
1064 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
1070 * @brief Updates the avatar links in a contact only if needed
1072 * @param string $avatar Link to avatar picture
1073 * @param int $uid User id of contact owner
1074 * @param int $cid Contact id
1075 * @param bool $force force picture update
1077 * @return array Returns array of the different avatar sizes
1079 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1081 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1082 if (!DBM::is_result($contact)) {
1085 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1088 if (($contact["avatar"] != $avatar) || $force) {
1089 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1094 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1098 // Update the public contact (contact id = 0)
1100 $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1101 if (DBM::is_result($pcontact)) {
1102 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1114 * @param integer $id contact id
1117 public static function updateFromProbe($id)
1120 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1121 This will reliably kill your communication with Friendica contacts.
1124 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1125 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1126 if (!DBM::is_result($contact)) {
1130 $ret = Probe::uri($contact["url"]);
1132 // If Probe::uri fails the network code will be different
1133 if ($ret["network"] != $contact["network"]) {
1139 // make sure to not overwrite existing values with blank entries
1140 foreach ($ret as $key => $val) {
1141 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1142 $ret[$key] = $contact[$key];
1145 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1156 'url' => $ret['url'],
1157 'nurl' => normalise_link($ret['url']),
1158 'addr' => $ret['addr'],
1159 'alias' => $ret['alias'],
1160 'batch' => $ret['batch'],
1161 'notify' => $ret['notify'],
1162 'poll' => $ret['poll'],
1163 'poco' => $ret['poco']
1168 // Update the corresponding gcontact entry
1169 PortableContact::lastUpdated($ret["url"]);
1175 * Takes a $uid and a url/handle and adds a new contact
1176 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1177 * dfrn_request page.
1179 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1182 * $return['success'] boolean true if successful
1183 * $return['message'] error text if success is false.
1185 * @brief Takes a $uid and a url/handle and adds a new contact
1187 * @param string $url
1188 * @param bool $interactive
1189 * @param string $network
1190 * @return boolean|string
1192 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1194 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1198 // remove ajax junk, e.g. Twitter
1199 $url = str_replace('/#!/', '/', $url);
1201 if (!Network::isUrlAllowed($url)) {
1202 $result['message'] = L10n::t('Disallowed profile URL.');
1206 if (Network::isUrlBlocked($url)) {
1207 $result['message'] = L10n::t('Blocked domain');
1212 $result['message'] = L10n::t('Connect URL missing.');
1216 $arr = ['url' => $url, 'contact' => []];
1218 Addon::callHooks('follow', $arr);
1221 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1225 if (x($arr['contact'], 'name')) {
1226 $ret = $arr['contact'];
1228 $ret = Probe::uri($url, $network, $uid, false);
1231 if (($network != '') && ($ret['network'] != $network)) {
1232 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1236 // check if we already have a contact
1237 // the poll url is more reliable than the profile url, as we may have
1238 // indirect links or webfinger links
1240 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1",
1242 dbesc($ret['poll']),
1243 dbesc(normalise_link($ret['poll'])),
1244 dbesc($ret['network'])
1247 if (!DBM::is_result($r)) {
1248 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
1250 dbesc(normalise_link($url)),
1251 dbesc($ret['network'])
1255 if (($ret['network'] === NETWORK_DFRN) && !DBM::is_result($r)) {
1257 if (strlen($a->path)) {
1258 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1260 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1263 goaway($ret['request'] . "&addr=$myaddr");
1267 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != NETWORK_DFRN)) {
1268 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1269 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1273 // This extra param just confuses things, remove it
1274 if ($ret['network'] === NETWORK_DIASPORA) {
1275 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1278 // do we have enough information?
1280 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1281 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1282 if (!x($ret, 'poll')) {
1283 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1285 if (!x($ret, 'name')) {
1286 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1288 if (!x($ret, 'url')) {
1289 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1291 if (strpos($url, '@') !== false) {
1292 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1293 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1298 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1299 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1300 $ret['notify'] = '';
1303 if (!$ret['notify']) {
1304 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1307 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1309 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1311 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1313 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1317 if (DBM::is_result($r)) {
1319 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1321 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1322 dba::update('contact', $fields, ['id' => $r[0]['id']]);
1324 $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1326 // create contact record
1327 dba::insert('contact', [
1329 'created' => DateTimeFormat::utcNow(),
1330 'url' => $ret['url'],
1331 'nurl' => normalise_link($ret['url']),
1332 'addr' => $ret['addr'],
1333 'alias' => $ret['alias'],
1334 'batch' => $ret['batch'],
1335 'notify' => $ret['notify'],
1336 'poll' => $ret['poll'],
1337 'poco' => $ret['poco'],
1338 'name' => $ret['name'],
1339 'nick' => $ret['nick'],
1340 'network' => $ret['network'],
1341 'pubkey' => $ret['pubkey'],
1342 'rel' => $new_relation,
1343 'priority'=> $ret['priority'],
1344 'writable'=> $writeable,
1345 'hidden' => $hidden,
1353 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1354 if (!DBM::is_result($contact)) {
1355 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1359 $contact_id = $contact['id'];
1360 $result['cid'] = $contact_id;
1362 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1364 // Update the avatar
1365 self::updateAvatar($ret['photo'], $uid, $contact_id);
1367 // pull feed and consume it, which should subscribe to the hub.
1369 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1371 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1372 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1376 if (DBM::is_result($r)) {
1377 if (in_array($contact['network'], [NETWORK_OSTATUS, NETWORK_DFRN])) {
1378 // create a follow slap
1380 $item['verb'] = ACTIVITY_FOLLOW;
1381 $item['follow'] = $contact["url"];
1382 $slap = OStatus::salmon($item, $r[0]);
1383 if (!empty($contact['notify'])) {
1384 Salmon::slapper($r[0], $contact['notify'], $slap);
1386 } elseif ($contact['network'] == NETWORK_DIASPORA) {
1387 $ret = Diaspora::sendShare($a->user, $contact);
1388 logger('share returns: ' . $ret);
1392 $result['success'] = true;
1396 public static function updateSslPolicy($contact, $new_policy)
1398 $ssl_changed = false;
1399 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1400 $ssl_changed = true;
1401 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1402 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1403 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1404 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1405 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1406 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1409 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1410 $ssl_changed = true;
1411 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1412 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1413 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1414 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1415 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1416 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1420 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1421 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1422 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1423 dba::update('contact', $fields, ['id' => $contact['id']]);
1429 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1430 $url = notags(trim($datarray['author-link']));
1431 $name = notags(trim($datarray['author-name']));
1432 $photo = notags(trim($datarray['author-avatar']));
1435 if (is_object($item)) {
1436 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1437 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1438 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1444 if (is_array($contact)) {
1445 if (($contact['rel'] == CONTACT_IS_SHARING)
1446 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1447 dba::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1448 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1450 // send email notification to owner?
1452 // create contact record
1453 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1454 `blocked`, `readonly`, `pending`, `writable`)
1455 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1456 intval($importer['uid']),
1457 dbesc(DateTimeFormat::utcNow()),
1459 dbesc(normalise_link($url)),
1463 dbesc(NETWORK_OSTATUS),
1464 intval(CONTACT_IS_FOLLOWER)
1468 'id' => dba::lastInsertId(),
1469 'network' => NETWORK_OSTATUS
1471 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1473 /// @TODO Encapsulate this into a function/method
1474 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1475 $user = dba::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1476 if (DBM::is_result($user) && !in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1477 // create notification
1478 $hash = random_string();
1480 if (is_array($contact_record)) {
1481 dba::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1482 'blocked' => false, 'knowyou' => false,
1483 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1486 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1488 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1489 in_array($user['page-flags'], [PAGE_NORMAL])) {
1492 'type' => NOTIFY_INTRO,
1493 'notify_flags' => $user['notify-flags'],
1494 'language' => $user['language'],
1495 'to_name' => $user['username'],
1496 'to_email' => $user['email'],
1497 'uid' => $user['uid'],
1498 'link' => System::baseUrl() . '/notifications/intro',
1499 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1500 'source_link' => $contact_record['url'],
1501 'source_photo' => $contact_record['photo'],
1502 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1507 } elseif (DBM::is_result($user) && in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1508 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1509 intval($importer['uid']),
1516 public static function removeFollower($importer, $contact, array $datarray = [], $item = "") {
1518 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1519 dba::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1521 Contact::remove($contact['id']);
1525 public static function removeSharer($importer, $contact, array $datarray = [], $item = "") {
1527 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1528 dba::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1530 Contact::remove($contact['id']);
1535 * @brief Create a birthday event.
1537 * Update the year and the birthday.
1539 public static function updateBirthdays()
1541 // This only handles foreign or alien networks where a birthday has been provided.
1542 // In-network birthdays are handled within local_delivery
1544 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1545 if (DBM::is_result($r)) {
1546 foreach ($r as $rr) {
1547 logger('update_contact_birthday: ' . $rr['bd']);
1549 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1552 * Add new birthday event for this person
1554 * $bdtext is just a readable placeholder in case the event is shared
1555 * with others. We will replace it during presentation to our $importer
1556 * to contain a sparkle link and perhaps a photo.
1559 // Check for duplicates
1560 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1561 intval($rr['uid']), intval($rr['id']), dbesc(DateTimeFormat::utc($nextbd)), dbesc('birthday'));
1563 if (DBM::is_result($s)) {
1567 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1568 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1570 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1571 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1572 dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utc($nextbd)),
1573 dbesc(DateTimeFormat::utc($nextbd . ' + 1 day ')), dbesc($bdtext), dbesc($bdtext2), dbesc('birthday'),
1579 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(substr($nextbd, 0, 4)),
1580 dbesc($nextbd), intval($rr['uid']), intval($rr['id'])
1587 * Remove the unavailable contact ids from the provided list
1589 * @param array $contact_ids Contact id list
1591 public static function pruneUnavailable(array &$contact_ids)
1593 if (empty($contact_ids)) {
1597 $str = dbesc(implode(',', $contact_ids));
1599 $stmt = dba::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1602 while($contact = dba::fetch($stmt)) {
1603 $return[] = $contact['id'];
1608 $contact_ids = $return;