]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
New dba functions
[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`.`changed`,
428 `item`.`moderated`,
429 `item`.`target-type`,
430 `item`.`target`,
431 `item`.`resource-id`,
432 `item`.`tag`,
433 `item`.`inform`,
434 `item`.`pubmail`,
435 `item`.`visible`,
436 `item`.`spam`,
437 `item`.`bookmark`,
438 `item`.`unseen`,
439 `item`.`deleted`,
440 `item`.`origin`,
441 `item`.`forum_mode`,
442 `item`.`last-child`,
443 `item`.`mention`,
444 `item`.`global`,
445 `item`.`gcontact-id`,
446 `item`.`shadow`,
447 */
448
449         return "`item`.`author-id`, `item`.`author-link`, `item`.`author-name`, `item`.`author-avatar`,
450                 `item`.`owner-id`, `item`.`owner-link`, `item`.`owner-name`, `item`.`owner-avatar`,
451                 `item`.`contact-id`, `item`.`uid`, `item`.`id`, `item`.`parent`,
452                 `item`.`uri`, `item`.`thr-parent`, `item`.`parent-uri`,
453                 `item`.`commented`, `item`.`created`, `item`.`edited`, `item`.`received`,
454                 `item`.`verb`, `item`.`object-type`, `item`.`postopts`, `item`.`plink`,
455                 `item`.`guid`, `item`.`wall`, `item`.`private`, `item`.`starred`,
456                 `item`.`title`, `item`.`body`, `item`.`file`, `item`.`event-id`,
457                 `item`.`location`, `item`.`coord`, `item`.`app`, `item`.`attach`,
458                 `item`.`rendered-hash`, `item`.`rendered-html`, `item`.`object`,
459                 `item`.`allow_cid`, `item`.`allow_gid`, `item`.`deny_cid`, `item`.`deny_gid`,
460                 `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
461
462                 `author`.`thumb` AS `author-thumb`, `owner`.`thumb` AS `owner-thumb`,
463
464                 `contact`.`network`, `contact`.`url`, `contact`.`name`, `contact`.`writable`,
465                 `contact`.`self`, `contact`.`id` AS `cid`, `contact`.`alias`";
466 }
467
468 /**
469  * @brief SQL join for contacts that are needed for displaying items
470  */
471 function item_joins() {
472         return "STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND
473                 (NOT `contact`.`blocked` OR `contact`.`pending`)
474                 LEFT JOIN `contact` AS `author` ON `author`.`id`=`item`.`author-id`
475                 LEFT JOIN `contact` AS `owner` ON `owner`.`id`=`item`.`owner-id`";
476 }
477
478 /**
479  * @brief SQL condition for items that are needed for displaying items
480  */
481 function item_condition() {
482         return "`item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`";
483 }
484
485 if (!function_exists('conversation')) {
486 /**
487  * "Render" a conversation or list of items for HTML display.
488  * There are two major forms of display:
489  *      - Sequential or unthreaded ("New Item View" or search results)
490  *      - conversation view
491  * The $mode parameter decides between the various renderings and also
492  * figures out how to determine page owner and other contextual items
493  * that are based on unique features of the calling module.
494  *
495  */
496 function conversation(App $a, $items, $mode, $update, $preview = false) {
497
498         require_once 'include/bbcode.php';
499         require_once 'include/Contact.php';
500         require_once 'mod/proxy.php';
501
502         $ssl_state = ((local_user()) ? true : false);
503
504         $profile_owner = 0;
505         $page_writeable = false;
506         $live_update_div = '';
507
508         $arr_blocked = null;
509
510         if (local_user()) {
511                 $str_blocked = get_pconfig(local_user(), 'system', 'blocked');
512                 if ($str_blocked) {
513                         $arr_blocked = explode(',', $str_blocked);
514                         for ($x = 0; $x < count($arr_blocked); $x ++) {
515                                 $arr_blocked[$x] = trim($arr_blocked[$x]);
516                         }
517                 }
518
519         }
520
521         $previewing = (($preview) ? ' preview ' : '');
522
523         if ($mode === 'network') {
524                 $profile_owner = local_user();
525                 $page_writeable = true;
526                 if (!$update) {
527                         /*
528                          * The special div is needed for liveUpdate to kick in for this page.
529                          * We only launch liveUpdate if you aren't filtering in some incompatible
530                          * way and also you aren't writing a comment (discovered in javascript).
531                          */
532                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
533                                 . "<script> var profile_uid = " . $_SESSION['uid']
534                                 . "; var netargs = '" . substr($a->cmd, 8)
535                                 . '?f='
536                                 . ((x($_GET, 'cid'))    ? '&cid='    . $_GET['cid']    : '')
537                                 . ((x($_GET, 'search')) ? '&search=' . $_GET['search'] : '')
538                                 . ((x($_GET, 'star'))   ? '&star='   . $_GET['star']   : '')
539                                 . ((x($_GET, 'order'))  ? '&order='  . $_GET['order']  : '')
540                                 . ((x($_GET, 'bmark'))  ? '&bmark='  . $_GET['bmark']  : '')
541                                 . ((x($_GET, 'liked'))  ? '&liked='  . $_GET['liked']  : '')
542                                 . ((x($_GET, 'conv'))   ? '&conv='   . $_GET['conv']   : '')
543                                 . ((x($_GET, 'spam'))   ? '&spam='   . $_GET['spam']   : '')
544                                 . ((x($_GET, 'nets'))   ? '&nets='   . $_GET['nets']   : '')
545                                 . ((x($_GET, 'cmin'))   ? '&cmin='   . $_GET['cmin']   : '')
546                                 . ((x($_GET, 'cmax'))   ? '&cmax='   . $_GET['cmax']   : '')
547                                 . ((x($_GET, 'file'))   ? '&file='   . $_GET['file']   : '')
548
549                                 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
550                 }
551         } elseif ($mode === 'profile') {
552                 $profile_owner = $a->profile['profile_uid'];
553                 $page_writeable = can_write_wall($a,$profile_owner);
554
555                 if (!$update) {
556                         $tab = notags(trim($_GET['tab']));
557                         $tab = ( $tab ? $tab : 'posts' );
558                         if ($tab === 'posts') {
559                                 /*
560                                  * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
561                                  * because browser prefetching might change it on us. We have to deliver it with the page.
562                                  */
563
564                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
565                                         . "<script> var profile_uid = " . $a->profile['profile_uid']
566                                         . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
567                         }
568                 }
569         } elseif ($mode === 'notes') {
570                 $profile_owner = local_user();
571                 $page_writeable = true;
572                 if (!$update) {
573                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
574                                 . "<script> var profile_uid = " . local_user()
575                                 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
576                 }
577         } elseif ($mode === 'display') {
578                 $profile_owner = $a->profile['uid'];
579                 $page_writeable = can_write_wall($a,$profile_owner);
580                 if (!$update) {
581                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
582                                 . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
583                                 . " var profile_page = 1; </script>";
584                 }
585         } elseif ($mode === 'community') {
586                 $profile_owner = 0;
587                 $page_writeable = false;
588                 if (!$update) {
589                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
590                                 . "<script> var profile_uid = -1; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
591                 }
592         } elseif ($mode === 'search') {
593                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
594         }
595
596         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
597
598
599         if ($update) {
600                 $return_url = $_SESSION['return_url'];
601         } else {
602                 $return_url = $_SESSION['return_url'] = $a->query_string;
603         }
604
605         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
606         call_hooks('conversation_start',$cb);
607
608         $items = $cb['items'];
609
610         $cmnt_tpl    = get_markup_template('comment_item.tpl');
611         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
612
613         $conv_responses = array(
614                 'like' => array('title' => t('Likes','title')), 'dislike' => array('title' => t('Dislikes','title')),
615                 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
616         );
617
618         // array with html for each thread (parent+comments)
619         $threads = array();
620         $threadsid = -1;
621
622         $page_template = get_markup_template("conversation.tpl");
623
624         if ($items && count($items)) {
625
626                 if ($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
627
628                         /*
629                          * "New Item View" on network page or search page results
630                          * - just loop through the items and format them minimally for display
631                          */
632
633                         /// @TODO old lost code?
634                         // $tpl = get_markup_template('search_item.tpl');
635                         $tpl = 'search_item.tpl';
636
637                         foreach ($items as $item) {
638
639                                 if ($arr_blocked) {
640                                         $blocked = false;
641                                         foreach ($arr_blocked as $b) {
642                                                 if ($b && link_compare($item['author-link'], $b)) {
643                                                         $blocked = true;
644                                                         break;
645                                                 }
646                                         }
647                                         if ($blocked) {
648                                                 continue;
649                                         }
650                                 }
651
652
653                                 $threadsid++;
654
655                                 $comment     = '';
656                                 $owner_url   = '';
657                                 $owner_name  = '';
658                                 $sparkle     = '';
659
660                                 if ($mode === 'search' || $mode === 'community') {
661                                         if (((activity_match($item['verb'], ACTIVITY_LIKE)) || (activity_match($item['verb'], ACTIVITY_DISLIKE)))
662                                                 && ($item['id'] != $item['parent']))
663                                                 continue;
664                                         $nickname = $item['nickname'];
665                                 } else {
666                                         $nickname = $a->user['nickname'];
667                                 }
668
669                                 // prevent private email from leaking.
670                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
671                                         continue;
672                                 }
673
674                                 $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
675                                 if ($item['author-link'] && (! $item['author-name'])) {
676                                         $profile_name = $item['author-link'];
677                                 }
678
679                                 $tags = array();
680                                 $hashtags = array();
681                                 $mentions = array();
682
683                                 $taglist = dba::p("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = ? AND `oid` = ? AND `type` IN (?, ?) ORDER BY `tid`",
684                                                 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
685
686                                 while ($tag = dba::fetch($taglist)) {
687                                         if ($tag["url"] == "") {
688                                                 $tag["url"] = $searchpath . strtolower($tag["term"]);
689                                         }
690
691                                         if ($tag["type"] == TERM_HASHTAG) {
692                                                 $hashtags[] = "#<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
693                                                 $prefix = "#";
694                                         } elseif ($tag["type"] == TERM_MENTION) {
695                                                 $mentions[] = "@<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
696                                                 $prefix = "@";
697                                         }
698                                         $tags[] = $prefix."<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
699                                 }
700                                 dba::close($taglist);
701
702                                 $sp = false;
703                                 $profile_link = best_link_url($item,$sp);
704                                 if ($profile_link === 'mailbox') {
705                                         $profile_link = '';
706                                 }
707
708                                 if ($sp) {
709                                         $sparkle = ' sparkle';
710                                 } else {
711                                         $profile_link = zrl($profile_link);
712                                 }
713
714                                 if (!x($item, 'author-thumb') || ($item['author-thumb'] == "")) {
715                                         $author_contact = get_contact_details_by_url($item['author-link'], $profile_owner);
716                                         if ($author_contact["thumb"]) {
717                                                 $item['author-thumb'] = $author_contact["thumb"];
718                                         } else {
719                                                 $item['author-thumb'] = $item['author-avatar'];
720                                         }
721                                 }
722
723                                 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
724                                         $owner_contact = get_contact_details_by_url($item['owner-link'], $profile_owner);
725                                         if ($owner_contact["thumb"]) {
726                                                 $item['owner-thumb'] = $owner_contact["thumb"];
727                                         } else {
728                                                 $item['owner-thumb'] = $item['owner-avatar'];
729                                         }
730                                 }
731
732                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
733                                 call_hooks('render_location',$locate);
734
735                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
736
737                                 localize_item($item);
738                                 if ($mode === 'network-new') {
739                                         $dropping = true;
740                                 } else {
741                                         $dropping = false;
742                                 }
743
744                                 $drop = array(
745                                         'dropping' => $dropping,
746                                         'pagedrop' => $page_dropping,
747                                         'select' => t('Select'),
748                                         'delete' => t('Delete'),
749                                 );
750
751                                 $star = false;
752                                 $isstarred = "unstarred";
753
754                                 $lock = false;
755                                 $likebuttons = false;
756                                 $shareable = false;
757
758                                 $body = prepare_body($item, true, $preview);
759
760                                 list($categories, $folders) = get_cats_and_terms($item);
761
762                                 if ($a->theme['template_engine'] === 'internal') {
763                                         $profile_name_e = template_escape($profile_name);
764                                         $item['title_e'] = template_escape($item['title']);
765                                         $body_e = template_escape($body);
766                                         $tags_e = template_escape($tags);
767                                         $hashtags_e = template_escape($hashtags);
768                                         $mentions_e = template_escape($mentions);
769                                         $location_e = template_escape($location);
770                                         $owner_name_e = template_escape($owner_name);
771                                 } else {
772                                         $profile_name_e = $profile_name;
773                                         $item['title_e'] = $item['title'];
774                                         $body_e = $body;
775                                         $tags_e = $tags;
776                                         $hashtags_e = $hashtags;
777                                         $mentions_e = $mentions;
778                                         $location_e = $location;
779                                         $owner_name_e = $owner_name;
780                                 }
781
782                                 if ($item['item_network'] == "") {
783                                         $item['item_network'] = $item['network'];
784                                 }
785
786                                 $tmp_item = array(
787                                         'template' => $tpl,
788                                         'id' => (($preview) ? 'P0' : $item['item_id']),
789                                         'network' => $item['item_network'],
790                                         'network_name' => network_to_name($item['item_network'], $profile_link),
791                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
792                                         'profile_url' => $profile_link,
793                                         'item_photo_menu' => item_photo_menu($item),
794                                         'name' => $profile_name_e,
795                                         'sparkle' => $sparkle,
796                                         'lock' => $lock,
797                                         'thumb' => App::remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
798                                         'title' => $item['title_e'],
799                                         'body' => $body_e,
800                                         'tags' => $tags_e,
801                                         'hashtags' => $hashtags_e,
802                                         'mentions' => $mentions_e,
803                                         'txt_cats' => t('Categories:'),
804                                         'txt_folders' => t('Filed under:'),
805                                         'has_cats' => ((count($categories)) ? 'true' : ''),
806                                         'has_folders' => ((count($folders)) ? 'true' : ''),
807                                         'categories' => $categories,
808                                         'folders' => $folders,
809                                         'text' => strip_tags($body_e),
810                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
811                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
812                                         'location' => $location_e,
813                                         'indent' => '',
814                                         'owner_name' => $owner_name_e,
815                                         'owner_url' => $owner_url,
816                                         'owner_photo' => App::remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
817                                         'plink' => get_plink($item),
818                                         'edpost' => false,
819                                         'isstarred' => $isstarred,
820                                         'star' => $star,
821                                         'drop' => $drop,
822                                         'vote' => $likebuttons,
823                                         'like' => '',
824                                         'dislike' => '',
825                                         'comment' => '',
826                                         //'conv' => (($preview) ? '' : array('href'=> 'display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
827                                         'conv' => (($preview) ? '' : array('href'=> 'display/'.$item['guid'], 'title'=> t('View in context'))),
828                                         'previewing' => $previewing,
829                                         'wait' => t('Please wait'),
830                                         'thread_level' => 1,
831                                 );
832
833                                 $arr = array('item' => $item, 'output' => $tmp_item);
834                                 call_hooks('display_item', $arr);
835
836                                 $threads[$threadsid]['id'] = $item['item_id'];
837                                 $threads[$threadsid]['network'] = $item['item_network'];
838                                 $threads[$threadsid]['items'] = array($arr['output']);
839
840                         }
841                 } else {
842                         // Normal View
843                         $page_template = get_markup_template("threaded_conversation.tpl");
844
845                         require_once 'object/Conversation.php';
846                         require_once 'object/Item.php';
847
848                         $conv = new Conversation($mode, $preview);
849
850                         /*
851                          * get all the topmost parents
852                          * this shouldn't be needed, as we should have only them in our array
853                          * But for now, this array respects the old style, just in case
854                          */
855                         $threads = array();
856                         foreach ($items as $item) {
857
858                                 if ($arr_blocked) {
859                                         $blocked = false;
860                                         foreach ($arr_blocked as $b) {
861                                                 if ($b && link_compare($item['author-link'], $b)) {
862                                                         $blocked = true;
863                                                         break;
864                                                 }
865                                         }
866                                         if ($blocked) {
867                                                 continue;
868                                         }
869                                 }
870
871                                 // Can we put this after the visibility check?
872                                 builtin_activity_puller($item, $conv_responses);
873
874                                 // Only add what is visible
875                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
876                                         continue;
877                                 }
878
879                                 if (! visible_activity($item)) {
880                                         continue;
881                                 }
882
883                                 call_hooks('display_item', $arr);
884
885                                 $item['pagedrop'] = $page_dropping;
886
887                                 if ($item['id'] == $item['parent']) {
888                                         $item_object = new Item($item);
889                                         $conv->add_thread($item_object);
890                                 }
891                         }
892
893                         $threads = $conv->get_template_data($conv_responses);
894
895                         if (!$threads) {
896                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
897                                 $threads = array();
898                         }
899                 }
900         }
901
902         $o = replace_macros($page_template, array(
903                 '$baseurl' => App::get_baseurl($ssl_state),
904                 '$return_path' => $a->query_string,
905                 '$live_update' => $live_update_div,
906                 '$remove' => t('remove'),
907                 '$mode' => $mode,
908                 '$user' => $a->user,
909                 '$threads' => $threads,
910                 '$dropping' => ($page_dropping && feature_enabled(local_user(), 'multi_delete') ? t('Delete Selected Items') : False),
911         ));
912
913         return $o;
914 }}
915
916 function best_link_url($item, &$sparkle, $ssl_state = false) {
917
918         $best_url = '';
919         $sparkle  = false;
920
921         $clean_url = normalise_link($item['author-link']);
922
923         if (local_user()) {
924                 $r = dba::select('contact', array('id'),
925                         array('network' => NETWORK_DFRN, 'uid' => local_user(), 'nurl' => normalise_link($clean_url), 'pending' => false),
926                         array('limit' => 1));
927                 if (dbm::is_result($r)) {
928                         $best_url = 'redir/' . $r['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 function item_photo_menu($item) {
945         $ssl_state = false;
946
947         if (local_user()) {
948                 $ssl_state = true;
949         }
950
951         $sub_link = '';
952         $poke_link = '';
953         $contact_url = '';
954         $pm_url = '';
955         $status_link = '';
956         $photos_link = '';
957         $posts_link = '';
958         $network = '';
959
960         if ((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
961                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
962         }
963
964         $sparkle = false;
965         $profile_link = best_link_url($item, $sparkle, $ssl_state);
966         if ($profile_link === 'mailbox') {
967                 $profile_link = '';
968         }
969
970         $cid = 0;
971         $network = '';
972         $rel = 0;
973         $r = dba::select('contact', array('id', 'network', 'rel'), array('uid' => local_user(), 'nurl' => normalise_link($item['author-link'])), array('limit' => 1));
974         if (dbm::is_result($r)) {
975                 $cid = $r['id'];
976                 $network = $r['network'];
977                 $rel = $r['rel'];
978         }
979
980         if ($sparkle) {
981                 $status_link = $profile_link . '?url=status';
982                 $photos_link = $profile_link . '?url=photos';
983                 $profile_link = $profile_link . '?url=profile';
984                 $zurl = '';
985         } else {
986                 $profile_link = zrl($profile_link);
987         }
988
989         if ($cid && !$item['self']) {
990                 $poke_link = 'poke/?f=&c=' . $cid;
991                 $contact_url = 'contacts/' . $cid;
992                 $posts_link = 'contacts/' . $cid . '/posts';
993
994                 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA))) {
995                         $pm_url = 'message/new/' . $cid;
996                 }
997         }
998
999         if (local_user()) {
1000                 $menu = array(
1001                         t('Follow Thread') => $sub_link,
1002                         t('View Status') => $status_link,
1003                         t('View Profile') => $profile_link,
1004                         t('View Photos') => $photos_link,
1005                         t('Network Posts') => $posts_link,
1006                         t('View Contact') => $contact_url,
1007                         t('Send PM') => $pm_url
1008                 );
1009
1010                 if ($network == NETWORK_DFRN) {
1011                         $menu[t("Poke")] = $poke_link;
1012                 }
1013
1014                 if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
1015                         in_array($item['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
1016                         $menu[t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
1017                 }
1018         } else {
1019                 $menu = array(t('View Profile') => $item['author-link']);
1020         }
1021
1022         $args = array('item' => $item, 'menu' => $menu);
1023
1024         call_hooks('item_photo_menu', $args);
1025
1026         $menu = $args['menu'];
1027
1028         $o = '';
1029         foreach ($menu as $k => $v) {
1030                 if (strpos($v, 'javascript:') === 0) {
1031                         $v = substr($v, 11);
1032                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1033                 } elseif ($v!='') {
1034                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1035                 }
1036         }
1037         return $o;
1038 }
1039
1040 if (! function_exists('builtin_activity_puller')) {
1041 /**
1042  * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
1043  * Increments the count of each matching activity and adds a link to the author as needed.
1044  *
1045  * @param array $item
1046  * @param array &$conv_responses (already created with builtin activity structure)
1047  * @return void
1048  */
1049 function builtin_activity_puller($item, &$conv_responses) {
1050         foreach ($conv_responses as $mode => $v) {
1051                 $url = '';
1052                 $sparkle = '';
1053
1054                 switch ($mode) {
1055                         case 'like':
1056                                 $verb = ACTIVITY_LIKE;
1057                                 break;
1058                         case 'dislike':
1059                                 $verb = ACTIVITY_DISLIKE;
1060                                 break;
1061                         case 'attendyes':
1062                                 $verb = ACTIVITY_ATTEND;
1063                                 break;
1064                         case 'attendno':
1065                                 $verb = ACTIVITY_ATTENDNO;
1066                                 break;
1067                         case 'attendmaybe':
1068                                 $verb = ACTIVITY_ATTENDMAYBE;
1069                                 break;
1070                         default:
1071                                 return;
1072                                 break;
1073                 }
1074
1075                 if ((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
1076                         $url = $item['author-link'];
1077                         if ((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'], $item['url']))) {
1078                                 $url = 'redir/' . $item['contact-id'];
1079                                 $sparkle = ' class="sparkle" ';
1080                         } else {
1081                                 $url = zrl($url);
1082                         }
1083
1084                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
1085
1086                         if (! $item['thr-parent']) {
1087                                 $item['thr-parent'] = $item['parent-uri'];
1088                         }
1089
1090                         if (! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l']))
1091                                 && (is_array($conv_responses[$mode][$item['thr-parent'] . '-l'])))) {
1092                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = array();
1093                         }
1094
1095                         // only list each unique author once
1096                         if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
1097                                 continue;
1098                         }
1099
1100                         if (! isset($conv_responses[$mode][$item['thr-parent']])) {
1101                                 $conv_responses[$mode][$item['thr-parent']] = 1;
1102                         } else {
1103                                 $conv_responses[$mode][$item['thr-parent']] ++;
1104                         }
1105
1106                         if (public_contact() == $item['author-id']) {
1107                                 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
1108                         }
1109
1110                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1111
1112                         // there can only be one activity verb per item so if we found anything, we can stop looking
1113                         return;
1114                 }
1115         }
1116 }}
1117
1118 if (! function_exists('format_like')) {
1119 /**
1120  * Format the vote text for a profile item
1121  * @param int $cnt = number of people who vote the item
1122  * @param array $arr = array of pre-linked names of likers/dislikers
1123  * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1124  * @param int $id  = item id
1125  * @return formatted text
1126  */
1127 function format_like($cnt, array $arr, $type, $id) {
1128         $o = '';
1129         $expanded = '';
1130
1131         if ($cnt == 1) {
1132                 $likers = $arr[0];
1133
1134                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1135                 // list which show all likers
1136                 switch ($type) {
1137                         case 'like' :
1138                                 $phrase = sprintf( t('%s likes this.'), $likers);
1139                                 break;
1140                         case 'dislike' :
1141                                 $phrase = sprintf( t('%s doesn\'t like this.'), $likers);
1142                                 break;
1143                         case 'attendyes' :
1144                                 $phrase = sprintf( t('%s attends.'), $likers);
1145                                 break;
1146                         case 'attendno' :
1147                                 $phrase = sprintf( t('%s doesn\'t attend.'), $likers);
1148                                 break;
1149                         case 'attendmaybe' :
1150                                 $phrase = sprintf( t('%s attends maybe.'), $likers);
1151                                 break;
1152                 }
1153         }
1154
1155         if ($cnt > 1) {
1156                 $total = count($arr);
1157                 if ($total >= MAX_LIKERS) {
1158                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1159                 }
1160                 if ($total < MAX_LIKERS) {
1161                         $last = t('and') . ' ' . $arr[count($arr)-1];
1162                         $arr2 = array_slice($arr, 0, -1);
1163                         $str = implode(', ', $arr2) . ' ' . $last;
1164                 }
1165                 if ($total >= MAX_LIKERS) {
1166                         $str = implode(', ', $arr);
1167                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
1168                 }
1169
1170                 $likers = $str;
1171
1172                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1173
1174                 switch ($type) {
1175                         case 'like':
1176                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> like this'), $spanatts, $cnt);
1177                                 $explikers = sprintf( t('%s like this.'), $likers);
1178                                 break;
1179                         case 'dislike':
1180                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t like this'), $spanatts, $cnt);
1181                                 $explikers = sprintf( t('%s don\'t like this.'), $likers);
1182                                 break;
1183                         case 'attendyes':
1184                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend'), $spanatts, $cnt);
1185                                 $explikers = sprintf( t('%s attend.'), $likers);
1186                                 break;
1187                         case 'attendno':
1188                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t attend'), $spanatts, $cnt);
1189                                 $explikers = sprintf( t('%s don\'t attend.'), $likers);
1190                                 break;
1191                         case 'attendmaybe':
1192                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend maybe'), $spanatts, $cnt);
1193                                 $explikers = sprintf( t('%s anttend maybe.'), $likers);
1194                                 break;
1195                 }
1196
1197                 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1198         }
1199
1200         $phrase .= EOL ;
1201         $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), array(
1202                 '$phrase' => $phrase,
1203                 '$type' => $type,
1204                 '$id' => $id
1205         ));
1206         $o .= $expanded;
1207
1208         return $o;
1209 }}
1210
1211 function status_editor(App $a, $x, $notes_cid = 0, $popup = false) {
1212         $o = '';
1213
1214         $geotag = (x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '');
1215
1216         $tpl = get_markup_template('jot-header.tpl');
1217         $a->page['htmlhead'] .= replace_macros($tpl, array(
1218                 '$newpost' => 'true',
1219                 '$baseurl' => App::get_baseurl(true),
1220                 '$geotag' => $geotag,
1221                 '$nickname' => $x['nickname'],
1222                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1223                 '$linkurl' => t('Please enter a link URL:'),
1224                 '$vidurl' => t("Please enter a video link/URL:"),
1225                 '$audurl' => t("Please enter an audio link/URL:"),
1226                 '$term' => t('Tag term:'),
1227                 '$fileas' => t('Save to Folder:'),
1228                 '$whereareu' => t('Where are you right now?'),
1229                 '$delitems' => t('Delete item(s)?')
1230         ));
1231
1232         $tpl = get_markup_template('jot-end.tpl');
1233         $a->page['end'] .= replace_macros($tpl, array(
1234                 '$newpost' => 'true',
1235                 '$baseurl' => App::get_baseurl(true),
1236                 '$geotag' => $geotag,
1237                 '$nickname' => $x['nickname'],
1238                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1239                 '$linkurl' => t('Please enter a link URL:'),
1240                 '$vidurl' => t("Please enter a video link/URL:"),
1241                 '$audurl' => t("Please enter an audio link/URL:"),
1242                 '$term' => t('Tag term:'),
1243                 '$fileas' => t('Save to Folder:'),
1244                 '$whereareu' => t('Where are you right now?')
1245         ));
1246
1247         $jotplugins = '';
1248         call_hooks('jot_tool', $jotplugins);
1249
1250         // Private/public post links for the non-JS ACL form
1251         $private_post = 1;
1252         if (x($_REQUEST, 'public')) {
1253                 $private_post = 0;
1254         }
1255
1256         $query_str = $a->query_string;
1257         if (strpos($query_str, 'public=1') !== false) {
1258                 $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1259         }
1260
1261         /*
1262          * I think $a->query_string may never have ? in it, but I could be wrong
1263          * It looks like it's from the index.php?q=[etc] rewrite that the web
1264          * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1265          */
1266         if (strpos($query_str, '?') === false) {
1267                 $public_post_link = '?public=1';
1268         } else {
1269                 $public_post_link = '&public=1';
1270         }
1271
1272         // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1273         $tpl = get_markup_template("jot.tpl");
1274
1275         $o .= replace_macros($tpl,array(
1276                 '$return_path' => $query_str,
1277                 '$action' =>  'item',
1278                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
1279                 '$upload' => t('Upload photo'),
1280                 '$shortupload' => t('upload photo'),
1281                 '$attach' => t('Attach file'),
1282                 '$shortattach' => t('attach file'),
1283                 '$weblink' => t('Insert web link'),
1284                 '$shortweblink' => t('web link'),
1285                 '$video' => t('Insert video link'),
1286                 '$shortvideo' => t('video link'),
1287                 '$audio' => t('Insert audio link'),
1288                 '$shortaudio' => t('audio link'),
1289                 '$setloc' => t('Set your location'),
1290                 '$shortsetloc' => t('set location'),
1291                 '$noloc' => t('Clear browser location'),
1292                 '$shortnoloc' => t('clear location'),
1293                 '$title' => $x['title'],
1294                 '$placeholdertitle' => t('Set title'),
1295                 '$category' => $x['category'],
1296                 '$placeholdercategory' => (feature_enabled(local_user(), 'categories') ? t('Categories (comma-separated list)') : ''),
1297                 '$wait' => t('Please wait'),
1298                 '$permset' => t('Permission settings'),
1299                 '$shortpermset' => t('permissions'),
1300                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
1301                 '$content' => $x['content'],
1302                 '$post_id' => $x['post_id'],
1303                 '$baseurl' => App::get_baseurl(true),
1304                 '$defloc' => $x['default_location'],
1305                 '$visitor' => $x['visitor'],
1306                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
1307                 '$public' => t('Public post'),
1308                 '$jotnets' => $jotnets,
1309                 '$lockstate' => $x['lockstate'],
1310                 '$bang' => $x['bang'],
1311                 '$profile_uid' => $x['profile_uid'],
1312                 '$preview' => ((feature_enabled($x['profile_uid'],'preview')) ? t('Preview') : ''),
1313                 '$jotplugins' => $jotplugins,
1314                 '$notes_cid' => $notes_cid,
1315                 '$sourceapp' => t($a->sourcename),
1316                 '$cancel' => t('Cancel'),
1317                 '$rand_num' => random_digits(12),
1318
1319                 // ACL permissions box
1320                 '$acl' => $x['acl'],
1321                 '$acl_data' => $x['acl_data'],
1322                 '$group_perms' => t('Post to Groups'),
1323                 '$contact_perms' => t('Post to Contacts'),
1324                 '$private' => t('Private post'),
1325                 '$is_private' => $private_post,
1326                 '$public_link' => $public_post_link,
1327
1328                 //jot nav tab (used in some themes)
1329                 '$message' => t('Message'),
1330                 '$browser' => t('Browser'),
1331         ));
1332
1333
1334         if ($popup == true) {
1335                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1336         }
1337
1338         return $o;
1339 }
1340
1341
1342 function get_item_children($arr, $parent) {
1343         $children = array();
1344         $a = get_app();
1345         foreach ($arr as $item) {
1346                 if ($item['id'] != $item['parent']) {
1347                         if (get_config('system', 'thread_allow') && $a->theme_thread_allow) {
1348                                 // Fallback to parent-uri if thr-parent is not set
1349                                 $thr_parent = $item['thr-parent'];
1350                                 if ($thr_parent == '') {
1351                                         $thr_parent = $item['parent-uri'];
1352                                 }
1353
1354                                 if ($thr_parent == $parent['uri']) {
1355                                         $item['children'] = get_item_children($arr, $item);
1356                                         $children[] = $item;
1357                                 }
1358                         } elseif ($item['parent'] == $parent['id']) {
1359                                 $children[] = $item;
1360                         }
1361                 }
1362         }
1363         return $children;
1364 }
1365
1366 /// @TODO Add type-hint
1367 function sort_item_children($items) {
1368         $result = $items;
1369         usort($result, 'sort_thr_created_rev');
1370         foreach ($result as $k => $i) {
1371                 if (count($result[$k]['children'])) {
1372                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1373                 }
1374         }
1375         return $result;
1376 }
1377
1378 /// @TODO Add type-hint
1379 function add_children_to_list($children, &$arr) {
1380         foreach ($children as $y) {
1381                 $arr[] = $y;
1382                 if (count($y['children'])) {
1383                         add_children_to_list($y['children'], $arr);
1384                 }
1385         }
1386 }
1387
1388 /// @TODO Add type-hint
1389 function conv_sort($arr, $order) {
1390
1391         if ((!(is_array($arr) && count($arr)))) {
1392                 return array();
1393         }
1394
1395         $parents = array();
1396         $children = array();
1397         $newarr = array();
1398
1399         /*
1400          * This is a preparation for having two different items with the same uri in one thread
1401          * This will otherwise lead to an endless loop.
1402          */
1403         foreach ($arr as $x) {
1404                 if (!isset($newarr[$x['uri']])) {
1405                         $newarr[$x['uri']] = $x;
1406                 }
1407         }
1408
1409         $arr = $newarr;
1410
1411         foreach ($arr as $x) {
1412                 if ($x['id'] == $x['parent']) {
1413                         $parents[] = $x;
1414                 }
1415         }
1416
1417         if (stristr($order, 'created')) {
1418                 usort($parents, 'sort_thr_created');
1419         } elseif (stristr($order, 'commented')) {
1420                 usort($parents, 'sort_thr_commented');
1421         }
1422
1423         if (count($parents)) {
1424                 foreach ($parents as $i => $_x) {
1425                         $parents[$i]['children'] = get_item_children($arr, $_x);
1426                 }
1427         }
1428
1429         /// @TODO Old-lost code?
1430         /*foreach ($arr as $x) {
1431                 if ($x['id'] != $x['parent']) {
1432                         $p = find_thread_parent_index($parents,$x);
1433                         if ($p !== false)
1434                                 $parents[$p]['children'][] = $x;
1435                 }
1436         }*/
1437         if (count($parents)) {
1438                 foreach ($parents as $k => $v) {
1439                         if (count($parents[$k]['children'])) {
1440                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1441                                 /// @TODO Old-lost code?
1442                                 /*$y = $parents[$k]['children'];
1443                                 usort($y,'sort_thr_created_rev');
1444                                 $parents[$k]['children'] = $y;*/
1445                         }
1446                 }
1447         }
1448
1449         $ret = array();
1450         if (count($parents)) {
1451                 foreach ($parents as $x) {
1452                         $ret[] = $x;
1453                         if (count($x['children'])) {
1454                                 add_children_to_list($x['children'], $ret);
1455                                 /// @TODO Old-lost code?
1456                                 /*foreach ($x['children'] as $y)
1457                                         $ret[] = $y;*/
1458                         }
1459                 }
1460         }
1461
1462         return $ret;
1463 }
1464
1465 /// @TODO Add type-hint
1466 function sort_thr_created($a, $b) {
1467         return strcmp($b['created'], $a['created']);
1468 }
1469
1470 /// @TODO Add type-hint
1471 function sort_thr_created_rev($a, $b) {
1472         return strcmp($a['created'], $b['created']);
1473 }
1474
1475 /// @TODO Add type-hint
1476 function sort_thr_commented($a, $b) {
1477         return strcmp($b['commented'], $a['commented']);
1478 }
1479
1480 /// @TODO Add type-hint
1481 function find_thread_parent_index($arr, $x) {
1482         foreach ($arr as $k => $v) {
1483                 if ($v['id'] == $x['parent']) {
1484                         return $k;
1485                 }
1486         }
1487         return false;
1488 }
1489
1490 /// @TODO Add type-hint
1491 function render_location_dummy($item) {
1492         if ($item['location'] != "") {
1493                 return $item['location'];
1494         }
1495
1496         if ($item['coord'] != "") {
1497                 return $item['coord'];
1498         }
1499 }
1500
1501 /// @TODO Add type-hint
1502 function get_responses($conv_responses, $response_verbs, $ob, $item) {
1503         $ret = array();
1504         foreach ($response_verbs as $v) {
1505                 $ret[$v] = array();
1506                 $ret[$v]['count'] = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri']] : '');
1507                 $ret[$v]['list']  = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri'] . '-l'] : '');
1508                 $ret[$v]['self']  = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri'] . '-self'] : '0');
1509                 if (count($ret[$v]['list']) > MAX_LIKERS) {
1510                         $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1511                         array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1512                                 . (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
1513                 } else {
1514                         $ret[$v]['list_part'] = '';
1515                 }
1516                 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1517                 $ret[$v]['title'] = $conv_responses[$v]['title'];
1518         }
1519
1520         $count = 0;
1521         foreach ($ret as $key) {
1522                 if ($key['count'] == true) {
1523                         $count++;
1524                 }
1525         }
1526         $ret['count'] = $count;
1527
1528         return $ret;
1529 }
1530
1531 function get_response_button_text($v, $count) {
1532         switch ($v) {
1533                 case 'like':
1534                         return tt('Like', 'Likes', $count, 'noun');
1535                         break;
1536                 case 'dislike':
1537                         return tt('Dislike', 'Dislikes', $count, 'noun');
1538                         break;
1539                 case 'attendyes':
1540                         return tt('Attending', 'Attending', $count, 'noun');
1541                         break;
1542                 case 'attendno':
1543                         return tt('Not Attending', 'Not Attending', $count, 'noun');
1544                         break;
1545                 case 'attendmaybe':
1546                         return tt('Undecided', 'Undecided', $count, 'noun');
1547                         break;
1548         }
1549 }