]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Merge pull request #4074 from MrPetovan/task/update-composer
[friendica.git] / src / Model / Contact.php
1 <?php
2
3 /**
4  * @file src/Model/Contact.php
5  */
6
7 namespace Friendica\Model;
8
9 use Friendica\BaseObject;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBM;
14 use Friendica\Network\Probe;
15 use Friendica\Model\Photo;
16 use Friendica\Protocol\Diaspora;
17 use Friendica\Protocol\DFRN;
18 use Friendica\Protocol\OStatus;
19 use Friendica\Protocol\Salmon;
20 use dba;
21
22 require_once 'boot.php';
23 require_once 'include/text.php';
24
25 /**
26  * @brief functions for interacting with a contact
27  */
28 class Contact extends BaseObject
29 {
30         /**
31          * @brief Returns a list of contacts belonging in a group
32          *
33          * @param int $gid
34          * @return array
35          */
36         public static function getByGroupId($gid)
37         {
38                 $return = [];
39                 if (intval($gid)) {
40                         $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
41                                 FROM `contact`
42                                 INNER JOIN `group_member`
43                                         ON `contact`.`id` = `group_member`.`contact-id`
44                                 WHERE `gid` = ?
45                                 AND `contact`.`uid` = ?
46                                 AND NOT `contact`.`self`
47                                 AND NOT `contact`.`blocked`
48                                 AND NOT `contact`.`pending`
49                                 ORDER BY `contact`.`name` ASC',
50                                 $gid,
51                                 local_user()
52                         );
53                         if (DBM::is_result($stmt)) {
54                                 $return = dba::inArray($stmt);
55                         }
56                 }
57
58                 return $return;
59         }
60
61         /**
62          * @brief Returns the count of OStatus contacts in a group
63          *
64          * @param int $gid
65          * @return int
66          */
67         public static function getOStatusCountByGroupId($gid)
68         {
69                 $return = 0;
70                 if (intval($gid)) {
71                         $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
72                                 FROM `contact`
73                                 INNER JOIN `group_member`
74                                         ON `contact`.`id` = `group_member`.`contact-id`
75                                 WHERE `gid` = ?
76                                 AND `contact`.`uid` = ?
77                                 AND `contact`.`network` = ?
78                                 AND `contact`.`notify` != ""',
79                                 $gid,
80                                 local_user(),
81                                 NETWORK_OSTATUS
82                         );
83                         $return = $contacts['count'];
84                 }
85
86                 return $return;
87         }
88
89
90         /**
91          * Creates the self-contact for the provided user id
92          *
93          * @param int $uid
94          * @return bool Operation success
95          */
96         public static function createSelfFromUserId($uid)
97         {
98                 // Only create the entry if it doesn't exist yet
99                 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
100                         return true;
101                 }
102
103                 $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => $uid], ['limit' => 1]);
104                 if (!DBM::is_result($user)) {
105                         return false;
106                 }
107
108                 $return = dba::insert('contact', [
109                         'uid'         => $user['uid'],
110                         'created'     => datetime_convert(),
111                         'self'        => 1,
112                         'name'        => $user['username'],
113                         'nick'        => $user['nickname'],
114                         'photo'       => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
115                         'thumb'       => System::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
116                         'micro'       => System::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
117                         'blocked'     => 0,
118                         'pending'     => 0,
119                         'url'         => System::baseUrl() . '/profile/' . $user['nickname'],
120                         'nurl'        => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
121                         'addr'        => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
122                         'request'     => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
123                         'notify'      => System::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
124                         'poll'        => System::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
125                         'confirm'     => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
126                         'poco'        => System::baseUrl() . '/poco/'         . $user['nickname'],
127                         'name-date'   => datetime_convert(),
128                         'uri-date'    => datetime_convert(),
129                         'avatar-date' => datetime_convert(),
130                         'closeness'   => 0
131                 ]);
132
133                 return $return;
134         }
135
136         /**
137          * @brief Marks a contact for removal
138          *
139          * @param int $id contact id
140          * @return null
141          */
142         public static function remove($id)
143         {
144                 // We want just to make sure that we don't delete our "self" contact
145                 $r = dba::select('contact', array('uid'), array('id' => $id, 'self' => false), array('limit' => 1));
146
147                 if (!DBM::is_result($r) || !intval($r['uid'])) {
148                         return;
149                 }
150
151                 $archive = PConfig::get($r['uid'], 'system', 'archive_removed_contacts');
152                 if ($archive) {
153                         dba::update('contact', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
154                         return;
155                 }
156
157                 dba::delete('contact', array('id' => $id));
158
159                 // Delete the rest in the background
160                 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
161         }
162
163         /**
164          * @brief Sends an unfriend message. Does not remove the contact
165          *
166          * @param array $user    User unfriending
167          * @param array $contact Contact unfriended
168          * @return void
169          */
170         public static function terminateFriendship(array $user, array $contact)
171         {
172                 if ($contact['network'] === NETWORK_OSTATUS) {
173                         // create an unfollow slap
174                         $item = array();
175                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
176                         $item['follow'] = $contact["url"];
177                         $slap = OStatus::salmon($item, $user);
178
179                         if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
180                                 Salmon::slapper($user, $contact['notify'], $slap);
181                         }
182                 } elseif ($contact['network'] === NETWORK_DIASPORA) {
183                         Diaspora::sendUnshare($user, $contact);
184                 } elseif ($contact['network'] === NETWORK_DFRN) {
185                         DFRN::deliver($user, $contact, 'placeholder', 1);
186                 }
187         }
188
189         /**
190          * @brief Marks a contact for archival after a communication issue delay
191          *
192          * Contact has refused to recognise us as a friend. We will start a countdown.
193          * If they still don't recognise us in 32 days, the relationship is over,
194          * and we won't waste any more time trying to communicate with them.
195          * This provides for the possibility that their database is temporarily messed
196          * up or some other transient event and that there's a possibility we could recover from it.
197          *
198          * @param array $contact contact to mark for archival
199          * @return type
200          */
201         public static function markForArchival(array $contact)
202         {
203                 // Contact already archived or "self" contact? => nothing to do
204                 if ($contact['archive'] || $contact['self']) {
205                         return;
206                 }
207
208                 if ($contact['term-date'] <= NULL_DATE) {
209                         dba::update('contact', array('term-date' => datetime_convert()), array('id' => $contact['id']));
210
211                         if ($contact['url'] != '') {
212                                 dba::update('contact', array('term-date' => datetime_convert()), array('`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE));
213                         }
214                 } else {
215                         /* @todo
216                          * We really should send a notification to the owner after 2-3 weeks
217                          * so they won't be surprised when the contact vanishes and can take
218                          * remedial action if this was a serious mistake or glitch
219                          */
220
221                         /// @todo Check for contact vitality via probing
222                         $expiry = $contact['term-date'] . ' + 32 days ';
223                         if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
224                                 /* Relationship is really truly dead. archive them rather than
225                                  * delete, though if the owner tries to unarchive them we'll start
226                                  * the whole process over again.
227                                  */
228                                 dba::update('contact', array('archive' => 1), array('id' => $contact['id']));
229
230                                 if ($contact['url'] != '') {
231                                         dba::update('contact', array('archive' => 1), array('nurl' => normalise_link($contact['url']), 'self' => false));
232                                 }
233                         }
234                 }
235         }
236
237         /**
238          * @brief Cancels the archival countdown
239          *
240          * @see Contact::markForArchival()
241          *
242          * @param array $contact contact to be unmarked for archival
243          * @return null
244          */
245         public static function unmarkForArchival(array $contact)
246         {
247                 $condition = array('`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE);
248                 $exists = dba::exists('contact', $condition);
249
250                 // We don't need to update, we never marked this contact for archival
251                 if (!$exists) {
252                         return;
253                 }
254
255                 // It's a miracle. Our dead contact has inexplicably come back to life.
256                 $fields = array('term-date' => NULL_DATE, 'archive' => false);
257                 dba::update('contact', $fields, array('id' => $contact['id']));
258
259                 if ($contact['url'] != '') {
260                         dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
261                 }
262         }
263
264         /**
265          * @brief Get contact data for a given profile link
266          *
267          * The function looks at several places (contact table and gcontact table) for the contact
268          * It caches its result for the same script execution to prevent duplicate calls
269          *
270          * @param string $url     The profile link
271          * @param int    $uid     User id
272          * @param array  $default If not data was found take this data as default value
273          *
274          * @return array Contact data
275          */
276         public static function getDetailsByURL($url, $uid = -1, array $default = [])
277         {
278                 static $cache = array();
279
280                 if ($url == '') {
281                         return $default;
282                 }
283
284                 if ($uid == -1) {
285                         $uid = local_user();
286                 }
287
288                 if (isset($cache[$url][$uid])) {
289                         return $cache[$url][$uid];
290                 }
291
292                 $ssl_url = str_replace('http://', 'https://', $url);
293
294                 // Fetch contact data from the contact table for the given user
295                 $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`,
296                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
297                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
298                 $r = dba::inArray($s);
299
300                 // Fetch contact data from the contact table for the given user, checking with the alias
301                 if (!DBM::is_result($r)) {
302                         $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`,
303                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
304                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
305                         $r = dba::inArray($s);
306                 }
307
308                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
309                 if (!DBM::is_result($r)) {
310                         $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`,
311                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
312                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
313                         $r = dba::inArray($s);
314                 }
315
316                 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
317                 if (!DBM::is_result($r)) {
318                         $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`,
319                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
320                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
321                         $r = dba::inArray($s);
322                 }
323
324                 // Fetch the data from the gcontact table
325                 if (!DBM::is_result($r)) {
326                         $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`,
327                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
328                         FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
329                         $r = dba::inArray($s);
330                 }
331
332                 if (DBM::is_result($r)) {
333                         // If there is more than one entry we filter out the connector networks
334                         if (count($r) > 1) {
335                                 foreach ($r as $id => $result) {
336                                         if ($result["network"] == NETWORK_STATUSNET) {
337                                                 unset($r[$id]);
338                                         }
339                                 }
340                         }
341
342                         $profile = array_shift($r);
343
344                         // "bd" always contains the upcoming birthday of a contact.
345                         // "birthday" might contain the birthday including the year of birth.
346                         if ($profile["birthday"] > '0001-01-01') {
347                                 $bd_timestamp = strtotime($profile["birthday"]);
348                                 $month = date("m", $bd_timestamp);
349                                 $day = date("d", $bd_timestamp);
350
351                                 $current_timestamp = time();
352                                 $current_year = date("Y", $current_timestamp);
353                                 $current_month = date("m", $current_timestamp);
354                                 $current_day = date("d", $current_timestamp);
355
356                                 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
357                                 $current = $current_year . "-" . $current_month . "-" . $current_day;
358
359                                 if ($profile["bd"] < $current) {
360                                         $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
361                                 }
362                         } else {
363                                 $profile["bd"] = '0001-01-01';
364                         }
365                 } else {
366                         $profile = $default;
367                 }
368
369                 if (($profile["photo"] == "") && isset($default["photo"])) {
370                         $profile["photo"] = $default["photo"];
371                 }
372
373                 if (($profile["name"] == "") && isset($default["name"])) {
374                         $profile["name"] = $default["name"];
375                 }
376
377                 if (($profile["network"] == "") && isset($default["network"])) {
378                         $profile["network"] = $default["network"];
379                 }
380
381                 if (($profile["thumb"] == "") && isset($profile["photo"])) {
382                         $profile["thumb"] = $profile["photo"];
383                 }
384
385                 if (($profile["micro"] == "") && isset($profile["thumb"])) {
386                         $profile["micro"] = $profile["thumb"];
387                 }
388
389                 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
390                         && in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))
391                 ) {
392                         Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
393                 }
394
395                 // Show contact details of Diaspora contacts only if connected
396                 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
397                         $profile["location"] = "";
398                         $profile["about"] = "";
399                         $profile["gender"] = "";
400                         $profile["birthday"] = '0001-01-01';
401                 }
402
403                 $cache[$url][$uid] = $profile;
404
405                 return $profile;
406         }
407
408         /**
409          * @brief Get contact data for a given address
410          *
411          * The function looks at several places (contact table and gcontact table) for the contact
412          *
413          * @param string $addr The profile link
414          * @param int    $uid  User id
415          *
416          * @return array Contact data
417          */
418         public static function getDetailsByAddr($addr, $uid = -1)
419         {
420                 static $cache = array();
421
422                 if ($addr == '') {
423                         return array();
424                 }
425
426                 if ($uid == -1) {
427                         $uid = local_user();
428                 }
429
430                 // Fetch contact data from the contact table for the given user
431                 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
432                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
433                 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d", dbesc($addr), intval($uid));
434
435                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
436                 if (!DBM::is_result($r))
437                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
438                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
439                         FROM `contact` WHERE `addr` = '%s' AND `uid` = 0", dbesc($addr));
440
441                 // Fetch the data from the gcontact table
442                 if (!DBM::is_result($r))
443                         $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`,
444                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
445                         FROM `gcontact` WHERE `addr` = '%s'", dbesc($addr));
446
447                 if (!DBM::is_result($r)) {
448                         $data = Probe::uri($addr);
449
450                         $profile = self::getDetailsByURL($data['url'], $uid);
451                 } else {
452                         $profile = $r[0];
453                 }
454
455                 return $profile;
456         }
457
458         /**
459          * @brief Returns the data array for the photo menu of a given contact
460          *
461          * @param array $contact contact
462          * @param int   $uid     optional, default 0
463          * @return array
464          */
465         public static function photoMenu(array $contact, $uid = 0)
466         {
467                 // @todo Unused, to be removed
468                 $a = get_app();
469
470                 $contact_url = '';
471                 $pm_url = '';
472                 $status_link = '';
473                 $photos_link = '';
474                 $posts_link = '';
475                 $contact_drop_link = '';
476                 $poke_link = '';
477
478                 if ($uid == 0) {
479                         $uid = local_user();
480                 }
481
482                 if ($contact['uid'] != $uid) {
483                         if ($uid == 0) {
484                                 $profile_link = zrl($contact['url']);
485                                 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
486
487                                 return $menu;
488                         }
489
490                         $r = dba::select('contact', array(), array('nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid), array('limit' => 1));
491                         if ($r) {
492                                 return self::photoMenu($r, $uid);
493                         } else {
494                                 $profile_link = zrl($contact['url']);
495                                 $connlnk = 'follow/?url=' . $contact['url'];
496                                 $menu = array(
497                                         'profile' => array(t('View Profile'), $profile_link, true),
498                                         'follow' => array(t('Connect/Follow'), $connlnk, true)
499                                 );
500
501                                 return $menu;
502                         }
503                 }
504
505                 $sparkle = false;
506                 if ($contact['network'] === NETWORK_DFRN) {
507                         $sparkle = true;
508                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
509                 } else {
510                         $profile_link = $contact['url'];
511                 }
512
513                 if ($profile_link === 'mailbox') {
514                         $profile_link = '';
515                 }
516
517                 if ($sparkle) {
518                         $status_link = $profile_link . '?url=status';
519                         $photos_link = $profile_link . '?url=photos';
520                         $profile_link = $profile_link . '?url=profile';
521                 }
522
523                 if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
524                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
525                 }
526
527                 if ($contact['network'] == NETWORK_DFRN) {
528                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
529                 }
530
531                 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
532
533                 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
534                 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
535
536                 /**
537                  * Menu array:
538                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
539                  */
540                 $menu = array(
541                         'status' => array(t("View Status"), $status_link, true),
542                         'profile' => array(t("View Profile"), $profile_link, true),
543                         'photos' => array(t("View Photos"), $photos_link, true),
544                         'network' => array(t("Network Posts"), $posts_link, false),
545                         'edit' => array(t("View Contact"), $contact_url, false),
546                         'drop' => array(t("Drop Contact"), $contact_drop_link, false),
547                         'pm' => array(t("Send PM"), $pm_url, false),
548                         'poke' => array(t("Poke"), $poke_link, false),
549                 );
550
551
552                 $args = array('contact' => $contact, 'menu' => &$menu);
553
554                 call_hooks('contact_photo_menu', $args);
555
556                 $menucondensed = array();
557
558                 foreach ($menu as $menuname => $menuitem) {
559                         if ($menuitem[1] != '') {
560                                 $menucondensed[$menuname] = $menuitem;
561                         }
562                 }
563
564                 return $menucondensed;
565         }
566
567         /**
568          * @brief Returns ungrouped contact count or list for user
569          *
570          * Returns either the total number of ungrouped contacts for the given user
571          * id or a paginated list of ungrouped contacts.
572          *
573          * @param int $uid   uid
574          * @param int $start optional, default 0
575          * @param int $count optional, default 0
576          *
577          * @return array
578          */
579         public static function getUngroupedList($uid, $start = 0, $count = 0)
580         {
581                 if (!$count) {
582                         $r = q(
583                                 "SELECT COUNT(*) AS `total`
584                                  FROM `contact`
585                                  WHERE `uid` = %d
586                                  AND NOT `self`
587                                  AND NOT `blocked`
588                                  AND NOT `pending`
589                                  AND `id` NOT IN (
590                                         SELECT DISTINCT(`contact-id`)
591                                         FROM `group_member`
592                                         WHERE `uid` = %d
593                                 )", intval($uid), intval($uid)
594                         );
595
596                         return $r;
597                 }
598
599                 $r = q(
600                         "SELECT *
601                         FROM `contact`
602                         WHERE `uid` = %d
603                         AND NOT `self`
604                         AND NOT `blocked`
605                         AND NOT `pending`
606                         AND `id` NOT IN (
607                                 SELECT DISTINCT(`contact-id`)
608                                 FROM `group_member`
609                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
610                                 WHERE `group`.`uid` = %d
611                         )
612                         LIMIT %d, %d", intval($uid), intval($uid), intval($start), intval($count)
613                 );
614                 return $r;
615         }
616
617         /**
618          * @brief Fetch the contact id for a given url and user
619          *
620          * First lookup in the contact table to find a record matching either `url`, `nurl`,
621          * `addr` or `alias`.
622          *
623          * If there's no record and we aren't looking for a public contact, we quit.
624          * If there's one, we check that it isn't time to update the picture else we
625          * directly return the found contact id.
626          *
627          * Second, we probe the provided $url wether it's http://server.tld/profile or
628          * nick@server.tld. We quit if we can't get any info back.
629          *
630          * Third, we create the contact record if it doesn't exist
631          *
632          * Fourth, we update the existing record with the new data (avatar, alias, nick)
633          * if there's any updates
634          *
635          * @param string  $url       Contact URL
636          * @param integer $uid       The user id for the contact (0 = public contact)
637          * @param boolean $no_update Don't update the contact
638          *
639          * @return integer Contact ID
640          */
641         public static function getIdForURL($url, $uid = 0, $no_update = false)
642         {
643                 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
644
645                 $contact_id = 0;
646
647                 if ($url == '') {
648                         return 0;
649                 }
650
651                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
652                 // We first try the nurl (http://server.tld/nick), most common case
653                 $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
654
655                 // Then the addr (nick@server.tld)
656                 if (!DBM::is_result($contact)) {
657                         $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
658                 }
659
660                 // Then the alias (which could be anything)
661                 if (!DBM::is_result($contact)) {
662                         // The link could be provided as http although we stored it as https
663                         $ssl_url = str_replace('http://', 'https://', $url);
664                         $r = dba::select('contact', array('id', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
665                         $contact = dba::fetch($r);
666                         dba::close($r);
667                 }
668
669                 if (DBM::is_result($contact)) {
670                         $contact_id = $contact["id"];
671
672                         // Update the contact every 7 days
673                         $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
674
675                         // We force the update if the avatar is empty
676                         if ($contact['avatar'] == '') {
677                                 $update_contact = true;
678                         }
679
680                         if (!$update_contact || $no_update) {
681                                 return $contact_id;
682                         }
683                 } elseif ($uid != 0) {
684                         // Non-existing user-specific contact, exiting
685                         return 0;
686                 }
687
688                 $data = Probe::uri($url, "", $uid);
689
690                 // Last try in gcontact for unsupported networks
691                 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
692                         if ($uid != 0) {
693                                 return 0;
694                         }
695
696                         // Get data from the gcontact table
697                         $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'), array('nurl' => normalise_link($url)), array('limit' => 1));
698                         if (!DBM::is_result($gcontacts)) {
699                                 return 0;
700                         }
701
702                         $data = array_merge($data, $gcontacts);
703                 }
704
705                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
706                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
707                 }
708
709                 $url = $data["url"];
710                 if (!$contact_id) {
711                         dba::insert(
712                                 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
713                                 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
714                                 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
715                                 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
716                                 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
717                                 'network' => $data["network"], 'pubkey' => $data["pubkey"],
718                                 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
719                                 'batch' => $data["batch"], 'request' => $data["request"],
720                                 'confirm' => $data["confirm"], 'poco' => $data["poco"],
721                                 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
722                                 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
723                                 'readonly' => 0, 'pending' => 0)
724                         );
725
726                         $s = dba::select('contact', array('id'), array('nurl' => normalise_link($data["url"]), 'uid' => $uid), array('order' => array('id'), 'limit' => 2));
727                         $contacts = dba::inArray($s);
728                         if (!DBM::is_result($contacts)) {
729                                 return 0;
730                         }
731
732                         $contact_id = $contacts[0]["id"];
733
734                         // Update the newly created contact from data in the gcontact table
735                         $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'), array('nurl' => normalise_link($data["url"])), array('limit' => 1));
736                         if (DBM::is_result($gcontact)) {
737                                 // Only use the information when the probing hadn't fetched these values
738                                 if ($data['keywords'] != '') {
739                                         unset($gcontact['keywords']);
740                                 }
741                                 if ($data['location'] != '') {
742                                         unset($gcontact['location']);
743                                 }
744                                 if ($data['about'] != '') {
745                                         unset($gcontact['about']);
746                                 }
747                                 dba::update('contact', $gcontact, array('id' => $contact_id));
748                         }
749
750                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
751                                 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
752                                         normalise_link($data["url"]), $contact_id));
753                         }
754                 }
755
756                 self::updateAvatar($data["photo"], $uid, $contact_id);
757
758                 $fields = array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey');
759                 $contact = dba::select('contact', $fields, array('id' => $contact_id), array('limit' => 1));
760
761                 // This condition should always be true
762                 if (!DBM::is_result($contact)) {
763                         return $contact_id;
764                 }
765
766                 $updated = array('addr' => $data['addr'],
767                         'alias' => $data['alias'],
768                         'url' => $data['url'],
769                         'nurl' => normalise_link($data['url']),
770                         'name' => $data['name'],
771                         'nick' => $data['nick']);
772
773                 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
774                 if (!empty($contact['pubkey'])) {
775                         unset($contact['pubkey']);
776                 } else {
777                         $updated['pubkey'] = $data['pubkey'];
778                 }
779
780                 if ($data['keywords'] != '') {
781                         $updated['keywords'] = $data['keywords'];
782                 }
783                 if ($data['location'] != '') {
784                         $updated['location'] = $data['location'];
785                 }
786                 if ($data['about'] != '') {
787                         $updated['about'] = $data['about'];
788                 }
789
790                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
791                         $updated['uri-date'] = datetime_convert();
792                 }
793                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
794                         $updated['name-date'] = datetime_convert();
795                 }
796
797                 $updated['avatar-date'] = datetime_convert();
798
799                 dba::update('contact', $updated, array('id' => $contact_id), $contact);
800
801                 return $contact_id;
802         }
803
804         /**
805          * @brief Checks if the contact is blocked
806          *
807          * @param int $cid contact id
808          *
809          * @return boolean Is the contact blocked?
810          */
811         public static function isBlocked($cid)
812         {
813                 if ($cid == 0) {
814                         return false;
815                 }
816
817                 $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
818                 if (!DBM::is_result($blocked)) {
819                         return false;
820                 }
821                 return (bool) $blocked['blocked'];
822         }
823
824         /**
825          * @brief Checks if the contact is hidden
826          *
827          * @param int $cid contact id
828          *
829          * @return boolean Is the contact hidden?
830          */
831         public static function isHidden($cid)
832         {
833                 if ($cid == 0) {
834                         return false;
835                 }
836
837                 $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
838                 if (!DBM::is_result($hidden)) {
839                         return false;
840                 }
841                 return (bool) $hidden['hidden'];
842         }
843
844         /**
845          * @brief Returns posts from a given contact url
846          *
847          * @param string $contact_url Contact URL
848          *
849          * @return string posts in HTML
850          */
851         public static function getPostsFromUrl($contact_url)
852         {
853                 $a = self::getApp();
854
855                 require_once 'include/conversation.php';
856
857                 // There are no posts with "uid = 0" with connector networks
858                 // This speeds up the query a lot
859                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
860                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
861
862                 if (!DBM::is_result($r)) {
863                         return '';
864                 }
865
866                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
867                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
868                 } else {
869                         $sql = "`item`.`uid` = %d";
870                 }
871
872                 $author_id = intval($r[0]["author-id"]);
873
874                 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
875
876                 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
877                         " ORDER BY `item`.`created` DESC LIMIT %d, %d", intval($author_id), intval(local_user()), intval($a->pager['start']), intval($a->pager['itemspage'])
878                 );
879
880
881                 $o = conversation($a, $r, 'community', false);
882
883                 $o .= alt_pager($a, count($r));
884
885                 return $o;
886         }
887
888         /**
889          * @brief Returns the account type name
890          *
891          * The function can be called with either the user or the contact array
892          *
893          * @param array $contact contact or user array
894          * @return string
895          */
896         public static function getAccountType(array $contact)
897         {
898                 // There are several fields that indicate that the contact or user is a forum
899                 // "page-flags" is a field in the user table,
900                 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
901                 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
902                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
903                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
904                         || (isset($contact['forum']) && intval($contact['forum']))
905                         || (isset($contact['prv']) && intval($contact['prv']))
906                         || (isset($contact['community']) && intval($contact['community']))
907                 ) {
908                         $type = ACCOUNT_TYPE_COMMUNITY;
909                 } else {
910                         $type = ACCOUNT_TYPE_PERSON;
911                 }
912
913                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
914                 if (isset($contact["contact-type"])) {
915                         $type = $contact["contact-type"];
916                 }
917                 if (isset($contact["account-type"])) {
918                         $type = $contact["account-type"];
919                 }
920
921                 switch ($type) {
922                         case ACCOUNT_TYPE_ORGANISATION:
923                                 $account_type = t("Organisation");
924                                 break;
925                         case ACCOUNT_TYPE_NEWS:
926                                 $account_type = t('News');
927                                 break;
928                         case ACCOUNT_TYPE_COMMUNITY:
929                                 $account_type = t("Forum");
930                                 break;
931                         default:
932                                 $account_type = "";
933                                 break;
934                 }
935
936                 return $account_type;
937         }
938
939         /**
940          * @brief Blocks a contact
941          *
942          * @param int $uid
943          * @return bool
944          */
945         public static function block($uid)
946         {
947                 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
948
949                 return $return;
950         }
951
952         /**
953          * @brief Unblocks a contact
954          *
955          * @param int $uid
956          * @return bool
957          */
958         public static function unblock($uid)
959         {
960                 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
961
962                 return $return;
963   }
964
965   /**
966    * @brief Updates the avatar links in a contact only if needed
967          *
968          * @param string $avatar Link to avatar picture
969          * @param int    $uid    User id of contact owner
970          * @param int    $cid    Contact id
971          * @param bool   $force  force picture update
972          *
973          * @return array Returns array of the different avatar sizes
974          */
975         public static function updateAvatar($avatar, $uid, $cid, $force = false)
976         {
977                 // Limit = 1 returns the row so no need for dba:inArray()
978                 $r = dba::select('contact', array('avatar', 'photo', 'thumb', 'micro', 'nurl'), array('id' => $cid), array('limit' => 1));
979                 if (!DBM::is_result($r)) {
980                         return false;
981                 } else {
982                         $data = array($r["photo"], $r["thumb"], $r["micro"]);
983                 }
984
985                 if (($r["avatar"] != $avatar) || $force) {
986                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
987
988                         if ($photos) {
989                                 dba::update(
990                                         'contact',
991                                         array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
992                                         array('id' => $cid)
993                                 );
994
995                                 // Update the public contact (contact id = 0)
996                                 if ($uid != 0) {
997                                         $pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1));
998                                         if (DBM::is_result($pcontact)) {
999                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1000                                         }
1001                                 }
1002
1003                                 return $photos;
1004                         }
1005                 }
1006
1007                 return $data;
1008         }
1009 }