code:
<?php
/*
 * GNU Social - a federating social network
 * Copyright (C) 2014, Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * @package     Activity
 * @maintainer  Mikael Nordfeldth <mmn@hethane.se>
 */
class FavoritePlugin extends ActivityVerbHandlerPlugin
{
    const PLUGIN_VERSION = '2.0.0';

    protected $email_notify_fave = 1;

    public function tag()
    {
        return 'favorite';
    }

    public function types()
    {
        return array();
    }

    public function verbs()
    {
        return array(ActivityVerb::FAVORITE, ActivityVerb::LIKE,
                    ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE);
    }

    public function onCheckSchema()
    {
        $schema = Schema::get();
        $schema->ensureTable('fave', Fave::schemaDef());
        return true;
    }

    public function initialize()
    {
        common_config_set('email', 'notify_fave', $this->email_notify_fave);
    }

    public function onStartUpgrade()
    {
        // This is a migration feature that will make sure we move
        // certain User preferences to the Profile_prefs table.
        // Introduced after commit b5fd2a048fc621ea05d756caba17275ab3dd0af4
        // on Sun Jul 13 16:30:37 2014 +0200
        $user = new User();
        $user->whereAdd('emailnotifyfav IS NOT NULL');
        if ($user->find()) {
            printfnq("Detected old User table (emailnotifyfav IS NOT NULL). Moving 'emailnotifyfav' property to Profile_prefs...");
            // First we'll make sure Profile_prefs exists
            $schema = Schema::get();
            $schema->ensureTable('profile_prefs', Profile_prefs::schemaDef());

            // Make sure we have our own tables setup properly
            while ($user->fetch()) {
                $user->setPref('email', 'notify_fave', $user->emailnotifyfav);
                $orig = clone($user);
                $user->emailnotifyfav = 'null';   // flag this preference as migrated
                $user->update($orig);
            }
            printfnq("DONE.\n");
        }
    }

    public function onEndUpgrade()
    {
        printfnq("Ensuring all faves have a URI...");

        $fave = new Fave();
        $fave->whereAdd('uri IS NULL');

        if ($fave->find()) {
            while ($fave->fetch()) {
                try {
                    $fave->decache();
                    $fave->query(sprintf('UPDATE fave '.
                                         'SET uri = "%s", '.
                                         '    modified = "%s" '.
                                         'WHERE user_id = %d '.
                                         'AND notice_id = %d',
                                         Fave::newUri($fave->getActor(), $fave->getTarget(), $fave->modified),
                                         common_sql_date(strtotime($fave->modified)),
                                         $fave->user_id,
                                         $fave->notice_id));
                } catch (Exception $e) {
                    common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
                }
            }
        }

        printfnq("DONE.\n");
    }

    public function onRouterInitialized(URLMapper $m)
    {
        // Web UI actions
        $m->connect('main/favor', array('action' => 'favor'));
        $m->connect('main/disfavor', array('action' => 'disfavor'));

        if (common_config('singleuser', 'enabled')) {
            $nickname = User::singleUserNickname();

            $m->connect('favorites',
                        array('action' => 'showfavorites',
                              'nickname' => $nickname));
            $m->connect('favoritesrss',
                        array('action' => 'favoritesrss',
                              'nickname' => $nickname));
        } else {
            $m->connect('favoritedrss', array('action' => 'favoritedrss'));
            $m->connect('favorited/', array('action' => 'favorited'));
            $m->connect('favorited', array('action' => 'favorited'));

            $m->connect(':nickname/favorites',
                        array('action' => 'showfavorites'),
                        array('nickname' => Nickname::DISPLAY_FMT));
            $m->connect(':nickname/favorites/rss',
                        array('action' => 'favoritesrss'),
                        array('nickname' => Nickname::DISPLAY_FMT));
        }

        // Favorites for API
        $m->connect('api/favorites/create.:format',
                    array('action' => 'ApiFavoriteCreate'),
                    array('format' => '(xml|json)'));
        $m->connect('api/favorites/destroy.:format',
                    array('action' => 'ApiFavoriteDestroy'),
                    array('format' => '(xml|json)'));
        $m->connect('api/favorites/list.:format',
                    array('action' => 'ApiTimelineFavorites'),
                    array('format' => '(xml|json|rss|atom|as)'));
        $m->connect('api/favorites/:id.:format',
                    array('action' => 'ApiTimelineFavorites'),
                    array('id' => Nickname::INPUT_FMT,
                          'format' => '(xml|json|rss|atom|as)'));
        $m->connect('api/favorites.:format',
                    array('action' => 'ApiTimelineFavorites'),
                    array('format' => '(xml|json|rss|atom|as)'));
        $m->connect('api/favorites/create/:id.:format',
                    array('action' => 'ApiFavoriteCreate'),
                    array('id' => '[0-9]+',
                          'format' => '(xml|json)'));
        $m->connect('api/favorites/destroy/:id.:format',
                    array('action' => 'ApiFavoriteDestroy'),
                    array('id' => '[0-9]+',
                          'format' => '(xml|json)'));

        // AtomPub API
        $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
                    array('action' => 'AtomPubShowFavorite'),
                    array('profile' => '[0-9]+',
                          'notice' => '[0-9]+'));

        $m->connect('api/statusnet/app/favorites/:profile.atom',
                    array('action' => 'AtomPubFavoriteFeed'),
                    array('profile' => '[0-9]+'));

        // Required for qvitter API
        $m->connect('api/statuses/favs/:id.:format',
                    array('action' => 'ApiStatusesFavs'),
                    array('id' => '[0-9]+',
                          'format' => '(xml|json)'));
    }

    // FIXME: Set this to abstract public in lib/activityhandlerplugin.php ddwhen all plugins have migrated!
    protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
    {
        assert($this->isMyActivity($act));

        // We must have an objects[0] here because in isMyActivity we require the count to be == 1
        $actobj = $act->objects[0];

        $object = Fave::saveActivityObject($actobj, $stored);

        return $object;
    }

    // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
    //          with the other microapps/activityhandlers as well.
    //          Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
    public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
    {
        if (!$this->isMyNotice($stored)) {
            return true;
        }

        $this->extendActivity($stored, $act, $scoped);
        return false;
    }

    public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
    {
        Fave::extendActivity($stored, $act, $scoped);
    }

    public function activityObjectFromNotice(Notice $notice)
    {
        $fave = Fave::fromStored($notice);
        return $fave->asActivityObject();
    }

    public function deleteRelated(Notice $notice)
    {
        try {
            $fave = Fave::fromStored($notice);
            $fave->delete();
        } catch (NoResultException $e) {
            // Cool, no problem. We wanted to get rid of it anyway.
        }
    }

    // API stuff

    /**
     * Typically just used to fill out Twitter-compatible API status data.
     *
     * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
     */
    public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
    {
        if ($scoped instanceof Profile) {
            $status['favorited'] = Fave::existsForProfile($notice, $scoped);
        } else {
            $status['favorited'] = false;
        }
        return true;
    }

    public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
    {
        $userdata['favourites_count'] = Fave::countByProfile($profile);
    }

    /**
     * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
     */
    public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
    {
        if ($scoped instanceof Profile) {
            $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
        }
        return true;
    }

    public function onNoticeDeleteRelated(Notice $notice)
    {
        parent::onNoticeDeleteRelated($notice);

        // The below algorithm is because we want to delete fave
        // activities on any notice which _has_ faves, and not as
        // in the parent function only ones that _are_ faves.

        $fave = new Fave();
        $fave->notice_id = $notice->id;

        if ($fave->find()) {
            while ($fave->fetch()) {
                $fave->delete();
            }
        }

        $fave->free();
    }

    public function onProfileDeleteRelated(Profile $profile, array &$related)
    {
        $fave = new Fave();
        $fave->user_id = $profile->id;
        $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
        $fave->free();

        Fave::blowCacheForProfileId($profile->id);
        return true;
    }

    public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
    {
        // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
        Fave::fillFaves($notice_ids);

        // DB caching
        if ($scoped instanceof Profile) {
            Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
        }
    }

    /**
     * show the "favorite" form in the notice options element
     * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
     *
     * @return void
     */
    public function onStartShowNoticeOptionItems($nli)
    {
        if (Event::handle('StartShowFaveForm', array($nli))) {
            $scoped = Profile::current();
            if ($scoped instanceof Profile) {
                if (Fave::existsForProfile($nli->notice, $scoped)) {
                    $disfavor = new DisfavorForm($nli->out, $nli->notice);
                    $disfavor->show();
                } else {
                    $favor = new FavorForm($nli->out, $nli->notice);
                    $favor->show();
                }
            }
            Event::handle('EndShowFaveForm', array($nli));
        }
    }

    protected function showNoticeListItem(NoticeListItem $nli)
    {
        // pass
    }
    public function openNoticeListItemElement(NoticeListItem $nli)
    {
        // pass
    }
    public function closeNoticeListItemElement(NoticeListItem $nli)
    {
        // pass
    }

    public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
    {
        $fave = new Fave();
        $fave->user_id = $uas->getUser()->id;

        if (!empty($uas->after)) {
            $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
        }

        if ($fave->find()) {
            while ($fave->fetch()) {
                $objs[] = clone($fave);
            }
        }

        return true;
    }

    public function onEndShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
    {
        if ($nli instanceof ThreadedNoticeListSubItem) {
            // The sub-items are replies to a conversation, thus we use different HTML elements etc.
            $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
        } else {
            $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
        }
        $threadActive = $item->show() || $threadActive;
        return true;
    }

    public function onEndFavorNotice(Profile $actor, Notice $target)
    {
        try {
            $notice_author = $target->getProfile();
            // Don't notify ourselves of our own favorite on our own notice,
            // or if it's a remote user (since we don't know their email addresses etc.)
            if ($notice_author->id == $actor->id || !$notice_author->isLocal()) {
                return true;
            }
            $local_user = $notice_author->getUser();
            mail_notify_fave($local_user, $actor, $target);
        } catch (Exception $e) {
            // Mm'kay, probably not a local user. Let's skip this favor notification.
        }
    }

    /**
     * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
     * using the class FavCommand.
     *
     * @param string  $cmd     Command being run
     * @param string  $arg     Rest of the message (including address)
     * @param User    $user    User sending the message
     * @param Command &$result The resulting command object to be run.
     *
     * @return boolean hook value
     */
    public function onStartInterpretCommand($cmd, $arg, $user, &$result)
    {
        if ($result === false && $cmd == 'fav') {
            if (empty($arg)) {
                $result = null;
            } else {
                list($other, $extra) = CommandInterpreter::split_arg($arg);
                if (!empty($extra)) {
                    $result = null;
                } else {
                    $result = new FavCommand($user, $other);
                }
            }
            return false;
        }
        return true;
    }

    public function onHelpCommandMessages(HelpCommand $help, array &$commands)
    {
        // TRANS: Help message for IM/SMS command "fav <nickname>".
        $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
        // TRANS: Help message for IM/SMS command "fav #<notice_id>".
        $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
    }

    /**
     * Are we allowed to perform a certain command over the API?
     */
    public function onCommandSupportedAPI(Command $cmd, &$supported)
    {
        $supported = $supported || $cmd instanceof FavCommand;
    }

    // Form stuff (settings etc.)

    public function onEndEmailFormData(Action $action, Profile $scoped)
    {
        $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;

        $action->elementStart('li');
        $action->checkbox('email-notify_fave',
                        // TRANS: Checkbox label in e-mail preferences form.
                        _('Send me email when someone adds my notice as a favorite.'),
                        $emailfave);
        $action->elementEnd('li');

        return true;
    }

    public function onStartEmailSaveForm(Action $action, Profile $scoped)
    {
        $emailfave = $action->booleanintstring('email-notify_fave');
        try {
            if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
                // No need to update setting
                return true;
            }
        } catch (NoResultException $e) {
            // Apparently there's no previously stored setting, then continue to save it as it is now.
        }

        $scoped->setPref('email', 'notify_fave', $emailfave);

        return true;
    }

    // Layout stuff

    public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
    {
        $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
                             // TRANS: Menu item in personal group navigation menu.
                             _m('MENU','Favorites'),
                             // @todo i18n FIXME: Need to make this two messages.
                             // TRANS: Menu item title in personal group navigation menu.
                             // TRANS: %s is a username.
                             sprintf(_('%s\'s favorite notices'), $target->getBestName()),
                             $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
                            'nav_timeline_favorites');
    }

    public function onEndPublicGroupNav(Menu $menu)
    {
        if (!common_config('singleuser', 'enabled')) {
            // TRANS: Menu item in search group navigation panel.
            $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
                                 // TRANS: Menu item title in search group navigation panel.
                                 _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
        }
    }

    public function onEndShowSections(Action $action)
    {
        if (!$action->isAction(array('all', 'public'))) {
            return true;
        }

        if (!common_config('performance', 'high')) {
            $section = new PopularNoticeSection($action, $action->getScoped());
            $section->show();
        }
    }

    protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
    {
        return Fave::existsForProfile($target, $scoped)
                // TRANS: Page/dialog box title when a notice is marked as favorite already
                ? _m('TITLE', 'Unmark notice as favorite')
                // TRANS: Page/dialog box title when a notice is not marked as favorite
                : _m('TITLE', 'Mark notice as favorite');
    }

    protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
    {
        if ($action->isPost()) {
            // The below tests are only for presenting to the user. POSTs which inflict
            // duplicate favorite entries are handled with AlreadyFulfilledException.
            return false;
        }

        $exists = Fave::existsForProfile($target, $scoped);
        $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;

        switch (true) {
        case $exists && ActivityUtils::compareVerbs($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
        case !$exists && ActivityUtils::compareVerbs($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
            common_redirect(common_local_url('activityverb',
                                array('id'   => $target->getID(),
                                      'verb' => ActivityUtils::resolveUri($expected_verb, true))));
            break;
        default:
            // No need to redirect as we are on the correct action already.
        }

        return false;
    }

    protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
    {
        switch (true) {
        case ActivityUtils::compareVerbs($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
            Fave::addNew($scoped, $target);
            break;
        case ActivityUtils::compareVerbs($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
            Fave::removeEntry($scoped, $target);
            break;
        default:
            throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
        }
        return false;
    }

    protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
    {
        return Fave::existsForProfile($target, $scoped)
                ? new DisfavorForm($action, $target)
                : new FavorForm($action, $target);
    }

    public function onPluginVersion(array &$versions)
    {
        $versions[] = array('name' => 'Favorite',
                            'version' => self::PLUGIN_VERSION,
                            'author' => 'Mikael Nordfeldth',
                            'homepage' => 'http://gnu.io/',
                            'rawdescription' =>
                            // TRANS: Plugin description.
                            _m('Favorites (likes) using ActivityStreams.'));

        return true;
    }
}

/**
 * Notify a user that one of their notices has been chosen as a 'fave'
 *
 * @param User    $rcpt   The user whose notice was faved
 * @param Profile $sender The user who faved the notice
 * @param Notice  $notice The notice that was faved
 *
 * @return void
 */
function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
{
    if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
        return;
    }

    // This test is actually "if the sender is sandboxed"
    if (!$sender->hasRight(Right::EMAILONFAVE)) {
        return;
    }

    if ($rcpt->hasBlocked($sender)) {
        // If the author has blocked us, don't spam them with a notification.
        return;
    }

    // We need the global mail.php for various mail related functions below.
    require_once INSTALLDIR.'/lib/mail.php';

    $bestname = $sender->getBestName();

    common_switch_locale($rcpt->language);

    // TRANS: Subject for favorite notification e-mail.
    // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
    $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());

    // TRANS: Body for favorite notification e-mail.
    // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
    // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
    // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
    // TRANS: %7$s is the adding user's nickname.
    $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
                      " as one of their favorites.\n\n" .
                      "The URL of your notice is:\n\n" .
                      "%3\$s\n\n" .
                      "The text of your notice is:\n\n" .
                      "%4\$s\n\n" .
                      "You can see the list of %1\$s's favorites here:\n\n" .
                      "%5\$s"),
                    $bestname,
                    common_exact_date($notice->created),
                    common_local_url('shownotice',
                                     array('notice' => $notice->id)),
                    $notice->content,
                    common_local_url('showfavorites',
                                     array('nickname' => $sender->getNickname())),
                    common_config('site', 'name'),
                    $sender->getNickname()) .
            mail_footer_block();

    $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());

    common_switch_locale();
    mail_to_user($rcpt, $subject, $body, $headers);
}


code:
The Favorite plugin adds the ability to mark a notice as a "favorite"
(i.e. "like").

Installation
============
This plugin is enabled by default

Settings
========
none

repo_name: andremichelle/gnu

path: plugins/Favorite/README

license: mit


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Add a notice to a user's list of favorite notices via the API
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  API
 * @package   StatusNet
 * @author    Craig Andrews <candrews@integralblue.com>
 * @author    Evan Prodromou <evan@status.net>
 * @author    Zach Copley <zach@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2009 StatusNet, Inc.
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://gnu.io/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * Favorites the status specified in the ID parameter as the authenticating user.
 * Returns the favorite status when successful.
 *
 * @category API
 * @package  StatusNet
 * @author   Craig Andrews <candrews@integralblue.com>
 * @author   Evan Prodromou <evan@status.net>
 * @author   Zach Copley <zach@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://gnu.io/
 */
class ApiFavoriteCreateAction extends ApiAuthAction
{
    var $notice = null;

    protected $needPost = true;

    protected function prepare(array $args=array())
    {
        parent::prepare($args);

        $this->notice = Notice::getKV($this->arg('id'));
        if (!empty($this->notice->repeat_of)) {
                common_log(LOG_DEBUG, 'Trying to Fave '.$this->notice->id.', repeat of '.$this->notice->repeat_of);
                common_log(LOG_DEBUG, 'Will Fave '.$this->notice->repeat_of.' instead');
                $real_notice_id = $this->notice->repeat_of;
                $this->notice = Notice::getKV($real_notice_id);
        }

        return true;
    }

    protected function handle()
    {
        parent::handle();

        if (!in_array($this->format, array('xml', 'json'))) {
            $this->clientError(
                // TRANS: Client error displayed when coming across a non-supported API method.
                _('API method not found.'),
                404,
                $this->format
            );
        }

        if (empty($this->notice)) {
            $this->clientError(
                // TRANS: Client error displayed when requesting a status with a non-existing ID.
                _('No status found with that ID.'),
                404,
                $this->format
            );
        }

        try {
            $stored = Fave::addNew($this->scoped, $this->notice);
        } catch (AlreadyFulfilledException $e) {
            // Note: Twitter lets you fave things repeatedly via API.
            $this->clientError($e->getMessage(), 403);
        }

        if ($this->format == 'xml') {
            $this->showSingleXmlStatus($this->notice);
        } elseif ($this->format == 'json') {
            $this->show_single_json_status($this->notice);
        }
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Remote a notice from a user's list of favorite notices via the API
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  API
 * @package   StatusNet
 * @author    Craig Andrews <candrews@integralblue.com>
 * @author    Evan Prodromou <evan@status.net>
 * @author    Zach Copley <zach@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Un-favorites the status specified in the ID parameter as the authenticating user.
 * Returns the un-favorited status in the requested format when successful.
 *
 * @category API
 * @package  StatusNet
 * @author   Craig Andrews <candrews@integralblue.com>
 * @author   Evan Prodromou <evan@status.net>
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class ApiFavoriteDestroyAction extends ApiAuthAction
{
    var $notice = null;

    /**
     * Take arguments for running
     *
     * @param array $args $_REQUEST args
     *
     * @return boolean success flag
     */
    function prepare(array $args = array())
    {
        parent::prepare($args);

        $this->user   = $this->auth_user;
        $this->notice = Notice::getKV($this->arg('id'));
        if ($this->notice->repeat_of != '' ) {
                common_log(LOG_DEBUG, 'Trying to unFave '.$this->notice->id);
                common_log(LOG_DEBUG, 'Will unFave '.$this->notice->repeat_of.' instead');
                $real_notice_id = $this->notice->repeat_of;
                $this->notice = Notice::getKV($real_notice_id);
        }

        return true;
    }

    /**
     * Handle the request
     *
     * Check the format and show the user info
     *
     * @param array $args $_REQUEST data (unused)
     *
     * @return void
     */
    function handle()
    {
        parent::handle();

        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            $this->clientError(
                // TRANS: Client error. POST is a HTTP command. It should not be translated.
                _('This method requires a POST.'),
                400,
                $this->format
            );
            return;
        }

        if (!in_array($this->format, array('xml', 'json'))) {
            $this->clientError(
                // TRANS: Client error displayed when coming across a non-supported API method.
                _('API method not found.'),
                404,
                $this->format
            );
            return;
        }

        if (empty($this->notice)) {
            $this->clientError(
                // TRANS: Client error displayed when trying to remove a favourite with an invalid ID.
                _('No status found with that ID.'),
                404,
                $this->format
            );
            return;
        }

        $fave            = new Fave();
        $fave->user_id   = $this->user->id;
        $fave->notice_id = $this->notice->id;

        if (!$fave->find(true)) {
            $this->clientError(
                // TRANS: Client error displayed when trying to remove a favourite that was not a favourite.
                _('That status is not a favorite.'),
                403,
                $this->favorite
            );
            return;
        }

        $result = $fave->delete();

        if (!$result) {
            common_log_db_error($fave, 'DELETE', __FILE__);
            $this->clientError(
                // TRANS: Client error displayed when removing a favourite has failed.
                _('Could not delete favorite.'),
                404,
                $this->format
            );
            return;
        }

        Fave::blowCacheForProfileId($this->user->id);

        if ($this->format == 'xml') {
            $this->showSingleXmlStatus($this->notice);
        } elseif ($this->format == 'json') {
            $this->show_single_json_status($this->notice);
        }
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Show up to 100 favs of a notice
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  API
 * @package   GNUsocial
 * @author    Hannes Mannerheim <h@nnesmannerhe.im>
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://www.gnu.org/software/social/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * Show up to 100 favs of a notice
 *
 */
class ApiStatusesFavsAction extends ApiAuthAction
{
    const MAXCOUNT = 100;

    var $original = null;   // Notice object for which to retrieve favs
    var $cnt      = self::MAXCOUNT;

    /**
     * Take arguments for running
     *
     * @param array $args $_REQUEST args
     *
     * @return boolean success flag
     */
    protected function prepare(array $args=array())
    {
        parent::prepare($args);

        if ($this->format !== 'json') {
            $this->clientError('This method currently only serves JSON.', 415);
        }

        $id = $this->trimmed('id');

        $this->original = Notice::getKV('id', $id);

        if (!($this->original instanceof Notice)) {
            // TRANS: Client error displayed trying to display redents of a non-exiting notice.
            $this->clientError(_('No such notice.'), 400);
        }

        $cnt = $this->trimmed('count');

        if (empty($cnt) || !is_integer($cnt)) {
            $cnt = 100;
        } else {
            $this->cnt = min((int)$cnt, self::MAXCOUNT);
        }

        return true;
    }

    /**
     * Handle the request
     *
     * Get favs and return them as json object
     *
     * @param array $args $_REQUEST data (unused)
     *
     * @return void
     */
    protected function handle()
    {
        parent::handle();

        $fave = new Fave();
        $fave->selectAdd();
        $fave->selectAdd('user_id');
        $fave->notice_id = $this->original->id;
        $fave->orderBy('modified');
        if (!is_null($this->cnt)) {
            $fave->limit(0, $this->cnt);
        }

		$ids = $fave->fetchAll('user_id');

		// get nickname and profile image
		$ids_with_profile_data = array();
		$i=0;
		foreach($ids as $id) {
			$profile = Profile::getKV('id', $id);
			$ids_with_profile_data[$i]['user_id'] = $id;
			$ids_with_profile_data[$i]['nickname'] = $profile->nickname;
			$ids_with_profile_data[$i]['fullname'] = $profile->fullname;
			$ids_with_profile_data[$i]['profileurl'] = $profile->profileurl;
			$profile = new Profile();
			$profile->id = $id;
			$avatarurl = $profile->avatarUrl(24);
			$ids_with_profile_data[$i]['avatarurl'] = $avatarurl;
			$i++;
		}

		$this->initDocument('json');
		$this->showJsonObjects($ids_with_profile_data);
		$this->endDocument('json');
    }

    /**
     * Return true if read only.
     *
     * MAY override
     *
     * @param array $args other arguments
     *
     * @return boolean is read only action?
     */

    function isReadOnly($args)
    {
        return true;
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Show a user's favorite notices
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  API
 * @package   StatusNet
 * @author    Craig Andrews <candrews@integralblue.com>
 * @author    Evan Prodromou <evan@status.net>
 * @author    Zach Copley <zach@status.net>
 * @copyright 2009-2010 StatusNet, Inc.
 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Returns the 20 most recent favorite notices for the authenticating user or user
 * specified by the ID parameter in the requested format.
 *
 * @category API
 * @package  StatusNet
 * @author   Craig Andrews <candrews@integralblue.com>
 * @author   Evan Prodromou <evan@status.net>
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class ApiTimelineFavoritesAction extends ApiBareAuthAction
{
    var $notices  = null;

    /**
     * Take arguments for running
     *
     * @param array $args $_REQUEST args
     *
     * @return boolean success flag
     */
    protected function prepare(array $args=array())
    {
        parent::prepare($args);

        $this->target = $this->getTargetProfile($this->arg('id'));

        if (!($this->target instanceof Profile)) {
            // TRANS: Client error displayed when requesting most recent favourite notices by a user for a non-existing user.
            $this->clientError(_('No such user.'), 404);
        }

        $this->notices = $this->getNotices();

        return true;
    }

    /**
     * Handle the request
     *
     * Just show the notices
     *
     * @return void
     */
    protected function handle()
    {
        parent::handle();
        $this->showTimeline();
    }

    /**
     * Show the timeline of notices
     *
     * @return void
     */
    function showTimeline()
    {
        $sitename = common_config('site', 'name');
        $title    = sprintf(
            // TRANS: Title for timeline of most recent favourite notices by a user.
            // TRANS: %1$s is the StatusNet sitename, %2$s is a user nickname.
            _('%1$s / Favorites from %2$s'),
            $sitename,
            $this->target->nickname
        );

        $taguribase = TagURI::base();
        $id         = "tag:$taguribase:Favorites:" . $this->target->id;

        $subtitle = sprintf(
            // TRANS: Subtitle for timeline of most recent favourite notices by a user.
            // TRANS: %1$s is the StatusNet sitename, %2$s is a user's full name,
            // TRANS: %3$s is a user nickname.
            _('%1$s updates favorited by %2$s / %3$s.'),
            $sitename,
            $this->target->getBestName(),
            $this->target->nickname
        );

        $logo = $this->target->avatarUrl(AVATAR_PROFILE_SIZE);
        $link = common_local_url('showfavorites',
                    array('nickname' => $this->target->nickname));
        $self = $this->getSelfUri();

        switch($this->format) {
        case 'xml':
            $this->showXmlTimeline($this->notices);
            break;
        case 'rss':
            $this->showRssTimeline(
                $this->notices,
                $title,
                $link,
                $subtitle,
                null,
                $logo,
                $self
            );
            break;
        case 'atom':
            header('Content-Type: application/atom+xml; charset=utf-8');

            $atom = new AtomNoticeFeed($this->auth_user);

            $atom->setId($id);
            $atom->setTitle($title);
            $atom->setSubtitle($subtitle);
            $atom->setLogo($logo);
            $atom->setUpdated('now');

            $atom->addLink($link);
            $atom->setSelfLink($self);

            $atom->addEntryFromNotices($this->notices);

            $this->raw($atom->getString());
            break;
        case 'json':
            $this->showJsonTimeline($this->notices);
            break;
        case 'as':
            header('Content-Type: ' . ActivityStreamJSONDocument::CONTENT_TYPE);
            $doc = new ActivityStreamJSONDocument($this->auth_user);
            $doc->setTitle($title);
            $doc->addLink($link,'alternate', 'text/html');
            $doc->addItemsFromNotices($this->notices);
            $this->raw($doc->asString());
            break;
        default:
            // TRANS: Client error displayed when coming across a non-supported API method.
            $this->clientError(_('API method not found.'), 404);
        }
    }

    /**
     * Get notices
     *
     * @return array notices
     */
    function getNotices()
    {
        $notices = array();

        common_debug("since id = " . $this->since_id . " max id = " . $this->max_id);

        $notice = Fave::stream($this->target->id,
                               ($this->page-1) * $this->count,  // offset
                               $this->count,                    // limit
                               (!empty($this->auth_user) && $this->auth_user->id == $this->target->id),   // own feed?
                               $this->since_id,
                               $this->max_id
                              );

        while ($notice->fetch()) {
            $notices[] = clone($notice);
        }

        return $notices;
    }

    /**
     * Is this action read only?
     *
     * @param array $args other arguments
     *
     * @return boolean true
     */
    function isReadOnly($args)
    {
        return true;
    }

    /**
     * When was this feed last modified?
     *
     * @return string datestamp of the latest notice in the stream
     */
    function lastModified()
    {
        if (!empty($this->notices) && (count($this->notices) > 0)) {
            return strtotime($this->notices[0]->created);
        }

        return null;
    }

    /**
     * An entity tag for this stream
     *
     * Returns an Etag based on the action name, language, user ID, and
     * timestamps of the first and last notice in the timeline
     *
     * @return string etag
     */
    function etag()
    {
        if (!empty($this->notices) && (count($this->notices) > 0)) {

            $last = count($this->notices) - 1;

            return '"' . implode(
                ':',
                array($this->arg('action'),
                      common_user_cache_hash($this->auth_user),
                      common_language(),
                      $this->target->id,
                      strtotime($this->notices[0]->created),
                      strtotime($this->notices[$last]->created))
            )
            . '"';
        }

        return null;
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2010, StatusNet, Inc.
 *
 * Feed of ActivityStreams 'favorite' actions
 *
 * PHP version 5
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  AtomPub
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL') && !defined('STATUSNET')) { exit(1); }

/**
 * Feed of ActivityStreams 'favorite' actions
 *
 * @category  AtomPub
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class AtompubfavoritefeedAction extends ApiAuthAction
{
    private $_profile = null;
    private $_faves   = null;

    protected function prepare(array $args=array())
    {
        parent::prepare($args);

        $this->_profile = Profile::getKV('id', $this->trimmed('profile'));

        if (!$this->_profile instanceof Profile) {
            // TRANS: Client exception thrown when requesting a favorite feed for a non-existing profile.
            throw new ClientException(_('No such profile.'), 404);
        }

        $offset = ($this->page-1) * $this->count;
        $limit  = $this->count + 1;

        $this->_faves = Fave::byProfile($this->_profile->id,
                                        $offset,
                                        $limit);

        return true;
    }

    protected function handle()
    {
        parent::handle();

        switch ($_SERVER['REQUEST_METHOD']) {
        case 'HEAD':
        case 'GET':
            $this->showFeed();
            break;
        case 'POST':
            $this->addFavorite();
            break;
        default:
            // TRANS: Client exception thrown when using an unsupported HTTP method.
            throw new ClientException(_('HTTP method not supported.'), 405);
        }

        return true;
    }

    /**
     * Show a feed of favorite activity streams objects
     *
     * @return void
     */
    function showFeed()
    {
        header('Content-Type: application/atom+xml; charset=utf-8');

        $url = common_local_url('AtomPubFavoriteFeed',
                                array('profile' => $this->_profile->id));

        $feed = new Atom10Feed(true);

        $feed->addNamespace('activity',
                            'http://activitystrea.ms/spec/1.0/');

        $feed->addNamespace('poco',
                            'http://portablecontacts.net/spec/1.0');

        $feed->addNamespace('media',
                            'http://purl.org/syndication/atommedia');

        $feed->id = $url;

        $feed->setUpdated('now');

        $feed->addAuthor($this->_profile->getBestName(),
                         $this->_profile->getUri());

        // TRANS: Title for Atom favorites feed.
        // TRANS: %s is a user nickname.
        $feed->setTitle(sprintf(_("%s favorites"),
                                $this->_profile->getBestName()));

        // TRANS: Subtitle for Atom favorites feed.
        // TRANS: %1$s is a user nickname, %2$s is the StatusNet sitename.
        $feed->setSubtitle(sprintf(_('Notices %1$s has favorited on %2$s'),
                                   $this->_profile->getBestName(),
                                   common_config('site', 'name')));

        $feed->addLink(common_local_url('showfavorites',
                                        array('nickname' =>
                                              $this->_profile->nickname)));

        $feed->addLink($url,
                       array('rel' => 'self',
                             'type' => 'application/atom+xml'));

        // If there's more...

        if ($this->page > 1) {
            $feed->addLink($url,
                           array('rel' => 'first',
                                 'type' => 'application/atom+xml'));

            $feed->addLink(common_local_url('AtomPubFavoriteFeed',
                                            array('profile' =>
                                                  $this->_profile->id),
                                            array('page' =>
                                                  $this->page - 1)),
                           array('rel' => 'prev',
                                 'type' => 'application/atom+xml'));
        }

        if ($this->_faves->N > $this->count) {

            $feed->addLink(common_local_url('AtomPubFavoriteFeed',
                                            array('profile' =>
                                                  $this->_profile->id),
                                            array('page' =>
                                                  $this->page + 1)),
                           array('rel' => 'next',
                                 'type' => 'application/atom+xml'));
        }

        $i = 0;

        while ($this->_faves->fetch()) {

            // We get one more than needed; skip that one

            $i++;

            if ($i > $this->count) {
                break;
            }

            $act = $this->_faves->asActivity();
            $feed->addEntryRaw($act->asString(false, false, false));
        }

        $this->raw($feed->getString());
    }

    /**
     * add a new favorite
     *
     * @return void
     */
    function addFavorite()
    {
        // XXX: Refactor this; all the same for atompub

        if (!$this->scoped instanceof Profile ||
            $this->scoped->id != $this->_profile->id) {
            // TRANS: Client exception thrown when trying to set a favorite for another user.
            throw new ClientException(_("Cannot add someone else's subscription."), 403);
        }

        $xml = file_get_contents('php://input');

        $dom = DOMDocument::loadXML($xml);

        if ($dom->documentElement->namespaceURI != Activity::ATOM ||
            $dom->documentElement->localName != 'entry') {
            // TRANS: Client error displayed when not using an Atom entry.
            throw new ClientException(_('Atom post must be an Atom entry.'));
        }

        $activity = new Activity($dom->documentElement);
        $notice = null;

        // Favorite plugin handles these as ActivityHandlerPlugin through Notice->saveActivity
        // which in turn uses "StoreActivityObject" event.
        Event::handle('StartAtomPubNewActivity', array(&$activity, $this->scoped, &$notice));
        assert($notice instanceof Notice);

        $act = $notice->asActivity();

        header('Content-Type: application/atom+xml; charset=utf-8');
        header('Content-Location: ' . $act->selfLink);

        $this->startXML();
        $this->raw($act->asString(true, true, true));
        $this->endXML();
    }

    /**
     * Return true if read only.
     *
     * MAY override
     *
     * @param array $args other arguments
     *
     * @return boolean is read only action?
     */
    function isReadOnly($args)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' ||
            $_SERVER['REQUEST_METHOD'] == 'HEAD') {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Return last modified, if applicable.
     *
     * MAY override
     *
     * @return string last modified http header
     */
    function lastModified()
    {
        // For comparison with If-Last-Modified
        // If not applicable, return null
        return null;
    }

    /**
     * Return etag, if applicable.
     *
     * MAY override
     *
     * @return string etag http header
     */
    function etag()
    {
        return null;
    }

    /**
     * Does this require authentication?
     *
     * @return boolean true if delete, else false
     */
    function requiresAuth()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' ||
            $_SERVER['REQUEST_METHOD'] == 'HEAD') {
            return false;
        } else {
            return true;
        }
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2010, StatusNet, Inc.
 *
 * Show a single favorite in Atom Activity Streams format
 *
 * PHP version 5
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  AtomPub
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    // This check helps protect against security problems;
    // your code file can't be executed directly from the web.
    exit(1);
}

/**
 * Show a single favorite in Atom Activity Streams format.
 *
 * Can also be used to delete a favorite.
 *
 * @category  Action
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class AtompubshowfavoriteAction extends ApiAuthAction
{
    private $_profile = null;
    private $_notice  = null;
    private $_fave    = null;

    /**
     * For initializing members of the class.
     *
     * @param array $args misc. arguments
     *
     * @return boolean true
     */
    protected function prepare(array $args=array())
    {
        parent::prepare($args);

        $profileId = $this->trimmed('profile');
        $noticeId  = $this->trimmed('notice');

        $this->_profile = Profile::getKV('id', $profileId);

        if (empty($this->_profile)) {
            // TRANS: Client exception.
            throw new ClientException(_('No such profile.'), 404);
        }

        $this->_notice = Notice::getKV('id', $noticeId);

        if (empty($this->_notice)) {
            // TRANS: Client exception thrown when referencing a non-existing notice.
            throw new ClientException(_('No such notice.'), 404);
        }

        $this->_fave = Fave::pkeyGet(array('user_id' => $profileId,
                                           'notice_id' => $noticeId));

        if (empty($this->_fave)) {
            // TRANS: Client exception thrown when referencing a non-existing favorite.
            throw new ClientException(_('No such favorite.'), 404);
        }

        return true;
    }

    /**
     * Handler method
     *
     * @return void
     */
    protected function handle()
    {
        parent::handle();

        switch ($_SERVER['REQUEST_METHOD']) {
        case 'GET':
        case 'HEAD':
            $this->showFave();
            break;
        case 'DELETE':
            $this->deleteFave();
            break;
        default:
            // TRANS: Client exception thrown using an unsupported HTTP method.
            throw new ClientException(_('HTTP method not supported.'), 405);
        }
        return true;
    }

    /**
     * Show a single favorite, in ActivityStreams format
     *
     * @return void
     */
    function showFave()
    {
        $activity = $this->_fave->asActivity();

        header('Content-Type: application/atom+xml; charset=utf-8');

        $this->startXML();
        $this->raw($activity->asString(true, true, true));
        $this->endXML();

        return;
    }

    /**
     * Delete the favorite
     *
     * @return void
     */
    function deleteFave()
    {
        if (empty($this->auth_user) ||
            $this->auth_user->id != $this->_profile->id) {
            // TRANS: Client exception thrown when trying to remove a favorite notice of another user.
            throw new ClientException(_("Cannot delete someone else's".
                                        " favorite."), 403);
        }

        $this->_fave->delete();

        return;
    }

    /**
     * Return true if read only.
     *
     * MAY override
     *
     * @param array $args other arguments
     *
     * @return boolean is read only action?
     */
    function isReadOnly($args)
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' ||
            $_SERVER['REQUEST_METHOD'] == 'HEAD') {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Return last modified, if applicable.
     *
     * MAY override
     *
     * @return string last modified http header
     */
    function lastModified()
    {
        return max(strtotime($this->_profile->modified),
                   strtotime($this->_notice->modified),
                   strtotime($this->_fave->modified));
    }

    /**
     * Return etag, if applicable.
     *
     * MAY override
     *
     * @return string etag http header
     */
    function etag()
    {
        $mtime = strtotime($this->_fave->modified);

        return 'W/"' . implode(':', array('AtomPubShowFavorite',
                                          $this->_profile->id,
                                          $this->_notice->id,
                                          $mtime)) . '"';
    }

    /**
     * Does this require authentication?
     *
     * @return boolean true if delete, else false
     */
    function requiresAuth()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' ||
            $_SERVER['REQUEST_METHOD'] == 'HEAD') {
            return false;
        } else {
            return true;
        }
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * List of popular notices
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Public
 * @package   StatusNet
 * @author    Zach Copley <zach@status.net>
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2008-2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * List of popular notices
 *
 * We provide a list of the most popular notices. Popularity
 * is measured by
 *
 * @category Personal
 * @package  StatusNet
 * @author   Zach Copley <zach@status.net>
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class FavoritedAction extends Action
{
    var $page = null;

    /**
     * Title of the page
     *
     * @return string Title of the page
     */

    function title()
    {
        if ($this->page == 1) {
            // TRANS: Page title for first page of favorited notices.
            return _('Popular notices');
        } else {
            // TRANS: Page title for all but first page of favorited notices.
            // TRANS: %d is the page number being displayed.
            return sprintf(_('Popular notices, page %d'), $this->page);
        }
    }

    /**
     * Instructions for use
     *
     * @return instructions for use
     */
    function getInstructions()
    {
        // TRANS: Description on page displaying favorited notices.
        return _('The most popular notices on the site right now.');
    }

    /**
     * Is this page read-only?
     *
     * @return boolean true
     */
    function isReadOnly($args)
    {
        return true;
    }

    /**
     * Take arguments for running
     *
     * @param array $args $_REQUEST args
     *
     * @return boolean success flag
     *
     * @todo move queries from showContent() to here
     */
    function prepare(array $args = array())
    {
        parent::prepare($args);
        $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;

        common_set_returnto($this->selfUrl());

        return true;
    }

    /**
     * Handle request
     *
     * Shows a page with list of favorite notices
     *
     * @param array $args $_REQUEST args; handled in prepare()
     *
     * @return void
     */
    function handle()
    {
        parent::handle();

        $this->showPage();
    }

    /**
     * Show the page notice
     *
     * Shows instructions for the page
     *
     * @return void
     */
    function showPageNotice()
    {
        $instr  = $this->getInstructions();
        $output = common_markup_to_html($instr);

        $this->elementStart('div', 'instructions');
        $this->raw($output);
        $this->elementEnd('div');
    }

    function showEmptyList()
    {
        // TRANS: Text displayed instead of a list when a site does not yet have any favourited notices.
        $message = _('Favorite notices appear on this page but no one has favorited one yet.') . ' ';

        if (common_logged_in()) {
            // TRANS: Additional text displayed instead of a list when a site does not yet have any favourited notices for logged in users.
            $message .= _('Be the first to add a notice to your favorites by clicking the fave button next to any notice you like.');
        }
        else {
            // TRANS: Additional text displayed instead of a list when a site does not yet have any favourited notices for not logged in users.
            // TRANS: %%action.register%% is a registration link. "[link text](link)" is Mark Down. Do not change the formatting.
            $message .= _('Why not [register an account](%%action.register%%) and be the first to add a notice to your favorites!');
        }

        $this->elementStart('div', 'guide');
        $this->raw(common_markup_to_html($message));
        $this->elementEnd('div');
    }

    /**
     * Content area
     *
     * Shows the list of popular notices
     *
     * @return void
     */
    function showContent()
    {
        $stream = new PopularNoticeStream($this->scoped);
        $notice = $stream->getNotices(($this->page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE+1);

        $nl = new NoticeList($notice, $this);

        $cnt = $nl->show();

        if ($cnt == 0) {
            $this->showEmptyList();
        }

        $this->pagination($this->page > 1, $cnt > NOTICES_PER_PAGE,
                          $this->page, 'favorited');
    }
}


code:
<?php
/**
 * RSS feed for user favorites action class.
 *
 * PHP version 5
 *
 * @category Action
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * RSS feed for user favorites action class.
 *
 * Formatting of RSS handled by Rss10Action
 *
 * @category Action
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 */
class FavoritesrssAction extends TargetedRss10Action
{
    protected function getNotices()
    {
        // is this our own stream?
        $own = $this->scoped instanceof Profile ? $this->target->getID() === $this->scoped->getID() : false;

        $stream = Fave::stream($this->target->getID(), 0, $this->limit, $own);
        return $stream->fetchAll();
    }

     /**
     * Get channel.
     *
     * @return array associative array on channel information
     */
    function getChannel()
    {
        $user = $this->user;
        $c    = array('url' => common_local_url('favoritesrss',
                                        array('nickname' =>
                                        $user->nickname)),
                   // TRANS: Title of RSS feed with favourite notices of a user.
                   // TRANS: %s is a user's nickname.
                   'title' => sprintf(_("%s's favorite notices"), $user->nickname),
                   'link' => common_local_url('showfavorites',
                                        array('nickname' =>
                                        $user->nickname)),
                   // TRANS: Desciption of RSS feed with favourite notices of a user.
                   // TRANS: %1$s is a user's nickname, %2$s is the name of the StatusNet site.
                   'description' => sprintf(_('Updates favored by %1$s on %2$s!'),
                                        $user->nickname, common_config('site', 'name')));
        return $c;
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * List of replies
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Personal
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2008-2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * List of replies
 *
 * @category Personal
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class ShowfavoritesAction extends ShowstreamAction
{
    function title()
    {
        if ($this->page == 1) {
            // TRANS: Title for first page of favourite notices of a user.
            // TRANS: %s is the user for whom the favourite notices are displayed.
            return sprintf(_('%s\'s favorite notices'), $this->getTarget()->getNickname());
        } else {
            // TRANS: Title for all but the first page of favourite notices of a user.
            // TRANS: %1$s is the user for whom the favourite notices are displayed, %2$d is the page number.
            return sprintf(_('%1$s\'s favorite notices, page %2$d'),
                           $this->getTarget()->getNickname(),
                           $this->page);
        }
    }

    public function getStream()
    {
        return new FaveNoticeStream($this->getTarget(), $this->scoped);
    }

    function getFeeds()
    {
        return array(new Feed(Feed::JSON,
                              common_local_url('ApiTimelineFavorites',
                                               array(
                                                    'id' => $this->getTarget()->getNickname(),
                                                    'format' => 'as')),
                              // TRANS: Feed link text. %s is a username.
                              sprintf(_('Feed for favorites of %s (Activity Streams JSON)'),
                                      $this->getTarget()->getNickname())),
                     new Feed(Feed::RSS1,
                              common_local_url('favoritesrss',
                                               array('nickname' => $this->getTarget()->getNickname())),
                              // TRANS: Feed link text. %s is a username.
                              sprintf(_('Feed for favorites of %s (RSS 1.0)'),
                                      $this->getTarget()->getNickname())),
                     new Feed(Feed::RSS2,
                              common_local_url('ApiTimelineFavorites',
                                               array(
                                                    'id' => $this->getTarget()->getNickname(),
                                                    'format' => 'rss')),
                              // TRANS: Feed link text. %s is a username.
                              sprintf(_('Feed for favorites of %s (RSS 2.0)'),
                                      $this->getTarget()->getNickname())),
                     new Feed(Feed::ATOM,
                              common_local_url('ApiTimelineFavorites',
                                               array(
                                                    'id' => $this->getTarget()->getNickname(),
                                                    'format' => 'atom')),
                              // TRANS: Feed link text. %s is a username.
                              sprintf(_('Feed for favorites of %s (Atom)'),
                                      $this->getTarget()->getNickname())));
    }

    function showEmptyListMessage()
    {
        if (common_logged_in()) {
            if ($this->getTarget()->sameAs($this->getScoped())) {
                // TRANS: Text displayed instead of favourite notices for the current logged in user that has no favourites.
                $message = _('You haven\'t chosen any favorite notices yet. Click the fave button on notices you like to bookmark them for later or shed a spotlight on them.');
            } else {
                // TRANS: Text displayed instead of favourite notices for a user that has no favourites while logged in.
                // TRANS: %s is a username.
                $message = sprintf(_('%s hasn\'t added any favorite notices yet. Post something interesting they would add to their favorites :)'), $this->getTarget()->getNickname());
            }
        }
        else {
                // TRANS: Text displayed instead of favourite notices for a user that has no favourites while not logged in.
                // TRANS: %s is a username, %%%%action.register%%%% is a link to the user registration page.
                // TRANS: (link text)[link] is a Mark Down link.
            $message = sprintf(_('%s hasn\'t added any favorite notices yet. Why not [register an account](%%%%action.register%%%%) and then post something interesting they would add to their favorites :)'), $this->getTarget()->getNickname());
        }

        $this->elementStart('div', 'guide');
        $this->raw(common_markup_to_html($message));
        $this->elementEnd('div');
    }

    /**
     * Show the content
     *
     * A list of notices that this user has marked as a favorite
     *
     * @return void
     */
    function showNotices()
    {
        $nl = new FavoritesNoticeList($this->notice, $this);

        $cnt = $nl->show();
        if (0 == $cnt) {
            $this->showEmptyListMessage();
        }

        $this->pagination($this->page > 1, $cnt > NOTICES_PER_PAGE,
                          $this->page, 'showfavorites',
                          array('nickname' => $this->getTarget()->getNickname()));
    }

    function showPageNotice() {
        // TRANS: Page notice for show favourites page.
        $this->element('p', 'instructions', _('This is a way to share what you like.'));
    }
}

class FavoritesNoticeList extends NoticeList
{
    function newListItem(Notice $notice)
    {
        return new FavoritesNoticeListItem($notice, $this->out);
    }
}

// All handled by superclass
class FavoritesNoticeListItem extends DoFollowListItem
{
}


code:
<?php
/**
 * Table Definition for fave
 */

class Fave extends Managed_DataObject
{
    public $__table = 'fave';                            // table name
    public $notice_id;                       // int(4)  primary_key not_null
    public $user_id;                         // int(4)  primary_key not_null
    public $uri;                             // varchar(191)   not 255 because utf8mb4 takes more space   not 255 because utf8mb4 takes more space
    public $created;                         // datetime  multiple_key not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'notice_id' => array('type' => 'int', 'not null' => true, 'description' => 'notice that is the favorite'),
                'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'user who likes this notice'),
                'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('notice_id', 'user_id'),
            'unique keys' => array(
                'fave_uri_key' => array('uri'),
            ),
            'foreign keys' => array(
                'fave_notice_id_fkey' => array('notice', array('notice_id' => 'id')),
                'fave_user_id_fkey' => array('profile', array('user_id' => 'id')), // note: formerly referenced notice.id, but we can now record remote users' favorites
            ),
            'indexes' => array(
                'fave_notice_id_idx' => array('notice_id'),
                'fave_user_id_idx' => array('user_id', 'modified'),
                'fave_modified_idx' => array('modified'),
            ),
        );
    }

    /**
     * Save a favorite record.
     * @fixme post-author notification should be moved here
     *
     * @param Profile $actor  the local or remote Profile who favorites
     * @param Notice  $target the notice that is favorited
     * @return Fave record on success
     * @throws Exception on failure
     */
    static function addNew(Profile $actor, Notice $target) {
        if (self::existsForProfile($target, $actor)) {
            // TRANS: Client error displayed when trying to mark a notice as favorite that already is a favorite.
            throw new AlreadyFulfilledException(_('You have already favorited this!'));
        }

        $act = new Activity();
        $act->type    = ActivityObject::ACTIVITY;
        $act->verb    = ActivityVerb::FAVORITE;
        $act->time    = time();
        $act->id      = self::newUri($actor, $target, common_sql_date($act->time));
        $act->title   = _("Favor");
        // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
        //        notice's nickname and %3$s is the content of the favorited notice.)
        $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
                                $actor->getNickname(), $target->getProfile()->getNickname(),
                                $target->getRendered());
        $act->actor   = $actor->asActivityObject();
        $act->target  = $target->asActivityObject();
        $act->objects = array(clone($act->target));

        $url = common_local_url('AtomPubShowFavorite', array('profile'=>$actor->id, 'notice'=>$target->id));
        $act->selfLink = $url;
        $act->editLink = $url;

        // saveActivity will in turn also call Fave::saveActivityObject which does
        // what this function used to do before this commit.
        $stored = Notice::saveActivity($act, $actor);

        return $stored;
    }

    static function removeEntry(Profile $actor, Notice $target)
    {
        $fave            = new Fave();
        $fave->user_id   = $actor->getID();
        $fave->notice_id = $target->getID();
        if (!$fave->find(true)) {
            // TRANS: Client error displayed when trying to remove a 'favor' when there is none in the first place.
            throw new AlreadyFulfilledException(_('This is already not favorited.'));
        }

        $result = $fave->delete();
        if ($result === false) {
            common_log_db_error($fave, 'DELETE', __FILE__);
            // TRANS: Server error displayed when removing a favorite from the database fails.
            throw new ServerException(_('Could not delete favorite.'));
        }

        Fave::blowCacheForProfileId($actor->getID());
        Fave::blowCacheForNoticeId($target->getID());
    }

    // exception throwing takeover!
    public function insert()
    {
        if (parent::insert()===false) {
            common_log_db_error($this, 'INSERT', __FILE__);
            throw new ServerException(sprintf(_m('Could not store new object of type %s'), get_called_class()));
        }
        self::blowCacheForProfileId($this->user_id);
        self::blowCacheForNoticeId($this->notice_id);
        return $this;
    }

    public function delete($useWhere=false)
    {
        $result = null;

        try {
            $profile = $this->getActor();
            $notice  = $this->getTarget();

            if (Event::handle('StartDisfavorNotice', array($profile, $notice, &$result))) {

                $result = parent::delete($useWhere);

                if ($result !== false) {
                    Event::handle('EndDisfavorNotice', array($profile, $notice));
                }
            }

        } catch (NoResultException $e) {
            // In case there's some inconsistency where the profile or notice was deleted without losing the fave db entry
            common_log(LOG_INFO, '"'.get_class($e->obj).'" with id=='.var_export($e->obj->id, true).' object not found when deleting favorite, ignoring...');
        } catch (EmptyPkeyValueException $e) {
            // Some buggy instances of GNU social have had favorites with notice id==0 stored in the database
            common_log(LOG_INFO, _ve($e->getMessage()));
        }

        // If we catch an exception above, then $result===null because parent::delete only returns an int>=0 or boolean false
        if (is_null($result)) {
            // Delete it without the event, as something is wrong and we don't want it anyway.
            $result = parent::delete($useWhere);
        }

        // Err, apparently we can reference $this->user_id after parent::delete,
        // I guess it's safe because this is the order it was before!
        self::blowCacheForProfileId($this->user_id);
        self::blowCacheForNoticeId($this->notice_id);
        self::blow('popular');

        return $result;
    }

    // FIXME: Instead of $own, send the scoped Profile so we can pass it along directly to FaveNoticeStream
    // and preferrably we should get a Profile instead of $user_id
    static function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
    {
        $target = Profile::getByID($user_id);
        $stream = new FaveNoticeStream($target, ($own ? $target : null));

        return $stream->getNotices($offset, $limit, $since_id, $max_id);
    }

    // FIXME: Instead of $own, send the scoped Profile so we can pass it along directly to FaveNoticeStream
    // and preferrably we should get a Profile instead of $user_id
    function idStream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
    {
        $target = Profile::getByID($user_id);
        $stream = new FaveNoticeStream($target, ($own ? $target : null));

        return $stream->getNoticeIds($offset, $limit, $since_id, $max_id);
    }

    function asActivity()
    {
        $target = $this->getTarget();
        $actor  = $this->getActor();

        $act = new Activity();

        $act->verb = ActivityVerb::FAVORITE;

        // FIXME: rationalize this with URL below

        $act->id   = $this->getUri();

        $act->time    = strtotime($this->created);
        // TRANS: Activity title when marking a notice as favorite.
        $act->title   = _("Favor");
        // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
        //        notice's nickname and %3$s is the content of the favorited notice.)
        $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
                                $actor->getNickname(), $target->getProfile()->getNickname(),
                                $target->getRendered());
        $act->context = new ActivityContext();
        $act->context->replyToID = $target->getUri();
        try {
            $act->context->replyToURL = $target->getUrl();
        } catch (InvalidUrlException $e) {
            // ok, no replyToURL, i.e. the href="" in <thr:in-reply-to/>
        }

        $act->actor     = $actor->asActivityObject();
        $act->target    = $target->asActivityObject();
        $act->objects   = array(clone($act->target));

        $url = common_local_url('AtomPubShowFavorite',
                                          array('profile' => $actor->id,
                                                'notice'  => $target->id));

        $act->selfLink = $url;
        $act->editLink = $url;

        return $act;
    }

    static function existsForProfile($notice, Profile $scoped)
    {
        $fave = self::pkeyGet(array('user_id'=>$scoped->id, 'notice_id'=>$notice->id));

        return ($fave instanceof Fave);
    }

    /**
     * Fetch a stream of favorites by profile
     *
     * @param integer $profileId Profile that faved
     * @param integer $offset    Offset from last
     * @param integer $limit     Number to get
     *
     * @return mixed stream of faves, use fetch() to iterate
     *
     * @todo Cache results
     * @todo integrate with Fave::stream()
     */

    static function byProfile($profileId, $offset, $limit)
    {
        $fav = new Fave();

        $fav->user_id = $profileId;

        $fav->orderBy('modified DESC');

        $fav->limit($offset, $limit);

        $fav->find();

        return $fav;
    }

    static function countByProfile(Profile $profile)
    {
        $c = Cache::instance();
        if (!empty($c)) {
            $cnt = $c->get(Cache::key('fave:count_by_profile:'.$profile->id));
            if (is_integer($cnt)) {
                return $cnt;
            }
        }

        $faves = new Fave();
        $faves->user_id = $profile->id;
        $cnt = (int) $faves->count('notice_id');

        if (!empty($c)) {
            $c->set(Cache::key('fave:count_by_profile:'.$profile->id), $cnt);
        }

        return $cnt;
    }

    static protected $_faves = array();

    /**
     * All faves of this notice
     *
     * @param Notice $notice A notice we wish to get faves for (may still be ArrayWrapper)
     *
     * @return array Array of Fave objects
     */
    static public function byNotice($notice)
    {
        if (!isset(self::$_faves[$notice->id])) {
            self::fillFaves(array($notice->id));
        }
        return self::$_faves[$notice->id];
    }

    static public function fillFaves(array $notice_ids)
    {
        $faveMap = Fave::listGet('notice_id', $notice_ids);
        self::$_faves = array_replace(self::$_faves, $faveMap);
    }

    static public function blowCacheForProfileId($profile_id)
    {
        $cache = Cache::instance();
        if ($cache) {
            // Faves don't happen chronologically, so we need to blow
            // ;last cache, too
            $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id));
            $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id.';last'));
            $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id));
            $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id.';last'));
            $cache->delete(Cache::key('fave:count_by_profile:'.$profile_id));
        }
    }
    static public function blowCacheForNoticeId($notice_id)
    {
        $cache = Cache::instance();
        if ($cache) {
            $cache->delete(Cache::key('fave:list-ids:notice_id:'.$notice_id));
        }
    }

    // Remember that we want the _activity_ notice here, not faves applied
    // to the supplied Notice (as with byNotice)!
    static public function fromStored(Notice $stored)
    {
        $class = get_called_class();
        $object = new $class;
        $object->uri = $stored->uri;
        if (!$object->find(true)) {
            throw new NoResultException($object);
        }
        return $object;
    }

    /**
     * Retrieves the _targeted_ notice of a verb (such as the notice that was
     * _favorited_, but not the favorite activity itself).
     *
     * @param Notice $stored    The activity notice.
     *
     * @throws NoResultException when it can't find what it's looking for.
     */
    static public function getTargetFromStored(Notice $stored)
    {
        return self::fromStored($stored)->getTarget();
    }

    static public function getObjectType()
    {
        return ActivityObject::ACTIVITY;
    }

    public function asActivityObject(Profile $scoped=null)
    {
        $actobj = new ActivityObject();
        $actobj->id = $this->getUri();
        $actobj->type = ActivityUtils::resolveUri(self::getObjectType());
        $actobj->actor = $this->getActorObject();
        $actobj->target = $this->getTargetObject();
        $actobj->objects = array(clone($actobj->target));
        $actobj->verb = ActivityVerb::FAVORITE;
        $actobj->title = ActivityUtils::verbToTitle($actobj->verb);
        $actobj->content = $this->getTarget()->getRendered();
        return $actobj;
    }

    /**
     * @param ActivityObject $actobj The _favored_ notice (which we're "in-reply-to")
     * @param Notice         $stored The _activity_ notice, i.e. the favor itself.
     */
    static public function parseActivityObject(ActivityObject $actobj, Notice $stored)
    {
        // throws exception if nothing was found, but it could also be a non-Notice...
        // FIXME: This should only test _one_ URI (and not the links etc.) though a function like this could be useful in other cases
        $local = ActivityUtils::findLocalObject($actobj->getIdentifiers());
        if (!$local instanceof Notice) {
            // $local always returns something, but this was not what we expected. Something is wrong.
            throw new Exception('Something other than a Notice was returned from findLocalObject');
        }

        $actor = $stored->getProfile();
        $object = new Fave();
        $object->user_id = $stored->getProfile()->id;
        $object->notice_id = $local->id;
        $object->uri = $stored->uri;
        $object->created = $stored->created;
        $object->modified = $stored->modified;
        return $object;
    }

    static public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
    {
        $target = self::getTargetFromStored($stored);

        // The following logic was copied from StatusNet's Activity plugin
        if (ActivityUtils::compareVerbs($target->verb, array(ActivityVerb::POST))) {
            // "I like the thing you posted"
            $act->objects = $target->asActivity()->objects;
        } else {
            // "I like that you did whatever you did"
            $act->target = $target->asActivityObject();
            $act->objects = array(clone($act->target));
        }
        $act->context->replyToID = $target->getUri();
        $act->context->replyToUrl = $target->getUrl();
        $act->title = ActivityUtils::verbToTitle($act->verb);
    }

    static function saveActivityObject(ActivityObject $actobj, Notice $stored)
    {
        $object = self::parseActivityObject($actobj, $stored);
        $object->insert();  // exception throwing in Fave's case!

        self::blowCacheForProfileId($object->user_id);
        self::blowCacheForNoticeId($object->notice_id);
        self::blow('popular');

        Event::handle('EndFavorNotice', array($stored->getProfile(), $object->getTarget()));
        return $object;
    }

    public function getTarget()
    {
        return Notice::getByID($this->notice_id);
    }

    public function getTargetObject()
    {
        return $this->getTarget()->asActivityObject();
    }

    protected $_stored = array();

    public function getStored()
    {
        if (!isset($this->_stored[$this->uri])) {
            $stored = new Notice();
            $stored->uri = $this->uri;
            if (!$stored->find(true)) {
                throw new NoResultException($stored);
            }
            $this->_stored[$this->uri] = $stored;
        }
        return $this->_stored[$this->uri];
    }

    public function getActor()
    {
        return Profile::getByID($this->user_id);
    }

    public function getActorObject()
    {
        return $this->getActor()->asActivityObject();
    }

    public function getUri()
    {
        if (!empty($this->uri)) {
            return $this->uri;
        }

        // We (should've in this case) created it ourselves, so we tag it ourselves
        return self::newUri($this->getActor(), $this->getTarget(), $this->created);
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Form for disfavoring a notice
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Form
 * @package   GNUsocial
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://www.gnu.org/software/social/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * Form for disfavoring a notice
 *
 * @category Form
 * @package  GNUsocial
 * @author   Evan Prodromou <evan@status.net>
 * @author   Sarven Capadisli <csarven@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://www.gnu.org/software/social/
 *
 * @see      FavorForm
 */
class DisfavorForm extends Form
{
    /**
     * Notice to disfavor
     */
    var $notice = null;

    /**
     * Constructor
     *
     * @param HTMLOutputter $out    output channel
     * @param Notice        $notice notice to disfavor
     */
    function __construct($out=null, $notice=null)
    {
        parent::__construct($out);

        $this->notice = $notice;
    }

    /**
     * ID of the form
     *
     * @return int ID of the form
     */
    function id()
    {
        return 'disfavor-' . $this->notice->id;
    }

    /**
     * Action of the form
     *
     * @return string URL of the action
     */
    function action()
    {
        return common_local_url('activityverb',
                                array('id'   => $this->notice->getID(),
                                      'verb' => ActivityUtils::resolveUri(ActivityVerb::UNFAVORITE, true)));
    }

    /**
     * Legend of the Form
     *
     * @return void
     */
    function formLegend()
    {
        // TRANS: Form legend for removing the favourite status for a favourite notice.
        $this->out->element('legend', null, _('Disfavor this notice'));
    }

    /**
     * Data elements
     *
     * @return void
     */

    function formData()
    {
        if (Event::handle('StartDisFavorNoticeForm', array($this, $this->notice))) {
            $this->out->hidden('notice-n'.$this->notice->id,
                               $this->notice->id,
                               'notice');
            Event::handle('EndDisFavorNoticeForm', array($this, $this->notice));
        }
    }

    /**
     * Action elements
     *
     * @return void
     */
    function formActions()
    {
        $this->out->submit('disfavor-submit-' . $this->notice->id,
                           // TRANS: Button text for removing the favourite status for a favourite notice.
                           _m('BUTTON','Disfavor favorite'),
                           'submit',
                           null,
                           // TRANS: Button title for removing the favourite status for a favourite notice.
                           _('Remove this notice from your list of favorite notices.'));
    }

    /**
     * Class of the form.
     *
     * @return string the form's class
     */
    function formClass()
    {
        return 'form_disfavor ajax';
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Form for favoring a notice
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Form
 * @package   GNUsocial
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://www.gnu.org/software/social/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * Form for favoring a notice
 *
 * @category Form
 * @package  GNUsocial
 * @author   Evan Prodromou <evan@status.net>
 * @author   Sarven Capadisli <csarven@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://www.gnu.org/software/social/
 *
 * @see      DisfavorForm
 */
class FavorForm extends Form
{
    /**
     * Notice to favor
     */
    var $notice = null;

    /**
     * Constructor
     *
     * @param HTMLOutputter $out    output channel
     * @param Notice        $notice notice to favor
     */
    function __construct($out=null, $notice=null)
    {
        parent::__construct($out);

        $this->notice = $notice;
    }

    /**
     * ID of the form
     *
     * @return int ID of the form
     */
    function id()
    {
        return 'favor-' . $this->notice->id;
    }

    /**
     * Action of the form
     *
     * @return string URL of the action
     */
    function action()
    {
        return common_local_url('activityverb',
                                array('id'   => $this->notice->getID(),
                                      'verb' => ActivityUtils::resolveUri(ActivityVerb::FAVORITE, true)));
    }

    /**
     * Legend of the Form
     *
     * @return void
     */
    function formLegend()
    {
        // TRANS: Form legend for adding the favourite status to a notice.
        $this->out->element('legend', null, _('Favor this notice'));
    }

    /**
     * Data elements
     *
     * @return void
     */
    function formData()
    {
        if (Event::handle('StartFavorNoticeForm', array($this, $this->notice))) {
            $this->out->hidden('notice-n'.$this->notice->id,
                               $this->notice->id,
                               'notice');
            Event::handle('EndFavorNoticeForm', array($this, $this->notice));
        }
    }

    /**
     * Action elements
     *
     * @return void
     */
    function formActions()
    {
        $this->out->submit('favor-submit-' . $this->notice->id,
                           // TRANS: Button text for adding the favourite status to a notice.
                           _m('BUTTON','Favor'),
                           'submit',
                           null,
                           // TRANS: Button title for adding the favourite status to a notice.
                           _('Add this notice to your list of favorite notices.'));
    }

    /**
     * Class of the form.
     *
     * @return string the form's class
     */
    function formClass()
    {
        return 'form_favor ajax';
    }
}