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