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