]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
d635ee872558c649ce49970e97bf11db9f7795f4
[friendica.git] / include / Contact.php
1 <?php
2
3 use Friendica\App;
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'] <= 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 ($url == '') {
218                 return $default;
219         }
220
221         if ($uid == -1) {
222                 $uid = local_user();
223         }
224
225         if (isset($cache[$url][$uid])) {
226                 return $cache[$url][$uid];
227         }
228
229         // Fetch contact data from the contact table for the given user
230         $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
231                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
232                 FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
233                         dbesc(normalise_link($url)), intval($uid));
234
235         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
236         if (!dbm::is_result($r))
237                 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
238                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
239                         FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
240                                 dbesc(normalise_link($url)));
241
242         // Fetch the data from the gcontact table
243         if (!dbm::is_result($r))
244                 $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`,
245                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
246                         FROM `gcontact` WHERE `nurl` = '%s'",
247                                 dbesc(normalise_link($url)));
248
249         if (dbm::is_result($r)) {
250                 // If there is more than one entry we filter out the connector networks
251                 if (count($r) > 1) {
252                         foreach ($r AS $id => $result) {
253                                 if ($result["network"] == NETWORK_STATUSNET) {
254                                         unset($r[$id]);
255                                 }
256                         }
257                 }
258
259                 $profile = array_shift($r);
260
261                 // "bd" always contains the upcoming birthday of a contact.
262                 // "birthday" might contain the birthday including the year of birth.
263                 if ($profile["birthday"] > '0001-01-01') {
264                         $bd_timestamp = strtotime($profile["birthday"]);
265                         $month = date("m", $bd_timestamp);
266                         $day = date("d", $bd_timestamp);
267
268                         $current_timestamp = time();
269                         $current_year = date("Y", $current_timestamp);
270                         $current_month = date("m", $current_timestamp);
271                         $current_day = date("d", $current_timestamp);
272
273                         $profile["bd"] = $current_year."-".$month."-".$day;
274                         $current = $current_year."-".$current_month."-".$current_day;
275
276                         if ($profile["bd"] < $current) {
277                                 $profile["bd"] = (++$current_year)."-".$month."-".$day;
278                         }
279                 } else {
280                         $profile["bd"] = '0001-01-01';
281                 }
282         } else {
283                 $profile = $default;
284         }
285
286         if (($profile["photo"] == "") AND isset($default["photo"])) {
287                 $profile["photo"] = $default["photo"];
288         }
289
290         if (($profile["name"] == "") AND isset($default["name"])) {
291                 $profile["name"] = $default["name"];
292         }
293
294         if (($profile["network"] == "") AND isset($default["network"])) {
295                 $profile["network"] = $default["network"];
296         }
297
298         if (($profile["thumb"] == "") AND isset($profile["photo"])) {
299                 $profile["thumb"] = $profile["photo"];
300         }
301
302         if (($profile["micro"] == "") AND isset($profile["thumb"])) {
303                 $profile["micro"] = $profile["thumb"];
304         }
305
306         if ((($profile["addr"] == "") OR ($profile["name"] == "")) AND ($profile["gid"] != 0) AND
307                 in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
308                 proc_run(PRIORITY_LOW, "include/update_gcontact.php", $profile["gid"]);
309         }
310
311         // Show contact details of Diaspora contacts only if connected
312         if (($profile["cid"] == 0) AND ($profile["network"] == NETWORK_DIASPORA)) {
313                 $profile["location"] = "";
314                 $profile["about"] = "";
315                 $profile["gender"] = "";
316                 $profile["birthday"] = '0001-01-01';
317         }
318
319         $cache[$url][$uid] = $profile;
320
321         return $profile;
322 }
323
324 /**
325  * @brief Get contact data for a given address
326  *
327  * The function looks at several places (contact table and gcontact table) for the contact
328  *
329  * @param string $addr The profile link
330  * @param int $uid User id
331  *
332  * @return array Contact data
333  */
334 function get_contact_details_by_addr($addr, $uid = -1) {
335         static $cache = array();
336
337         if ($addr == '') {
338                 return array();
339         }
340
341         if ($uid == -1) {
342                 $uid = local_user();
343         }
344
345         // Fetch contact data from the contact table for the given user
346         $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
347                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
348                 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
349                         dbesc($addr), intval($uid));
350
351         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
352         if (!dbm::is_result($r))
353                 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
354                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
355                         FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
356                                 dbesc($addr));
357
358         // Fetch the data from the gcontact table
359         if (!dbm::is_result($r))
360                 $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`,
361                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
362                         FROM `gcontact` WHERE `addr` = '%s'",
363                                 dbesc($addr));
364
365         if (!dbm::is_result($r)) {
366                 require_once('include/Probe.php');
367                 $data = Probe::uri($addr);
368
369                 $profile = get_contact_details_by_url($data['url'], $uid);
370         } else {
371                 $profile = $r[0];
372         }
373
374         return $profile;
375 }
376
377 if (! function_exists('contact_photo_menu')) {
378 function contact_photo_menu($contact, $uid = 0)
379 {
380         $a = get_app();
381
382         $contact_url = '';
383         $pm_url = '';
384         $status_link = '';
385         $photos_link = '';
386         $posts_link = '';
387         $contact_drop_link = '';
388         $poke_link = '';
389
390         if ($uid == 0) {
391                 $uid = local_user();
392         }
393
394         if ($contact['uid'] != $uid) {
395                 if ($uid == 0) {
396                         $profile_link = zrl($contact['url']);
397                         $menu = Array('profile' => array(t('View Profile'), $profile_link, true));
398
399                         return $menu;
400                 }
401
402                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `network` = '%s' AND `uid` = %d",
403                         dbesc($contact['nurl']), dbesc($contact['network']), intval($uid));
404                 if ($r) {
405                         return contact_photo_menu($r[0], $uid);
406                 } else {
407                         $profile_link = zrl($contact['url']);
408                         $connlnk = 'follow/?url='.$contact['url'];
409                         $menu = array(
410                                 'profile' => array(t('View Profile'), $profile_link, true),
411                                 'follow' => array(t('Connect/Follow'), $connlnk, true)
412                         );
413
414                         return $menu;
415                 }
416         }
417
418         $sparkle = false;
419         if ($contact['network'] === NETWORK_DFRN) {
420                 $sparkle = true;
421                 $profile_link = App::get_baseurl() . '/redir/' . $contact['id'];
422         } else {
423                 $profile_link = $contact['url'];
424         }
425
426         if ($profile_link === 'mailbox') {
427                 $profile_link = '';
428         }
429
430         if ($sparkle) {
431                 $status_link = $profile_link . '?url=status';
432                 $photos_link = $profile_link . '?url=photos';
433                 $profile_link = $profile_link . '?url=profile';
434         }
435
436         if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
437                 $pm_url = App::get_baseurl() . '/message/new/' . $contact['id'];
438         }
439
440         if ($contact['network'] == NETWORK_DFRN) {
441                 $poke_link = App::get_baseurl() . '/poke/?f=&c=' . $contact['id'];
442         }
443
444         $contact_url = App::get_baseurl() . '/contacts/' . $contact['id'];
445
446         $posts_link = App::get_baseurl() . '/contacts/' . $contact['id'] . '/posts';
447         $contact_drop_link = App::get_baseurl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
448
449         /**
450          * menu array:
451          * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
452          */
453         $menu = array(
454                 'status' => array(t("View Status"), $status_link, true),
455                 'profile' => array(t("View Profile"), $profile_link, true),
456                 'photos' => array(t("View Photos"), $photos_link, true),
457                 'network' => array(t("Network Posts"), $posts_link, false),
458                 'edit' => array(t("View Contact"), $contact_url, false),
459                 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
460                 'pm' => array(t("Send PM"), $pm_url, false),
461                 'poke' => array(t("Poke"), $poke_link, false),
462         );
463
464
465         $args = array('contact' => $contact, 'menu' => &$menu);
466
467         call_hooks('contact_photo_menu', $args);
468
469         $menucondensed = array();
470
471         foreach ($menu AS $menuname => $menuitem) {
472                 if ($menuitem[1] != '') {
473                         $menucondensed[$menuname] = $menuitem;
474                 }
475         }
476
477         return $menucondensed;
478 }}
479
480
481 function random_profile() {
482         $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
483                                 AND `last_contact` >= `last_failure`
484                                 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
485                         ORDER BY rand() LIMIT 1",
486                 dbesc(NETWORK_DFRN));
487
488         if (dbm::is_result($r))
489                 return dirname($r[0]['url']);
490         return '';
491 }
492
493
494 function contacts_not_grouped($uid,$start = 0,$count = 0) {
495
496         if(! $count) {
497                 $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) ",
498                         intval($uid),
499                         intval($uid)
500                 );
501
502                 return $r;
503
504
505         }
506
507         $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",
508                 intval($uid),
509                 intval($uid),
510                 intval($start),
511                 intval($count)
512         );
513
514         return $r;
515 }
516
517 /**
518  * @brief Fetch the contact id for a given url and user
519  *
520  * First lookup in the contact table to find a record matching either `url`, `nurl`,
521  * `addr` or `alias`.
522  *
523  * If there's no record and we aren't looking for a public contact, we quit.
524  * If there's one, we check that it isn't time to update the picture else we
525  * directly return the found contact id.
526  *
527  * Second, we probe the provided $url wether it's http://server.tld/profile or
528  * nick@server.tld. We quit if we can't get any info back.
529  *
530  * Third, we create the contact record if it doesn't exist
531  *
532  * Fourth, we update the existing record with the new data (avatar, alias, nick)
533  * if there's any updates
534  *
535  * @param string $url Contact URL
536  * @param integer $uid The user id for the contact (0 = public contact)
537  * @param boolean $no_update Don't update the contact
538  *
539  * @return integer Contact ID
540  */
541 function get_contact($url, $uid = 0, $no_update = false) {
542         logger("Get contact data for url ".$url." and user ".$uid." - ".App::callstack(), LOGGER_DEBUG);;
543
544         $data = array();
545         $contact_id = 0;
546
547         if ($url == '') {
548                 return 0;
549         }
550
551         // We first try the nurl (http://server.tld/nick), most common case
552         $contacts = q("SELECT `id`, `avatar-date` FROM `contact`
553                                         WHERE `nurl` = '%s'
554                                         AND `uid` = %d",
555                         dbesc(normalise_link($url)),
556                         intval($uid));
557
558
559         // Then the addr (nick@server.tld)
560         if (! dbm::is_result($contacts)) {
561                 $contacts = q("SELECT `id`, `avatar-date` FROM `contact`
562                                         WHERE `addr` = '%s'
563                                         AND `uid` = %d",
564                         dbesc($url),
565                         intval($uid));
566         }
567
568         // Then the alias (which could be anything)
569         if (! dbm::is_result($contacts)) {
570                 $contacts = q("SELECT `id`, `avatar-date` FROM `contact`
571                                         WHERE `alias` IN ('%s', '%s')
572                                         AND `uid` = %d",
573                         dbesc($url),
574                         dbesc(normalise_link($url)),
575                         intval($uid));
576         }
577
578         if (dbm::is_result($contacts)) {
579                 $contact_id = $contacts[0]["id"];
580
581                 // Update the contact every 7 days
582                 $update_photo = ($contacts[0]['avatar-date'] < datetime_convert('','','now -7 days'));
583
584                 if (!$update_photo OR $no_update) {
585                         return $contact_id;
586                 }
587         } elseif ($uid != 0) {
588                 // Non-existing user-specific contact, exiting
589                 return 0;
590         }
591
592         require_once('include/Probe.php');
593         $data = Probe::uri($url);
594
595         // Last try in gcontact for unsupported networks
596         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO))) {
597                 if ($uid != 0) {
598                         return 0;
599                 }
600
601                 // Get data from the gcontact table
602                 $gcontacts = q("SELECT `name`, `nick`, `url`, `photo`, `addr`, `alias`, `network` FROM `gcontact` WHERE `nurl` = '%s'",
603                          dbesc(normalise_link($url)));
604                 if (!$gcontacts) {
605                         return 0;
606                 }
607
608                 $data = $gcontacts[0];
609         }
610
611         $url = $data["url"];
612
613         if (!$contact_id) {
614                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
615                                         `name`, `nick`, `photo`, `network`, `pubkey`, `rel`, `priority`,
616                                         `batch`, `request`, `confirm`, `poco`, `name-date`, `uri-date`,
617                                         `writable`, `blocked`, `readonly`, `pending`)
618                                         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)",
619                         intval($uid),
620                         dbesc(datetime_convert()),
621                         dbesc($data["url"]),
622                         dbesc(normalise_link($data["url"])),
623                         dbesc($data["addr"]),
624                         dbesc($data["alias"]),
625                         dbesc($data["notify"]),
626                         dbesc($data["poll"]),
627                         dbesc($data["name"]),
628                         dbesc($data["nick"]),
629                         dbesc($data["photo"]),
630                         dbesc($data["network"]),
631                         dbesc($data["pubkey"]),
632                         intval(CONTACT_IS_SHARING),
633                         intval($data["priority"]),
634                         dbesc($data["batch"]),
635                         dbesc($data["request"]),
636                         dbesc($data["confirm"]),
637                         dbesc($data["poco"]),
638                         dbesc(datetime_convert()),
639                         dbesc(datetime_convert())
640                 );
641
642                 $contacts = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
643                                 dbesc(normalise_link($data["url"])),
644                                 intval($uid));
645                 if (!dbm::is_result($contacts)) {
646                         return 0;
647                 }
648
649                 $contact_id = $contacts[0]["id"];
650
651                 // Update the newly created contact from data in the gcontact table
652                 $gcontacts = q("SELECT `location`, `about`, `keywords`, `gender` FROM `gcontact` WHERE `nurl` = '%s'",
653                          dbesc(normalise_link($data["url"])));
654                 if (dbm::is_result($gcontacts)) {
655                         logger("Update contact " . $data["url"] . ' from gcontact');
656                         q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d",
657                                 dbesc($gcontacts[0]["location"]), dbesc($gcontacts[0]["about"]), dbesc($gcontacts[0]["keywords"]),
658                                 dbesc($gcontacts[0]["gender"]), intval($contact_id));
659                 }
660         }
661
662         if (count($contacts) > 1 AND $uid == 0 AND $contact_id != 0 AND $url != "") {
663                 q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d AND NOT `self`",
664                         dbesc(normalise_link($url)),
665                         intval($contact_id));
666         }
667
668         require_once "Photo.php";
669
670         update_contact_avatar($data["photo"], $uid, $contact_id);
671
672         $contacts = q("SELECT `addr`, `alias`, `name`, `nick` FROM `contact` WHERE `id` = %d", intval($contact_id));
673
674         // This condition should always be true
675         if (!dbm::is_result($contacts)) {
676                 return $contact_id;
677         }
678
679         // Only update if there had something been changed
680         if ($data["addr"] != $contacts[0]["addr"] OR
681                 $data["alias"] != $contacts[0]["alias"] OR
682                 $data["name"] != $contacts[0]["name"] OR
683                 $data["nick"] != $contacts[0]["nick"]) {
684                 q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
685                         `name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
686                         dbesc($data["addr"]),
687                         dbesc($data["alias"]),
688                         dbesc($data["name"]),
689                         dbesc($data["nick"]),
690                         dbesc(datetime_convert()),
691                         dbesc(datetime_convert()),
692                         intval($contact_id)
693                 );
694         }
695
696         return $contact_id;
697 }
698
699 /**
700  * @brief Returns posts from a given gcontact
701  *
702  * @param App $a argv application class
703  * @param int $gcontact_id Global contact
704  *
705  * @return string posts in HTML
706  */
707 function posts_from_gcontact(App $a, $gcontact_id) {
708
709         require_once('include/conversation.php');
710
711         // There are no posts with "uid = 0" with connector networks
712         // This speeds up the query a lot
713         $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
714         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
715                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
716         else
717                 $sql = "`item`.`uid` = %d";
718
719         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
720                         `author-name` AS `name`, `owner-avatar` AS `photo`,
721                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
722                 FROM `item`
723                 WHERE `gcontact-id` = %d AND $sql AND
724                         NOT `deleted` AND NOT `moderated` AND `visible`
725                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
726                 intval($gcontact_id),
727                 intval(local_user()),
728                 intval($a->pager['start']),
729                 intval($a->pager['itemspage'])
730         );
731
732         $o = conversation($a, $r, 'community', false);
733
734         $o .= alt_pager($a, count($r));
735
736         return $o;
737 }
738 /**
739  * @brief Returns posts from a given contact url
740  *
741  * @param App $a argv application class
742  * @param string $contact_url Contact URL
743  *
744  * @return string posts in HTML
745  */
746 function posts_from_contact_url(App $a, $contact_url) {
747
748         require_once('include/conversation.php');
749
750         // There are no posts with "uid = 0" with connector networks
751         // This speeds up the query a lot
752         $r = q("SELECT `network`, `id` AS `author-id` FROM `contact`
753                 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
754                 dbesc(normalise_link($contact_url)));
755         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
756                 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND `item`.`private`))";
757         } else {
758                 $sql = "`item`.`uid` = %d";
759         }
760
761         if (!dbm::is_result($r)) {
762                 return '';
763         }
764
765         $author_id = intval($r[0]["author-id"]);
766
767         $r = q(item_query()." AND `item`.`author-id` = %d AND ".$sql.
768                 " ORDER BY `item`.`created` DESC LIMIT %d, %d",
769                 intval($author_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 /**
783  * @brief Returns a formatted location string from the given profile array
784  *
785  * @param array $profile Profile array (Generated from the "profile" table)
786  *
787  * @return string Location string
788  */
789 function formatted_location($profile) {
790         $location = '';
791
792         if($profile['locality'])
793                 $location .= $profile['locality'];
794
795         if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
796                 if($location)
797                         $location .= ', ';
798
799                 $location .= $profile['region'];
800         }
801
802         if($profile['country-name']) {
803                 if($location)
804                         $location .= ', ';
805
806                 $location .= $profile['country-name'];
807         }
808
809         return $location;
810 }
811
812 /**
813  * @brief Returns the account type name
814  *
815  * The function can be called with either the user or the contact array
816  *
817  * @param array $contact contact or user array
818  */
819 function account_type($contact) {
820
821         // There are several fields that indicate that the contact or user is a forum
822         // "page-flags" is a field in the user table,
823         // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
824         // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
825         if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
826                 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
827                 || (isset($contact['forum']) && intval($contact['forum']))
828                 || (isset($contact['prv']) && intval($contact['prv']))
829                 || (isset($contact['community']) && intval($contact['community'])))
830                 $type = ACCOUNT_TYPE_COMMUNITY;
831         else
832                 $type = ACCOUNT_TYPE_PERSON;
833
834         // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
835         if (isset($contact["contact-type"]))
836                 $type = $contact["contact-type"];
837         if (isset($contact["account-type"]))
838                 $type = $contact["account-type"];
839
840         switch($type) {
841                 case ACCOUNT_TYPE_ORGANISATION:
842                         $account_type = t("Organisation");
843                         break;
844                 case ACCOUNT_TYPE_NEWS:
845                         $account_type = t('News');
846                         break;
847                 case ACCOUNT_TYPE_COMMUNITY:
848                         $account_type = t("Forum");
849                         break;
850                 default:
851                         $account_type = "";
852                         break;
853         }
854
855         return $account_type;
856 }
857 ?>