code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Superclass for plugins that do instant messaging
 *
 * 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  Plugin
 * @package   StatusNet
 * @author    Craig Andrews <candrews@integralblue.com>
 * @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);
}

/**
 * Superclass for plugins that do authentication
 *
 * Implementations will likely want to override onStartIoManagerClasses() so that their
 *   IO manager is used
 *
 * @category Plugin
 * @package  StatusNet
 * @author   Craig Andrews <candrews@integralblue.com>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
abstract class ImPlugin extends Plugin
{
    //name of this IM transport
    public $transport = null;
    //list of screennames that should get all public notices
    public $public = array();

    /**
     * normalize a screenname for comparison
     *
     * @param string $screenname screenname to normalize
     *
     * @return string an equivalent screenname in normalized form
     */
    abstract function normalize($screenname);

    /**
     * validate (ensure the validity of) a screenname
     *
     * @param string $screenname screenname to validate
     *
     * @return boolean
     */
    abstract function validate($screenname);

    /**
     * get the internationalized/translated display name of this IM service
     *
     * @return string
     */
    abstract function getDisplayName();

    /**
     * send a single notice to a given screenname
     * The implementation should put raw data, ready to send, into the outgoing
     *   queue using enqueueOutgoingRaw()
     *
     * @param string $screenname screenname to send to
     * @param Notice $notice notice to send
     *
     * @return boolean success value
     */
    function sendNotice($screenname, Notice $notice)
    {
        return $this->sendMessage($screenname, $this->formatNotice($notice));
    }

    /**
     * send a message (text) to a given screenname
     * The implementation should put raw data, ready to send, into the outgoing
     *   queue using enqueueOutgoingRaw()
     *
     * @param string $screenname screenname to send to
     * @param Notice $body text to send
     *
     * @return boolean success value
     */
    abstract function sendMessage($screenname, $body);

    /**
     * receive a raw message
     * Raw IM data is taken from the incoming queue, and passed to this function.
     * It should parse the raw message and call handleIncoming()
     *
     * Returning false may CAUSE REPROCESSING OF THE QUEUE ITEM, and should
     * be used for temporary failures only. For permanent failures such as
     * unrecognized addresses, return true to indicate your processing has
     * completed.
     *
     * @param object $data raw IM data
     *
     * @return boolean true if processing completed, false for temporary failures
     */
    abstract function receiveRawMessage($data);

    /**
     * get the screenname of the daemon that sends and receives message for this service
     *
     * @return string screenname of this plugin
     */
    abstract function daemonScreenname();

    /**
     * get the microid uri of a given screenname
     *
     * @param string $screenname screenname
     *
     * @return string microid uri
     */
    function microiduri($screenname)
    {
        return $this->transport . ':' . $screenname;
    }
    //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - MISC ========================\

    /**
     * Put raw message data (ready to send) into the outgoing queue
     *
     * @param object $data
     */
    function enqueueOutgoingRaw($data)
    {
        $qm = QueueManager::get();
        $qm->enqueue($data, $this->transport . '-out');
    }

    /**
     * Put raw message data (received, ready to be processed) into the incoming queue
     *
     * @param object $data
     */
    function enqueueIncomingRaw($data)
    {
        $qm = QueueManager::get();
        $qm->enqueue($data, $this->transport . '-in');
    }

    /**
     * given a screenname, get the corresponding user
     *
     * @param string $screenname
     *
     * @return User user
     */
    function getUser($screenname)
    {
        $user_im_prefs = $this->getUserImPrefsFromScreenname($screenname);
        if($user_im_prefs){
            $user = User::getKV('id', $user_im_prefs->user_id);
            $user_im_prefs->free();
            return $user;
        }else{
            return false;
        }
    }

    /**
     * given a screenname, get the User_im_prefs object for this transport
     *
     * @param string $screenname
     *
     * @return User_im_prefs user_im_prefs
     */
    function getUserImPrefsFromScreenname($screenname)
    {
        $user_im_prefs = User_im_prefs::pkeyGet(
            array('transport' => $this->transport,
                  'screenname' => $this->normalize($screenname)));
        if ($user_im_prefs) {
            return $user_im_prefs;
        } else {
            return false;
        }
    }

    /**
     * given a User, get their screenname
     *
     * @param User $user
     *
     * @return string screenname of that user
     */
    function getScreenname($user)
    {
        $user_im_prefs = $this->getUserImPrefsFromUser($user);
        if ($user_im_prefs) {
            return $user_im_prefs->screenname;
        } else {
            return false;
        }
    }

    /**
     * given a User, get their User_im_prefs
     *
     * @param User $user
     *
     * @return User_im_prefs user_im_prefs of that user
     */
    function getUserImPrefsFromUser($user)
    {
        $user_im_prefs = User_im_prefs::pkeyGet(
            array('transport' => $this->transport,
                  'user_id' => $user->id));
        if ($user_im_prefs){
            return $user_im_prefs;
        } else {
            return false;
        }
    }
    //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - SENDING ========================\
    /**
     * Send a message to a given screenname from the site
     *
     * @param string $screenname screenname to send the message to
     * @param string $msg message contents to send
     *
     * @param boolean success
     */
    protected function sendFromSite($screenname, $msg)
    {
        $text = '['.common_config('site', 'name') . '] ' . $msg;
        $this->sendMessage($screenname, $text);
    }

    /**
     * Send a confirmation code to a user
     *
     * @param string $screenname screenname sending to
     * @param string $code the confirmation code
     * @param User $user user sending to
     *
     * @return boolean success value
     */
    function sendConfirmationCode($screenname, $code, $user)
    {
        // TRANS: Body text for confirmation code e-mail.
        // TRANS: %1$s is a user nickname, %2$s is the StatusNet sitename,
        // TRANS: %3$s is the display name of an IM plugin.
        $body = sprintf(_('User "%1$s" on %2$s has said that your %3$s screenname belongs to them. ' .
          'If that is true, you can confirm by clicking on this URL: ' .
          '%4$s' .
          ' . (If you cannot click it, copy-and-paste it into the ' .
          'address bar of your browser). If that user is not you, ' .
          'or if you did not request this confirmation, just ignore this message.'),
          $user->nickname, common_config('site', 'name'), $this->getDisplayName(), common_local_url('confirmaddress', null, array('code' => $code)));

        return $this->sendMessage($screenname, $body);
    }

    /**
     * send a notice to all public listeners
     *
     * For notices that are generated on the local system (by users), we can optionally
     * forward them to remote listeners by XMPP.
     *
     * @param Notice $notice notice to broadcast
     *
     * @return boolean success flag
     */

    function publicNotice($notice)
    {
        // Now, users who want everything

        // FIXME PRIV don't send out private messages here
        // XXX: should we send out non-local messages if public,localonly
        // = false? I think not

        foreach ($this->public as $screenname) {
            common_log(LOG_INFO,
                       'Sending notice ' . $notice->id .
                       ' to public listener ' . $screenname,
                       __FILE__);
            $this->sendNotice($screenname, $notice);
        }

        return true;
    }

    /**
     * broadcast a notice to all subscribers and reply recipients
     *
     * This function will send a notice to all subscribers on the local server
     * who have IM addresses, and have IM notification enabled, and
     * have this subscription enabled for IM. It also sends the notice to
     * all recipients of @-replies who have IM addresses and IM notification
     * enabled. This is really the heart of IM distribution in StatusNet.
     *
     * @param Notice $notice The notice to broadcast
     *
     * @return boolean success flag
     */

    function broadcastNotice($notice)
    {
        $ni = $notice->whoGets();

        foreach ($ni as $user_id => $reason) {
            $user = User::getKV($user_id);
            if (empty($user)) {
                // either not a local user, or just not found
                continue;
            }
            $user_im_prefs = $this->getUserImPrefsFromUser($user);
            if(!$user_im_prefs || !$user_im_prefs->notify){
                continue;
            }

            switch ($reason) {
            case NOTICE_INBOX_SOURCE_REPLY:
                if (!$user_im_prefs->replies) {
                    continue 2;
                }
                break;
            case NOTICE_INBOX_SOURCE_SUB:
                $sub = Subscription::pkeyGet(array('subscriber' => $user->id,
                                                   'subscribed' => $notice->profile_id));
                if (empty($sub) || !$sub->jabber) {
                    continue 2;
                }
                break;
            case NOTICE_INBOX_SOURCE_GROUP:
                break;
            default:
                // TRANS: Exception thrown when trying to deliver a notice to an unknown inbox.
                // TRANS: %d is the unknown inbox ID (number).
                throw new Exception(sprintf(_('Unknown inbox source %d.'), $reason));
            }

            common_log(LOG_INFO,
                       'Sending notice ' . $notice->id . ' to ' . $user_im_prefs->screenname,
                       __FILE__);
            $this->sendNotice($user_im_prefs->screenname, $notice);
            $user_im_prefs->free();
        }

        return true;
    }

    /**
     * makes a plain-text formatted version of a notice, suitable for IM distribution
     *
     * @param Notice  $notice  notice being sent
     *
     * @return string plain-text version of the notice, with user nickname prefixed
     */

    protected function formatNotice(Notice $notice)
    {
        $profile = $notice->getProfile();

        try {
            $parent = $notice->getParent();
            $orig_profile = $parent->getProfile();
            $nicknames = sprintf('%1$s => %2$s', $profile->nickname, $orig_profile->nickname);
        } catch (Exception $e) {
            $nicknames = $profile->nickname;
        }

        return sprintf('%1$s: %2$s [%3$u]', $nicknames, $notice->content, $notice->id);
    }
    //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - RECEIVING ========================\

    /**
     * Attempt to handle a message as a command
     * @param User $user user the message is from
     * @param string $body message text
     * @return boolean true if the message was a command and was executed, false if it was not a command
     */
    protected function handleCommand($user, $body)
    {
        $inter = new CommandInterpreter();
        $cmd = $inter->handle_command($user, $body);
        if ($cmd) {
            $chan = new IMChannel($this);
            $cmd->execute($chan);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Is some text an autoreply message?
     * @param string $txt message text
     * @return boolean true if autoreply
     */
    protected function isAutoreply($txt)
    {
        if (preg_match('/[\[\(]?[Aa]uto[-\s]?[Rr]e(ply|sponse)[\]\)]/', $txt)) {
            return true;
        } else if (preg_match('/^System: Message wasn\'t delivered. Offline storage size was exceeded.$/', $txt)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Is some text an OTR message?
     * @param string $txt message text
     * @return boolean true if OTR
     */
    protected function isOtr($txt)
    {
        if (preg_match('/^\?OTR/', $txt)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Helper for handling incoming messages
     * Your incoming message handler will probably want to call this function
     *
     * @param string $from screenname the message was sent from
     * @param string $message message contents
     *
     * @param boolean success
     */
    protected function handleIncoming($from, $notice_text)
    {
        $user = $this->getUser($from);
        // For common_current_user to work
        global $_cur;
        $_cur = $user;

        if (!$user) {
            $this->sendFromSite($from, 'Unknown user; go to ' .
                             common_local_url('imsettings') .
                             ' to add your address to your account');
            common_log(LOG_WARNING, 'Message from unknown user ' . $from);
            return;
        }
        if ($this->handleCommand($user, $notice_text)) {
            common_log(LOG_INFO, "Command message by $from handled.");
            return;
        } else if ($this->isAutoreply($notice_text)) {
            common_log(LOG_INFO, 'Ignoring auto reply from ' . $from);
            return;
        } else if ($this->isOtr($notice_text)) {
            common_log(LOG_INFO, 'Ignoring OTR from ' . $from);
            return;
        } else {

            common_log(LOG_INFO, 'Posting a notice from ' . $user->nickname);

            $this->addNotice($from, $user, $notice_text);
        }

        $user->free();
        unset($user);
        unset($_cur);
        unset($message);
    }

    /**
     * Helper for handling incoming messages
     * Your incoming message handler will probably want to call this function
     *
     * @param string $from screenname the message was sent from
     * @param string $message message contents
     *
     * @param boolean success
     */
    protected function addNotice($screenname, $user, $body)
    {
        $body = trim(strip_tags($body));
        $content_shortened = common_shorten_links($body);
        if (Notice::contentTooLong($content_shortened)) {
          $this->sendFromSite($screenname,
                              // TRANS: Message given when a status is too long. %1$s is the maximum number of characters,
                              // TRANS: %2$s is the number of characters sent (used for plural).
                              sprintf(_m('Message too long - maximum is %1$d character, you sent %2$d.',
                                         'Message too long - maximum is %1$d characters, you sent %2$d.',
                                         Notice::maxContent()),
                                      Notice::maxContent(),
                                      mb_strlen($content_shortened)));
          return;
        }

        try {
            $notice = Notice::saveNew($user->id, $content_shortened, $this->transport);
        } catch (Exception $e) {
            common_log(LOG_ERR, $e->getMessage());
            $this->sendFromSite($from, $e->getMessage());
            return;
        }

        common_log(LOG_INFO,
                   'Added notice ' . $notice->id . ' from user ' . $user->nickname);
        $notice->free();
        unset($notice);
    }

    //========================EVENT HANDLERS========================\

    /**
     * Register notice queue handler
     *
     * @param QueueManager $manager
     *
     * @return boolean hook return
     */
    function onEndInitializeQueueManager($manager)
    {
        $manager->connect($this->transport . '-in', new ImReceiverQueueHandler($this), 'im');
        $manager->connect($this->transport, new ImQueueHandler($this));
        $manager->connect($this->transport . '-out', new ImSenderQueueHandler($this), 'im');
        return true;
    }

    function onStartImDaemonIoManagers(&$classes)
    {
        //$classes[] = new ImManager($this); // handles sending/receiving/pings/reconnects
        return true;
    }

    function onStartEnqueueNotice($notice, &$transports)
    {
        $profile = Profile::getKV($notice->profile_id);

        if (!$profile) {
            common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
                       'unknown profile ' . common_log_objstring($notice),
                       __FILE__);
        }else{
            $transports[] = $this->transport;
        }

        return true;
    }

    function onEndShowHeadElements($action)
    {
        $aname = $action->trimmed('action');

        if ($aname == 'shownotice') {

            $user_im_prefs = new User_im_prefs();
            $user_im_prefs->user_id = $action->profile->id;
            $user_im_prefs->transport = $this->transport;

            if ($user_im_prefs->find() && $user_im_prefs->fetch() && $user_im_prefs->microid && $action->notice->uri) {
                $id = new Microid($this->microiduri($user_im_prefs->screenname),
                                  $action->notice->uri);
                $action->element('meta', array('name' => 'microid',
                                             'content' => $id->toString()));
            }

        } else if ($aname == 'showstream') {

            $user_im_prefs = new User_im_prefs();
            $user_im_prefs->user_id = $action->user->id;
            $user_im_prefs->transport = $this->transport;

            if ($user_im_prefs->find() && $user_im_prefs->fetch() && $user_im_prefs->microid && $action->profile->profileurl) {
                $id = new Microid($this->microiduri($user_im_prefs->screenname),
                                  $action->selfUrl());
                $action->element('meta', array('name' => 'microid',
                                               'content' => $id->toString()));
            }
        }
    }

    function onNormalizeImScreenname($transport, &$screenname)
    {
        if($transport == $this->transport)
        {
            $screenname = $this->normalize($screenname);
            return false;
        }
    }

    function onValidateImScreenname($transport, $screenname, &$valid)
    {
        if($transport == $this->transport)
        {
            $valid = $this->validate($screenname);
            return false;
        }
    }

    function onGetImTransports(&$transports)
    {
        $transports[$this->transport] = array(
            'display' => $this->getDisplayName(),
            'daemonScreenname' => $this->daemonScreenname());
    }

    function onSendImConfirmationCode($transport, $screenname, $code, $user)
    {
        if($transport == $this->transport)
        {
            $this->sendConfirmationCode($screenname, $code, $user);
            return false;
        }
    }

    function onUserDeleteRelated($user, &$tables)
    {
        $tables[] = 'User_im_prefs';
        return true;
    }

    function onHaveImPlugin(&$haveImPlugin) {
        $haveImPlugin = true; // set flag true (we're loaded, after all!)
        return false; // stop looking
    }

    function initialize()
    {
        if( ! common_config('queue', 'enabled'))
        {
            // TRANS: Server exception thrown trying to initialise an IM plugin without meeting all prerequisites.
            throw new ServerException(_('Queueing must be enabled to use IM plugins.'));
        }

        if(is_null($this->transport)){
            // TRANS: Server exception thrown trying to initialise an IM plugin without a transport method.
            throw new ServerException(_('Transport cannot be null.'));
        }
    }
}


code:
<?php
/*
 * 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); }

/**
 * Common superclass for all IM sending queue handlers.
 */

class ImQueueHandler extends QueueHandler
{
    function __construct($plugin)
    {
        $this->plugin = $plugin;
    }

    /**
     * Handle a notice
     * @param Notice $notice
     * @return boolean success
     */
    function handle($notice)
    {
        $this->plugin->broadcastNotice($notice);
        if ($notice->is_local == Notice::LOCAL_PUBLIC ||
            $notice->is_local == Notice::LOCAL_NONPUBLIC) {
            $this->plugin->publicNotice($notice);
        }
        return true;
    }

}

license: mit


code:
<?php
/*
 * 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); }

/**
 * Common superclass for all IM receiving queue handlers.
 */

class ImReceiverQueueHandler extends QueueHandler
{
    function __construct($plugin)
    {
        $this->plugin = $plugin;
    }

    /**
     * Handle incoming IM data sent by a user to the IM bot
     * @param object $data
     * @return boolean success
     */
    function handle($data)
    {
        return $this->plugin->receiveRawMessage($data);
    }
}


code:
<?php
/*
 * 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); }

/**
 * Common superclass for all IM sending queue handlers.
 */

class ImSenderQueueHandler extends QueueHandler
{
    function __construct($plugin)
    {
        $this->plugin = $plugin;
    }

    /**
     * Handle outgoing IM data to be sent from the bot to a user
     * @param object $data
     * @return boolean success
     */
    function handle($data)
    {
        return $this->plugin->imManager->send_raw_message($data);
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Stream of notices for a profile's "all" feed
 *
 * 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  NoticeStream
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2011 StatusNet, Inc.
 * @copyright 2014 Free Software Foundation, 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); }

/**
 * Stream of notices for a profile's "all" feed
 *
 * @category  General
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2011 StatusNet, Inc.
 * @copyright 2014 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class InboxNoticeStream extends ScopingNoticeStream
{
    /**
     * Constructor
     *
     * @param Profile $target Profile to get a stream for
     * @param Profile $scoped Currently scoped profile (if null, it is fetched)
     */
    function __construct(Profile $target, Profile $scoped=null)
    {
        if ($scoped === null) {
            $scoped = Profile::current();
        }
        // FIXME: we don't use CachingNoticeStream - but maybe we should?
        parent::__construct(new CachingNoticeStream(new RawInboxNoticeStream($target), 'profileall'), $scoped);
    }
}

/**
 * Raw stream of notices for the target's inbox
 *
 * @category  General
 * @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 RawInboxNoticeStream extends NoticeStream
{
    protected $target  = null;
    protected $inbox = null;

    /**
     * Constructor
     *
     * @param Profile $target Profile to get a stream for
     */
    function __construct(Profile $target)
    {
        $this->target  = $target;
    }

    /**
     * Get IDs in a range
     *
     * @param int $offset   Offset from start
     * @param int $limit    Limit of number to get
     * @param int $since_id Since this notice
     * @param int $max_id   Before this notice
     *
     * @return Array IDs found
     */
    function getNoticeIds($offset, $limit, $since_id, $max_id)
    {
        $notice = new Notice();
        $notice->selectAdd();
        $notice->selectAdd('id');
        $notice->whereAdd(sprintf('notice.created > "%s"', $notice->escape($this->target->created)));
        // Reply:: is a table of mentions
        // Subscription:: is a table of subscriptions (every user is subscribed to themselves)
        $notice->whereAdd(
                sprintf('notice.id IN (SELECT notice_id FROM reply WHERE profile_id=%1$d) ' .
                        'OR notice.profile_id IN (SELECT subscribed FROM subscription WHERE subscriber=%1$d) ' .
                        'OR notice.id IN (SELECT notice_id FROM group_inbox WHERE group_id IN (SELECT group_id FROM group_member WHERE profile_id=%1$d))' .
                        'OR notice.id IN (SELECT notice_id FROM attention WHERE profile_id=%1$d)',
                    $this->target->id)
            );
        if (!empty($since_id)) {
            $notice->whereAdd(sprintf('notice.id > %d', $since_id));
        }
        if (!empty($max_id)) {
            $notice->whereAdd(sprintf('notice.id <= %d', $max_id));
        }
        if (!empty($this->selectVerbs)) {
            $notice->whereAddIn('verb', $this->selectVerbs, $notice->columnType('verb'));
        }
        $notice->limit($offset, $limit);
        // notice.id will give us even really old posts, which were
        // recently imported. For example if a remote instance had
        // problems and just managed to post here. Another solution
        // would be to have a 'notice.imported' field and order by it.
        $notice->orderBy('notice.id DESC');

        if (!$notice->find()) {
            return array();
        }

        $ids = $notice->fetchAll('id');

        return $ids;
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Personal tag cloud section
 *
 * 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 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);
}

/**
 * Personal tag cloud section
 *
 * @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 InboxTagCloudSection extends TagCloudSection
{
    const MAX_NOTICES = 1024;   // legacy value for "Inbox" table size when that existed

    protected $target = null;

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

    function title()
    {
        // TRANS: Title for inbox tag cloud section.
        return _m('TITLE', 'Trends');
    }

    function getTags()
    {
        $profile = Profile::current();

        $stream = new InboxNoticeStream($this->target, $profile);

        $ids = $stream->getNoticeIds(0, self::MAX_NOTICES, null, null);

        if (empty($ids)) {
            $tag = array();
        } else {
            $weightexpr = common_sql_weight('notice_tag.created', common_config('tag', 'dropoff'));
            // @fixme should we use the cutoff too? Doesn't help with indexing per-user.

            $qry = 'SELECT notice_tag.tag, '.
                $weightexpr . ' as weight ' .
                'FROM notice_tag JOIN notice ' .
                'ON notice_tag.notice_id = notice.id ' .
                'WHERE notice.id in (' . implode(',', $ids) . ')'.
                'GROUP BY notice_tag.tag ' .
                'ORDER BY weight DESC ';

            $limit = TAGS_PER_SECTION;
            $offset = 0;

            if (common_config('db','type') == 'pgsql') {
                $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
            } else {
                $qry .= ' LIMIT ' . $offset . ', ' . $limit;
            }

            $t = new Notice_tag();

            $t->query($qry);

            $tag = array();

            while ($t->fetch()) {
                $tag[] = clone($t);
            }
        }

        return new ArrayWrapper($tag);
    }

    function showMore()
    {
    }
}


code:
<?php

/**
 * Information action
 *
 * PHP version 5
 *
 * @category Action
 * @package  StatusNet
 * @author   Zach Copley <zach@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) 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/>.
 */

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

/**
 * Base class for displaying dialog box like messages to the user
 *
 * @category Action
 * @package  StatusNet
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
 * @see ErrorAction
 */

class InfoAction extends Action
{
    var $message = null;

    function __construct($title, $message, $output='php://output', $indent=null)
    {
        parent::__construct($output, $indent);

        $this->message = $message;
        $this->title   = $title;

        // XXX: hack alert: usually we aren't going to
        // call this page directly, but because it's
        // an action it needs an args array anyway
        $this->prepare($_REQUEST);
    }

    /**
     * Page title.
     *
     * @return page title
     */

    function title()
    {
        return empty($this->title) ? '' : $this->title;
    }

    function isReadOnly($args)
    {
        return true;
    }

    // Overload a bunch of stuff so the page isn't too bloated

    function showBody()
    {
        $this->elementStart('body', array('id' => 'error'));
        $this->elementStart('div', array('id' => 'wrap'));
        $this->showHeader();
        $this->showCore();
        $this->showFooter();
        $this->elementEnd('div');
        $this->elementEnd('body');
    }

    function showCore()
    {
        $this->elementStart('div', array('id' => 'core'));
        $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
        $this->elementStart('div', array('id' => 'content_wrapper'));
        $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
        $this->showContentBlock();
        $this->elementEnd('div');
        $this->elementEnd('div');
        $this->elementEnd('div');
        $this->elementEnd('div');
    }

    function showHeader()
    {
        $this->elementStart('div', array('id' => 'header'));
        $this->showLogo();
        $this->showPrimaryNav();
        $this->elementEnd('div');
    }

    /**
     * Display content.
     *
     * @return nothing
     */
    function showContent()
    {
        $this->element('div', array('class' => 'info'), $this->message);
    }

}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * widget for displaying notice attachments thumbnails
 *
 * 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  UI
 * @package   StatusNet
 * @author    Brion Vibber <brion@status.net>
 * @copyright 2010 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')) {
    exit(1);
}

class InlineAttachmentList extends AttachmentList
{
    function showListStart()
    {
        $this->out->element('h3', null, _('Attachments'));
        parent::showListStart();
    }

    /**
     * returns a new list item for the current attachment
     *
     * @param File $notice the current attachment
     *
     * @return ListItem a list item for displaying the attachment
     */
    function newListItem(File $attachment)
    {
        return new InlineAttachmentListItem($attachment, $this->out);
    }
}

class InlineAttachmentListItem extends AttachmentListItem
{
    function showLink() {
        $this->out->element('a', $this->linkAttr(), $this->title());
        $this->showRepresentation();
    }

    /**
     * start a single notice.
     *
     * @return void
     */
    function showStart()
    {
        // XXX: RDFa
        // TODO: add notice_type class e.g., notice_video, notice_image
        $this->out->elementStart('li', array('class' => 'inline-attachment'));
    }

    /**
     * finish the notice
     *
     * Close the last elements in the notice list item
     *
     * @return void
     */
    function showEnd()
    {
        $this->out->elementEnd('li');
    }
}


code:
<?php

/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2009-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/>.
 *
 * @category Installation
 * @package  Installation
 *
 * @author   Adrian Lang <mail@adrianlang.de>
 * @author   Brenda Wallace <shiny@cpan.org>
 * @author   Brett Taylor <brett@webfroot.co.nz>
 * @author   Brion Vibber <brion@pobox.com>
 * @author   CiaranG <ciaran@ciarang.com>
 * @author   Craig Andrews <candrews@integralblue.com>
 * @author   Eric Helgeson <helfire@Erics-MBP.local>
 * @author   Evan Prodromou <evan@status.net>
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @author   Robin Millette <millette@controlyourself.ca>
 * @author   Sarven Capadisli <csarven@status.net>
 * @author   Tom Adams <tom@holizz.com>
 * @author   Zach Copley <zach@status.net>
 * @copyright 2009-2010 StatusNet, Inc http://status.net
 * @copyright 2009-2014 Free Software Foundation, Inc http://www.fsf.org
 * @license  GNU Affero General Public License http://www.gnu.org/licenses/
 * @version  1.0.x
 * @link     http://status.net
 */

abstract class Installer
{
    /** Web site info */
    public $sitename, $server, $path, $fancy, $siteProfile, $ssl;
    /** DB info */
    public $host, $database, $dbtype, $username, $password, $db;
    /** Administrator info */
    public $adminNick, $adminPass, $adminEmail;
    /** Should we skip writing the configuration file? */
    public $skipConfig = false;

    public static $dbModules = array(
        'mysql' => array(
            'name' => 'MariaDB (or MySQL 5.5+)',
            'check_module' => 'mysqli',
            'scheme' => 'mysqli', // DSN prefix for PEAR::DB
        ),
/*        'pgsql' => array(
            'name' => 'PostgreSQL',
            'check_module' => 'pgsql',
            'scheme' => 'pgsql', // DSN prefix for PEAR::DB
        ),*/
    );

    /**
     * Attempt to include a PHP file and report if it worked, while
     * suppressing the annoying warning messages on failure.
     */
    private function haveIncludeFile($filename) {
        $old = error_reporting(error_reporting() & ~E_WARNING);
        $ok = include_once($filename);
        error_reporting($old);
        return $ok;
    }

    /**
     * Check if all is ready for installation
     *
     * @return void
     */
    function checkPrereqs()
    {
        $pass = true;

        $config = INSTALLDIR.'/config.php';
        if (file_exists($config)) {
            if (!is_writable($config) || filesize($config) > 0) {
                if (filesize($config) == 0) {
                    $this->warning('Config file "config.php" already exists and is empty, but is not writable.');
                } else {
                    $this->warning('Config file "config.php" already exists.');
                }
                $pass = false;
            }
        }

        if (version_compare(PHP_VERSION, '5.3.2', '<')) {
            $this->warning('Require PHP version 5.3.2 or greater.');
            $pass = false;
        }

        $reqs = array('gd', 'curl', 'json',
                      'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');

        foreach ($reqs as $req) {
            if (!$this->checkExtension($req)) {
                $this->warning(sprintf('Cannot load required extension: %s', $req));
                $pass = false;
            }
        }

        // Make sure we have at least one database module available
        $missingExtensions = array();
        foreach (self::$dbModules as $type => $info) {
            if (!$this->checkExtension($info['check_module'])) {
                $missingExtensions[] = $info['check_module'];
            }
        }

        if (count($missingExtensions) == count(self::$dbModules)) {
            $req = implode(', ', $missingExtensions);
            $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
            $pass = false;
        }

        // @fixme this check seems to be insufficient with Windows ACLs
        if (!is_writable(INSTALLDIR)) {
            $this->warning(sprintf('Cannot write config file to: %s
', INSTALLDIR),
                           sprintf('On your server, try this command: chmod a+w %s', INSTALLDIR));
            $pass = false;
        }

        // Check the subdirs used for file uploads
        $fileSubdirs = array('avatar', 'background', 'file');
        foreach ($fileSubdirs as $fileSubdir) {
            $fileFullPath = INSTALLDIR."/$fileSubdir/";
            if (!is_writable($fileFullPath)) {
                $this->warning(sprintf('Cannot write to %s directory: %s', $fileSubdir, $fileFullPath),
                               sprintf('On your server, try this command: chmod a+w %s', $fileFullPath));
                $pass = false;
            }
        }

        return $pass;
    }

    /**
     * Checks if a php extension is both installed and loaded
     *
     * @param string $name of extension to check
     *
     * @return boolean whether extension is installed and loaded
     */
    function checkExtension($name)
    {
        if (extension_loaded($name)) {
            return true;
        } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
            // dl will throw a fatal error if it's disabled or we're in safe mode.
            // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
            $soname = $name . '.' . PHP_SHLIB_SUFFIX;
            if (PHP_SHLIB_SUFFIX == 'dll') {
                $soname = "php_" . $soname;
            }
            return @dl($soname);
        } else {
            return false;
        }
    }

    /**
     * Basic validation on the database paramters
     * Side effects: error output if not valid
     *
     * @return boolean success
     */
    function validateDb()
    {
        $fail = false;

        if (empty($this->host)) {
            $this->updateStatus("No hostname specified.", true);
            $fail = true;
        }

        if (empty($this->database)) {
            $this->updateStatus("No database specified.", true);
            $fail = true;
        }

        if (empty($this->username)) {
            $this->updateStatus("No username specified.", true);
            $fail = true;
        }

        if (empty($this->sitename)) {
            $this->updateStatus("No sitename specified.", true);
            $fail = true;
        }

        return !$fail;
    }

    /**
     * Basic validation on the administrator user paramters
     * Side effects: error output if not valid
     *
     * @return boolean success
     */
    function validateAdmin()
    {
        $fail = false;

        if (empty($this->adminNick)) {
            $this->updateStatus("No initial user nickname specified.", true);
            $fail = true;
        }
        if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
            $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
                         '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
            $fail = true;
        }
        // @fixme hardcoded list; should use Nickname::isValid()
        // if/when it's safe to have loaded the infrastructure here
        $blacklist = array('main', 'panel', 'twitter', 'settings', 'rsd.xml', 'favorited', 'featured', 'favoritedrss', 'featuredrss', 'rss', 'getfile', 'api', 'groups', 'group', 'peopletag', 'tag', 'user', 'message', 'conversation', 'notice', 'attachment', 'search', 'index.php', 'doc', 'opensearch', 'robots.txt', 'xd_receiver.html', 'facebook');
        if (in_array($this->adminNick, $blacklist)) {
            $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
                         '" is reserved.', true);
            $fail = true;
        }

        if (empty($this->adminPass)) {
            $this->updateStatus("No initial user password specified.", true);
            $fail = true;
        }

        return !$fail;
    }

    /**
     * Make sure a site profile was selected
     *
     * @return type boolean success
     */
    function validateSiteProfile()
    {
        if (empty($this->siteProfile))  {
            $this->updateStatus("No site profile selected.", true);
            return false;
        }

        return true;
    }

    /**
     * Set up the database with the appropriate function for the selected type...
     * Saves database info into $this->db.
     *
     * @fixme escape things in the connection string in case we have a funny pass etc
     * @return mixed array of database connection params on success, false on failure
     */
    function setupDatabase()
    {
        if ($this->db) {
            throw new Exception("Bad order of operations: DB already set up.");
        }
        $this->updateStatus("Starting installation...");

        if (empty($this->password)) {
            $auth = '';
        } else {
            $auth = ":$this->password";
        }
        $scheme = self::$dbModules[$this->dbtype]['scheme'];
        $dsn = "{$scheme}://{$this->username}{$auth}@{$this->host}/{$this->database}";

        $this->updateStatus("Checking database...");
        $conn = $this->connectDatabase($dsn);

        // ensure database encoding is UTF8
        if ($this->dbtype == 'mysql') {
            // @fixme utf8m4 support for mysql 5.5?
            // Force the comms charset to utf8 for sanity
            // This doesn't currently work. :P
            //$conn->executes('set names utf8');
        } else if ($this->dbtype == 'pgsql') {
            $record = $conn->getRow('SHOW server_encoding');
            if ($record->server_encoding != 'UTF8') {
                $this->updateStatus("GNU social requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
                return false;
            }
        }

        if (!$conn instanceof DB_common) {
            // Is not the right instance
            throw new Exception('Cannot connect to database: ' . $conn->getMessage());
        }

        $res = $this->updateStatus("Creating database tables...");
        if (!$this->createCoreTables($conn)) {
            $this->updateStatus("Error creating tables.", true);
            return false;
        }

        foreach (array('sms_carrier' => 'SMS carrier',
                    'notice_source' => 'notice source',
                    'foreign_services' => 'foreign service')
              as $scr => $name) {
            $this->updateStatus(sprintf("Adding %s data to database...", $name));
            $res = $this->runDbScript($scr.'.sql', $conn);
            if ($res === false) {
                $this->updateStatus(sprintf("Can't run %s script.", $name), true);
                return false;
            }
        }

        $db = array('type' => $this->dbtype, 'database' => $dsn);
        return $db;
    }

    /**
     * Open a connection to the database.
     *
     * @param <type> $dsn
     * @return <type>
     */
    function connectDatabase($dsn)
    {
        global $_DB;
        return $_DB->connect($dsn);
    }

    /**
     * Create core tables on the given database connection.
     *
     * @param DB_common $conn
     */
    function createCoreTables(DB_common $conn)
    {
        $schema = Schema::get($conn);
        $tableDefs = $this->getCoreSchema();
        foreach ($tableDefs as $name => $def) {
            if (defined('DEBUG_INSTALLER')) {
                echo " $name ";
            }
            $schema->ensureTable($name, $def);
        }
        return true;
    }

    /**
     * Fetch the core table schema definitions.
     *
     * @return array of table names => table def arrays
     */
    function getCoreSchema()
    {
        $schema = array();
        include INSTALLDIR . '/db/core.php';
        return $schema;
    }

    /**
     * Return a parseable PHP literal for the given value.
     * This will include quotes for strings, etc.
     *
     * @param mixed $val
     * @return string
     */
    function phpVal($val)
    {
        return var_export($val, true);
    }

    /**
     * Return an array of parseable PHP literal for the given values.
     * These will include quotes for strings, etc.
     *
     * @param mixed $val
     * @return array
     */
    function phpVals($map)
    {
        return array_map(array($this, 'phpVal'), $map);
    }

    /**
     * Write a stock configuration file.
     *
     * @return boolean success
     *
     * @fixme escape variables in output in case we have funny chars, apostrophes etc
     */
    function writeConf()
    {
        $vals = $this->phpVals(array(
            'sitename' => $this->sitename,
            'server' => $this->server,
            'path' => $this->path,
            'ssl' => in_array($this->ssl, array('never', 'sometimes', 'always'))
                     ? $this->ssl
                     : 'never',
            'db_database' => $this->db['database'],
            'db_type' => $this->db['type']
        ));

        // assemble configuration file in a string
        $cfg =  "<?php\n".
                "if (!defined('GNUSOCIAL')) { exit(1); }\n\n".

                // site name
                "\$config['site']['name'] = {$vals['sitename']};\n\n".

                // site location
                "\$config['site']['server'] = {$vals['server']};\n".
                "\$config['site']['path'] = {$vals['path']}; \n\n".
                "\$config['site']['ssl'] = {$vals['ssl']}; \n\n".

                // checks if fancy URLs are enabled
                ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').

                // database
                "\$config['db']['database'] = {$vals['db_database']};\n\n".
                ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
                "\$config['db']['type'] = {$vals['db_type']};\n\n";

        // Normalize line endings for Windows servers
        $cfg = str_replace("\n", PHP_EOL, $cfg);

        // write configuration file out to install directory
        $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);

        return $res;
    }

    /**
     * Write the site profile. We do this after creating the initial user
     * in case the site profile is set to single user. This gets around the
     * 'chicken-and-egg' problem of the system requiring a valid user for
     * single user mode, before the intial user is actually created. Yeah,
     * we should probably do this in smarter way.
     *
     * @return int res number of bytes written
     */
    function writeSiteProfile()
    {
        $vals = $this->phpVals(array(
            'site_profile' => $this->siteProfile,
            'nickname' => $this->adminNick
        ));

        $cfg =
        // site profile
        "\$config['site']['profile'] = {$vals['site_profile']};\n";

        if ($this->siteProfile == "singleuser") {
            $cfg .= "\$config['singleuser']['nickname'] = {$vals['nickname']};\n\n";
        } else {
            $cfg .= "\n";
        }

        // Normalize line endings for Windows servers
        $cfg = str_replace("\n", PHP_EOL, $cfg);

        // write configuration file out to install directory
        $res = file_put_contents(INSTALLDIR.'/config.php', $cfg, FILE_APPEND);

        return $res;
    }

    /**
     * Install schema into the database
     *
     * @param string    $filename location of database schema file
     * @param DB_common $conn     connection to database
     *
     * @return boolean - indicating success or failure
     */
    function runDbScript($filename, DB_common $conn)
    {
        $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
        $stmts = explode(';', $sql);
        foreach ($stmts as $stmt) {
            $stmt = trim($stmt);
            if (!mb_strlen($stmt)) {
                continue;
            }
            try {
                $res = $conn->simpleQuery($stmt);
            } catch (Exception $e) {
                $error = $e->getMessage();
                $this->updateStatus("ERROR ($error) for SQL '$stmt'");
                return false;
            }
        }
        return true;
    }

    /**
     * Create the initial admin user account.
     * Side effect: may load portions of GNU social framework.
     * Side effect: outputs program info
     */
    function registerInitialUser()
    {
        require_once INSTALLDIR . '/lib/common.php';

        $data = array('nickname' => $this->adminNick,
                      'password' => $this->adminPass,
                      'fullname' => $this->adminNick);
        if ($this->adminEmail) {
            $data['email'] = $this->adminEmail;
        }
        $user = User::register($data);

        if (empty($user)) {
            return false;
        }

        // give initial user carte blanche

        $user->grantRole('owner');
        $user->grantRole('moderator');
        $user->grantRole('administrator');

        return true;
    }

    /**
     * The beef of the installer!
     * Create database, config file, and admin user.
     *
     * Prerequisites: validation of input data.
     *
     * @return boolean success
     */
    function doInstall()
    {
        global $config;

        $this->updateStatus("Initializing...");
        ini_set('display_errors', 1);
        error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
        if (!defined('GNUSOCIAL')) {
            define('GNUSOCIAL', true);
        }
        if (!defined('STATUSNET')) {
            define('STATUSNET', true);
        }

        require_once INSTALLDIR . '/lib/framework.php';
        StatusNet::initDefaults($this->server, $this->path);

        if ($this->siteProfile == "singleuser") {
            // Until we use ['site']['profile']==='singleuser' everywhere
            $config['singleuser']['enabled'] = true;
        }

        try {
            $this->db = $this->setupDatabase();
            if (!$this->db) {
                // database connection failed, do not move on to create config file.
                return false;
            }
        } catch (Exception $e) {
            // Lower-level DB error!
            $this->updateStatus("Database error: " . $e->getMessage(), true);
            return false;
        }

        // Make sure we can write to the file twice
        $oldUmask = umask(000);

        if (!$this->skipConfig) {
            $this->updateStatus("Writing config file...");
            $res = $this->writeConf();

            if (!$res) {
                $this->updateStatus("Can't write config file.", true);
                return false;
            }
        }

        if (!empty($this->adminNick)) {
            // Okay, cross fingers and try to register an initial user
            if ($this->registerInitialUser()) {
                $this->updateStatus(
                    "An initial user with the administrator role has been created."
                );
            } else {
                $this->updateStatus(
                    "Could not create initial user account.",
                    true
                );
                return false;
            }
        }

        if (!$this->skipConfig) {
            $this->updateStatus("Setting site profile...");
            $res = $this->writeSiteProfile();

            if (!$res) {
                $this->updateStatus("Can't write to config file.", true);
                return false;
            }
        }

        // Restore original umask
        umask($oldUmask);
        // Set permissions back to something decent
        chmod(INSTALLDIR.'/config.php', 0644);

        $scheme = $this->ssl === 'always' ? 'https' : 'http';
        $link = "{$scheme}://{$this->server}/{$this->path}";

        $this->updateStatus("GNU social has been installed at $link");
        $this->updateStatus(
            'DONE! You can visit your new GNU social site (log in as "'.htmlspecialchars($this->adminNick).'"). If this is your first GNU social install, make your experience the best possible by visiting our resource site to join the mailing list and good documentation.'
        );

        return true;
    }

    /**
     * Output a pre-install-time warning message
     * @param string $message HTML ok, but should be plaintext-able
     * @param string $submessage HTML ok, but should be plaintext-able
     */
    abstract function warning($message, $submessage='');

    /**
     * Output an install-time progress message
     * @param string $message HTML ok, but should be plaintext-able
     * @param boolean $error true if this should be marked as an error condition
     */
    abstract function updateStatus($status, $error=false);

}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when a URL is invalid
 *
 * 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  Exception
 * @package   StatusNet
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://status.net/
 */

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

/**
 * Class for an exception when a URL is invalid
 *
 * @category Exception
 * @package  GNUsocial
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link     http://status.net/
 */

class InvalidUrlException extends ServerException
{
    public $url = null;

    public function __construct($url)
    {
        $this->url = $url;
        // We could log an entry here with the search parameters
        parent::__construct(_('Invalid URL.'));
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Section for an invite button
 *
 * 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  Section
 * @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);
}

/**
 * Invite button
 *
 * @category  Section
 * @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 InviteButtonSection extends Section
{
    protected $buttonText;

    function __construct($out = null, $buttonText = null)
    {
        $this->out = $out;
        if (empty($buttonText)) {
            // TRANS: Default button text for inviting more users to the StatusNet instance.
            $this->buttonText = _m('BUTTON', 'Invite more colleagues');
        } else {
            $this->buttonText = $buttonText;
        }
    }

    function showTitle()
    {
        return false;
    }

    function divId()
    {
        return 'invite_button';
    }

    function showContent()
    {
        $this->out->element(
            'a',
            array(
                'href' => common_local_url('invite'),
                'class' => 'invite_button'
            ),
            $this->buttonText
        );
        return false;
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Form for inviting collegues and friends
 *
 * 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   StatusNet
 * @author    Zach Copley <zach@status.net>
 * @copyright 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')) {
    exit(1);
}

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

/**
 * Form for inviting collegues and friends
 *
 * @category Form
 * @package  StatusNet
 * @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 InviteForm extends Form
{
    /**
     * Constructor
     *
     * @param Action $out output channel
     */
    function __construct($out=null)
    {
        parent::__construct($out);
    }

    /**
     * ID of the form
     *
     * @return string ID of the form
     */
    function id()
    {
       return 'form_invite';
    }

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

    /**
     * Name of the form
     *
     * @return void
     */
    function formLegend()
    {
        // TRANS: Form legend.
        $this->out->element('legend', null, _('Invite collegues'));
    }

    /**
     * Data elements of the form
     *
     * @return void
     */
    function formData()
    {
        $this->out->elementStart('ul', 'form_data');
        $this->out->elementStart('li');
        $this->out->textarea(
            'addresses',
            // TRANS: Field label for a list of e-mail addresses.
            _('Email addresses'),
            $this->out->trimmed('addresses'),
            // TRANS: Field title for a list of e-mail addresses.
            _('Addresses of friends to invite (one per line).')
        );
        $this->out->elementEnd('li');
        $this->out->elementStart('li');
        $this->out->textarea(
            // TRANS: Field label for a personal message to send to invitees.
            'personal', _('Personal message'),
            $this->out->trimmed('personal'),
            // TRANS: Field title for a personal message to send to invitees.
            _('Optionally add a personal message to the invitation.')
        );
        $this->out->elementEnd('li');
        $this->out->elementEnd('ul');
    }

    /**
     * Action elements
     *
     * @return void
     */
    function formActions()
    {
        $this->out->submit(
            'send',
            // TRANS: Send button for inviting friends
            _m('BUTTON','Send'), 'submit form_action-primary',
            'send',
            // TRANS: Submit button title.
            _('Send invitations.')
        );
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Abstract class for i/o managers
 *
 * 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  QueueManager
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @author    Brion Vibber <brion@status.net>
 * @copyright 2009-2010 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/
 */

abstract class IoManager
{
    const SINGLE_ONLY = 0;
    const INSTANCE_PER_SITE = 1;
    const INSTANCE_PER_PROCESS = 2;

    /**
     * Factory function to get an appropriate subclass.
     */
    public static function get() {
        throw new MethodNotImplementedException(__METHOD__);
    }

    /**
     * Tell the i/o queue master if and how we can handle multi-site
     * processes.
     *
     * Return one of:
     *   IoManager::SINGLE_ONLY
     *   IoManager::INSTANCE_PER_SITE
     *   IoManager::INSTANCE_PER_PROCESS
     */
    public static function multiSite()
    {
        return IoManager::SINGLE_ONLY;
    }

    /**
     * If in a multisite configuration, the i/o master will tell
     * your manager about each site you'll have to handle so you
     * can do any necessary per-site setup.
     *
     * The new site will be the currently live configuration during
     * this call.
     */
    public function addSite()
    {
        /* no-op */
    }

    /**
     * This method is called when data is available on one of your
     * i/o manager's sockets. The socket with data is passed in,
     * in case you have multiple sockets.
     *
     * If your i/o manager is based on polling during idle processing,
     * you don't need to implement this.
     *
     * @param resource $socket
     * @return boolean true on success, false on failure
     */
    public function handleInput($socket)
    {
        return true;
    }

    /**
     * Return any open sockets that the run loop should listen
     * for input on. If input comes in on a listed socket,
     * the matching manager's handleInput method will be called.
     *
     * @return array of resources
     */
    function getSockets()
    {
        return array();
    }

    /**
     * Maximum planned time between poll() calls when input isn't waiting.
     * Actual time may vary!
     *
     * When we get a polling hit, the timeout will be cut down to 0 while
     * input is coming in, then will back off to this amount if no further
     * input shows up.
     *
     * By default polling is disabled; you must override this to enable
     * polling for this manager.
     *
     * @return int max poll interval in seconds, or 0 to disable polling
     */
    function pollInterval()
    {
        return 0;
    }

    /**
     * Request a maximum timeout for listeners before the next idle period.
     * Actual wait may be shorter, so don't go crazy in your idle()!
     * Wait could be longer if other handlers performed some slow activity.
     *
     * Return 0 to request that listeners return immediately if there's no
     * i/o and speed up the idle as much as possible; but don't do that all
     * the time as this will burn CPU.
     *
     * @return int seconds
     */
    function timeout()
    {
        return 60;
    }

    /**
     * Called by IoManager after each handled item or empty polling cycle.
     * This is a good time to e.g. service your XMPP connection.
     *
     * Doesn't need to be overridden if there's no maintenance to do.
     */
    function idle()
    {
        return true;
    }

    /**
     * The meat of a polling manager... check for something to do
     * and do it! Note that you should not take too long, as other
     * i/o managers may need to do some work too!
     *
     * On a successful hit, the next poll() call will come as soon
     * as possible followed by exponential backoff up to pollInterval()
     * if no more data is available.
     *
     * @return boolean true if events were hit
     */
    public function poll()
    {
        return false;
    }

    /**
     * Initialization, run when the queue manager starts.
     * If this function indicates failure, the handler run will be aborted.
     *
     * @param IoMaster $master process/event controller
     * @return boolean true on success, false on failure
     */
    public function start($master)
    {
        $this->master = $master;
        return true;
    }

    /**
     * Cleanup, run when the queue manager ends.
     * If this function indicates failure, a warning will be logged.
     *
     * @return boolean true on success, false on failure
     */
    public function finish()
    {
        return true;
    }

    /**
     * Ping iomaster's queue status monitor with a stats update.
     * Only valid during input loop!
     *
     * @param string $counter keyword for counter to increment
     */
    public function stats($counter, $owners=array())
    {
        $this->master->stats($counter, $owners);
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * I/O manager to wrap around socket-reading and polling queue & connection managers.
 *
 * 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  QueueManager
 * @package   StatusNet
 * @author    Brion Vibber <brion@status.net>
 * @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://status.net/
 */

abstract class IoMaster
{
    public $id;

    protected $multiSite = false;
    protected $managers = array();
    protected $singletons = array();

    protected $pollTimeouts = array();
    protected $lastPoll = array();

    public $shutdown = false; // Did we do a graceful shutdown?
    public $respawn = true; // Should we respawn after shutdown?

    /**
     * @param string $id process ID to use in logging/monitoring
     */
    public function __construct($id)
    {
        $this->id = $id;
        $this->monitor = new QueueMonitor();
    }

    public function init($multiSite=null)
    {
        if ($multiSite !== null) {
            $this->multiSite = $multiSite;
        }

        $this->initManagers();
    }

    /**
     * Initialize IoManagers which are appropriate to this instance;
     * pass class names or instances into $this->instantiate().
     *
     * If setup and configuration may vary between sites in multi-site
     * mode, it's the subclass's responsibility to set them up here.
     *
     * Switching site configurations is an acceptable side effect.
     */
    abstract function initManagers();

    /**
     * Instantiate an i/o manager class for the current site.
     * If a multi-site capable handler is already present,
     * we don't need to build a new one.
     *
     * @param mixed $manager class name (to run $class::get()) or object
     */
    protected function instantiate($manager)
    {
        if (is_string($manager)) {
            $manager = call_user_func(array($class, 'get'));
        }

        $caps = $manager->multiSite();
        if ($caps == IoManager::SINGLE_ONLY) {
            if ($this->multiSite) {
                throw new Exception("$class can't run with --all; aborting.");
            }
        } else if ($caps == IoManager::INSTANCE_PER_PROCESS) {
            $manager->addSite();
        }

        if (!in_array($manager, $this->managers, true)) {
            // Only need to save singletons once
            $this->managers[] = $manager;
        }
    }

    /**
     * Basic run loop...
     *
     * Initialize all io managers, then sit around waiting for input.
     * Between events or timeouts, pass control back to idle() method
     * to allow for any additional background processing.
     */
    function service()
    {
        $this->logState('init');
        $this->start();
        $this->checkMemory(false);

        while (!$this->shutdown) {
            $timeouts = array_values($this->pollTimeouts);
            $timeouts[] = 60; // default max timeout

            // Wait for something on one of our sockets
            $sockets = array();
            $managers = array();
            foreach ($this->managers as $manager) {
                foreach ($manager->getSockets() as $socket) {
                    $sockets[] = $socket;
                    $managers[] = $manager;
                }
                $timeouts[] = intval($manager->timeout());
            }

            $timeout = min($timeouts);
            if ($sockets) {
                $read = $sockets;
                $write = array();
                $except = array();
                $this->logState('listening');
                //common_debug("Waiting up to $timeout seconds for socket data...");
                $ready = stream_select($read, $write, $except, $timeout, 0);

                if ($ready === false) {
                    common_log(LOG_ERR, "Error selecting on sockets");
                } else if ($ready > 0) {
                    foreach ($read as $socket) {
                        $index = array_search($socket, $sockets, true);
                        if ($index !== false) {
                            $this->logState('queue');
                            $managers[$index]->handleInput($socket);
                        } else {
                            common_log(LOG_ERR, "Saw input on a socket we didn't listen to");
                        }
                    }
                }
            }

            if ($timeout > 0 && empty($sockets)) {
                // If we had no listeners, sleep until the pollers' next requested wakeup.
                common_log(LOG_DEBUG, "Sleeping $timeout seconds until next poll cycle...");
                $this->logState('sleep');
                sleep($timeout);
            }

            $this->logState('poll');
            $this->poll();

            $this->logState('idle');
            $this->idle();

            $this->checkMemory();
        }

        $this->logState('shutdown');
        $this->finish();
    }

    /**
     * Check runtime memory usage, possibly triggering a graceful shutdown
     * and thread respawn if we've crossed the soft limit.
     *
     * @param boolean $respawn if false we'll shut down instead of respawning
     */
    protected function checkMemory($respawn=true)
    {
        $memoryLimit = $this->softMemoryLimit();
        if ($memoryLimit > 0) {
            $usage = memory_get_usage();
            if ($usage > $memoryLimit) {
                common_log(LOG_INFO, "Queue thread hit soft memory limit ($usage > $memoryLimit); gracefully restarting.");
                if ($respawn) {
                    $this->requestRestart();
                } else {
                    $this->requestShutdown();
                }
            } else if (common_config('queue', 'debug_memory')) {
                $fmt = number_format($usage);
                common_log(LOG_DEBUG, "Memory usage $fmt");
            }
        }
    }

    /**
     * Return fully-parsed soft memory limit in bytes.
     * @return intval 0 or -1 if not set
     */
    function softMemoryLimit()
    {
        $softLimit = trim(common_config('queue', 'softlimit'));
        if (substr($softLimit, -1) == '%') {
            $limit = $this->parseMemoryLimit(ini_get('memory_limit'));
            if ($limit > 0) {
                return intval(substr($softLimit, 0, -1) * $limit / 100);
            } else {
                return -1;
            }
        } else {
            return $this->parseMemoryLimit($softLimit);
        }
        return $softLimit;
    }

    /**
     * Interpret PHP shorthand for memory_limit and friends.
     * Why don't they just expose the actual numeric value? :P
     * @param string $mem
     * @return int
     */
    public function parseMemoryLimit($mem)
    {
        // http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
        $mem = strtolower(trim($mem));
        $size = array('k' => 1024,
                      'm' => 1024*1024,
                      'g' => 1024*1024*1024);
        if (empty($mem)) {
            return 0;
        } else if (is_numeric($mem)) {
            return intval($mem);
        } else {
            $mult = substr($mem, -1);
            if (isset($size[$mult])) {
                return substr($mem, 0, -1) * $size[$mult];
            } else {
                return intval($mem);
            }
        }
    }

    function start()
    {
        foreach ($this->managers as $index => $manager) {
            $manager->start($this);
            // @fixme error check
            if ($manager->pollInterval()) {
                // We'll want to check for input on the first pass
                $this->pollTimeouts[$index] = 0;
                $this->lastPoll[$index] = 0;
            }
        }
    }

    function finish()
    {
        foreach ($this->managers as $manager) {
            $manager->finish();
            // @fixme error check
        }
    }

    /**
     * Called during the idle portion of the runloop to see which handlers
     */
    function poll()
    {
        foreach ($this->managers as $index => $manager) {
            $interval = $manager->pollInterval();
            if ($interval <= 0) {
                // Not a polling manager.
                continue;
            }

            if (isset($this->pollTimeouts[$index])) {
                $timeout = $this->pollTimeouts[$index];
                if (time() - $this->lastPoll[$index] < $timeout) {
                    // Not time to poll yet.
                    continue;
                }
            } else {
                $timeout = 0;
            }
            $hit = $manager->poll();

            $this->lastPoll[$index] = time();
            if ($hit) {
                // Do the next poll quickly, there may be more input!
                $this->pollTimeouts[$index] = 0;
            } else {
                // Empty queue. Exponential backoff up to the maximum poll interval.
                if ($timeout > 0) {
                    $timeout = min($timeout * 2, $interval);
                } else {
                    $timeout = 1;
                }
                $this->pollTimeouts[$index] = $timeout;
            }
        }
    }

    /**
     * Called after each handled item or empty polling cycle.
     * This is a good time to e.g. service your XMPP connection.
     */
    function idle()
    {
        foreach ($this->managers as $manager) {
            $manager->idle();
        }
    }

    /**
     * Send thread state update to the monitoring server, if configured.
     *
     * @param string $state ('init', 'queue', 'shutdown' etc)
     * @param string $substate (optional, eg queue name 'omb' 'sms' etc)
     */
    protected function logState($state, $substate='')
    {
        $this->monitor->logState($this->id, $state, $substate);
    }

    /**
     * Send thread stats.
     * Thread ID will be implicit; other owners can be listed as well
     * for per-queue and per-site records.
     *
     * @param string $key counter name
     * @param array $owners list of owner keys like 'queue:xmpp' or 'site:stat01'
     */
    public function stats($key, $owners=array())
    {
        $owners[] = "thread:" . $this->id;
        $this->monitor->stats($key, $owners);
    }

    /**
     * For IoManagers to request a graceful shutdown at end of event loop.
     */
    public function requestShutdown()
    {
        $this->shutdown = true;
        $this->respawn = false;
    }

    /**
     * For IoManagers to request a graceful restart at end of event loop.
     */
    public function requestRestart()
    {
        $this->shutdown = true;
        $this->respawn = true;
    }

}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Form for joining a group
 *
 * 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   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @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://status.net/
 */

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

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

/**
 * Form for joining a group
 *
 * @category Form
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Sarven Capadisli <csarven@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/
 *
 * @see      UnsubscribeForm
 */
class JoinForm extends Form
{
    /**
     * group for user to join
     */
    var $group = null;

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

        $this->group = $group;
    }

    /**
     * ID of the form
     *
     * @return string ID of the form
     */
    function id()
    {
        return 'group-join-' . $this->group->id;
    }

    /**
     * class of the form
     *
     * @return string of the form class
     */
    function formClass()
    {
        return 'form_group_join ajax';
    }

    /**
     * Action of the form
     *
     * @return string URL of the action
     */
    function action()
    {
        return common_local_url('joingroup',
                                array('id' => $this->group->id));
    }

    /**
     * Action elements
     *
     * @return void
     */
    function formActions()
    {
        // TRANS: Button text for joining a group.
        $this->out->submit('submit', _m('BUTTON','Join'));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * widget for displaying a list 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  Search
 * @package   StatusNet
 * @author    Zach Copley <zach@status.net>
 * @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://status.net/
 */

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

/**
 * widget-like class for showing JSON search results
 *
 * @category Search
 * @package  StatusNet
 * @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 JSONSearchResultsList
{
    protected $notice;  // protected attrs invisible to json_encode()
    protected $rpp;

    // The below attributes are carefully named so the JSON output from
    // this obj matches the output from search.twitter.com

    var $results;
    var $since_id;
    var $max_id;
    var $refresh_url;
    var $results_per_page;
    var $completed_in;
    var $page;
    var $query;

    /**
     * constructor
     *
     * @param Notice $notice   stream of notices from DB_DataObject
     * @param string $query    the original search query
     * @param int    $rpp      the number of results to display per page
     * @param int    $page     a page offset
     * @param int    $since_id only display notices newer than this
     */

    function __construct($notice, $query, $rpp, $page, $since_id = 0)
    {
        $this->notice           = $notice;
        $this->query            = urlencode($query);
        $this->results_per_page = $rpp;
        $this->rpp              = $rpp;
        $this->page             = $page;
        $this->since_id         = $since_id;
        $this->results          = array();
    }

    /**
     * show the list of search results
     *
     * @return int $count of the search results listed.
     */

    function show()
    {
        $cnt = 0;
        $this->max_id = 0;

        $time_start = microtime(true);

        while ($this->notice->fetch() && $cnt <= $this->rpp) {
            $cnt++;

            // XXX: Hmmm. this depends on desc sort order
            if (!$this->max_id) {
                $this->max_id = (int)$this->notice->id;
            }

            if ($this->since_id && $this->notice->id <= $this->since_id) {
                break;
            }

            if ($cnt > $this->rpp) {
                break;
            }

            $profile = $this->notice->getProfile();

            // Don't show notices from deleted users

            if (!empty($profile)) {
                $item = new ResultItem($this->notice);
                array_push($this->results, $item);
            }
        }

        $time_end           = microtime(true);
        $this->completed_in = $time_end - $time_start;

        // Set other attrs

        $this->refresh_url = '?since_id=' . $this->max_id .
            '&q=' . $this->query;

        // pagination stuff

        if ($cnt > $this->rpp) {
            $this->next_page = '?page=' . ($this->page + 1) .
                '&max_id=' . $this->max_id;
            if ($this->rpp != 15) {
                $this->next_page .= '&rpp=' . $this->rpp;
            }
            $this->next_page .= '&q=' . $this->query;
        }

        if ($this->page > 1) {
            $this->previous_page = '?page=' . ($this->page - 1) .
                '&max_id=' . $this->max_id;
            if ($this->rpp != 15) {
                $this->previous_page .= '&rpp=' . $this->rpp;
            }
            $this->previous_page .= '&q=' . $this->query;
        }

        print json_encode($this);

        return $cnt;
    }
}

/**
 * widget for displaying a single JSON search result
 *
 * @category UI
 * @package  StatusNet
 * @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/
 * @see      JSONSearchResultsList
 */

class ResultItem
{
    /** The notice this item is based on. */

    protected $notice;  // protected attrs invisible to json_encode()

    /** The profile associated with the notice. */

    protected $profile;

    // The below attributes are carefully named so the JSON output from
    // this obj matches the output from search.twitter.com

    var $text;
    var $to_user_id;
    var $to_user;
    var $from_user;
    var $id;
    var $from_user_id;
    var $iso_language_code;
    var $source;
    var $profile_image_url;
    var $created_at;

    /**
     * constructor
     *
     * Also initializes the profile attribute.
     *
     * @param Notice $notice The notice we'll display
     */

    function __construct($notice)
    {
        $this->notice  = $notice;
        $this->profile = $notice->getProfile();
        $this->buildResult();
    }

    /**
     * Build a search result object
     *
     * This populates the the result in preparation for JSON encoding.
     *
     * @return void
     */

    function buildResult()
    {
        $this->text      = $this->notice->content;
        $replier_profile = null;

        if ($this->notice->reply_to) {
            $reply = Notice::getKV(intval($this->notice->reply_to));
            if ($reply) {
                $replier_profile = $reply->getProfile();
            }
        }

        $this->to_user_id = ($replier_profile) ?
            intval($replier_profile->id) : null;
        $this->to_user    = ($replier_profile) ?
            $replier_profile->nickname : null;

        $this->from_user    = $this->profile->nickname;
        $this->id           = $this->notice->id;
        $this->from_user_id = $this->profile->id;

        $this->iso_language_code = Profile_prefs::getConfigData($this->profile, 'site', 'language');

        $this->source = $this->getSourceLink($this->notice->source);

        $this->profile_image_url = $this->profile->avatarUrl(AVATAR_STREAM_SIZE);

        $this->created_at = common_date_rfc2822($this->notice->created);
    }

    /**
     * Show the source of the notice
     *
     * Either the name (and link) of the API client that posted the notice,
     * or one of other other channels.
     *
     * @param string $source the source of the Notice
     *
     * @return string a fully rendered source of the Notice
     */
    function getSourceLink($source)
    {
        // Gettext translations for the below source types are available.
        $source_name = _($source);
        switch ($source) {
        case 'web':
        case 'xmpp':
        case 'mail':
        case 'omb':
        case 'api':
            break;
        default:
            $ns = Notice_source::getKV($source);
            if ($ns instanceof Notice_source) {
                $source_name = 'url . '">' . $ns->name . '';
            }
            break;
        }

        return $source_name;
    }
}