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