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