Ejemplo n.º 1
1
 private function readMove()
 {
     do {
         $isValid = true;
         $move = readline("Your move: ");
         $move = explode(",", $move);
         if (count($move) != 2) {
             $isValid = false;
         }
         foreach ($move as $k => $m) {
             $m = trim($m);
             $move[$k] = $m;
             if ($m !== '0' && $m !== '1' && $m !== '2') {
                 $isValid = false;
             }
         }
         if ($isValid && $this->deck[$move[0]][$move[1]] != 0) {
             $isValid = false;
         }
         if (!$isValid) {
             echo "Your move is wrong format, value or position (format: ROW,COLUMN). <Example> 0,0 or 0,1 or 1,2\n";
         }
     } while (!$isValid);
     return $move;
 }
Ejemplo n.º 2
0
 public function authCode()
 {
     while (!is_null($this->_last_fetch_captcha) and microtime(true) - $this->_last_fetch_captcha < 2) {
         usleep(1000);
     }
     $this->_last_fetch_captcha = microtime(true);
     // 1. 先輸入認證碼
     $url = 'http://lvr.land.moi.gov.tw/N11/ImageNumberN13';
     $response = http_get($url);
     $message = http_parse_message($response);
     if (!preg_match('#JSESSIONID=([^;]*);#', $message->headers['Set-Cookie'], $matches)) {
         throw new Exception("找不到 JSESSIONID");
     }
     $this->cookie = $matches[1];
     $tmpfp = tmpfile();
     fwrite($tmpfp, $message->body);
     $tmp_meta = stream_get_meta_data($tmpfp);
     $return_var = 0;
     system('jp2a ' . escapeshellarg($tmp_meta['uri']), $return_var);
     if ($return_var == 1) {
         // 不是圖片,就再試一次...
         return $this->authCode();
     }
     fclose($tmpfp);
     $code = readline("請輸入認證碼: ");
     // 2. 輸入認證碼
     $response = http_post_fields('http://lvr.land.moi.gov.tw/N11/login.action', array('command' => 'login', 'count' => 0, 'rand_code' => intval($code), 'in_type' => 'land'), array(), array('cookies' => array('JSESSIONID' => $this->cookie)));
     if (strpos(http_parse_message($response)->body, '驗證碼錯誤')) {
         error_log('驗證碼錯誤,重試一次');
         $this->authCode();
     }
 }
Ejemplo n.º 3
0
function go($board, $colour, $cpu)
{
    $col = 0;
    showBoard($board);
    $cols = cols($board);
    if ($cpu == 0) {
        while (!in_array($col, $cols)) {
            $msg = 'player ' . $colour . ' - please choose a column (' . implode(',', $cols) . '): ';
            $col = readline($msg);
        }
    } else {
        sleep(0.5);
        print 'cpu thinking... ' . "\n";
        $col = $cols[array_rand($cols, 1)];
    }
    sleep(1);
    array_push($board[$col], $colour);
    if (check($board, $col)) {
        win($board, $colour);
        sleep(1);
        return 1;
    } else {
        return $board;
    }
}
Ejemplo n.º 4
0
 public static function input($prefix = '')
 {
     if (static::readline_support()) {
         return readline($prefix);
     }
     return fgets(STDIN);
 }
Ejemplo n.º 5
0
 protected static function _getAction()
 {
     do {
         $action = readline("action > ");
         if ($action === false) {
             break;
         }
         $action = trim($action);
         if ($action === '') {
             echo implode("\n", Action::$whitelist), "\n\n";
         } else {
             if (in_array($action, ['q', 'quit'])) {
                 return false;
             } else {
                 if ($action) {
                     if (!Action::isWhitelisted($action)) {
                         echo "Action not found\n";
                         $action = '';
                     }
                 }
             }
         }
     } while ($action === '');
     return $action;
 }
Ejemplo n.º 6
0
 protected function main()
 {
     if (!file_exists($this->configPath)) {
         mkdir($this->configPath, 0777, true);
     }
     $this->readConfig();
     if (!$this->config['email']) {
         throw new \Exception('Email is required for initialization.');
     }
     if (!$this->config['client-id'] || !$this->config['client-secret']) {
         throw new \Exception('Amazon Cloud Drive API credentials are required for initialization.');
     }
     $this->saveConfig();
     $this->cacheStore = $this->generateCacheStore();
     $this->clouddrive = new CloudDrive($this->config['email'], $this->config['client-id'], $this->config['client-secret'], $this->cacheStore);
     $response = $this->clouddrive->getAccount()->authorize();
     if (!$response['success']) {
         $this->output->writeln($response['data']['message']);
         if (isset($response['data']['auth_url'])) {
             $this->output->writeln('Navigate to the following URL and paste in the redirect URL here.');
             $this->output->writeln($response['data']['auth_url']);
             $redirectUrl = readline();
             $response = $this->clouddrive->getAccount()->authorize($redirectUrl);
             if ($response['success']) {
                 $this->output->writeln('<info>Successfully authenticated with Amazon Cloud Drive.</info>');
                 return;
             }
             $this->output->getErrorOutput()->writeln('<error>Failed to authenticate with Amazon Cloud Drive: ' . json_encode($response['data']) . '</error>');
         }
     } else {
         $this->output->writeln('<error>That user is already authenticated with Amazon Cloud Drive.</error>');
     }
 }
Ejemplo n.º 7
0
function mal_readline($prompt)
{
    global $HISTORY_FILE;
    static $history_loaded = false;
    // Load the history file
    if (!$history_loaded) {
        $history_loaded = true;
        if (is_readable($HISTORY_FILE)) {
            if ($file = fopen($HISTORY_FILE, "r")) {
                while (!feof($file)) {
                    $line = fgets($file);
                    if ($line) {
                        readline_add_history($line);
                    }
                }
                fclose($file);
            }
        }
    }
    $line = readline($prompt);
    if ($line === false) {
        return NULL;
    }
    readline_add_history($line);
    // Append to the history file
    if (is_writable($HISTORY_FILE)) {
        if ($file = fopen($HISTORY_FILE, "a")) {
            fputs($file, $line . "\n");
            fclose($file);
        }
    }
    return $line;
}
Ejemplo n.º 8
0
	public function read($path) {
		$this->_historize(\AIP\lib\clnt\cmnctr\Communicator::i()->get_last_history());
		
		$line = readline($this->_get_input_question($path));
		
		return $line;
	}
Ejemplo n.º 9
0
 private function listenForInput()
 {
     echo "Please type a letter: ";
     $input = readline();
     $this->handleInput($input);
     $this->listenForInput();
 }
Ejemplo n.º 10
0
 /**
  * Выбрать альбом для прослушивания
  */
 public function actionRandAlbom($unusual = 0)
 {
     if ($unusual) {
         $played = implode(',', ArrayHelper::map(Played::find()->all(), 'id', 'source_id'));
         $alboms = Source::find()->where("id NOT IN (" . $played . ")")->andWhere(['status' => 3])->all();
         if ($alboms) {
             $rand = rand(0, count($alboms));
             $new_played = new Played();
             $new_played->source_id = $alboms[$rand]->id;
             $new_played->save(false);
             echo "Ставь " . $alboms[$rand]->title . " -- " . $alboms[$rand]->author->name . PHP_EOL;
         } else {
             echo "Ничего нет" . PHP_EOL;
         }
     } else {
         $played = implode(',', ArrayHelper::map(Played::find()->all(), 'id', 'source_id'));
         $alboms = Source::find()->where("id NOT IN (" . $played . ")")->andWhere(['status' => 1])->all();
         if ($alboms) {
             $rand = rand(0, count($alboms));
             $data = readline("Устроит " . $alboms[$rand]->title . " -- " . $alboms[$rand]->author->name . " ? Y или N ? ");
             if ($data == 'N') {
                 $this->actionRandAlbom();
             } else {
                 $new_played = new Played();
                 $new_played->source_id = $alboms[$rand]->id;
                 $new_played->save(false);
                 echo "Ставь " . $alboms[$rand]->title . " -- " . $alboms[$rand]->author->name . PHP_EOL;
             }
         } else {
             echo "Ничего нет" . PHP_EOL;
         }
     }
 }
Ejemplo n.º 11
0
function loopException()
{
    while (true) {
        readline('Press any key to continue..');
        exceptionFunction();
    }
}
Ejemplo n.º 12
0
function prompt($parser, $item, $category, $locations)
{
    echo "\n" . $item->title() . "\n";
    echo $locations[0]['name'] . ' <-> ' . $locations[1]['name'] . "\n";
    if ($category) {
        echo $category['name'] . " ok?\n";
    }
    while (true) {
        $in = readline('> ');
        if ($in == 'q') {
            return;
        } elseif ($in == 'm') {
            echo $item->title() . "\n";
            echo $item->guid() . "\n";
            echo $item->description() . "\n";
            echo $item->content() . "\n";
        } elseif ($in == 'no') {
            return;
        } elseif ($in == 'h') {
            foreach ($parser->getClassifier()->getAllCategories() as $category) {
                echo "  " . $category['id'] . "> " . $category['name'] . "\n";
            }
            echo "  q> skip\n";
            echo "  m> more\n";
        } else {
            if (!$category) {
                $category = $parser->getClassifier()->getCategory($in);
            }
            if ($category) {
                return $category;
            }
        }
    }
}
 public function up()
 {
     $table = $this->table('archive_publication');
     $table->addColumn('name', 'string', array('length' => 40))->addColumn('inactive', 'boolean', array('default' => 0))->addIndex('inactive')->create();
     $table = $this->table('archive_issue');
     $table->addColumn('issue', 'integer')->addColumn('date', 'date')->addColumn('publication', 'integer')->addColumn('inactive', 'boolean', array('default' => 0))->addIndex('publication')->addIndex('issue')->addIndex('inactive')->addIndex(array('issue', 'publication'), array('unique' => true))->addForeignKey('publication', 'archive_publication', 'id')->create();
     $table = $this->table('archive_file');
     $table->addColumn('issue', 'integer')->addColumn('issue_id', 'integer', array('null' => true))->addColumn('publication', 'integer')->addColumn('part', 'string', array('length' => 5))->addColumn('filename', 'string', array('length' => 255))->addColumn('content', 'text')->addIndex('part')->create();
     $this->execute("ALTER TABLE `archive_file` ADD FULLTEXT(`content`);");
     $db = readline("Please enter the name of the archive database to copy data from. Phinx must have read access to this database. To skip this step, press CTRL-D.\n");
     if (!$db) {
         return;
     }
     $this->execute("INSERT INTO archive_publication (id, name) SELECT PubNo AS id, PubName AS name FROM `" . $db . "`.Publications");
     $this->execute("INSERT INTO archive_issue (id, issue, date, publication) SELECT id AS id, IssueNo AS issue, PubDate AS date, PubNo AS publication FROM `" . $db . "`.Issues");
     $this->execute("INSERT INTO archive_file (issue, publication, part, filename, content) SELECT DISTINCT IssueNo AS issue, PubNo AS publication, Title AS part, FileName AS filename, Content AS content FROM `" . $db . "`.Files");
     // Now correct issue IDs
     foreach ($this->fetchAll('SELECT id, issue, publication FROM archive_file') as $file) {
         $issue = $this->fetchRow('SELECT id FROM archive_issue WHERE issue = ' . $file['issue'] . ' AND publication = ' . $file['publication']);
         if ($issue['id'] == NULL) {
             echo '-> Issue record could not be found for file ' . $file['id'] . ' supposed issue ' . $file['issue'] . ' in publication ' . $file['publication'] . "\n";
             $this->execute('UPDATE archive_file SET issue_id = NULL WHERE id = ' . $file['id']);
             continue;
         }
         $this->execute('UPDATE archive_file SET issue_id = ' . $issue['id'] . ' WHERE id = ' . $file['id']);
     }
     $table = $this->table('archive_file');
     $table->removeColumn('issue')->removeColumn('publication')->addForeignKey('issue_id', 'archive_issue', 'id')->addIndex('issue_id')->save();
 }
    public function create()
    {
        echo "You must create config file in next step \n";
        $user = readline("Username datebase: ");
        $password = readline("Password database: ");
        $host = readline("Host database: ");
        $driver = readline("Driver datebase: ");
        $dbname = readline("Datebase name: ");
        $templateClass = readline("Template class(default {$this->defaults['template_class']}):");
        $pathCRUD = readline("where to put crud files?(give absolute path): ");
        /** default settings * */
        !empty($templateClass) ?: ($templateClass = $this->defaults['template_class']);
        $output = <<<EOT
            <?php return array(
                'db' => [
                  'dsn'=> '{$driver}:host={$host};dbname={$dbname}',
                  'username' => '{$user}',
                  'password' => '{$password}',
                   ],
                 'path_crud' => '{$pathCRUD}',
                 'template_class' => '{$templateClass}'
                 );
EOT;
        if (!file_put_contents(self::CONFIG_FILE, $output)) {
            chmod(self::CONFIG_FILE, fileperms(self::CONFIG_FILE) | 128 + 16 + 2);
            throw new ScaffoldingException('failed create config file');
        }
    }
Ejemplo n.º 15
0
 /**
  * @brief Read a line, optionally setting the completer
  *
  * @param string $prompt The prompt to display
  * @param ReadlineAutoCompleter $completer The completer instance
  * @param boolean $autohistory Add command to history automatically (default is false)
  */
 static function read($prompt = null, ReadlineAutoCompleter $completer = null, $autohistory = false)
 {
     $oldcompleter = null;
     // If we got an autocompleter, assign it
     if ($completer) {
         // Save a copy of the old completer if any
         if (self::$completer && $completer !== self::$completer) {
             $oldcompleter = self::$completer;
         }
         // Assign and set up the proxy call
         self::$completer = $completer;
         readline_completion_function(array('Readline', '_rlAutoCompleteProxy'));
     }
     // Read the line
     $ret = readline($prompt);
     // Restore old completer (if any) and add the command to the history
     // if autohistory is enabled.
     if ($oldcompleter) {
         self::$completer = $oldcompleter;
     }
     if ($autohistory) {
         self::addHistory($ret);
     }
     return $ret;
 }
Ejemplo n.º 16
0
 public function getAuthorization()
 {
     /* try to get cached access token first */
     if (file_exists(".acc_tok_cache")) {
         while ($reuseAccTok != 'y' && $reuseAccTok != 'n') {
             $reuseAccTok = readline("Reuse cached access token (y/n)? ");
             readline_add_history($reuseAccTok);
         }
         if ($reuseAccTok == 'y') {
             $accTokenString = file_get_contents(".acc_tok_cache");
             $accessToken = unserialize($accTokenString);
             echo "Using access token: ";
             print_r($accessToken);
         }
     }
     /* no cached access token, get a new one */
     if (empty($accessToken)) {
         try {
             $reqToken = $this->oauth->getRequestToken($this->reqTokenURL);
         } catch (OAuthException $oae) {
             echo "The following exception occured when trying to get a request token: " . $oae->getMessage() . "\n";
         }
         print_r($reqToken);
         echo "Now you have to authorize the following token: " . $this->authorizeURL . "?oauth_token=" . $reqToken['oauth_token'] . "\n";
         $this->ssp_readline("Press any key to continue...\n");
         $accessToken = $reqToken;
         $this->oauth->setToken($reqToken['oauth_token'], $reqToken['oauth_token_secret']);
         $accessToken = $this->oauth->getAccessToken($this->accTokenURL);
         $accessTokenString = serialize($accessToken);
         file_put_contents(".acc_tok_cache", $accessTokenString);
     }
     $this->oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
 }
Ejemplo n.º 17
0
function process($arguments)
{
    $dump_data = false;
    $term = get_term_default();
    array_shift($arguments);
    if (!isset($arguments[0])) {
        $arguments[0] = '-h';
    }
    $argCount = count($arguments);
    for ($i = 0; $i < $argCount; $i++) {
        if ($arguments[$i] == '-h') {
            print_help();
            exit;
        } elseif ($arguments[$i] == '-f') {
            $i++;
            if (!isset($arguments[$i])) {
                exit("Configuration file not included.\n");
            }
            $file_directory = $arguments[$i];
        } elseif ($arguments[$i] == '-n') {
            $i++;
            if (!isset($arguments[$i])) {
                exit("Student rows not included.\n");
            }
            $number_of_students = $arguments[$i];
        } elseif ($arguments[$i] == '-x') {
            $dump_data = true;
        } elseif ($arguments[$i] == '-t') {
            $i++;
            if (!isset($arguments[$i])) {
                exit("Term is missing.\n");
            }
            $term = $arguments[$i];
        } else {
            exit("Unknown command\n");
        }
    }
    if (empty($number_of_students)) {
        $number_of_students = NUMBER_OF_STUDENTS;
    }
    include_database_file($file_directory);
    if ($dump_data) {
        $response = readline("Are you sure you want to reset ALL your student tables? (y/N):");
        if ($response == 'y') {
            reset_tables();
        } else {
            echo "Ending script.\n\n";
            exit;
        }
        echo "\nReset complete.\n------------------------------------\n\n";
    }
    build_table();
    echo TABLE_NAME . " table created.\n";
    echo "------------------------------------\n\n";
    echo "Creating {$number_of_students} students.\n\n";
    insert_rows($number_of_students, $term);
    echo "------------------------------------\nStudent creation complete.\n\n";
    echo "Make sure your inc/hms_defines.php file contains the following setting:\ndefine('SOAP_OVERRIDE_FILE', 'FakeSoapTable.php');\n";
}
Ejemplo n.º 18
0
 /**
  * Get input from the shell, using readline or the standard STDIN
  *
  * Named options must be in the following formats:
  * php index.php user -v --v -name=John --name=John
  *
  * @param	string|int	$name	the name of the option (int if unnamed)
  * @return	string
  */
 public static function input($prefix = '')
 {
     if (static::$readline_support) {
         return readline($prefix);
     }
     echo $prefix;
     return fgets(STDIN);
 }
Ejemplo n.º 19
0
 /**
  * displays a message and waits for user input
  * @param  string $msg  A short message to display
  * @param  string $hint An array of strings to display as possible values
  * @return string       The user-provided response
  */
 public function read($msg, array $hint = null)
 {
     // if hint is null then set it to an empty array
     if (!is_array($hint)) {
         $hint = array();
     }
     return readline($msg . $this->renderHint($hint) . $this->_promptPrefix);
 }
Ejemplo n.º 20
0
 /**
  * Read input from console
  *
  * @param string $prompt
  *
  * @return string
  */
 public function readline($prompt)
 {
     if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
         echo $prompt;
         return stream_get_line(STDIN, 2048, PHP_EOL);
     }
     return readline($prompt);
 }
Ejemplo n.º 21
0
function readfilepath($prompt)
{
    $source = trim(readline($prompt));
    if (!file_exists($source)) {
        error("The specified source file does not exist or is not a file!\n({$source})");
    }
    return $source;
}
Ejemplo n.º 22
0
Archivo: Shell.php Proyecto: g4z/poop
 /**
  * Read a line from the command prompt
  * @return string
  */
 public function readInput()
 {
     $line = readline($this->prompt);
     if (!empty($line)) {
         readline_add_history($line);
     }
     return $line;
 }
Ejemplo n.º 23
0
 /**
  * Get input from the shell, using readline or the standard STDIN
  *
  * Named options must be in the following formats:
  * php index.php user -v --v -name=John --name=John
  *
  * @param	string|int	$name	the name of the option (int if unnamed)
  * @return	string
  */
 public function input($prefix = '')
 {
     if ($this->readline_support) {
         return readline($prefix);
     }
     echo $prefix;
     return fgets(STDIN);
 }
Ejemplo n.º 24
0
function getCliInput()
{
    if (function_exists('readline')) {
        return readline("> ");
    }
    echo "> ";
    return stream_get_line(STDIN, 1024, PHP_EOL);
}
Ejemplo n.º 25
0
 function play()
 {
     $this->message("\n\n\n\n\n============turn:" . $this->game->get_time() . "==");
     $statement = readline("// play: ");
     $parts = explode(' ', $statement);
     $command = array_shift($parts);
     $g = $this->game;
     $continue = true;
     $look = true;
     $increment = false;
     switch ($command) {
         case 'help':
             $args = implode(' ', $parts);
             $this->help($args);
             $look = false;
             break;
         case 'go':
             $args = implode(' ', $parts);
             $g->go($args);
             $increment = true;
             break;
         case 'inventory':
             $g->describe_inventory();
             $look = false;
             break;
         case 'local':
             $g->describe_local();
             $look = false;
             break;
         case 'examine':
             $target = implode(' ', $parts);
             $g->examine($target);
             $look = false;
             break;
         case 'look':
             $preposition = array_shift($parts);
             if ($preposition == 'at') {
                 $target = implode(' ', $parts);
                 $g->examine($target);
             }
             break;
         case 'exit':
         case 'quit':
         case 'menu':
             $continue = false;
             $look = false;
             break;
     }
     if ($increment) {
         $g->step();
     }
     if ($look) {
         $g->look();
     }
     if ($continue) {
         $this->play();
     }
 }
Ejemplo n.º 26
0
 /**
  * in
  * 
  * @param string $text
  * @param boolean $escape
  * @return string
  */
 public static function in($text, $escape = false)
 {
     $line = readline($text);
     readline_add_history($line);
     if ($escape) {
         return escapeshellcmd($line);
     }
     return $line;
 }
Ejemplo n.º 27
0
function prompt($msg)
{
    if (PHP_OS == 'WINNT') {
        echo $msg;
        return stream_get_line(STDIN, 1024, PHP_EOL);
    } else {
        return readline($msg);
    }
}
Ejemplo n.º 28
0
function password_request()
{
    if (strlen($password = readline("Input your password:")) >= 8) {
        return $password;
    } else {
        p('Short password. Try again!');
        return password_request();
    }
}
/**
 * Cross-platform input on the command line
 *
 * @param string $question The question to ask
 *
 * @return string
 */
function getInput($question = '')
{
    if (!function_exists('readline')) {
        echo $question . ' ';
        return stream_get_line(STDIN, 1024, PHP_EOL);
    } else {
        return readline($question . ' ');
    }
}
Ejemplo n.º 30
-1
function installConfig()
{
    require_once "../include/pbkdf2.php";
    $fout = fopen("../config_local.php_", 'w') or die("Could not write to local configuration file!");
    fwrite($fout, "<?php\n");
    fwrite($fout, '$config["site_name"] = "' . readline("Site name? ") . '";' . "\n");
    fwrite($fout, '$config["root_path"] = "' . readline("Root path (ex: /uxpanel/)? ") . '";' . "\n");
    fwrite($fout, '$config["mail_from"] = "' . readline("E-mail address to send as? ") . '";' . "\n");
    fwrite($fout, '$config["admin_username"] = "******"Admin username? ") . '";' . "\n");
    fwrite($fout, '$config["admin_password"] = "******"Admin password? ")) . '";' . "\n");
    fwrite($fout, '$config["admin_passwordtype"] = "pbkdf2";' . "\n");
    fwrite($fout, '$config["db_hostname"] = "' . readline("Database hostname? ") . '";' . "\n");
    fwrite($fout, '$config["db_name"] = "' . readline("Database name? ") . '";' . "\n");
    fwrite($fout, '$config["db_username"] = "******"Database username? ") . '";' . "\n");
    fwrite($fout, '$config["db_password"] = "******"Database password? ") . '";' . "\n");
    do {
        $slave = readline("Install as slave (y/n)? ");
    } while ($slave != "y" && $slave != "n");
    $slave = $slave == "y";
    fwrite($fout, '$config["slave"] = ' . ($slave ? "true" : "false") . ';' . "\n");
    if ($slave) {
        fwrite($fout, '$config["slave_master"] = "' . readline("Master URL (ex: http://master.yourdomain.com/uxpanel/)? ") . '";' . "\n");
        fwrite($fout, '$config["slave_id"] = ' . readline("Slave ID number? ") . ';' . "\n");
    }
    fwrite($fout, "?>\n");
    fclose($fout);
    rename("../config_local.php_", "../config_local.php");
}