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