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 Net_URL_Mapper $m path-to-action mapper
114 * @return boolean hook value; true means continue processing, false means stop.
116 function onRouterInitialized($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(&$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)
283 if ($this->isMyNotice($notice)) {
285 $nb = Bookmark::getByNotice($notice);
296 * Save a bookmark from an activity
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
302 * @return Notice resulting notice
304 function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
306 $bookmark = $activity->objects[0];
308 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
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.'));
316 if (count($relLinkEls) > 1) {
317 common_log(LOG_WARNING,
318 "Got too many link rel=related in a Bookmark.");
321 $linkEl = $relLinkEls[0];
323 $url = $linkEl->getAttribute('href');
327 foreach ($activity->categories as $category) {
328 $tags[] = common_canonical_tag($category->term);
331 if (!empty($activity->time)) {
332 $options['created'] = common_sql_date($activity->time);
335 // Fill in location if available
337 $location = $activity->context->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;
348 $options['groups'] = array();
349 $options['replies'] = array(); // TODO: context->attention
351 foreach ($activity->context->attention as $attnUrl=>$type) {
353 $other = Profile::fromUri($attnUrl);
354 if ($other->isGroup()) {
355 $options['groups'][] = $other->id;
357 $options['replies'][] = $attnUrl;
359 } catch (UnknownUriException $e) {
360 // We simply don't know this URI, despite lookup attempts.
364 // Maintain direct reply associations
365 // @fixme what about conversation ID?
367 if (!empty($activity->context->replyToID)) {
368 $orig = Notice::getKV('uri',
369 $activity->context->replyToID);
371 $options['reply_to'] = $orig->id;
375 return Bookmark::saveNew($actor,
383 function activityObjectFromNotice(Notice $notice)
385 assert($this->isMyNotice($notice));
388 "Formatting notice {$notice->uri} as a bookmark.");
390 $object = new ActivityObject();
391 $nb = Bookmark::getByNotice($notice);
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();
399 // Attributes of the URL
401 $attachments = $notice->attachments();
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.'));
409 $target = $attachments[0];
411 $attrs = array('rel' => 'related',
412 'href' => $target->url);
414 if (!empty($target->title)) {
415 $attrs['title'] = $target->title;
418 $object->extra[] = array('link', $attrs, null);
420 // Attributes of the thumbnail, if any
423 $thumbnail = $target->getThumbnail();
424 $tattrs = array('rel' => 'preview',
425 'href' => $thumbnail->url);
427 if (!empty($thumbnail->width)) {
428 $tattrs['media:width'] = $thumbnail->width;
431 if (!empty($thumbnail->height)) {
432 $tattrs['media:height'] = $thumbnail->height;
435 $object->extra[] = array('link', $tattrs, null);
436 } catch (UnsupportedMediaException $e) {
437 // No image thumbnail metadata available
444 * Given a notice list item, returns an adapter specific
447 * @param NoticeListItem $nli item to adapt
449 * @return NoticeListItemAdapter adapter or null
451 function adaptNoticeListItem($nli)
453 return new BookmarkListItem($nli);
456 function entryForm($out)
458 return new InitialBookmarkForm($out);
468 // TRANS: Application title.
469 return _m('TITLE','Bookmark');
472 function onEndUpgrade()
474 // Version 0.9.x of the plugin didn't stamp notices
475 // with verb and object-type (for obvious reasons). Update
476 // those notices here.
478 $notice = new Notice();
480 $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
481 $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
485 while ($notice->fetch()) {
486 $original = clone($notice);
487 $notice->verb = ActivityVerb::POST;
488 $notice->object_type = ActivityObject::BOOKMARK;
489 $notice->update($original);
493 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
495 assert($obj->type == ActivityObject::BOOKMARK);
497 $bm = Bookmark::getKV('uri', $obj->id);
500 throw new ServerException("Unknown bookmark: " . $obj->id);
503 $out['displayName'] = $bm->title;
504 $out['targetUrl'] = $bm->url;