]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
[Scrutinizer] Fix undeclared variables in src/ (except Protocol/)
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @file src/Model/Contact.php
4  */
5 namespace Friendica\Model;
6
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 dba;
26
27 require_once 'boot.php';
28 require_once 'include/dba.php';
29 require_once 'include/text.php';
30
31 /**
32  * @brief functions for interacting with a contact
33  */
34 class Contact extends BaseObject
35 {
36         /**
37          * @brief Returns a list of contacts belonging in a group
38          *
39          * @param int $gid
40          * @return array
41          */
42         public static function getByGroupId($gid)
43         {
44                 $return = [];
45                 if (intval($gid)) {
46                         $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
47                                 FROM `contact`
48                                 INNER JOIN `group_member`
49                                         ON `contact`.`id` = `group_member`.`contact-id`
50                                 WHERE `gid` = ?
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',
56                                 $gid,
57                                 local_user()
58                         );
59                         if (DBM::is_result($stmt)) {
60                                 $return = dba::inArray($stmt);
61                         }
62                 }
63
64                 return $return;
65         }
66
67         /**
68          * @brief Returns the count of OStatus contacts in a group
69          *
70          * @param int $gid
71          * @return int
72          */
73         public static function getOStatusCountByGroupId($gid)
74         {
75                 $return = 0;
76                 if (intval($gid)) {
77                         $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
78                                 FROM `contact`
79                                 INNER JOIN `group_member`
80                                         ON `contact`.`id` = `group_member`.`contact-id`
81                                 WHERE `gid` = ?
82                                 AND `contact`.`uid` = ?
83                                 AND `contact`.`network` = ?
84                                 AND `contact`.`notify` != ""',
85                                 $gid,
86                                 local_user(),
87                                 NETWORK_OSTATUS
88                         );
89                         $return = $contacts['count'];
90                 }
91
92                 return $return;
93         }
94
95         /**
96          * Creates the self-contact for the provided user id
97          *
98          * @param int $uid
99          * @return bool Operation success
100          */
101         public static function createSelfFromUserId($uid)
102         {
103                 // Only create the entry if it doesn't exist yet
104                 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
105                         return true;
106                 }
107
108                 $user = dba::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
109                 if (!DBM::is_result($user)) {
110                         return false;
111                 }
112
113                 $return = dba::insert('contact', [
114                         'uid'         => $user['uid'],
115                         'created'     => DateTimeFormat::utcNow(),
116                         'self'        => 1,
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',
122                         'blocked'     => 0,
123                         'pending'     => 0,
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(),
135                         'closeness'   => 0
136                 ]);
137
138                 return $return;
139         }
140
141         /**
142          * @brief Marks a contact for removal
143          *
144          * @param int $id contact id
145          * @return null
146          */
147         public static function remove($id)
148         {
149                 // We want just to make sure that we don't delete our "self" contact
150                 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
151                 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
152                         return;
153                 }
154
155                 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
156                 if ($archive) {
157                         dba::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
158                         return;
159                 }
160
161                 dba::delete('contact', ['id' => $id]);
162
163                 // Delete the rest in the background
164                 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
165         }
166
167         /**
168          * @brief Sends an unfriend message. Does not remove the contact
169          *
170          * @param array $user    User unfriending
171          * @param array $contact Contact unfriended
172          * @return void
173          */
174         public static function terminateFriendship(array $user, array $contact)
175         {
176                 if ($contact['network'] === NETWORK_OSTATUS) {
177                         // create an unfollow slap
178                         $item = [];
179                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
180                         $item['follow'] = $contact["url"];
181                         $slap = OStatus::salmon($item, $user);
182
183                         if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
184                                 Salmon::slapper($user, $contact['notify'], $slap);
185                         }
186                 } elseif ($contact['network'] === NETWORK_DIASPORA) {
187                         Diaspora::sendUnshare($user, $contact);
188                 } elseif ($contact['network'] === NETWORK_DFRN) {
189                         DFRN::deliver($user, $contact, 'placeholder', 1);
190                 }
191         }
192
193         /**
194          * @brief Marks a contact for archival after a communication issue delay
195          *
196          * Contact has refused to recognise us as a friend. We will start a countdown.
197          * If they still don't recognise us in 32 days, the relationship is over,
198          * and we won't waste any more time trying to communicate with them.
199          * This provides for the possibility that their database is temporarily messed
200          * up or some other transient event and that there's a possibility we could recover from it.
201          *
202          * @param array $contact contact to mark for archival
203          * @return null
204          */
205         public static function markForArchival(array $contact)
206         {
207                 // Contact already archived or "self" contact? => nothing to do
208                 if ($contact['archive'] || $contact['self']) {
209                         return;
210                 }
211
212                 if ($contact['term-date'] <= NULL_DATE) {
213                         dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
214
215                         if ($contact['url'] != '') {
216                                 dba::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
217                         }
218                 } else {
219                         /* @todo
220                          * We really should send a notification to the owner after 2-3 weeks
221                          * so they won't be surprised when the contact vanishes and can take
222                          * remedial action if this was a serious mistake or glitch
223                          */
224
225                         /// @todo Check for contact vitality via probing
226                         $expiry = $contact['term-date'] . ' + 32 days ';
227                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
228                                 /* Relationship is really truly dead. archive them rather than
229                                  * delete, though if the owner tries to unarchive them we'll start
230                                  * the whole process over again.
231                                  */
232                                 dba::update('contact', ['archive' => 1], ['id' => $contact['id']]);
233
234                                 if ($contact['url'] != '') {
235                                         dba::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
236                                 }
237                         }
238                 }
239         }
240
241         /**
242          * @brief Cancels the archival countdown
243          *
244          * @see Contact::markForArchival()
245          *
246          * @param array $contact contact to be unmarked for archival
247          * @return null
248          */
249         public static function unmarkForArchival(array $contact)
250         {
251                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
252                 $exists = dba::exists('contact', $condition);
253
254                 // We don't need to update, we never marked this contact for archival
255                 if (!$exists) {
256                         return;
257                 }
258
259                 // It's a miracle. Our dead contact has inexplicably come back to life.
260                 $fields = ['term-date' => NULL_DATE, 'archive' => false];
261                 dba::update('contact', $fields, ['id' => $contact['id']]);
262
263                 if ($contact['url'] != '') {
264                         dba::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
265                 }
266         }
267
268         /**
269          * @brief Get contact data for a given profile link
270          *
271          * The function looks at several places (contact table and gcontact table) for the contact
272          * It caches its result for the same script execution to prevent duplicate calls
273          *
274          * @param string $url     The profile link
275          * @param int    $uid     User id
276          * @param array  $default If not data was found take this data as default value
277          *
278          * @return array Contact data
279          */
280         public static function getDetailsByURL($url, $uid = -1, array $default = [])
281         {
282                 static $cache = [];
283
284                 if ($url == '') {
285                         return $default;
286                 }
287
288                 if ($uid == -1) {
289                         $uid = local_user();
290                 }
291
292                 if (isset($cache[$url][$uid])) {
293                         return $cache[$url][$uid];
294                 }
295
296                 $ssl_url = str_replace('http://', 'https://', $url);
297
298                 // Fetch contact data from the contact table for the given user
299                 $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`,
300                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
301                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
302                 $r = dba::inArray($s);
303
304                 // Fetch contact data from the contact table for the given user, checking with the alias
305                 if (!DBM::is_result($r)) {
306                         $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`,
307                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
308                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
309                         $r = dba::inArray($s);
310                 }
311
312                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
313                 if (!DBM::is_result($r)) {
314                         $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`,
315                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
316                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
317                         $r = dba::inArray($s);
318                 }
319
320                 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
321                 if (!DBM::is_result($r)) {
322                         $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`,
323                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
324                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
325                         $r = dba::inArray($s);
326                 }
327
328                 // Fetch the data from the gcontact table
329                 if (!DBM::is_result($r)) {
330                         $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`,
331                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
332                         FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
333                         $r = dba::inArray($s);
334                 }
335
336                 if (DBM::is_result($r)) {
337                         // If there is more than one entry we filter out the connector networks
338                         if (count($r) > 1) {
339                                 foreach ($r as $id => $result) {
340                                         if ($result["network"] == NETWORK_STATUSNET) {
341                                                 unset($r[$id]);
342                                         }
343                                 }
344                         }
345
346                         $profile = array_shift($r);
347
348                         // "bd" always contains the upcoming birthday of a contact.
349                         // "birthday" might contain the birthday including the year of birth.
350                         if ($profile["birthday"] > '0001-01-01') {
351                                 $bd_timestamp = strtotime($profile["birthday"]);
352                                 $month = date("m", $bd_timestamp);
353                                 $day = date("d", $bd_timestamp);
354
355                                 $current_timestamp = time();
356                                 $current_year = date("Y", $current_timestamp);
357                                 $current_month = date("m", $current_timestamp);
358                                 $current_day = date("d", $current_timestamp);
359
360                                 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
361                                 $current = $current_year . "-" . $current_month . "-" . $current_day;
362
363                                 if ($profile["bd"] < $current) {
364                                         $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
365                                 }
366                         } else {
367                                 $profile["bd"] = '0001-01-01';
368                         }
369                 } else {
370                         $profile = $default;
371                 }
372
373                 if (($profile["photo"] == "") && isset($default["photo"])) {
374                         $profile["photo"] = $default["photo"];
375                 }
376
377                 if (($profile["name"] == "") && isset($default["name"])) {
378                         $profile["name"] = $default["name"];
379                 }
380
381                 if (($profile["network"] == "") && isset($default["network"])) {
382                         $profile["network"] = $default["network"];
383                 }
384
385                 if (($profile["thumb"] == "") && isset($profile["photo"])) {
386                         $profile["thumb"] = $profile["photo"];
387                 }
388
389                 if (($profile["micro"] == "") && isset($profile["thumb"])) {
390                         $profile["micro"] = $profile["thumb"];
391                 }
392
393                 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
394                         && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
395                 ) {
396                         Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
397                 }
398
399                 // Show contact details of Diaspora contacts only if connected
400                 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
401                         $profile["location"] = "";
402                         $profile["about"] = "";
403                         $profile["gender"] = "";
404                         $profile["birthday"] = '0001-01-01';
405                 }
406
407                 $cache[$url][$uid] = $profile;
408
409                 return $profile;
410         }
411
412         /**
413          * @brief Get contact data for a given address
414          *
415          * The function looks at several places (contact table and gcontact table) for the contact
416          *
417          * @param string $addr The profile link
418          * @param int    $uid  User id
419          *
420          * @return array Contact data
421          */
422         public static function getDetailsByAddr($addr, $uid = -1)
423         {
424                 static $cache = [];
425
426                 if ($addr == '') {
427                         return [];
428                 }
429
430                 if ($uid == -1) {
431                         $uid = local_user();
432                 }
433
434                 // Fetch contact data from the contact table for the given user
435                 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
436                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
437                         FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
438                         dbesc($addr),
439                         intval($uid)
440                 );
441                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
442                 if (!DBM::is_result($r)) {
443                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
444                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
445                                 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
446                                 dbesc($addr)
447                         );
448                 }
449
450                 // Fetch the data from the gcontact table
451                 if (!DBM::is_result($r)) {
452                         $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`,
453                                 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
454                                 FROM `gcontact` WHERE `addr` = '%s'",
455                                 dbesc($addr)
456                         );
457                 }
458
459                 if (!DBM::is_result($r)) {
460                         $data = Probe::uri($addr);
461
462                         $profile = self::getDetailsByURL($data['url'], $uid);
463                 } else {
464                         $profile = $r[0];
465                 }
466
467                 return $profile;
468         }
469
470         /**
471          * @brief Returns the data array for the photo menu of a given contact
472          *
473          * @param array $contact contact
474          * @param int   $uid     optional, default 0
475          * @return array
476          */
477         public static function photoMenu(array $contact, $uid = 0)
478         {
479                 // @todo Unused, to be removed
480                 $a = get_app();
481
482                 $contact_url = '';
483                 $pm_url = '';
484                 $status_link = '';
485                 $photos_link = '';
486                 $posts_link = '';
487                 $contact_drop_link = '';
488                 $poke_link = '';
489
490                 if ($uid == 0) {
491                         $uid = local_user();
492                 }
493
494                 if ($contact['uid'] != $uid) {
495                         if ($uid == 0) {
496                                 $profile_link = Profile::zrl($contact['url']);
497                                 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
498
499                                 return $menu;
500                         }
501
502                         // Look for our own contact if the uid doesn't match and isn't public
503                         $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
504                         if (DBM::is_result($contact_own)) {
505                                 return self::photoMenu($contact_own, $uid);
506                         } else {
507                                 $profile_link = Profile::zrl($contact['url']);
508                                 $connlnk = 'follow/?url=' . $contact['url'];
509                                 $menu = [
510                                         'profile' => [L10n::t('View Profile'), $profile_link, true],
511                                         'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
512                                 ];
513
514                                 return $menu;
515                         }
516                 }
517
518                 $sparkle = false;
519                 if ($contact['network'] === NETWORK_DFRN) {
520                         $sparkle = true;
521                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
522                 } else {
523                         $profile_link = $contact['url'];
524                 }
525
526                 if ($profile_link === 'mailbox') {
527                         $profile_link = '';
528                 }
529
530                 if ($sparkle) {
531                         $status_link = $profile_link . '?url=status';
532                         $photos_link = $profile_link . '?url=photos';
533                         $profile_link = $profile_link . '?url=profile';
534                 }
535
536                 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
537                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
538                 }
539
540                 if ($contact['network'] == NETWORK_DFRN) {
541                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
542                 }
543
544                 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
545
546                 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
547                 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
548
549                 /**
550                  * Menu array:
551                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
552                  */
553                 $menu = [
554                         'status'  => [L10n::t("View Status")  , $status_link      , true],
555                         'profile' => [L10n::t("View Profile") , $profile_link     , true],
556                         'photos'  => [L10n::t("View Photos")  , $photos_link      , true],
557                         'network' => [L10n::t("Network Posts"), $posts_link       , false],
558                         'edit'    => [L10n::t("View Contact") , $contact_url      , false],
559                         'drop'    => [L10n::t("Drop Contact") , $contact_drop_link, false],
560                         'pm'      => [L10n::t("Send PM")      , $pm_url           , false],
561                         'poke'    => [L10n::t("Poke")         , $poke_link        , false],
562                 ];
563
564                 $args = ['contact' => $contact, 'menu' => &$menu];
565
566                 Addon::callHooks('contact_photo_menu', $args);
567
568                 $menucondensed = [];
569
570                 foreach ($menu as $menuname => $menuitem) {
571                         if ($menuitem[1] != '') {
572                                 $menucondensed[$menuname] = $menuitem;
573                         }
574                 }
575
576                 return $menucondensed;
577         }
578
579         /**
580          * @brief Returns ungrouped contact count or list for user
581          *
582          * Returns either the total number of ungrouped contacts for the given user
583          * id or a paginated list of ungrouped contacts.
584          *
585          * @param int $uid   uid
586          * @param int $start optional, default 0
587          * @param int $count optional, default 0
588          *
589          * @return array
590          */
591         public static function getUngroupedList($uid, $start = 0, $count = 0)
592         {
593                 if (!$count) {
594                         $r = q(
595                                 "SELECT COUNT(*) AS `total`
596                                  FROM `contact`
597                                  WHERE `uid` = %d
598                                  AND NOT `self`
599                                  AND NOT `blocked`
600                                  AND NOT `pending`
601                                  AND `id` NOT IN (
602                                         SELECT DISTINCT(`contact-id`)
603                                         FROM `group_member`
604                                         WHERE `uid` = %d
605                                 )",
606                                 intval($uid),
607                                 intval($uid)
608                         );
609
610                         return $r;
611                 }
612
613                 $r = q(
614                         "SELECT *
615                         FROM `contact`
616                         WHERE `uid` = %d
617                         AND NOT `self`
618                         AND NOT `blocked`
619                         AND NOT `pending`
620                         AND `id` NOT IN (
621                                 SELECT DISTINCT(`contact-id`)
622                                 FROM `group_member`
623                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
624                                 WHERE `group`.`uid` = %d
625                         )
626                         LIMIT %d, %d",
627                         intval($uid),
628                         intval($uid),
629                         intval($start),
630                         intval($count)
631                 );
632
633                 return $r;
634         }
635
636         /**
637          * @brief Fetch the contact id for a given URL and user
638          *
639          * First lookup in the contact table to find a record matching either `url`, `nurl`,
640          * `addr` or `alias`.
641          *
642          * If there's no record and we aren't looking for a public contact, we quit.
643          * If there's one, we check that it isn't time to update the picture else we
644          * directly return the found contact id.
645          *
646          * Second, we probe the provided $url whether it's http://server.tld/profile or
647          * nick@server.tld. We quit if we can't get any info back.
648          *
649          * Third, we create the contact record if it doesn't exist
650          *
651          * Fourth, we update the existing record with the new data (avatar, alias, nick)
652          * if there's any updates
653          *
654          * @param string  $url       Contact URL
655          * @param integer $uid       The user id for the contact (0 = public contact)
656          * @param boolean $no_update Don't update the contact
657          *
658          * @return integer Contact ID
659          */
660         public static function getIdForURL($url, $uid = 0, $no_update = false)
661         {
662                 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
663
664                 $contact_id = 0;
665
666                 if ($url == '') {
667                         return 0;
668                 }
669
670                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
671                 // We first try the nurl (http://server.tld/nick), most common case
672                 $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
673
674                 // Then the addr (nick@server.tld)
675                 if (!DBM::is_result($contact)) {
676                         $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
677                 }
678
679                 // Then the alias (which could be anything)
680                 if (!DBM::is_result($contact)) {
681                         // The link could be provided as http although we stored it as https
682                         $ssl_url = str_replace('http://', 'https://', $url);
683                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
684                         $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
685                 }
686
687                 if (DBM::is_result($contact)) {
688                         $contact_id = $contact["id"];
689
690                         // Update the contact every 7 days
691                         $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
692
693                         // We force the update if the avatar is empty
694                         if (!x($contact, 'avatar')) {
695                                 $update_contact = true;
696                         }
697
698                         if (!$update_contact || $no_update) {
699                                 return $contact_id;
700                         }
701                 } elseif ($uid != 0) {
702                         // Non-existing user-specific contact, exiting
703                         return 0;
704                 }
705
706                 $data = Probe::uri($url, "", $uid);
707
708                 // Last try in gcontact for unsupported networks
709                 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL])) {
710                         if ($uid != 0) {
711                                 return 0;
712                         }
713
714                         // Get data from the gcontact table
715                         $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
716                         if (!DBM::is_result($gcontact)) {
717                                 return 0;
718                         }
719
720                         $data = array_merge($data, $gcontact);
721                 }
722
723                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
724                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
725                 }
726
727                 $url = $data["url"];
728                 if (!$contact_id) {
729                         dba::insert('contact', [
730                                 'uid'       => $uid,
731                                 'created'   => DateTimeFormat::utcNow(),
732                                 'url'       => $data["url"],
733                                 'nurl'      => normalise_link($data["url"]),
734                                 'addr'      => $data["addr"],
735                                 'alias'     => $data["alias"],
736                                 'notify'    => $data["notify"],
737                                 'poll'      => $data["poll"],
738                                 'name'      => $data["name"],
739                                 'nick'      => $data["nick"],
740                                 'photo'     => $data["photo"],
741                                 'keywords'  => $data["keywords"],
742                                 'location'  => $data["location"],
743                                 'about'     => $data["about"],
744                                 'network'   => $data["network"],
745                                 'pubkey'    => $data["pubkey"],
746                                 'rel'       => CONTACT_IS_SHARING,
747                                 'priority'  => $data["priority"],
748                                 'batch'     => $data["batch"],
749                                 'request'   => $data["request"],
750                                 'confirm'   => $data["confirm"],
751                                 'poco'      => $data["poco"],
752                                 'name-date' => DateTimeFormat::utcNow(),
753                                 'uri-date'  => DateTimeFormat::utcNow(),
754                                 'avatar-date' => DateTimeFormat::utcNow(),
755                                 'writable'  => 1,
756                                 'blocked'   => 0,
757                                 'readonly'  => 0,
758                                 'pending'   => 0]
759                         );
760
761                         $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
762                         $contacts = dba::inArray($s);
763                         if (!DBM::is_result($contacts)) {
764                                 return 0;
765                         }
766
767                         $contact_id = $contacts[0]["id"];
768
769                         // Update the newly created contact from data in the gcontact table
770                         $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
771                         if (DBM::is_result($gcontact)) {
772                                 // Only use the information when the probing hadn't fetched these values
773                                 if ($data['keywords'] != '') {
774                                         unset($gcontact['keywords']);
775                                 }
776                                 if ($data['location'] != '') {
777                                         unset($gcontact['location']);
778                                 }
779                                 if ($data['about'] != '') {
780                                         unset($gcontact['about']);
781                                 }
782                                 dba::update('contact', $gcontact, ['id' => $contact_id]);
783                         }
784
785                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
786                                 dba::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
787                                         normalise_link($data["url"]), $contact_id]);
788                         }
789                 }
790
791                 self::updateAvatar($data["photo"], $uid, $contact_id);
792
793                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
794                 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
795
796                 // This condition should always be true
797                 if (!DBM::is_result($contact)) {
798                         return $contact_id;
799                 }
800
801                 $updated = ['addr' => $data['addr'],
802                         'alias' => $data['alias'],
803                         'url' => $data['url'],
804                         'nurl' => normalise_link($data['url']),
805                         'name' => $data['name'],
806                         'nick' => $data['nick']];
807
808                 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
809                 if (!empty($contact['pubkey'])) {
810                         unset($contact['pubkey']);
811                 } else {
812                         $updated['pubkey'] = $data['pubkey'];
813                 }
814
815                 if ($data['keywords'] != '') {
816                         $updated['keywords'] = $data['keywords'];
817                 }
818                 if ($data['location'] != '') {
819                         $updated['location'] = $data['location'];
820                 }
821                 if ($data['about'] != '') {
822                         $updated['about'] = $data['about'];
823                 }
824
825                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
826                         $updated['uri-date'] = DateTimeFormat::utcNow();
827                 }
828                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
829                         $updated['name-date'] = DateTimeFormat::utcNow();
830                 }
831
832                 $updated['avatar-date'] = DateTimeFormat::utcNow();
833
834                 dba::update('contact', $updated, ['id' => $contact_id], $contact);
835
836                 return $contact_id;
837         }
838
839         /**
840          * @brief Checks if the contact is blocked
841          *
842          * @param int $cid contact id
843          *
844          * @return boolean Is the contact blocked?
845          */
846         public static function isBlocked($cid)
847         {
848                 if ($cid == 0) {
849                         return false;
850                 }
851
852                 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
853                 if (!DBM::is_result($blocked)) {
854                         return false;
855                 }
856                 return (bool) $blocked['blocked'];
857         }
858
859         /**
860          * @brief Checks if the contact is hidden
861          *
862          * @param int $cid contact id
863          *
864          * @return boolean Is the contact hidden?
865          */
866         public static function isHidden($cid)
867         {
868                 if ($cid == 0) {
869                         return false;
870                 }
871
872                 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
873                 if (!DBM::is_result($hidden)) {
874                         return false;
875                 }
876                 return (bool) $hidden['hidden'];
877         }
878
879         /**
880          * @brief Returns posts from a given contact url
881          *
882          * @param string $contact_url Contact URL
883          *
884          * @return string posts in HTML
885          */
886         public static function getPostsFromUrl($contact_url)
887         {
888                 $a = self::getApp();
889
890                 require_once 'include/conversation.php';
891
892                 // There are no posts with "uid = 0" with connector networks
893                 // This speeds up the query a lot
894                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
895                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
896                         dbesc(normalise_link($contact_url))
897                 );
898
899                 if (!DBM::is_result($r)) {
900                         return '';
901                 }
902
903                 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
904                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
905                 } else {
906                         $sql = "`item`.`uid` = %d";
907                 }
908
909                 $author_id = intval($r[0]["author-id"]);
910
911                 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
912
913                 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
914                         " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
915                         intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
916                         intval($a->pager['start']), intval($a->pager['itemspage'])
917                 );
918
919                 $o = conversation($a, $r, 'contact-posts', false);
920
921                 $o .= alt_pager($a, count($r));
922
923                 return $o;
924         }
925
926         /**
927          * @brief Returns the account type name
928          *
929          * The function can be called with either the user or the contact array
930          *
931          * @param array $contact contact or user array
932          * @return string
933          */
934         public static function getAccountType(array $contact)
935         {
936                 // There are several fields that indicate that the contact or user is a forum
937                 // "page-flags" is a field in the user table,
938                 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
939                 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
940                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
941                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
942                         || (isset($contact['forum']) && intval($contact['forum']))
943                         || (isset($contact['prv']) && intval($contact['prv']))
944                         || (isset($contact['community']) && intval($contact['community']))
945                 ) {
946                         $type = ACCOUNT_TYPE_COMMUNITY;
947                 } else {
948                         $type = ACCOUNT_TYPE_PERSON;
949                 }
950
951                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
952                 if (isset($contact["contact-type"])) {
953                         $type = $contact["contact-type"];
954                 }
955
956                 if (isset($contact["account-type"])) {
957                         $type = $contact["account-type"];
958                 }
959
960                 switch ($type) {
961                         case ACCOUNT_TYPE_ORGANISATION:
962                                 $account_type = L10n::t("Organisation");
963                                 break;
964                         case ACCOUNT_TYPE_NEWS:
965                                 $account_type = L10n::t('News');
966                                 break;
967                         case ACCOUNT_TYPE_COMMUNITY:
968                                 $account_type = L10n::t("Forum");
969                                 break;
970                         default:
971                                 $account_type = "";
972                                 break;
973                 }
974
975                 return $account_type;
976         }
977
978         /**
979          * @brief Blocks a contact
980          *
981          * @param int $uid
982          * @return bool
983          */
984         public static function block($uid)
985         {
986                 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
987
988                 return $return;
989         }
990
991         /**
992          * @brief Unblocks a contact
993          *
994          * @param int $uid
995          * @return bool
996          */
997         public static function unblock($uid)
998         {
999                 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
1000
1001                 return $return;
1002         }
1003
1004         /**
1005          * @brief Updates the avatar links in a contact only if needed
1006          *
1007          * @param string $avatar Link to avatar picture
1008          * @param int    $uid    User id of contact owner
1009          * @param int    $cid    Contact id
1010          * @param bool   $force  force picture update
1011          *
1012          * @return array Returns array of the different avatar sizes
1013          */
1014         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1015         {
1016                 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1017                 if (!DBM::is_result($contact)) {
1018                         return false;
1019                 } else {
1020                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1021                 }
1022
1023                 if (($contact["avatar"] != $avatar) || $force) {
1024                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1025
1026                         if ($photos) {
1027                                 dba::update(
1028                                         'contact',
1029                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1030                                         ['id' => $cid]
1031                                 );
1032
1033                                 // Update the public contact (contact id = 0)
1034                                 if ($uid != 0) {
1035                                         $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl']]);
1036                                         if (DBM::is_result($pcontact)) {
1037                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1038                                         }
1039                                 }
1040
1041                                 return $photos;
1042                         }
1043                 }
1044
1045                 return $data;
1046         }
1047
1048         /**
1049          * @param integer $id contact id
1050          * @return boolean
1051          */
1052         public static function updateFromProbe($id)
1053         {
1054                 /*
1055                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1056                   This will reliably kill your communication with Friendica contacts.
1057                  */
1058
1059                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1060                 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1061                 if (!DBM::is_result($contact)) {
1062                         return false;
1063                 }
1064
1065                 $ret = Probe::uri($contact["url"]);
1066
1067                 // If Probe::uri fails the network code will be different
1068                 if ($ret["network"] != $contact["network"]) {
1069                         return false;
1070                 }
1071
1072                 $update = false;
1073
1074                 // make sure to not overwrite existing values with blank entries
1075                 foreach ($ret as $key => $val) {
1076                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1077                                 $ret[$key] = $contact[$key];
1078                         }
1079
1080                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1081                                 $update = true;
1082                         }
1083                 }
1084
1085                 if (!$update) {
1086                         return true;
1087                 }
1088
1089                 dba::update(
1090                         'contact', [
1091                                 'url'    => $ret['url'],
1092                                 'nurl'   => normalise_link($ret['url']),
1093                                 'addr'   => $ret['addr'],
1094                                 'alias'  => $ret['alias'],
1095                                 'batch'  => $ret['batch'],
1096                                 'notify' => $ret['notify'],
1097                                 'poll'   => $ret['poll'],
1098                                 'poco'   => $ret['poco']
1099                         ],
1100                         ['id' => $id]
1101                 );
1102
1103                 // Update the corresponding gcontact entry
1104                 PortableContact::lastUpdated($ret["url"]);
1105
1106                 return true;
1107         }
1108
1109         /**
1110          * Takes a $uid and a url/handle and adds a new contact
1111          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1112          * dfrn_request page.
1113          *
1114          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1115          *
1116          * Returns an array
1117          * $return['success'] boolean true if successful
1118          * $return['message'] error text if success is false.
1119          *
1120          * @brief Takes a $uid and a url/handle and adds a new contact
1121          * @param int    $uid
1122          * @param string $url
1123          * @param bool   $interactive
1124          * @param string $network
1125          * @return boolean|string
1126          */
1127         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1128         {
1129                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1130
1131                 $a = get_app();
1132
1133                 // remove ajax junk, e.g. Twitter
1134                 $url = str_replace('/#!/', '/', $url);
1135
1136                 if (!Network::isUrlAllowed($url)) {
1137                         $result['message'] = L10n::t('Disallowed profile URL.');
1138                         return $result;
1139                 }
1140
1141                 if (Network::isUrlBlocked($url)) {
1142                         $result['message'] = L10n::t('Blocked domain');
1143                         return $result;
1144                 }
1145
1146                 if (!$url) {
1147                         $result['message'] = L10n::t('Connect URL missing.');
1148                         return $result;
1149                 }
1150
1151                 $arr = ['url' => $url, 'contact' => []];
1152
1153                 Addon::callHooks('follow', $arr);
1154
1155                 if (empty($arr)) {
1156                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1157                         return $result;
1158                 }
1159
1160                 if (x($arr['contact'], 'name')) {
1161                         $ret = $arr['contact'];
1162                 } else {
1163                         $ret = Probe::uri($url, $network, $uid, false);
1164                 }
1165
1166                 if (($network != '') && ($ret['network'] != $network)) {
1167                         logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1168                         return result;
1169                 }
1170
1171                 if ($ret['network'] === NETWORK_DFRN) {
1172                         if ($interactive) {
1173                                 if (strlen($a->path)) {
1174                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1175                                 } else {
1176                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1177                                 }
1178
1179                                 goaway($ret['request'] . "&addr=$myaddr");
1180
1181                                 // NOTREACHED
1182                         }
1183                 } elseif (Config::get('system', 'dfrn_only')) {
1184                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1185                         $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1186                         return $result;
1187                 }
1188
1189                 // This extra param just confuses things, remove it
1190                 if ($ret['network'] === NETWORK_DIASPORA) {
1191                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1192                 }
1193
1194                 // do we have enough information?
1195
1196                 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1197                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1198                         if (!x($ret, 'poll')) {
1199                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1200                         }
1201                         if (!x($ret, 'name')) {
1202                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1203                         }
1204                         if (!x($ret, 'url')) {
1205                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1206                         }
1207                         if (strpos($url, '@') !== false) {
1208                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1209                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1210                         }
1211                         return $result;
1212                 }
1213
1214                 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1215                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1216                         $ret['notify'] = '';
1217                 }
1218
1219                 if (!$ret['notify']) {
1220                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1221                 }
1222
1223                 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1224
1225                 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1226
1227                 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1228
1229                 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1230                         $writeable = 1;
1231                 }
1232
1233                 // check if we already have a contact
1234                 // the poll url is more reliable than the profile url, as we may have
1235                 // indirect links or webfinger links
1236
1237                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1238                         intval($uid),
1239                         dbesc($ret['poll']),
1240                         dbesc(normalise_link($ret['poll'])),
1241                         dbesc($ret['network'])
1242                 );
1243
1244                 if (!DBM::is_result($r)) {
1245                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1246                                 intval($uid),
1247                                 dbesc(normalise_link($url)),
1248                                 dbesc($ret['network'])
1249                         );
1250                 }
1251
1252                 if (DBM::is_result($r)) {
1253                         // update contact
1254                         $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1255
1256                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1257                         dba::update('contact', $fields, ['id' => $r[0]['id']]);
1258                 } else {
1259                         $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1260
1261                         // create contact record
1262                         dba::insert('contact', [
1263                                 'uid'     => $uid,
1264                                 'created' => DateTimeFormat::utcNow(),
1265                                 'url'     => $ret['url'],
1266                                 'nurl'    => normalise_link($ret['url']),
1267                                 'addr'    => $ret['addr'],
1268                                 'alias'   => $ret['alias'],
1269                                 'batch'   => $ret['batch'],
1270                                 'notify'  => $ret['notify'],
1271                                 'poll'    => $ret['poll'],
1272                                 'poco'    => $ret['poco'],
1273                                 'name'    => $ret['name'],
1274                                 'nick'    => $ret['nick'],
1275                                 'network' => $ret['network'],
1276                                 'pubkey'  => $ret['pubkey'],
1277                                 'rel'     => $new_relation,
1278                                 'priority'=> $ret['priority'],
1279                                 'writable'=> $writeable,
1280                                 'hidden'  => $hidden,
1281                                 'blocked' => 0,
1282                                 'readonly'=> 0,
1283                                 'pending' => 0,
1284                                 'subhub'  => $subhub
1285                         ]);
1286                 }
1287
1288                 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1289                 if (!DBM::is_result($contact)) {
1290                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1291                         return $result;
1292                 }
1293
1294                 $contact_id = $contact['id'];
1295                 $result['cid'] = $contact_id;
1296
1297                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1298
1299                 // Update the avatar
1300                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1301
1302                 // pull feed and consume it, which should subscribe to the hub.
1303
1304                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1305
1306                 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1307                         WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1308                         intval($uid)
1309                 );
1310
1311                 if (DBM::is_result($r)) {
1312                         if (($contact['network'] == NETWORK_OSTATUS) && (strlen($contact['notify']))) {
1313                                 // create a follow slap
1314                                 $item = [];
1315                                 $item['verb'] = ACTIVITY_FOLLOW;
1316                                 $item['follow'] = $contact["url"];
1317                                 $slap = OStatus::salmon($item, $r[0]);
1318                                 Salmon::slapper($r[0], $contact['notify'], $slap);
1319                         }
1320
1321                         if ($contact['network'] == NETWORK_DIASPORA) {
1322                                 $ret = Diaspora::sendShare($a->user, $contact);
1323                                 logger('share returns: ' . $ret);
1324                         }
1325                 }
1326
1327                 $result['success'] = true;
1328                 return $result;
1329         }
1330
1331         public static function updateSslPolicy($contact, $new_policy)
1332         {
1333                 $ssl_changed = false;
1334                 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1335                         $ssl_changed = true;
1336                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
1337                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
1338                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
1339                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
1340                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
1341                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
1342                 }
1343
1344                 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1345                         $ssl_changed = true;
1346                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
1347                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
1348                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
1349                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
1350                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
1351                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
1352                 }
1353
1354                 if ($ssl_changed) {
1355                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1356                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
1357                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1358                         dba::update('contact', $fields, ['id' => $contact['id']]);
1359                 }
1360
1361                 return $contact;
1362         }
1363
1364         public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1365                 $url = notags(trim($datarray['author-link']));
1366                 $name = notags(trim($datarray['author-name']));
1367                 $photo = notags(trim($datarray['author-avatar']));
1368                 $nick = '';
1369
1370                 if (is_object($item)) {
1371                         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1372                         if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1373                                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1374                         }
1375                 } else {
1376                         $nick = $item;
1377                 }
1378
1379                 if (is_array($contact)) {
1380                         if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
1381                                 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1382                                 dba::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1383                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1384                         }
1385                         // send email notification to owner?
1386                 } else {
1387                         // create contact record
1388                         q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1389                                 `blocked`, `readonly`, `pending`, `writable`)
1390                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1391                                 intval($importer['uid']),
1392                                 dbesc(DateTimeFormat::utcNow()),
1393                                 dbesc($url),
1394                                 dbesc(normalise_link($url)),
1395                                 dbesc($name),
1396                                 dbesc($nick),
1397                                 dbesc($photo),
1398                                 dbesc(NETWORK_OSTATUS),
1399                                 intval(CONTACT_IS_FOLLOWER)
1400                         );
1401
1402                         $contact_record = [
1403                                 'id' => dba::lastInsertId(),
1404                                 'network' => NETWORK_OSTATUS
1405                         ];
1406                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1407
1408                         /// @TODO Encapsulate this into a function/method
1409                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1410                         $user = dba::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1411                         if (DBM::is_result($user) && !in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1412                                 // create notification
1413                                 $hash = random_string();
1414
1415                                 if (is_array($contact_record)) {
1416                                         dba::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1417                                                                 'blocked' => false, 'knowyou' => false,
1418                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1419                                 }
1420
1421                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1422
1423                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1424                                         in_array($user['page-flags'], [PAGE_NORMAL])) {
1425
1426                                         notification([
1427                                                 'type'         => NOTIFY_INTRO,
1428                                                 'notify_flags' => $user['notify-flags'],
1429                                                 'language'     => $user['language'],
1430                                                 'to_name'      => $user['username'],
1431                                                 'to_email'     => $user['email'],
1432                                                 'uid'          => $user['uid'],
1433                                                 'link'             => System::baseUrl() . '/notifications/intro',
1434                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1435                                                 'source_link'  => $contact_record['url'],
1436                                                 'source_photo' => $contact_record['photo'],
1437                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1438                                                 'otype'        => 'intro'
1439                                         ]);
1440
1441                                 }
1442                         } elseif (DBM::is_result($user) && in_array($user['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1443                                 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1444                                                 intval($importer['uid']),
1445                                                 dbesc($url)
1446                                 );
1447                         }
1448                 }
1449         }
1450
1451         public static function removeFollower($importer, $contact, array $datarray = [], $item = "") {
1452
1453                 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1454                         dba::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1455                 } else {
1456                         Contact::remove($contact['id']);
1457                 }
1458         }
1459
1460         public static function removeSharer($importer, $contact, array $datarray = [], $item = "") {
1461
1462                 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1463                         dba::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1464                 } else {
1465                         Contact::remove($contact['id']);
1466                 }
1467         }
1468
1469         /**
1470          * @brief Create a birthday event.
1471          *
1472          * Update the year and the birthday.
1473          */
1474         public static function updateBirthdays()
1475         {
1476                 // This only handles foreign or alien networks where a birthday has been provided.
1477                 // In-network birthdays are handled within local_delivery
1478
1479                 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1480                 if (DBM::is_result($r)) {
1481                         foreach ($r as $rr) {
1482                                 logger('update_contact_birthday: ' . $rr['bd']);
1483
1484                                 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1485
1486                                 /*
1487                                  * Add new birthday event for this person
1488                                  *
1489                                  * $bdtext is just a readable placeholder in case the event is shared
1490                                  * with others. We will replace it during presentation to our $importer
1491                                  * to contain a sparkle link and perhaps a photo.
1492                                  */
1493
1494                                 // Check for duplicates
1495                                 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1496                                         intval($rr['uid']), intval($rr['id']), dbesc(DateTimeFormat::utc($nextbd)), dbesc('birthday'));
1497
1498                                 if (DBM::is_result($s)) {
1499                                         continue;
1500                                 }
1501
1502                                 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1503                                 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1504
1505                                 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1506                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1507                                         dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utcNow()), dbesc(DateTimeFormat::utc($nextbd)),
1508                                         dbesc(DateTimeFormat::utc($nextbd . ' + 1 day ')), dbesc($bdtext), dbesc($bdtext2), dbesc('birthday'),
1509                                         intval(0)
1510                                 );
1511
1512
1513                                 // update bdyear
1514                                 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(substr($nextbd, 0, 4)),
1515                                         dbesc($nextbd), intval($rr['uid']), intval($rr['id'])
1516                                 );
1517                         }
1518                 }
1519         }
1520 }