]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Bookmark/BookmarkPlugin.php
Merge branch 'oauth-default-icon' into 'nightly'
[quix0rs-gnu-social.git] / plugins / Bookmark / BookmarkPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * A plugin to enable social-bookmarking functionality
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  SocialBookmark
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('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Bookmark plugin main class
37  *
38  * @category  Bookmark
39  * @package   StatusNet
40  * @author    Brion Vibber <brionv@status.net>
41  * @author    Evan Prodromou <evan@status.net>
42  * @copyright 2010 StatusNet, Inc.
43  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
44  * @link      http://status.net/
45  */
46 class BookmarkPlugin extends MicroAppPlugin
47 {
48     const VERSION         = '0.1';
49     const IMPORTDELICIOUS = 'BookmarkPlugin:IMPORTDELICIOUS';
50
51     var $oldSaveNew = true;
52
53     /**
54      * Authorization for importing delicious bookmarks
55      *
56      * By default, everyone can import bookmarks except silenced people.
57      *
58      * @param Profile $profile Person whose rights to check
59      * @param string  $right   Right to check; const value
60      * @param boolean &$result Result of the check, writeable
61      *
62      * @return boolean hook value
63      */
64     function onUserRightsCheck($profile, $right, &$result)
65     {
66         if ($right == self::IMPORTDELICIOUS) {
67             $result = !$profile->isSilenced();
68             return false;
69         }
70         return true;
71     }
72
73     /**
74      * Database schema setup
75      *
76      * @see Schema
77      * @see ColumnDef
78      *
79      * @return boolean hook value; true means continue processing, false means stop.
80      */
81     function onCheckSchema()
82     {
83         $schema = Schema::get();
84
85         $schema->ensureTable('bookmark', Bookmark::schemaDef());
86
87         return true;
88     }
89
90     /**
91      * Show the CSS necessary for this plugin
92      *
93      * @param Action $action the action being run
94      *
95      * @return boolean hook value
96      */
97     function onEndShowStyles($action)
98     {
99         $action->cssLink($this->path('css/bookmark.css'));
100         return true;
101     }
102
103     function onEndShowScripts($action)
104     {
105         $action->script($this->path('js/bookmark.js'));
106         return true;
107     }
108
109     /**
110      * Map URLs to actions
111      *
112      * @param URLMapper $m path-to-action mapper
113      *
114      * @return boolean hook value; true means continue processing, false means stop.
115      */
116     public function onRouterInitialized(URLMapper $m)
117     {
118         if (common_config('singleuser', 'enabled')) {
119             $nickname = User::singleUserNickname();
120             $m->connect('bookmarks',
121                         array('action' => 'bookmarks', 'nickname' => $nickname));
122             $m->connect('bookmarks/rss',
123                         array('action' => 'bookmarksrss', 'nickname' => $nickname));
124         } else {
125             $m->connect(':nickname/bookmarks',
126                         array('action' => 'bookmarks'),
127                         array('nickname' => Nickname::DISPLAY_FMT));
128             $m->connect(':nickname/bookmarks/rss',
129                         array('action' => 'bookmarksrss'),
130                         array('nickname' => Nickname::DISPLAY_FMT));
131         }
132
133         $m->connect('api/bookmarks/:id.:format',
134                     array('action' => 'ApiTimelineBookmarks',
135                           'id' => Nickname::INPUT_FMT,
136                           'format' => '(xml|json|rss|atom|as)'));
137
138         $m->connect('main/bookmark/new',
139                     array('action' => 'newbookmark'),
140                     array('id' => '[0-9]+'));
141
142         $m->connect('main/bookmark/popup',
143                     array('action' => 'bookmarkpopup'));
144
145         $m->connect('main/bookmark/import',
146                     array('action' => 'importdelicious'));
147
148         $m->connect('main/bookmark/forurl',
149                     array('action' => 'bookmarkforurl'));
150
151         $m->connect('bookmark/:id',
152                     array('action' => 'showbookmark'),
153                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
154
155         $m->connect('notice/by-url/:id',
156                     array('action' => 'noticebyurl'),
157                     array('id' => '[0-9]+'));
158
159         return true;
160     }
161
162
163     /**
164      * Add our two queue handlers to the queue manager
165      *
166      * @param QueueManager $qm current queue manager
167      *
168      * @return boolean hook value
169      */
170     function onEndInitializeQueueManager($qm)
171     {
172         $qm->connect('dlcsback', 'DeliciousBackupImporter');
173         $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
174         return true;
175     }
176
177     /**
178      * Plugin version data
179      *
180      * @param array &$versions array of version data
181      *
182      * @return value
183      */
184     function onPluginVersion(array &$versions)
185     {
186         $versions[] = array('name' => 'Bookmark',
187                             'version' => self::VERSION,
188                             'author' => 'Evan Prodromou, Stephane Berube, Jean Baptiste Favre',
189                             'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
190                             'description' =>
191                             // TRANS: Plugin description.
192                             _m('Simple extension for supporting bookmarks. ') .
193                             'BookmarkList feature has been developped by Stephane Berube. ' .
194                             'Integration has been done by Jean Baptiste Favre.');
195         return true;
196     }
197
198     /**
199      * Load our document if requested
200      *
201      * @param string &$title  Title to fetch
202      * @param string &$output HTML to output
203      *
204      * @return boolean hook value
205      */
206     function onStartLoadDoc(&$title, &$output)
207     {
208         if ($title == 'bookmarklet') {
209             $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
210
211             $c      = file_get_contents($filename);
212             $output = common_markup_to_html($c);
213             return false; // success!
214         }
215
216         return true;
217     }
218
219     /**
220      * Show a link to our delicious import page on profile settings form
221      *
222      * @param Action $action Profile settings action being shown
223      *
224      * @return boolean hook value
225      */
226     function onEndProfileSettingsActions($action)
227     {
228         $user = common_current_user();
229
230         if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
231             $action->elementStart('li');
232             $action->element('a',
233                              array('href' => common_local_url('importdelicious')),
234                              // TRANS: Link text in proile leading to import form.
235                              _m('Import del.icio.us bookmarks'));
236             $action->elementEnd('li');
237         }
238
239         return true;
240     }
241
242     /**
243      * Modify the default menu to link to our custom action
244      *
245      * Using event handlers, it's possible to modify the default UI for pages
246      * almost without limit. In this method, we add a menu item to the default
247      * primary menu for the interface to link to our action.
248      *
249      * The Action class provides a rich set of events to hook, as well as output
250      * methods.
251      *
252      * @param Action $action The current action handler. Use this to
253      * do any output.
254      *
255      * @return boolean hook value; true means continue processing, false means stop.
256      *
257      * @see Action
258      */
259     function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
260     {
261         $menu->menuItem(common_local_url('bookmarks', array('nickname' => $target->getNickname())),
262                           // TRANS: Menu item in sample plugin.
263                           _m('Bookmarks'),
264                           // TRANS: Menu item title in sample plugin.
265                           _m('A list of your bookmarks'), false, 'nav_timeline_bookmarks');
266         return true;
267     }
268
269     function types()
270     {
271         return array(ActivityObject::BOOKMARK);
272     }
273
274     /**
275      * When a notice is deleted, delete the related Bookmark
276      *
277      * @param Notice $notice Notice being deleted
278      *
279      * @return boolean hook value
280      */
281     function deleteRelated(Notice $notice)
282     {
283         try {
284             $nb = Bookmark::fromStored($notice);
285         } catch (NoResultException $e) {
286             throw new AlreadyFulfilledException('Bookmark already gone when deleting: '.$e->getMessage());
287         }
288         $nb->delete();
289         
290         return true;
291     }
292
293     /**
294      * Save a bookmark from an activity
295      *
296      * @param Activity $activity Activity to save
297      * @param Profile  $actor    Profile to use as author
298      * @param array    $options  Options to pass to bookmark-saving code
299      *
300      * @return Notice resulting notice
301      */
302     function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
303     {
304         $bookmark = $activity->objects[0];
305
306         $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
307
308         if (count($relLinkEls) < 1) {
309             // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
310             throw new ClientException(_m('Expected exactly 1 link '.
311                                         'rel=related in a Bookmark.'));
312         }
313
314         if (count($relLinkEls) > 1) {
315             common_log(LOG_WARNING,
316                        "Got too many link rel=related in a Bookmark.");
317         }
318
319         $linkEl = $relLinkEls[0];
320
321         $url = $linkEl->getAttribute('href');
322
323         $tags = array();
324
325         foreach ($activity->categories as $category) {
326             $tags[] = common_canonical_tag($category->term);
327         }
328
329         if (!empty($activity->time)) {
330             $options['created'] = common_sql_date($activity->time);
331         }
332
333         // Fill in location if available
334
335         $location = $activity->context->location;
336
337         if ($location) {
338             $options['lat'] = $location->lat;
339             $options['lon'] = $location->lon;
340             if ($location->location_id) {
341                 $options['location_ns'] = $location->location_ns;
342                 $options['location_id'] = $location->location_id;
343             }
344         }
345
346         $options['groups']  = array();
347         $options['replies'] = array();  // TODO: context->attention
348
349         foreach ($activity->context->attention as $attnUrl=>$type) {
350             try {
351                 $other = Profile::fromUri($attnUrl);
352                 if ($other->isGroup()) {
353                     $options['groups'][] = $other->id;
354                 } else {
355                     $options['replies'][] = $attnUrl;
356                 }
357             } catch (UnknownUriException $e) {
358                 // We simply don't know this URI, despite lookup attempts.
359             }
360         }
361
362         // Maintain direct reply associations
363         // @fixme what about conversation ID?
364
365         if (!empty($activity->context->replyToID)) {
366             $orig = Notice::getKV('uri',
367                                       $activity->context->replyToID);
368             if (!empty($orig)) {
369                 $options['reply_to'] = $orig->id;
370             }
371         }
372
373         return Bookmark::saveNew($actor,
374                                  $bookmark->title,
375                                  $url,
376                                  $tags,
377                                  $bookmark->summary,
378                                  $options);
379     }
380
381     function activityObjectFromNotice(Notice $notice)
382     {
383         assert($this->isMyNotice($notice));
384
385         common_log(LOG_INFO,
386                    "Formatting notice {$notice->uri} as a bookmark.");
387
388         $object = new ActivityObject();
389         $nb = Bookmark::fromStored($notice);
390
391         $object->id      = $notice->uri;
392         $object->type    = ActivityObject::BOOKMARK;
393         $object->title   = $nb->getTitle();
394         $object->summary = $nb->getDescription();
395         $object->link    = $notice->getUrl();
396
397         // Attributes of the URL
398
399         $attachments = $notice->attachments();
400
401         if (count($attachments) != 1) {
402             // TRANS: Server exception thrown when a bookmark has multiple attachments.
403             throw new ServerException(_m('Bookmark notice with the '.
404                                         'wrong number of attachments.'));
405         }
406
407         $target = $attachments[0];
408
409         $attrs = array('rel' => 'related',
410                        'href' => $target->getUrl());
411
412         if (!empty($target->title)) {
413             $attrs['title'] = $target->title;
414         }
415
416         $object->extra[] = array('link', $attrs, null);
417
418         // Attributes of the thumbnail, if any
419
420         try {
421             $thumbnail = $target->getThumbnail();
422             $tattrs = array('rel' => 'preview',
423                             'href' => $thumbnail->getUrl());
424
425             if (!empty($thumbnail->width)) {
426                 $tattrs['media:width'] = $thumbnail->width;
427             }
428
429             if (!empty($thumbnail->height)) {
430                 $tattrs['media:height'] = $thumbnail->height;
431             }
432
433             $object->extra[] = array('link', $tattrs, null);
434         } catch (UnsupportedMediaException $e) {
435             // No image thumbnail metadata available
436         }
437
438         return $object;
439     }
440
441     function entryForm($out)
442     {
443         return new InitialBookmarkForm($out);
444     }
445
446     function tag()
447     {
448         return 'bookmark';
449     }
450
451     function appTitle()
452     {
453         // TRANS: Application title.
454         return _m('TITLE','Bookmark');
455     }
456
457     function onEndUpgrade()
458     {
459         // Version 0.9.x of the plugin didn't stamp notices
460         // with verb and object-type (for obvious reasons). Update
461         // those notices here.
462
463         $notice = new Notice();
464         
465         $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
466         $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
467
468         $notice->find();
469
470         while ($notice->fetch()) {
471             $original = clone($notice);
472             $notice->verb        = ActivityVerb::POST;
473             $notice->object_type = ActivityObject::BOOKMARK;
474             $notice->update($original);
475         }
476     }
477
478     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
479     {
480         assert($obj->type == ActivityObject::BOOKMARK);
481
482         $bm = Bookmark::getByPK(array('uri' => $obj->id));
483
484         $out['displayName'] = $bm->getTitle();
485         $out['targetUrl']   = $bm->getUrl();
486
487         return true;
488     }
489
490     protected function showNoticeItemNotice(NoticeListItem $nli)
491     {
492         $nli->out->elementStart('div', 'entry-title');
493         $nli->showAuthor();
494         $nli->showContent();
495         $nli->out->elementEnd('div');
496     }
497
498     public function getDescription()
499     {
500         return $this->description;
501     }
502
503     public function getTitle()
504     {
505         return $this->title;
506     }
507
508     public function getUrl()
509     {
510         if (empty($this->url)) {
511             throw new InvalidUrlException($this->url);
512         }
513         return $this->url;
514     }
515
516     protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
517     {
518         $nb = Bookmark::fromStored($stored);
519
520         $profile = $stored->getProfile();
521
522         // Whether to nofollow
523         $attrs = array('href' => $nb->getUrl(), 'class' => 'bookmark-title');
524
525         $nf = common_config('nofollow', 'external');
526
527         if ($nf == 'never' || ($nf == 'sometimes' and $out instanceof ShowstreamAction)) {
528             $attrs['rel'] = 'external';
529         } else {
530             $attrs['rel'] = 'nofollow external';
531         }
532
533         $out->elementStart('h3');
534         $out->element('a', $attrs, $nb->title);
535         $out->elementEnd('h3');
536
537         // Replies look like "for:" tags
538         $replies = $stored->getReplies();
539         $tags = $stored->getTags();
540
541         if (!empty($nb->description)) {
542             $out->element('p',
543                           array('class' => 'bookmark-description'),
544                           $nb->description);
545         }
546
547         if (!empty($replies) || !empty($tags)) {
548
549             $out->elementStart('ul', array('class' => 'bookmark-tags'));
550
551             foreach ($replies as $reply) {
552                 $other = Profile::getKV('id', $reply);
553                 if (!empty($other)) {
554                     $out->elementStart('li');
555                     $out->element('a', array('rel' => 'tag',
556                                              'href' => $other->profileurl,
557                                              'title' => $other->getBestName()),
558                                   sprintf('for:%s', $other->nickname));
559                     $out->elementEnd('li');
560                     $out->text(' ');
561                 }
562             }
563
564             foreach ($tags as $tag) {
565                 $tag = trim($tag);
566                 if (!empty($tag)) {
567                     $out->elementStart('li');
568                     $out->element('a',
569                                   array('rel' => 'tag',
570                                         'href' => Notice_tag::url($tag)),
571                                   $tag);
572                     $out->elementEnd('li');
573                     $out->text(' ');
574                 }
575             }
576
577             $out->elementEnd('ul');
578         }
579
580     }
581 }