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