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