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