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