]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Merge pull request #4031 from MrPetovan/task/3878-move-objects-to-model
[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\Object\Image;
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          * Creates the self-contact for the provided user id
32          *
33          * @param int $uid
34          * @return bool Operation success
35          */
36         public static function createSelfFromUserId($uid)
37         {
38                 // Only create the entry if it doesn't exist yet
39                 if (dba::exists('contact', ['uid' => intval($uid), 'self'])) {
40                         return true;
41                 }
42
43                 $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => intval($uid)], ['limit' => 1]);
44                 if (!DBM::is_result($user)) {
45                         return false;
46                 }
47
48                 $return = dba::insert('contact', [
49                         'uid'         => $user['uid'],
50                         'created'     => datetime_convert(),
51                         'self'        => 1,
52                         'name'        => $user['username'],
53                         'nick'        => $user['nickname'],
54                         'photo'       => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
55                         'thumb'       => System::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
56                         'micro'       => System::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
57                         'blocked'     => 0,
58                         'pending'     => 0,
59                         'url'         => System::baseUrl() . '/profile/' . $user['nickname'],
60                         'nurl'        => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
61                         'addr'        => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
62                         'request'     => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
63                         'notify'      => System::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
64                         'poll'        => System::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
65                         'confirm'     => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
66                         'poco'        => System::baseUrl() . '/poco/'         . $user['nickname'],
67                         'name-date'   => datetime_convert(),
68                         'uri-date'    => datetime_convert(),
69                         'avatar-date' => datetime_convert(),
70                         'closeness'   => 0
71                 ]);
72
73                 return $return;
74         }
75
76         /**
77          * @brief Marks a contact for removal
78          *
79          * @param int $id contact id
80          * @return null
81          */
82         public static function remove($id)
83         {
84                 // We want just to make sure that we don't delete our "self" contact
85                 $r = dba::select('contact', array('uid'), array('id' => $id, 'self' => false), array('limit' => 1));
86
87                 if (!DBM::is_result($r) || !intval($r['uid'])) {
88                         return;
89                 }
90
91                 $archive = PConfig::get($r['uid'], 'system', 'archive_removed_contacts');
92                 if ($archive) {
93                         dba::update('contact', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
94                         return;
95                 }
96
97                 dba::delete('contact', array('id' => $id));
98
99                 // Delete the rest in the background
100                 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
101         }
102
103         /**
104          * @brief Sends an unfriend message. Does not remove the contact
105          *
106          * @param array $user    User unfriending
107          * @param array $contact Contact unfriended
108          * @return void
109          */
110         public static function terminateFriendship(array $user, array $contact)
111         {
112                 if ($contact['network'] === NETWORK_OSTATUS) {
113                         // create an unfollow slap
114                         $item = array();
115                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
116                         $item['follow'] = $contact["url"];
117                         $slap = OStatus::salmon($item, $user);
118
119                         if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
120                                 Salmon::slapper($user, $contact['notify'], $slap);
121                         }
122                 } elseif ($contact['network'] === NETWORK_DIASPORA) {
123                         Diaspora::sendUnshare($user, $contact);
124                 } elseif ($contact['network'] === NETWORK_DFRN) {
125                         DFRN::deliver($user, $contact, 'placeholder', 1);
126                 }
127         }
128
129         /**
130          * @brief Marks a contact for archival after a communication issue delay
131          *
132          * Contact has refused to recognise us as a friend. We will start a countdown.
133          * If they still don't recognise us in 32 days, the relationship is over,
134          * and we won't waste any more time trying to communicate with them.
135          * This provides for the possibility that their database is temporarily messed
136          * up or some other transient event and that there's a possibility we could recover from it.
137          *
138          * @param array $contact contact to mark for archival
139          * @return type
140          */
141         public static function markForArchival(array $contact)
142         {
143                 // Contact already archived or "self" contact? => nothing to do
144                 if ($contact['archive'] || $contact['self']) {
145                         return;
146                 }
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` <= ? AND NOT `self`', 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']), 'self' => false));
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                 $fields = array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey');
697                 $contact = dba::select('contact', $fields, array('id' => $contact_id), array('limit' => 1));
698
699                 // This condition should always be true
700                 if (!DBM::is_result($contact)) {
701                         return $contact_id;
702                 }
703
704                 $updated = array('addr' => $data['addr'],
705                         'alias' => $data['alias'],
706                         'url' => $data['url'],
707                         'nurl' => normalise_link($data['url']),
708                         'name' => $data['name'],
709                         'nick' => $data['nick']);
710
711                 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
712                 if (!empty($contact['pubkey'])) {
713                         unset($contact['pubkey']);
714                 } else {
715                         $updated['pubkey'] = $data['pubkey'];
716                 }
717
718                 if ($data['keywords'] != '') {
719                         $updated['keywords'] = $data['keywords'];
720                 }
721                 if ($data['location'] != '') {
722                         $updated['location'] = $data['location'];
723                 }
724                 if ($data['about'] != '') {
725                         $updated['about'] = $data['about'];
726                 }
727
728                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
729                         $updated['uri-date'] = datetime_convert();
730                 }
731                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
732                         $updated['name-date'] = datetime_convert();
733                 }
734
735                 $updated['avatar-date'] = datetime_convert();
736
737                 dba::update('contact', $updated, array('id' => $contact_id), $contact);
738
739                 return $contact_id;
740         }
741
742         /**
743          * @brief Checks if the contact is blocked
744          *
745          * @param int $cid contact id
746          *
747          * @return boolean Is the contact blocked?
748          */
749         public static function isBlocked($cid)
750         {
751                 if ($cid == 0) {
752                         return false;
753                 }
754
755                 $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
756                 if (!DBM::is_result($blocked)) {
757                         return false;
758                 }
759                 return (bool) $blocked['blocked'];
760         }
761
762         /**
763          * @brief Checks if the contact is hidden
764          *
765          * @param int $cid contact id
766          *
767          * @return boolean Is the contact hidden?
768          */
769         public static function isHidden($cid)
770         {
771                 if ($cid == 0) {
772                         return false;
773                 }
774
775                 $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
776                 if (!DBM::is_result($hidden)) {
777                         return false;
778                 }
779                 return (bool) $hidden['hidden'];
780         }
781
782         /**
783          * @brief Returns posts from a given contact url
784          *
785          * @param string $contact_url Contact URL
786          *
787          * @return string posts in HTML
788          */
789         public static function getPostsFromUrl($contact_url)
790         {
791                 $a = self::getApp();
792
793                 require_once 'include/conversation.php';
794
795                 // There are no posts with "uid = 0" with connector networks
796                 // This speeds up the query a lot
797                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
798                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
799
800                 if (!DBM::is_result($r)) {
801                         return '';
802                 }
803
804                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
805                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
806                 } else {
807                         $sql = "`item`.`uid` = %d";
808                 }
809
810                 $author_id = intval($r[0]["author-id"]);
811
812                 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
813
814                 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
815                         " ORDER BY `item`.`created` DESC LIMIT %d, %d", intval($author_id), intval(local_user()), intval($a->pager['start']), intval($a->pager['itemspage'])
816                 );
817
818
819                 $o = conversation($a, $r, 'community', false);
820
821                 $o .= alt_pager($a, count($r));
822
823                 return $o;
824         }
825
826         /**
827          * @brief Returns the account type name
828          *
829          * The function can be called with either the user or the contact array
830          *
831          * @param array $contact contact or user array
832          * @return string
833          */
834         public static function getAccountType(array $contact)
835         {
836                 // There are several fields that indicate that the contact or user is a forum
837                 // "page-flags" is a field in the user table,
838                 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
839                 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
840                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
841                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
842                         || (isset($contact['forum']) && intval($contact['forum']))
843                         || (isset($contact['prv']) && intval($contact['prv']))
844                         || (isset($contact['community']) && intval($contact['community']))
845                 ) {
846                         $type = ACCOUNT_TYPE_COMMUNITY;
847                 } else {
848                         $type = ACCOUNT_TYPE_PERSON;
849                 }
850
851                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
852                 if (isset($contact["contact-type"])) {
853                         $type = $contact["contact-type"];
854                 }
855                 if (isset($contact["account-type"])) {
856                         $type = $contact["account-type"];
857                 }
858
859                 switch ($type) {
860                         case ACCOUNT_TYPE_ORGANISATION:
861                                 $account_type = t("Organisation");
862                                 break;
863                         case ACCOUNT_TYPE_NEWS:
864                                 $account_type = t('News');
865                                 break;
866                         case ACCOUNT_TYPE_COMMUNITY:
867                                 $account_type = t("Forum");
868                                 break;
869                         default:
870                                 $account_type = "";
871                                 break;
872                 }
873
874                 return $account_type;
875         }
876
877         /**
878          * @brief Blocks a contact
879          *
880          * @param int $uid
881          * @return bool
882          */
883         public static function block($uid)
884         {
885                 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
886
887                 return $return;
888         }
889
890         /**
891          * @brief Unblocks a contact
892          *
893          * @param int $uid
894          * @return bool
895          */
896         public static function unblock($uid)
897         {
898                 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
899
900                 return $return;
901   }
902
903   /**
904    * @brief Updates the avatar links in a contact only if needed
905          *
906          * @param string $avatar Link to avatar picture
907          * @param int    $uid    User id of contact owner
908          * @param int    $cid    Contact id
909          * @param bool   $force  force picture update
910          *
911          * @return array Returns array of the different avatar sizes
912          */
913         public static function updateAvatar($avatar, $uid, $cid, $force = false)
914         {
915                 // Limit = 1 returns the row so no need for dba:inArray()
916                 $r = dba::select('contact', array('avatar', 'photo', 'thumb', 'micro', 'nurl'), array('id' => $cid), array('limit' => 1));
917                 if (!DBM::is_result($r)) {
918                         return false;
919                 } else {
920                         $data = array($r["photo"], $r["thumb"], $r["micro"]);
921                 }
922
923                 if (($r["avatar"] != $avatar) || $force) {
924                         $photos = Image::importProfilePhoto($avatar, $uid, $cid, true);
925
926                         if ($photos) {
927                                 dba::update(
928                                         'contact',
929                                         array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
930                                         array('id' => $cid)
931                                 );
932
933                                 // Update the public contact (contact id = 0)
934                                 if ($uid != 0) {
935                                         $pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1));
936                                         if (DBM::is_result($pcontact)) {
937                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
938                                         }
939                                 }
940
941                                 return $photos;
942                         }
943                 }
944
945                 return $data;
946         }
947 }