]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
ff5dc2aed72370204ae41ede6b90aa6f730c2e5c
[friendica.git] / include / conversation.php
1 <?php
2 /**
3  * @file include/conversation.php
4  */
5 use Friendica\App;
6 use Friendica\Content\Feature;
7 use Friendica\Core\Config;
8 use Friendica\Core\PConfig;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Object\Thread;
13 use Friendica\Object\Post;
14
15 require_once "include/bbcode.php";
16 require_once "include/acl_selectors.php";
17
18 function item_extract_images($body) {
19
20         $saved_image = array();
21         $orig_body = $body;
22         $new_body = '';
23
24         $cnt = 0;
25         $img_start = strpos($orig_body, '[img');
26         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
27         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
28         while (($img_st_close !== false) && ($img_end !== false)) {
29
30                 $img_st_close++; // make it point to AFTER the closing bracket
31                 $img_end += $img_start;
32
33                 if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
34                         // This is an embedded image
35
36                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
37                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
38
39                         $cnt++;
40                 } else {
41                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
42                 }
43
44                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
45
46                 if ($orig_body === false) {
47                         // in case the body ends on a closing image tag
48                         $orig_body = '';
49                 }
50
51                 $img_start = strpos($orig_body, '[img');
52                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
53                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
54         }
55
56         $new_body = $new_body . $orig_body;
57
58         return array('body' => $new_body, 'images' => $saved_image);
59 }
60
61 function item_redir_and_replace_images($body, $images, $cid) {
62
63         $origbody = $body;
64         $newbody = '';
65
66         $cnt = 1;
67         $pos = get_bb_tag_pos($origbody, 'url', 1);
68         while ($pos !== false && $cnt < 1000) {
69
70                 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
71                 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
72                                    . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
73
74                 $newbody .= substr($origbody, 0, $pos['start']['open']);
75                 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
76                 $origbody = substr($origbody, $pos['end']['close']);
77                 if ($origbody === false) {
78                         $origbody = '';
79                 }
80
81                 $subject = preg_replace($search, $replace, $subject);
82                 $newbody .= $subject;
83
84                 $cnt++;
85                 $pos = get_bb_tag_pos($origbody, 'url', 1);
86         }
87         $newbody .= $origbody;
88
89         $cnt = 0;
90         foreach ($images as $image) {
91                 /*
92                  * We're depending on the property of 'foreach' (specified on the PHP website) that
93                  * it loops over the array starting from the first element and going sequentially
94                  * to the last element.
95                  */
96                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
97                 $cnt++;
98         }
99         return $newbody;
100 }
101
102 /**
103  * Render actions localized
104  */
105 function localize_item(&$item) {
106
107         $extracted = item_extract_images($item['body']);
108         if ($extracted['images']) {
109                 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
110         }
111
112         /// @Separted ???
113         $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
114         if (activity_match($item['verb'], ACTIVITY_LIKE)
115                 || activity_match($item['verb'], ACTIVITY_DISLIKE)
116                 || activity_match($item['verb'], ACTIVITY_ATTEND)
117                 || activity_match($item['verb'], ACTIVITY_ATTENDNO)
118                 || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
119
120                 /// @TODO may hurt performance
121                 $r = q("SELECT * FROM `item`, `contact`
122                         WHERE `item`.`contact-id`=`contact`.`id`
123                         AND `item`.`uri`='%s'",
124                         dbesc($item['parent-uri']));
125                 if (!DBM::is_result($r)) {
126                         return;
127                 }
128                 $obj = $r[0];
129
130                 $author  = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
131                 $objauthor =  '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
132
133                 switch ($obj['verb']) {
134                         case ACTIVITY_POST:
135                                 switch ($obj['object-type']) {
136                                         case ACTIVITY_OBJ_EVENT:
137                                                 $post_type = t('event');
138                                                 break;
139                                         default:
140                                                 $post_type = t('status');
141                                 }
142                                 break;
143                         default:
144                                 if ($obj['resource-id']) {
145                                         $post_type = t('photo');
146                                         $m = array();
147                                         preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
148                                         $rr['plink'] = $m[1];
149                                 } else {
150                                         $post_type = t('status');
151                                 }
152                 }
153
154                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
155
156                 if (activity_match($item['verb'], ACTIVITY_LIKE)) {
157                         $bodyverb = t('%1$s likes %2$s\'s %3$s');
158                 }
159                 elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
160                         $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
161                 }
162                 elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
163                         $bodyverb = t('%1$s attends %2$s\'s %3$s');
164                 }
165                 elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
166                         $bodyverb = t('%1$s doesn\'t attend %2$s\'s %3$s');
167                 }
168                 elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
169                         $bodyverb = t('%1$s attends maybe %2$s\'s %3$s');
170                 }
171                 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
172
173         }
174         if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
175
176                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
177
178                 $Aname = $item['author-name'];
179                 $Alink = $item['author-link'];
180
181                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
182
183                 $obj = parse_xml_string($xmlhead.$item['object']);
184                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
185
186                 $Bname = $obj->title;
187                 $Blink = ""; $Bphoto = "";
188                 foreach ($links->link as $l) {
189                         $atts = $l->attributes();
190                         switch ($atts['rel']) {
191                                 case "alternate": $Blink = $atts['href'];
192                                 case "photo": $Bphoto = $atts['href'];
193                         }
194                 }
195
196                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
197                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
198                 if ($Bphoto != "") {
199                         $Bphoto = '[url=' . zrl($Blink) . '][img]' . $Bphoto . '[/img][/url]';
200                 }
201
202                 $item['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
203
204         }
205         if (stristr($item['verb'], ACTIVITY_POKE)) {
206                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
207                 if (! $verb) {
208                         return;
209                 }
210                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) {
211                         return;
212                 }
213
214                 $Aname = $item['author-name'];
215                 $Alink = $item['author-link'];
216
217                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
218
219                 $obj = parse_xml_string($xmlhead.$item['object']);
220                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
221
222                 $Bname = $obj->title;
223                 $Blink = "";
224                 $Bphoto = "";
225                 foreach ($links->link as $l) {
226                         $atts = $l->attributes();
227                         switch ($atts['rel']) {
228                                 case "alternate": $Blink = $atts['href'];
229                                 case "photo": $Bphoto = $atts['href'];
230                         }
231                 }
232
233                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
234                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
235                 if ($Bphoto != "") {
236                         $Bphoto = '[url=' . zrl($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
237                 }
238
239                 /*
240                  * we can't have a translation string with three positions but no distinguishable text
241                  * So here is the translate string.
242                  */
243                 $txt = t('%1$s poked %2$s');
244
245                 // now translate the verb
246                 $poked_t = trim(sprintf($txt, "", ""));
247                 $txt = str_replace( $poked_t, t($verb), $txt);
248
249                 // then do the sprintf on the translation string
250
251                 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
252
253         }
254
255         if (activity_match($item['verb'], ACTIVITY_TAG)) {
256                 /// @TODO may hurt performance "joining" two tables + asterisk
257                 $r = q("SELECT * FROM `item`, `contact`
258                         WHERE `item`.`contact-id`=`contact`.`id`
259                         AND `item`.`uri`='%s'",
260                         dbesc($item['parent-uri']));
261
262                 if (!DBM::is_result($r)) {
263                         return;
264                 }
265
266                 $obj = $r[0];
267
268                 $author  = '[url=' . zrl($item['author-link']) . ']' . $item['author-name'] . '[/url]';
269                 $objauthor =  '[url=' . zrl($obj['author-link']) . ']' . $obj['author-name'] . '[/url]';
270
271                 switch ($obj['verb']) {
272                         case ACTIVITY_POST:
273                                 switch ($obj['object-type']) {
274                                         case ACTIVITY_OBJ_EVENT:
275                                                 $post_type = t('event');
276                                                 break;
277                                         default:
278                                                 $post_type = t('status');
279                                 }
280                                 break;
281                         default:
282                                 if ($obj['resource-id']) {
283                                         $post_type = t('photo');
284                                         $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
285                                         $rr['plink'] = $m[1];
286                                 } else {
287                                         $post_type = t('status');
288                                 }
289                                 // Let's break everthing ... ;-)
290                                 break;
291                 }
292                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
293
294                 $parsedobj = parse_xml_string($xmlhead.$item['object']);
295
296                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
297                 $item['body'] = sprintf( t('%1$s tagged %2$s\'s %3$s with %4$s'), $author, $objauthor, $plink, $tag );
298
299         }
300         if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
301
302                 if ($item['object-type'] == "") {
303                         return;
304                 }
305
306                 $Aname = $item['author-name'];
307                 $Alink = $item['author-link'];
308
309                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
310
311                 $obj = parse_xml_string($xmlhead.$item['object']);
312                 if (strlen($obj->id)) {
313                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
314                                         dbesc($obj->id),
315                                         intval($item['uid'])
316                         );
317
318                         if (DBM::is_result($r) && $r[0]['plink']) {
319                                 $target = $r[0];
320                                 $Bname = $target['author-name'];
321                                 $Blink = $target['author-link'];
322                                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
323                                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
324                                 $P = '[url=' . $target['plink'] . ']' . t('post/item') . '[/url]';
325                                 $item['body'] = sprintf( t('%1$s marked %2$s\'s %3$s as favorite'), $A, $B, $P)."\n";
326                         }
327                 }
328         }
329         $matches = null;
330         if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
331                 foreach ($matches as $mtch) {
332                         if (! strpos($mtch[1], 'zrl=')) {
333                                 $item['body'] = str_replace($mtch[0], '@[url=' . zrl($mtch[1]) . ']', $item['body']);
334                         }
335                 }
336         }
337
338         // add zrl's to public images
339         $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
340         if (preg_match($photo_pattern, $item['body'])) {
341                 $photo_replace = '[url=' . zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5'  . '[/img][/url]';
342                 $item['body'] = bb_tag_preg_replace($photo_pattern, $photo_replace, 'url', $item['body']);
343         }
344
345         // add sparkle links to appropriate permalinks
346
347         $x = stristr($item['plink'],'/display/');
348         if ($x) {
349                 $sparkle = false;
350                 $y = best_link_url($item, $sparkle);
351
352                 if (strstr($y, '/redir/')) {
353                         $item['plink'] = $y . '?f=&url=' . $item['plink'];
354                 }
355         }
356 }
357
358 /**
359  * Count the total of comments on this item and its desendants
360  * @TODO proper type-hint + doc-tag
361  */
362 function count_descendants($item) {
363         $total = count($item['children']);
364
365         if ($total > 0) {
366                 foreach ($item['children'] as $child) {
367                         if (! visible_activity($child)) {
368                                 $total --;
369                         }
370                         $total += count_descendants($child);
371                 }
372         }
373
374         return $total;
375 }
376
377 function visible_activity($item) {
378
379         /*
380          * likes (etc.) can apply to other things besides posts. Check if they are post children,
381          * in which case we handle them specially
382          */
383         $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
384         foreach ($hidden_activities as $act) {
385                 if (activity_match($item['verb'], $act)) {
386                         return false;
387                 }
388         }
389
390         if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
391                 if (! (($item['self']) && ($item['uid'] == local_user()))) {
392                         return false;
393                 }
394         }
395
396         return true;
397 }
398
399 /**
400  * @brief SQL query for items
401  */
402 function item_query() {
403         return "SELECT " . item_fieldlists() . " FROM `item` " .
404                 item_joins() . " WHERE " . item_condition();
405 }
406
407 /**
408  * @brief List of all data fields that are needed for displaying items
409  */
410 function item_fieldlists() {
411
412 /*
413 These Fields are not added below (yet). They are here to for bug search.
414 `item`.`type`,
415 `item`.`extid`,
416 `item`.`changed`,
417 `item`.`moderated`,
418 `item`.`target-type`,
419 `item`.`target`,
420 `item`.`resource-id`,
421 `item`.`tag`,
422 `item`.`inform`,
423 `item`.`pubmail`,
424 `item`.`visible`,
425 `item`.`spam`,
426 `item`.`bookmark`,
427 `item`.`unseen`,
428 `item`.`deleted`,
429 `item`.`origin`,
430 `item`.`forum_mode`,
431 `item`.`last-child`,
432 `item`.`mention`,
433 `item`.`global`,
434 `item`.`gcontact-id`,
435 `item`.`shadow`,
436 */
437
438         return "`item`.`author-id`, `item`.`author-link`, `item`.`author-name`, `item`.`author-avatar`,
439                 `item`.`owner-id`, `item`.`owner-link`, `item`.`owner-name`, `item`.`owner-avatar`,
440                 `item`.`contact-id`, `item`.`uid`, `item`.`id`, `item`.`parent`,
441                 `item`.`uri`, `item`.`thr-parent`, `item`.`parent-uri`,
442                 `item`.`commented`, `item`.`created`, `item`.`edited`, `item`.`received`,
443                 `item`.`verb`, `item`.`object-type`, `item`.`postopts`, `item`.`plink`,
444                 `item`.`guid`, `item`.`wall`, `item`.`private`, `item`.`starred`,
445                 `item`.`title`, `item`.`body`, `item`.`file`, `item`.`event-id`,
446                 `item`.`location`, `item`.`coord`, `item`.`app`, `item`.`attach`,
447                 `item`.`rendered-hash`, `item`.`rendered-html`, `item`.`object`,
448                 `item`.`allow_cid`, `item`.`allow_gid`, `item`.`deny_cid`, `item`.`deny_gid`,
449                 `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
450
451                 `author`.`thumb` AS `author-thumb`, `owner`.`thumb` AS `owner-thumb`,
452
453                 `contact`.`network`, `contact`.`url`, `contact`.`name`, `contact`.`writable`,
454                 `contact`.`self`, `contact`.`id` AS `cid`, `contact`.`alias`,
455
456                 `event`.`created` AS `event-created`, `event`.`edited` AS `event-edited`,
457                 `event`.`start` AS `event-start`,`event`.`finish` AS `event-finish`,
458                 `event`.`summary` AS `event-summary`,`event`.`desc` AS `event-desc`,
459                 `event`.`location` AS `event-location`, `event`.`type` AS `event-type`,
460                 `event`.`nofinish` AS `event-nofinish`,`event`.`adjust` AS `event-adjust`,
461                 `event`.`ignore` AS `event-ignore`, `event`.`id` AS `event-id`";
462 }
463
464 /**
465  * @brief SQL join for contacts that are needed for displaying items
466  */
467 function item_joins() {
468         return "STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND
469                 (NOT `contact`.`blocked` OR `contact`.`pending`)
470                 LEFT JOIN `contact` AS `author` ON `author`.`id`=`item`.`author-id`
471                 LEFT JOIN `contact` AS `owner` ON `owner`.`id`=`item`.`owner-id`
472                 LEFT JOIN `event` ON `event-id` = `event`.`id`";
473 }
474
475 /**
476  * @brief SQL condition for items that are needed for displaying items
477  */
478 function item_condition() {
479         return "`item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`";
480 }
481
482 /**
483  * "Render" a conversation or list of items for HTML display.
484  * There are two major forms of display:
485  *      - Sequential or unthreaded ("New Item View" or search results)
486  *      - conversation view
487  * The $mode parameter decides between the various renderings and also
488  * figures out how to determine page owner and other contextual items
489  * that are based on unique features of the calling module.
490  *
491  */
492 function conversation(App $a, $items, $mode, $update, $preview = false) {
493         require_once 'include/bbcode.php';
494         require_once 'mod/proxy.php';
495
496         $ssl_state = ((local_user()) ? true : false);
497
498         $profile_owner = 0;
499         $live_update_div = '';
500
501         $arr_blocked = null;
502
503         if (local_user()) {
504                 $str_blocked = PConfig::get(local_user(), 'system', 'blocked');
505                 if ($str_blocked) {
506                         $arr_blocked = explode(',', $str_blocked);
507                         for ($x = 0; $x < count($arr_blocked); $x ++) {
508                                 $arr_blocked[$x] = trim($arr_blocked[$x]);
509                         }
510                 }
511
512         }
513
514         $previewing = (($preview) ? ' preview ' : '');
515
516         if ($mode === 'network') {
517                 $profile_owner = local_user();
518                 if (!$update) {
519                         /*
520                          * The special div is needed for liveUpdate to kick in for this page.
521                          * We only launch liveUpdate if you aren't filtering in some incompatible
522                          * way and also you aren't writing a comment (discovered in javascript).
523                          */
524                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
525                                 . "<script> var profile_uid = " . $_SESSION['uid']
526                                 . "; var netargs = '" . substr($a->cmd, 8)
527                                 . '?f='
528                                 . ((x($_GET, 'cid'))    ? '&cid='    . $_GET['cid']    : '')
529                                 . ((x($_GET, 'search')) ? '&search=' . $_GET['search'] : '')
530                                 . ((x($_GET, 'star'))   ? '&star='   . $_GET['star']   : '')
531                                 . ((x($_GET, 'order'))  ? '&order='  . $_GET['order']  : '')
532                                 . ((x($_GET, 'bmark'))  ? '&bmark='  . $_GET['bmark']  : '')
533                                 . ((x($_GET, 'liked'))  ? '&liked='  . $_GET['liked']  : '')
534                                 . ((x($_GET, 'conv'))   ? '&conv='   . $_GET['conv']   : '')
535                                 . ((x($_GET, 'spam'))   ? '&spam='   . $_GET['spam']   : '')
536                                 . ((x($_GET, 'nets'))   ? '&nets='   . $_GET['nets']   : '')
537                                 . ((x($_GET, 'cmin'))   ? '&cmin='   . $_GET['cmin']   : '')
538                                 . ((x($_GET, 'cmax'))   ? '&cmax='   . $_GET['cmax']   : '')
539                                 . ((x($_GET, 'file'))   ? '&file='   . $_GET['file']   : '')
540
541                                 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
542                 }
543         } elseif ($mode === 'profile') {
544                 $profile_owner = $a->profile['profile_uid'];
545
546                 if (!$update) {
547                         $tab = 'posts';
548                         if (x($_GET, 'tab')) {
549                                 $tab = notags(trim($_GET['tab']));
550                         }
551                         if ($tab === 'posts') {
552                                 /*
553                                  * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
554                                  * because browser prefetching might change it on us. We have to deliver it with the page.
555                                  */
556
557                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
558                                         . "<script> var profile_uid = " . $a->profile['profile_uid']
559                                         . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
560                         }
561                 }
562         } elseif ($mode === 'notes') {
563                 $profile_owner = local_user();
564                 if (!$update) {
565                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
566                                 . "<script> var profile_uid = " . local_user()
567                                 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
568                 }
569         } elseif ($mode === 'display') {
570                 $profile_owner = $a->profile['uid'];
571                 if (!$update) {
572                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
573                                 . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
574                                 . " var profile_page = 1; </script>";
575                 }
576         } elseif ($mode === 'community') {
577                 if (!$community_readonly) {
578                         $items = community_add_items($items);
579                 }
580                 $profile_owner = 0;
581 // Currently deactivated. Will be activated when we can comment on the community page
582 //              if (!$update) {
583 //                      $live_update_div = '<div id="live-community"></div>' . "\r\n"
584 //                              . "<script> var profile_uid = -1; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
585 //              }
586         } elseif ($mode === 'search') {
587                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
588         }
589
590         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
591
592
593         if ($update) {
594                 $return_url = $_SESSION['return_url'];
595         } else {
596                 $return_url = $_SESSION['return_url'] = $a->query_string;
597         }
598
599         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
600         call_hooks('conversation_start',$cb);
601
602         $items = $cb['items'];
603
604         $cmnt_tpl    = get_markup_template('comment_item.tpl');
605         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
606
607         $conv_responses = array(
608                 'like' => array('title' => t('Likes','title')), 'dislike' => array('title' => t('Dislikes','title')),
609                 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
610         );
611
612         // array with html for each thread (parent+comments)
613         $threads = array();
614         $threadsid = -1;
615
616         $page_template = get_markup_template("conversation.tpl");
617
618         if ($items && count($items)) {
619                 $community_readonly = ($mode === 'community');
620
621                 // Currently behind a config value. This allows the commenting and sharing of every public item.
622                 if (Config::get('system', 'comment_public') && local_user()) {
623                         if ($mode === 'community') {
624                                 $community_readonly = false;
625                                 $writable = true;
626                         } else {
627                                 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], array(NETWORK_OSTATUS, NETWORK_DIASPORA));
628                         }
629                 } else {
630                         $writable = false;
631                 }
632
633                 if ($mode === 'network-new' || $mode === 'search' || $community_readonly) {
634
635                         /*
636                          * "New Item View" on network page or search page results
637                          * - just loop through the items and format them minimally for display
638                          */
639
640                         /// @TODO old lost code?
641                         // $tpl = get_markup_template('search_item.tpl');
642                         $tpl = 'search_item.tpl';
643
644                         foreach ($items as $item) {
645
646                                 if ($arr_blocked) {
647                                         $blocked = false;
648                                         foreach ($arr_blocked as $b) {
649                                                 if ($b && link_compare($item['author-link'], $b)) {
650                                                         $blocked = true;
651                                                         break;
652                                                 }
653                                         }
654                                         if ($blocked) {
655                                                 continue;
656                                         }
657                                 }
658
659
660                                 $threadsid++;
661
662                                 $owner_url   = '';
663                                 $owner_name  = '';
664                                 $sparkle     = '';
665
666                                 // prevent private email from leaking.
667                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
668                                         continue;
669                                 }
670
671                                 $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
672                                 if ($item['author-link'] && (! $item['author-name'])) {
673                                         $profile_name = $item['author-link'];
674                                 }
675
676                                 $tags = array();
677                                 $hashtags = array();
678                                 $mentions = array();
679
680                                 $searchpath = System::baseUrl()."/search?tag=";
681
682                                 $taglist = dba::select('term', array('type', 'term', 'url'),
683                                                         array("`otype` = ? AND `oid` = ? AND `type` IN (?, ?)", TERM_OBJ_POST, $item['id'], TERM_HASHTAG, TERM_MENTION),
684                                                         array('order' => array('tid')));
685
686                                 while ($tag = dba::fetch($taglist)) {
687                                         if ($tag["url"] == "") {
688                                                 $tag["url"] = $searchpath . strtolower($tag["term"]);
689                                         }
690
691                                         $tag["url"] = best_link_url($item, $sp, $tag["url"]);
692
693                                         if ($tag["type"] == TERM_HASHTAG) {
694                                                 $hashtags[] = "#<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
695                                                 $prefix = "#";
696                                         } elseif ($tag["type"] == TERM_MENTION) {
697                                                 $mentions[] = "@<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
698                                                 $prefix = "@";
699                                         }
700                                         $tags[] = $prefix."<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
701                                 }
702                                 dba::close($taglist);
703
704                                 $sp = false;
705                                 $profile_link = best_link_url($item, $sp);
706                                 if ($profile_link === 'mailbox') {
707                                         $profile_link = '';
708                                 }
709
710                                 if ($sp) {
711                                         $sparkle = ' sparkle';
712                                 } else {
713                                         $profile_link = zrl($profile_link);
714                                 }
715
716                                 if (!x($item, 'author-thumb') || ($item['author-thumb'] == "")) {
717                                         $author_contact = Contact::getDetailsByURL($item['author-link'], $profile_owner);
718                                         if ($author_contact["thumb"]) {
719                                                 $item['author-thumb'] = $author_contact["thumb"];
720                                         } else {
721                                                 $item['author-thumb'] = $item['author-avatar'];
722                                         }
723                                 }
724
725                                 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
726                                         $owner_contact = Contact::getDetailsByURL($item['owner-link'], $profile_owner);
727                                         if ($owner_contact["thumb"]) {
728                                                 $item['owner-thumb'] = $owner_contact["thumb"];
729                                         } else {
730                                                 $item['owner-thumb'] = $item['owner-avatar'];
731                                         }
732                                 }
733
734                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
735                                 call_hooks('render_location',$locate);
736
737                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
738
739                                 localize_item($item);
740                                 if ($mode === 'network-new') {
741                                         $dropping = true;
742                                 } else {
743                                         $dropping = false;
744                                 }
745
746                                 $drop = array(
747                                         'dropping' => $dropping,
748                                         'pagedrop' => $page_dropping,
749                                         'select' => t('Select'),
750                                         'delete' => t('Delete'),
751                                 );
752
753                                 $star = false;
754                                 $isstarred = "unstarred";
755
756                                 $lock = false;
757                                 $likebuttons = false;
758                                 $shareable = false;
759
760                                 $body = prepare_body($item, true, $preview);
761
762                                 list($categories, $folders) = get_cats_and_terms($item);
763
764                                 $profile_name_e = $profile_name;
765                                 $item['title_e'] = $item['title'];
766                                 $body_e = $body;
767                                 $tags_e = $tags;
768                                 $hashtags_e = $hashtags;
769                                 $mentions_e = $mentions;
770                                 $location_e = $location;
771                                 $owner_name_e = $owner_name;
772
773                                 if ($item['item_network'] == "") {
774                                         $item['item_network'] = $item['network'];
775                                 }
776
777                                 $tmp_item = array(
778                                         'template' => $tpl,
779                                         'id' => (($preview) ? 'P0' : $item['item_id']),
780                                         'guid' => (($preview) ? 'Q0' : $item['guid']),
781                                         'network' => $item['item_network'],
782                                         'network_name' => network_to_name($item['item_network'], $profile_link),
783                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
784                                         'profile_url' => $profile_link,
785                                         'item_photo_menu' => item_photo_menu($item),
786                                         'name' => $profile_name_e,
787                                         'sparkle' => $sparkle,
788                                         'lock' => $lock,
789                                         'thumb' => System::removedBaseUrl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
790                                         'title' => $item['title_e'],
791                                         'body' => $body_e,
792                                         'tags' => $tags_e,
793                                         'hashtags' => $hashtags_e,
794                                         'mentions' => $mentions_e,
795                                         'txt_cats' => t('Categories:'),
796                                         'txt_folders' => t('Filed under:'),
797                                         'has_cats' => ((count($categories)) ? 'true' : ''),
798                                         'has_folders' => ((count($folders)) ? 'true' : ''),
799                                         'categories' => $categories,
800                                         'folders' => $folders,
801                                         'text' => strip_tags($body_e),
802                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
803                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
804                                         'location' => $location_e,
805                                         'indent' => '',
806                                         'owner_name' => $owner_name_e,
807                                         'owner_url' => $owner_url,
808                                         'owner_photo' => System::removedBaseUrl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
809                                         'plink' => get_plink($item),
810                                         'edpost' => false,
811                                         'isstarred' => $isstarred,
812                                         'star' => $star,
813                                         'drop' => $drop,
814                                         'vote' => $likebuttons,
815                                         'like' => '',
816                                         'dislike' => '',
817                                         'comment' => '',
818                                         'conv' => (($preview) ? '' : array('href'=> 'display/'.$item['guid'], 'title'=> t('View in context'))),
819                                         'previewing' => $previewing,
820                                         'wait' => t('Please wait'),
821                                         'thread_level' => 1,
822                                 );
823
824                                 $arr = array('item' => $item, 'output' => $tmp_item);
825                                 call_hooks('display_item', $arr);
826
827                                 $threads[$threadsid]['id'] = $item['item_id'];
828                                 $threads[$threadsid]['network'] = $item['item_network'];
829                                 $threads[$threadsid]['items'] = array($arr['output']);
830
831                         }
832                 } else {
833                         // Normal View
834                         $page_template = get_markup_template("threaded_conversation.tpl");
835
836                         $conv = new Thread($mode, $preview, $writable);
837
838                         /*
839                          * get all the topmost parents
840                          * this shouldn't be needed, as we should have only them in our array
841                          * But for now, this array respects the old style, just in case
842                          */
843                         $threads = array();
844                         foreach ($items as $item) {
845
846                                 if ($arr_blocked) {
847                                         $blocked = false;
848                                         foreach ($arr_blocked as $b) {
849                                                 if ($b && link_compare($item['author-link'], $b)) {
850                                                         $blocked = true;
851                                                         break;
852                                                 }
853                                         }
854                                         if ($blocked) {
855                                                 continue;
856                                         }
857                                 }
858
859                                 // Can we put this after the visibility check?
860                                 builtin_activity_puller($item, $conv_responses);
861
862                                 // Only add what is visible
863                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
864                                         continue;
865                                 }
866
867                                 if (! visible_activity($item)) {
868                                         continue;
869                                 }
870
871                                 call_hooks('display_item', $arr);
872
873                                 $item['pagedrop'] = $page_dropping;
874
875                                 if ($item['id'] == $item['parent']) {
876                                         $item_object = new Post($item);
877                                         $conv->addParent($item_object);
878                                 }
879                         }
880
881                         $threads = $conv->getTemplateData($conv_responses);
882
883                         if (!$threads) {
884                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
885                                 $threads = array();
886                         }
887                 }
888         }
889
890         $o = replace_macros($page_template, array(
891                 '$baseurl' => System::baseUrl($ssl_state),
892                 '$return_path' => $a->query_string,
893                 '$live_update' => $live_update_div,
894                 '$remove' => t('remove'),
895                 '$mode' => $mode,
896                 '$user' => $a->user,
897                 '$threads' => $threads,
898                 '$dropping' => ($page_dropping && Feature::isEnabled(local_user(), 'multi_delete') ? t('Delete Selected Items') : False),
899         ));
900
901         return $o;
902 }
903
904 /**
905  * @brief Add comments to top level entries that had been fetched before
906  *
907  * The system will fetch the comments for the local user whenever possible.
908  * This behaviour is currently needed to allow commenting on Friendica posts.
909  *
910  * @param array $parents Parent items
911  *
912  * @return array items with parents and comments
913  */
914 function community_add_items($parents) {
915         $max_comments = Config::get("system", "max_comments", 100);
916
917         $items = array();
918
919         foreach ($parents AS $parent) {
920                 $thread_items = dba::p(item_query()." AND `item`.`uid` = ?
921                         AND `item`.`parent-uri` = ?
922                         ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
923                         local_user(),
924                         $parent['uri']
925                 );
926                 $comments = dba::inArray($thread_items);
927
928                 if (count($comments) == 0) {
929                         $thread_items = dba::p(item_query()." AND `item`.`uid` = 0
930                                 AND `item`.`parent-uri` = ?
931                                 ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
932                                 $parent['uri']
933                         );
934                         $comments = dba::inArray($thread_items);
935                 }
936
937                 if (count($comments) != 0) {
938                         $items = array_merge($items, $comments);
939                 }
940         }
941
942         foreach ($items as $index => $item) {
943                 if ($item['uid'] == 0) {
944                         $items[$index]['writable'] = in_array($item['network'], [NETWORK_DIASPORA, NETWORK_OSTATUS]);
945                 }
946         }
947
948         $items = conv_sort($items, "`commented`");
949
950         return $items;
951 }
952
953 function best_link_url($item, &$sparkle, $url = '') {
954
955         $best_url = '';
956         $sparkle  = false;
957
958         $clean_url = normalise_link($item['author-link']);
959
960         if (local_user()) {
961                 $r = dba::select('contact', array('id'),
962                         array('network' => NETWORK_DFRN, 'uid' => local_user(), 'nurl' => normalise_link($clean_url), 'pending' => false),
963                         array('limit' => 1));
964                 if (DBM::is_result($r)) {
965                         $best_url = 'redir/' . $r['id'];
966                         $sparkle = true;
967                         if ($url != '') {
968                                 $hostname = get_app()->get_hostname();
969                                 if (!strstr($url, $hostname)) {
970                                         $best_url .= "?url=".$url;
971                                 } else {
972                                         $best_url = $url;
973                                 }
974                         }
975                 }
976         }
977         if (! $best_url) {
978                 if ($url != '') {
979                         $best_url = $url;
980                 } elseif (strlen($item['author-link'])) {
981                         $best_url = $item['author-link'];
982                 } else {
983                         $best_url = $item['url'];
984                 }
985         }
986
987         return $best_url;
988 }
989
990
991 function item_photo_menu($item) {
992         $sub_link = '';
993         $poke_link = '';
994         $contact_url = '';
995         $pm_url = '';
996         $status_link = '';
997         $photos_link = '';
998         $posts_link = '';
999         $network = '';
1000
1001         if ((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
1002                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
1003         }
1004
1005         $sparkle = false;
1006         $profile_link = best_link_url($item, $sparkle);
1007         if ($profile_link === 'mailbox') {
1008                 $profile_link = '';
1009         }
1010
1011         $cid = 0;
1012         $network = '';
1013         $rel = 0;
1014         $r = dba::select('contact', array('id', 'network', 'rel'), array('uid' => local_user(), 'nurl' => normalise_link($item['author-link'])), array('limit' => 1));
1015         if (DBM::is_result($r)) {
1016                 $cid = $r['id'];
1017                 $network = $r['network'];
1018                 $rel = $r['rel'];
1019         }
1020
1021         if ($sparkle) {
1022                 $status_link = $profile_link . '?url=status';
1023                 $photos_link = $profile_link . '?url=photos';
1024                 $profile_link = $profile_link . '?url=profile';
1025                 $zurl = '';
1026         } else {
1027                 $profile_link = zrl($profile_link);
1028         }
1029
1030         if ($cid && !$item['self']) {
1031                 $poke_link = 'poke/?f=&c=' . $cid;
1032                 $contact_url = 'contacts/' . $cid;
1033                 $posts_link = 'contacts/' . $cid . '/posts';
1034
1035                 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA))) {
1036                         $pm_url = 'message/new/' . $cid;
1037                 }
1038         }
1039
1040         if (local_user()) {
1041                 $menu = array(
1042                         t('Follow Thread') => $sub_link,
1043                         t('View Status') => $status_link,
1044                         t('View Profile') => $profile_link,
1045                         t('View Photos') => $photos_link,
1046                         t('Network Posts') => $posts_link,
1047                         t('View Contact') => $contact_url,
1048                         t('Send PM') => $pm_url
1049                 );
1050
1051                 if ($network == NETWORK_DFRN) {
1052                         $menu[t("Poke")] = $poke_link;
1053                 }
1054
1055                 if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
1056                         in_array($item['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
1057                         $menu[t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
1058                 }
1059         } else {
1060                 $menu = array(t('View Profile') => $item['author-link']);
1061         }
1062
1063         $args = array('item' => $item, 'menu' => $menu);
1064
1065         call_hooks('item_photo_menu', $args);
1066
1067         $menu = $args['menu'];
1068
1069         $o = '';
1070         foreach ($menu as $k => $v) {
1071                 if (strpos($v, 'javascript:') === 0) {
1072                         $v = substr($v, 11);
1073                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1074                 } elseif ($v!='') {
1075                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1076                 }
1077         }
1078         return $o;
1079 }
1080
1081 /**
1082  * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
1083  * Increments the count of each matching activity and adds a link to the author as needed.
1084  *
1085  * @param array $item
1086  * @param array &$conv_responses (already created with builtin activity structure)
1087  * @return void
1088  */
1089 function builtin_activity_puller($item, &$conv_responses) {
1090         foreach ($conv_responses as $mode => $v) {
1091                 $url = '';
1092                 $sparkle = '';
1093
1094                 switch ($mode) {
1095                         case 'like':
1096                                 $verb = ACTIVITY_LIKE;
1097                                 break;
1098                         case 'dislike':
1099                                 $verb = ACTIVITY_DISLIKE;
1100                                 break;
1101                         case 'attendyes':
1102                                 $verb = ACTIVITY_ATTEND;
1103                                 break;
1104                         case 'attendno':
1105                                 $verb = ACTIVITY_ATTENDNO;
1106                                 break;
1107                         case 'attendmaybe':
1108                                 $verb = ACTIVITY_ATTENDMAYBE;
1109                                 break;
1110                         default:
1111                                 return;
1112                                 break;
1113                 }
1114
1115                 if ((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
1116                         $url = $item['author-link'];
1117                         if ((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'], $item['url']))) {
1118                                 $url = 'redir/' . $item['contact-id'];
1119                                 $sparkle = ' class="sparkle" ';
1120                         } else {
1121                                 $url = zrl($url);
1122                         }
1123
1124                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
1125
1126                         if (! $item['thr-parent']) {
1127                                 $item['thr-parent'] = $item['parent-uri'];
1128                         }
1129
1130                         if (! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l']))
1131                                 && (is_array($conv_responses[$mode][$item['thr-parent'] . '-l'])))) {
1132                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = array();
1133                         }
1134
1135                         // only list each unique author once
1136                         if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
1137                                 continue;
1138                         }
1139
1140                         if (! isset($conv_responses[$mode][$item['thr-parent']])) {
1141                                 $conv_responses[$mode][$item['thr-parent']] = 1;
1142                         } else {
1143                                 $conv_responses[$mode][$item['thr-parent']] ++;
1144                         }
1145
1146                         if (public_contact() == $item['author-id']) {
1147                                 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
1148                         }
1149
1150                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1151
1152                         // there can only be one activity verb per item so if we found anything, we can stop looking
1153                         return;
1154                 }
1155         }
1156 }
1157
1158 /**
1159  * Format the vote text for a profile item
1160  * @param int $cnt = number of people who vote the item
1161  * @param array $arr = array of pre-linked names of likers/dislikers
1162  * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1163  * @param int $id  = item id
1164  * @return formatted text
1165  */
1166 function format_like($cnt, array $arr, $type, $id) {
1167         $o = '';
1168         $expanded = '';
1169
1170         if ($cnt == 1) {
1171                 $likers = $arr[0];
1172
1173                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1174                 // list which show all likers
1175                 switch ($type) {
1176                         case 'like' :
1177                                 $phrase = sprintf( t('%s likes this.'), $likers);
1178                                 break;
1179                         case 'dislike' :
1180                                 $phrase = sprintf( t('%s doesn\'t like this.'), $likers);
1181                                 break;
1182                         case 'attendyes' :
1183                                 $phrase = sprintf( t('%s attends.'), $likers);
1184                                 break;
1185                         case 'attendno' :
1186                                 $phrase = sprintf( t('%s doesn\'t attend.'), $likers);
1187                                 break;
1188                         case 'attendmaybe' :
1189                                 $phrase = sprintf( t('%s attends maybe.'), $likers);
1190                                 break;
1191                 }
1192         }
1193
1194         if ($cnt > 1) {
1195                 $total = count($arr);
1196                 if ($total >= MAX_LIKERS) {
1197                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1198                 }
1199                 if ($total < MAX_LIKERS) {
1200                         $last = t('and') . ' ' . $arr[count($arr)-1];
1201                         $arr2 = array_slice($arr, 0, -1);
1202                         $str = implode(', ', $arr2) . ' ' . $last;
1203                 }
1204                 if ($total >= MAX_LIKERS) {
1205                         $str = implode(', ', $arr);
1206                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
1207                 }
1208
1209                 $likers = $str;
1210
1211                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1212
1213                 switch ($type) {
1214                         case 'like':
1215                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> like this'), $spanatts, $cnt);
1216                                 $explikers = sprintf( t('%s like this.'), $likers);
1217                                 break;
1218                         case 'dislike':
1219                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t like this'), $spanatts, $cnt);
1220                                 $explikers = sprintf( t('%s don\'t like this.'), $likers);
1221                                 break;
1222                         case 'attendyes':
1223                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend'), $spanatts, $cnt);
1224                                 $explikers = sprintf( t('%s attend.'), $likers);
1225                                 break;
1226                         case 'attendno':
1227                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t attend'), $spanatts, $cnt);
1228                                 $explikers = sprintf( t('%s don\'t attend.'), $likers);
1229                                 break;
1230                         case 'attendmaybe':
1231                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend maybe'), $spanatts, $cnt);
1232                                 $explikers = sprintf( t('%s anttend maybe.'), $likers);
1233                                 break;
1234                 }
1235
1236                 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1237         }
1238
1239         $phrase .= EOL ;
1240         $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), array(
1241                 '$phrase' => $phrase,
1242                 '$type' => $type,
1243                 '$id' => $id
1244         ));
1245         $o .= $expanded;
1246
1247         return $o;
1248 }
1249
1250 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1251 {
1252         $o = '';
1253
1254         $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '';
1255
1256         $tpl = get_markup_template('jot-header.tpl');
1257         $a->page['htmlhead'] .= replace_macros($tpl, array(
1258                 '$newpost'   => 'true',
1259                 '$baseurl'   => System::baseUrl(true),
1260                 '$geotag'    => $geotag,
1261                 '$nickname'  => $x['nickname'],
1262                 '$ispublic'  => t('Visible to <strong>everybody</strong>'),
1263                 '$linkurl'   => t('Please enter a link URL:'),
1264                 '$vidurl'    => t("Please enter a video link/URL:"),
1265                 '$audurl'    => t("Please enter an audio link/URL:"),
1266                 '$term'      => t('Tag term:'),
1267                 '$fileas'    => t('Save to Folder:'),
1268                 '$whereareu' => t('Where are you right now?'),
1269                 '$delitems'  => t('Delete item(s)?')
1270         ));
1271
1272         $tpl = get_markup_template('jot-end.tpl');
1273         $a->page['end'] .= replace_macros($tpl, array(
1274                 '$newpost'   => 'true',
1275                 '$baseurl'   => System::baseUrl(true),
1276                 '$geotag'    => $geotag,
1277                 '$nickname'  => $x['nickname'],
1278                 '$ispublic'  => t('Visible to <strong>everybody</strong>'),
1279                 '$linkurl'   => t('Please enter a link URL:'),
1280                 '$vidurl'    => t("Please enter a video link/URL:"),
1281                 '$audurl'    => t("Please enter an audio link/URL:"),
1282                 '$term'      => t('Tag term:'),
1283                 '$fileas'    => t('Save to Folder:'),
1284                 '$whereareu' => t('Where are you right now?')
1285         ));
1286
1287         $jotplugins = '';
1288         call_hooks('jot_tool', $jotplugins);
1289
1290         // Private/public post links for the non-JS ACL form
1291         $private_post = 1;
1292         if (x($_REQUEST, 'public')) {
1293                 $private_post = 0;
1294         }
1295
1296         $query_str = $a->query_string;
1297         if (strpos($query_str, 'public=1') !== false) {
1298                 $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1299         }
1300
1301         /*
1302          * I think $a->query_string may never have ? in it, but I could be wrong
1303          * It looks like it's from the index.php?q=[etc] rewrite that the web
1304          * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1305          */
1306         if (strpos($query_str, '?') === false) {
1307                 $public_post_link = '?public=1';
1308         } else {
1309                 $public_post_link = '&public=1';
1310         }
1311
1312         // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1313         $tpl = get_markup_template("jot.tpl");
1314
1315         $o .= replace_macros($tpl,array(
1316                 '$return_path'  => $query_str,
1317                 '$action'       => 'item',
1318                 '$share'        => defaults($x, 'button', t('Share')),
1319                 '$upload'       => t('Upload photo'),
1320                 '$shortupload'  => t('upload photo'),
1321                 '$attach'       => t('Attach file'),
1322                 '$shortattach'  => t('attach file'),
1323                 '$weblink'      => t('Insert web link'),
1324                 '$shortweblink' => t('web link'),
1325                 '$video'        => t('Insert video link'),
1326                 '$shortvideo'   => t('video link'),
1327                 '$audio'        => t('Insert audio link'),
1328                 '$shortaudio'   => t('audio link'),
1329                 '$setloc'       => t('Set your location'),
1330                 '$shortsetloc'  => t('set location'),
1331                 '$noloc'        => t('Clear browser location'),
1332                 '$shortnoloc'   => t('clear location'),
1333                 '$title'        => defaults($x, 'title', ''),
1334                 '$placeholdertitle' => t('Set title'),
1335                 '$category'     => defaults($x, 'category', ''),
1336                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? t('Categories (comma-separated list)') : '',
1337                 '$wait'         => t('Please wait'),
1338                 '$permset'      => t('Permission settings'),
1339                 '$shortpermset' => t('permissions'),
1340                 '$ptyp'         => $notes_cid ? 'note' : 'wall',
1341                 '$content'      => defaults($x, 'content', ''),
1342                 '$post_id'      => defaults($x, 'post_id', ''),
1343                 '$baseurl'      => System::baseUrl(true),
1344                 '$defloc'       => $x['default_location'],
1345                 '$visitor'      => $x['visitor'],
1346                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1347                 '$public'       => t('Public post'),
1348                 '$lockstate'    => $x['lockstate'],
1349                 '$bang'         => $x['bang'],
1350                 '$profile_uid'  => $x['profile_uid'],
1351                 '$preview'      => Feature::isEnabled($x['profile_uid'], 'preview') ? t('Preview') : '',
1352                 '$jotplugins'   => $jotplugins,
1353                 '$notes_cid'    => $notes_cid,
1354                 '$sourceapp'    => t($a->sourcename),
1355                 '$cancel'       => t('Cancel'),
1356                 '$rand_num'     => random_digits(12),
1357
1358                 // ACL permissions box
1359                 '$acl'           => $x['acl'],
1360                 '$acl_data'      => $x['acl_data'],
1361                 '$group_perms'   => t('Post to Groups'),
1362                 '$contact_perms' => t('Post to Contacts'),
1363                 '$private'       => t('Private post'),
1364                 '$is_private'    => $private_post,
1365                 '$public_link'   => $public_post_link,
1366
1367                 //jot nav tab (used in some themes)
1368                 '$message' => t('Message'),
1369                 '$browser' => t('Browser'),
1370         ));
1371
1372
1373         if ($popup == true) {
1374                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1375         }
1376
1377         return $o;
1378 }
1379
1380 /**
1381  * Plucks the children of the given parent from a given item list.
1382  *
1383  * @brief Plucks all the children in the given item list of the given parent
1384  *
1385  * @param array $item_list
1386  * @param array $parent
1387  * @param bool $recursive
1388  * @return type
1389  */
1390 function get_item_children(array &$item_list, array $parent, $recursive = true)
1391 {
1392         $children = [];
1393         foreach ($item_list as $i => $item) {
1394                 if ($item['id'] != $item['parent']) {
1395                         if ($recursive) {
1396                                 // Fallback to parent-uri if thr-parent is not set
1397                                 $thr_parent = $item['thr-parent'];
1398                                 if ($thr_parent == '') {
1399                                         $thr_parent = $item['parent-uri'];
1400                                 }
1401
1402                                 if ($thr_parent == $parent['uri']) {
1403                                         $item['children'] = get_item_children($item_list, $item);
1404                                         $children[] = $item;
1405                                         unset($item_list[$i]);
1406                                 }
1407                         } elseif ($item['parent'] == $parent['id']) {
1408                                 $children[] = $item;
1409                                 unset($item_list[$i]);
1410                         }
1411                 }
1412         }
1413         return $children;
1414 }
1415
1416 /**
1417  * @brief Recursively sorts a tree-like item array
1418  *
1419  * @param array $items
1420  * @return array
1421  */
1422 function sort_item_children(array $items)
1423 {
1424         $result = $items;
1425         usort($result, 'sort_thr_created_rev');
1426         foreach ($result as $k => $i) {
1427                 if (isset($result[$k]['children'])) {
1428                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1429                 }
1430         }
1431         return $result;
1432 }
1433
1434 /**
1435  * @brief Recursively add all children items at the top level of a list
1436  *
1437  * @param array $children List of items to append
1438  * @param array $item_list
1439  */
1440 function add_children_to_list(array $children, array &$item_list)
1441 {
1442         foreach ($children as $child) {
1443                 $item_list[] = $child;
1444                 if (isset($child['children'])) {
1445                         add_children_to_list($child['children'], $item_list);
1446                 }
1447         }
1448 }
1449
1450 /**
1451  * This recursive function takes the item tree structure created by conv_sort() and
1452  * flatten the extraneous depth levels when people reply sequentially, removing the
1453  * stairs effect in threaded conversations limiting the available content width.
1454  *
1455  * The basic principle is the following: if a post item has only one reply and is
1456  * the last reply of its parent, then the reply is moved to the parent.
1457  *
1458  * This process is rendered somewhat more complicated because items can be either
1459  * replies or likes, and these don't factor at all in the reply count/last reply.
1460  *
1461  * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1462  *
1463  * @param array $parent A tree-like array of items
1464  * @return array
1465  */
1466 function smart_flatten_conversation(array $parent)
1467 {
1468         if (! isset($parent['children']) || count($parent['children']) == 0) {
1469                 return $parent;
1470         }
1471
1472         // We use a for loop to ensure we process the newly-moved items
1473         for ($i = 0; $i < count($parent['children']); $i++) {
1474                 $child = $parent['children'][$i];
1475
1476                 if (isset($child['children']) && count($child['children'])) {
1477                         // This helps counting only the regular posts
1478                         $count_post_closure = function($var) {
1479                                 return $var['verb'] === ACTIVITY_POST;
1480                         };
1481
1482                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1483
1484                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1485
1486                         // If there's only one child's children post and this is the last child post
1487                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1488
1489                                 // Searches the post item in the children
1490                                 $j = 0;
1491                                 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1492                                         $j ++;
1493                                 }
1494
1495                                 $moved_item = $child['children'][$j];
1496                                 unset($parent['children'][$i]['children'][$j]);
1497                                 $parent['children'][] = $moved_item;
1498                         } else {
1499                                 $parent['children'][$i] = smart_flatten_conversation($child);
1500                         }
1501                 }
1502         }
1503
1504         return $parent;
1505 }
1506
1507
1508 /**
1509  * Expands a flat list of items into corresponding tree-like conversation structures,
1510  * sort the top-level posts either on "created" or "commented", and finally
1511  * append all the items at the top level (???)
1512  *
1513  * @brief Expands a flat item list into a conversation array for display
1514  *
1515  * @param array  $item_list A list of items belonging to one or more conversations
1516  * @param string $order     Either on "created" or "commented"
1517  * @return array
1518  */
1519 function conv_sort(array $item_list, $order)
1520 {
1521         $parents = [];
1522
1523         if (!(is_array($item_list) && count($item_list))) {
1524                 return $parents;
1525         }
1526
1527         $item_array = [];
1528
1529         // Dedupes the item list on the uri to prevent infinite loops
1530         foreach ($item_list as $item) {
1531                 $item_array[$item['uri']] = $item;
1532         }
1533
1534         // Extract the top level items
1535         foreach ($item_array as $item) {
1536                 if ($item['id'] == $item['parent']) {
1537                         $parents[] = $item;
1538                 }
1539         }
1540
1541         if (stristr($order, 'created')) {
1542                 usort($parents, 'sort_thr_created');
1543         } elseif (stristr($order, 'commented')) {
1544                 usort($parents, 'sort_thr_commented');
1545         }
1546
1547         /*
1548          * Plucks children from the item_array, second pass collects eventual orphan
1549          * items and add them as children of their top-level post.
1550          */
1551         foreach ($parents as $i => $parent) {
1552                 $parents[$i]['children'] =
1553                         array_merge(get_item_children($item_array, $parent, true),
1554                                 get_item_children($item_array, $parent, false));
1555         }
1556
1557         foreach ($parents as $i => $parent) {
1558                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1559         }
1560
1561         if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1562                 foreach ($parents as $i => $parent) {
1563                         $parents[$i] = smart_flatten_conversation($parent);
1564                 }
1565         }
1566
1567         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1568         /// However, this apparently ensures responses (likes, attendance) display (?!)
1569         foreach ($parents as $parent) {
1570                 if (count($parent['children'])) {
1571                         add_children_to_list($parent['children'], $parents);
1572                 }
1573         }
1574
1575         return $parents;
1576 }
1577
1578 /**
1579  * @brief usort() callback to sort item arrays by the created key
1580  *
1581  * @param array $a
1582  * @param array $b
1583  * @return int
1584  */
1585 function sort_thr_created(array $a, array $b)
1586 {
1587         return strcmp($b['created'], $a['created']);
1588 }
1589
1590 /**
1591  * @brief usort() callback to reverse sort item arrays by the created key
1592  *
1593  * @param array $a
1594  * @param array $b
1595  * @return int
1596  */
1597 function sort_thr_created_rev(array $a, array $b)
1598 {
1599         return strcmp($a['created'], $b['created']);
1600 }
1601
1602 /**
1603  * @brief usort() callback to sort item arrays by the commented key
1604  *
1605  * @param array $a
1606  * @param array $b
1607  * @return type
1608  */
1609 function sort_thr_commented(array $a, array $b)
1610 {
1611         return strcmp($b['commented'], $a['commented']);
1612 }
1613
1614 /// @TODO Add type-hint
1615 function render_location_dummy($item) {
1616         if ($item['location'] != "") {
1617                 return $item['location'];
1618         }
1619
1620         if ($item['coord'] != "") {
1621                 return $item['coord'];
1622         }
1623 }
1624
1625 /// @TODO Add type-hint
1626 function get_responses($conv_responses, $response_verbs, $ob, $item) {
1627         $ret = array();
1628         foreach ($response_verbs as $v) {
1629                 $ret[$v] = array();
1630                 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
1631                 $ret[$v]['list']  = defaults($conv_responses[$v], $item['uri'] . '-l', '');
1632                 $ret[$v]['self']  = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1633                 if (count($ret[$v]['list']) > MAX_LIKERS) {
1634                         $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1635                         array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1636                                 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
1637                 } else {
1638                         $ret[$v]['list_part'] = '';
1639                 }
1640                 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1641                 $ret[$v]['title'] = $conv_responses[$v]['title'];
1642         }
1643
1644         $count = 0;
1645         foreach ($ret as $key) {
1646                 if ($key['count'] == true) {
1647                         $count++;
1648                 }
1649         }
1650         $ret['count'] = $count;
1651
1652         return $ret;
1653 }
1654
1655 function get_response_button_text($v, $count) {
1656         switch ($v) {
1657                 case 'like':
1658                         return tt('Like', 'Likes', $count, 'noun');
1659                         break;
1660                 case 'dislike':
1661                         return tt('Dislike', 'Dislikes', $count, 'noun');
1662                         break;
1663                 case 'attendyes':
1664                         return tt('Attending', 'Attending', $count, 'noun');
1665                         break;
1666                 case 'attendno':
1667                         return tt('Not Attending', 'Not Attending', $count, 'noun');
1668                         break;
1669                 case 'attendmaybe':
1670                         return tt('Undecided', 'Undecided', $count, 'noun');
1671                         break;
1672         }
1673 }