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