code:
# Translation of StatusNet - FacebookBridge to Simplified Chinese (中文（简体）)
# Exported from translatewiki.net
#
# Author: Hydra
# --
# This file is distributed under the same license as the StatusNet package.
#
msgid ""
msgstr ""
"Project-Id-Version: StatusNet - FacebookBridge\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-06-30 11:07+0000\n"
"PO-Revision-Date: 2012-06-30 11:08:35+0000\n"
"Language-Team: Simplified Chinese <https://translatewiki.net/wiki/Portal:zh-"
"hans>\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-POT-Import-Date: 2012-04-19 14:01:11+0000\n"
"X-Generator: MediaWiki 1.20alpha (233fc08); Translate 2012-06-21\n"
"X-Translation-Project: translatewiki.net <https://translatewiki.net>\n"
"X-Language-Code: zh-hans\n"
"X-Message-Group: #out-statusnet-plugin-facebookbridge\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#. TRANS: Client error displayed when trying to login while already logged in.
msgid "Already logged in."
msgstr "已登录。"

#. TRANS: Form instructions.
msgid "Login with your Facebook Account"
msgstr "与您的 Facebook 帐户登录"

#. TRANS: Page title.
#. TRANS: Alt text for "Login with Facebook" image.
msgid "Login with Facebook"
msgstr "使用 Facebook 登录"

#. TRANS: Title for "Login with Facebook" image.
#, fuzzy
msgid "Login with Facebook."
msgstr "使用 Facebook 登录"

#. TRANS: Title for Facebook administration panel.
#, fuzzy
msgctxt "TITLE"
msgid "Facebook integration settings"
msgstr "Facebook 集成设置"

#. TRANS: Instruction for Facebook administration panel.
msgid "Facebook integration settings"
msgstr "Facebook 集成设置"

#. TRANS: Client error displayed when providing too long a Facebook application ID.
#, fuzzy
msgid "Invalid Facebook ID. Maximum length is 255 characters."
msgstr "无效的 Facebook ID。最大长度为 255 个字符。"

#. TRANS: Client error displayed when providing too long a Facebook secret key.
#, fuzzy
msgid "Invalid Facebook secret. Maximum length is 255 characters."
msgstr "无效的 Facebook 秘密。最大长度为 255 个字符。"

#. TRANS: Fieldset legend.
msgid "Facebook application settings"
msgstr "Facebook 应用程序设置"

#. TRANS: Field label for Facebook application ID.
msgid "Application ID"
msgstr "应用程序 ID"

#. TRANS: Field title for Facebook application ID.
#, fuzzy
msgid "ID of your Facebook application."
msgstr "Facebook 应用程序的 ID"

#. TRANS: Field label for Facebook secret key.
msgid "Secret"
msgstr "秘密"

#. TRANS: Field title for Facebook secret key.
#, fuzzy
msgid "Application secret."
msgstr "应用程序的秘密"

#. TRANS: Button text to save Facebook integration settings.
#. TRANS: Submit button to save synchronisation settings.
msgctxt "BUTTON"
msgid "Save"
msgstr "保存"

#. TRANS: Button title to save Facebook integration settings.
#, fuzzy
msgid "Save Facebook settings."
msgstr "保存的 Facebook 设置"

#. TRANS: Client error displayed when the session token does not match or is not given.
msgid "There was a problem with your session token. Try again, please."
msgstr "有一个与您的会话令牌的问题。请再次尝试。"

#. TRANS: Page title for Facebook settings.
#, fuzzy
msgctxt "TITLE"
msgid "Facebook settings"
msgstr "Facebook 的设置"

#. TRANS: Instructions for Facebook settings.
msgid "Facebook settings"
msgstr "Facebook 的设置"

#. TRANS: Form note. User is connected to facebook.
msgid "Connected Facebook user"
msgstr "已连接的 Facebook 用户"

#. TRANS: Checkbox label in Facebook settings.
msgid "Publish my notices to Facebook."
msgstr "将我的通知发布到 Facebook。"

#. TRANS: Checkbox label in Facebook settings.
msgid "Send \"@\" replies to Facebook."
msgstr "发送 \"@\" Facebook 的答复。"

#. TRANS: Fieldset legend for form to disconnect from Facebook.
msgid "Disconnect my account from Facebook"
msgstr "从 Facebook 拔下我的账户"

#. TRANS: Notice in disconnect from Facebook form if user has no local StatusNet password.
#, php-format
msgid ""
"Disconnecting your Faceboook would make it impossible to log in! Please [set "
"a password](%s) first."
msgstr ""

#. TRANS: Message displayed when initiating disconnect of a StatusNet user
#. TRANS: from a Facebook account. %1$s is the StatusNet site name.
#, php-format
msgid ""
"Keep your %1$s account but disconnect from Facebook. You'll use your %1$s "
"password to log in."
msgstr ""

#. TRANS: Submit button.
msgctxt "BUTTON"
msgid "Disconnect"
msgstr ""

#. TRANS: Notice in case saving of synchronisation preferences fail.
msgid "There was a problem saving your sync preferences."
msgstr ""

#. TRANS: Confirmation that synchronisation settings have been saved into the system.
msgid "Sync preferences saved."
msgstr ""

#. TRANS: Server error displayed when deleting the link to a Facebook account fails.
#, fuzzy
msgid "Could not delete link to Facebook."
msgstr "将我的通知发布到 Facebook。"

#. TRANS: Confirmation message. StatusNet account was unlinked from Facebook.
msgid "You have disconnected from Facebook."
msgstr ""

msgid "Unable to authenticate you with Facebook."
msgstr ""

#. TRANS: Client error displayed when trying to connect to Facebook while not logged in.
msgid ""
"You must be logged into Facebook to register a local account using Facebook."
msgstr "您必须登录到 Facebook 注册使用 Facebook 的本地帐户。"

#. TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
#. TRANS: in the same StatusNet site.
msgid "There is already a local account linked with that Facebook account."
msgstr "已存在与该 Facebook 帐户相关的本地帐户。"

#. TRANS: Form validation error displayed when user has not agreed to the license.
#, fuzzy
msgid "You cannot register if you do not agree to the license."
msgstr "如果您不同意该许可，您不能注册。"

#. TRANS: Form validation error displayed when an unhandled error occurs.
msgid "An unknown error has occured."
msgstr "出现了一个未知的错误。"

#. TRANS: Form instructions for connecting to Facebook.
#. TRANS: %s is the site name.
#, php-format
msgid ""
"This is the first time you have logged into %s so we must connect your "
"Facebook to a local account. You can either create a new local account, or "
"connect with an existing local account."
msgstr ""

#. TRANS: Page title.
msgid "Facebook Setup"
msgstr "Facebook 安装程序"

#. TRANS: Fieldset legend.
msgid "Connection options"
msgstr "连接选项"

#. TRANS: %s is the name of the license used by the user for their status updates.
#, php-format
msgid ""
"My text and files are available under %s except this private data: password, "
"email address, IM address, and phone number."
msgstr ""

#. TRANS: Fieldset legend.
msgid "Create new account"
msgstr "创建新的帐户"

#. TRANS: Form instructions.
msgid "Create a new user with this nickname."
msgstr "此别名与创建新用户。"

#. TRANS: Field label.
msgid "New nickname"
msgstr "新的昵称"

#. TRANS: Field title.
#, fuzzy
msgid "1-64 lowercase letters or numbers, no punctuation or spaces."
msgstr "1-64 个小写字母或没有标点符号或空格的数字"

#. TRANS: Submit button to create a new account.
msgctxt "BUTTON"
msgid "Create"
msgstr "创建"

#. TRANS: Fieldset legend.
msgid "Connect existing account"
msgstr "连接现有的帐户"

#. TRANS: Form instructions.
msgid ""
"If you already have an account, login with your username and password to "
"connect it to your Facebook."
msgstr "如果您已经有一个的帐户使用您的用户名和密码以连接到在 Facebook 的登录。"

#. TRANS: Field label.
msgid "Existing nickname"
msgstr "现有的昵称"

#. TRANS: Field label.
msgid "Password"
msgstr "密码"

#. TRANS: Submit button to connect a Facebook account to an existing StatusNet account.
msgctxt "BUTTON"
msgid "Connect"
msgstr "连接"

#. TRANS: Client error trying to register with registrations not allowed.
#. TRANS: Client error trying to register with registrations 'invite only'.
msgid "Registration not allowed."
msgstr "不允许注册。"

#. TRANS: Client error trying to register with an invalid invitation code.
msgid "Not a valid invitation code."
msgstr "不是一个有效的邀请代码。"

#. TRANS: Form validation error displayed when picking a nickname that is not allowed.
msgid "Nickname not allowed."
msgstr "不允许使用的昵称。"

#. TRANS: Form validation error displayed when picking a nickname that is already in use.
msgid "Nickname already in use. Try another one."
msgstr "别名已在使用中。请尝试另一个。"

#. TRANS: Server error displayed when connecting to Facebook fails.
msgid "Error connecting user to Facebook."
msgstr "Facebook 中连接用户时出错。"

#. TRANS: Form validation error displayed when username/password combination is incorrect.
msgid "Invalid username or password."
msgstr "无效的用户名或密码。"

#. TRANS: Menu item for "Facebook" in administration panel.
#. TRANS: Menu item for "Facebook" in user settings.
msgctxt "MENU"
msgid "Facebook"
msgstr "Facebook"

#. TRANS: Menu title for "Facebook" login.
#, fuzzy
msgid "Login or register using Facebook."
msgstr "登入或使用 Facebook 的注册"

#. TRANS: Menu title for "Facebook" in administration panel.
#, fuzzy
msgid "Facebook integration configuration."
msgstr "Facebook 整合配置"

#. TRANS: Menu title for "Facebook" in user settings.
#, fuzzy
msgid "Facebook settings."
msgstr "Facebook 的设置"

#. TRANS: Plugin description.
msgid "A plugin for integrating StatusNet with Facebook."
msgstr "StatusNet 与结合 Facebook 的插件。"

#. TRANS: E-mail subject.
msgid "Your Facebook connection has been removed"
msgstr "Facebook 的连接已被删除"

#. TRANS: E-mail body. %1$s is a username, %2$s is the StatusNet sitename.
#, php-format
msgid ""
"Hi %1$s,\n"
"\n"
"We are sorry to inform you we are unable to publish your notice to\n"
"Facebook, and have removed the connection between your %2$s account and\n"
"Facebook.\n"
"\n"
"This may have happened because you have removed permission for %2$s\n"
"to post on your behalf, or perhaps you have deactivated your Facebook\n"
"account. You can reconnect your %2$s account to Facebook at any time by\n"
"logging in with Facebook again.\n"
"\n"
"Sincerely,\n"
"\n"
"%2$s\n"
msgstr ""

#. TRANS: E-mail subject. %s is the StatusNet sitename.
#, php-format
msgid "Contact the %s administrator to retrieve your account"
msgstr "与 %s 管理员联系，以检索您的帐户"

#. TRANS: E-mail body. %1$s is a username,
#. TRANS: %2$s is the StatusNet sitename, %3$s is the site contact e-mail address.
#, php-format
msgid ""
"Hi %1$s,\n"
"\n"
"We have noticed you have deauthorized the Facebook connection for your\n"
"%2$s account.  You have not set a password for your %2$s account yet, so\n"
"you will not be able to login. If you wish to continue using your %2$s\n"
"account, please contact the site administrator (%3$s) to set a password.\n"
"\n"
"Sincerely,\n"
"\n"
"%2$s\n"
msgstr ""


code:
Events that come with the Favorite plugin
=========================================

EndFavorNotice: After saving a notice as a favorite
- $profile: profile of the person faving (can be remote!)
- $notice: notice being faved

StartDisfavorNotice: Saving a notice as a favorite
- $profile: profile of the person faving (can be remote!)
- $notice: notice being faved
- &$result: result of the disfavoring (if you override)

EndDisfavorNotice: After saving a notice as a favorite
- $profile: profile of the person faving (can be remote!)
- $notice: notice being faved

StartFavorNoticeForm: starting the data in the form for favoring a notice
- $FavorForm: the favor form being shown
- $notice: notice being favored

EndFavorNoticeForm: Ending the data in the form for favoring a notice
- $FavorForm: the favor form being shown
- $notice: notice being favored

StartDisFavorNoticeForm: starting the data in the form for disfavoring a notice
- $DisfavorForm: the disfavor form being shown
- $notice: notice being difavored

EndDisFavorNoticeForm: Ending the data in the form for disfavoring a notice
- $DisfavorForm: the disfavor form being shown
- $notice: notice being disfavored

StartShowFaveForm: just before showing the fave form
- $item: the NoticeListItem object being shown

EndShowFaveForm: just after showing the fave form
- $item: the NoticeListItem object being shown

license: mit


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 ActivityHandlerPlugin
{
    protected $email_notify_fave = 1;

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

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

    public function verbs()
    {
        return array(ActivityVerb::FAVORITE);
    }

    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->user_id, $fave->notice_id, $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',
                          'format' => '(xml|json)'));
        $m->connect('api/favorites/destroy.:format',
                    array('action' => 'ApiFavoriteDestroy',
                          'format' => '(xml|json)'));
        $m->connect('api/favorites/list.:format',
                    array('action' => 'ApiTimelineFavorites',
                          'format' => '(xml|json|rss|atom|as)'));
        $m->connect('api/favorites/:id.:format',
                    array('action' => 'ApiTimelineFavorites',
                          'id' => Nickname::INPUT_FMT,
                          'format' => '(xml|json|rss|atom|as)'));
        $m->connect('api/favorites.:format',
                    array('action' => 'ApiTimelineFavorites',
                          'format' => '(xml|json|rss|atom|as)'));
        $m->connect('api/favorites/create/:id.:format',
                    array('action' => 'ApiFavoriteCreate',
                          'id' => '[0-9]+',
                          'format' => '(xml|json)'));
        $m->connect('api/favorites/destroy/:id.:format',
                    array('action' => 'ApiFavoriteDestroy',
                          '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',
                          '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));

        // If empty, we should've created it ourselves on our node.
        if (!isset($options['created'])) {
            $options['created'] = !empty($act->time) ? common_sql_date($act->time) : common_sql_now();
        }

        // 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;
        }

        common_debug('Extending activity '.$stored->id.' with '.get_called_class());
        $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 onUserDeleteRelated(User $user, array &$related)
    {
        $fave = new Fave();
        $fave->user_id = $user->id;
        $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"

        Fave::blowCacheForProfileId($user->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));
        }
    }

    public 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 onStartShowThreadedNoticeTailItems(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->boolean('email-notify_fave') ? 1 : 0;
        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();
        }
    }

    public function onPluginVersion(array &$versions)
    {
        $versions[] = array('name' => 'Favorite',
                            'version' => GNUSOCIAL_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:
<?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
            );
        }

        // Note: Twitter lets you fave things repeatedly via API.

        if (Fave::existsForProfile($this->notice, $this->scoped)) {
            $this->clientError(
                // TRANS: Client error displayed when trying to mark a notice favourite that already is a favourite.
                _('This status is already a favorite.'),
                403,
                $this->format
            );
        }

        // throws exception on failure
        $stored = Fave::addNew($this->scoped, $this->notice);

        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($args)
    {
        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($args)
    {
        parent::handle($args);

        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
/**
 * Disfavor action.
 *
 * PHP version 5
 *
 * @category Action
 * @package  GNUsocial
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://www.gnu.org/software/social/
 *
 * 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); }

/**
 * DisfavorAction class.
 *
 * @category Action
 * @package  GNUsocial
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://www.gnu.org/software/social/
 */
class DisfavorAction extends FormAction
{
    public function showForm($msg=null, $success=false)
    {
        if ($success) {
            common_redirect(common_local_url('showfavorites',
                array('nickname' => $this->scoped->nickname)), 303);
        }
        parent::showForm($msg, $success);
    }

    protected function handlePost()
    {
        $id     = $this->trimmed('notice');
        $notice = Notice::getKV($id);
        if (!$notice instanceof Notice) {
            $this->serverError(_('Notice not found'));
        }

        $fave            = new Fave();
        $fave->user_id   = $this->scoped->id;
        $fave->notice_id = $notice->id;
        if (!$fave->find(true)) {
            throw new NoResultException($fave);
        }
        $result = $fave->delete();
        if (!$result) {
            common_log_db_error($fave, 'DELETE', __FILE__);
            // TRANS: Server error displayed when removing a favorite from the database fails.
            $this->serverError(_('Could not delete favorite.'));
        }
        Fave::blowCacheForProfileId($this->scoped->id);
        if (StatusNet::isAjax()) {
            $this->startHTML('text/xml;charset=utf-8');
            $this->elementStart('head');
            // TRANS: Title for page on which favorites can be added.
            $this->element('title', null, _('Add to favorites'));
            $this->elementEnd('head');
            $this->elementStart('body');
            $favor = new FavorForm($this, $notice);
            $favor->show();
            $this->elementEnd('body');
            $this->endHTML();
            exit;
        }
    }
}


code:
<?php
/**
 * Favor action.
 *
 * PHP version 5
 *
 * @category Action
 * @package  GNUsocial
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://www.gnu.org/software/social/
 *
 * 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); }

/**
 * FavorAction class.
 *
 * @category Action
 * @package  GNUsocial
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://www.gnu.org/software/social/
 */
class FavorAction extends FormAction
{
    protected $needPost = true;

    protected $object = null;

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

        $this->target = Notice::getKV($this->trimmed('notice'));
        if (!$this->target instanceof Notice) {
            throw new ServerException(_m('No such notice.'));
        }
        if (!$this->target->inScope($this->scoped)) {
            // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
            // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
            throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $this->scoped->getNickname(), $this->target->id), 403);
        }

        return true;
    }

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

        if (Fave::existsForProfile($this->target, $this->scoped)) {
            // 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!'));
        }

        // throws exception on failure
        $stored = Fave::addNew($this->scoped, $this->target);

        return _('Favorited the notice');
    }

    protected function showContent()
    {
        if ($this->target instanceof Notice) {
            $disfavor = new DisfavorForm($this, $this->target);
            $disfavor->show();
        }
    }
}


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($args)
    {
        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($args)
    {
        parent::handle($args);

        $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(Profile::current());
        $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('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

require_once INSTALLDIR.'/lib/rssaction.php';

/**
 * 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 Rss10Action
{
    /** The user whose favorites to display */

    var $user = null;

    /**
     * Find the user to display by supplied nickname
     *
     * @param array $args Arguments from $_REQUEST
     *
     * @return boolean success
     */
    function prepare($args)
    {
        parent::prepare($args);

        $nickname   = $this->trimmed('nickname');
        $this->user = User::getKV('nickname', $nickname);

        if (!$this->user) {
            // TRANS: Client error displayed when trying to get the RSS feed with favorites of a user that does not exist.
            $this->clientError(_('No such user.'));
        } else {
            $this->notices = $this->getNotices($this->limit);
            return true;
        }
    }

    /**
     * Get notices
     *
     * @param integer $limit max number of notices to return
     *
     * @return array notices
     */
    function getNotices($limit=0)
    {
        $notice  = Fave::stream($this->user->id, 0, $limit, $false);
        $notices = array();
        while ($notice->fetch()) {
            $notices[] = clone($notice);
        }
        return $notices;
    }

     /**
     * 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;
    }

    /**
     * Get image.
     *
     * @return void
    */
    function getImage()
    {
        return null;
    }

}


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('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

require_once INSTALLDIR.'/lib/personalgroupnav.php';
require_once INSTALLDIR.'/lib/noticelist.php';
require_once INSTALLDIR.'/lib/feedlist.php';

/**
 * 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 Action
{
    /** User we're getting the faves of */
    var $user = null;
    /** Page of the faves we're on */
    var $page = null;

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

    /**
     * Title of the page
     *
     * Includes name of user and page number.
     *
     * @return string title of page
     */
    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->user->nickname);
        } 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->user->nickname,
                           $this->page);
        }
    }

    /**
     * Prepare the object
     *
     * Check the input values and initialize the object.
     * Shows an error page on bad input.
     *
     * @param array $args $_REQUEST data
     *
     * @return boolean success flag
     */
    function prepare($args)
    {
        parent::prepare($args);

        $nickname = common_canonical_nickname($this->arg('nickname'));

        $this->user = User::getKV('nickname', $nickname);

        if (!$this->user) {
            // TRANS: Client error displayed when trying to display favourite notices for a non-existing user.
            $this->clientError(_('No such user.'));
        }

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

        if (!$this->page) {
            $this->page = 1;
        }

        common_set_returnto($this->selfUrl());

        $cur = common_current_user();

        // Show imported/gateway notices as well as local if
        // the user is looking at their own favorites, otherwise not.
        $this->notice = Fave::stream($this->user->id,
                                     ($this->page-1)*NOTICES_PER_PAGE,  // offset
                                     NOTICES_PER_PAGE + 1,              // limit
                                     (!empty($cur) && $cur->id == $this->user->id)  // own feed?
                                    );

        if (empty($this->notice)) {
            // TRANS: Server error displayed when favourite notices could not be retrieved from the database.
            $this->serverError(_('Could not retrieve favorite notices.'));
        }

        if($this->page > 1 && $this->notice->N == 0){
            // TRANS: Client error when page not found (404)
            $this->clientError(_('No such page.'), 404);
        }

        return true;
    }

    /**
     * Handle a request
     *
     * Just show the page. All args already handled.
     *
     * @param array $args $_REQUEST data
     *
     * @return void
     */
    function handle($args)
    {
        parent::handle($args);
        $this->showPage();
    }

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

    function showEmptyListMessage()
    {
        if (common_logged_in()) {
            $current_user = common_current_user();
            if ($this->user->id === $current_user->id) {
                // 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->user->nickname);
            }
        }
        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->user->nickname);
        }

        $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 showContent()
    {
        $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->user->nickname));
    }

    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)
    {
        return new FavoritesNoticeListItem($notice, $this->out);
    }
}

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