]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Bookmark/BookmarkPlugin.php
Merge branch 'master' of gitorious.org:social/mainline into social-master
[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         if ($this->isMyNotice($notice)) {
284                 
285                 $nb = Bookmark::getByNotice($notice);
286
287                 if (!empty($nb)) {
288                 $nb->delete();
289                 }
290         }
291         
292         return true;
293     }
294
295     /**
296      * Save a bookmark from an activity
297      *
298      * @param Activity $activity Activity to save
299      * @param Profile  $actor    Profile to use as author
300      * @param array    $options  Options to pass to bookmark-saving code
301      *
302      * @return Notice resulting notice
303      */
304     function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
305     {
306         $bookmark = $activity->objects[0];
307
308         $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
309
310         if (count($relLinkEls) < 1) {
311             // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
312             throw new ClientException(_m('Expected exactly 1 link '.
313                                         'rel=related in a Bookmark.'));
314         }
315
316         if (count($relLinkEls) > 1) {
317             common_log(LOG_WARNING,
318                        "Got too many link rel=related in a Bookmark.");
319         }
320
321         $linkEl = $relLinkEls[0];
322
323         $url = $linkEl->getAttribute('href');
324
325         $tags = array();
326
327         foreach ($activity->categories as $category) {
328             $tags[] = common_canonical_tag($category->term);
329         }
330
331         if (!empty($activity->time)) {
332             $options['created'] = common_sql_date($activity->time);
333         }
334
335         // Fill in location if available
336
337         $location = $activity->context->location;
338
339         if ($location) {
340             $options['lat'] = $location->lat;
341             $options['lon'] = $location->lon;
342             if ($location->location_id) {
343                 $options['location_ns'] = $location->location_ns;
344                 $options['location_id'] = $location->location_id;
345             }
346         }
347
348         $options['groups']  = array();
349         $options['replies'] = array();  // TODO: context->attention
350
351         foreach ($activity->context->attention as $attnUrl=>$type) {
352             try {
353                 $other = Profile::fromUri($attnUrl);
354                 if ($other->isGroup()) {
355                     $options['groups'][] = $other->id;
356                 } else {
357                     $options['replies'][] = $attnUrl;
358                 }
359             } catch (UnknownUriException $e) {
360                 // We simply don't know this URI, despite lookup attempts.
361             }
362         }
363
364         // Maintain direct reply associations
365         // @fixme what about conversation ID?
366
367         if (!empty($activity->context->replyToID)) {
368             $orig = Notice::getKV('uri',
369                                       $activity->context->replyToID);
370             if (!empty($orig)) {
371                 $options['reply_to'] = $orig->id;
372             }
373         }
374
375         return Bookmark::saveNew($actor,
376                                  $bookmark->title,
377                                  $url,
378                                  $tags,
379                                  $bookmark->summary,
380                                  $options);
381     }
382
383     function activityObjectFromNotice(Notice $notice)
384     {
385         assert($this->isMyNotice($notice));
386
387         common_log(LOG_INFO,
388                    "Formatting notice {$notice->uri} as a bookmark.");
389
390         $object = new ActivityObject();
391         $nb = Bookmark::getByNotice($notice);
392
393         $object->id      = $notice->uri;
394         $object->type    = ActivityObject::BOOKMARK;
395         $object->title   = $nb->title;
396         $object->summary = $nb->description;
397         $object->link    = $notice->getUrl();
398
399         // Attributes of the URL
400
401         $attachments = $notice->attachments();
402
403         if (count($attachments) != 1) {
404             // TRANS: Server exception thrown when a bookmark has multiple attachments.
405             throw new ServerException(_m('Bookmark notice with the '.
406                                         'wrong number of attachments.'));
407         }
408
409         $target = $attachments[0];
410
411         $attrs = array('rel' => 'related',
412                        'href' => $target->url);
413
414         if (!empty($target->title)) {
415             $attrs['title'] = $target->title;
416         }
417
418         $object->extra[] = array('link', $attrs, null);
419
420         // Attributes of the thumbnail, if any
421
422         try {
423             $thumbnail = $target->getThumbnail();
424             $tattrs = array('rel' => 'preview',
425                             'href' => $thumbnail->url);
426
427             if (!empty($thumbnail->width)) {
428                 $tattrs['media:width'] = $thumbnail->width;
429             }
430
431             if (!empty($thumbnail->height)) {
432                 $tattrs['media:height'] = $thumbnail->height;
433             }
434
435             $object->extra[] = array('link', $tattrs, null);
436         } catch (UnsupportedMediaException $e) {
437             // No image thumbnail metadata available
438         }
439
440         return $object;
441     }
442
443     function entryForm($out)
444     {
445         return new InitialBookmarkForm($out);
446     }
447
448     function tag()
449     {
450         return 'bookmark';
451     }
452
453     function appTitle()
454     {
455         // TRANS: Application title.
456         return _m('TITLE','Bookmark');
457     }
458
459     function onEndUpgrade()
460     {
461         // Version 0.9.x of the plugin didn't stamp notices
462         // with verb and object-type (for obvious reasons). Update
463         // those notices here.
464
465         $notice = new Notice();
466         
467         $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
468         $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
469
470         $notice->find();
471
472         while ($notice->fetch()) {
473             $original = clone($notice);
474             $notice->verb        = ActivityVerb::POST;
475             $notice->object_type = ActivityObject::BOOKMARK;
476             $notice->update($original);
477         }
478     }
479
480     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
481     {
482         assert($obj->type == ActivityObject::BOOKMARK);
483
484         $bm = Bookmark::getKV('uri', $obj->id);
485
486         if (empty($bm)) {
487             throw new ServerException("Unknown bookmark: " . $obj->id);
488         }
489
490         $out['displayName'] = $bm->title;
491         $out['targetUrl']   = $bm->url;
492
493         return true;
494     }
495
496     protected function showNoticeItemNotice(NoticeListItem $nli)
497     {
498         $nli->out->elementStart('div', 'entry-title');
499         $nli->showAuthor();
500         $nli->showContent();
501         $nli->out->elementEnd('div');
502     }
503
504     protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
505     {
506         $nb = Bookmark::getByNotice($stored);
507
508         if (empty($nb)) {
509             common_log(LOG_ERR, "No bookmark for notice {$stored->id}");
510             parent::showContent();
511             return;
512         } else if (empty($nb->url)) {
513             common_log(LOG_ERR, "No url for bookmark {$nb->id} for notice {$stored->id}");
514             parent::showContent();
515             return;
516         }
517
518         $profile = $stored->getProfile();
519
520         // Whether to nofollow
521         $attrs = array('href' => $nb->url, 'class' => 'bookmark-title');
522
523         $nf = common_config('nofollow', 'external');
524
525         if ($nf == 'never' || ($nf == 'sometimes' and $out instanceof ShowstreamAction)) {
526             $attrs['rel'] = 'external';
527         } else {
528             $attrs['rel'] = 'nofollow external';
529         }
530
531         $out->elementStart('h3');
532         $out->element('a', $attrs, $nb->title);
533         $out->elementEnd('h3');
534
535         // Replies look like "for:" tags
536         $replies = $stored->getReplies();
537         $tags = $stored->getTags();
538
539         if (!empty($replies) || !empty($tags)) {
540
541             $out->elementStart('ul', array('class' => 'bookmark-tags'));
542
543             foreach ($replies as $reply) {
544                 $other = Profile::getKV('id', $reply);
545                 if (!empty($other)) {
546                     $out->elementStart('li');
547                     $out->element('a', array('rel' => 'tag',
548                                              'href' => $other->profileurl,
549                                              'title' => $other->getBestName()),
550                                   sprintf('for:%s', $other->nickname));
551                     $out->elementEnd('li');
552                     $out->text(' ');
553                 }
554             }
555
556             foreach ($tags as $tag) {
557                 $tag = trim($tag);
558                 if (!empty($tag)) {
559                     $out->elementStart('li');
560                     $out->element('a',
561                                   array('rel' => 'tag',
562                                         'href' => Notice_tag::url($tag)),
563                                   $tag);
564                     $out->elementEnd('li');
565                     $out->text(' ');
566                 }
567             }
568
569             $out->elementEnd('ul');
570         }
571
572         if (!empty($nb->description)) {
573             $out->element('p',
574                           array('class' => 'bookmark-description'),
575                           $nb->description);
576         }
577     }
578 }