domainstatusnetworkinstaller.php 9.54 KB
Newer Older
1 2 3 4 5 6
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Installer class for domain-based multi-homing systems
Siebrand Mazeland's avatar
Siebrand Mazeland committed
7
 *
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
 * 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  DomainStatusNetwork
 * @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);
}

/**
 * Installer class for domain-based multi-homing systems
 *
 * @category  DomainStatusNetwork
 * @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 DomainStatusNetworkInstaller extends Installer
{
    protected $domain   = null;
    protected $rootname = null;
    protected $sitedb   = null;
    protected $rootpass = null;
    protected $nickname = null;
    protected $sn       = null;
55 56

    public $verbose     = false;
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

    function __construct($domain)
    {
        $this->domain = $domain;
    }

    /**
     * Go for it!
     * @return boolean success
     */
    function main()
    {
        // We don't check prereqs. Check 'em before setting up a
        // multi-home system, kthxbi
        if ($this->prepare()) {
            return $this->handle();
        } else {
            $this->showHelp();
            return false;
        }
    }

    /**
     * Get our input parameters...
     * @return boolean success
     */
    function prepare()
    {
        $config = $this->getConfig();

        $this->nickname = DomainStatusNetworkPlugin::nicknameForDomain($this->domain);

        // XXX make this configurable

        $this->sitename = sprintf('The %s Status Network', $this->domain);

        $this->server   = $this->nickname.'.'.$config['WILDCARD'];
        $this->path     = null;
        $this->fancy    = true;

97 98
        $datanick = $this->databaseize($this->nickname);

99
        $this->host     = $config['DBHOSTNAME'];
100
        $this->database = $datanick.$config['DBBASE'];
101
        $this->dbtype   = 'mysql'; // XXX: support others... someday
102 103 104 105 106 107 108
        $this->username = $datanick.$config['USERBASE'];

        // Max size for MySQL

        if (strlen($this->username) > 16) {
            $this->username = sprintf('%s%08x', substr($this->username, 0, 8), crc32($this->username));
        }
109 110 111 112 113 114 115 116 117 118 119

        $pwgen = $config['PWDGEN'];

        $password = `$pwgen`;

        $this->password = trim($password);

        // For setting up the database

        $this->rootname = $config['ADMIN'];
        $this->rootpass = $config['ADMINPASS'];
Evan Prodromou's avatar
Evan Prodromou committed
120
        $this->sitehost = $config['SITEDBHOSTNAME'];
121 122
        $this->sitedb   = $config['SITEDB'];

123 124 125 126 127 128 129 130
        $tagstr = $config['TAGS'];

        if (!empty($tagstr)) {
            $this->tags = preg_split('/[\s,]+/', $tagstr);
        } else {
            $this->tags = array();
        }

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
        // Explicitly empty

        $this->adminNick    = null;
        $this->adminPass    = null;
        $this->adminEmail   = null;
        $this->adminUpdates = null;

        /** Should we skip writing the configuration file? */
        $this->skipConfig = true;

        if (!$this->validateDb()) {
            return false;
        }

        return true;
    }

    function handle()
    {
        return $this->doInstall();
    }

    function setupDatabase()
    {
155
        $this->updateStatus('Creating database...');
156 157
        $this->createDatabase();
        parent::setupDatabase();
158
        $this->updateStatus('Creating file directories...');
159
        $this->createDirectories();
160
        $this->updateStatus('Saving status network...');
161
        $this->saveStatusNetwork();
162
        $this->updateStatus('Checking schema for plugins...');
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        $this->checkSchema();
    }

    function saveStatusNetwork()
    {
        Status_network::setupDB($this->sitehost,
                                $this->rootname,
                                $this->rootpass,
                                $this->sitedb, array());

        $sn = new Status_network();

        $sn->nickname = $this->nickname;
        $sn->dbhost   = $this->host;
        $sn->dbuser   = $this->username;
        $sn->dbpass   = $this->password;
        $sn->dbname   = $this->database;
180
        $sn->sitename = $this->sitename;
Evan Prodromou's avatar
Evan Prodromou committed
181
        $sn->created  = common_sql_now();
182 183 184 185

        $result = $sn->insert();

        if (!$result) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
186
            throw new ServerException("Could not create status_network: " . print_r($sn, true));
187 188
        }

189 190 191 192 193 194 195 196
        // Re-fetch; stupid auto-increment integer isn't working

        $sn = Status_network::staticGet('nickname', $sn->nickname);

        if (empty($sn)) {
            throw new ServerException("Created {$this->nickname} status_network and could not find it again.");
        }

197 198 199 200 201 202 203 204 205
        // Set default tags

        $tags = $this->tags;

        // Add domain tag

        $tags[] = 'domain='.$this->domain;

        $sn->setTags($tags);
206 207 208

        $this->sn = $sn;
    }
Siebrand Mazeland's avatar
Siebrand Mazeland committed
209

210 211 212 213 214 215 216 217
    function checkSchema()
    {
        $config = $this->getConfig();

        Status_network::$wildcard = $config['WILDCARD'];

        StatusNet::switchSite($this->nickname);

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        // We need to initialize the schema_version stuff to make later setup easier

        $schema = array();
        require INSTALLDIR.'/db/core.php';
        $tableDefs = $schema;

        $schema = Schema::get();
        $schemaUpdater = new SchemaUpdater($schema);

        foreach ($tableDefs as $table => $def) {
            $schemaUpdater->register($table, $def);
        }

        $schemaUpdater->checkSchema();

233 234 235 236 237 238 239 240 241 242 243 244 245 246
        Event::handle('CheckSchema');
    }

    function getStatusNetwork()
    {
        return $this->sn;
    }

    function createDirectories()
    {
        $config = $this->getConfig();

        foreach (array('AVATARBASE', 'BACKGROUNDBASE', 'FILEBASE') as $key) {
            $base = $config[$key];
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            $dirname = $base.'/'.$this->nickname;

            // Make sure our bits are set
            $mask = umask(0);
            mkdir($dirname, 0770, true);
            umask($mask);

            // If you set the setuid bit on your base dirs this should be
            // unnecessary, but just in case. You must be root for this
            // to work.

            if (array_key_exists('WEBUSER', $config)) {
                chown($dirname, $config['WEBUSER']);
            }
            if (array_key_exists('WEBGROUP', $config)) {
                chgrp($dirname, $config['WEBGROUP']);
            }
264 265 266 267 268 269 270 271
        }
    }

    function createDatabase()
    {
        // Create the New DB
        $res = mysql_connect($this->host, $this->rootname, $this->rootpass);
        if (!$res) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
272
            throw new ServerException("Cannot connect to {$this->host} as {$this->rootname}.");
273 274 275 276 277 278 279
        }

        mysql_query("CREATE DATABASE ". mysql_real_escape_string($this->database), $res);

        $return = mysql_select_db($this->database, $res);

        if (!$return) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
280
            throw new ServerException("Unable to connect to {$this->database} on {$this->host}.");
281 282 283
        }

        foreach (array('localhost', '%') as $src) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
284
            mysql_query("GRANT ALL ON " .
285 286 287 288 289 290 291 292 293 294 295
                        mysql_real_escape_string($this->database).".* TO '" .
                        $this->username . "'@'".$src."' ".
                        "IDENTIFIED BY '".$this->password."'", $res);
        }

        mysql_close($res);
    }

    function getConfig()
    {
        static $config;
Siebrand Mazeland's avatar
Siebrand Mazeland committed
296

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
        $cfg_file = "/etc/statusnet/setup.cfg";

        if (empty($config)) {
            $result = parse_ini_file($cfg_file);

            $config = array();
            foreach ($result as $key => $value) {
                $key = str_replace('export ', '', $key);
                $config[$key] = $value;
            }
        }

        return $config;
    }

    function showHelp()
    {
    }

    function warning($message, $submessage='')
    {
        print $this->html2text($message) . "\n";
        if ($submessage != '') {
            print "  " . $this->html2text($submessage) . "\n";
        }
        print "\n";
    }

    function updateStatus($status, $error=false)
    {
        if ($this->verbose || $error) {
            if ($error) {
                print "ERROR: ";
            }
            print $this->html2text($status);
            print "\n";
        }
    }

    private function html2text($html)
    {
        // break out any links for text legibility
        $breakout = preg_replace('/<a[^>+]\bhref="(.*)"[^>]*>(.*)<\/a>/',
                                 '\2 &lt;\1&gt;',
                                 $html);
        return html_entity_decode(strip_tags($breakout), ENT_QUOTES, 'UTF-8');
    }
344 345 346 347 348 349

    function databaseize($nickname)
    {
        $nickname = str_replace('-', '_', $nickname);
        return $nickname;
    }
350
}