]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
Merge pull request #2286 from annando/1601-dfrn
[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         // don't delete yet, will be done later when contacts have deleted my stuff
26         // q("DELETE FROM `contact` WHERE `uid` = %d", intval($uid));
27         q("DELETE FROM `gcign` WHERE `uid` = %d", intval($uid));
28         q("DELETE FROM `group` WHERE `uid` = %d", intval($uid));
29         q("DELETE FROM `group_member` WHERE `uid` = %d", intval($uid));
30         q("DELETE FROM `intro` WHERE `uid` = %d", intval($uid));
31         q("DELETE FROM `event` WHERE `uid` = %d", intval($uid));
32         q("DELETE FROM `item` WHERE `uid` = %d", intval($uid));
33         q("DELETE FROM `item_id` WHERE `uid` = %d", intval($uid));
34         q("DELETE FROM `mail` WHERE `uid` = %d", intval($uid));
35         q("DELETE FROM `mailacct` WHERE `uid` = %d", intval($uid));
36         q("DELETE FROM `manage` WHERE `uid` = %d", intval($uid));
37         q("DELETE FROM `notify` WHERE `uid` = %d", intval($uid));
38         q("DELETE FROM `photo` WHERE `uid` = %d", intval($uid));
39         q("DELETE FROM `attach` WHERE `uid` = %d", intval($uid));
40         q("DELETE FROM `profile` WHERE `uid` = %d", intval($uid));
41         q("DELETE FROM `profile_check` WHERE `uid` = %d", intval($uid));
42         q("DELETE FROM `pconfig` WHERE `uid` = %d", intval($uid));
43         q("DELETE FROM `search` WHERE `uid` = %d", intval($uid));
44         q("DELETE FROM `spam` WHERE `uid` = %d", intval($uid));
45         // don't delete yet, will be done later when contacts have deleted my stuff
46         // q("DELETE FROM `user` WHERE `uid` = %d", intval($uid));
47         q("UPDATE `user` SET `account_removed` = 1, `account_expires_on` = UTC_TIMESTAMP() WHERE `uid` = %d", intval($uid));
48         proc_run('php', "include/notifier.php", "removeme", $uid);
49
50         // Send an update to the directory
51         proc_run('php', "include/directory.php", $r[0]['url']);
52
53         if($uid == local_user()) {
54                 unset($_SESSION['authenticated']);
55                 unset($_SESSION['uid']);
56                 goaway($a->get_baseurl());
57         }
58 }
59
60
61 function contact_remove($id) {
62
63         $r = q("select uid from contact where id = %d limit 1",
64                 intval($id)
65         );
66         if((! count($r)) || (! intval($r[0]['uid'])))
67                 return;
68
69         $archive = get_pconfig($r[0]['uid'], 'system','archive_removed_contacts');
70         if($archive) {
71                 q("update contact set `archive` = 1, `network` = 'none', `writable` = 0 where id = %d",
72                         intval($id)
73                 );
74                 return;
75         }
76
77         q("DELETE FROM `contact` WHERE `id` = %d",
78                 intval($id)
79         );
80         q("DELETE FROM `item` WHERE `contact-id` = %d ",
81                 intval($id)
82         );
83         q("DELETE FROM `photo` WHERE `contact-id` = %d ",
84                 intval($id)
85         );
86         q("DELETE FROM `mail` WHERE `contact-id` = %d ",
87                 intval($id)
88         );
89         q("DELETE FROM `event` WHERE `cid` = %d ",
90                 intval($id)
91         );
92         q("DELETE FROM `queue` WHERE `cid` = %d ",
93                 intval($id)
94         );
95
96 }
97
98
99 // sends an unfriend message. Does not remove the contact
100
101 function terminate_friendship($user,$self,$contact) {
102
103
104         $a = get_app();
105
106         require_once('include/datetime.php');
107
108         if($contact['network'] === NETWORK_OSTATUS) {
109
110                 $slap = replace_macros(get_markup_template('follow_slap.tpl'), array(
111                         '$name' => $user['username'],
112                         '$profile_page' => $a->get_baseurl() . '/profile/' . $user['nickname'],
113                         '$photo' => $self['photo'],
114                         '$thumb' => $self['thumb'],
115                         '$published' => datetime_convert('UTC','UTC', 'now', ATOM_TIME),
116                         '$item_id' => 'urn:X-dfrn:' . $a->get_hostname() . ':unfollow:' . get_guid(32),
117                         '$title' => '',
118                         '$type' => 'text',
119                         '$content' => t('stopped following'),
120                         '$nick' => $user['nickname'],
121                         '$verb' => 'http://ostatus.org/schema/1.0/unfollow', // ACTIVITY_UNFOLLOW,
122                         '$ostat_follow' => '' // '<as:verb>http://ostatus.org/schema/1.0/unfollow</as:verb>' . "\r\n"
123                 ));
124
125                 if((x($contact,'notify')) && (strlen($contact['notify']))) {
126                         require_once('include/salmon.php');
127                         slapper($user,$contact['notify'],$slap);
128                 }
129         }
130         elseif($contact['network'] === NETWORK_DIASPORA) {
131                 require_once('include/diaspora.php');
132                 diaspora_unshare($user,$contact);
133         }
134         elseif($contact['network'] === NETWORK_DFRN) {
135                 require_once('include/dfrn.php');
136                 dfrn::deliver($user,$contact,'placeholder', 1);
137         }
138
139 }
140
141
142 // Contact has refused to recognise us as a friend. We will start a countdown.
143 // If they still don't recognise us in 32 days, the relationship is over,
144 // and we won't waste any more time trying to communicate with them.
145 // This provides for the possibility that their database is temporarily messed
146 // up or some other transient event and that there's a possibility we could recover from it.
147
148 if(! function_exists('mark_for_death')) {
149 function mark_for_death($contact) {
150
151         if($contact['archive'])
152                 return;
153
154         if($contact['term-date'] == '0000-00-00 00:00:00') {
155                 q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
156                                 dbesc(datetime_convert()),
157                                 intval($contact['id'])
158                 );
159         }
160         else {
161
162                 /// @todo 
163                 /// We really should send a notification to the owner after 2-3 weeks
164                 /// so they won't be surprised when the contact vanishes and can take
165                 /// remedial action if this was a serious mistake or glitch
166
167                 $expiry = $contact['term-date'] . ' + 32 days ';
168                 if(datetime_convert() > datetime_convert('UTC','UTC',$expiry)) {
169
170                         // relationship is really truly dead.
171                         // archive them rather than delete
172                         // though if the owner tries to unarchive them we'll start the whole process over again
173
174                         q("update contact set `archive` = 1 where id = %d",
175                                 intval($contact['id'])
176                         );
177                         q("UPDATE `item` SET `private` = 2 WHERE `contact-id` = %d AND `uid` = %d", intval($contact['id']), intval($contact['uid']));
178
179                         //contact_remove($contact['id']);
180
181                 }
182         }
183
184 }}
185
186 if(! function_exists('unmark_for_death')) {
187 function unmark_for_death($contact) {
188         // It's a miracle. Our dead contact has inexplicably come back to life.
189         q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
190                 dbesc('0000-00-00 00:00:00'),
191                 intval($contact['id'])
192         );
193 }}
194
195 function get_contact_details_by_url($url, $uid = -1) {
196         if ($uid == -1)
197                 $uid = local_user();
198
199         $r = q("SELECT `id` AS `gid`, `url`, `name`, `nick`, `addr`, `photo`, `location`, `about`, `keywords`, `gender`, `community`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
200                 dbesc(normalise_link($url)));
201
202         if ($r) {
203                 $profile = $r[0];
204
205                 if ((($profile["addr"] == "") OR ($profile["name"] == "")) AND
206                         in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
207                         proc_run('php',"include/update_gcontact.php", $profile["gid"]);
208         }
209
210         // Fetching further contact data from the contact table
211         $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd`, `self` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `network` IN ('%s', '')",
212                 dbesc(normalise_link($url)), intval($uid), dbesc($profile["network"]));
213
214         if (!count($r) AND !isset($profile))
215                 $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd`, `self` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
216                         dbesc(normalise_link($url)), intval($uid));
217
218         if (!count($r) AND !isset($profile))
219                 $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
220                         dbesc(normalise_link($url)));
221
222         if ($r) {
223                 if (!isset($profile["url"]) AND $r[0]["url"])
224                         $profile["url"] = $r[0]["url"];
225                 if (!isset($profile["name"]) AND $r[0]["name"])
226                         $profile["name"] = $r[0]["name"];
227                 if (!isset($profile["nick"]) AND $r[0]["nick"])
228                         $profile["nick"] = $r[0]["nick"];
229                 if (!isset($profile["addr"]) AND $r[0]["addr"])
230                         $profile["addr"] = $r[0]["addr"];
231                 if ((!isset($profile["photo"]) OR $r[0]["self"]) AND $r[0]["photo"])
232                         $profile["photo"] = $r[0]["photo"];
233                 if (!isset($profile["location"]) AND $r[0]["location"])
234                         $profile["location"] = $r[0]["location"];
235                 if (!isset($profile["about"]) AND $r[0]["about"])
236                         $profile["about"] = $r[0]["about"];
237                 if (!isset($profile["keywords"]) AND $r[0]["keywords"])
238                         $profile["keywords"] = $r[0]["keywords"];
239                 if (!isset($profile["gender"]) AND $r[0]["gender"])
240                         $profile["gender"] = $r[0]["gender"];
241                 if (isset($r[0]["forum"]) OR isset($r[0]["prv"]))
242                         $profile["community"] = ($r[0]["forum"] OR $r[0]["prv"]);
243                 if (!isset($profile["network"]) AND $r[0]["network"])
244                         $profile["network"] = $r[0]["network"];
245                 if (!isset($profile["addr"]) AND $r[0]["addr"])
246                         $profile["addr"] = $r[0]["addr"];
247                 if (!isset($profile["bd"]) AND $r[0]["bd"])
248                         $profile["bd"] = $r[0]["bd"];
249                 if (isset($r[0]["thumb"]))
250                         $profile["thumb"] = $r[0]["thumb"];
251                 if ($r[0]["uid"] == 0)
252                         $profile["cid"] = 0;
253                 else
254                         $profile["cid"] = $r[0]["id"];
255         } else
256                 $profile["cid"] = 0;
257
258         if (($profile["cid"] == 0) AND ($profile["network"] == NETWORK_DIASPORA)) {
259                 $profile["location"] = "";
260                 $profile["about"] = "";
261         }
262
263         return($profile);
264 }
265
266 if(! function_exists('contact_photo_menu')){
267 function contact_photo_menu($contact, $uid = 0) {
268
269         $a = get_app();
270
271         $contact_url="";
272         $pm_url="";
273         $status_link="";
274         $photos_link="";
275         $posts_link="";
276         $contact_drop_link = "";
277         $poke_link="";
278
279         if ($uid == 0)
280                 $uid = local_user();
281
282         if ($contact["uid"] != $uid) {
283                 if ($uid == 0) {
284                         $profile_link = zrl($contact['url']);
285                         $menu = Array('profile' => array(t("View Profile"), $profile_link, true));
286
287                         return $menu;
288                 }
289
290                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `network` = '%s' AND `uid` = %d",
291                         dbesc($contact["nurl"]), dbesc($contact["network"]), intval($uid));
292                 if ($r)
293                         return contact_photo_menu($r[0], $uid);
294                 else {
295                         $profile_link = zrl($contact['url']);
296                         $connlnk = 'follow/?url='.$contact['url'];
297                         $menu = Array(
298                                 'profile' => array(t("View Profile"), $profile_link, true),
299                                 'follow' => array(t("Connect/Follow"), $connlnk, true)
300                                 );
301
302                         return $menu;
303                 }
304         }
305
306         $sparkle = false;
307         if($contact['network'] === NETWORK_DFRN) {
308                 $sparkle = true;
309                 $profile_link = $a->get_baseurl() . '/redir/' . $contact['id'];
310         }
311         else
312                 $profile_link = $contact['url'];
313
314         if($profile_link === 'mailbox')
315                 $profile_link = '';
316
317         if($sparkle) {
318                 $status_link = $profile_link . "?url=status";
319                 $photos_link = $profile_link . "?url=photos";
320                 $profile_link = $profile_link . "?url=profile";
321         }
322
323         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA)))
324                 $pm_url = $a->get_baseurl() . '/message/new/' . $contact['id'];
325
326         if ($contact["network"] == NETWORK_DFRN)
327                 $poke_link = $a->get_baseurl() . '/poke/?f=&c=' . $contact['id'];
328
329         $contact_url = $a->get_baseurl() . '/contacts/' . $contact['id'];
330         $posts_link = $a->get_baseurl() . "/contacts/" . $contact['id'] . '/posts';
331         $contact_drop_link = $a->get_baseurl() . "/contacts/" . $contact['id'] . '/drop?confirm=1';
332
333
334         /**
335          * menu array:
336          * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
337          */
338         $menu = Array(
339                 'status' => array(t("View Status"), $status_link, true),
340                 'profile' => array(t("View Profile"), $profile_link, true),
341                 'photos' => array(t("View Photos"), $photos_link,true),
342                 'network' => array(t("Network Posts"), $posts_link,false),
343                 'edit' => array(t("Edit Contact"), $contact_url, false),
344                 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
345                 'pm' => array(t("Send PM"), $pm_url, false),
346                 'poke' => array(t("Poke"), $poke_link, false),
347         );
348
349
350         $args = array('contact' => $contact, 'menu' => &$menu);
351
352         call_hooks('contact_photo_menu', $args);
353
354         $menucondensed = array();
355
356         foreach ($menu AS $menuname=>$menuitem)
357                 if ($menuitem[1] != "")
358                         $menucondensed[$menuname] = $menuitem;
359
360         return $menucondensed;
361 }}
362
363
364 function random_profile() {
365         $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
366                                 AND `last_contact` >= `last_failure`
367                                 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
368                         ORDER BY rand() LIMIT 1",
369                 dbesc(NETWORK_DFRN));
370
371         if(count($r))
372                 return dirname($r[0]['url']);
373         return '';
374 }
375
376
377 function contacts_not_grouped($uid,$start = 0,$count = 0) {
378
379         if(! $count) {
380                 $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) ",
381                         intval($uid),
382                         intval($uid)
383                 );
384
385                 return $r;
386
387
388         }
389
390         $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",
391                 intval($uid),
392                 intval($uid),
393                 intval($start),
394                 intval($count)
395         );
396
397         return $r;
398 }
399
400 function get_contact($url, $uid = 0) {
401         require_once("include/Scrape.php");
402
403         $data = array();
404         $contactid = 0;
405
406         // is it an address in the format user@server.tld?
407         /// @todo use gcontact and/or the addr field for a lookup
408         if (!strstr($url, "http") OR strstr($url, "@")) {
409                 $data = probe_url($url);
410                 $url = $data["url"];
411                 if ($url == "")
412                         return 0;
413         }
414
415         $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
416                         dbesc(normalise_link($url)),
417                         intval($uid));
418
419         if (!$contact)
420                 $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `uid` = %d ORDER BY `id` LIMIT 1",
421                                 dbesc($url),
422                                 dbesc(normalise_link($url)),
423                                 intval($uid));
424
425         if ($contact) {
426                 $contactid = $contact[0]["id"];
427
428                 // Update the contact every 7 days
429                 $update_photo = ($contact[0]['avatar-date'] < datetime_convert('','','now -7 days'));
430                 //$update_photo = ($contact[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
431
432                 if (!$update_photo)
433                         return($contactid);
434         } elseif ($uid != 0)
435                 return 0;
436
437         if (!count($data))
438                 $data = probe_url($url);
439
440         // Does this address belongs to a valid network?
441         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
442                 return 0;
443
444         $url = $data["url"];
445
446         if ($contactid == 0) {
447                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
448                                         `name`, `nick`, `photo`, `network`, `pubkey`, `rel`, `priority`,
449                                         `batch`, `request`, `confirm`, `poco`,
450                                         `writable`, `blocked`, `readonly`, `pending`)
451                                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s', 1, 0, 0, 0)",
452                         intval($uid),
453                         dbesc(datetime_convert()),
454                         dbesc($data["url"]),
455                         dbesc(normalise_link($data["url"])),
456                         dbesc($data["addr"]),
457                         dbesc($data["alias"]),
458                         dbesc($data["notify"]),
459                         dbesc($data["poll"]),
460                         dbesc($data["name"]),
461                         dbesc($data["nick"]),
462                         dbesc($data["photo"]),
463                         dbesc($data["network"]),
464                         dbesc($data["pubkey"]),
465                         intval(CONTACT_IS_SHARING),
466                         intval($data["priority"]),
467                         dbesc($data["batch"]),
468                         dbesc($data["request"]),
469                         dbesc($data["confirm"]),
470                         dbesc($data["poco"])
471                 );
472
473                 $contact = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
474                                 dbesc(normalise_link($data["url"])),
475                                 intval($uid));
476                 if (!$contact)
477                         return 0;
478
479                 $contactid = $contact[0]["id"];
480         }
481
482         if ((count($contact) > 1) AND ($uid == 0) AND ($contactid != 0) AND ($url != ""))
483                 q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d",
484                         dbesc(normalise_link($url)),
485                         intval($contactid));
486
487         require_once("Photo.php");
488
489         $photos = import_profile_photo($data["photo"],$uid,$contactid);
490
491         q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s',
492                 `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
493                 `name-date` = '%s', `uri-date` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
494                 dbesc($photos[0]),
495                 dbesc($photos[1]),
496                 dbesc($photos[2]),
497                 dbesc($data["addr"]),
498                 dbesc($data["alias"]),
499                 dbesc($data["name"]),
500                 dbesc($data["nick"]),
501                 dbesc(datetime_convert()),
502                 dbesc(datetime_convert()),
503                 dbesc(datetime_convert()),
504                 intval($contactid)
505         );
506
507         return $contactid;
508 }
509
510 /**
511  * @brief Returns posts from a given gcontact
512  *
513  * @param App $a argv application class
514  * @param int $gcontact_id Global contact
515  *
516  * @return string posts in HTML
517  */
518 function posts_from_gcontact($a, $gcontact_id) {
519
520         require_once('include/conversation.php');
521
522         // There are no posts with "uid = 0" with connector networks
523         // This speeds up the query a lot
524         $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
525         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
526                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
527         else
528                 $sql = "`item`.`uid` = %d";
529
530         if(get_config('system', 'old_pager')) {
531                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
532                         WHERE `gcontact-id` = %d and $sql",
533                         intval($gcontact_id),
534                         intval(local_user()));
535
536                 $a->set_pager_total($r[0]['total']);
537         }
538
539         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
540                         `author-name` AS `name`, `owner-avatar` AS `photo`,
541                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
542                 FROM `item` FORCE INDEX (`gcontactid_uid_created`)
543                 WHERE `gcontact-id` = %d AND $sql AND
544                         NOT `deleted` AND NOT `moderated` AND `visible`
545                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
546                 intval($gcontact_id),
547                 intval(local_user()),
548                 intval($a->pager['start']),
549                 intval($a->pager['itemspage'])
550         );
551
552         $o = conversation($a,$r,'community',false);
553
554         if(!get_config('system', 'old_pager')) {
555                 $o .= alt_pager($a,count($r));
556         } else {
557                 $o .= paginate($a);
558         }
559
560         return $o;
561 }
562
563 /**
564  * @brief set the gcontact-id in all item entries
565  *
566  * This job has to be started multiple times until all entries are set.
567  * It isn't started in the update function since it would consume too much time and can be done in the background.
568  */
569 function item_set_gcontact() {
570         define ('POST_UPDATE_VERSION', 1192);
571
572         // Was the script completed?
573         if (get_config("system", "post_update_version") >= POST_UPDATE_VERSION)
574                 return;
575
576         // Check if the first step is done (Setting "gcontact-id" in the item table)
577         $r = q("SELECT `author-link`, `author-name`, `author-avatar`, `uid`, `network` FROM `item` WHERE `gcontact-id` = 0 LIMIT 1000");
578         if (!$r) {
579                 // Are there unfinished entries in the thread table?
580                 $r = q("SELECT COUNT(*) AS `total` FROM `thread`
581                         INNER JOIN `item` ON `item`.`id` =`thread`.`iid`
582                         WHERE `thread`.`gcontact-id` = 0 AND
583                                 (`thread`.`uid` IN (SELECT `uid` from `user`) OR `thread`.`uid` = 0)");
584
585                 if ($r AND ($r[0]["total"] == 0)) {
586                         set_config("system", "post_update_version", POST_UPDATE_VERSION);
587                         return false;
588                 }
589
590                 // Update the thread table from the item table
591                 q("UPDATE `thread` INNER JOIN `item` ON `item`.`id`=`thread`.`iid`
592                                 SET `thread`.`gcontact-id` = `item`.`gcontact-id`
593                         WHERE `thread`.`gcontact-id` = 0 AND
594                                 (`thread`.`uid` IN (SELECT `uid` from `user`) OR `thread`.`uid` = 0)");
595
596                 return false;
597         }
598
599         $item_arr = array();
600         foreach ($r AS $item) {
601                 $index = $item["author-link"]."-".$item["uid"];
602                 $item_arr[$index] = array("author-link" => $item["author-link"],
603                                                 "uid" => $item["uid"],
604                                                 "network" => $item["network"]);
605         }
606
607         // Set the "gcontact-id" in the item table and add a new gcontact entry if needed
608         foreach($item_arr AS $item) {
609                 $gcontact_id = get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
610                                                 "photo" => $item['author-avatar'], "name" => $item['author-name']));
611                 q("UPDATE `item` SET `gcontact-id` = %d WHERE `uid` = %d AND `author-link` = '%s' AND `gcontact-id` = 0",
612                         intval($gcontact_id), intval($item["uid"]), dbesc($item["author-link"]));
613         }
614         return true;
615 }
616
617 /**
618  * @brief Returns posts from a given contact
619  *
620  * @param App $a argv application class
621  * @param int $contact_id contact
622  *
623  * @return string posts in HTML
624  */
625 function posts_from_contact($a, $contact_id) {
626
627         require_once('include/conversation.php');
628
629         $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id));
630         if (!$r)
631                 return false;
632
633         $contact = $r[0];
634
635         if(get_config('system', 'old_pager')) {
636                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
637                         WHERE `item`.`uid` = %d AND `author-link` IN ('%s', '%s')",
638                         intval(local_user()),
639                         dbesc(str_replace("https://", "http://", $contact["url"])),
640                         dbesc(str_replace("http://", "https://", $contact["url"])));
641
642                 $a->set_pager_total($r[0]['total']);
643         }
644
645         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
646                         `author-name` AS `name`, `owner-avatar` AS `photo`,
647                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
648                 FROM `item` FORCE INDEX (`uid_contactid_created`)
649                 WHERE `item`.`uid` = %d AND `contact-id` = %d
650                         AND `author-link` IN ('%s', '%s')
651                         AND NOT `deleted` AND NOT `moderated` AND `visible`
652                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
653                 intval(local_user()),
654                 intval($contact_id),
655                 dbesc(str_replace("https://", "http://", $contact["url"])),
656                 dbesc(str_replace("http://", "https://", $contact["url"])),
657                 intval($a->pager['start']),
658                 intval($a->pager['itemspage'])
659         );
660
661         $o .= conversation($a,$r,'community',false);
662
663         if(!get_config('system', 'old_pager'))
664                 $o .= alt_pager($a,count($r));
665         else
666                 $o .= paginate($a);
667
668         return $o;
669 }
670
671 /**
672  * @brief Returns a formatted location string from the given profile array
673  *
674  * @param array $profile Profile array (Generated from the "profile" table)
675  *
676  * @return string Location string
677  */
678 function formatted_location($profile) {
679         $location = '';
680
681         if($profile['locality'])
682                 $location .= $profile['locality'];
683
684         if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
685                 if($location)
686                         $location .= ', ';
687
688                 $location .= $profile['region'];
689         }
690
691         if($profile['country-name']) {
692                 if($location)
693                         $location .= ', ';
694
695                 $location .= $profile['country-name'];
696         }
697
698         return $location;
699 }
700 ?>