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