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