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($this->path('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,
255 'class' => 'bookmark-title entry-title'),
257 $out->elementEnd('h3');
259 $countUrl = common_local_url('noticebyurl',
260 array('id' => $att->id));
262 $out->element('a', array('class' => 'bookmark-notice-count',
263 'href' => $countUrl),
264 $att->noticeCount());
267 // Replies look like "for:" tags
269 $replies = $nli->notice->getReplies();
270 $tags = $nli->notice->getTags();
272 if (!empty($replies) || !empty($tags)) {
274 $out->elementStart('ul', array('class' => 'bookmark-tags'));
276 foreach ($replies as $reply) {
277 $other = Profile::staticGet('id', $reply);
278 $out->elementStart('li');
279 $out->element('a', array('rel' => 'tag',
280 'href' => $other->profileurl,
281 'title' => $other->getBestName()),
282 sprintf('for:%s', $other->nickname));
283 $out->elementEnd('li');
287 foreach ($tags as $tag) {
288 $out->elementStart('li');
290 array('rel' => 'tag',
291 'href' => Notice_tag::url($tag)),
293 $out->elementEnd('li');
297 $out->elementEnd('ul');
300 if (!empty($nb->description)) {
302 array('class' => 'bookmark-description'),
306 if (common_config('attachments', 'show_thumbs')) {
308 foreach ($atts as $check) {
309 $thumbnail = File_thumbnail::staticGet('file_id', $check->id);
310 if (!empty($thumbnail)) {
316 $al = new InlineAttachmentList($notice, $out);
321 $out->elementStart('div', array('class' => 'bookmark-info entry-content'));
323 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
326 array('src' => ($avatar) ?
327 $avatar->displayUrl() :
328 Avatar::defaultImage(AVATAR_MINI_SIZE),
329 'class' => 'avatar photo bookmark-avatar',
330 'width' => AVATAR_MINI_SIZE,
331 'height' => AVATAR_MINI_SIZE,
332 'alt' => $profile->getBestName()));
337 array('href' => $profile->profileurl,
338 'title' => $profile->getBestName()),
341 $nli->showNoticeLink();
342 $nli->showNoticeSource();
343 $nli->showNoticeLocation();
347 $out->elementEnd('div');
349 $nli->showNoticeOptions();
357 * Render a notice as a Bookmark object
359 * @param Notice $notice Notice to render
360 * @param ActivityObject &$object Empty object to fill
362 * @return boolean hook value
365 function onStartActivityObjectFromNotice($notice, &$object)
368 "Checking {$notice->uri} to see if it's a bookmark.");
370 $nb = Bookmark::getByNotice($notice);
375 "Formatting notice {$notice->uri} as a bookmark.");
377 $object->id = $notice->uri;
378 $object->type = ActivityObject::BOOKMARK;
379 $object->title = $nb->title;
380 $object->summary = $nb->description;
381 $object->link = $notice->bestUrl();
383 // Attributes of the URL
385 $attachments = $notice->attachments();
387 if (count($attachments) != 1) {
388 throw new ServerException(_('Bookmark notice with the '.
389 'wrong number of attachments.'));
392 $target = $attachments[0];
394 $attrs = array('rel' => 'related',
395 'href' => $target->url);
397 if (!empty($target->title)) {
398 $attrs['title'] = $target->title;
401 $object->extra[] = array('link', $attrs, null);
403 // Attributes of the thumbnail, if any
405 $thumbnail = $target->getThumbnail();
407 if (!empty($thumbnail)) {
408 $tattrs = array('rel' => 'preview',
409 'href' => $thumbnail->url);
411 if (!empty($thumbnail->width)) {
412 $tattrs['media:width'] = $thumbnail->width;
415 if (!empty($thumbnail->height)) {
416 $tattrs['media:height'] = $thumbnail->height;
419 $object->extra[] = array('link', $attrs, null);
429 * Add our two queue handlers to the queue manager
431 * @param QueueManager $qm current queue manager
433 * @return boolean hook value
436 function onEndInitializeQueueManager($qm)
438 $qm->connect('dlcsback', 'DeliciousBackupImporter');
439 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
444 * Plugin version data
446 * @param array &$versions array of version data
451 function onPluginVersion(&$versions)
453 $versions[] = array('name' => 'Bookmark',
454 'version' => self::VERSION,
455 'author' => 'Evan Prodromou',
456 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
458 _m('Simple extension for supporting bookmarks.'));
463 * Load our document if requested
465 * @param string &$title Title to fetch
466 * @param string &$output HTML to output
468 * @return boolean hook value
471 function onStartLoadDoc(&$title, &$output)
473 if ($title == 'bookmarklet') {
474 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
476 $c = file_get_contents($filename);
477 $output = common_markup_to_html($c);
478 return false; // success!
485 * Handle a posted bookmark from PuSH
487 * @param Activity $activity activity to handle
488 * @param Ostatus_profile $oprofile Profile for the feed
490 * @return boolean hook value
493 function onStartHandleFeedEntryWithProfile($activity, $oprofile)
495 common_log(LOG_INFO, "BookmarkPlugin called for new feed entry.");
497 if (self::_isPostBookmark($activity)) {
500 "Importing activity {$activity->id} as a bookmark.");
502 $author = $oprofile->checkAuthorship($activity);
504 if (empty($author)) {
505 throw new ClientException(_('Can\'t get author for activity.'));
508 self::_postRemoteBookmark($author,
518 * Handle a posted bookmark from Salmon
520 * @param Activity $activity activity to handle
521 * @param mixed $target user or group targeted
523 * @return boolean hook value
526 function onStartHandleSalmonTarget($activity, $target)
528 if (self::_isPostBookmark($activity)) {
530 $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
532 if ($target instanceof User_group) {
533 $uri = $target->getUri();
534 if (!in_array($uri, $activity->context->attention)) {
535 throw new ClientException(_("Bookmark not posted ".
538 } else if ($target instanceof User) {
541 if (!empty($activity->context->replyToID)) {
542 $original = Notice::staticGet('uri',
543 $activity->context->replyToID);
545 if (!in_array($uri, $activity->context->attention) &&
547 $original->profile_id != $target->id)) {
548 throw new ClientException(_("Bookmark not posted ".
552 throw new ServerException(_("Don't know how to handle ".
553 "this kind of target."));
556 $author = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
558 self::_postRemoteBookmark($author,
568 * Handle bookmark posted via AtomPub
570 * @param Activity &$activity Activity that was posted
571 * @param User $user User that posted it
572 * @param Notice &$notice Resulting notice
574 * @return boolean hook value
577 function onStartAtomPubNewActivity(&$activity, $user, &$notice)
579 if (self::_isPostBookmark($activity)) {
580 $options = array('source' => 'atompub');
581 $notice = self::_postBookmark($user->getProfile(),
591 * Handle bookmark imported from a backup file
593 * @param User $user User to import for
594 * @param ActivityObject $author Original author per import file
595 * @param Activity $activity Activity to import
596 * @param boolean $trusted Is this a trusted user?
597 * @param boolean &$done Is this done (success or unrecoverable error)
599 * @return boolean hook value
602 function onStartImportActivity($user, $author, $activity, $trusted, &$done)
604 if (self::_isPostBookmark($activity)) {
606 $bookmark = $activity->objects[0];
609 'Importing Bookmark ' . $bookmark->id .
610 ' for user ' . $user->nickname);
612 $options = array('uri' => $bookmark->id,
613 'url' => $bookmark->link,
614 'source' => 'restore');
616 $saved = self::_postBookmark($user->getProfile(), $activity, $options);
618 if (!empty($saved)) {
629 * Show a link to our delicious import page on profile settings form
631 * @param Action $action Profile settings action being shown
633 * @return boolean hook value
636 function onEndProfileSettingsActions($action)
638 $user = common_current_user();
640 if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
641 $action->elementStart('li');
642 $action->element('a',
643 array('href' => common_local_url('importdelicious')),
644 _('Import del.icio.us bookmarks'));
645 $action->elementEnd('li');
652 * Output our CSS class for bookmark notice list elements
654 * @param NoticeListItem $nli The item being shown
656 * @return boolean hook value
659 function onStartOpenNoticeListItemElement($nli)
661 $nb = Bookmark::getByNotice($nli->notice);
663 $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
664 $nli->out->elementStart('li', array('class' => 'hentry notice bookmark',
665 'id' => 'notice-' . $id));
666 Event::handle('EndOpenNoticeListItemElement', array($nli));
673 * Save a remote bookmark (from Salmon or PuSH)
675 * @param Ostatus_profile $author Author of the bookmark
676 * @param Activity $activity Activity to save
678 * @return Notice resulting notice.
681 static private function _postRemoteBookmark(Ostatus_profile $author,
684 $bookmark = $activity->objects[0];
686 $options = array('uri' => $bookmark->id,
687 'url' => $bookmark->link,
688 'is_local' => Notice::REMOTE_OMB,
689 'source' => 'ostatus');
691 return self::_postBookmark($author->localProfile(), $activity, $options);
695 * Save a bookmark from an activity
697 * @param Profile $profile Profile to use as author
698 * @param Activity $activity Activity to save
699 * @param array $options Options to pass to bookmark-saving code
701 * @return Notice resulting notice
704 static private function _postBookmark(Profile $profile,
708 $bookmark = $activity->objects[0];
710 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
712 if (count($relLinkEls) < 1) {
713 throw new ClientException(_('Expected exactly 1 link '.
714 'rel=related in a Bookmark.'));
717 if (count($relLinkEls) > 1) {
718 common_log(LOG_WARNING,
719 "Got too many link rel=related in a Bookmark.");
722 $linkEl = $relLinkEls[0];
724 $url = $linkEl->getAttribute('href');
728 foreach ($activity->categories as $category) {
729 $tags[] = common_canonical_tag($category->term);
732 if (!empty($activity->time)) {
733 $options['created'] = common_sql_date($activity->time);
736 // Fill in location if available
738 $location = $activity->context->location;
741 $options['lat'] = $location->lat;
742 $options['lon'] = $location->lon;
743 if ($location->location_id) {
744 $options['location_ns'] = $location->location_ns;
745 $options['location_id'] = $location->location_id;
749 $replies = $activity->context->attention;
751 $options['groups'] = array();
752 $options['replies'] = array();
754 foreach ($replies as $replyURI) {
755 $other = Profile::fromURI($replyURI);
756 if (!empty($other)) {
757 $options['replies'][] = $replyURI;
759 $group = User_group::staticGet('uri', $replyURI);
760 if (!empty($group)) {
761 $options['groups'][] = $replyURI;
766 // Maintain direct reply associations
767 // @fixme what about conversation ID?
769 if (!empty($activity->context->replyToID)) {
770 $orig = Notice::staticGet('uri',
771 $activity->context->replyToID);
773 $options['reply_to'] = $orig->id;
777 return Bookmark::saveNew($profile,
786 * Test if an activity represents posting a bookmark
788 * @param Activity $activity Activity to test
790 * @return true if it's a Post of a Bookmark, else false
793 static private function _isPostBookmark($activity)
795 return ($activity->verb == ActivityVerb::POST &&
796 $activity->objects[0]->type == ActivityObject::BOOKMARK);