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