]> git.mxchange.org Git - friendica.git/blob - object/Item.php
2c9d65598117c05f0d27e1817cb85c7f66ae9020
[friendica.git] / object / Item.php
1 <?php
2 if(class_exists('Item'))
3         return;
4
5 require_once('object/BaseObject.php');
6 require_once('include/text.php');
7 require_once('boot.php');
8
9 /**
10  * An item
11  */
12 class Item extends BaseObject {
13         private $data = array();
14         private $template = null;
15         private $available_templates = array(
16                 'wall' => 'wall_thread.tpl',
17                 'wall2wall' => 'wallwall_thread.tpl'
18         );
19         private $comment_box_template = 'comment_item.tpl';
20         private $toplevel = false;
21         private $writable = false;
22         private $children = array();
23         private $parent = null;
24         private $conversation = null;
25         private $redirect_url = null;
26         private $owner_url = '';
27         private $owner_photo = '';
28         private $owner_name = '';
29         private $wall_to_wall = false;
30         private $threaded = false;
31         private $visiting = false;
32
33         public function __construct($data) {
34                 $a = $this->get_app();
35                 
36                 $this->data = $data;
37                 $this->set_template('wall');
38                 $this->toplevel = ($this->get_id() == $this->get_data_value('parent'));
39
40                 if(is_array($_SESSION['remote'])) {
41                         foreach($_SESSION['remote'] as $visitor) {
42                                 if($visitor['cid'] == $this->get_data_value('contact-id')) {
43                                         $this->visiting = true;
44                                         break;
45                                 }
46                         }
47                 }
48                 
49                 $this->writable = ($this->get_data_value('writable') || $this->get_data_value('self'));
50
51                 $ssl_state = ((local_user()) ? true : false);
52                 $this->redirect_url = $a->get_baseurl($ssl_state) . '/redir/' . $this->get_data_value('cid') ;
53
54                 if(get_config('system','thread_allow') && $a->theme_thread_allow && !$this->is_toplevel())
55                         $this->threaded = true;
56
57                 // Prepare the children
58                 if(count($data['children'])) {
59                         foreach($data['children'] as $item) {
60                                 /*
61                                  * Only add will be displayed
62                                  */
63                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
64                                         continue;
65                                 }
66                                 if($item['verb'] === ACTIVITY_LIKE || $item['verb'] === ACTIVITY_DISLIKE) {
67                                         continue;
68                                 }
69                                 $child = new Item($item);
70                                 $this->add_child($child);
71                         }
72                 }
73         }
74
75         /**
76          * Get data in a form usable by a conversation template
77          *
78          * Returns:
79          *      _ The data requested on success
80          *      _ false on failure
81          */
82         public function get_template_data($alike, $dlike, $thread_level=1) {
83                 $result = array();
84
85                 $a = $this->get_app();
86
87                 $item = $this->get_data();
88
89                 $commentww = '';
90                 $sparkle = '';
91                 $buttons = '';
92                 $dropping = false;
93                 $star = false;
94                 $isstarred = "unstarred";
95                 $indent = '';
96                 $osparkle = '';
97                 $total_children = $this->count_descendants();
98
99                 $conv = $this->get_conversation();
100
101                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid']) 
102                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
103                         ? t('Private Message')
104                         : false);
105                 $shareable = ((($conv->get_profile_owner() == local_user()) && ($item['private'] != 1)) ? true : false);
106                 if(local_user() && link_compare($a->contact['url'],$item['author-link']))
107                         $edpost = array($a->get_baseurl($ssl_state)."/editpost/".$item['id'], t("Edit"));
108                 else
109                         $edpost = false;
110                 if(($this->get_data_value('uid') == local_user()) || $this->is_visiting())
111                         $dropping = true;
112
113                 $drop = array(
114                         'dropping' => $dropping,
115                         'select' => t('Select'), 
116                         'delete' => t('Delete'),
117                 );
118                 
119                 $filer = (($conv->get_profile_owner() == local_user()) ? t("save to folder") : false);
120
121                 $diff_author    = ((link_compare($item['url'],$item['author-link'])) ? false : true);
122                 $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
123                 if($item['author-link'] && (! $item['author-name']))
124                         $profile_name = $item['author-link'];
125
126                 $sp = false;
127                 $profile_link = best_link_url($item,$sp);
128                 if($profile_link === 'mailbox')
129                         $profile_link = '';
130                 if($sp)
131                         $sparkle = ' sparkle';
132                 else
133                         $profile_link = zrl($profile_link);                 
134
135                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
136                 if(($normalised != 'mailbox') && (x($a->contacts,$normalised)))
137                         $profile_avatar = $a->contacts[$normalised]['thumb'];
138                 else
139                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $a->get_cached_avatar_image($this->get_data_value('thumb')));
140
141                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
142                 call_hooks('render_location',$locate);
143                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
144
145                 $tags=array();
146                 $hashtags = array();
147                 $mentions = array();
148                 foreach(explode(',',$item['tag']) as $tag){
149                         $tag = trim($tag);
150                         if ($tag!="") {
151                                 $t = bbcode($tag);
152                                 $tags[] = $t;
153                                 if($t[0] == '#')
154                                         $hashtags[] = $t;
155                                 elseif($t[0] == '@')
156                                         $mentions[] = $t;
157                         }
158
159                 }        
160
161                 $like    = ((x($alike,$item['uri'])) ? format_like($alike[$item['uri']],$alike[$item['uri'] . '-l'],'like',$item['uri']) : '');
162                 $dislike = ((x($dlike,$item['uri'])) ? format_like($dlike[$item['uri']],$dlike[$item['uri'] . '-l'],'dislike',$item['uri']) : '');
163
164                 /*
165                  * We should avoid doing this all the time, but it depends on the conversation mode
166                  * And the conv mode may change when we change the conv, or it changes its mode
167                  * Maybe we should establish a way to be notified about conversation changes
168                  */
169                 $this->check_wall_to_wall();
170                 
171                 if($this->is_wall_to_wall() && ($this->get_owner_url() == $this->get_redirect_url()))
172                         $osparkle = ' sparkle';
173                 
174                 if($this->is_toplevel()) {
175                         if($conv->get_profile_owner() == local_user()) {
176                                 $isstarred = (($item['starred']) ? "starred" : "unstarred");
177
178                                 $star = array(
179                                         'do' => t("add star"),
180                                         'undo' => t("remove star"),
181                                         'toggle' => t("toggle star status"),
182                                         'classdo' => (($item['starred']) ? "hidden" : ""),
183                                         'classundo' => (($item['starred']) ? "" : "hidden"),
184                                         'starred' =>  t('starred'),
185                                         'tagger' => t("add tag"),
186                                         'classtagger' => "",
187                                 );
188                         }
189                 } else {
190                         $indent = 'comment';
191                 }
192
193                 if($conv->is_writable()) {
194                         $buttons = array(
195                                 'like' => array( t("I like this \x28toggle\x29"), t("like")),
196                                 'dislike' => array( t("I don't like this \x28toggle\x29"), t("dislike")),
197                         );
198                         if ($shareable) $buttons['share'] = array( t('Share this'), t('share'));
199                 }
200
201                 if(strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0)
202                         $indent .= ' shiny';
203
204                 localize_item($item);
205
206                 $body = prepare_body($item,true);
207
208         list($categories, $folders) = get_cats_and_terms($item);
209
210                 $tmp_item = array(
211                         'template' => $this->get_template(),
212                         
213                         'type' => implode("",array_slice(explode("/",$item['verb']),-1)),
214                         'tags' => $tags,
215             'hashtags' => $hashtags,
216             'mentions' => $mentions,
217             'categories' => $categories,
218             'folders' => $folders,            
219                         'body' => template_escape($body),
220                         'text' => strip_tags(template_escape($body)),
221                         'id' => $this->get_id(),
222                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
223                         'olinktitle' => sprintf( t('View %s\'s profile @ %s'), $this->get_owner_name(), ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
224                         'to' => t('to'),
225                         'wall' => t('Wall-to-Wall'),
226                         'vwall' => t('via Wall-To-Wall:'),
227                         'profile_url' => $profile_link,
228                         'item_photo_menu' => item_photo_menu($item),
229                         'name' => template_escape($profile_name),
230                         'thumb' => $profile_avatar,
231                         'osparkle' => $osparkle,
232                         'sparkle' => $sparkle,
233                         'title' => template_escape($item['title']),
234                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
235                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
236                         'lock' => $lock,
237                         'location' => template_escape($location),
238                         'indent' => $indent,
239                         'owner_url' => $this->get_owner_url(),
240                         'owner_photo' => $this->get_owner_photo(),
241                         'owner_name' => template_escape($this->get_owner_name()),
242                         'plink' => get_plink($item),
243                         'edpost' => $edpost,
244                         'isstarred' => $isstarred,
245                         'star' => $star,
246                         'filer' => $filer,
247                         'drop' => $drop,
248                         'vote' => $buttons,
249                         'like' => $like,
250                         'dislike' => $dislike,
251                         'comment' => $this->get_comment_box($indent),
252                         'previewing' => ($conv->is_preview() ? ' preview ' : ''),
253                         'wait' => t('Please wait'),
254                         'thread_level' => $thread_level
255                 );
256
257                 $arr = array('item' => $item, 'output' => $tmp_item);
258                 call_hooks('display_item', $arr);
259
260                 $result = $arr['output'];
261
262                 $result['children'] = array();
263                 $children = $this->get_children();
264                 $nb_children = count($children);
265                 if($nb_children > 0) {
266                         foreach($children as $child) {
267                                 $result['children'][] = $child->get_template_data($alike, $dlike, $thread_level + 1);
268                         }
269                         // Collapse
270                         if(($nb_children > 2) || ($thread_level > 1)) {
271                                 $result['children'][0]['comment_firstcollapsed'] = true;
272                                 $result['children'][0]['num_comments'] = sprintf( tt('%d comment','%d comments',$total_children),$total_children );
273                                 $result['children'][0]['hidden_comments_num'] = $total_children;
274                                 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
275                                 $result['children'][0]['hide_text'] = t('show more');
276                                 if($thread_level > 1) {
277                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
278                                 }
279                                 else {
280                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
281                                 }
282                         }
283                 }
284                 
285         if ($this->is_toplevel()) {
286             $result['total_comments_num'] = "$total_children";
287             $result['total_comments_text'] = tt('comment', 'comments', $total_children);
288         }
289         
290                 $result['private'] = $item['private'];
291                 $result['toplevel'] = ($this->is_toplevel() ? 'toplevel_item' : '');
292
293                 if($this->is_threaded()) {
294                         $result['flatten'] = false;
295                         $result['threaded'] = true;
296                 }
297                 else {
298                         $result['flatten'] = true;
299                         $result['threaded'] = false;
300                 }
301
302                 return $result;
303         }
304         
305         public function get_id() {
306                 return $this->get_data_value('id');
307         }
308
309         public function is_threaded() {
310                 return $this->threaded;
311         }
312
313         /**
314          * Add a child item
315          */
316         public function add_child($item) {
317                 $item_id = $item->get_id();
318                 if(!$item_id) {
319                         logger('[ERROR] Item::add_child : Item has no ID!!', LOGGER_DEBUG);
320                         return false;
321                 }
322                 if($this->get_child($item->get_id())) {
323                         logger('[WARN] Item::add_child : Item already exists ('. $item->get_id() .').', LOGGER_DEBUG);
324                         return false;
325                 }
326                 /*
327                  * Only add what will be displayed
328                  */
329                 if($item->get_data_value('network') === NETWORK_MAIL && local_user() != $item->get_data_value('uid')) {
330                         logger('[WARN] Item::add_child : Item is a mail ('. $item->get_id() .').', LOGGER_DEBUG);
331                         return false;
332                 }
333                 if($item->get_data_value('verb') === ACTIVITY_LIKE || $item->get_data_value('verb') === ACTIVITY_DISLIKE) {
334                         logger('[WARN] Item::add_child : Item is a (dis)like ('. $item->get_id() .').', LOGGER_DEBUG);
335                         return false;
336                 }
337                 
338                 $item->set_parent($this);
339                 $this->children[] = $item;
340                 return end($this->children);
341         }
342
343         /**
344          * Get a child by its ID
345          */
346         public function get_child($id) {
347                 foreach($this->get_children() as $child) {
348                         if($child->get_id() == $id)
349                                 return $child;
350                 }
351                 return null;
352         }
353
354         /**
355          * Get all ou children
356          */
357         public function get_children() {
358                 return $this->children;
359         }
360
361         /**
362          * Set our parent
363          */
364         protected function set_parent($item) {
365                 $parent = $this->get_parent();
366                 if($parent) {
367                         $parent->remove_child($this);
368                 }
369                 $this->parent = $item;
370                 $this->set_conversation($item->get_conversation());
371         }
372
373         /**
374          * Remove our parent
375          */
376         protected function remove_parent() {
377                 $this->parent = null;
378                 $this->conversation = null;
379         }
380
381         /**
382          * Remove a child
383          */
384         public function remove_child($item) {
385                 $id = $item->get_id();
386                 foreach($this->get_children() as $key => $child) {
387                         if($child->get_id() == $id) {
388                                 $child->remove_parent();
389                                 unset($this->children[$key]);
390                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
391                                 $this->children = array_values($this->children);
392                                 return true;
393                         }
394                 }
395                 logger('[WARN] Item::remove_child : Item is not a child ('. $id .').', LOGGER_DEBUG);
396                 return false;
397         }
398
399         /**
400          * Get parent item
401          */
402         protected function get_parent() {
403                 return $this->parent;
404         }
405
406         /**
407          * set conversation
408          */
409         public function set_conversation($conv) {
410                 $previous_mode = ($this->conversation ? $this->conversation->get_mode() : '');
411                 
412                 $this->conversation = $conv;
413
414                 // Set it on our children too
415                 foreach($this->get_children() as $child)
416                         $child->set_conversation($conv);
417         }
418
419         /**
420          * get conversation
421          */
422         public function get_conversation() {
423                 return $this->conversation;
424         }
425
426         /**
427          * Get raw data
428          *
429          * We shouldn't need this
430          */
431         public function get_data() {
432                 return $this->data;
433         }
434
435         /**
436          * Get a data value
437          *
438          * Returns:
439          *      _ value on success
440          *      _ false on failure
441          */
442         public function get_data_value($name) {
443                 if(!isset($this->data[$name])) {
444                         logger('[ERROR] Item::get_data_value : Item has no value name "'. $name .'".', LOGGER_DEBUG);
445                         return false;
446                 }
447
448                 return $this->data[$name];
449         }
450
451         /**
452          * Set template
453          */
454         private function set_template($name) {
455                 if(!x($this->available_templates, $name)) {
456                         logger('[ERROR] Item::set_template : Template not available ("'. $name .'").', LOGGER_DEBUG);
457                         return false;
458                 }
459                 $this->template = $this->available_templates[$name];
460         }
461
462         /**
463          * Get template
464          */
465         private function get_template() {
466                 return $this->template;
467         }
468
469         /**
470          * Check if this is a toplevel post
471          */
472         private function is_toplevel() {
473                 return $this->toplevel;
474         }
475
476         /**
477          * Check if this is writable
478          */
479         private function is_writable() {
480                 $conv = $this->get_conversation();
481
482                 if($conv) {
483                         // This will allow us to comment on wall-to-wall items owned by our friends
484                         // and community forums even if somebody else wrote the post.
485                         return ($this->writable || ($this->is_visiting() && $conv->get_mode() == 'profile'));
486                 }
487                 return $this->writable;
488         }
489
490         /**
491          * Count the total of our descendants
492          */
493         private function count_descendants() {
494                 $children = $this->get_children();
495                 $total = count($children);
496                 if($total > 0) {
497                         foreach($children as $child) {
498                                 $total += $child->count_descendants();
499                         }
500                 }
501                 return $total;
502         }
503
504         /**
505          * Get the template for the comment box
506          */
507         private function get_comment_box_template() {
508                 return $this->comment_box_template;
509         }
510
511         /**
512          * Get the comment box
513          *
514          * Returns:
515          *      _ The comment box string (empty if no comment box)
516          *      _ false on failure
517          */
518         private function get_comment_box($indent) {
519                 if(!$this->is_toplevel() && !get_config('system','thread_allow')) {
520                         return '';
521                 }
522                 
523                 $comment_box = '';
524                 $conv = $this->get_conversation();
525                 $template = get_markup_template($this->get_comment_box_template());
526                 $ww = '';
527                 if( ($conv->get_mode() === 'network') && $this->is_wall_to_wall() )
528                         $ww = 'ww';
529
530                 if($conv->is_writable() && $this->is_writable()) {
531                         $a = $this->get_app();
532                         $qc = $qcomment =  null;
533
534                         /*
535                          * Hmmm, code depending on the presence of a particular plugin?
536                          * This should be better if done by a hook
537                          */
538                         if(in_array('qcomment',$a->plugins)) {
539                                 $qc = ((local_user()) ? get_pconfig(local_user(),'qcomment','words') : null);
540                                 $qcomment = (($qc) ? explode("\n",$qc) : null);
541                         }
542                         $comment_box = replace_macros($template,array(
543                                 '$return_path' => '',
544                                 '$threaded' => $this->is_threaded(),
545                                 '$jsreload' => (($conv->get_mode() === 'display') ? $_SESSION['return_url'] : ''),
546                                 '$type' => (($conv->get_mode() === 'profile') ? 'wall-comment' : 'net-comment'),
547                                 '$id' => $this->get_id(),
548                                 '$parent' => $this->get_id(),
549                                 '$qcomment' => $qcomment,
550                                 '$profile_uid' =>  $conv->get_profile_owner(),
551                                 '$mylink' => $a->contact['url'],
552                                 '$mytitle' => t('This is you'),
553                                 '$myphoto' => $a->contact['thumb'],
554                                 '$comment' => t('Comment'),
555                                 '$submit' => t('Submit'),
556                                 '$edbold' => t('Bold'),
557                                 '$editalic' => t('Italic'),
558                                 '$eduline' => t('Underline'),
559                                 '$edquote' => t('Quote'),
560                                 '$edcode' => t('Code'),
561                                 '$edimg' => t('Image'),
562                                 '$edurl' => t('Link'),
563                                 '$edvideo' => t('Video'),
564                                 '$preview' => t('Preview'),
565                                 '$indent' => $indent,
566                                 '$sourceapp' => t($a->sourcename),
567                                 '$ww' => (($conv->get_mode() === 'network') ? $ww : '')
568                         ));
569                 }
570
571                 return $comment_box;
572         }
573
574         private function get_redirect_url() {
575                 return $this->redirect_url;
576         }
577
578         /**
579          * Check if we are a wall to wall item and set the relevant properties
580          */
581         protected function check_wall_to_wall() {
582                 $a = $this->get_app();
583                 $conv = $this->get_conversation();
584                 $this->wall_to_wall = false;
585                 
586                 if($this->is_toplevel()) {
587                         if( (! $this->get_data_value('self')) && ($conv->get_mode() !== 'profile')) {
588                                 if($this->get_data_value('wall')) {
589
590                                         // On the network page, I am the owner. On the display page it will be the profile owner.
591                                         // This will have been stored in $a->page_contact by our calling page.
592                                         // Put this person as the wall owner of the wall-to-wall notice.
593
594                                         $this->owner_url = zrl($a->page_contact['url']);
595                                         $this->owner_photo = $a->page_contact['thumb'];
596                                         $this->owner_name = $a->page_contact['name'];
597                                         $this->set_template('wall2wall');
598                                         $this->wall_to_wall = true;
599                                 }
600                                 else if($this->get_data_value('owner-link')) {
601
602                                         $owner_linkmatch = (($this->get_data_value('owner-link')) && link_compare($this->get_data_value('owner-link'),$this->get_data_value('author-link')));
603                                         $alias_linkmatch = (($this->get_data_value('alias')) && link_compare($this->get_data_value('alias'),$this->get_data_value('author-link')));
604                                         $owner_namematch = (($this->get_data_value('owner-name')) && $this->get_data_value('owner-name') == $this->get_data_value('author-name'));
605                                         if((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
606
607                                                 // The author url doesn't match the owner (typically the contact)
608                                                 // and also doesn't match the contact alias. 
609                                                 // The name match is a hack to catch several weird cases where URLs are 
610                                                 // all over the park. It can be tricked, but this prevents you from
611                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
612                                                 // well that it's the same Bob Smith. 
613
614                                                 // But it could be somebody else with the same name. It just isn't highly likely. 
615                                                 
616
617                                                 $this->owner_photo = $this->get_data_value('owner-avatar');
618                                                 $this->owner_name = $this->get_data_value('owner-name');
619                                                 $this->set_template('wall2wall');
620                                                 $this->wall_to_wall = true;
621                                                 // If it is our contact, use a friendly redirect link
622                                                 if((link_compare($this->get_data_value('owner-link'),$this->get_data_value('url'))) 
623                                                         && ($this->get_data_value('network') === NETWORK_DFRN)) {
624                                                         $this->owner_url = $this->get_redirect_url();
625                                                 }
626                                                 else
627                                                         $this->owner_url = zrl($this->get_data_value('owner-link'));
628                                         }
629                                 }
630                         }
631                 }
632
633                 if(!$this->wall_to_wall) {
634                         $this->set_template('wall');
635                         $this->owner_url = '';
636                         $this->owner_photo = '';
637                         $this->owner_name = '';
638                 }
639         }
640
641         private function is_wall_to_wall() {
642                 return $this->wall_to_wall;
643         }
644
645         private function get_owner_url() {
646                 return $this->owner_url;
647         }
648
649         private function get_owner_photo() {
650                 return $this->owner_photo;
651         }
652
653         private function get_owner_name() {
654                 return $this->owner_name;
655         }
656
657         private function is_visiting() {
658                 return $this->visiting;
659         }
660 }
661 ?>