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 * Output our CSS class for bookmark notice list elements
245 * @param NoticeListItem $nli The item being shown
247 * @return boolean hook value
250 function onStartOpenNoticeListItemElement($nli)
252 if (!$this->isMyNotice($nli->notice)) {
256 $nb = Bookmark::getByNotice($nli->notice);
259 $this->log(LOG_INFO, "Notice {$nli->notice->id} has bookmark class but no matching Bookmark record.");
263 $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
264 $class = 'h-entry notice bookmark';
265 if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
266 $class .= ' limited-scope';
268 $nli->out->elementStart('li', array('class' => $class,
269 'id' => 'notice-' . $id));
271 Event::handle('EndOpenNoticeListItemElement', array($nli));
276 * Modify the default menu to link to our custom action
278 * Using event handlers, it's possible to modify the default UI for pages
279 * almost without limit. In this method, we add a menu item to the default
280 * primary menu for the interface to link to our action.
282 * The Action class provides a rich set of events to hook, as well as output
285 * @param Action $action The current action handler. Use this to
288 * @return boolean hook value; true means continue processing, false means stop.
292 function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
294 $menu->menuItem(common_local_url('bookmarks', array('nickname' => $target->getNickname())),
295 // TRANS: Menu item in sample plugin.
297 // TRANS: Menu item title in sample plugin.
298 _m('A list of your bookmarks'), false, 'nav_timeline_bookmarks');
304 return array(ActivityObject::BOOKMARK);
308 * When a notice is deleted, delete the related Bookmark
310 * @param Notice $notice Notice being deleted
312 * @return boolean hook value
314 function deleteRelated(Notice $notice)
316 if ($this->isMyNotice($notice)) {
318 $nb = Bookmark::getByNotice($notice);
329 * Save a bookmark from an activity
331 * @param Activity $activity Activity to save
332 * @param Profile $actor Profile to use as author
333 * @param array $options Options to pass to bookmark-saving code
335 * @return Notice resulting notice
337 function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
339 $bookmark = $activity->objects[0];
341 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
343 if (count($relLinkEls) < 1) {
344 // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
345 throw new ClientException(_m('Expected exactly 1 link '.
346 'rel=related in a Bookmark.'));
349 if (count($relLinkEls) > 1) {
350 common_log(LOG_WARNING,
351 "Got too many link rel=related in a Bookmark.");
354 $linkEl = $relLinkEls[0];
356 $url = $linkEl->getAttribute('href');
360 foreach ($activity->categories as $category) {
361 $tags[] = common_canonical_tag($category->term);
364 if (!empty($activity->time)) {
365 $options['created'] = common_sql_date($activity->time);
368 // Fill in location if available
370 $location = $activity->context->location;
373 $options['lat'] = $location->lat;
374 $options['lon'] = $location->lon;
375 if ($location->location_id) {
376 $options['location_ns'] = $location->location_ns;
377 $options['location_id'] = $location->location_id;
381 $options['groups'] = array();
382 $options['replies'] = array(); // TODO: context->attention
384 foreach ($activity->context->attention as $attnUrl=>$type) {
386 $other = Profile::fromUri($attnUrl);
387 if ($other->isGroup()) {
388 $options['groups'][] = $other->id;
390 $options['replies'][] = $attnUrl;
392 } catch (UnknownUriException $e) {
393 // We simply don't know this URI, despite lookup attempts.
397 // Maintain direct reply associations
398 // @fixme what about conversation ID?
400 if (!empty($activity->context->replyToID)) {
401 $orig = Notice::getKV('uri',
402 $activity->context->replyToID);
404 $options['reply_to'] = $orig->id;
408 return Bookmark::saveNew($actor,
416 function activityObjectFromNotice(Notice $notice)
418 assert($this->isMyNotice($notice));
421 "Formatting notice {$notice->uri} as a bookmark.");
423 $object = new ActivityObject();
424 $nb = Bookmark::getByNotice($notice);
426 $object->id = $notice->uri;
427 $object->type = ActivityObject::BOOKMARK;
428 $object->title = $nb->title;
429 $object->summary = $nb->description;
430 $object->link = $notice->getUrl();
432 // Attributes of the URL
434 $attachments = $notice->attachments();
436 if (count($attachments) != 1) {
437 // TRANS: Server exception thrown when a bookmark has multiple attachments.
438 throw new ServerException(_m('Bookmark notice with the '.
439 'wrong number of attachments.'));
442 $target = $attachments[0];
444 $attrs = array('rel' => 'related',
445 'href' => $target->url);
447 if (!empty($target->title)) {
448 $attrs['title'] = $target->title;
451 $object->extra[] = array('link', $attrs, null);
453 // Attributes of the thumbnail, if any
456 $thumbnail = $target->getThumbnail();
457 $tattrs = array('rel' => 'preview',
458 'href' => $thumbnail->url);
460 if (!empty($thumbnail->width)) {
461 $tattrs['media:width'] = $thumbnail->width;
464 if (!empty($thumbnail->height)) {
465 $tattrs['media:height'] = $thumbnail->height;
468 $object->extra[] = array('link', $tattrs, null);
469 } catch (UnsupportedMediaException $e) {
470 // No image thumbnail metadata available
477 * Given a notice list item, returns an adapter specific
480 * @param NoticeListItem $nli item to adapt
482 * @return NoticeListItemAdapter adapter or null
484 function adaptNoticeListItem($nli)
486 return new BookmarkListItem($nli);
489 function entryForm($out)
491 return new InitialBookmarkForm($out);
501 // TRANS: Application title.
502 return _m('TITLE','Bookmark');
505 function onEndUpgrade()
507 // Version 0.9.x of the plugin didn't stamp notices
508 // with verb and object-type (for obvious reasons). Update
509 // those notices here.
511 $notice = new Notice();
513 $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
514 $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
518 while ($notice->fetch()) {
519 $original = clone($notice);
520 $notice->verb = ActivityVerb::POST;
521 $notice->object_type = ActivityObject::BOOKMARK;
522 $notice->update($original);
526 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
528 assert($obj->type == ActivityObject::BOOKMARK);
530 $bm = Bookmark::getKV('uri', $obj->id);
533 throw new ServerException("Unknown bookmark: " . $obj->id);
536 $out['displayName'] = $bm->title;
537 $out['targetUrl'] = $bm->url;