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