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