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';
52 * Authorization for importing delicious bookmarks
54 * By default, everyone can import bookmarks except silenced people.
56 * @param Profile $profile Person whose rights to check
57 * @param string $right Right to check; const value
58 * @param boolean &$result Result of the check, writeable
60 * @return boolean hook value
62 function onUserRightsCheck($profile, $right, &$result)
64 if ($right == self::IMPORTDELICIOUS) {
65 $result = !$profile->isSilenced();
72 * Database schema setup
77 * @return boolean hook value; true means continue processing, false means stop.
79 function onCheckSchema()
81 $schema = Schema::get();
83 $schema->ensureTable('bookmark', Bookmark::schemaDef());
89 * Show the CSS necessary for this plugin
91 * @param Action $action the action being run
93 * @return boolean hook value
95 function onEndShowStyles($action)
97 $action->cssLink($this->path('css/bookmark.css'));
101 function onEndShowScripts($action)
103 $action->script($this->path('js/bookmark.js'));
108 * Map URLs to actions
110 * @param Net_URL_Mapper $m path-to-action mapper
112 * @return boolean hook value; true means continue processing, false means stop.
114 function onRouterInitialized($m)
116 if (common_config('singleuser', 'enabled')) {
117 $nickname = User::singleUserNickname();
118 $m->connect('bookmarks',
119 array('action' => 'bookmarks', 'nickname' => $nickname));
120 $m->connect('bookmarks/rss',
121 array('action' => 'bookmarksrss', 'nickname' => $nickname));
123 $m->connect(':nickname/bookmarks',
124 array('action' => 'bookmarks'),
125 array('nickname' => Nickname::DISPLAY_FMT));
126 $m->connect(':nickname/bookmarks/rss',
127 array('action' => 'bookmarksrss'),
128 array('nickname' => Nickname::DISPLAY_FMT));
131 $m->connect('api/bookmarks/:id.:format',
132 array('action' => 'ApiTimelineBookmarks',
133 'id' => Nickname::INPUT_FMT,
134 'format' => '(xml|json|rss|atom|as)'));
136 $m->connect('main/bookmark/new',
137 array('action' => 'newbookmark'),
138 array('id' => '[0-9]+'));
140 $m->connect('main/bookmark/popup',
141 array('action' => 'bookmarkpopup'));
143 $m->connect('main/bookmark/import',
144 array('action' => 'importdelicious'));
146 $m->connect('main/bookmark/forurl',
147 array('action' => 'bookmarkforurl'));
149 $m->connect('bookmark/:id',
150 array('action' => 'showbookmark'),
151 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
153 $m->connect('notice/by-url/:id',
154 array('action' => 'noticebyurl'),
155 array('id' => '[0-9]+'));
162 * Add our two queue handlers to the queue manager
164 * @param QueueManager $qm current queue manager
166 * @return boolean hook value
168 function onEndInitializeQueueManager($qm)
170 $qm->connect('dlcsback', 'DeliciousBackupImporter');
171 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
176 * Plugin version data
178 * @param array &$versions array of version data
182 function onPluginVersion(&$versions)
184 $versions[] = array('name' => 'Bookmark',
185 'version' => self::VERSION,
186 'author' => 'Evan Prodromou, Stephane Berube, Jean Baptiste Favre',
187 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
189 // TRANS: Plugin description.
190 _m('Simple extension for supporting bookmarks. ') .
191 'BookmarkList feature has been developped by Stephane Berube. ' .
192 'Integration has been done by Jean Baptiste Favre.');
197 * Load our document if requested
199 * @param string &$title Title to fetch
200 * @param string &$output HTML to output
202 * @return boolean hook value
204 function onStartLoadDoc(&$title, &$output)
206 if ($title == 'bookmarklet') {
207 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
209 $c = file_get_contents($filename);
210 $output = common_markup_to_html($c);
211 return false; // success!
218 * Show a link to our delicious import page on profile settings form
220 * @param Action $action Profile settings action being shown
222 * @return boolean hook value
224 function onEndProfileSettingsActions($action)
226 $user = common_current_user();
228 if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
229 $action->elementStart('li');
230 $action->element('a',
231 array('href' => common_local_url('importdelicious')),
232 // TRANS: Link text in proile leading to import form.
233 _m('Import del.icio.us bookmarks'));
234 $action->elementEnd('li');
241 * Output our CSS class for bookmark notice list elements
243 * @param NoticeListItem $nli The item being shown
245 * @return boolean hook value
248 function onStartOpenNoticeListItemElement($nli)
250 if (!$this->isMyNotice($nli->notice)) {
254 $nb = Bookmark::getByNotice($nli->notice);
257 $this->log(LOG_INFO, "Notice {$nli->notice->id} has bookmark class but no matching Bookmark record.");
261 $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
262 $class = 'h-entry notice bookmark';
263 if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
264 $class .= ' limited-scope';
266 $nli->out->elementStart('li', array('class' => $class,
267 'id' => 'notice-' . $id));
269 Event::handle('EndOpenNoticeListItemElement', array($nli));
274 * Modify the default menu to link to our custom action
276 * Using event handlers, it's possible to modify the default UI for pages
277 * almost without limit. In this method, we add a menu item to the default
278 * primary menu for the interface to link to our action.
280 * The Action class provides a rich set of events to hook, as well as output
283 * @param Action $action The current action handler. Use this to
286 * @return boolean hook value; true means continue processing, false means stop.
290 function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
292 $menu->menuItem(common_local_url('bookmarks', array('nickname' => $target->getNickname())),
293 // TRANS: Menu item in sample plugin.
295 // TRANS: Menu item title in sample plugin.
296 _m('A list of your bookmarks'), false, 'nav_timeline_bookmarks');
302 return array(ActivityObject::BOOKMARK);
306 * When a notice is deleted, delete the related Bookmark
308 * @param Notice $notice Notice being deleted
310 * @return boolean hook value
312 function deleteRelated(Notice $notice)
314 if ($this->isMyNotice($notice)) {
316 $nb = Bookmark::getByNotice($notice);
327 * Save a bookmark from an activity
329 * @param Activity $activity Activity to save
330 * @param Profile $actor Profile to use as author
331 * @param array $options Options to pass to bookmark-saving code
333 * @return Notice resulting notice
335 function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
337 $bookmark = $activity->objects[0];
339 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
341 if (count($relLinkEls) < 1) {
342 // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
343 throw new ClientException(_m('Expected exactly 1 link '.
344 'rel=related in a Bookmark.'));
347 if (count($relLinkEls) > 1) {
348 common_log(LOG_WARNING,
349 "Got too many link rel=related in a Bookmark.");
352 $linkEl = $relLinkEls[0];
354 $url = $linkEl->getAttribute('href');
358 foreach ($activity->categories as $category) {
359 $tags[] = common_canonical_tag($category->term);
362 if (!empty($activity->time)) {
363 $options['created'] = common_sql_date($activity->time);
366 // Fill in location if available
368 $location = $activity->context->location;
371 $options['lat'] = $location->lat;
372 $options['lon'] = $location->lon;
373 if ($location->location_id) {
374 $options['location_ns'] = $location->location_ns;
375 $options['location_id'] = $location->location_id;
379 $options['groups'] = array();
380 $options['replies'] = array(); // TODO: context->attention
382 foreach ($activity->context->attention as $attnUrl=>$type) {
384 $other = Profile::fromUri($attnUrl);
385 if ($other->isGroup()) {
386 $options['groups'][] = $other->id;
388 $options['replies'][] = $attnUrl;
390 } catch (UnknownUriException $e) {
391 // We simply don't know this URI, despite lookup attempts.
395 // Maintain direct reply associations
396 // @fixme what about conversation ID?
398 if (!empty($activity->context->replyToID)) {
399 $orig = Notice::getKV('uri',
400 $activity->context->replyToID);
402 $options['reply_to'] = $orig->id;
406 return Bookmark::saveNew($actor,
414 function activityObjectFromNotice(Notice $notice)
416 assert($this->isMyNotice($notice));
419 "Formatting notice {$notice->uri} as a bookmark.");
421 $object = new ActivityObject();
422 $nb = Bookmark::getByNotice($notice);
424 $object->id = $notice->uri;
425 $object->type = ActivityObject::BOOKMARK;
426 $object->title = $nb->title;
427 $object->summary = $nb->description;
428 $object->link = $notice->getUrl();
430 // Attributes of the URL
432 $attachments = $notice->attachments();
434 if (count($attachments) != 1) {
435 // TRANS: Server exception thrown when a bookmark has multiple attachments.
436 throw new ServerException(_m('Bookmark notice with the '.
437 'wrong number of attachments.'));
440 $target = $attachments[0];
442 $attrs = array('rel' => 'related',
443 'href' => $target->url);
445 if (!empty($target->title)) {
446 $attrs['title'] = $target->title;
449 $object->extra[] = array('link', $attrs, null);
451 // Attributes of the thumbnail, if any
454 $thumbnail = $target->getThumbnail();
455 $tattrs = array('rel' => 'preview',
456 'href' => $thumbnail->url);
458 if (!empty($thumbnail->width)) {
459 $tattrs['media:width'] = $thumbnail->width;
462 if (!empty($thumbnail->height)) {
463 $tattrs['media:height'] = $thumbnail->height;
466 $object->extra[] = array('link', $tattrs, null);
467 } catch (UnsupportedMediaException $e) {
468 // No image thumbnail metadata available
475 * Given a notice list item, returns an adapter specific
478 * @param NoticeListItem $nli item to adapt
480 * @return NoticeListItemAdapter adapter or null
482 function adaptNoticeListItem($nli)
484 return new BookmarkListItem($nli);
487 function entryForm($out)
489 return new InitialBookmarkForm($out);
499 // TRANS: Application title.
500 return _m('TITLE','Bookmark');
503 function onEndUpgrade()
505 // Version 0.9.x of the plugin didn't stamp notices
506 // with verb and object-type (for obvious reasons). Update
507 // those notices here.
509 $notice = new Notice();
511 $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
512 $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
516 while ($notice->fetch()) {
517 $original = clone($notice);
518 $notice->verb = ActivityVerb::POST;
519 $notice->object_type = ActivityObject::BOOKMARK;
520 $notice->update($original);
524 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
526 assert($obj->type == ActivityObject::BOOKMARK);
528 $bm = Bookmark::getKV('uri', $obj->id);
531 throw new ServerException("Unknown bookmark: " . $obj->id);
534 $out['displayName'] = $bm->title;
535 $out['targetUrl'] = $bm->url;