]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
Merge pull request #3112 from Quix0r/rewrites/coding-convention
[friendica.git] / include / Contact.php
1 <?php
2
3 // Included here for completeness, but this is a very dangerous operation.
4 // It is the caller's responsibility to confirm the requestor's intent and
5 // authorisation to do this.
6
7 function user_remove($uid) {
8         if (! $uid)
9                 return;
10         logger('Removing user: ' . $uid);
11
12         $r = q("select * from user where uid = %d limit 1", intval($uid));
13
14         call_hooks('remove_user',$r[0]);
15
16         // save username (actually the nickname as it is guaranteed
17         // unique), so it cannot be re-registered in the future.
18
19         q("insert into userd ( username ) values ( '%s' )",
20                 $r[0]['nickname']
21         );
22
23         /// @todo Should be done in a background job since this likely will run into a time out
24         // don't delete yet, will be done later when contacts have deleted my stuff
25         // q("DELETE FROM `contact` WHERE `uid` = %d", intval($uid));
26         q("DELETE FROM `gcign` WHERE `uid` = %d", intval($uid));
27         q("DELETE FROM `group` WHERE `uid` = %d", intval($uid));
28         q("DELETE FROM `group_member` WHERE `uid` = %d", intval($uid));
29         q("DELETE FROM `intro` WHERE `uid` = %d", intval($uid));
30         q("DELETE FROM `event` WHERE `uid` = %d", intval($uid));
31         q("DELETE FROM `item` WHERE `uid` = %d", intval($uid));
32         q("DELETE FROM `item_id` WHERE `uid` = %d", intval($uid));
33         q("DELETE FROM `mail` WHERE `uid` = %d", intval($uid));
34         q("DELETE FROM `mailacct` WHERE `uid` = %d", intval($uid));
35         q("DELETE FROM `manage` WHERE `uid` = %d", intval($uid));
36         q("DELETE FROM `notify` WHERE `uid` = %d", intval($uid));
37         q("DELETE FROM `photo` WHERE `uid` = %d", intval($uid));
38         q("DELETE FROM `attach` WHERE `uid` = %d", intval($uid));
39         q("DELETE FROM `profile` WHERE `uid` = %d", intval($uid));
40         q("DELETE FROM `profile_check` WHERE `uid` = %d", intval($uid));
41         q("DELETE FROM `pconfig` WHERE `uid` = %d", intval($uid));
42         q("DELETE FROM `search` WHERE `uid` = %d", intval($uid));
43         q("DELETE FROM `spam` WHERE `uid` = %d", intval($uid));
44         // don't delete yet, will be done later when contacts have deleted my stuff
45         // q("DELETE FROM `user` WHERE `uid` = %d", intval($uid));
46         q("UPDATE `user` SET `account_removed` = 1, `account_expires_on` = UTC_TIMESTAMP() WHERE `uid` = %d", intval($uid));
47         proc_run(PRIORITY_HIGH, "include/notifier.php", "removeme", $uid);
48
49         // Send an update to the directory
50         proc_run(PRIORITY_LOW, "include/directory.php", $r[0]['url']);
51
52         if ($uid == local_user()) {
53                 unset($_SESSION['authenticated']);
54                 unset($_SESSION['uid']);
55                 goaway(App::get_baseurl());
56         }
57 }
58
59
60 function contact_remove($id) {
61
62         // We want just to make sure that we don't delete our "self" contact
63         $r = q("SELECT `uid` FROM `contact` WHERE `id` = %d AND NOT `self` LIMIT 1",
64                 intval($id)
65         );
66         if (!dbm::is_result($r) || !intval($r[0]['uid'])) {
67                 return;
68         }
69
70         $archive = get_pconfig($r[0]['uid'], 'system','archive_removed_contacts');
71         if ($archive) {
72                 q("update contact set `archive` = 1, `network` = 'none', `writable` = 0 where id = %d",
73                         intval($id)
74                 );
75                 return;
76         }
77
78         q("DELETE FROM `contact` WHERE `id` = %d", intval($id));
79
80         // Delete the rest in the background
81         proc_run(PRIORITY_LOW, 'include/remove_contact.php', $id);
82 }
83
84
85 // sends an unfriend message. Does not remove the contact
86
87 function terminate_friendship($user,$self,$contact) {
88
89         /// @TODO Get rid of this, include/datetime.php should care about it by itself
90         $a = get_app();
91
92         require_once('include/datetime.php');
93
94         if ($contact['network'] === NETWORK_OSTATUS) {
95
96                 require_once('include/ostatus.php');
97
98                 // create an unfollow slap
99                 $item = array();
100                 $item['verb'] = NAMESPACE_OSTATUS."/unfollow";
101                 $item['follow'] = $contact["url"];
102                 $slap = ostatus::salmon($item, $user);
103
104                 if ((x($contact,'notify')) && (strlen($contact['notify']))) {
105                         require_once('include/salmon.php');
106                         slapper($user,$contact['notify'],$slap);
107                 }
108         } elseif ($contact['network'] === NETWORK_DIASPORA) {
109                 require_once('include/diaspora.php');
110                 Diaspora::send_unshare($user,$contact);
111         } elseif ($contact['network'] === NETWORK_DFRN) {
112                 require_once('include/dfrn.php');
113                 dfrn::deliver($user,$contact,'placeholder', 1);
114         }
115
116 }
117
118
119 // Contact has refused to recognise us as a friend. We will start a countdown.
120 // If they still don't recognise us in 32 days, the relationship is over,
121 // and we won't waste any more time trying to communicate with them.
122 // This provides for the possibility that their database is temporarily messed
123 // up or some other transient event and that there's a possibility we could recover from it.
124
125 function mark_for_death(array $contact) {
126
127         if ($contact['archive']) {
128                 return;
129         }
130
131         /// @TODO Comparison of strings this way may lead to bugs/incompatibility, better switch to DateTime
132         if ($contact['term-date'] <= NULL_DATE) {
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(NULL_DATE),
191                 intval($contact['id'])
192         );
193
194         if ($contact['url'] != '') {
195                 q("UPDATE `contact` SET `term-date` = '%s' WHERE `nurl` = '%s'",
196                         dbesc(NULL_DATE),
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                 require_once('include/Probe.php');
359                 $data = Probe::uri($addr);
360
361                 $profile = get_contact_details_by_url($data['url'], $uid);
362         } else {
363                 $profile = $r[0];
364         }
365
366         return $profile;
367 }
368
369 if (! function_exists('contact_photo_menu')) {
370 function contact_photo_menu($contact, $uid = 0)
371 {
372         $a = get_app();
373
374         $contact_url = '';
375         $pm_url = '';
376         $status_link = '';
377         $photos_link = '';
378         $posts_link = '';
379         $contact_drop_link = '';
380         $poke_link = '';
381
382         if ($uid == 0) {
383                 $uid = local_user();
384         }
385
386         if ($contact['uid'] != $uid) {
387                 if ($uid == 0) {
388                         $profile_link = zrl($contact['url']);
389                         $menu = Array('profile' => array(t('View Profile'), $profile_link, true));
390
391                         return $menu;
392                 }
393
394                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `network` = '%s' AND `uid` = %d",
395                         dbesc($contact['nurl']), dbesc($contact['network']), intval($uid));
396                 if ($r) {
397                         return contact_photo_menu($r[0], $uid);
398                 } else {
399                         $profile_link = zrl($contact['url']);
400                         $connlnk = 'follow/?url='.$contact['url'];
401                         $menu = array(
402                                 'profile' => array(t('View Profile'), $profile_link, true),
403                                 'follow' => array(t('Connect/Follow'), $connlnk, true)
404                         );
405
406                         return $menu;
407                 }
408         }
409
410         $sparkle = false;
411         if ($contact['network'] === NETWORK_DFRN) {
412                 $sparkle = true;
413                 $profile_link = App::get_baseurl() . '/redir/' . $contact['id'];
414         } else {
415                 $profile_link = $contact['url'];
416         }
417
418         if ($profile_link === 'mailbox') {
419                 $profile_link = '';
420         }
421
422         if ($sparkle) {
423                 $status_link = $profile_link . '?url=status';
424                 $photos_link = $profile_link . '?url=photos';
425                 $profile_link = $profile_link . '?url=profile';
426         }
427
428         if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
429                 $pm_url = App::get_baseurl() . '/message/new/' . $contact['id'];
430         }
431
432         if ($contact['network'] == NETWORK_DFRN) {
433                 $poke_link = App::get_baseurl() . '/poke/?f=&c=' . $contact['id'];
434         }
435
436         $contact_url = App::get_baseurl() . '/contacts/' . $contact['id'];
437
438         $posts_link = App::get_baseurl() . '/contacts/' . $contact['id'] . '/posts';
439         $contact_drop_link = App::get_baseurl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
440
441         /**
442          * menu array:
443          * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
444          */
445         $menu = array(
446                 'status' => array(t("View Status"), $status_link, true),
447                 'profile' => array(t("View Profile"), $profile_link, true),
448                 'photos' => array(t("View Photos"), $photos_link, true),
449                 'network' => array(t("Network Posts"), $posts_link, false),
450                 'edit' => array(t("View Contact"), $contact_url, false),
451                 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
452                 'pm' => array(t("Send PM"), $pm_url, false),
453                 'poke' => array(t("Poke"), $poke_link, false),
454         );
455
456
457         $args = array('contact' => $contact, 'menu' => &$menu);
458
459         call_hooks('contact_photo_menu', $args);
460
461         $menucondensed = array();
462
463         foreach ($menu AS $menuname => $menuitem) {
464                 if ($menuitem[1] != '') {
465                         $menucondensed[$menuname] = $menuitem;
466                 }
467         }
468
469         return $menucondensed;
470 }}
471
472
473 function random_profile() {
474         $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
475                                 AND `last_contact` >= `last_failure`
476                                 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
477                         ORDER BY rand() LIMIT 1",
478                 dbesc(NETWORK_DFRN));
479
480         if (dbm::is_result($r))
481                 return dirname($r[0]['url']);
482         return '';
483 }
484
485
486 function contacts_not_grouped($uid,$start = 0,$count = 0) {
487
488         if (! $count) {
489                 $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) ",
490                         intval($uid),
491                         intval($uid)
492                 );
493
494                 return $r;
495
496
497         }
498
499         $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",
500                 intval($uid),
501                 intval($uid),
502                 intval($start),
503                 intval($count)
504         );
505
506         return $r;
507 }
508
509 /**
510  * @brief Fetch the contact id for a given url and user
511  *
512  * First lookup in the contact table to find a record matching either `url`, `nurl`,
513  * `addr` or `alias`.
514  *
515  * If there's no record and we aren't looking for a public contact, we quit.
516  * If there's one, we check that it isn't time to update the picture else we
517  * directly return the found contact id.
518  *
519  * Second, we probe the provided $url wether it's http://server.tld/profile or
520  * nick@server.tld. We quit if we can't get any info back.
521  *
522  * Third, we create the contact record if it doesn't exist
523  *
524  * Fourth, we update the existing record with the new data (avatar, alias, nick)
525  * if there's any updates
526  *
527  * @param string $url Contact URL
528  * @param integer $uid The user id for the contact (0 = public contact)
529  * @param boolean $no_update Don't update the contact
530  *
531  * @return integer Contact ID
532  */
533 function get_contact($url, $uid = 0, $no_update = false) {
534         logger("Get contact data for url ".$url." and user ".$uid." - ".App::callstack(), LOGGER_DEBUG);;
535
536         $data = array();
537         $contact_id = 0;
538
539         // We first try the nurl (http://server.tld/nick), most common case
540         $contacts = q("SELECT `id`, `avatar-date` FROM `contact`
541                                         WHERE `nurl` = '%s'
542                                         AND `uid` = %d",
543                         dbesc(normalise_link($url)),
544                         intval($uid));
545
546
547         // Then the addr (nick@server.tld)
548         if (! dbm::is_result($contacts)) {
549                 $contacts = q("SELECT `id`, `avatar-date` FROM `contact`
550                                         WHERE `addr` = '%s'
551                                         AND `uid` = %d",
552                         dbesc($url),
553                         intval($uid));
554         }
555
556         // Then the alias (which could be anything)
557         if (! dbm::is_result($contacts)) {
558                 $contacts = q("SELECT `id`, `avatar-date` FROM `contact`
559                                         WHERE `alias` IN ('%s', '%s')
560                                         AND `uid` = %d",
561                         dbesc($url),
562                         dbesc(normalise_link($url)),
563                         intval($uid));
564         }
565
566         if (dbm::is_result($contacts)) {
567                 $contact_id = $contacts[0]["id"];
568
569                 // Update the contact every 7 days
570                 $update_photo = ($contacts[0]['avatar-date'] < datetime_convert('','','now -7 days'));
571
572                 if (!$update_photo OR $no_update) {
573                         return $contact_id;
574                 }
575         } elseif ($uid != 0) {
576                 // Non-existing user-specific contact, exiting
577                 return 0;
578         }
579
580         require_once('include/Probe.php');
581         $data = Probe::uri($url);
582
583         // Last try in gcontact for unsupported networks
584         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO))) {
585                 if ($uid != 0) {
586                         return 0;
587                 }
588
589                 // Get data from the gcontact table
590                 $gcontacts = q("SELECT `name`, `nick`, `url`, `photo`, `addr`, `alias`, `network` FROM `gcontact` WHERE `nurl` = '%s'",
591                          dbesc(normalise_link($url)));
592                 if (!$gcontacts) {
593                         return 0;
594                 }
595
596                 $data = $gcontacts[0];
597         }
598
599         $url = $data["url"];
600
601         if (!$contact_id) {
602                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
603                                         `name`, `nick`, `photo`, `network`, `pubkey`, `rel`, `priority`,
604                                         `batch`, `request`, `confirm`, `poco`, `name-date`, `uri-date`,
605                                         `writable`, `blocked`, `readonly`, `pending`)
606                                         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)",
607                         intval($uid),
608                         dbesc(datetime_convert()),
609                         dbesc($data["url"]),
610                         dbesc(normalise_link($data["url"])),
611                         dbesc($data["addr"]),
612                         dbesc($data["alias"]),
613                         dbesc($data["notify"]),
614                         dbesc($data["poll"]),
615                         dbesc($data["name"]),
616                         dbesc($data["nick"]),
617                         dbesc($data["photo"]),
618                         dbesc($data["network"]),
619                         dbesc($data["pubkey"]),
620                         intval(CONTACT_IS_SHARING),
621                         intval($data["priority"]),
622                         dbesc($data["batch"]),
623                         dbesc($data["request"]),
624                         dbesc($data["confirm"]),
625                         dbesc($data["poco"]),
626                         dbesc(datetime_convert()),
627                         dbesc(datetime_convert())
628                 );
629
630                 $contacts = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
631                                 dbesc(normalise_link($data["url"])),
632                                 intval($uid));
633                 if (!dbm::is_result($contacts)) {
634                         return 0;
635                 }
636
637                 $contact_id = $contacts[0]["id"];
638
639                 // Update the newly created contact from data in the gcontact table
640                 $gcontacts = q("SELECT `location`, `about`, `keywords`, `gender` FROM `gcontact` WHERE `nurl` = '%s'",
641                          dbesc(normalise_link($data["url"])));
642                 if (dbm::is_result($gcontacts)) {
643                         logger("Update contact " . $data["url"] . ' from gcontact');
644                         q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d",
645                                 dbesc($gcontacts[0]["location"]), dbesc($gcontacts[0]["about"]), dbesc($gcontacts[0]["keywords"]),
646                                 dbesc($gcontacts[0]["gender"]), intval($contact_id));
647                 }
648         }
649
650         if (count($contacts) > 1 AND $uid == 0 AND $contact_id != 0 AND $url != "") {
651                 q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d AND NOT `self`",
652                         dbesc(normalise_link($url)),
653                         intval($contact_id));
654         }
655
656         require_once "Photo.php";
657
658         update_contact_avatar($data["photo"], $uid, $contact_id);
659
660         $contacts = q("SELECT `addr`, `alias`, `name`, `nick` FROM `contact` WHERE `id` = %d", intval($contact_id));
661
662         // This condition should always be true
663         if (!dbm::is_result($contacts)) {
664                 return $contact_id;
665         }
666
667         // Only update if there had something been changed
668         if ($data["addr"] != $contacts[0]["addr"] OR
669                 $data["alias"] != $contacts[0]["alias"] OR
670                 $data["name"] != $contacts[0]["name"] OR
671                 $data["nick"] != $contacts[0]["nick"]) {
672                 q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
673                         `name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
674                         dbesc($data["addr"]),
675                         dbesc($data["alias"]),
676                         dbesc($data["name"]),
677                         dbesc($data["nick"]),
678                         dbesc(datetime_convert()),
679                         dbesc(datetime_convert()),
680                         intval($contact_id)
681                 );
682         }
683
684         return $contact_id;
685 }
686
687 /**
688  * @brief Returns posts from a given gcontact
689  *
690  * @param App $a argv application class
691  * @param int $gcontact_id Global contact
692  *
693  * @return string posts in HTML
694  */
695 function posts_from_gcontact(App $a, $gcontact_id) {
696
697         require_once('include/conversation.php');
698
699         // There are no posts with "uid = 0" with connector networks
700         // This speeds up the query a lot
701         $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
702         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
703                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
704         else
705                 $sql = "`item`.`uid` = %d";
706
707         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
708                         `author-name` AS `name`, `owner-avatar` AS `photo`,
709                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
710                 FROM `item`
711                 WHERE `gcontact-id` = %d AND $sql AND
712                         NOT `deleted` AND NOT `moderated` AND `visible`
713                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
714                 intval($gcontact_id),
715                 intval(local_user()),
716                 intval($a->pager['start']),
717                 intval($a->pager['itemspage'])
718         );
719
720         $o = conversation($a, $r, 'community', false);
721
722         $o .= alt_pager($a, count($r));
723
724         return $o;
725 }
726 /**
727  * @brief Returns posts from a given contact url
728  *
729  * @param App $a argv application class
730  * @param string $contact_url Contact URL
731  *
732  * @return string posts in HTML
733  */
734 function posts_from_contact_url(App $a, $contact_url) {
735
736         require_once('include/conversation.php');
737
738         // There are no posts with "uid = 0" with connector networks
739         // This speeds up the query a lot
740         $r = q("SELECT `network`, `id` AS `author-id` FROM `contact`
741                 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
742                 dbesc(normalise_link($contact_url)));
743         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
744                 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND `item`.`private`))";
745         } else {
746                 $sql = "`item`.`uid` = %d";
747         }
748
749         if (!dbm::is_result($r)) {
750                 return '';
751         }
752
753         $author_id = intval($r[0]["author-id"]);
754
755         $r = q(item_query()." AND `item`.`author-id` = %d AND ".$sql.
756                 " ORDER BY `item`.`created` DESC LIMIT %d, %d",
757                 intval($author_id),
758                 intval(local_user()),
759                 intval($a->pager['start']),
760                 intval($a->pager['itemspage'])
761         );
762
763         $o = conversation($a, $r, 'community', false);
764
765         $o .= alt_pager($a, count($r));
766
767         return $o;
768 }
769
770 /**
771  * @brief Returns a formatted location string from the given profile array
772  *
773  * @param array $profile Profile array (Generated from the "profile" table)
774  *
775  * @return string Location string
776  */
777 function formatted_location($profile) {
778         $location = '';
779
780         if ($profile['locality'])
781                 $location .= $profile['locality'];
782
783         if ($profile['region'] AND ($profile['locality'] != $profile['region'])) {
784                 if ($location)
785                         $location .= ', ';
786
787                 $location .= $profile['region'];
788         }
789
790         if ($profile['country-name']) {
791                 if ($location)
792                         $location .= ', ';
793
794                 $location .= $profile['country-name'];
795         }
796
797         return $location;
798 }
799
800 /**
801  * @brief Returns the account type name
802  *
803  * The function can be called with either the user or the contact array
804  *
805  * @param array $contact contact or user array
806  */
807 function account_type($contact) {
808
809         // There are several fields that indicate that the contact or user is a forum
810         // "page-flags" is a field in the user table,
811         // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
812         // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
813         if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
814                 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
815                 || (isset($contact['forum']) && intval($contact['forum']))
816                 || (isset($contact['prv']) && intval($contact['prv']))
817                 || (isset($contact['community']) && intval($contact['community'])))
818                 $type = ACCOUNT_TYPE_COMMUNITY;
819         else
820                 $type = ACCOUNT_TYPE_PERSON;
821
822         // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
823         if (isset($contact["contact-type"]))
824                 $type = $contact["contact-type"];
825         if (isset($contact["account-type"]))
826                 $type = $contact["account-type"];
827
828         switch($type) {
829                 case ACCOUNT_TYPE_ORGANISATION:
830                         $account_type = t("Organisation");
831                         break;
832                 case ACCOUNT_TYPE_NEWS:
833                         $account_type = t('News');
834                         break;
835                 case ACCOUNT_TYPE_COMMUNITY:
836                         $account_type = t("Forum");
837                         break;
838                 default:
839                         $account_type = "";
840                         break;
841         }
842
843         return $account_type;
844 }
845 ?>