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