public function monitor($file, $channel)
 {
     if (false === ($fp = @fopen($file, "r"))) {
         Cli::error("Failed to open {$file}");
     } else {
         Cli::out("Monitoring file: {$file}");
     }
     while (1) {
         if (-1 === fseek($fp, 0, SEEK_END) or !($pos = ftell($fp))) {
             goto retry;
         }
         if ($this->lastPosition === null or $this->lastPosition > $pos) {
             $this->lastPosition = $pos;
             goto retry;
         }
         if ($this->lastPosition < $pos) {
             fseek($fp, $this->lastPosition - $pos, SEEK_CUR);
             if (false === ($content = fread($fp, $pos - $this->lastPosition))) {
                 goto retry;
             }
             try {
                 $this->client->send($content, $channel);
             } catch (\Exception $ex) {
                 Cli::error($ex->getMessage());
             }
             $this->lastPosition = $pos;
         }
         retry:
         usleep(200000);
     }
 }
Exemple #2
0
 function test_out()
 {
     // default
     ob_start();
     Cli::out('Some text.');
     $out = ob_get_clean();
     $this->assertEquals("Some text.\n", $out);
     // no newline
     ob_start();
     Cli::out('Some text.', 'default', '');
     $out = ob_get_clean();
     $this->assertEquals("Some text.", $out);
     // info message
     ob_start();
     Cli::out('Some text.', 'info');
     $out = ob_get_clean();
     $this->assertEquals("Some text.\n", $out);
     // success message
     ob_start();
     Cli::out('Some text.', 'success');
     $out = ob_get_clean();
     $this->assertEquals("Some text.\n", $out);
     // error message
     ob_start();
     Cli::out('Some text.', 'error');
     $out = ob_get_clean();
     $this->assertEquals("Some text.\n", $out);
 }
 public function onTask($server, $task_id, $from, $data)
 {
     Cli::out("Task #{$task_id} started.");
     $json = json_decode($data, true);
     foreach ($this->subscribers as $fd => $row) {
         if (empty($json['channel']) or empty($row['channel']) or false !== strpos(',' . $row['channel'] . ',', ',' . $json['channel'] . ',')) {
             $this->server->push($fd, $data);
         }
     }
     return true;
 }
 protected function process($data, $source)
 {
     if (false === ($array = $this->parseMessage($data))) {
         Cli::out("Invalid data.");
         return;
     }
     if (array_key_exists($array['cmd'], $this->handlers)) {
         call_user_func($this->handlers[$array['cmd']], $array, $source, $data);
     } else {
         Cli::out(sprintf("Unknown cmd [%s].", $array['cmd']));
     }
 }
Exemple #5
0
    // list settings in section
    if (count($parts) === 1) {
        list($section) = $parts;
        if (!preg_match($valid_section_name, $section)) {
            Cli::out('Invalid section name: ' . $section, 'error');
            return;
        }
        $settings = conf($section);
        $names = array_keys($settings);
        sort($names);
        echo join(', ', $names) . "\n";
        // show specific setting (encoded as JSON value)
    } elseif (count($parts) === 2) {
        list($section, $setting) = $parts;
        if (!preg_match($valid_section_name, $section)) {
            Cli::out('Invalid section name: ' . $section, 'error');
            return;
        }
        if (!preg_match($valid_setting_name, $setting)) {
            Cli::out('Invalid setting name: ' . $setting, 'error');
            return;
        }
        $value = conf($section, $setting);
        if (!defined('JSON_PRETTY_PRINT')) {
            define('JSON_PRETTY_PRINT', 0);
        }
        echo json_encode($value, JSON_PRETTY_PRINT) . "\n";
    } else {
        Cli::out('Invalid setting value: ' . $_SERVER['argv'][2], 'error');
    }
}
Exemple #6
0
            echo "See conf/updates/error.log for details.\n";
            file_put_contents('conf/updates/error.log', $output);
            return;
        }
        // Patch is okay to apply
        echo "Patch ok, applying...\n";
        exec('patch -p1 -f -i ' . $version['patch']);
        // Apply associated database updates
        if ($version['script']) {
            printf("Applying db update: %s\n", basename($version['script']));
            $sqldata = sql_split(file_get_contents($version['script']));
            DB::beginTransaction();
            foreach ($sqldata as $sql) {
                if (!DB::execute($sql)) {
                    $error = DB::error();
                    DB::rollback();
                    Cli::out('Error applying db update: ' . $version['script'], 'error');
                    echo "See conf/updates/error.log for details.\n";
                    file_put_contents('conf/updates/error.log', $error);
                    return;
                }
            }
            DB::commit();
        }
    }
    Cli::out(sprintf("Applied %d updates.", count($versions)), 'success');
}
// Upgrade the apps that were specified as well
foreach ($update_apps as $app) {
    // TODO: Implement me
}
<?php

/**
 * Generates a random password of the specified length
 * (default is 8 characters), using random lower- and
 * upper-case letters, numbers, and symbols.
 */
if (!$this->cli) {
    die('Must be run from the command line.');
}
$page->layout = false;
require_once 'apps/cli/lib/Functions.php';
if (isset($_SERVER['argv'][2])) {
    if (!is_numeric($_SERVER['argv'][2])) {
        Cli::out('Usage: ./elefant generate-password <length|8>', 'info');
        die;
    }
    $length = $_SERVER['argv'][2];
} else {
    $length = 8;
}
echo generate_password($length) . "\n";
Exemple #8
0
    }
}
$data = array('appname' => $name, 'plural' => $plural, 'fields' => $fields, 'pkey' => $pkey, 'open_tag' => '<?php', 'close_tag' => '?>', 'backslash' => '\\');
mkdir('apps/' . $plural . '/conf', 0755, true);
mkdir('apps/' . $plural . '/forms', 0755, true);
mkdir('apps/' . $plural . '/handlers', 0755, true);
mkdir('apps/' . $plural . '/lib', 0755, true);
mkdir('apps/' . $plural . '/models', 0755, true);
mkdir('apps/' . $plural . '/views', 0755, true);
require_once 'apps/cli/lib/CRUDHelpers.php';
file_put_contents('apps/' . $plural . '/conf/config.php', $tpl->render('cli/crud-app/config', $data));
file_put_contents('apps/' . $plural . '/conf/acl.php', $tpl->render('cli/crud-app/acl', $data));
file_put_contents('apps/' . $plural . '/conf/install_mysql.sql', $tpl->render('cli/crud-app/install_mysql', $data));
file_put_contents('apps/' . $plural . '/conf/install_pgsql.sql', $tpl->render('cli/crud-app/install_pgsql', $data));
file_put_contents('apps/' . $plural . '/conf/install_sqlite.sql', $tpl->render('cli/crud-app/install_sqlite', $data));
file_put_contents('apps/' . $plural . '/forms/add.php', $tpl->render('cli/crud-app/add_form', $data));
file_put_contents('apps/' . $plural . '/forms/edit.php', $tpl->render('cli/crud-app/edit_form', $data));
file_put_contents('apps/' . $plural . '/models/' . cli\Filter::camel($name) . '.php', $tpl->render('cli/crud-app/model', $data));
file_put_contents('apps/' . $plural . '/handlers/admin.php', $tpl->render('cli/crud-app/admin_handler', $data));
file_put_contents('apps/' . $plural . '/handlers/index.php', $tpl->render('cli/crud-app/index_handler', $data));
file_put_contents('apps/' . $plural . '/handlers/add.php', $tpl->render('cli/crud-app/add_handler', $data));
file_put_contents('apps/' . $plural . '/handlers/edit.php', $tpl->render('cli/crud-app/edit_handler', $data));
file_put_contents('apps/' . $plural . '/handlers/delete.php', $tpl->render('cli/crud-app/delete_handler', $data));
file_put_contents('apps/' . $plural . '/handlers/install.php', $tpl->render('cli/crud-app/install_handler', $data));
file_put_contents('apps/' . $plural . '/handlers/upgrade.php', $tpl->render('cli/crud-app/upgrade_handler', $data));
file_put_contents('apps/' . $plural . '/views/index.html', $tpl->render('cli/crud-app/index_view', $data));
file_put_contents('apps/' . $plural . '/views/add.html', $tpl->render('cli/crud-app/add_view', $data));
file_put_contents('apps/' . $plural . '/views/edit.html', $tpl->render('cli/crud-app/edit_view', $data));
file_put_contents('apps/' . $plural . '/views/admin.html', $tpl->render('cli/crud-app/admin_view', $data));
Cli::out('App created in apps/' . $plural, 'success');
Exemple #9
0
<?php

/**
 * This command imports a schema file into the database.
 */
if (!$this->cli) {
    die('Must be run from the command line.');
}
$page->layout = false;
if (!isset($_SERVER['argv'][2])) {
    Cli::out('Usage: ./elefant import-db <file>', 'info');
    die;
}
$file = $_SERVER['argv'][2];
if (!file_exists($file)) {
    Cli::out('** Error: File not found: ' . $file, 'error');
    die;
}
// import the database schema
$sqldata = sql_split(file_get_contents($file));
DB::beginTransaction();
foreach ($sqldata as $sql) {
    if (!DB::execute($sql)) {
        Cli::out('** Error: ' . DB::error(), 'error');
        DB::rollback();
        return;
    }
}
DB::commit();
Cli::out(count($sqldata) . ' commands executed.', 'success');
Exemple #10
0
 /**
  * Initialize a progress bar
  *
  * @param mixed $total   number of times we're going to call set
  * @param int   $message message to prefix the bar with
  * @param int   $options overrides for default options
  *
  * @static
  * @return string - the progress bar string with 0 progress
  */
 public static function start($total = null, $message = '', $options = array())
 {
     if ($message) {
         $options['message'] = $message;
     }
     $options['total'] = $total;
     $options['start'] = time();
     self::reset($options);
     Cli::out(self::display());
 }
Exemple #11
0
<?php

/**
 * Generate or reset an API token and secret key for the specified user.
 * Note that resetting an API token and secret key will cause any use
 * of the old one to fail.
 */
if (!$this->cli) {
    die("Must be run from the command line.\n");
}
$page->layout = false;
if (!isset($_SERVER['argv'][2])) {
    Cli::out('Usage: ./elefant api/create-token <user-id>', 'info');
    return;
}
$user = new User($_SERVER['argv'][2]);
if ($user->error) {
    Cli::out('Error: User not found.', 'error');
    return;
}
list($token, $key) = api\Api::create_token($user->id);
echo $token . ':' . $key . "\n";
Exemple #12
0
 */
if (!$this->cli) {
    die('Must be run from the command line.');
}
$page->layout = false;
if (!isset($_SERVER['argv'][2])) {
    Cli::out('Usage: ./elefant backup <path>', 'info');
    die;
}
$path = $_SERVER['argv'][2];
if (!is_dir($path)) {
    Cli::out('** Error: Specified path is not a folder.', 'error');
    die;
}
if (!is_writeable($path)) {
    Cli::out('** Error: Specified folder is not writeable.', 'error');
    die;
}
// add trailing slash
$path = preg_match('/\\/$/', $path) ? $path : $path . '/';
date_default_timezone_set('GMT');
$ts = gmdate('Y-m-d-H-i-s');
if (!@is_dir('.backups')) {
    mkdir('.backups');
    file_put_contents('.backups/.htaccess', "Order allow,deny\nDeny from all\n");
}
mkdir('.backups/backup-' . $ts);
exec('./elefant export-db .backups/backup-' . $ts . '/dump.sql');
copy('.htaccess', '.backups/backup-' . $ts . '/.htaccess');
exec('cp -R * .backups/backup-' . $ts . '/');
chdir('.backups');
Exemple #13
0
 * Show the documentation for a helper, found in the first comment
 * block in the source file.
 */
if (!$this->cli) {
    die('Must be run from the command line.');
}
$page->layout = false;
if (!isset($_SERVER['argv'][2])) {
    Cli::out('Usage: ./elefant helper-docs <helper>', 'error');
    die;
}
$helper = $_SERVER['argv'][2];
list($app, $handler) = explode('/', $helper, 2);
$route = 'apps/' . $app . '/handlers/' . $handler . '.php';
if (!file_exists($route)) {
    Cli::out('Helper not found in ' . $route, 'error');
    die;
}
echo "\n# Helper: " . $helper . "\n\n";
// Get the comment itself
$comments = array_filter(token_get_all(file_get_contents($route)), function ($entry) {
    return $entry[0] == T_DOC_COMMENT;
});
$comments = array_shift($comments);
if (!isset($comments[1])) {
    echo "No documentation found.\n\n";
    die;
}
$docs = $comments[1];
// remove comment block tags
$docs = preg_replace('/^\\/\\*\\*?/', '', $docs);
Exemple #14
0
        if (isset($_SERVER['argv'][2])) {
            exec('sqlite3 ' . $conf['Database']['master']['file'] . ' .dump > ' . $_SERVER['argv'][2]);
        } else {
            passthru('sqlite3 ' . $conf['Database']['master']['file'] . ' .dump');
        }
        break;
    case 'mysql':
        // get port number
        list($host, $port) = strpos($conf['Database']['master']['host'], ':') !== false ? explode(':', $conf['Database']['master']['host']) : array($conf['Database']['master']['host'], 3306);
        if (isset($_SERVER['argv'][2])) {
            exec(sprintf('mysqldump --password=%s -u %s -h %s -P %d %s > %s', escapeshellcmd($conf['Database']['master']['pass']), $conf['Database']['master']['user'], $host, $port, $conf['Database']['master']['name'], $_SERVER['argv'][2]));
        } else {
            passthru(sprintf('mysqldump --password=%s -u %s -h %s -P %d %s', escapeshellcmd($conf['Database']['master']['pass']), $conf['Database']['master']['user'], $host, $port, $conf['Database']['master']['name']));
        }
        break;
    case 'pgsql':
        // get port number
        list($host, $port) = strpos($conf['Database']['master']['host'], ':') !== false ? explode(':', $conf['Database']['master']['host']) : array($conf['Database']['master']['host'], 3306);
        file_put_contents('conf/.pgpass', sprintf('%s:%d:%s:%s:%s', $host, $port, $conf['Database']['master']['name'], $conf['Database']['master']['user'], $conf['Database']['master']['pass']));
        chmod('conf/.pgpass', 0600);
        if (isset($_SERVER['argv'][2])) {
            exec(sprintf('export PGPASSFILE=conf/.pgpass; pg_dump -U %s -h %s -p %d %s > %s; export PGPASSFILE=~/.pgpass', $conf['Database']['master']['user'], $host, $port, $conf['Database']['master']['name'], $_SERVER['argv'][2]));
        } else {
            passthru(sprintf('export PGPASSFILE=conf/.pgpass; pg_dump -U %s -h %s -p %d %s; export PGPASSFILE=~/.pgpass', $conf['Database']['master']['user'], $host, $port, $conf['Database']['master']['name']));
        }
        unlink('conf/.pgpass');
        break;
    default:
        Cli::out('** Error: Unable to determine database driver from site config.', 'error');
        break;
}
                $include[] = $string['orig'];
                break;
            }
        }
    }
}
// Include and export each language
foreach ($i18n->languages as $lang) {
    $code = !empty($lang['locale']) ? $lang['code'] . '_' . $lang['locale'] : $lang['code'];
    require 'lang/' . $code . '.php';
    $export = array();
    foreach ($include as $string) {
        if (isset($this->lang_hash[$code][$string])) {
            $export[$string] = $this->lang_hash[$code][$string];
        }
    }
    asort($export);
    $out = "<?php\n\nif (! isset (\$this->lang_hash['{$code}'])) {\n";
    $out .= "\t\$this->lang_hash['{$code}'] = array ();\n}\n\n";
    $out .= "\$this->lang_hash['{$code}'] = array_merge (\n\t";
    $out .= "\$this->lang_hash['{$code}'],\n\tarray (\n";
    $sep = '';
    foreach ($export as $k => $v) {
        $out .= sprintf("%s\t\t'%s' => '%s'", $sep, str_replace('\'', '\\\'', stripslashes($k)), str_replace('\'', '&apos;', stripslashes($v)));
        $sep = ",\r";
    }
    $out .= "\n\t)\n);\n";
    file_put_contents('apps/' . $app . '/lang/' . $code . '.php', $out);
}
Cli::out(sprintf('Translations exported to apps/%s/lang', $app), 'success');
Exemple #16
0
 * This command builds the scaffolding for a new
 * app in the apps folder. This includes the basic
 * directory structure as well as some sample
 * files (config, handlers, views).
 */
if (!$this->cli) {
    die('Must be run from the command line.');
}
$page->layout = false;
if (!isset($_SERVER['argv'][2])) {
    Cli::out('Usage: ./elefant build-app <appname>', 'info');
    die;
}
if (file_exists('apps/' . $_SERVER['argv'][2])) {
    Cli::out('apps/' . $_SERVER['argv'][2] . ' already exists.  Please choose a different name for your new app.', 'info');
    die;
}
$appname = $_SERVER['argv'][2];
$data = array('appname' => $appname, 'open_tag' => '<?php', 'close_tag' => '?>');
mkdir('apps/' . $appname . '/conf', 0755, true);
mkdir('apps/' . $appname . '/forms', 0755, true);
mkdir('apps/' . $appname . '/handlers', 0755, true);
mkdir('apps/' . $appname . '/lib', 0755, true);
mkdir('apps/' . $appname . '/models', 0755, true);
mkdir('apps/' . $appname . '/views', 0755, true);
file_put_contents('apps/' . $appname . '/handlers/index.php', $tpl->render('cli/build-app/index_handler', $data));
file_put_contents('apps/' . $appname . '/handlers/admin.php', $tpl->render('cli/build-app/admin_handler', $data));
file_put_contents('apps/' . $appname . '/views/index.html', $tpl->render('cli/build-app/index_view', $data));
file_put_contents('apps/' . $appname . '/conf/config.php', $tpl->render('cli/build-app/config', $data));
Cli::out('App created in apps/' . $appname, 'success');
Exemple #17
0
<?php

/**
 * Encrypts the specified password in a compatible format
 * for storage in the Elefant user table.
 */
if (!$this->cli) {
    die('Must be run from the command line.');
}
$page->layout = false;
if (!isset($_SERVER['argv'][2])) {
    Cli::out('Usage: ./elefant encrypt-password <password>', 'info');
    return;
}
echo User::encrypt_pass($_SERVER['argv'][2]) . "\n";
Exemple #18
0
DB::beginTransaction();
foreach ($sqldata as $sql) {
    if (trim($sql) === 'begin' || trim($sql) === 'commit') {
        continue;
    }
    if (!DB::execute($sql)) {
        Cli::out('** Error: ' . DB::error(), 'error');
        DB::rollback();
        return;
    }
}
// change the admin user's password
$pass = generate_password(8);
$date = gmdate('Y-m-d H:i:s');
if (!DB::execute("update `#prefix#user` set `email` = ?, `password` = ? where `id` = 1", $conf['General']['email_from'], User::encrypt_pass($pass))) {
    Cli::out('Error: ' . DB::error(), 'error');
    DB::rollback();
    return;
}
DB::commit();
// respond with the root password
echo "Database created. Your initial admin account is:\n";
Cli::block('Username: <info>' . $conf['General']['email_from'] . "</info>\n");
Cli::block('Password: <info>' . $pass . "</info>\n");
// create versions entries for initial content
$wp = new Webpage('index');
Versions::add($wp);
$b = new Block('members');
Versions::add($b);
// disable the installer
@umask(00);