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';
163 case 'InitialBookmarkForm':
164 case 'DeliciousBackupImporter':
165 case 'DeliciousBookmarkImporter':
166 include_once $dir.'/'.strtolower($cls).'.php';
174 * Map URLs to actions
176 * @param Net_URL_Mapper $m path-to-action mapper
178 * @return boolean hook value; true means continue processing, false means stop.
180 function onRouterInitialized($m)
182 $m->connect('main/bookmark/new',
183 array('action' => 'newbookmark'),
184 array('id' => '[0-9]+'));
186 $m->connect('main/bookmark/popup',
187 array('action' => 'bookmarkpopup'));
189 $m->connect('main/bookmark/import',
190 array('action' => 'importdelicious'));
192 $m->connect('main/bookmark/forurl',
193 array('action' => 'bookmarkforurl'));
195 $m->connect('bookmark/:id',
196 array('action' => 'showbookmark'),
197 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
199 $m->connect('notice/by-url/:id',
200 array('action' => 'noticebyurl'),
201 array('id' => '[0-9]+'));
208 * Add our two queue handlers to the queue manager
210 * @param QueueManager $qm current queue manager
212 * @return boolean hook value
214 function onEndInitializeQueueManager($qm)
216 $qm->connect('dlcsback', 'DeliciousBackupImporter');
217 $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
222 * Plugin version data
224 * @param array &$versions array of version data
228 function onPluginVersion(&$versions)
230 $versions[] = array('name' => 'Bookmark',
231 'version' => self::VERSION,
232 'author' => 'Evan Prodromou',
233 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
235 // TRANS: Plugin description.
236 _m('Simple extension for supporting bookmarks.'));
241 * Load our document if requested
243 * @param string &$title Title to fetch
244 * @param string &$output HTML to output
246 * @return boolean hook value
248 function onStartLoadDoc(&$title, &$output)
250 if ($title == 'bookmarklet') {
251 $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
253 $c = file_get_contents($filename);
254 $output = common_markup_to_html($c);
255 return false; // success!
262 * Show a link to our delicious import page on profile settings form
264 * @param Action $action Profile settings action being shown
266 * @return boolean hook value
268 function onEndProfileSettingsActions($action)
270 $user = common_current_user();
272 if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
273 $action->elementStart('li');
274 $action->element('a',
275 array('href' => common_local_url('importdelicious')),
276 // TRANS: Link text in proile leading to import form.
277 _m('Import del.icio.us bookmarks'));
278 $action->elementEnd('li');
285 * Output our CSS class for bookmark notice list elements
287 * @param NoticeListItem $nli The item being shown
289 * @return boolean hook value
292 function onStartOpenNoticeListItemElement($nli)
294 $nb = Bookmark::getByNotice($nli->notice);
296 $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
297 $class = 'hentry notice bookmark';
298 if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
299 $class .= ' limited-scope';
301 $nli->out->elementStart('li', array('class' => $class,
302 'id' => 'notice-' . $id));
303 Event::handle('EndOpenNoticeListItemElement', array($nli));
310 * Save a remote bookmark (from Salmon or PuSH)
312 * @param Ostatus_profile $author Author of the bookmark
313 * @param Activity $activity Activity to save
315 * @return Notice resulting notice.
317 static private function _postRemoteBookmark(Ostatus_profile $author,
320 $bookmark = $activity->objects[0];
322 $options = array('uri' => $bookmark->id,
323 'url' => $bookmark->link,
324 'is_local' => Notice::REMOTE_OMB,
325 'source' => 'ostatus');
327 return self::_postBookmark($author->localProfile(), $activity, $options);
331 * Test if an activity represents posting a bookmark
333 * @param Activity $activity Activity to test
335 * @return true if it's a Post of a Bookmark, else false
337 static private function _isPostBookmark($activity)
339 return ($activity->verb == ActivityVerb::POST &&
340 $activity->objects[0]->type == ActivityObject::BOOKMARK);
345 return array(ActivityObject::BOOKMARK);
349 * When a notice is deleted, delete the related Bookmark
351 * @param Notice $notice Notice being deleted
353 * @return boolean hook value
355 function deleteRelated($notice)
357 $nb = Bookmark::getByNotice($notice);
367 * Save a bookmark from an activity
369 * @param Activity $activity Activity to save
370 * @param Profile $profile Profile to use as author
371 * @param array $options Options to pass to bookmark-saving code
373 * @return Notice resulting notice
375 function saveNoticeFromActivity($activity, $profile, $options=array())
377 $bookmark = $activity->objects[0];
379 $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
381 if (count($relLinkEls) < 1) {
382 // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
383 throw new ClientException(_m('Expected exactly 1 link '.
384 'rel=related in a Bookmark.'));
387 if (count($relLinkEls) > 1) {
388 common_log(LOG_WARNING,
389 "Got too many link rel=related in a Bookmark.");
392 $linkEl = $relLinkEls[0];
394 $url = $linkEl->getAttribute('href');
398 foreach ($activity->categories as $category) {
399 $tags[] = common_canonical_tag($category->term);
402 if (!empty($activity->time)) {
403 $options['created'] = common_sql_date($activity->time);
406 // Fill in location if available
408 $location = $activity->context->location;
411 $options['lat'] = $location->lat;
412 $options['lon'] = $location->lon;
413 if ($location->location_id) {
414 $options['location_ns'] = $location->location_ns;
415 $options['location_id'] = $location->location_id;
419 $replies = $activity->context->attention;
421 $options['groups'] = array();
422 $options['replies'] = array();
424 foreach ($replies as $replyURI) {
425 $other = Profile::fromURI($replyURI);
426 if (!empty($other)) {
427 $options['replies'][] = $replyURI;
429 $group = User_group::staticGet('uri', $replyURI);
430 if (!empty($group)) {
431 $options['groups'][] = $replyURI;
436 // Maintain direct reply associations
437 // @fixme what about conversation ID?
439 if (!empty($activity->context->replyToID)) {
440 $orig = Notice::staticGet('uri',
441 $activity->context->replyToID);
443 $options['reply_to'] = $orig->id;
447 return Bookmark::saveNew($profile,
455 function activityObjectFromNotice($notice)
457 assert($this->isMyNotice($notice));
460 "Formatting notice {$notice->uri} as a bookmark.");
462 $object = new ActivityObject();
463 $nb = Bookmark::getByNotice($notice);
465 $object->id = $notice->uri;
466 $object->type = ActivityObject::BOOKMARK;
467 $object->title = $nb->title;
468 $object->summary = $nb->description;
469 $object->link = $notice->bestUrl();
471 // Attributes of the URL
473 $attachments = $notice->attachments();
475 if (count($attachments) != 1) {
476 // TRANS: Server exception thrown when a bookmark has multiple attachments.
477 throw new ServerException(_m('Bookmark notice with the '.
478 'wrong number of attachments.'));
481 $target = $attachments[0];
483 $attrs = array('rel' => 'related',
484 'href' => $target->url);
486 if (!empty($target->title)) {
487 $attrs['title'] = $target->title;
490 $object->extra[] = array('link', $attrs, null);
492 // Attributes of the thumbnail, if any
494 $thumbnail = $target->getThumbnail();
496 if (!empty($thumbnail)) {
497 $tattrs = array('rel' => 'preview',
498 'href' => $thumbnail->url);
500 if (!empty($thumbnail->width)) {
501 $tattrs['media:width'] = $thumbnail->width;
504 if (!empty($thumbnail->height)) {
505 $tattrs['media:height'] = $thumbnail->height;
508 $object->extra[] = array('link', $attrs, null);
515 * @fixme WARNING WARNING WARNING this opens a 'div' that is apparently closed by MicroAppPlugin
516 * @fixme that's probably wrong?
518 * @param Notice $notice
519 * @param HTMLOutputter $out
521 function showNotice($notice, $out)
523 $nb = Bookmark::getByNotice($notice);
525 $profile = $notice->getProfile();
527 $atts = $notice->attachments();
529 if (count($atts) < 1) {
530 // Something wrong; let default code deal with it.
531 // TRANS: Exception thrown when a bookmark has no attachments.
532 // TRANS: %1$s is a bookmark ID, %2$s is a notice ID (number).
533 throw new Exception(sprintf(_m('Bookmark %1$s (notice %2$d) has no attachments.'),
540 // XXX: only show the bookmark URL for non-single-page stuff
542 if ($out instanceof ShowbookmarkAction) {
544 $out->elementStart('h3');
546 array('href' => $att->url,
547 'class' => 'bookmark-title entry-title'),
549 $out->elementEnd('h3');
551 $countUrl = common_local_url('noticebyurl',
552 array('id' => $att->id));
554 $out->element('a', array('class' => 'bookmark-notice-count',
555 'href' => $countUrl),
556 $att->noticeCount());
559 // Replies look like "for:" tags
561 $replies = $notice->getReplies();
562 $tags = $notice->getTags();
564 if (!empty($replies) || !empty($tags)) {
566 $out->elementStart('ul', array('class' => 'bookmark-tags'));
568 foreach ($replies as $reply) {
569 $other = Profile::staticGet('id', $reply);
570 if (!empty($other)) {
571 $out->elementStart('li');
572 $out->element('a', array('rel' => 'tag',
573 'href' => $other->profileurl,
574 'title' => $other->getBestName()),
575 sprintf('for:%s', $other->nickname));
576 $out->elementEnd('li');
581 foreach ($tags as $tag) {
582 $out->elementStart('li');
584 array('rel' => 'tag',
585 'href' => Notice_tag::url($tag)),
587 $out->elementEnd('li');
591 $out->elementEnd('ul');
594 if (!empty($nb->description)) {
596 array('class' => 'bookmark-description'),
600 if (common_config('attachments', 'show_thumbs')) {
602 foreach ($atts as $check) {
603 $thumbnail = File_thumbnail::staticGet('file_id', $check->id);
604 if (!empty($thumbnail)) {
610 $al = new InlineAttachmentList($notice, $out);
615 $out->elementStart('div', array('class' => 'bookmark-info entry-content'));
617 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
620 array('src' => ($avatar) ?
621 $avatar->displayUrl() :
622 Avatar::defaultImage(AVATAR_MINI_SIZE),
623 'class' => 'avatar photo bookmark-avatar',
624 'width' => AVATAR_MINI_SIZE,
625 'height' => AVATAR_MINI_SIZE,
626 'alt' => $profile->getBestName()));
628 $out->raw(' '); // avoid for AJAX XML compatibility
630 $out->elementStart('span', 'vcard author'); // hack for belongsOnTimeline; JS needs to be able to find the author
632 array('class' => 'url',
633 'href' => $profile->profileurl,
634 'title' => $profile->getBestName()),
636 $out->elementEnd('span');
639 function entryForm($out)
641 return new InitialBookmarkForm($out);
651 // TRANS: Application title.
652 return _m('TITLE','Bookmark');