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