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