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('profile_id',
99 new ColumnDef('title',
102 new ColumnDef('description',
109 new ColumnDef('url_crc32',
114 new ColumnDef('created',
121 $schema->createIndex('bookmark',
124 'bookmark_profile_url_idx');
125 } catch (Exception $e) {
126 common_log(LOG_ERR, $e->getMessage());
133 * When a notice is deleted, delete the related Bookmark
135 * @param Notice $notice Notice being deleted
137 * @return boolean hook value
140 function onNoticeDeleteRelated($notice)
142 $nb = Bookmark::getByNotice($notice);
152 * Show the CSS necessary for this plugin
154 * @param Action $action the action being run
156 * @return boolean hook value
159 function onEndShowStyles($action)
161 $action->cssLink('plugins/Bookmark/bookmark.css');
166 * Load related modules when needed
168 * @param string $cls Name of the class to be loaded
170 * @return boolean hook value; true means continue processing, false means stop.
173 function onAutoload($cls)
175 $dir = dirname(__FILE__);
179 case 'ShowbookmarkAction':
180 case 'NewbookmarkAction':
181 case 'BookmarkpopupAction':
182 case 'NoticebyurlAction':
183 case 'ImportdeliciousAction':
184 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
187 include_once $dir.'/'.$cls.'.php';
190 case 'DeliciousBackupImporter':
191 case 'DeliciousBookmarkImporter':
192 include_once $dir.'/'.strtolower($cls).'.php';
200 * Map URLs to actions
202 * @param Net_URL_Mapper $m path-to-action mapper
204 * @return boolean hook value; true means continue processing, false means stop.
207 function onRouterInitialized($m)
209 $m->connect('main/bookmark/new',
210 array('action' => 'newbookmark'),
211 array('id' => '[0-9]+'));
213 $m->connect('main/bookmark/popup',
214 array('action' => 'bookmarkpopup'));
216 $m->connect('main/bookmark/import',
217 array('action' => 'importdelicious'));
219 $m->connect('bookmark/:user/:created/:crc32',
220 array('action' => 'showbookmark'),
221 array('user' => '[0-9]+',
222 'created' => '[0-9]{14}',
223 'crc32' => '[0-9a-f]{8}'));
225 $m->connect('notice/by-url/:id',
226 array('action' => 'noticebyurl'),
227 array('id' => '[0-9]+'));
233 * Output the HTML for a bookmark in a list
235 * @param NoticeListItem $nli The list item being shown.
237 * @return boolean hook value
240 function onStartShowNoticeItem($nli)
242 $nb = Bookmark::getByNotice($nli->notice);
247 $notice = $nli->notice;
248 $profile = $nli->profile;
250 $atts = $notice->attachments();
252 if (count($atts) < 1) {
253 // Something wrong; let default code deal with it.
259 // XXX: only show the bookmark URL for non-single-page stuff
261 if ($out instanceof ShowbookmarkAction) {
263 $out->elementStart('h3');
265 array('href' => $att->url),
267 $out->elementEnd('h3');
269 $countUrl = common_local_url('noticebyurl',
270 array('id' => $att->id));
272 $out->element('a', array('class' => 'bookmark_notice_count',
273 'href' => $countUrl),
274 $att->noticeCount());
277 $out->elementStart('ul', array('class' => 'bookmark_tags'));
279 // Replies look like "for:" tags
281 $replies = $nli->notice->getReplies();
283 if (!empty($replies)) {
284 foreach ($replies as $reply) {
285 $other = Profile::staticGet('id', $reply);
286 $out->elementStart('li');
287 $out->element('a', array('rel' => 'tag',
288 'href' => $other->profileurl,
289 'title' => $other->getBestName()),
290 sprintf('for:%s', $other->nickname));
291 $out->elementEnd('li');
296 $tags = $nli->notice->getTags();
298 foreach ($tags as $tag) {
299 $out->elementStart('li');
301 array('rel' => 'tag',
302 'href' => Notice_tag::url($tag)),
304 $out->elementEnd('li');
308 $out->elementEnd('ul');
311 array('class' => 'bookmark_description'),
314 if (common_config('attachments', 'show_thumbs')) {
315 $al = new InlineAttachmentList($notice, $out);
319 $out->elementStart('p', array('style' => 'float: left'));
321 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
323 $out->element('img', array('src' => ($avatar) ?
324 $avatar->displayUrl() :
325 Avatar::defaultImage(AVATAR_MINI_SIZE),
326 'class' => 'avatar photo bookmark_avatar',
327 'width' => AVATAR_MINI_SIZE,
328 'height' => AVATAR_MINI_SIZE,
329 'alt' => $profile->getBestName()));
331 $out->element('a', array('href' => $profile->profileurl,
332 'title' => $profile->getBestName()),
335 $nli->showNoticeLink();
336 $nli->showNoticeSource();
337 $nli->showNoticeLocation();
341 $out->elementEnd('p');
343 $nli->showNoticeOptions();
351 * Render a notice as a Bookmark object
353 * @param Notice $notice Notice to render
354 * @param ActivityObject &$object Empty object to fill
356 * @return boolean hook value
359 function onStartActivityObjectFromNotice($notice, &$object)
362 "Checking {$notice->uri} to see if it's a bookmark.");
364 $nb = Bookmark::getByNotice($notice);
369 "Formatting notice {$notice->uri} as a bookmark.");
371 $object->id = $notice->uri;
372 $object->type = ActivityObject::BOOKMARK;
373 $object->title = $nb->title;
374 $object->summary = $nb->description;
375 $object->link = $notice->bestUrl();
377 // Attributes of the URL
379 $attachments = $notice->attachments();
381 if (count($attachments) != 1) {
382 throw new ServerException(_('Bookmark notice with the '.
383 'wrong number of attachments.'));
386 $target = $attachments[0];
388 $attrs = array('rel' => 'related',
389 'href' => $target->url);
391 if (!empty($target->title)) {
392 $attrs['title'] = $target->title;
395 $object->extra[] = array('link', $attrs, null);
397 // Attributes of the thumbnail, if any
399 $thumbnail = $target->getThumbnail();
401 if (!empty($thumbnail)) {
402 $tattrs = array('rel' => 'preview',
403 'href' => $thumbnail->url);
405 if (!empty($thumbnail->width)) {
406 $tattrs['media:width'] = $thumbnail->width;
409 if (!empty($thumbnail->height)) {
410 $tattrs['media:height'] = $thumbnail->height;
413 $object->extra[] = array('link', $attrs, null);
423 * Add our two queue handlers to the queue manager
425 * @param QueueManager $qm current queue manager
427 * @return boolean hook value
430 function onEndInitializeQueueManager($qm)
432 $qm->connect('dlcsback', 'DeliciousBackupImporter');
433 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
438 * Plugin version data
440 * @param array &$versions array of version data
445 function onPluginVersion(&$versions)
447 $versions[] = array('name' => 'Sample',
448 'version' => self::VERSION,
449 'author' => 'Evan Prodromou',
450 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
452 _m('Simple extension for supporting bookmarks.'));
457 * Load our document if requested
459 * @param string &$title Title to fetch
460 * @param string &$output HTML to output
462 * @return boolean hook value
465 function onStartLoadDoc(&$title, &$output)
467 if ($title == 'bookmarklet') {
468 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
470 $c = file_get_contents($filename);
471 $output = common_markup_to_html($c);
472 return false; // success!
479 * Handle a posted bookmark from PuSH
481 * @param Activity $activity activity to handle
482 * @param Ostatus_profile $oprofile Profile for the feed
484 * @return boolean hook value
487 function onStartHandleFeedEntryWithProfile($activity, $oprofile)
489 common_log(LOG_INFO, "BookmarkPlugin called for new feed entry.");
491 if (self::_isPostBookmark($activity)) {
494 "Importing activity {$activity->id} as a bookmark.");
496 $author = $oprofile->checkAuthorship($activity);
498 if (empty($author)) {
499 throw new ClientException(_('Can\'t get author for activity.'));
502 self::_postRemoteBookmark($author,
512 * Handle a posted bookmark from Salmon
514 * @param Activity $activity activity to handle
515 * @param mixed $target user or group targeted
517 * @return boolean hook value
520 function onStartHandleSalmonTarget($activity, $target)
522 if (self::_isPostBookmark($activity)) {
524 $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
526 if ($target instanceof User_group) {
527 $uri = $target->getUri();
528 if (!in_array($uri, $activity->context->attention)) {
529 throw new ClientException(_("Bookmark not posted ".
532 } else if ($target instanceof User) {
535 if (!empty($activity->context->replyToID)) {
536 $original = Notice::staticGet('uri',
537 $activity->context->replyToID);
539 if (!in_array($uri, $activity->context->attention) &&
541 $original->profile_id != $target->id)) {
542 throw new ClientException(_("Bookmark not posted ".
546 throw new ServerException(_("Don't know how to handle ".
547 "this kind of target."));
550 $author = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
552 self::_postRemoteBookmark($author,
562 * Handle bookmark posted via AtomPub
564 * @param Activity &$activity Activity that was posted
565 * @param User $user User that posted it
566 * @param Notice &$notice Resulting notice
568 * @return boolean hook value
571 function onStartAtomPubNewActivity(&$activity, $user, &$notice)
573 if (self::_isPostBookmark($activity)) {
574 $options = array('source' => 'atompub');
575 $notice = self::_postBookmark($user->getProfile(),
585 * Handle bookmark imported from a backup file
587 * @param User $user User to import for
588 * @param ActivityObject $author Original author per import file
589 * @param Activity $activity Activity to import
590 * @param boolean $trusted Is this a trusted user?
591 * @param boolean &$done Is this done (success or unrecoverable error)
593 * @return boolean hook value
596 function onStartImportActivity($user, $author, $activity, $trusted, &$done)
598 if (self::_isPostBookmark($activity)) {
600 $bookmark = $activity->objects[0];
603 'Importing Bookmark ' . $bookmark->id .
604 ' for user ' . $user->nickname);
606 $options = array('uri' => $bookmark->id,
607 'url' => $bookmark->link,
608 'source' => 'restore');
610 $saved = self::_postBookmark($user->getProfile(), $activity, $options);
612 if (!empty($saved)) {
623 * Show a link to our delicious import page on profile settings form
625 * @param Action $action Profile settings action being shown
627 * @return boolean hook value
630 function onEndProfileSettingsActions($action)
632 $user = common_current_user();
634 if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
635 $action->elementStart('li');
636 $action->element('a',
637 array('href' => common_local_url('importdelicious')),
638 _('Import del.icio.us bookmarks'));
639 $action->elementEnd('li');
646 * Save a remote bookmark (from Salmon or PuSH)
648 * @param Ostatus_profile $author Author of the bookmark
649 * @param Activity $activity Activity to save
651 * @return Notice resulting notice.
654 static private function _postRemoteBookmark(Ostatus_profile $author,
657 $bookmark = $activity->objects[0];
659 $options = array('uri' => $bookmark->id,
660 'url' => $bookmark->link,
661 'is_local' => Notice::REMOTE_OMB,
662 'source' => 'ostatus');
664 return self::_postBookmark($author->localProfile(), $activity, $options);
668 * Save a bookmark from an activity
670 * @param Profile $profile Profile to use as author
671 * @param Activity $activity Activity to save
672 * @param array $options Options to pass to bookmark-saving code
674 * @return Notice resulting notice
677 static private function _postBookmark(Profile $profile,
681 $bookmark = $activity->objects[0];
683 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
685 if (count($relLinkEls) < 1) {
686 throw new ClientException(_('Expected exactly 1 link '.
687 'rel=related in a Bookmark.'));
690 if (count($relLinkEls) > 1) {
691 common_log(LOG_WARNING,
692 "Got too many link rel=related in a Bookmark.");
695 $linkEl = $relLinkEls[0];
697 $url = $linkEl->getAttribute('href');
701 foreach ($activity->categories as $category) {
702 $tags[] = common_canonical_tag($category->term);
705 if (!empty($activity->time)) {
706 $options['created'] = common_sql_date($activity->time);
709 // Fill in location if available
711 $location = $activity->context->location;
714 $options['lat'] = $location->lat;
715 $options['lon'] = $location->lon;
716 if ($location->location_id) {
717 $options['location_ns'] = $location->location_ns;
718 $options['location_id'] = $location->location_id;
722 $replies = $activity->context->attention;
724 $options['groups'] = array();
725 $options['replies'] = array();
727 foreach ($replies as $replyURI) {
728 $other = Profile::fromURI($replyURI);
729 if (!empty($other)) {
730 $options['replies'][] = $replyURI;
732 $group = User_group::staticGet('uri', $replyURI);
733 if (!empty($group)) {
734 $options['groups'][] = $replyURI;
739 // Maintain direct reply associations
740 // @fixme what about conversation ID?
742 if (!empty($activity->context->replyToID)) {
743 $orig = Notice::staticGet('uri',
744 $activity->context->replyToID);
746 $options['reply_to'] = $orig->id;
750 return Bookmark::saveNew($profile,
759 * Test if an activity represents posting a bookmark
761 * @param Activity $activity Activity to test
763 * @return true if it's a Post of a Bookmark, else false
766 static private function _isPostBookmark($activity)
768 return ($activity->verb == ActivityVerb::POST &&
769 $activity->objects[0]->type == ActivityObject::BOOKMARK);