Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / lib / noticelistitem.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * An item in a notice list
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Widget
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('GNUSOCIAL')) { exit(1); }
32
33 /**
34  * widget for displaying a single notice
35  *
36  * This widget has the core smarts for showing a single notice: what to display,
37  * where, and under which circumstances. Its key method is show(); this is a recipe
38  * that calls all the other show*() methods to build up a single notice. The
39  * ProfileNoticeListItem subclass, for example, overrides showAuthor() to skip
40  * author info (since that's implicit by the data in the page).
41  *
42  * @category UI
43  * @package  StatusNet
44  * @author   Evan Prodromou <evan@status.net>
45  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46  * @link     http://status.net/
47  * @see      NoticeList
48  * @see      ProfileNoticeListItem
49  */
50 class NoticeListItem extends Widget
51 {
52     /** The notice this item will show. */
53     var $notice = null;
54
55     /** The notice that was repeated. */
56     var $repeat = null;
57
58     /** The profile of the author of the notice, extracted once for convenience. */
59     var $profile = null;
60
61     protected $addressees = true;
62     protected $attachments = true;
63     protected $id_prefix = null;
64     protected $options = true;
65     protected $maxchars = 0;   // if <= 0 it means use full posts
66     protected $item_tag = 'li';
67     protected $pa = null;
68
69     /**
70      * constructor
71      *
72      * Also initializes the profile attribute.
73      *
74      * @param Notice $notice The notice we'll display
75      */
76     function __construct(Notice $notice, Action $out=null, array $prefs=array())
77     {
78         parent::__construct($out);
79         if (!empty($notice->repeat_of)) {
80             $original = Notice::getKV('id', $notice->repeat_of);
81             if (!$original instanceof Notice) { // could have been deleted
82                 $this->notice = $notice;
83             } else {
84                 $this->notice = $original;
85                 $this->repeat = $notice;
86             }
87         } else {
88             $this->notice  = $notice;
89         }
90
91         $this->profile = $this->notice->getProfile();
92         
93         // integer preferences
94         foreach(array('maxchars') as $key) {
95             if (array_key_exists($key, $prefs)) {
96                 $this->$key = (int)$prefs[$key];
97             }
98         }
99         // boolean preferences
100         foreach(array('addressees', 'attachments', 'options') as $key) {
101             if (array_key_exists($key, $prefs)) {
102                 $this->$key = (bool)$prefs[$key];
103             }
104         }
105         // string preferences
106         foreach(array('id_prefix', 'item_tag') as $key) {
107             if (array_key_exists($key, $prefs)) {
108                 $this->$key = $prefs[$key];
109             }
110         }
111     }
112
113     /**
114      * recipe function for displaying a single notice.
115      *
116      * This uses all the other methods to correctly display a notice. Override
117      * it or one of the others to fine-tune the output.
118      *
119      * @return void
120      */
121     function show()
122     {
123         if (empty($this->notice)) {
124             common_log(LOG_WARNING, "Trying to show missing notice; skipping.");
125             return;
126         } else if (empty($this->profile)) {
127             common_log(LOG_WARNING, "Trying to show missing profile (" . $this->notice->profile_id . "); skipping.");
128             return;
129         }
130
131         $this->showStart();
132         if (Event::handle('StartShowNoticeItem', array($this))) {
133             $this->showNotice();
134             Event::handle('EndShowNoticeItem', array($this));
135         }
136         $this->showEnd();
137     }
138
139     function showNotice()
140     {
141         if (Event::handle('StartShowNoticeItemNotice', array($this))) {
142             $this->showNoticeHeaders();
143             $this->showContent();
144             $this->showNoticeFooter();
145             Event::handle('EndShowNoticeItemNotice', array($this));
146         }
147     }
148
149     function showNoticeHeaders()
150     {
151         $this->elementStart('section', array('class'=>'notice-headers'));
152         $this->showNoticeTitle();
153         $this->showAuthor();
154
155         if (!empty($this->notice->reply_to) || count($this->getProfileAddressees()) > 0) {
156             $this->elementStart('div', array('class' => 'parents'));
157             try {
158                 $this->showParent();
159             } catch (NoParentNoticeException $e) {
160                 // no parent notice
161             }
162             if ($this->addressees) { $this->showAddressees(); }
163             $this->elementEnd('div');
164         }
165         $this->elementEnd('section');
166     }
167
168     function showNoticeFooter()
169     {
170         $this->elementStart('footer');
171         $this->showNoticeInfo();
172         if ($this->options) { $this->showNoticeOptions(); }
173         if ($this->attachments) { $this->showNoticeAttachments(); }
174         $this->elementEnd('footer');
175     }
176
177     function showNoticeTitle()
178     {
179         if (Event::handle('StartShowNoticeTitle', array($this))) {
180             $this->element('a', array('href' => $this->notice->getUrl(true),
181                                       'class' => 'notice-title'),
182                            $this->notice->getTitle());
183             Event::handle('EndShowNoticeTitle', array($this));
184         }
185     }
186
187     function showNoticeInfo()
188     {
189         if (Event::handle('StartShowNoticeInfo', array($this))) {
190             $this->showNoticeLink();
191             $this->showNoticeSource();
192             $this->showNoticeLocation();
193             $this->showPermalink();
194             Event::handle('EndShowNoticeInfo', array($this));
195         }
196     }
197
198     function showNoticeOptions()
199     {
200         if (Event::handle('StartShowNoticeOptions', array($this))) {
201             $user = common_current_user();
202
203             if ($user instanceof User) {
204                 $this->out->elementStart('div', 'notice-options');
205                 if (Event::handle('StartShowNoticeOptionItems', array($this))) {
206                     $this->showReplyLink();
207                     $this->showDeleteLink();
208                     Event::handle('EndShowNoticeOptionItems', array($this));
209                 }
210                 $this->out->elementEnd('div');
211             }
212
213             Event::handle('EndShowNoticeOptions', array($this));
214         }
215     }
216
217     /**
218      * start a single notice.
219      *
220      * @return void
221      */
222     function showStart()
223     {
224         if (Event::handle('StartOpenNoticeListItemElement', array($this))) {
225             $id = (empty($this->repeat)) ? $this->notice->id : $this->repeat->id;
226             $class = 'h-entry notice';
227             if ($this->notice->scope != 0 && $this->notice->scope != 1) {
228                 $class .= ' limited-scope';
229             }
230             if (!empty($this->notice->source)) {
231                 $class .= ' notice-source-'.$this->notice->source;
232             }
233             $id_prefix = (strlen($this->id_prefix) ? $this->id_prefix . '-' : '');
234             $this->out->elementStart($this->item_tag, array('class' => $class,
235                                                  'id' => "${id_prefix}notice-${id}"));
236             Event::handle('EndOpenNoticeListItemElement', array($this));
237         }
238     }
239
240     /**
241      * show the author of a notice
242      *
243      * By default, this shows the avatar and (linked) nickname of the author.
244      *
245      * @return void
246      */
247
248     function showAuthor()
249     {
250         $attrs = array('href' => $this->profile->profileurl,
251                        'class' => 'h-card',
252                        'title' => $this->profile->getNickname());
253         if(empty($this->repeat)) { $attrs['class'] .= ' p-author'; }
254
255         if (Event::handle('StartShowNoticeItemAuthor', array($this->profile, $this->out, &$attrs))) {
256             $this->out->elementStart('a', $attrs);
257             $this->showAvatar($this->profile);
258             $this->out->text($this->profile->getStreamName());
259             $this->out->elementEnd('a');
260             Event::handle('EndShowNoticeItemAuthor', array($this->profile, $this->out));
261         }
262     }
263
264     function showParent()
265     {
266         $this->out->element(
267             'a',
268             array(
269                 'href' => $this->notice->getParent()->getUrl(),
270                 'class' => 'u-in-reply-to',
271                 'rel' => 'in-reply-to'
272             ),
273             'in reply to'
274         );
275     }
276
277     function showAddressees()
278     {
279         $pa = $this->getProfileAddressees();
280
281         if (!empty($pa)) {
282             $this->out->elementStart('ul', 'addressees');
283             $first = true;
284             foreach ($pa as $addr) {
285                 $this->out->elementStart('li', 'h-card');
286                 $text = $addr['text'];
287                 unset($addr['text']);
288                 $this->out->element('a', $addr, $text);
289                 $this->out->elementEnd('li');
290             }
291             $this->out->elementEnd('ul', 'addressees');
292         }
293     }
294
295     function getProfileAddressees()
296     {
297         if($this->pa) { return $this->pa; }
298         $this->pa = array();
299
300         $attentions = $this->getReplyProfiles();
301
302         foreach ($attentions as $attn) {
303             $class = $attn->isGroup() ? 'group' : 'account';
304             $this->pa[] = array('href' => $attn->profileurl,
305                                 'title' => $attn->getNickname(),
306                                 'class' => "addressee {$class}",
307                                 'text' => $attn->getStreamName());
308         }
309
310         return $this->pa;
311     }
312
313     function getReplyProfiles()
314     {
315         return $this->notice->getReplyProfiles();
316     }
317
318     /**
319      * show the nickname of the author
320      *
321      * Links to the author's profile page
322      *
323      * @return void
324      */
325     function showNickname()
326     {
327         $this->out->raw('<span class="p-name">' .
328                         htmlspecialchars($this->profile->getNickname()) .
329                         '</span>');
330     }
331
332     /**
333      * show the content of the notice
334      *
335      * Shows the content of the notice. This is pre-rendered for efficiency
336      * at save time. Some very old notices might not be pre-rendered, so
337      * they're rendered on the spot.
338      *
339      * @return void
340      */
341     function showContent()
342     {
343         // FIXME: URL, image, video, audio
344         $this->out->elementStart('article', array('class' => 'e-content'));
345         if (Event::handle('StartShowNoticeContent', array($this->notice, $this->out, $this->out->getScoped()))) {
346             if ($this->maxchars > 0 && mb_strlen($this->notice->content) > $this->maxchars) {
347                 $this->out->text(mb_substr($this->notice->content, 0, $this->maxchars) . '[…]');
348             } else {
349                 $this->out->raw($this->notice->getRendered());
350             }
351             Event::handle('EndShowNoticeContent', array($this->notice, $this->out, $this->out->getScoped()));
352         }
353         $this->out->elementEnd('article');
354     }
355
356     function showNoticeAttachments() {
357         if (common_config('attachments', 'show_thumbs')) {
358             $al = new InlineAttachmentList($this->notice, $this->out);
359             $al->show();
360         }
361     }
362
363     /**
364      * show the link to the main page for the notice
365      *
366      * Displays a local link to the rendered notice, with "relative" time.
367      *
368      * @return void
369      */
370     function showNoticeLink()
371     {
372         $this->out->elementStart('a', array('rel' => 'bookmark',
373                                             'class' => 'timestamp',
374                                             'href' => Conversation::getUrlFromNotice($this->notice)));
375         $this->out->element('time', array('class' => 'dt-published',
376                                           'datetime' => common_date_iso8601($this->notice->created),
377                                           'title' => common_exact_date($this->notice->created)),
378                             common_date_string($this->notice->created));
379         $this->out->elementEnd('a');
380     }
381
382     /**
383      * show the notice location
384      *
385      * shows the notice location in the correct language.
386      *
387      * If an URL is available, makes a link. Otherwise, just a span.
388      *
389      * @return void
390      */
391     function showNoticeLocation()
392     {
393         return;
394         try {
395             $location = Notice_location::locFromStored($this->notice);
396         } catch (NoResultException $e) {
397             return;
398         } catch (ServerException $e) {
399             return;
400         }
401
402         $name = $location->getName();
403
404         $lat = $location->lat;
405         $lon = $location->lon;
406         $latlon = (!empty($lat) && !empty($lon)) ? $lat.';'.$lon : '';
407
408         if (empty($name)) {
409             $latdms = $this->decimalDegreesToDMS(abs($lat));
410             $londms = $this->decimalDegreesToDMS(abs($lon));
411             // TRANS: Used in coordinates as abbreviation of north.
412             $north = _('N');
413             // TRANS: Used in coordinates as abbreviation of south.
414             $south = _('S');
415             // TRANS: Used in coordinates as abbreviation of east.
416             $east = _('E');
417             // TRANS: Used in coordinates as abbreviation of west.
418             $west = _('W');
419             $name = sprintf(
420                 // TRANS: Coordinates message.
421                 // TRANS: %1$s is lattitude degrees, %2$s is lattitude minutes,
422                 // TRANS: %3$s is lattitude seconds, %4$s is N (north) or S (south) depending on lattitude,
423                 // TRANS: %5$s is longitude degrees, %6$s is longitude minutes,
424                 // TRANS: %7$s is longitude seconds, %8$s is E (east) or W (west) depending on longitude,
425                 _('%1$u°%2$u\'%3$u"%4$s %5$u°%6$u\'%7$u"%8$s'),
426                 $latdms['deg'],$latdms['min'], $latdms['sec'],($lat>0? $north:$south),
427                 $londms['deg'],$londms['min'], $londms['sec'],($lon>0? $east:$west));
428         }
429
430         $url  = $location->getUrl();
431
432         $this->out->text(' ');
433         $this->out->elementStart('span', array('class' => 'location'));
434         // TRANS: Followed by geo location.
435         $this->out->text(_('at'));
436         $this->out->text(' ');
437         if (empty($url)) {
438             $this->out->element('abbr', array('class' => 'geo',
439                                               'title' => $latlon),
440                                 $name);
441         } else {
442             $xstr = new XMLStringer(false);
443             $xstr->elementStart('a', array('href' => $url,
444                                            'rel' => 'external'));
445             $xstr->element('abbr', array('class' => 'geo',
446                                          'title' => $latlon),
447                            $name);
448             $xstr->elementEnd('a');
449             $this->out->raw($xstr->getString());
450         }
451         $this->out->elementEnd('span');
452     }
453
454     /**
455      * @param number $dec decimal degrees
456      * @return array split into 'deg', 'min', and 'sec'
457      */
458     function decimalDegreesToDMS($dec)
459     {
460         $deg = intval($dec);
461         $tempma = abs($dec) - abs($deg);
462
463         $tempma = $tempma * 3600;
464         $min = floor($tempma / 60);
465         $sec = $tempma - ($min*60);
466
467         return array("deg"=>$deg,"min"=>$min,"sec"=>$sec);
468     }
469
470     /**
471      * Show the source of the notice
472      *
473      * Either the name (and link) of the API client that posted the notice,
474      * or one of other other channels.
475      *
476      * @return void
477      */
478     function showNoticeSource()
479     {
480         $ns = $this->notice->getSource();
481
482         if (!$ns instanceof Notice_source) {
483             return false;
484         }
485
486         // TRANS: A possible notice source (web interface).
487         $source_name = (empty($ns->name)) ? ($ns->code ? _($ns->code) : _m('SOURCE','web')) : _($ns->name);
488         $this->out->text(' ');
489         $this->out->elementStart('span', 'source');
490         // @todo FIXME: probably i18n issue. If "from" is followed by text, that should be a parameter to "from" (from %s).
491         // TRANS: Followed by notice source.
492         $this->out->text(_('from'));
493         $this->out->text(' ');
494
495         $name  = $source_name;
496         $url   = $ns->url;
497         $title = null;
498
499         if (Event::handle('StartNoticeSourceLink', array($this->notice, &$name, &$url, &$title))) {
500             $name = $source_name;
501             $url  = $ns->url;
502         }
503         Event::handle('EndNoticeSourceLink', array($this->notice, &$name, &$url, &$title));
504
505         // if $ns->name and $ns->url are populated we have
506         // configured a source attr somewhere
507         if (!empty($name) && !empty($url)) {
508             $this->out->elementStart('span', 'device');
509
510             $attrs = array(
511                 'href' => $url,
512                 'rel' => 'external'
513             );
514
515             if (!empty($title)) {
516                 $attrs['title'] = $title;
517             }
518
519             $this->out->element('a', $attrs, $name);
520             $this->out->elementEnd('span');
521         } else {
522             $this->out->element('span', 'device', $name);
523         }
524
525         $this->out->elementEnd('span');
526     }
527
528     /**
529      * show link to single-notice view for this notice item
530      *
531      * A permalink that goes to this specific object and nothing else
532      *
533      * @return void
534      */
535     function showPermalink()
536     {
537         $class = 'permalink u-url';
538         if (!$this->notice->isLocal()) {
539             $class .= ' external';
540         }
541
542         try {
543             if($this->repeat) {
544                 $this->out->element('a',
545                             array('href' => $this->repeat->getUrl(),
546                                   'class' => 'u-url'),
547                             '');
548                 $class = str_replace('u-url', 'u-repost-of', $class);
549             }
550         } catch (InvalidUrlException $e) {
551             // no permalink available
552         }
553
554         try {
555             $this->out->element('a',
556                         array('href' => $this->notice->getUrl(true),
557                               'class' => $class),
558                         // TRANS: Addition in notice list item for single-notice view.
559                         _('permalink'));
560         } catch (InvalidUrlException $e) {
561             // no permalink available
562         }
563     }
564
565     /**
566      * show a link to reply to the current notice
567      *
568      * Should either do the reply in the current notice form (if available), or
569      * link out to the notice-posting form. A little flakey, doesn't always work.
570      *
571      * @return void
572      */
573     function showReplyLink()
574     {
575         if (common_logged_in()) {
576             $this->out->text(' ');
577             $reply_url = common_local_url('newnotice',
578                                           array('replyto' => $this->profile->getNickname(), 'inreplyto' => $this->notice->id));
579             $this->out->elementStart('a', array('href' => $reply_url,
580                                                 'class' => 'notice_reply',
581                                                 // TRANS: Link title in notice list item to reply to a notice.
582                                                 'title' => _('Reply to this notice.')));
583             // TRANS: Link text in notice list item to reply to a notice.
584             $this->out->text(_('Reply'));
585             $this->out->text(' ');
586             $this->out->element('span', 'notice_id', $this->notice->id);
587             $this->out->elementEnd('a');
588         }
589     }
590
591     /**
592      * if the user is the author, let them delete the notice
593      *
594      * @return void
595      */
596     function showDeleteLink()
597     {
598         $user = common_current_user();
599
600         $todel = (empty($this->repeat)) ? $this->notice : $this->repeat;
601
602         if (!empty($user) &&
603             ($todel->profile_id == $user->id || $user->hasRight(Right::DELETEOTHERSNOTICE))) {
604             $this->out->text(' ');
605             $deleteurl = common_local_url('deletenotice',
606                                           array('notice' => $todel->id));
607             $this->out->element('a', array('href' => $deleteurl,
608                                            'class' => 'notice_delete popup',
609                                            // TRANS: Link title in notice list item to delete a notice.
610                                            'title' => _('Delete this notice from the timeline.')),
611                                            // TRANS: Link text in notice list item to delete a notice.
612                                            _('Delete'));
613         }
614     }
615
616     /**
617      * finish the notice
618      *
619      * Close the last elements in the notice list item
620      *
621      * @return void
622      */
623     function showEnd()
624     {
625         if (Event::handle('StartCloseNoticeListItemElement', array($this))) {
626             $this->out->elementEnd('li');
627             Event::handle('EndCloseNoticeListItemElement', array($this));
628         }
629     }
630
631     /**
632      * Get the notice in question
633      *
634      * For hooks, etc., this may be useful
635      *
636      * @return Notice The notice we're showing
637      */
638
639     function getNotice()
640     {
641         return $this->notice;
642     }
643 }