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