]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Add new method from include/group in relevant Model classes
[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 `group_member`.`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 `group_member`.`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' => intval($uid), 'self'])) {
100                         return true;
101                 }
102
103                 $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => intval($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` WHERE `uid` = %d
609                         )
610                         LIMIT %d, %d", intval($uid), intval($uid), intval($start), intval($count)
611                 );
612                 return $r;
613         }
614
615         /**
616          * @brief Fetch the contact id for a given url and user
617          *
618          * First lookup in the contact table to find a record matching either `url`, `nurl`,
619          * `addr` or `alias`.
620          *
621          * If there's no record and we aren't looking for a public contact, we quit.
622          * If there's one, we check that it isn't time to update the picture else we
623          * directly return the found contact id.
624          *
625          * Second, we probe the provided $url wether it's http://server.tld/profile or
626          * nick@server.tld. We quit if we can't get any info back.
627          *
628          * Third, we create the contact record if it doesn't exist
629          *
630          * Fourth, we update the existing record with the new data (avatar, alias, nick)
631          * if there's any updates
632          *
633          * @param string  $url       Contact URL
634          * @param integer $uid       The user id for the contact (0 = public contact)
635          * @param boolean $no_update Don't update the contact
636          *
637          * @return integer Contact ID
638          */
639         public static function getIdForURL($url, $uid = 0, $no_update = false)
640         {
641                 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
642
643                 $contact_id = 0;
644
645                 if ($url == '') {
646                         return 0;
647                 }
648
649                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
650                 // We first try the nurl (http://server.tld/nick), most common case
651                 $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
652
653                 // Then the addr (nick@server.tld)
654                 if (!DBM::is_result($contact)) {
655                         $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
656                 }
657
658                 // Then the alias (which could be anything)
659                 if (!DBM::is_result($contact)) {
660                         // The link could be provided as http although we stored it as https
661                         $ssl_url = str_replace('http://', 'https://', $url);
662                         $r = dba::select('contact', array('id', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
663                         $contact = dba::fetch($r);
664                         dba::close($r);
665                 }
666
667                 if (DBM::is_result($contact)) {
668                         $contact_id = $contact["id"];
669
670                         // Update the contact every 7 days
671                         $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
672
673                         // We force the update if the avatar is empty
674                         if ($contact['avatar'] == '') {
675                                 $update_contact = true;
676                         }
677
678                         if (!$update_contact || $no_update) {
679                                 return $contact_id;
680                         }
681                 } elseif ($uid != 0) {
682                         // Non-existing user-specific contact, exiting
683                         return 0;
684                 }
685
686                 $data = Probe::uri($url, "", $uid);
687
688                 // Last try in gcontact for unsupported networks
689                 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
690                         if ($uid != 0) {
691                                 return 0;
692                         }
693
694                         // Get data from the gcontact table
695                         $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'), array('nurl' => normalise_link($url)), array('limit' => 1));
696                         if (!DBM::is_result($gcontacts)) {
697                                 return 0;
698                         }
699
700                         $data = array_merge($data, $gcontacts);
701                 }
702
703                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
704                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
705                 }
706
707                 $url = $data["url"];
708                 if (!$contact_id) {
709                         dba::insert(
710                                 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
711                                 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
712                                 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
713                                 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
714                                 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
715                                 'network' => $data["network"], 'pubkey' => $data["pubkey"],
716                                 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
717                                 'batch' => $data["batch"], 'request' => $data["request"],
718                                 'confirm' => $data["confirm"], 'poco' => $data["poco"],
719                                 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
720                                 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
721                                 'readonly' => 0, 'pending' => 0)
722                         );
723
724                         $s = dba::select('contact', array('id'), array('nurl' => normalise_link($data["url"]), 'uid' => $uid), array('order' => array('id'), 'limit' => 2));
725                         $contacts = dba::inArray($s);
726                         if (!DBM::is_result($contacts)) {
727                                 return 0;
728                         }
729
730                         $contact_id = $contacts[0]["id"];
731
732                         // Update the newly created contact from data in the gcontact table
733                         $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'), array('nurl' => normalise_link($data["url"])), array('limit' => 1));
734                         if (DBM::is_result($gcontact)) {
735                                 // Only use the information when the probing hadn't fetched these values
736                                 if ($data['keywords'] != '') {
737                                         unset($gcontact['keywords']);
738                                 }
739                                 if ($data['location'] != '') {
740                                         unset($gcontact['location']);
741                                 }
742                                 if ($data['about'] != '') {
743                                         unset($gcontact['about']);
744                                 }
745                                 dba::update('contact', $gcontact, array('id' => $contact_id));
746                         }
747
748                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
749                                 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
750                                         normalise_link($data["url"]), $contact_id));
751                         }
752                 }
753
754                 self::updateAvatar($data["photo"], $uid, $contact_id);
755
756                 $fields = array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey');
757                 $contact = dba::select('contact', $fields, array('id' => $contact_id), array('limit' => 1));
758
759                 // This condition should always be true
760                 if (!DBM::is_result($contact)) {
761                         return $contact_id;
762                 }
763
764                 $updated = array('addr' => $data['addr'],
765                         'alias' => $data['alias'],
766                         'url' => $data['url'],
767                         'nurl' => normalise_link($data['url']),
768                         'name' => $data['name'],
769                         'nick' => $data['nick']);
770
771                 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
772                 if (!empty($contact['pubkey'])) {
773                         unset($contact['pubkey']);
774                 } else {
775                         $updated['pubkey'] = $data['pubkey'];
776                 }
777
778                 if ($data['keywords'] != '') {
779                         $updated['keywords'] = $data['keywords'];
780                 }
781                 if ($data['location'] != '') {
782                         $updated['location'] = $data['location'];
783                 }
784                 if ($data['about'] != '') {
785                         $updated['about'] = $data['about'];
786                 }
787
788                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
789                         $updated['uri-date'] = datetime_convert();
790                 }
791                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
792                         $updated['name-date'] = datetime_convert();
793                 }
794
795                 $updated['avatar-date'] = datetime_convert();
796
797                 dba::update('contact', $updated, array('id' => $contact_id), $contact);
798
799                 return $contact_id;
800         }
801
802         /**
803          * @brief Checks if the contact is blocked
804          *
805          * @param int $cid contact id
806          *
807          * @return boolean Is the contact blocked?
808          */
809         public static function isBlocked($cid)
810         {
811                 if ($cid == 0) {
812                         return false;
813                 }
814
815                 $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
816                 if (!DBM::is_result($blocked)) {
817                         return false;
818                 }
819                 return (bool) $blocked['blocked'];
820         }
821
822         /**
823          * @brief Checks if the contact is hidden
824          *
825          * @param int $cid contact id
826          *
827          * @return boolean Is the contact hidden?
828          */
829         public static function isHidden($cid)
830         {
831                 if ($cid == 0) {
832                         return false;
833                 }
834
835                 $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
836                 if (!DBM::is_result($hidden)) {
837                         return false;
838                 }
839                 return (bool) $hidden['hidden'];
840         }
841
842         /**
843          * @brief Returns posts from a given contact url
844          *
845          * @param string $contact_url Contact URL
846          *
847          * @return string posts in HTML
848          */
849         public static function getPostsFromUrl($contact_url)
850         {
851                 $a = self::getApp();
852
853                 require_once 'include/conversation.php';
854
855                 // There are no posts with "uid = 0" with connector networks
856                 // This speeds up the query a lot
857                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
858                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
859
860                 if (!DBM::is_result($r)) {
861                         return '';
862                 }
863
864                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
865                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
866                 } else {
867                         $sql = "`item`.`uid` = %d";
868                 }
869
870                 $author_id = intval($r[0]["author-id"]);
871
872                 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
873
874                 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
875                         " ORDER BY `item`.`created` DESC LIMIT %d, %d", intval($author_id), intval(local_user()), intval($a->pager['start']), intval($a->pager['itemspage'])
876                 );
877
878
879                 $o = conversation($a, $r, 'community', false);
880
881                 $o .= alt_pager($a, count($r));
882
883                 return $o;
884         }
885
886         /**
887          * @brief Returns the account type name
888          *
889          * The function can be called with either the user or the contact array
890          *
891          * @param array $contact contact or user array
892          * @return string
893          */
894         public static function getAccountType(array $contact)
895         {
896                 // There are several fields that indicate that the contact or user is a forum
897                 // "page-flags" is a field in the user table,
898                 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
899                 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
900                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
901                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
902                         || (isset($contact['forum']) && intval($contact['forum']))
903                         || (isset($contact['prv']) && intval($contact['prv']))
904                         || (isset($contact['community']) && intval($contact['community']))
905                 ) {
906                         $type = ACCOUNT_TYPE_COMMUNITY;
907                 } else {
908                         $type = ACCOUNT_TYPE_PERSON;
909                 }
910
911                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
912                 if (isset($contact["contact-type"])) {
913                         $type = $contact["contact-type"];
914                 }
915                 if (isset($contact["account-type"])) {
916                         $type = $contact["account-type"];
917                 }
918
919                 switch ($type) {
920                         case ACCOUNT_TYPE_ORGANISATION:
921                                 $account_type = t("Organisation");
922                                 break;
923                         case ACCOUNT_TYPE_NEWS:
924                                 $account_type = t('News');
925                                 break;
926                         case ACCOUNT_TYPE_COMMUNITY:
927                                 $account_type = t("Forum");
928                                 break;
929                         default:
930                                 $account_type = "";
931                                 break;
932                 }
933
934                 return $account_type;
935         }
936
937         /**
938          * @brief Blocks a contact
939          *
940          * @param int $uid
941          * @return bool
942          */
943         public static function block($uid)
944         {
945                 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
946
947                 return $return;
948         }
949
950         /**
951          * @brief Unblocks a contact
952          *
953          * @param int $uid
954          * @return bool
955          */
956         public static function unblock($uid)
957         {
958                 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
959
960                 return $return;
961   }
962
963   /**
964    * @brief Updates the avatar links in a contact only if needed
965          *
966          * @param string $avatar Link to avatar picture
967          * @param int    $uid    User id of contact owner
968          * @param int    $cid    Contact id
969          * @param bool   $force  force picture update
970          *
971          * @return array Returns array of the different avatar sizes
972          */
973         public static function updateAvatar($avatar, $uid, $cid, $force = false)
974         {
975                 // Limit = 1 returns the row so no need for dba:inArray()
976                 $r = dba::select('contact', array('avatar', 'photo', 'thumb', 'micro', 'nurl'), array('id' => $cid), array('limit' => 1));
977                 if (!DBM::is_result($r)) {
978                         return false;
979                 } else {
980                         $data = array($r["photo"], $r["thumb"], $r["micro"]);
981                 }
982
983                 if (($r["avatar"] != $avatar) || $force) {
984                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
985
986                         if ($photos) {
987                                 dba::update(
988                                         'contact',
989                                         array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
990                                         array('id' => $cid)
991                                 );
992
993                                 // Update the public contact (contact id = 0)
994                                 if ($uid != 0) {
995                                         $pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1));
996                                         if (DBM::is_result($pcontact)) {
997                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
998                                         }
999                                 }
1000
1001                                 return $photos;
1002                         }
1003                 }
1004
1005                 return $data;
1006         }
1007 }