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