]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
fixed parser error, need parentheses
[friendica.git] / include / Contact.php
1 <?php
2
3 use Friendica\App;
4 use Friendica\Network\Probe;
5
6 // Included here for completeness, but this is a very dangerous operation.
7 // It is the caller's responsibility to confirm the requestor's intent and
8 // authorisation to do this.
9
10 function user_remove($uid) {
11         if(! $uid)
12                 return;
13         logger('Removing user: ' . $uid);
14
15         $r = q("select * from user where uid = %d limit 1", intval($uid));
16
17         call_hooks('remove_user',$r[0]);
18
19         // save username (actually the nickname as it is guaranteed
20         // unique), so it cannot be re-registered in the future.
21
22         q("insert into userd ( username ) values ( '%s' )",
23                 $r[0]['nickname']
24         );
25
26         /// @todo Should be done in a background job since this likely will run into a time out
27         // don't delete yet, will be done later when contacts have deleted my stuff
28         // q("DELETE FROM `contact` WHERE `uid` = %d", intval($uid));
29         q("DELETE FROM `gcign` WHERE `uid` = %d", intval($uid));
30         q("DELETE FROM `group` WHERE `uid` = %d", intval($uid));
31         q("DELETE FROM `group_member` WHERE `uid` = %d", intval($uid));
32         q("DELETE FROM `intro` WHERE `uid` = %d", intval($uid));
33         q("DELETE FROM `event` WHERE `uid` = %d", intval($uid));
34         q("DELETE FROM `item` WHERE `uid` = %d", intval($uid));
35         q("DELETE FROM `item_id` WHERE `uid` = %d", intval($uid));
36         q("DELETE FROM `mail` WHERE `uid` = %d", intval($uid));
37         q("DELETE FROM `mailacct` WHERE `uid` = %d", intval($uid));
38         q("DELETE FROM `manage` WHERE `uid` = %d", intval($uid));
39         q("DELETE FROM `notify` WHERE `uid` = %d", intval($uid));
40         q("DELETE FROM `photo` WHERE `uid` = %d", intval($uid));
41         q("DELETE FROM `attach` WHERE `uid` = %d", intval($uid));
42         q("DELETE FROM `profile` WHERE `uid` = %d", intval($uid));
43         q("DELETE FROM `profile_check` WHERE `uid` = %d", intval($uid));
44         q("DELETE FROM `pconfig` WHERE `uid` = %d", intval($uid));
45         q("DELETE FROM `search` WHERE `uid` = %d", intval($uid));
46         q("DELETE FROM `spam` WHERE `uid` = %d", intval($uid));
47         // don't delete yet, will be done later when contacts have deleted my stuff
48         // q("DELETE FROM `user` WHERE `uid` = %d", intval($uid));
49         q("UPDATE `user` SET `account_removed` = 1, `account_expires_on` = UTC_TIMESTAMP() WHERE `uid` = %d", intval($uid));
50         proc_run(PRIORITY_HIGH, "include/notifier.php", "removeme", $uid);
51
52         // Send an update to the directory
53         proc_run(PRIORITY_LOW, "include/directory.php", $r[0]['url']);
54
55         if($uid == local_user()) {
56                 unset($_SESSION['authenticated']);
57                 unset($_SESSION['uid']);
58                 goaway(App::get_baseurl());
59         }
60 }
61
62
63 function contact_remove($id) {
64
65         // We want just to make sure that we don't delete our "self" contact
66         $r = q("SELECT `uid` FROM `contact` WHERE `id` = %d AND NOT `self` LIMIT 1",
67                 intval($id)
68         );
69         if (!dbm::is_result($r) || !intval($r[0]['uid'])) {
70                 return;
71         }
72
73         $archive = get_pconfig($r[0]['uid'], 'system','archive_removed_contacts');
74         if ($archive) {
75                 q("update contact set `archive` = 1, `network` = 'none', `writable` = 0 where id = %d",
76                         intval($id)
77                 );
78                 return;
79         }
80
81         q("DELETE FROM `contact` WHERE `id` = %d", intval($id));
82
83         // Delete the rest in the background
84         proc_run(PRIORITY_LOW, 'include/remove_contact.php', $id);
85 }
86
87
88 // sends an unfriend message. Does not remove the contact
89
90 function terminate_friendship($user,$self,$contact) {
91
92         /// @TODO Get rid of this, include/datetime.php should care about it by itself
93         $a = get_app();
94
95         require_once 'include/datetime.php';
96
97         if ($contact['network'] === NETWORK_OSTATUS) {
98
99                 require_once 'include/ostatus.php';
100
101                 // create an unfollow slap
102                 $item = array();
103                 $item['verb'] = NAMESPACE_OSTATUS."/unfollow";
104                 $item['follow'] = $contact["url"];
105                 $slap = ostatus::salmon($item, $user);
106
107                 if ((x($contact,'notify')) && (strlen($contact['notify']))) {
108                         require_once 'include/salmon.php';
109                         slapper($user,$contact['notify'],$slap);
110                 }
111         } elseif ($contact['network'] === NETWORK_DIASPORA) {
112                 require_once 'include/diaspora.php';
113                 Diaspora::send_unshare($user,$contact);
114         } elseif ($contact['network'] === NETWORK_DFRN) {
115                 require_once 'include/dfrn.php';
116                 dfrn::deliver($user,$contact,'placeholder', 1);
117         }
118
119 }
120
121
122 // Contact has refused to recognise us as a friend. We will start a countdown.
123 // If they still don't recognise us in 32 days, the relationship is over,
124 // and we won't waste any more time trying to communicate with them.
125 // This provides for the possibility that their database is temporarily messed
126 // up or some other transient event and that there's a possibility we could recover from it.
127
128 function mark_for_death($contact) {
129
130         if($contact['archive'])
131                 return;
132
133         if ($contact['term-date'] <= NULL_DATE) {
134                 q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
135                                 dbesc(datetime_convert()),
136                                 intval($contact['id'])
137                 );
138
139                 if ($contact['url'] != '') {
140                         q("UPDATE `contact` SET `term-date` = '%s'
141                                 WHERE `nurl` = '%s' AND `term-date` <= '1000-00-00'",
142                                         dbesc(datetime_convert()),
143                                         dbesc(normalise_link($contact['url']))
144                         );
145                 }
146         } else {
147
148                 /// @todo
149                 /// We really should send a notification to the owner after 2-3 weeks
150                 /// so they won't be surprised when the contact vanishes and can take
151                 /// remedial action if this was a serious mistake or glitch
152
153                 /// @todo
154                 /// Check for contact vitality via probing
155
156                 $expiry = $contact['term-date'] . ' + 32 days ';
157                 if(datetime_convert() > datetime_convert('UTC','UTC',$expiry)) {
158
159                         // relationship is really truly dead.
160                         // archive them rather than delete
161                         // though if the owner tries to unarchive them we'll start the whole process over again
162
163                         q("UPDATE `contact` SET `archive` = 1 WHERE `id` = %d",
164                                 intval($contact['id'])
165                         );
166
167                         if ($contact['url'] != '') {
168                                 q("UPDATE `contact` SET `archive` = 1 WHERE `nurl` = '%s'",
169                                         dbesc(normalise_link($contact['url']))
170                                 );
171                         }
172                 }
173         }
174
175 }
176
177 function unmark_for_death($contact) {
178
179         $r = q("SELECT `term-date` FROM `contact` WHERE `id` = %d AND `term-date` > '%s'",
180                 intval($contact['id']),
181                 dbesc('1000-00-00 00:00:00')
182         );
183
184         // We don't need to update, we never marked this contact as dead
185         if (!dbm::is_result($r)) {
186                 return;
187         }
188
189         // It's a miracle. Our dead contact has inexplicably come back to life.
190         q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
191                 dbesc(NULL_DATE),
192                 intval($contact['id'])
193         );
194
195         if ($contact['url'] != '') {
196                 q("UPDATE `contact` SET `term-date` = '%s' WHERE `nurl` = '%s'",
197                         dbesc(NULL_DATE),
198                         dbesc(normalise_link($contact['url']))
199                 );
200         }
201 }
202
203 /**
204  * @brief Get contact data for a given profile link
205  *
206  * The function looks at several places (contact table and gcontact table) for the contact
207  * It caches its result for the same script execution to prevent duplicate calls
208  *
209  * @param string $url The profile link
210  * @param int $uid User id
211  * @param array $default If not data was found take this data as default value
212  *
213  * @return array Contact data
214  */
215 function get_contact_details_by_url($url, $uid = -1, $default = array()) {
216         static $cache = array();
217
218         if ($url == '') {
219                 return $default;
220         }
221
222         if ($uid == -1) {
223                 $uid = local_user();
224         }
225
226         if (isset($cache[$url][$uid])) {
227                 return $cache[$url][$uid];
228         }
229
230         // Fetch contact data from the contact table for the given user
231         $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
232                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
233                 FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
234                         dbesc(normalise_link($url)), intval($uid));
235
236         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
237         if (!dbm::is_result($r))
238                 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
239                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
240                         FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
241                                 dbesc(normalise_link($url)));
242
243         // Fetch the data from the gcontact table
244         if (!dbm::is_result($r))
245                 $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`,
246                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
247                         FROM `gcontact` WHERE `nurl` = '%s'",
248                                 dbesc(normalise_link($url)));
249
250         if (dbm::is_result($r)) {
251                 // If there is more than one entry we filter out the connector networks
252                 if (count($r) > 1) {
253                         foreach ($r AS $id => $result) {
254                                 if ($result["network"] == NETWORK_STATUSNET) {
255                                         unset($r[$id]);
256                                 }
257                         }
258                 }
259
260                 $profile = array_shift($r);
261
262                 // "bd" always contains the upcoming birthday of a contact.
263                 // "birthday" might contain the birthday including the year of birth.
264                 if ($profile["birthday"] > '0001-01-01') {
265                         $bd_timestamp = strtotime($profile["birthday"]);
266                         $month = date("m", $bd_timestamp);
267                         $day = date("d", $bd_timestamp);
268
269                         $current_timestamp = time();
270                         $current_year = date("Y", $current_timestamp);
271                         $current_month = date("m", $current_timestamp);
272                         $current_day = date("d", $current_timestamp);
273
274                         $profile["bd"] = $current_year."-".$month."-".$day;
275                         $current = $current_year."-".$current_month."-".$current_day;
276
277                         if ($profile["bd"] < $current) {
278                                 $profile["bd"] = (++$current_year)."-".$month."-".$day;
279                         }
280                 } else {
281                         $profile["bd"] = '0001-01-01';
282                 }
283         } else {
284                 $profile = $default;
285         }
286
287         if (($profile["photo"] == "") AND isset($default["photo"])) {
288                 $profile["photo"] = $default["photo"];
289         }
290
291         if (($profile["name"] == "") AND isset($default["name"])) {
292                 $profile["name"] = $default["name"];
293         }
294
295         if (($profile["network"] == "") AND isset($default["network"])) {
296                 $profile["network"] = $default["network"];
297         }
298
299         if (($profile["thumb"] == "") AND isset($profile["photo"])) {
300                 $profile["thumb"] = $profile["photo"];
301         }
302
303         if (($profile["micro"] == "") AND isset($profile["thumb"])) {
304                 $profile["micro"] = $profile["thumb"];
305         }
306
307         if ((($profile["addr"] == "") OR ($profile["name"] == "")) AND ($profile["gid"] != 0) AND
308                 in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
309                 proc_run(PRIORITY_LOW, "include/update_gcontact.php", $profile["gid"]);
310         }
311
312         // Show contact details of Diaspora contacts only if connected
313         if (($profile["cid"] == 0) AND ($profile["network"] == NETWORK_DIASPORA)) {
314                 $profile["location"] = "";
315                 $profile["about"] = "";
316                 $profile["gender"] = "";
317                 $profile["birthday"] = '0001-01-01';
318         }
319
320         $cache[$url][$uid] = $profile;
321
322         return $profile;
323 }
324
325 /**
326  * @brief Get contact data for a given address
327  *
328  * The function looks at several places (contact table and gcontact table) for the contact
329  *
330  * @param string $addr The profile link
331  * @param int $uid User id
332  *
333  * @return array Contact data
334  */
335 function get_contact_details_by_addr($addr, $uid = -1) {
336         static $cache = array();
337
338         if ($addr == '') {
339                 return array();
340         }
341
342         if ($uid == -1) {
343                 $uid = local_user();
344         }
345
346         // Fetch contact data from the contact table for the given user
347         $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
348                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
349                 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
350                         dbesc($addr), intval($uid));
351
352         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
353         if (!dbm::is_result($r))
354                 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
355                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
356                         FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
357                                 dbesc($addr));
358
359         // Fetch the data from the gcontact table
360         if (!dbm::is_result($r))
361                 $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`,
362                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
363                         FROM `gcontact` WHERE `addr` = '%s'",
364                                 dbesc($addr));
365
366         if (!dbm::is_result($r)) {
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         $data = Probe::uri($url);
593
594         // Last try in gcontact for unsupported networks
595         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO))) {
596                 if ($uid != 0) {
597                         return 0;
598                 }
599
600                 // Get data from the gcontact table
601                 $gcontacts = q("SELECT `name`, `nick`, `url`, `photo`, `addr`, `alias`, `network` FROM `gcontact` WHERE `nurl` = '%s'",
602                          dbesc(normalise_link($url)));
603                 if (!$gcontacts) {
604                         return 0;
605                 }
606
607                 $data = $gcontacts[0];
608         }
609
610         $url = $data["url"];
611
612         if (!$contact_id) {
613                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
614                                         `name`, `nick`, `photo`, `network`, `pubkey`, `rel`, `priority`,
615                                         `batch`, `request`, `confirm`, `poco`, `name-date`, `uri-date`,
616                                         `writable`, `blocked`, `readonly`, `pending`)
617                                         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)",
618                         intval($uid),
619                         dbesc(datetime_convert()),
620                         dbesc($data["url"]),
621                         dbesc(normalise_link($data["url"])),
622                         dbesc($data["addr"]),
623                         dbesc($data["alias"]),
624                         dbesc($data["notify"]),
625                         dbesc($data["poll"]),
626                         dbesc($data["name"]),
627                         dbesc($data["nick"]),
628                         dbesc($data["photo"]),
629                         dbesc($data["network"]),
630                         dbesc($data["pubkey"]),
631                         intval(CONTACT_IS_SHARING),
632                         intval($data["priority"]),
633                         dbesc($data["batch"]),
634                         dbesc($data["request"]),
635                         dbesc($data["confirm"]),
636                         dbesc($data["poco"]),
637                         dbesc(datetime_convert()),
638                         dbesc(datetime_convert())
639                 );
640
641                 $contacts = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
642                                 dbesc(normalise_link($data["url"])),
643                                 intval($uid));
644                 if (!dbm::is_result($contacts)) {
645                         return 0;
646                 }
647
648                 $contact_id = $contacts[0]["id"];
649
650                 // Update the newly created contact from data in the gcontact table
651                 $gcontacts = q("SELECT `location`, `about`, `keywords`, `gender` FROM `gcontact` WHERE `nurl` = '%s'",
652                          dbesc(normalise_link($data["url"])));
653                 if (dbm::is_result($gcontacts)) {
654                         logger("Update contact " . $data["url"] . ' from gcontact');
655                         q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d",
656                                 dbesc($gcontacts[0]["location"]), dbesc($gcontacts[0]["about"]), dbesc($gcontacts[0]["keywords"]),
657                                 dbesc($gcontacts[0]["gender"]), intval($contact_id));
658                 }
659         }
660
661         if (count($contacts) > 1 AND $uid == 0 AND $contact_id != 0 AND $url != "") {
662                 q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d AND NOT `self`",
663                         dbesc(normalise_link($url)),
664                         intval($contact_id));
665         }
666
667         require_once "Photo.php";
668
669         update_contact_avatar($data["photo"], $uid, $contact_id);
670
671         $contacts = q("SELECT `addr`, `alias`, `name`, `nick` FROM `contact` WHERE `id` = %d", intval($contact_id));
672
673         // This condition should always be true
674         if (!dbm::is_result($contacts)) {
675                 return $contact_id;
676         }
677
678         // Only update if there had something been changed
679         if ($data["addr"] != $contacts[0]["addr"] OR
680                 $data["alias"] != $contacts[0]["alias"] OR
681                 $data["name"] != $contacts[0]["name"] OR
682                 $data["nick"] != $contacts[0]["nick"]) {
683                 q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
684                         `name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
685                         dbesc($data["addr"]),
686                         dbesc($data["alias"]),
687                         dbesc($data["name"]),
688                         dbesc($data["nick"]),
689                         dbesc(datetime_convert()),
690                         dbesc(datetime_convert()),
691                         intval($contact_id)
692                 );
693         }
694
695         return $contact_id;
696 }
697
698 /**
699  * @brief Returns posts from a given gcontact
700  *
701  * @param App $a argv application class
702  * @param int $gcontact_id Global contact
703  *
704  * @return string posts in HTML
705  */
706 function posts_from_gcontact(App $a, $gcontact_id) {
707
708         require_once 'include/conversation.php';
709
710         // There are no posts with "uid = 0" with connector networks
711         // This speeds up the query a lot
712         $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
713         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
714                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
715         else
716                 $sql = "`item`.`uid` = %d";
717
718         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
719                         `author-name` AS `name`, `owner-avatar` AS `photo`,
720                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
721                 FROM `item`
722                 WHERE `gcontact-id` = %d AND $sql AND
723                         NOT `deleted` AND NOT `moderated` AND `visible`
724                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
725                 intval($gcontact_id),
726                 intval(local_user()),
727                 intval($a->pager['start']),
728                 intval($a->pager['itemspage'])
729         );
730
731         $o = conversation($a, $r, 'community', false);
732
733         $o .= alt_pager($a, count($r));
734
735         return $o;
736 }
737 /**
738  * @brief Returns posts from a given contact url
739  *
740  * @param App $a argv application class
741  * @param string $contact_url Contact URL
742  *
743  * @return string posts in HTML
744  */
745 function posts_from_contact_url(App $a, $contact_url) {
746
747         require_once 'include/conversation.php';
748
749         // There are no posts with "uid = 0" with connector networks
750         // This speeds up the query a lot
751         $r = q("SELECT `network`, `id` AS `author-id` FROM `contact`
752                 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
753                 dbesc(normalise_link($contact_url)));
754         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
755                 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND `item`.`private`))";
756         } else {
757                 $sql = "`item`.`uid` = %d";
758         }
759
760         if (!dbm::is_result($r)) {
761                 return '';
762         }
763
764         $author_id = intval($r[0]["author-id"]);
765
766         $r = q(item_query()." AND `item`.`author-id` = %d AND ".$sql.
767                 " ORDER BY `item`.`created` DESC LIMIT %d, %d",
768                 intval($author_id),
769                 intval(local_user()),
770                 intval($a->pager['start']),
771                 intval($a->pager['itemspage'])
772         );
773
774         $o = conversation($a, $r, 'community', false);
775
776         $o .= alt_pager($a, count($r));
777
778         return $o;
779 }
780
781 /**
782  * @brief Returns a formatted location string from the given profile array
783  *
784  * @param array $profile Profile array (Generated from the "profile" table)
785  *
786  * @return string Location string
787  */
788 function formatted_location($profile) {
789         $location = '';
790
791         if($profile['locality'])
792                 $location .= $profile['locality'];
793
794         if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
795                 if($location)
796                         $location .= ', ';
797
798                 $location .= $profile['region'];
799         }
800
801         if($profile['country-name']) {
802                 if($location)
803                         $location .= ', ';
804
805                 $location .= $profile['country-name'];
806         }
807
808         return $location;
809 }
810
811 /**
812  * @brief Returns the account type name
813  *
814  * The function can be called with either the user or the contact array
815  *
816  * @param array $contact contact or user array
817  */
818 function account_type($contact) {
819
820         // There are several fields that indicate that the contact or user is a forum
821         // "page-flags" is a field in the user table,
822         // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
823         // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
824         if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
825                 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
826                 || (isset($contact['forum']) && intval($contact['forum']))
827                 || (isset($contact['prv']) && intval($contact['prv']))
828                 || (isset($contact['community']) && intval($contact['community'])))
829                 $type = ACCOUNT_TYPE_COMMUNITY;
830         else
831                 $type = ACCOUNT_TYPE_PERSON;
832
833         // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
834         if (isset($contact["contact-type"]))
835                 $type = $contact["contact-type"];
836         if (isset($contact["account-type"]))
837                 $type = $contact["account-type"];
838
839         switch($type) {
840                 case ACCOUNT_TYPE_ORGANISATION:
841                         $account_type = t("Organisation");
842                         break;
843                 case ACCOUNT_TYPE_NEWS:
844                         $account_type = t('News');
845                         break;
846                 case ACCOUNT_TYPE_COMMUNITY:
847                         $account_type = t("Forum");
848                         break;
849                 default:
850                         $account_type = "";
851                         break;
852         }
853
854         return $account_type;
855 }