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