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 // For storing user-submitted flags on profiles
85 $schema->ensureTable('bookmark',
86 array(new ColumnDef('id',
91 new ColumnDef('profile_id',
101 new ColumnDef('title',
104 new ColumnDef('description',
111 new ColumnDef('created',
121 * Show the CSS necessary for this plugin
123 * @param Action $action the action being run
125 * @return boolean hook value
127 function onEndShowStyles($action)
129 $action->cssLink($this->path('bookmark.css'));
133 function onEndShowScripts($action)
135 $action->script($this->path('js/bookmark.js'));
140 * Map URLs to actions
142 * @param Net_URL_Mapper $m path-to-action mapper
144 * @return boolean hook value; true means continue processing, false means stop.
146 function onRouterInitialized($m)
148 if (common_config('singleuser', 'enabled')) {
149 $nickname = User::singleUserNickname();
150 $m->connect('bookmarks',
151 array('action' => 'bookmarks', 'nickname' => $nickname));
152 $m->connect('bookmarks/rss',
153 array('action' => 'bookmarksrss', 'nickname' => $nickname));
155 $m->connect(':nickname/bookmarks',
156 array('action' => 'bookmarks'),
157 array('nickname' => Nickname::DISPLAY_FMT));
158 $m->connect(':nickname/bookmarks/rss',
159 array('action' => 'bookmarksrss'),
160 array('nickname' => Nickname::DISPLAY_FMT));
163 $m->connect('api/bookmarks/:id.:format',
164 array('action' => 'ApiTimelineBookmarks',
165 'id' => Nickname::INPUT_FMT,
166 'format' => '(xml|json|rss|atom|as)'));
168 $m->connect('main/bookmark/new',
169 array('action' => 'newbookmark'),
170 array('id' => '[0-9]+'));
172 $m->connect('main/bookmark/popup',
173 array('action' => 'bookmarkpopup'));
175 $m->connect('main/bookmark/import',
176 array('action' => 'importdelicious'));
178 $m->connect('main/bookmark/forurl',
179 array('action' => 'bookmarkforurl'));
181 $m->connect('bookmark/:id',
182 array('action' => 'showbookmark'),
183 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
185 $m->connect('notice/by-url/:id',
186 array('action' => 'noticebyurl'),
187 array('id' => '[0-9]+'));
194 * Add our two queue handlers to the queue manager
196 * @param QueueManager $qm current queue manager
198 * @return boolean hook value
200 function onEndInitializeQueueManager($qm)
202 $qm->connect('dlcsback', 'DeliciousBackupImporter');
203 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
208 * Plugin version data
210 * @param array &$versions array of version data
214 function onPluginVersion(&$versions)
216 $versions[] = array('name' => 'Bookmark',
217 'version' => self::VERSION,
218 'author' => 'Evan Prodromou, Stephane Berube, Jean Baptiste Favre',
219 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
221 // TRANS: Plugin description.
222 _m('Simple extension for supporting bookmarks. ') .
223 'BookmarkList feature has been developped by Stephane Berube. ' .
224 'Integration has been done by Jean Baptiste Favre.');
229 * Load our document if requested
231 * @param string &$title Title to fetch
232 * @param string &$output HTML to output
234 * @return boolean hook value
236 function onStartLoadDoc(&$title, &$output)
238 if ($title == 'bookmarklet') {
239 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
241 $c = file_get_contents($filename);
242 $output = common_markup_to_html($c);
243 return false; // success!
250 * Show a link to our delicious import page on profile settings form
252 * @param Action $action Profile settings action being shown
254 * @return boolean hook value
256 function onEndProfileSettingsActions($action)
258 $user = common_current_user();
260 if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
261 $action->elementStart('li');
262 $action->element('a',
263 array('href' => common_local_url('importdelicious')),
264 // TRANS: Link text in proile leading to import form.
265 _m('Import del.icio.us bookmarks'));
266 $action->elementEnd('li');
273 * Output our CSS class for bookmark notice list elements
275 * @param NoticeListItem $nli The item being shown
277 * @return boolean hook value
280 function onStartOpenNoticeListItemElement($nli)
282 if (!$this->isMyNotice($nli->notice)) {
286 $nb = Bookmark::getByNotice($nli->notice);
289 $this->log(LOG_INFO, "Notice {$nli->notice->id} has bookmark class but no matching Bookmark record.");
293 $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
294 $class = 'hentry notice bookmark';
295 if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
296 $class .= ' limited-scope';
298 $nli->out->elementStart('li', array('class' => $class,
299 'id' => 'notice-' . $id));
301 Event::handle('EndOpenNoticeListItemElement', array($nli));
306 * Modify the default menu to link to our custom action
308 * Using event handlers, it's possible to modify the default UI for pages
309 * almost without limit. In this method, we add a menu item to the default
310 * primary menu for the interface to link to our action.
312 * The Action class provides a rich set of events to hook, as well as output
315 * @param Action $action The current action handler. Use this to
318 * @return boolean hook value; true means continue processing, false means stop.
322 function onEndPersonalGroupNav($action)
324 $this->user = common_current_user();
327 // TRANS: Client error displayed when trying to display bookmarks for a non-existing user.
328 $this->clientError(_('No such user.'));
332 $action->menuItem(common_local_url('bookmarks', array('nickname' => $this->user->nickname)),
333 // TRANS: Menu item in sample plugin.
335 // TRANS: Menu item title in sample plugin.
336 _m('A list of your bookmarks'), false, 'nav_timeline_bookmarks');
341 * Save a remote bookmark (from Salmon or PuSH)
343 * @param Ostatus_profile $author Author of the bookmark
344 * @param Activity $activity Activity to save
346 * @return Notice resulting notice.
348 static private function _postRemoteBookmark(Ostatus_profile $author,
351 $bookmark = $activity->objects[0];
353 $options = array('uri' => $bookmark->id,
354 'url' => $bookmark->link,
355 'is_local' => Notice::REMOTE,
356 'source' => 'ostatus');
358 return self::_postBookmark($author->localProfile(), $activity, $options);
362 * Test if an activity represents posting a bookmark
364 * @param Activity $activity Activity to test
366 * @return true if it's a Post of a Bookmark, else false
368 static private function _isPostBookmark($activity)
370 return ($activity->verb == ActivityVerb::POST &&
371 $activity->objects[0]->type == ActivityObject::BOOKMARK);
376 return array(ActivityObject::BOOKMARK);
380 * When a notice is deleted, delete the related Bookmark
382 * @param Notice $notice Notice being deleted
384 * @return boolean hook value
386 function deleteRelated($notice)
388 if ($this->isMyNotice($notice)) {
390 $nb = Bookmark::getByNotice($notice);
401 * Save a bookmark from an activity
403 * @param Activity $activity Activity to save
404 * @param Profile $profile Profile to use as author
405 * @param array $options Options to pass to bookmark-saving code
407 * @return Notice resulting notice
409 function saveNoticeFromActivity($activity, $profile, $options=array())
411 $bookmark = $activity->objects[0];
413 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
415 if (count($relLinkEls) < 1) {
416 // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
417 throw new ClientException(_m('Expected exactly 1 link '.
418 'rel=related in a Bookmark.'));
421 if (count($relLinkEls) > 1) {
422 common_log(LOG_WARNING,
423 "Got too many link rel=related in a Bookmark.");
426 $linkEl = $relLinkEls[0];
428 $url = $linkEl->getAttribute('href');
432 foreach ($activity->categories as $category) {
433 $tags[] = common_canonical_tag($category->term);
436 if (!empty($activity->time)) {
437 $options['created'] = common_sql_date($activity->time);
440 // Fill in location if available
442 $location = $activity->context->location;
445 $options['lat'] = $location->lat;
446 $options['lon'] = $location->lon;
447 if ($location->location_id) {
448 $options['location_ns'] = $location->location_ns;
449 $options['location_id'] = $location->location_id;
453 $options['groups'] = array();
454 $options['replies'] = array(); // TODO: context->attention
456 foreach ($activity->context->attention as $attnUrl=>$type) {
457 $other = Profile::fromURI($attnUrl);
458 if ($other instanceof Profile) {
459 $options['replies'][] = $attnUrl;
461 // Maybe we can get rid of this since every User_group got a Profile?
462 // TODO: Make sure the above replies get sorted properly for groups (or handled afterwards)
463 $group = User_group::getKV('uri', $attnUrl);
464 if ($group instanceof User_group) {
465 $options['groups'][] = $attnUrl;
470 // Maintain direct reply associations
471 // @fixme what about conversation ID?
473 if (!empty($activity->context->replyToID)) {
474 $orig = Notice::getKV('uri',
475 $activity->context->replyToID);
477 $options['reply_to'] = $orig->id;
481 return Bookmark::saveNew($profile,
489 function activityObjectFromNotice($notice)
491 assert($this->isMyNotice($notice));
494 "Formatting notice {$notice->uri} as a bookmark.");
496 $object = new ActivityObject();
497 $nb = Bookmark::getByNotice($notice);
499 $object->id = $notice->uri;
500 $object->type = ActivityObject::BOOKMARK;
501 $object->title = $nb->title;
502 $object->summary = $nb->description;
503 $object->link = $notice->bestUrl();
505 // Attributes of the URL
507 $attachments = $notice->attachments();
509 if (count($attachments) != 1) {
510 // TRANS: Server exception thrown when a bookmark has multiple attachments.
511 throw new ServerException(_m('Bookmark notice with the '.
512 'wrong number of attachments.'));
515 $target = $attachments[0];
517 $attrs = array('rel' => 'related',
518 'href' => $target->url);
520 if (!empty($target->title)) {
521 $attrs['title'] = $target->title;
524 $object->extra[] = array('link', $attrs, null);
526 // Attributes of the thumbnail, if any
528 $thumbnail = $target->getThumbnail();
530 if (!empty($thumbnail)) {
531 $tattrs = array('rel' => 'preview',
532 'href' => $thumbnail->url);
534 if (!empty($thumbnail->width)) {
535 $tattrs['media:width'] = $thumbnail->width;
538 if (!empty($thumbnail->height)) {
539 $tattrs['media:height'] = $thumbnail->height;
542 $object->extra[] = array('link', $attrs, null);
549 * Given a notice list item, returns an adapter specific
552 * @param NoticeListItem $nli item to adapt
554 * @return NoticeListItemAdapter adapter or null
556 function adaptNoticeListItem($nli)
558 return new BookmarkListItem($nli);
561 function entryForm($out)
563 return new InitialBookmarkForm($out);
573 // TRANS: Application title.
574 return _m('TITLE','Bookmark');
577 function onEndUpgrade()
579 // Version 0.9.x of the plugin didn't stamp notices
580 // with verb and object-type (for obvious reasons). Update
581 // those notices here.
583 $notice = new Notice();
585 $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
586 $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
590 while ($notice->fetch()) {
591 $original = clone($notice);
592 $notice->verb = ActivityVerb::POST;
593 $notice->object_type = ActivityObject::BOOKMARK;
594 $notice->update($original);
598 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
600 assert($obj->type == ActivityObject::BOOKMARK);
602 $bm = Bookmark::getKV('uri', $obj->id);
605 throw new ServerException("Unknown bookmark: " . $obj->id);
608 $out['displayName'] = $bm->title;
609 $out['targetUrl'] = $bm->url;