3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
6 * A plugin to enable social-bookmarking functionality
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.
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.
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/>.
23 * @category SocialBookmark
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/
31 if (!defined('STATUSNET')) {
36 * Bookmark plugin main class
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/
46 class BookmarkPlugin extends MicroAppPlugin
48 const VERSION = '0.1';
49 const IMPORTDELICIOUS = 'BookmarkPlugin:IMPORTDELICIOUS';
51 var $oldSaveNew = true;
54 * Authorization for importing delicious bookmarks
56 * By default, everyone can import bookmarks except silenced people.
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
62 * @return boolean hook value
64 function onUserRightsCheck($profile, $right, &$result)
66 if ($right == self::IMPORTDELICIOUS) {
67 $result = !$profile->isSilenced();
74 * Database schema setup
79 * @return boolean hook value; true means continue processing, false means stop.
81 function onCheckSchema()
83 $schema = Schema::get();
85 $schema->ensureTable('bookmark', Bookmark::schemaDef());
91 * Show the CSS necessary for this plugin
93 * @param Action $action the action being run
95 * @return boolean hook value
97 function onEndShowStyles($action)
99 $action->cssLink($this->path('css/bookmark.css'));
103 function onEndShowScripts($action)
105 $action->script($this->path('js/bookmark.js'));
110 * Map URLs to actions
112 * @param URLMapper $m path-to-action mapper
114 * @return boolean hook value; true means continue processing, false means stop.
116 public function onRouterInitialized(URLMapper $m)
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));
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));
133 $m->connect('api/bookmarks/:id.:format',
134 array('action' => 'ApiTimelineBookmarks',
135 'id' => Nickname::INPUT_FMT,
136 'format' => '(xml|json|rss|atom|as)'));
138 $m->connect('main/bookmark/new',
139 array('action' => 'newbookmark'),
140 array('id' => '[0-9]+'));
142 $m->connect('main/bookmark/popup',
143 array('action' => 'bookmarkpopup'));
145 $m->connect('main/bookmark/import',
146 array('action' => 'importdelicious'));
148 $m->connect('main/bookmark/forurl',
149 array('action' => 'bookmarkforurl'));
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}'));
155 $m->connect('notice/by-url/:id',
156 array('action' => 'noticebyurl'),
157 array('id' => '[0-9]+'));
164 * Add our two queue handlers to the queue manager
166 * @param QueueManager $qm current queue manager
168 * @return boolean hook value
170 function onEndInitializeQueueManager($qm)
172 $qm->connect('dlcsback', 'DeliciousBackupImporter');
173 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
178 * Plugin version data
180 * @param array &$versions array of version data
184 function onPluginVersion(array &$versions)
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',
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.');
199 * Load our document if requested
201 * @param string &$title Title to fetch
202 * @param string &$output HTML to output
204 * @return boolean hook value
206 function onStartLoadDoc(&$title, &$output)
208 if ($title == 'bookmarklet') {
209 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
211 $c = file_get_contents($filename);
212 $output = common_markup_to_html($c);
213 return false; // success!
220 * Show a link to our delicious import page on profile settings form
222 * @param Action $action Profile settings action being shown
224 * @return boolean hook value
226 function onEndProfileSettingsActions($action)
228 $user = common_current_user();
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');
243 * Modify the default menu to link to our custom action
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.
249 * The Action class provides a rich set of events to hook, as well as output
252 * @param Action $action The current action handler. Use this to
255 * @return boolean hook value; true means continue processing, false means stop.
259 function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
261 $menu->menuItem(common_local_url('bookmarks', array('nickname' => $target->getNickname())),
262 // TRANS: Menu item in sample plugin.
264 // TRANS: Menu item title in sample plugin.
265 _m('A list of your bookmarks'), false, 'nav_timeline_bookmarks');
271 return array(ActivityObject::BOOKMARK);
275 * When a notice is deleted, delete the related Bookmark
277 * @param Notice $notice Notice being deleted
279 * @return boolean hook value
281 function deleteRelated(Notice $notice)
284 $nb = Bookmark::fromStored($notice);
285 } catch (NoResultException $e) {
286 throw new AlreadyFulfilledException('Bookmark already gone when deleting: '.$e->getMessage());
294 * Save a bookmark from an activity
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
300 * @return Notice resulting notice
302 function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
304 $bookmark = $activity->objects[0];
306 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
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.'));
314 if (count($relLinkEls) > 1) {
315 common_log(LOG_WARNING,
316 "Got too many link rel=related in a Bookmark.");
319 $linkEl = $relLinkEls[0];
321 $url = $linkEl->getAttribute('href');
325 foreach ($activity->categories as $category) {
326 $tags[] = common_canonical_tag($category->term);
329 if (!empty($activity->time)) {
330 $options['created'] = common_sql_date($activity->time);
333 // Fill in location if available
335 $location = $activity->context->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;
346 $options['groups'] = array();
347 $options['replies'] = array(); // TODO: context->attention
349 foreach ($activity->context->attention as $attnUrl=>$type) {
351 $other = Profile::fromUri($attnUrl);
352 if ($other->isGroup()) {
353 $options['groups'][] = $other->id;
355 $options['replies'][] = $attnUrl;
357 } catch (UnknownUriException $e) {
358 // We simply don't know this URI, despite lookup attempts.
362 // Maintain direct reply associations
363 // @fixme what about conversation ID?
365 if (!empty($activity->context->replyToID)) {
366 $orig = Notice::getKV('uri',
367 $activity->context->replyToID);
369 $options['reply_to'] = $orig->id;
373 return Bookmark::saveNew($actor,
381 function activityObjectFromNotice(Notice $notice)
383 assert($this->isMyNotice($notice));
386 "Formatting notice {$notice->uri} as a bookmark.");
388 $object = new ActivityObject();
389 $nb = Bookmark::fromStored($notice);
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();
397 // Attributes of the URL
399 $attachments = $notice->attachments();
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.'));
407 $target = $attachments[0];
409 $attrs = array('rel' => 'related',
410 'href' => $target->getUrl());
412 if (!empty($target->title)) {
413 $attrs['title'] = $target->title;
416 $object->extra[] = array('link', $attrs, null);
418 // Attributes of the thumbnail, if any
421 $thumbnail = $target->getThumbnail();
422 $tattrs = array('rel' => 'preview',
423 'href' => $thumbnail->getUrl());
425 if (!empty($thumbnail->width)) {
426 $tattrs['media:width'] = $thumbnail->width;
429 if (!empty($thumbnail->height)) {
430 $tattrs['media:height'] = $thumbnail->height;
433 $object->extra[] = array('link', $tattrs, null);
434 } catch (UnsupportedMediaException $e) {
435 // No image thumbnail metadata available
441 function entryForm($out)
443 return new InitialBookmarkForm($out);
453 // TRANS: Application title.
454 return _m('TITLE','Bookmark');
457 function onEndUpgrade()
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.
463 $notice = new Notice();
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.'"))');
470 while ($notice->fetch()) {
471 $original = clone($notice);
472 $notice->verb = ActivityVerb::POST;
473 $notice->object_type = ActivityObject::BOOKMARK;
474 $notice->update($original);
478 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
480 assert($obj->type == ActivityObject::BOOKMARK);
482 $bm = Bookmark::getByPK(array('uri' => $obj->id));
484 $out['displayName'] = $bm->getTitle();
485 $out['targetUrl'] = $bm->getUrl();
490 protected function showNoticeItemNotice(NoticeListItem $nli)
492 $nli->out->elementStart('div', 'entry-title');
495 $nli->out->elementEnd('div');
498 public function getDescription()
500 return $this->description;
503 public function getTitle()
508 public function getUrl()
510 if (empty($this->url)) {
511 throw new InvalidUrlException($this->url);
516 protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
518 $nb = Bookmark::fromStored($stored);
520 $profile = $stored->getProfile();
522 // Whether to nofollow
523 $attrs = array('href' => $nb->getUrl(), 'class' => 'bookmark-title');
525 $nf = common_config('nofollow', 'external');
527 if ($nf == 'never' || ($nf == 'sometimes' and $out instanceof ShowstreamAction)) {
528 $attrs['rel'] = 'external';
530 $attrs['rel'] = 'nofollow external';
533 $out->elementStart('h3');
534 $out->element('a', $attrs, $nb->title);
535 $out->elementEnd('h3');
537 // Replies look like "for:" tags
538 $replies = $stored->getReplies();
539 $tags = $stored->getTags();
541 if (!empty($nb->description)) {
543 array('class' => 'bookmark-description'),
547 if (!empty($replies) || !empty($tags)) {
549 $out->elementStart('ul', array('class' => 'bookmark-tags'));
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');
564 foreach ($tags as $tag) {
567 $out->elementStart('li');
569 array('rel' => 'tag',
570 'href' => Notice_tag::url($tag)),
572 $out->elementEnd('li');
577 $out->elementEnd('ul');