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