]> git.mxchange.org Git - friendica.git/blob - src/Object/Contact.php
Merge pull request #3985 from hoergen/develop
[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\Protocol\Diaspora;
17 use Friendica\Protocol\DFRN;
18 use Friendica\Protocol\OStatus;
19 use dba;
20
21 require_once 'boot.php';
22 require_once 'include/text.php';
23
24 /**
25  * @brief functions for interacting with a contact
26  */
27 class Contact extends BaseObject
28 {
29         /**
30          * @brief Marks a contact for removal
31          *
32          * @param int $id contact id
33          * @return null
34          */
35         public static function remove($id)
36         {
37                 // We want just to make sure that we don't delete our "self" contact
38                 $r = dba::select('contact', array('uid'), array('id' => $id, 'self' => false), array('limit' => 1));
39
40                 if (!DBM::is_result($r) || !intval($r['uid'])) {
41                         return;
42                 }
43
44                 $archive = PConfig::get($r['uid'], 'system', 'archive_removed_contacts');
45                 if ($archive) {
46                         dba::update('contact', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
47                         return;
48                 }
49
50                 dba::delete('contact', array('id' => $id));
51
52                 // Delete the rest in the background
53                 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
54         }
55
56         /**
57          * @brief Sends an unfriend message. Does not remove the contact
58          *
59          * @param array $user    User unfriending
60          * @param array $contact Contact unfriended
61          * @return void
62          */
63         public static function terminateFriendship(array $user, array $contact)
64         {
65                 if ($contact['network'] === NETWORK_OSTATUS) {
66                         // create an unfollow slap
67                         $item = array();
68                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
69                         $item['follow'] = $contact["url"];
70                         $slap = OStatus::salmon($item, $user);
71
72                         if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
73                                 require_once 'include/salmon.php';
74                                 slapper($user, $contact['notify'], $slap);
75                         }
76                 } elseif ($contact['network'] === NETWORK_DIASPORA) {
77                         Diaspora::sendUnshare($user, $contact);
78                 } elseif ($contact['network'] === NETWORK_DFRN) {
79                         DFRN::deliver($user, $contact, 'placeholder', 1);
80                 }
81         }
82
83         /**
84          * @brief Marks a contact for archival after a communication issue delay
85          *
86          * Contact has refused to recognise us as a friend. We will start a countdown.
87          * If they still don't recognise us in 32 days, the relationship is over,
88          * and we won't waste any more time trying to communicate with them.
89          * This provides for the possibility that their database is temporarily messed
90          * up or some other transient event and that there's a possibility we could recover from it.
91          *
92          * @param array $contact contact to mark for archival
93          * @return type
94          */
95         public static function markForArchival(array $contact)
96         {
97                 // Contact already archived, nothing to do
98                 if ($contact['archive']) {
99                         return;
100                 }
101
102                 if ($contact['term-date'] <= NULL_DATE) {
103                         dba::update('contact', array('term-date' => datetime_convert()), array('id' => $contact['id']));
104
105                         if ($contact['url'] != '') {
106                                 dba::update('contact', array('term-date' => datetime_convert()), array('`nurl` = ? AND `term-date` <= ?', normalise_link($contact['url']), NULL_DATE));
107                         }
108                 } else {
109                         /* @todo
110                          * We really should send a notification to the owner after 2-3 weeks
111                          * so they won't be surprised when the contact vanishes and can take
112                          * remedial action if this was a serious mistake or glitch
113                          */
114
115                         /// @todo Check for contact vitality via probing
116                         $expiry = $contact['term-date'] . ' + 32 days ';
117                         if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
118                                 /* Relationship is really truly dead. archive them rather than
119                                  * delete, though if the owner tries to unarchive them we'll start
120                                  * the whole process over again.
121                                  */
122                                 dba::update('contact', array('archive' => 1), array('id' => $contact['id']));
123
124                                 if ($contact['url'] != '') {
125                                         dba::update('contact', array('archive' => 1), array('nurl' => normalise_link($contact['url'])));
126                                 }
127                         }
128                 }
129         }
130
131         /**
132          * @brief Cancels the archival countdown
133          *
134          * @see Contact::markForArchival()
135          *
136          * @param array $contact contact to be unmarked for archival
137          * @return null
138          */
139         public static function unmarkForArchival(array $contact)
140         {
141                 $condition = array('`id` = ? AND (`term-date` > ? OR `archive`)', $contact[`id`], NULL_DATE);
142                 $exists = dba::exists('contact', $condition);
143
144                 // We don't need to update, we never marked this contact for archival
145                 if (!$exists) {
146                         return;
147                 }
148
149                 // It's a miracle. Our dead contact has inexplicably come back to life.
150                 $fields = array('term-date' => NULL_DATE, 'archive' => false);
151                 dba::update('contact', $fields, array('id' => $contact['id']));
152
153                 if ($contact['url'] != '') {
154                         dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
155                 }
156         }
157
158         /**
159          * @brief Get contact data for a given profile link
160          *
161          * The function looks at several places (contact table and gcontact table) for the contact
162          * It caches its result for the same script execution to prevent duplicate calls
163          *
164          * @param string $url     The profile link
165          * @param int    $uid     User id
166          * @param array  $default If not data was found take this data as default value
167          *
168          * @return array Contact data
169          */
170         public static function getDetailsByURL($url, $uid = -1, array $default = [])
171         {
172                 static $cache = array();
173
174                 if ($url == '') {
175                         return $default;
176                 }
177
178                 if ($uid == -1) {
179                         $uid = local_user();
180                 }
181
182                 if (isset($cache[$url][$uid])) {
183                         return $cache[$url][$uid];
184                 }
185
186                 $ssl_url = str_replace('http://', 'https://', $url);
187
188                 // Fetch contact data from the contact table for the given user
189                 $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`,
190                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
191                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
192                 $r = dba::inArray($s);
193
194                 // Fetch contact data from the contact table for the given user, checking with the alias
195                 if (!DBM::is_result($r)) {
196                         $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`,
197                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
198                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
199                         $r = dba::inArray($s);
200                 }
201
202                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
203                 if (!DBM::is_result($r)) {
204                         $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`,
205                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
206                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
207                         $r = dba::inArray($s);
208                 }
209
210                 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
211                 if (!DBM::is_result($r)) {
212                         $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`,
213                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
214                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
215                         $r = dba::inArray($s);
216                 }
217
218                 // Fetch the data from the gcontact table
219                 if (!DBM::is_result($r)) {
220                         $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`,
221                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
222                         FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
223                         $r = dba::inArray($s);
224                 }
225
226                 if (DBM::is_result($r)) {
227                         // If there is more than one entry we filter out the connector networks
228                         if (count($r) > 1) {
229                                 foreach ($r as $id => $result) {
230                                         if ($result["network"] == NETWORK_STATUSNET) {
231                                                 unset($r[$id]);
232                                         }
233                                 }
234                         }
235
236                         $profile = array_shift($r);
237
238                         // "bd" always contains the upcoming birthday of a contact.
239                         // "birthday" might contain the birthday including the year of birth.
240                         if ($profile["birthday"] > '0001-01-01') {
241                                 $bd_timestamp = strtotime($profile["birthday"]);
242                                 $month = date("m", $bd_timestamp);
243                                 $day = date("d", $bd_timestamp);
244
245                                 $current_timestamp = time();
246                                 $current_year = date("Y", $current_timestamp);
247                                 $current_month = date("m", $current_timestamp);
248                                 $current_day = date("d", $current_timestamp);
249
250                                 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
251                                 $current = $current_year . "-" . $current_month . "-" . $current_day;
252
253                                 if ($profile["bd"] < $current) {
254                                         $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
255                                 }
256                         } else {
257                                 $profile["bd"] = '0001-01-01';
258                         }
259                 } else {
260                         $profile = $default;
261                 }
262
263                 if (($profile["photo"] == "") && isset($default["photo"])) {
264                         $profile["photo"] = $default["photo"];
265                 }
266
267                 if (($profile["name"] == "") && isset($default["name"])) {
268                         $profile["name"] = $default["name"];
269                 }
270
271                 if (($profile["network"] == "") && isset($default["network"])) {
272                         $profile["network"] = $default["network"];
273                 }
274
275                 if (($profile["thumb"] == "") && isset($profile["photo"])) {
276                         $profile["thumb"] = $profile["photo"];
277                 }
278
279                 if (($profile["micro"] == "") && isset($profile["thumb"])) {
280                         $profile["micro"] = $profile["thumb"];
281                 }
282
283                 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
284                         && in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))
285                 ) {
286                         Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
287                 }
288
289                 // Show contact details of Diaspora contacts only if connected
290                 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
291                         $profile["location"] = "";
292                         $profile["about"] = "";
293                         $profile["gender"] = "";
294                         $profile["birthday"] = '0001-01-01';
295                 }
296
297                 $cache[$url][$uid] = $profile;
298
299                 return $profile;
300         }
301
302         /**
303          * @brief Get contact data for a given address
304          *
305          * The function looks at several places (contact table and gcontact table) for the contact
306          *
307          * @param string $addr The profile link
308          * @param int    $uid  User id
309          *
310          * @return array Contact data
311          */
312         public static function getDetailsByAddr($addr, $uid = -1)
313         {
314                 static $cache = array();
315
316                 if ($addr == '') {
317                         return array();
318                 }
319
320                 if ($uid == -1) {
321                         $uid = local_user();
322                 }
323
324                 // Fetch contact data from the contact table for the given user
325                 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
326                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
327                 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d", dbesc($addr), intval($uid));
328
329                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
330                 if (!DBM::is_result($r))
331                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
332                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
333                         FROM `contact` WHERE `addr` = '%s' AND `uid` = 0", dbesc($addr));
334
335                 // Fetch the data from the gcontact table
336                 if (!DBM::is_result($r))
337                         $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`,
338                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
339                         FROM `gcontact` WHERE `addr` = '%s'", dbesc($addr));
340
341                 if (!DBM::is_result($r)) {
342                         $data = Probe::uri($addr);
343
344                         $profile = self::getDetailsByURL($data['url'], $uid);
345                 } else {
346                         $profile = $r[0];
347                 }
348
349                 return $profile;
350         }
351
352         /**
353          * @brief Returns the data array for the photo menu of a given contact
354          *
355          * @param array $contact contact
356          * @param int   $uid     optional, default 0
357          * @return array
358          */
359         public static function photoMenu(array $contact, $uid = 0)
360         {
361                 // @todo Unused, to be removed
362                 $a = get_app();
363
364                 $contact_url = '';
365                 $pm_url = '';
366                 $status_link = '';
367                 $photos_link = '';
368                 $posts_link = '';
369                 $contact_drop_link = '';
370                 $poke_link = '';
371
372                 if ($uid == 0) {
373                         $uid = local_user();
374                 }
375
376                 if ($contact['uid'] != $uid) {
377                         if ($uid == 0) {
378                                 $profile_link = zrl($contact['url']);
379                                 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
380
381                                 return $menu;
382                         }
383
384                         $r = dba::select('contact', array(), array('nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid), array('limit' => 1));
385                         if ($r) {
386                                 return self::photoMenu($r, $uid);
387                         } else {
388                                 $profile_link = zrl($contact['url']);
389                                 $connlnk = 'follow/?url=' . $contact['url'];
390                                 $menu = array(
391                                         'profile' => array(t('View Profile'), $profile_link, true),
392                                         'follow' => array(t('Connect/Follow'), $connlnk, true)
393                                 );
394
395                                 return $menu;
396                         }
397                 }
398
399                 $sparkle = false;
400                 if ($contact['network'] === NETWORK_DFRN) {
401                         $sparkle = true;
402                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
403                 } else {
404                         $profile_link = $contact['url'];
405                 }
406
407                 if ($profile_link === 'mailbox') {
408                         $profile_link = '';
409                 }
410
411                 if ($sparkle) {
412                         $status_link = $profile_link . '?url=status';
413                         $photos_link = $profile_link . '?url=photos';
414                         $profile_link = $profile_link . '?url=profile';
415                 }
416
417                 if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
418                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
419                 }
420
421                 if ($contact['network'] == NETWORK_DFRN) {
422                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
423                 }
424
425                 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
426
427                 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
428                 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
429
430                 /**
431                  * Menu array:
432                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
433                  */
434                 $menu = array(
435                         'status' => array(t("View Status"), $status_link, true),
436                         'profile' => array(t("View Profile"), $profile_link, true),
437                         'photos' => array(t("View Photos"), $photos_link, true),
438                         'network' => array(t("Network Posts"), $posts_link, false),
439                         'edit' => array(t("View Contact"), $contact_url, false),
440                         'drop' => array(t("Drop Contact"), $contact_drop_link, false),
441                         'pm' => array(t("Send PM"), $pm_url, false),
442                         'poke' => array(t("Poke"), $poke_link, false),
443                 );
444
445
446                 $args = array('contact' => $contact, 'menu' => &$menu);
447
448                 call_hooks('contact_photo_menu', $args);
449
450                 $menucondensed = array();
451
452                 foreach ($menu as $menuname => $menuitem) {
453                         if ($menuitem[1] != '') {
454                                 $menucondensed[$menuname] = $menuitem;
455                         }
456                 }
457
458                 return $menucondensed;
459         }
460
461         /**
462          * @brief Returns ungrouped contact count or list for user
463          *
464          * Returns either the total number of ungrouped contacts for the given user
465          * id or a paginated list of ungrouped contacts.
466          *
467          * @param int $uid   uid
468          * @param int $start optional, default 0
469          * @param int $count optional, default 0
470          *
471          * @return array
472          */
473         public static function getUngroupedList($uid, $start = 0, $count = 0)
474         {
475                 if (!$count) {
476                         $r = q(
477                                 "SELECT COUNT(*) AS `total`
478                                  FROM `contact`
479                                  WHERE `uid` = %d
480                                  AND NOT `self`
481                                  AND NOT `blocked`
482                                  AND NOT `pending`
483                                  AND `id` NOT IN (
484                                         SELECT DISTINCT(`contact-id`)
485                                         FROM `group_member`
486                                         WHERE `uid` = %d
487                                 )", intval($uid), intval($uid)
488                         );
489
490                         return $r;
491                 }
492
493                 $r = q(
494                         "SELECT *
495                         FROM `contact`
496                         WHERE `uid` = %d
497                         AND NOT `self`
498                         AND NOT `blocked`
499                         AND NOT `pending`
500                         AND `id` NOT IN (
501                                 SELECT DISTINCT(`contact-id`)
502                                 FROM `group_member` WHERE `uid` = %d
503                         )
504                         LIMIT %d, %d", intval($uid), intval($uid), intval($start), intval($count)
505                 );
506                 return $r;
507         }
508
509         /**
510          * @brief Fetch the contact id for a given url and user
511          *
512          * First lookup in the contact table to find a record matching either `url`, `nurl`,
513          * `addr` or `alias`.
514          *
515          * If there's no record and we aren't looking for a public contact, we quit.
516          * If there's one, we check that it isn't time to update the picture else we
517          * directly return the found contact id.
518          *
519          * Second, we probe the provided $url wether it's http://server.tld/profile or
520          * nick@server.tld. We quit if we can't get any info back.
521          *
522          * Third, we create the contact record if it doesn't exist
523          *
524          * Fourth, we update the existing record with the new data (avatar, alias, nick)
525          * if there's any updates
526          *
527          * @param string  $url       Contact URL
528          * @param integer $uid       The user id for the contact (0 = public contact)
529          * @param boolean $no_update Don't update the contact
530          *
531          * @return integer Contact ID
532          */
533         public static function getIdForURL($url, $uid = 0, $no_update = false)
534         {
535                 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
536
537                 $contact_id = 0;
538
539                 if ($url == '') {
540                         return 0;
541                 }
542
543                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
544                 // We first try the nurl (http://server.tld/nick), most common case
545                 $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
546
547                 // Then the addr (nick@server.tld)
548                 if (!DBM::is_result($contact)) {
549                         $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
550                 }
551
552                 // Then the alias (which could be anything)
553                 if (!DBM::is_result($contact)) {
554                         // The link could be provided as http although we stored it as https
555                         $ssl_url = str_replace('http://', 'https://', $url);
556                         $r = dba::select('contact', array('id', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
557                         $contact = dba::fetch($r);
558                         dba::close($r);
559                 }
560
561                 if (DBM::is_result($contact)) {
562                         $contact_id = $contact["id"];
563
564                         // Update the contact every 7 days
565                         $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
566
567                         // We force the update if the avatar is empty
568                         if ($contact['avatar'] == '') {
569                                 $update_contact = true;
570                         }
571
572                         if (!$update_contact || $no_update) {
573                                 return $contact_id;
574                         }
575                 } elseif ($uid != 0) {
576                         // Non-existing user-specific contact, exiting
577                         return 0;
578                 }
579
580                 $data = Probe::uri($url, "", $uid);
581
582                 // Last try in gcontact for unsupported networks
583                 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
584                         if ($uid != 0) {
585                                 return 0;
586                         }
587
588                         // Get data from the gcontact table
589                         $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'), array('nurl' => normalise_link($url)), array('limit' => 1));
590                         if (!DBM::is_result($gcontacts)) {
591                                 return 0;
592                         }
593
594                         $data = array_merge($data, $gcontacts);
595                 }
596
597                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
598                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
599                 }
600
601                 $url = $data["url"];
602                 if (!$contact_id) {
603                         dba::insert(
604                                 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
605                                 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
606                                 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
607                                 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
608                                 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
609                                 'network' => $data["network"], 'pubkey' => $data["pubkey"],
610                                 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
611                                 'batch' => $data["batch"], 'request' => $data["request"],
612                                 'confirm' => $data["confirm"], 'poco' => $data["poco"],
613                                 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
614                                 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
615                                 'readonly' => 0, 'pending' => 0)
616                         );
617
618                         $s = dba::select('contact', array('id'), array('nurl' => normalise_link($data["url"]), 'uid' => $uid), array('order' => array('id'), 'limit' => 2));
619                         $contacts = dba::inArray($s);
620                         if (!DBM::is_result($contacts)) {
621                                 return 0;
622                         }
623
624                         $contact_id = $contacts[0]["id"];
625
626                         // Update the newly created contact from data in the gcontact table
627                         $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'), array('nurl' => normalise_link($data["url"])), array('limit' => 1));
628                         if (DBM::is_result($gcontact)) {
629                                 // Only use the information when the probing hadn't fetched these values
630                                 if ($data['keywords'] != '') {
631                                         unset($gcontact['keywords']);
632                                 }
633                                 if ($data['location'] != '') {
634                                         unset($gcontact['location']);
635                                 }
636                                 if ($data['about'] != '') {
637                                         unset($gcontact['about']);
638                                 }
639                                 dba::update('contact', $gcontact, array('id' => $contact_id));
640                         }
641
642                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
643                                 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
644                                         normalise_link($data["url"]), $contact_id));
645                         }
646                 }
647
648                 require_once 'include/Photo.php';
649
650                 update_contact_avatar($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 }