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