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/
47 class BookmarkPlugin extends Plugin
49 const VERSION = '0.1';
50 const IMPORTDELICIOUS = 'BookmarkPlugin:IMPORTDELICIOUS';
53 * Authorization for importing delicious bookmarks
55 * By default, everyone can import bookmarks except silenced people.
57 * @param Profile $profile Person whose rights to check
58 * @param string $right Right to check; const value
59 * @param boolean &$result Result of the check, writeable
61 * @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.
82 function onCheckSchema()
84 $schema = Schema::get();
86 // For storing user-submitted flags on profiles
88 $schema->ensureTable('bookmark',
89 array(new ColumnDef('id',
94 new ColumnDef('profile_id',
104 new ColumnDef('title',
107 new ColumnDef('description',
114 new ColumnDef('created',
124 * When a notice is deleted, delete the related Bookmark
126 * @param Notice $notice Notice being deleted
128 * @return boolean hook value
131 function onNoticeDeleteRelated($notice)
133 $nb = Bookmark::getByNotice($notice);
143 * Show the CSS necessary for this plugin
145 * @param Action $action the action being run
147 * @return boolean hook value
150 function onEndShowStyles($action)
152 $action->cssLink('plugins/Bookmark/bookmark.css');
157 * Load related modules when needed
159 * @param string $cls Name of the class to be loaded
161 * @return boolean hook value; true means continue processing, false means stop.
164 function onAutoload($cls)
166 $dir = dirname(__FILE__);
170 case 'ShowbookmarkAction':
171 case 'NewbookmarkAction':
172 case 'BookmarkpopupAction':
173 case 'NoticebyurlAction':
174 case 'ImportdeliciousAction':
175 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
178 include_once $dir.'/'.$cls.'.php';
181 case 'DeliciousBackupImporter':
182 case 'DeliciousBookmarkImporter':
183 include_once $dir.'/'.strtolower($cls).'.php';
191 * Map URLs to actions
193 * @param Net_URL_Mapper $m path-to-action mapper
195 * @return boolean hook value; true means continue processing, false means stop.
198 function onRouterInitialized($m)
200 $m->connect('main/bookmark/new',
201 array('action' => 'newbookmark'),
202 array('id' => '[0-9]+'));
204 $m->connect('main/bookmark/popup',
205 array('action' => 'bookmarkpopup'));
207 $m->connect('main/bookmark/import',
208 array('action' => 'importdelicious'));
210 $m->connect('bookmark/:id',
211 array('action' => 'showbookmark'),
212 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
214 $m->connect('notice/by-url/:id',
215 array('action' => 'noticebyurl'),
216 array('id' => '[0-9]+'));
222 * Output the HTML for a bookmark in a list
224 * @param NoticeListItem $nli The list item being shown.
226 * @return boolean hook value
229 function onStartShowNoticeItem($nli)
231 $nb = Bookmark::getByNotice($nli->notice);
236 $notice = $nli->notice;
237 $profile = $nli->profile;
239 $atts = $notice->attachments();
241 if (count($atts) < 1) {
242 // Something wrong; let default code deal with it.
248 // XXX: only show the bookmark URL for non-single-page stuff
250 if ($out instanceof ShowbookmarkAction) {
252 $out->elementStart('h3');
254 array('href' => $att->url),
256 $out->elementEnd('h3');
258 $countUrl = common_local_url('noticebyurl',
259 array('id' => $att->id));
261 $out->element('a', array('class' => 'bookmark_notice_count',
262 'href' => $countUrl),
263 $att->noticeCount());
266 // Replies look like "for:" tags
268 $replies = $nli->notice->getReplies();
269 $tags = $nli->notice->getTags();
271 if (!empty($replies) || !empty($tags)) {
273 $out->elementStart('ul', array('class' => 'bookmark_tags'));
275 foreach ($replies as $reply) {
276 $other = Profile::staticGet('id', $reply);
277 $out->elementStart('li');
278 $out->element('a', array('rel' => 'tag',
279 'href' => $other->profileurl,
280 'title' => $other->getBestName()),
281 sprintf('for:%s', $other->nickname));
282 $out->elementEnd('li');
286 foreach ($tags as $tag) {
287 $out->elementStart('li');
289 array('rel' => 'tag',
290 'href' => Notice_tag::url($tag)),
292 $out->elementEnd('li');
296 $out->elementEnd('ul');
299 if (!empty($nb->description)) {
301 array('class' => 'bookmark_description'),
305 if (common_config('attachments', 'show_thumbs')) {
307 foreach ($atts as $check) {
308 $thumbnail = File_thumbnail::staticGet('file_id', $check->id);
309 if (!empty($thumbnail)) {
315 $al = new InlineAttachmentList($notice, $out);
320 $out->elementStart('p', array('class' => 'bookmark_info'));
322 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
325 array('src' => ($avatar) ?
326 $avatar->displayUrl() :
327 Avatar::defaultImage(AVATAR_MINI_SIZE),
328 'class' => 'avatar photo bookmark_avatar',
329 'width' => AVATAR_MINI_SIZE,
330 'height' => AVATAR_MINI_SIZE,
331 'alt' => $profile->getBestName()));
336 array('href' => $profile->profileurl,
337 'title' => $profile->getBestName()),
340 $nli->showNoticeLink();
341 $nli->showNoticeSource();
342 $nli->showNoticeLocation();
346 $out->elementEnd('p');
348 $nli->showNoticeOptions();
356 * Render a notice as a Bookmark object
358 * @param Notice $notice Notice to render
359 * @param ActivityObject &$object Empty object to fill
361 * @return boolean hook value
364 function onStartActivityObjectFromNotice($notice, &$object)
367 "Checking {$notice->uri} to see if it's a bookmark.");
369 $nb = Bookmark::getByNotice($notice);
374 "Formatting notice {$notice->uri} as a bookmark.");
376 $object->id = $notice->uri;
377 $object->type = ActivityObject::BOOKMARK;
378 $object->title = $nb->title;
379 $object->summary = $nb->description;
380 $object->link = $notice->bestUrl();
382 // Attributes of the URL
384 $attachments = $notice->attachments();
386 if (count($attachments) != 1) {
387 throw new ServerException(_('Bookmark notice with the '.
388 'wrong number of attachments.'));
391 $target = $attachments[0];
393 $attrs = array('rel' => 'related',
394 'href' => $target->url);
396 if (!empty($target->title)) {
397 $attrs['title'] = $target->title;
400 $object->extra[] = array('link', $attrs, null);
402 // Attributes of the thumbnail, if any
404 $thumbnail = $target->getThumbnail();
406 if (!empty($thumbnail)) {
407 $tattrs = array('rel' => 'preview',
408 'href' => $thumbnail->url);
410 if (!empty($thumbnail->width)) {
411 $tattrs['media:width'] = $thumbnail->width;
414 if (!empty($thumbnail->height)) {
415 $tattrs['media:height'] = $thumbnail->height;
418 $object->extra[] = array('link', $attrs, null);
428 * Add our two queue handlers to the queue manager
430 * @param QueueManager $qm current queue manager
432 * @return boolean hook value
435 function onEndInitializeQueueManager($qm)
437 $qm->connect('dlcsback', 'DeliciousBackupImporter');
438 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
443 * Plugin version data
445 * @param array &$versions array of version data
450 function onPluginVersion(&$versions)
452 $versions[] = array('name' => 'Sample',
453 'version' => self::VERSION,
454 'author' => 'Evan Prodromou',
455 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
457 _m('Simple extension for supporting bookmarks.'));
462 * Load our document if requested
464 * @param string &$title Title to fetch
465 * @param string &$output HTML to output
467 * @return boolean hook value
470 function onStartLoadDoc(&$title, &$output)
472 if ($title == 'bookmarklet') {
473 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
475 $c = file_get_contents($filename);
476 $output = common_markup_to_html($c);
477 return false; // success!
484 * Handle a posted bookmark from PuSH
486 * @param Activity $activity activity to handle
487 * @param Ostatus_profile $oprofile Profile for the feed
489 * @return boolean hook value
492 function onStartHandleFeedEntryWithProfile($activity, $oprofile)
494 common_log(LOG_INFO, "BookmarkPlugin called for new feed entry.");
496 if (self::_isPostBookmark($activity)) {
499 "Importing activity {$activity->id} as a bookmark.");
501 $author = $oprofile->checkAuthorship($activity);
503 if (empty($author)) {
504 throw new ClientException(_('Can\'t get author for activity.'));
507 self::_postRemoteBookmark($author,
517 * Handle a posted bookmark from Salmon
519 * @param Activity $activity activity to handle
520 * @param mixed $target user or group targeted
522 * @return boolean hook value
525 function onStartHandleSalmonTarget($activity, $target)
527 if (self::_isPostBookmark($activity)) {
529 $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
531 if ($target instanceof User_group) {
532 $uri = $target->getUri();
533 if (!in_array($uri, $activity->context->attention)) {
534 throw new ClientException(_("Bookmark not posted ".
537 } else if ($target instanceof User) {
540 if (!empty($activity->context->replyToID)) {
541 $original = Notice::staticGet('uri',
542 $activity->context->replyToID);
544 if (!in_array($uri, $activity->context->attention) &&
546 $original->profile_id != $target->id)) {
547 throw new ClientException(_("Bookmark not posted ".
551 throw new ServerException(_("Don't know how to handle ".
552 "this kind of target."));
555 $author = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
557 self::_postRemoteBookmark($author,
567 * Handle bookmark posted via AtomPub
569 * @param Activity &$activity Activity that was posted
570 * @param User $user User that posted it
571 * @param Notice &$notice Resulting notice
573 * @return boolean hook value
576 function onStartAtomPubNewActivity(&$activity, $user, &$notice)
578 if (self::_isPostBookmark($activity)) {
579 $options = array('source' => 'atompub');
580 $notice = self::_postBookmark($user->getProfile(),
590 * Handle bookmark imported from a backup file
592 * @param User $user User to import for
593 * @param ActivityObject $author Original author per import file
594 * @param Activity $activity Activity to import
595 * @param boolean $trusted Is this a trusted user?
596 * @param boolean &$done Is this done (success or unrecoverable error)
598 * @return boolean hook value
601 function onStartImportActivity($user, $author, $activity, $trusted, &$done)
603 if (self::_isPostBookmark($activity)) {
605 $bookmark = $activity->objects[0];
608 'Importing Bookmark ' . $bookmark->id .
609 ' for user ' . $user->nickname);
611 $options = array('uri' => $bookmark->id,
612 'url' => $bookmark->link,
613 'source' => 'restore');
615 $saved = self::_postBookmark($user->getProfile(), $activity, $options);
617 if (!empty($saved)) {
628 * Show a link to our delicious import page on profile settings form
630 * @param Action $action Profile settings action being shown
632 * @return boolean hook value
635 function onEndProfileSettingsActions($action)
637 $user = common_current_user();
639 if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
640 $action->elementStart('li');
641 $action->element('a',
642 array('href' => common_local_url('importdelicious')),
643 _('Import del.icio.us bookmarks'));
644 $action->elementEnd('li');
651 * Save a remote bookmark (from Salmon or PuSH)
653 * @param Ostatus_profile $author Author of the bookmark
654 * @param Activity $activity Activity to save
656 * @return Notice resulting notice.
659 static private function _postRemoteBookmark(Ostatus_profile $author,
662 $bookmark = $activity->objects[0];
664 $options = array('uri' => $bookmark->id,
665 'url' => $bookmark->link,
666 'is_local' => Notice::REMOTE_OMB,
667 'source' => 'ostatus');
669 return self::_postBookmark($author->localProfile(), $activity, $options);
673 * Save a bookmark from an activity
675 * @param Profile $profile Profile to use as author
676 * @param Activity $activity Activity to save
677 * @param array $options Options to pass to bookmark-saving code
679 * @return Notice resulting notice
682 static private function _postBookmark(Profile $profile,
686 $bookmark = $activity->objects[0];
688 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
690 if (count($relLinkEls) < 1) {
691 throw new ClientException(_('Expected exactly 1 link '.
692 'rel=related in a Bookmark.'));
695 if (count($relLinkEls) > 1) {
696 common_log(LOG_WARNING,
697 "Got too many link rel=related in a Bookmark.");
700 $linkEl = $relLinkEls[0];
702 $url = $linkEl->getAttribute('href');
706 foreach ($activity->categories as $category) {
707 $tags[] = common_canonical_tag($category->term);
710 if (!empty($activity->time)) {
711 $options['created'] = common_sql_date($activity->time);
714 // Fill in location if available
716 $location = $activity->context->location;
719 $options['lat'] = $location->lat;
720 $options['lon'] = $location->lon;
721 if ($location->location_id) {
722 $options['location_ns'] = $location->location_ns;
723 $options['location_id'] = $location->location_id;
727 $replies = $activity->context->attention;
729 $options['groups'] = array();
730 $options['replies'] = array();
732 foreach ($replies as $replyURI) {
733 $other = Profile::fromURI($replyURI);
734 if (!empty($other)) {
735 $options['replies'][] = $replyURI;
737 $group = User_group::staticGet('uri', $replyURI);
738 if (!empty($group)) {
739 $options['groups'][] = $replyURI;
744 // Maintain direct reply associations
745 // @fixme what about conversation ID?
747 if (!empty($activity->context->replyToID)) {
748 $orig = Notice::staticGet('uri',
749 $activity->context->replyToID);
751 $options['reply_to'] = $orig->id;
755 return Bookmark::saveNew($profile,
764 * Test if an activity represents posting a bookmark
766 * @param Activity $activity Activity to test
768 * @return true if it's a Post of a Bookmark, else false
771 static private function _isPostBookmark($activity)
773 return ($activity->verb == ActivityVerb::POST &&
774 $activity->objects[0]->type == ActivityObject::BOOKMARK);