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