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