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

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

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

    /**
     * Save a favorite record.
     * @fixme post-author notification should be moved here
     *
     * @param Profile $actor  the local or remote Profile who favorites
     * @param Notice  $target the notice that is favorited
     * @return Fave record on success
     * @throws Exception on failure
     */
    static function addNew(Profile $actor, Notice $target) {
        $act = new Activity();
        $act->type    = ActivityObject::ACTIVITY;
        $act->verb    = ActivityVerb::FAVORITE;
        $act->time    = time();
        $act->id      = self::newUri($actor, $target, common_sql_date($act->time));
        $act->title   = _("Favor");
        // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
        //        notice's nickname and %3$s is the content of the favorited notice.)
        $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
                                $actor->getNickname(), $target->getProfile()->getNickname(),
                                $target->rendered ?: $target->content);
        $act->actor   = $actor->asActivityObject();
        $act->target  = $target->asActivityObject();
        $act->objects = array(clone($act->target));

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

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

        return $stored;
    }

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

    public function delete($useWhere=false)
    {
        $profile = Profile::getKV('id', $this->user_id);
        $notice  = Notice::getKV('id', $this->notice_id);

        $result = null;

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

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

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

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

        return $result;
    }

    function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
    {
        $stream = new FaveNoticeStream($user_id, $own);

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

    function idStream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
    {
        $stream = new FaveNoticeStream($user_id, $own);

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

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

        $act = new Activity();

        $act->verb = ActivityVerb::FAVORITE;

        // FIXME: rationalize this with URL below

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

        $act->time    = strtotime($this->created);
        // TRANS: Activity title when marking a notice as favorite.
        $act->title   = _("Favor");
        // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
        //        notice's nickname and %3$s is the content of the favorited notice.)
        $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
                                $actor->getNickname(), $target->getProfile()->getNickname(),
                                $target->rendered ?: $target->content);

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

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

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

        return $act;
    }

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

        return ($fave instanceof Fave);
    }

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

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

        $fav->user_id = $profileId;

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

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

        $fav->find();

        return $fav;
    }

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

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

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

        return $cnt;
    }

    static protected $_faves = array();

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

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

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

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

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

    static public function getObjectType()
    {
        return 'activity';
    }

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

    /**
     * @param ActivityObject $actobj The _favored_ notice (which we're "in-reply-to")
     * @param Notice         $stored The _activity_ notice, i.e. the favor itself.
     */
    static public function parseActivityObject(ActivityObject $actobj, Notice $stored)
    {
        $local = ActivityUtils::findLocalObject($actobj->getIdentifiers());
        if (!$local instanceof Notice) {
            // $local always returns something, but this was not what we expected. Something is wrong.
            throw new Exception('Something other than a Notice was returned from findLocalObject');
        }

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

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

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

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

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

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

    public function getAttentionArray() {
        // not all objects can/should carry attentions, so we don't require extending this
        // the format should be an array with URIs to mentioned profiles
        return array();
    }

    public function getTarget()
    {
        // throws exception on failure
        $target = new Notice();
        $target->id = $this->notice_id;
        if (!$target->find(true)) {
            throw new NoResultException($target);
        }

        return $target;
    }

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

    protected $_stored = array();

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

    public function getActor()
    {
        $profile = new Profile();
        $profile->id = $this->user_id;
        if (!$profile->find(true)) {
            throw new NoResultException($profile);
        }
        return $profile;
    }

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

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

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

    static function newUri(Profile $actor, Managed_DataObject $target, $created=null)
    {
        if (is_null($created)) {
            $created = common_sql_now();
        }
        return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
                                        $actor->id,
                                        ActivityUtils::resolveUri(self::getObjectType(), true),
                                        $target->id,
                                        common_date_iso8601($created));
    }
}


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

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

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

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

        $this->notice = $notice;
    }

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

    /**
     * Action of the form
     *
     * @return string URL of the action
     */
    function action()
    {
        return common_local_url('disfavor');
    }

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

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

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

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

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

license: mit


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

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

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

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

        $this->notice = $notice;
    }

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

    /**
     * Action of the form
     *
     * @return string URL of the action
     */
    function action()
    {
        return common_local_url('favor');
    }

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

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

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

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


code:
<?php

class FavCommand extends Command
{
    var $other = null;

    function __construct($user, $other)
    {
        parent::__construct($user);
        $this->other = $other;
    }

    function handle($channel)
    {
        $notice = $this->getNotice($this->other);

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

        if ($fave->fetch()) {
            // TRANS: Error message text shown when a favorite could not be set because it has already been favorited.
            $channel->error($this->user, _('Could not create favorite: Already favorited.'));
            return;
        }

        try {
            $fave = Fave::addNew($this->user->getProfile(), $notice);
        } catch (Exception $e) {
            $channel->error($this->user, $e->getMessage());
            return;
        }

        // TRANS: Text shown when a notice has been marked as favourite successfully.
        $channel->output($this->user, _('Notice marked as fave.'));
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Notice stream for favorites
 *
 * 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  Stream
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 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);
}

/**
 * Notice stream for favorites
 *
 * @category  Stream
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class FaveNoticeStream extends ScopingNoticeStream
{
    function __construct($user_id, $own, $profile = -1)
    {
        $stream = new RawFaveNoticeStream($user_id, $own);
        if ($own) {
            $key = 'fave:ids_by_user_own:'.$user_id;
        } else {
            $key = 'fave:ids_by_user:'.$user_id;
        }
        if (is_int($profile) && $profile == -1) {
            $profile = Profile::current();
        }
        parent::__construct(new CachingNoticeStream($stream, $key),
                            $profile);
    }
}

/**
 * Raw notice stream for favorites
 *
 * @category  Stream
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class RawFaveNoticeStream extends NoticeStream
{
    protected $user_id;
    protected $own;

    function __construct($user_id, $own)
    {
        parent::__construct();

        $this->user_id = $user_id;
        $this->own     = $own;

        $this->selectVerbs = array();
    }

    /**
     * Note that the sorting for this is by order of *fave* not order of *notice*.
     *
     * @fixme add since_id, max_id support?
     *
     * @param <type> $user_id
     * @param <type> $own
     * @param <type> $offset
     * @param <type> $limit
     * @param <type> $since_id
     * @param <type> $max_id
     * @return <type>
     */
    function getNoticeIds($offset, $limit, $since_id, $max_id)
    {
        $fav = new Fave();
        $qry = null;

        if ($this->own) {
            $qry  = 'SELECT fave.* FROM fave ';
            $qry .= 'WHERE fave.user_id = ' . $this->user_id . ' ';
        } else {
             $qry =  'SELECT fave.* FROM fave ';
             $qry .= 'INNER JOIN notice ON fave.notice_id = notice.id ';
             $qry .= 'WHERE fave.user_id = ' . $this->user_id . ' ';
             $qry .= 'AND notice.is_local != ' . Notice::GATEWAY . ' ';
        }

        if ($since_id != 0) {
            $qry .= 'AND notice_id > ' . $since_id . ' ';
        }

        if ($max_id != 0) {
            $qry .= 'AND notice_id <= ' . $max_id . ' ';
        }

        // NOTE: we sort by fave time, not by notice time!

        $qry .= 'ORDER BY modified DESC ';

        if (!is_null($offset)) {
            $qry .= "LIMIT $limit OFFSET $offset";
        }

        $fav->query($qry);

        $ids = array();

        while ($fav->fetch()) {
            $ids[] = $fav->notice_id;
        }

        $fav->free();
        unset($fav);

        return $ids;
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Base class for sections showing lists of 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  Widget
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009,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);
}

/**
 * Base class for sections showing lists of notices
 *
 * These are the widgets that show interesting data about a person
 * group, or site.
 *
 * @category Widget
 * @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 PopularNoticeSection extends NoticeSection
{
    protected $viewer;

    function __construct($out, Profile $viewer=null)
    {
        parent::__construct($out);
        $this->viewer = $viewer;
    }

    function getNotices()
    {
        $stream = new PopularNoticeStream($this->viewer);
        return $stream->getNotices(0, NOTICES_PER_SECTION + 1);
    }

    function title()
    {
        // TRANS: Title for favourited notices section.
        return _('Popular notices');
    }

    function divId()
    {
        return 'popular_section';
    }

    function moreUrl()
    {
        if (common_config('singleuser', 'enabled')) {
            $user = User::singleUser();
            common_local_url('showfavorites', array('nickname' =>
                                                    $user->nickname));
        } else {
            return common_local_url('favorited');
        }
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Stream of notices sorted by popularity
 *
 * 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  Popular
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 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);
}

/**
 * Stream of notices sorted by popularity
 *
 * @category  Popular
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

class PopularNoticeStream extends ScopingNoticeStream
{
    function __construct($profile=null)
    {
        parent::__construct(new CachingNoticeStream(new RawPopularNoticeStream(),
                                                    'popular',
                                                    false),
                            $profile);
    }
}

class RawPopularNoticeStream extends NoticeStream
{
    function getNoticeIds($offset, $limit, $since_id, $max_id)
    {
        $weightexpr = common_sql_weight('modified', common_config('popular', 'dropoff'));
        $cutoff = sprintf("modified > '%s'",
                          common_sql_date(time() - common_config('popular', 'cutoff')));

        $fave = new Fave();
        $fave->selectAdd();
        $fave->selectAdd('notice_id');
        $fave->selectAdd("$weightexpr as weight");
        $fave->whereAdd($cutoff);
        $fave->orderBy('weight DESC');
        $fave->groupBy('notice_id');

        if (!is_null($offset)) {
            $fave->limit($offset, $limit);
        }

        // FIXME: $since_id, $max_id are ignored

        $ids = array();

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

        return $ids;
    }
}


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

/**
 * Placeholder for showing faves...
 */
class ThreadedNoticeListFavesItem extends NoticeListActorsItem
{
    function getProfiles()
    {
        $faves = Fave::byNotice($this->notice);
        $profiles = array();
        foreach ($faves as $fave) {
            $profiles[] = $fave->user_id;
        }
        return $profiles;
    }

    function magicList($items)
    {
        if (count($items) > 4) {
            return parent::magicList(array_slice($items, 0, 3));
        } else {
            return parent::magicList($items);
        }
    }

    function getListMessage($count, $you)
    {
        if ($count == 1 && $you) {
            // darn first person being different from third person!
            // TRANS: List message for notice favoured by logged in user.
            return _m('FAVELIST', 'You like this.');
        } else if ($count > 4) {
            // TRANS: List message for when more than 4 people like something.
            // TRANS: %%s is a list of users liking a notice, %d is the number over 4 that like the notice.
            // TRANS: Plural is decided on the total number of users liking the notice (count of %%s + %d).
            return sprintf(_m('%%s and %d others like this.',
                              '%%s and %d others like this.',
                              $count),
                           $count - 3);
        } else {
            // TRANS: List message for favoured notices.
            // TRANS: %%s is a list of users liking a notice.
            // TRANS: Plural is based on the number of of users that have favoured a notice.
            return sprintf(_m('%%s likes this.',
                              '%%s like this.',
                              $count),
                           $count);
        }
    }

    function showStart()
    {
        $this->out->elementStart('li', array('class' => 'notice-data notice-faves'));
    }

    function showEnd()
    {
        $this->out->elementEnd('li');
    }
}


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

// @todo FIXME: needs documentation.
class ThreadedNoticeListInlineFavesItem extends ThreadedNoticeListFavesItem
{
    function showStart()
    {
        $this->out->elementStart('div', array('class' => 'notice-faves'));
    }

    function showEnd()
    {
        $this->out->elementEnd('div');
    }
}


code:
<?php
/**
 * GNU social feed polling plugin, to avoid using external PuSH hubs
 *
 * @category  Feed
 * @package   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://www.gnu.org/software/social/
 */

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

class FeedPollerPlugin extends Plugin {
    public $interval = 5;   // interval in minutes for feed checks

    public function onEndInitializeQueueManager(QueueManager $qm)
    {
        $qm->connect(FeedPoll::QUEUE_CHECK, 'FeedPollQueueHandler');
        return true;
    }

    public function onCronMinutely()
    {
        $args = array('interval'=>$this->interval);
        FeedPoll::enqueueNewFeeds($args);
        return true;
    }

    public function onFeedSubscribe(FeedSub $feedsub)
    {
        if (!$feedsub->isPuSH()) {
            FeedPoll::setupFeedSub($feedsub, $this->interval*60);
            return false;   // We're polling this feed, so stop processing FeedSubscribe
        }
        return true;
    }

    public function onFeedUnsubscribe(FeedSub $feedsub)
    {
        if (!$feedsub->isPuSH()) {
            // removes sub_state setting and such
            $feedsub->confirmUnsubscribe();
            return false;
        }
        return true;
    }

    public function onPluginVersion(&$versions)
    {
        $versions[] = array('name' => 'FeedPoller',
                            'version' => GNUSOCIAL_VERSION,
                            'author' => 'Mikael Nordfeldth',
                            'homepage' => 'http://www.gnu.org/software/social/',
                            'description' =>
                            // TRANS: Plugin description.
                            _m('Feed polling plugin to avoid using external push hubs.'));
        return true;
    }
}


code:
<?php
/**
 * Store last poll time in db, then check if they should be renewed (if so, enqueue).
 * Can be called from a queue handler on a per-feed status to poll stuff.
 *
 * Used as internal feed polling mechanism (atom/rss)
 *
 * @category OStatus
 * @package  GNUsocial
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://www.gnu.org/software/social/
 */

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

class FeedPoll {
    const DEFAULT_INTERVAL = 5; // in minutes

    const QUEUE_CHECK = 'feedpoll-check';

    // TODO: Find some smart way to add feeds only once, so they don't get more than 1 feedpoll in the queue each
    //       probably through sub_start sub_end trickery.
    public static function enqueueNewFeeds(array $args=array()) {
        if (!isset($args['interval']) || !is_int($args['interval']) || $args['interval']<=0) {
            $args['interval'] = self::DEFAULT_INTERVAL;
        }

        $args['interval'] *= 60;    // minutes to seconds

        $feedsub = new FeedSub();
        $feedsub->sub_state = 'nohub';
        // Find feeds that haven't been polled within the desired interval,
        // though perhaps we're abusing the "last_update" field here?
        $feedsub->whereAdd(sprintf('last_update < "%s"', common_sql_date(time()-$args['interval'])));
        $feedsub->find();

        $qm = QueueManager::get();
        while ($feedsub->fetch()) {
            $orig = clone($feedsub);
            $item = array('id' => $feedsub->id);
            $qm->enqueue($item, self::QUEUE_CHECK);
            $feedsub->last_update = common_sql_now();
            $feedsub->update($orig);
        }
    }

    public function setupFeedSub(FeedSub $feedsub, $interval=300)
    {
        $orig = clone($feedsub);
        $feedsub->sub_state = 'nohub';
        $feedsub->sub_start = common_sql_date(time());
        $feedsub->sub_end   = '';
        $feedsub->last_update = common_sql_date(time()-$interval);  // force polling as soon as we can
        $feedsub->update($orig);
    }

    public function checkUpdates(FeedSub $feedsub)
    {
        $request = new HTTPClient();
        $feed = $request->get($feedsub->uri);
        if (!$feed->isOk()) {
            throw new ServerException('FeedSub could not fetch id='.$feedsub->id.' (Error '.$feed->getStatus().': '.$feed->getBody());
        }
        $feedsub->receive($feed->getBody(), null);
    }
}


code:
<?php

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

/**
 * Poll a feed based on its urlhash, the full url is in the feedsub table
 *
 * @author Mikael Nordfeldth <mmn@hethane.se>
 */
class FeedPollQueueHandler extends QueueHandler
{
    public function transport()
    {
        return FeedPoll::QUEUE_CHECK;
    }

    public function handle($item)
    {
        $feedsub = FeedSub::getKV('id', $item['id']);
        if (!$feedsub instanceof FeedSub) {
            // Removed from the feedsub table I guess
            return true;
        }
        if (!$feedsub->sub_state == 'nohub') {
            // We're not supposed to poll this (either it's PuSH or it's unsubscribed)
            return true;
        }

        try {
            FeedPoll::checkUpdates($feedsub);
        } catch (Exception $e) {
            common_log(LOG_ERR, "Failed to check feedsub id= ".$feedsub->id.' ("'.$e->getMessage().'")');
        }

        return true;
    }
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2010, 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/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));

$helptext = <<<END_OF_HELP
pollfeed.php feeduri

Poll the feed, assuming it has sub_state 'nohub'.

END_OF_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

require_once(__DIR__ . '/../lib/feedpoll.php');

if (empty($args[0]) || !Validate::uri($args[0])) {
    echo "$helptext\n";
    exit(1);
}

$uri = $args[0];

$feedsub = FeedSub::getKV('uri', $uri);

if (!$feedsub instanceof FeedSub) {
    echo "No FeedSub feed known for URI $uri\n";
    exit(1);
}

if ($feedsub->sub_state != 'nohub') {
    echo "Feed is a PuSH feed, so we will not poll it.\n";
    exit(1);
}

showSub($feedsub);

try {
    FeedPoll::checkUpdates($feedsub);
} catch (Exception $e) {
    echo "Could not check updates for feed: ".$e->getMessage();
    echo $e->getTraceAsString();
    exit(1);
}

function showSub(FeedSub $sub)
{
    echo "  Subscription state: $sub->sub_state\n";
    echo "  Signature secret: $sub->secret\n";
    echo "  Sub start date: $sub->sub_start\n";
    echo "  Record created: $sub->created\n";
    echo "  Record modified: $sub->modified\n";
}


code:
<?php
/*
 * StatusNet Plugin: 0.9
 * Plugin Name: FirePHP
 * Description: Sends StatusNet log output to FirePHP
 * Version: 0.1
 * Author: Craig Andrews <candrews@integralblue.com>
 * Author URI: http://candrews.integralblue.com/
*/

/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 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/>.
 * @category  Plugin
 * @package MinifyPlugin
 * @maintainer Craig Andrews <candrews@integralblue.com>
 * @author    Craig Andrews <candrews@integralblue.com>
 * @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') && !defined('LACONICA')) { exit(1); }

// We bundle the FirePHP library...
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/FirePHP/lib');

class FirePHPPlugin extends Plugin
{
    private $firephp;

    function onInitializePlugin()
    {
        //Output buffering has to be enabled so FirePHP can send the HTTP headers it needs
        ob_start();
        require_once('FirePHPCore/FirePHP.class.php');
        $this->firephp = FirePHP::getInstance(true);
    }

    function onStartLog(&$priority, &$msg, &$filename)
    {
        static $firephp_priorities = array(FirePHP::ERROR, FirePHP::ERROR, FirePHP::ERROR, FirePHP::ERROR,
                                      FirePHP::WARN, FirePHP::LOG, FirePHP::LOG, FirePHP::INFO);
        $fp_priority = $firephp_priorities[$priority];
        $this->firephp->fb($msg, $fp_priority);
    }

    function onPluginVersion(&$versions)
    {
        $versions[] = array('name' => 'FirePHP',
                            'version' => GNUSOCIAL_VERSION,
                            'author' => 'Craig Andrews',
                            'homepage' => 'http://status.net/wiki/Plugin:FirePHP',
                            'rawdescription' =>
                            // TRANS: Plugin description.
                            _m('The FirePHP plugin writes StatusNet\'s log output to FirePHP.'));
        return true;
    }
}


code:
The FirePHP plugin writes StatusNet's log output to FirePHP.

Using FirePHP on production sites can expose sensitive information.

You must protect the security of your application by disabling FirePHP logging
on your live site!

Installation
============
add "addPlugin('FirePHP',
    array('setting'=>'value', 'setting2'=>'value2', ...);"
to the bottom of your config.php

Settings
========
None at the moment.

Example
=======

addPlugin('FirePHP', array());

path: plugins/FirePHP/README


code:
2008-06-14 - Release Version: 0.3.1

  - (Issue 108) ignore class name case in object filter

2009-05-11 - Release Version: 0.3
2009-05-01 - Release Version: 0.3.rc.1

  - (Issue 90) PHP4 compatible version of FirePHPCore
  - (Issue 98) Thrown exceptions don't send an HTTP 500 if the FirePHP exception handler is enabled
  - (Issue 85) Support associative arrays in encodeTable method in FirePHP.class.php
  - (Issue 66) Add a new getOptions() public method in API
  - (Issue 82) Define $this->options outside of __construct
  - (Issue 72) Message error if group name is null
  - (Issue 68) registerErrorHandler() and registerExceptionHandler() should returns previous handlers defined
  - (Issue 69) Add the missing register handler in the triumvirate (error, exception, assert)
  - (Issue 75) [Error & Exception Handling] Option to not exit script execution
  - (Issue 83) Exception handler can't throw exceptions
  - (Issue 80) Auto/Pre collapsing groups AND Custom group row colors

2008-11-09 - Release Version: 0.2.1

  - (Issue 70) Problem when logging resources

2008-10-21 - Release Version: 0.2.0

	- Updated version to 0.2.0
	- Switched to using __sleep instead of __wakeup
	- Added support to exclude object members when encoding
  - Add support to enable/disable logging

2008-10-17 - Release Version: 0.2.b.8

  - New implementation for is_utf8()
  - (Issue 55) maxObjectDepth Option not working correctly when using TABLE and EXCEPTION Type
  - Bugfix for max[Object|Array]Depth when encoding nested array/object graphs
  - Bugfix for FB::setOptions()

2008-10-16 - Release Version: 0.2.b.7

  - (Issue 45) Truncate dump when string have non utf8 cars
  - (Issue 52) logging will not work when firephp object gets stored in the session.

2008-10-16 - Release Version: 0.2.b.6

  - (Issue 37) Display file and line information for each log message
  - (Issue 51) Limit output of object graphs
  - Bugfix for encoding object members set to NULL|false|''

2008-10-14 - Release Version: 0.2.b.5

  - Updated JsonStream wildfire protocol to be more robust
  - (Issue 33) PHP error notices running demos
  - (Issue 48) Warning: ReflectionProperty::getValue() expects exactly 1 parameter, 0 given

2008-10-08 - Release Version: 0.2.b.4

	- Bugfix for logging objects with recursion

2008-10-08 - Release Version: 0.2.b.3

  - (Issue 43) Notice message in 0.2b2
  - Added support for PHP's native json_encode() if available
  - Revised object encoder to detect object recursion

2008-10-07 - Release Version: 0.2.b.2

  - (Issue 28) Need solution for logging private and protected object variables
  - Added trace() and table() aliases in FirePHP class
  - (Issue 41) Use PHP doc in FirePHP
  - (Issue 39) Static logging method for object oriented API

2008-10-01 - Release Version: 0.2.b.1

  - Added support for error and exception handling
  - Updated min PHP version for PEAR package to 5.2
  - Added version constant for library
  - Gave server library it's own wildfire plugin namespace
  - Migrated communication protocol to Wildfire JsonStream
  - Added support for console groups using "group" and "groupEnd"
  - Added support for log, info, warn and error logging aliases
  - (Issue 29) problem with TRACE when using with error_handler
  - (Issue 33) PHP error notices running demos
  - (Issue 12) undefined index php notice
  - Removed closing ?> php tags
  - (Issue 13) the code in the fb() function has a second return statement that will never be reached

2008-07-30 - Release Version: 0.1.1.3

	- Include __className property in JSON string if variable was an object
	- Bugfix - Mis-spelt "Exception" in JSON encoding code

2008-06-13 - Release Version: 0.1.1.1

	- Bugfix - Standardize windows paths in stack traces
	- Bugfix - Display correct stack trace info in windows environments
	- Bugfix - Check $_SERVER['HTTP_USER_AGENT'] before returning

2008-06-13 - Release Version: 0.1.1

	- Added support for FirePHP::TRACE log style
	- Changed license to New BSD License

2008-06-06 - Release Version: 0.0.2

  - Bugfix - Added usleep() to header writing loop to ensure unique index
  - Bugfix - Ensure chunk_split does not generate trailing "\n" with empty data header
  - Added support for FirePHP::TABLE log style


code:
                         _______________________________
                         F  i  r  e  P  H  P  C  o  r  e

  Current Development
  -------------------

  Christoph Dorn <christoph@christophdorn.com>
  Michael Day    <manveru.alma@gmail.com>

  If you've done work on FirePHPCore and you are not listed here,
  please feel free to add yourself.

path: plugins/FirePHP/extlib/FirePHP/CREDITS


path: plugins/FirePHP/extlib/FirePHP/README