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'));
139 * Load related modules when needed
141 * @param string $cls Name of the class to be loaded
143 * @return boolean hook value; true means continue processing, false means stop.
145 function onAutoload($cls)
147 $dir = dirname(__FILE__);
151 case 'ShowbookmarkAction':
152 case 'NewbookmarkAction':
153 case 'BookmarkpopupAction':
154 case 'NoticebyurlAction':
155 case 'BookmarkforurlAction':
156 case 'ImportdeliciousAction':
157 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
160 include_once $dir.'/'.$cls.'.php';
162 case 'BookmarkListItem':
164 case 'InitialBookmarkForm':
165 case 'DeliciousBackupImporter':
166 case 'DeliciousBookmarkImporter':
167 include_once $dir.'/'.strtolower($cls).'.php';
175 * Map URLs to actions
177 * @param Net_URL_Mapper $m path-to-action mapper
179 * @return boolean hook value; true means continue processing, false means stop.
181 function onRouterInitialized($m)
183 $m->connect('main/bookmark/new',
184 array('action' => 'newbookmark'),
185 array('id' => '[0-9]+'));
187 $m->connect('main/bookmark/popup',
188 array('action' => 'bookmarkpopup'));
190 $m->connect('main/bookmark/import',
191 array('action' => 'importdelicious'));
193 $m->connect('main/bookmark/forurl',
194 array('action' => 'bookmarkforurl'));
196 $m->connect('bookmark/:id',
197 array('action' => 'showbookmark'),
198 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
200 $m->connect('notice/by-url/:id',
201 array('action' => 'noticebyurl'),
202 array('id' => '[0-9]+'));
209 * Add our two queue handlers to the queue manager
211 * @param QueueManager $qm current queue manager
213 * @return boolean hook value
215 function onEndInitializeQueueManager($qm)
217 $qm->connect('dlcsback', 'DeliciousBackupImporter');
218 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
223 * Plugin version data
225 * @param array &$versions array of version data
229 function onPluginVersion(&$versions)
231 $versions[] = array('name' => 'Bookmark',
232 'version' => self::VERSION,
233 'author' => 'Evan Prodromou',
234 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
236 // TRANS: Plugin description.
237 _m('Simple extension for supporting bookmarks.'));
242 * Load our document if requested
244 * @param string &$title Title to fetch
245 * @param string &$output HTML to output
247 * @return boolean hook value
249 function onStartLoadDoc(&$title, &$output)
251 if ($title == 'bookmarklet') {
252 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
254 $c = file_get_contents($filename);
255 $output = common_markup_to_html($c);
256 return false; // success!
263 * Show a link to our delicious import page on profile settings form
265 * @param Action $action Profile settings action being shown
267 * @return boolean hook value
269 function onEndProfileSettingsActions($action)
271 $user = common_current_user();
273 if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
274 $action->elementStart('li');
275 $action->element('a',
276 array('href' => common_local_url('importdelicious')),
277 // TRANS: Link text in proile leading to import form.
278 _m('Import del.icio.us bookmarks'));
279 $action->elementEnd('li');
286 * Output our CSS class for bookmark notice list elements
288 * @param NoticeListItem $nli The item being shown
290 * @return boolean hook value
293 function onStartOpenNoticeListItemElement($nli)
295 if (!$this->isMyNotice($nli->notice)) {
299 $nb = Bookmark::getByNotice($nli->notice);
302 $this->log(LOG_INFO, "Notice {$nli->notice->id} has bookmark class but no matching Bookmark record.");
306 $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
307 $class = 'hentry notice bookmark';
308 if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
309 $class .= ' limited-scope';
311 $nli->out->elementStart('li', array('class' => $class,
312 'id' => 'notice-' . $id));
314 Event::handle('EndOpenNoticeListItemElement', array($nli));
319 * Save a remote bookmark (from Salmon or PuSH)
321 * @param Ostatus_profile $author Author of the bookmark
322 * @param Activity $activity Activity to save
324 * @return Notice resulting notice.
326 static private function _postRemoteBookmark(Ostatus_profile $author,
329 $bookmark = $activity->objects[0];
331 $options = array('uri' => $bookmark->id,
332 'url' => $bookmark->link,
333 'is_local' => Notice::REMOTE,
334 'source' => 'ostatus');
336 return self::_postBookmark($author->localProfile(), $activity, $options);
340 * Test if an activity represents posting a bookmark
342 * @param Activity $activity Activity to test
344 * @return true if it's a Post of a Bookmark, else false
346 static private function _isPostBookmark($activity)
348 return ($activity->verb == ActivityVerb::POST &&
349 $activity->objects[0]->type == ActivityObject::BOOKMARK);
354 return array(ActivityObject::BOOKMARK);
358 * When a notice is deleted, delete the related Bookmark
360 * @param Notice $notice Notice being deleted
362 * @return boolean hook value
364 function deleteRelated($notice)
366 if ($this->isMyNotice($notice)) {
368 $nb = Bookmark::getByNotice($notice);
379 * Save a bookmark from an activity
381 * @param Activity $activity Activity to save
382 * @param Profile $profile Profile to use as author
383 * @param array $options Options to pass to bookmark-saving code
385 * @return Notice resulting notice
387 function saveNoticeFromActivity($activity, $profile, $options=array())
389 $bookmark = $activity->objects[0];
391 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
393 if (count($relLinkEls) < 1) {
394 // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
395 throw new ClientException(_m('Expected exactly 1 link '.
396 'rel=related in a Bookmark.'));
399 if (count($relLinkEls) > 1) {
400 common_log(LOG_WARNING,
401 "Got too many link rel=related in a Bookmark.");
404 $linkEl = $relLinkEls[0];
406 $url = $linkEl->getAttribute('href');
410 foreach ($activity->categories as $category) {
411 $tags[] = common_canonical_tag($category->term);
414 if (!empty($activity->time)) {
415 $options['created'] = common_sql_date($activity->time);
418 // Fill in location if available
420 $location = $activity->context->location;
423 $options['lat'] = $location->lat;
424 $options['lon'] = $location->lon;
425 if ($location->location_id) {
426 $options['location_ns'] = $location->location_ns;
427 $options['location_id'] = $location->location_id;
431 $replies = $activity->context->attention;
433 $options['groups'] = array();
434 $options['replies'] = array();
436 foreach ($replies as $replyURI) {
437 $other = Profile::fromURI($replyURI);
438 if (!empty($other)) {
439 $options['replies'][] = $replyURI;
441 $group = User_group::staticGet('uri', $replyURI);
442 if (!empty($group)) {
443 $options['groups'][] = $replyURI;
448 // Maintain direct reply associations
449 // @fixme what about conversation ID?
451 if (!empty($activity->context->replyToID)) {
452 $orig = Notice::staticGet('uri',
453 $activity->context->replyToID);
455 $options['reply_to'] = $orig->id;
459 return Bookmark::saveNew($profile,
467 function activityObjectFromNotice($notice)
469 assert($this->isMyNotice($notice));
472 "Formatting notice {$notice->uri} as a bookmark.");
474 $object = new ActivityObject();
475 $nb = Bookmark::getByNotice($notice);
477 $object->id = $notice->uri;
478 $object->type = ActivityObject::BOOKMARK;
479 $object->title = $nb->title;
480 $object->summary = $nb->description;
481 $object->link = $notice->bestUrl();
483 // Attributes of the URL
485 $attachments = $notice->attachments();
487 if (count($attachments) != 1) {
488 // TRANS: Server exception thrown when a bookmark has multiple attachments.
489 throw new ServerException(_m('Bookmark notice with the '.
490 'wrong number of attachments.'));
493 $target = $attachments[0];
495 $attrs = array('rel' => 'related',
496 'href' => $target->url);
498 if (!empty($target->title)) {
499 $attrs['title'] = $target->title;
502 $object->extra[] = array('link', $attrs, null);
504 // Attributes of the thumbnail, if any
506 $thumbnail = $target->getThumbnail();
508 if (!empty($thumbnail)) {
509 $tattrs = array('rel' => 'preview',
510 'href' => $thumbnail->url);
512 if (!empty($thumbnail->width)) {
513 $tattrs['media:width'] = $thumbnail->width;
516 if (!empty($thumbnail->height)) {
517 $tattrs['media:height'] = $thumbnail->height;
520 $object->extra[] = array('link', $attrs, null);
527 * Given a notice list item, returns an adapter specific
530 * @param NoticeListItem $nli item to adapt
532 * @return NoticeListItemAdapter adapter or null
534 function adaptNoticeListItem($nli)
536 return new BookmarkListItem($nli);
539 function entryForm($out)
541 return new InitialBookmarkForm($out);
551 // TRANS: Application title.
552 return _m('TITLE','Bookmark');
555 function onEndUpgrade()
557 // Version 0.9.x of the plugin didn't stamp notices
558 // with verb and object-type (for obvious reasons). Update
559 // those notices here.
561 $notice = new Notice();
563 $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
564 $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
568 while ($notice->fetch()) {
569 $original = clone($notice);
570 $notice->verb = ActivityVerb::POST;
571 $notice->object_type = ActivityObject::BOOKMARK;
572 $notice->update($original);
576 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
578 assert($obj->type == ActivityObject::BOOKMARK);
580 $bm = Bookmark::staticGet('uri', $obj->id);
583 throw new ServerException("Unknown bookmark: " . $obj->id);
586 $out['displayName'] = $bm->title;
587 $out['targetUrl'] = $bm->url;