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