public function RestartById($c) { if (!count(DB::query('SELECT * from ' . self::TABLE . ' WHERE id="' . $c . '"'))) { io::out("Work with id={$c} is not exists", IO::MESSAGE_FAIL); return; } $list = DB::query('SELECT * FROM ' . self::TABLE . ' where isnull(finished_at) and not isnull(locked_at) and isnull(failed_at) and id=' . $c . ' ORDER BY run_at DESC'); if (count($list)) { IO::out("This is working now...You cant restart!", IO::MESSAGE_FAIL); return; } if (IO::YES == io::dialog('Do you really want to restart work with id ' . $c . '?', IO::NO | IO::YES, IO::NO)) { DB::query("UPDATE " . self::TABLE . " set attempts='1',finished_at=null, locked_at=null, \n failed_at=null, run_at=now() WHERE id='" . $c . "'"); $php_path = exec("which php"); if (empty($php_path)) { return $this->log("###" . date("c") . " Call from console PHP executable not found"); } if (!is_executable($php_path)) { return $this->log("###" . date("c") . " Call from console {$php_path} could not be executed"); } exec($php_path . ' ' . trim(escapeshellarg(Config::get('ROOT_DIR') . "/vendors/delayedjob/JobHandler.php"), "'") . ' >> ' . Config::get('ROOT_DIR') . '/logs/delayedjob.log 2>&1 &'); io::done('Restarting...'); } else { io::done('Cancel restart'); } IO::out(""); }
function process() { Console::initCore(); if (($c = ArgsHolder::get()->shiftCommand()) == 'help') { return $this->cmdHelp(); } try { $format = "%-25s %s"; IO::out(""); $s = DB::query('SELECT * FROM ' . self::TABLE . ' where id="' . $c . '"'); if (!count($s)) { io::out("Work with id={$c} is not exists", IO::MESSAGE_FAIL); return; } io::out(sprintf($format, "~CYAN~id~~~", $c)); io::out(sprintf($format, "~CYAN~queue~~~", $this->emp($s[0]['queue']))); io::out(sprintf($format, "~CYAN~priority~~~", $this->emp($s[0]['priority']))); io::out(sprintf($format, "~CYAN~run at~~~", $this->emp($s[0]['run_at']))); io::out(sprintf($format, "~CYAN~locked at~~~", $this->emp($s[0]['locked_at']))); io::out(sprintf($format, "~CYAN~finished at~~~", $this->emp($s[0]['finished_at']))); io::out(sprintf($format, "~CYAN~failed at~~~", $this->emp($s[0]['failed_at']))); io::out(sprintf($format, "~CYAN~attemts~~~", $this->emp($s[0]['attempts']))); $handler = unserialize($s[0]["handler"]); io::out(sprintf($format, "~CYAN~call~~~", $handler["class"] . "::" . $handler["method"]) . "(...)"); if (isset($handler["param"])) { io::out(sprintf($format, "~CYAN~params~~~", trim(self::walker($handler['param']), ','))); } } catch (Exception $e) { io::out($e->getMessage(), IO::MESSAGE_FAIL); return; } IO::out(""); }
function process() { Console::initCore(); if ($r = ArgsHolder::get()->getOption('count')) { $this->count = $r; } if (($c = ArgsHolder::get()->shiftCommand()) == 'help') { return $this->cmdHelp(); } try { IO::out(""); $sql = 'SELECT * FROM ' . self::TABLE . ' where not isnull(finished_at) and not isnull(locked_at) and isnull(failed_at) ORDER BY run_at DESC'; if ($this->count) { $list = DB::query($sql . ' LIMIT ' . $this->count); } else { $list = DB::query($sql); } if (!count($list)) { IO::out("No finished work!", IO::MESSAGE_FAIL); return; } io::out(sprintf("%-10s %-7s %-3s %-20s %-20s %-19s %-4s %-5s", "~CYAN~id", "queue", "pr", "run_at", "locked_at", "finished_at", "att", "call_to~~~")); foreach ($list as $l) { $handler = unserialize($l["handler"]); io::out(sprintf("%-4s %-7s %-3s %-20s %-20s %-20s %-3s %-5s", $l["id"], $l["queue"], $l["priority"], $l["run_at"], $l["locked_at"], $l["finished_at"], $l["attempts"], $handler["class"] . "::" . $handler["method"] . "(...)")); } } catch (Exception $e) { io::out($e->getMessage(), IO::MESSAGE_FAIL); return; } IO::out(""); }
function CmdList() { io::out('~WHITE~Current env~~~: ' . ($env = EnvManager::getCurrent())); io::out(); IO::OUt('~WHITE~Avaible enviroments:~~~'); foreach (EnvManager::envList() as $e) { if ($e != $env) { io::out(' ' . $e); } } }
public function deleteQueue($c) { if (!DB::query('SELECT id from ' . self::TABLE . ' WHERE queue="' . $c . '"')) { io::out("Queue {$c} is not exists", IO::MESSAGE_FAIL); return; } if (IO::YES == io::dialog('Realy you really want to delete all jobs with queue ' . $c . '?', IO::NO | IO::YES, IO::NO)) { DB::query("DELETE FROM " . self::TABLE . " WHERE queue='" . $c . "'"); io::done('Deleting...'); } else { io::done('Cancel delete'); } }
function delete($what) { io::out('Deleting: '); foreach ($what as $t) { echo $t; if (file_exists($t)) { if (is_dir($t)) { $t = new Dir($t, true); } else { $t = new File($t, true); } $r = $t->delete(); io::done(); } else { echo " Not found."; } echo PHP_EOL; } }
function process() { if (!($c = ArgsHolder::get()->shiftCommand())) { return io::out('Incorrect parameter', IO::MESSAGE_FAIL) | 1; } $root = Config::get('ROOT_DIR'); $file = $root . '/includes/env/' . strtolower($c) . '_env.php'; if (!file_exists($file)) { return io::out('Mode ' . $c . ' not exists', IO::MESSAGE_FAIL) | 1; } IO::out('Updating Loader', false); $loader = fopen($root . '/includes/env/Loader.php', 'w'); flock($loader, LOCK_EX); $put = '<?php require_once("' . $c . '_env.php");'; fwrite($loader, $put); flock($loader, LOCK_UN); fclose($loader); io::done(); io::out('Backup config.ini', false); if (copy($root . '/config/config.ini', $root . '/config/config.ini.bak')) { io::done(); } else { return IO::out('Can\'t backup file config.ini', IO::MESSAGE_FAIL) | 1; } IO::out('Updating config.ini', false); $file_array = file($root . '/config/config.ini'); $str = null; foreach ($file_array as $fa) { if (preg_match('/\\[\\s*config\\s*:\\s*\\S+\\]/', $fa, $match)) { $str .= '[config : ' . $c . ']' . PHP_EOL; } else { $str .= $fa; } } $config = fopen($root . '/config/config.ini', 'w'); flock($config, LOCK_EX); fwrite($config, $str); flock($config, LOCK_UN); fclose($config); io::done(); IO::done('Enviroments set to ~WHITE~' . $c . '~~~'); }
public function cmdUserlist() { if (!count(ACL::getGroups())) { return io::out('There is no groups yet.'); } $users = ACL::getUsers(); if ($group = ArgsHolder::get()->shiftCommand()) { if (!in_array($group, array_values(ACL::getGroups()))) { return io::out("No such group {$group}", IO::MESSAGE_FAIL) | 3; } IO::out("~WHITE~User(s) from group " . $group . "~~~:"); foreach ($users[$group] as $u) { IO::out(" " . $u); } } else { foreach (array_keys($users) as $g) { IO::out("~WHITE~Group " . $g . "~~~:"); foreach ($users[$g] as $u) { IO::out(" " . $u); } } } }
function process() { $root = Config::get('ROOT_DIR'); if (($src = ArgsHolder::get()->shiftCommand()) === false || ($new = ArgsHolder::get()->shiftCommand()) === false) { return io::out('Incorrect param count', IO::MESSAGE_FAIL) | 1; } $src_file = $root . '/includes/env/' . strtolower($src) . '_env.php'; $new_file = $root . '/includes/env/' . strtolower($new) . '_env.php'; if (file_exists($new_file)) { return io::out('Enviroments ~WHITE~' . $new . '~~~ already exists!', IO::MESSAGE_FAIL) | 2; } if (!file_exists($src_file)) { return io::out('Source enviroments ~WHITE~' . $src . '~~~ is not exists!', IO::MESSAGE_FAIL) | 2; } io::out('Writing files', false); if (!copy($src_file, $new_file)) { return io::out('Unable copy env files (' . $src_file . ' to ' . $new_file . ')', IO::MESSAGE_FAIL) | 3; } $file_array = file($root . '/config/config.ini'); $str = null; foreach ($file_array as $fa) { if (preg_match('/\\[\\s*config\\s*:\\s*\\S+\\]/', $fa, $match)) { $str .= '[' . $new . ': base ]' . PHP_EOL . $match[0] . PHP_EOL; } else { $str .= $fa; } } $config = fopen($root . '/config/config.ini', 'w'); flock($config, LOCK_EX); $r = fwrite($config, $str); flock($config, LOCK_UN); fclose($config); if (!$r) { return io::out('Cant write ~WHITE~config.ini~~~', IO::MESSAGE_FAIL) | 4; } io::done(); }
private function infoByExt($ext) { $info = $this->extInfo(); if (isset($info[$ext])) { $extinfo = $info[$ext]; io::out(''); io::out('~WHITE~Information about extension ' . $ext . ":~~~"); foreach ($extinfo as $ei) { foreach ($ei as $k => $v) { if (is_array($v)) { array_pop($v); foreach ($v as $kk => $vv) { io::out(sprintf("%-40s %s", $k, "~CYAN~" . $vv . "~~~")); } } else { io::out(sprintf("%-40s %s", $k, "~CYAN~" . $v . "~~~")); } } } io::out(''); } else { io::out('No such extension ' . $ext, IO::MESSAGE_FAIL); } }
/** * Встроенная комманда help реализует отображение справочной информации. * * Если передедан необязательный параметр $command отображается справка * подкомманды. * * @param string $command * @return int 0 */ protected function cmdHelp($command = null) { $help = $this->parseHelpFile(); $subCommands = is_null($command) ? $this->getCommands() : array(); if (!is_null($command)) { $help = $help['inclass'][$command]; } IO::out($help['short']); if (!empty($help['main'])) { IO::out($help['main']); } $list = array(); foreach ($subCommands as $subCmd) { $i = $this->getCommandInfo($subCmd); $list[$subCmd] = trim($i['help']['short']); } if (isset($help['inclass']) && count($help['inclass'])) { foreach ($help['inclass'] as $inCmd => $v) { $list[$inCmd] = trim($v['short']); } } if (count($list)) { ksort($list, SORT_STRING); IO::out("~WHITE~Commands~~~:"); IO::outOptions($list); IO::out(); } // Command Options if (isset($help['options']) && count($help['options'])) { io::out('~WHITE~Options~~~:'); io::outOptions($help['options']); io::out(); } // Common IO Help IO::out(IO::help()); return 0; }
public function createTar($root, $name, $separate = null) { if (file_exists($root . '/' . $name . "_" . date('Ymd') . ".tar.bz2")) { $filename = $name . "_" . date('Ymd_H_i_s') . '.tar'; } else { $filename = $name . "_" . date('Ymd') . '.tar'; } //$cmd="tar -cvf ".$root."/".$filename." ".$root." --exclude='*web*' --exclude='*~'"; chdir($root); IO::out('Packing main... ' . "\t", false); if ($this->all) { $cmd = "tar --exclude='.svn' --exclude='*~' -cvf " . $root . "/" . $filename . " * 2>&1"; } else { $cmd = "tar --exclude='web' --exclude='.svn' --exclude='*~' -cvf " . $root . "/" . $filename . " * 2>&1"; } exec($cmd, $out, $return); if ($return == 0) { io::done(); } if (IO::getVerboseLevel() == IO::MESSAGE_INFO || $return) { foreach ($out as $o) { io::out($o); } } if ($return) { io::out('Return code ' . $return, IO::MESSAGE_FAIL); io::out('Executed command: ' . $cmd); return; } if (!$this->all) { $cmd = "tar --exclude='*~' --exclude='.svn' -uvf " . $root . "/" . $filename . " ./web/css/ ./web/js/ 2>&1"; io::out('Adding web/css, web/js...', false); exec($cmd, $out, $return); if ($return == 0 && !$this->all) { io::done(); } if (IO::getVerboseLevel() == IO::MESSAGE_INFO || $return) { foreach ($out as $o) { io::out($o); } } if ($return) { io::out('Return code ' . $return, IO::MESSAGE_FAIL); io::out('Executed command: ' . $cmd); return; } } io::out('Bzip ' . $filename . '...', false); $cmd = "bzip2 -9 " . $root . "/" . $filename; exec($cmd, $out, $return); if ($return == 0) { io::done(); } if (IO::getVerboseLevel() == IO::MESSAGE_INFO || $return) { foreach ($out as $o) { io::out($o); } } if ($return) { io::out('Return code ' . $return, IO::MESSAGE_FAIL); io::out('Executed command: ' . $cmd); return; } return $filename . ".bz2"; }
static function undeploy($dir) { $f = $dir->getFile('queries.sql'); // файла нет или он пустой if (!$f->canRead() || ($queries = file_get_contents($f)) === false) { return; } io::out("\t" . '[~PURPLE~Q~~~] ' . basename($f->getParent()) . '/' . basename($f) . '~~~', false); SqlTask::execQuery($queries); io::done(); }
function process() { $root = Config::get('ROOT_DIR'); $file_array = file_get_contents($root . '/config/config.ini'); try { //Look for php-cgi in the system $php_path = exec("which php-cgi"); if (empty($php_path) || !is_executable($php_path)) { IO::out('Look for PHP-CGI in the system.', IO::MESSAGE_FAIL); IO::out("You can't to check hosting because PHP-CGI not found."); return; } $out = exec("echo \"<?php echo 'php-cgi test' ?>\" | {$php_path} -q "); if ($out != "php-cgi test") { IO::out('Look for PHP-CGI in the system.', IO::MESSAGE_FAIL); IO::out("You can't to check hosting because PHP-CGI not found."); return; } IO::out('Look for PHP-CGI in the system.', IO::MESSAGE_OK); $toini = array(); foreach ($this->for_check as $k => $v) { $output = array(); $subcmd = '<?php $r=ini_get("' . $k . '");if($r) echo $r; else echo ((int)$r);'; exec("echo '" . $subcmd . "' | {$php_path} -q", $output); if ($k == 'error_log') { IO::out($k . ' = ' . $output[0], IO::MESSAGE_OK); continue; } if ($k == 'error_log' || $k == 'max_execution_time' || $k == 'max_input_time' || $k == 'upload_max_filesize' || $k == 'memory_limit' || $k == 'post_max_size') { $ch = str_replace('m', '', strtolower($output[0])); if ((int) $ch >= (int) $v) { IO::out($k . ' = ' . $output[0], IO::MESSAGE_OK); continue; } else { io::out($k . ' = ' . $output[0] . ' this must be >=' . $v, IO::MESSAGE_FAIL); continue; } } if ($v == $output[0]) { IO::out($k . ' = ' . $output[0], IO::MESSAGE_OK); } else { $out = array(); $subcmd = '<?php ini_set("' . $k . '","' . $v . '");$r=ini_get("' . $k . '");if($r=="' . $v . '") echo 111; else echo print_r($r);'; exec("echo '" . $subcmd . "' | {$php_path} -q", $out); if ($out[0] == 111) { $toini[$k] = $v; IO::out($k . ' = ' . $output[0] . ', but you can set "' . $v . '"', IO::MESSAGE_WARN); } else { io::out($k . ' = ' . $output[0], IO::MESSAGE_FAIL); } } } $output = array(); $subcmd = '<?php $r=ini_get("upload_max_filesize");if($r) echo $r; else echo ((int)$r);'; exec("echo '" . $subcmd . "' | {$php_path} -q", $output); $umf = str_replace('m', '', strtolower($output[0])); $output = array(); $subcmd = '<?php $r=ini_get("post_max_size");if($r) echo $r; else echo ((int)$r);'; exec("echo '" . $subcmd . "' | {$php_path} -q", $output); $pms = str_replace('m', '', strtolower($output[0])); $output = array(); $subcmd = '<?php $r=ini_get("memory_limit");if($r) echo $r; else echo ((int)$r);'; exec("echo '" . $subcmd . "' | {$php_path} -q", $output); $ml = str_replace('m', '', strtolower($output[0])); if ((int) $pms < (int) $umf) { IO::out('post_max_size < upload_max_filesize', IO::MESSAGE_FAIL); } if ((int) $pms > (int) $ml) { IO::out('post_max_size > memory_limit', IO::MESSAGE_FAIL); } if ((int) $pms >= (int) $umf && (int) $pms < (int) $ml) { IO::out('upload_max_filesize(' . $umf . ')=< ini.post_max_size(' . $pms . ') < ini.memory_limit(' . $ml . ')', IO::MESSAGE_OK); } if (is_writable('/tmp')) { IO::out('Temp dir is writable.', IO::MESSAGE_OK); } else { IO::out('Temp dir is not writable!', IO::MESSAGE_FAIL); } IO::out(); IO::out('Check for extensions:'); exec("{$php_path} -m", $output); foreach ($this->ext as $e) { if ($e == 'gd') { if (!in_array($e, $output)) { if (!in_array('imagick', $output)) { io::out('Extension ' . $e . ' or imagick are not loaded.', IO::MESSAGE_FAIL); } else { io::out('Extension imagick is loaded.', IO::MESSAGE_OK); } } else { io::out('Extension ' . $e . ' is loaded.', IO::MESSAGE_OK); } continue; } if (!in_array($e, $output)) { io::out('Extension ' . $e . ' is not loaded.', IO::MESSAGE_FAIL); } else { if ($e == 'apc') { io::out('Extension ' . $e . ' is loaded.You can set "apc.enabled=On" in php.ini.', IO::MESSAGE_OK); continue; } else { io::out('Extension ' . $e . ' is loaded.', IO::MESSAGE_OK); } } } IO::out(); IO::out('Check for modes:'); IO::out('Check for Production:'); foreach ($this->mod_production as $k => $v) { $output = array(); $subcmd = '<?php ini_set("' . $k . '",' . (int) $v . ');$r=ini_get("' . $k . '");if($r==' . $v . ') echo 1; else echo (int)$r;'; exec("echo '" . $subcmd . "' | {$php_path} -q", $output); if ($output[0]) { IO::out($k . ' = ' . $v, IO::MESSAGE_OK); } else { IO::out($k . ' = ' . $output[0], IO::MESSAGE_FAIL); } } IO::out(); IO::out('Check for Development:'); foreach ($this->mod_dev as $k => $v) { $output = array(); $subcmd = '<?php ini_set("' . $k . '",' . (int) $v . ');$r=ini_get("' . $k . '");if($r==' . $v . ') echo 1; else echo (int)$r;'; exec("echo '" . $subcmd . "' | {$php_path} -q", $output); if ($output[0]) { IO::out($k . ' = ' . $v, IO::MESSAGE_OK); } else { IO::out($k . ' = ' . $output[0], IO::MESSAGE_FAIL); } } IO::out(); if (ArgsHolder::get()->getOption('generate-ini')) { if (!empty($toini)) { io::out('Generating php.ini', false); $res = array(); if (file_exists(Config::get('ROOT_DIR') . '/php.ini')) { $file = file(Config::get('ROOT_DIR') . '/php.ini'); for ($i = 0; $i < count($file); $i++) { if ($file[$i] != "\n") { $res[strtok($file[$i], '=')] = strtok('='); } } } foreach ($toini as $k => $v) { if (!isset($res[$k])) { $res[$k] = $v; } if ($res[$k] != $toini[$k]) { $res[$k] = $toini[$k]; } } foreach ($res as $key => $val) { $write[] = $key . '=' . $val; } $f = fopen(Config::get('ROOT_DIR') . '/php.ini', 'w'); if (flock($f, LOCK_EX)) { fwrite($f, implode("\n", $write)); flock($f, LOCK_UN); } else { echo "Couldn't get the lock!"; } fclose($f); IO::done(); } } } catch (exception $e) { io::out($e->getmessage(), IO::MESSAGE_FAIL); return; } }
/** * Удаление указанного пакета */ function cmdUninstall() { if (($nvr = ArgsHolder::get()->shiftCommand(false)) == false) { return IO::out('Specify package file', IO::MESSAGE_FAIL) | 1; } try { PackageManager::get()->startup(); PackageManager::uninstall(trim($nvr, '\'"')); PackageManager::get()->shutdown(); } catch (Exception $e) { PackageManager::getRollback()->stepBack(); return io::out($e->getMessage(), IO::MESSAGE_FAIL) | (is_null($e->getCode()) ? 2 : $e->getCode()); } }
static function undeploy($dir) { io::out('Undeploying => ~GRAY~' . substr($dir, strlen(Config::getInstance()->root_dir)) . '~~~: '); $fu = new FileUpdater(Dir::get(Config::getInstance()->root_dir, true), self::restoreTargetPath($dir), $dir); $fu->undo(); }
public function cmdRemove() { if (($name = ArgsHolder::get()->shiftCommand()) === false) { return io::out('Incorrect param count', IO::MESSAGE_FAIL); } if (file_exists($this->root_dir . '/controllers/' . $name . '.php')) { if (IO::YES == io::dialog('Realy Delete controller,models,pages with name ~WHITE~' . $name . '~~~?', IO::NO | IO::YES, IO::NO)) { IO::out('~WHITE~Removing:~~~'); self::rRem($this->root_dir . '/controllers/' . $name . '.php'); io::done(' controllers/' . $name . '.php'); self::rRem($this->root_dir . $this->models_dir . '/' . $name); io::done(' ' . $this->models_dir . '/' . $name); self::rRem($this->root_dir . '/pages/' . $name); io::done(' pages/' . $name); } } else { io::out('Controller with name ~WHITE~' . $name . '~~~ not exist ', IO::MESSAGE_FAIL); } }
/** * Откат задачи * * @param Dir $dir директория в которой были сохранены откаты */ static function undeploy($dir) { $f = $dir->getFile('message'); $f->exists() ? io::out(file_get_contents($f)) : null; }
/** * Размещение пакета * * @throws Exception if one of deploy task throws an exception */ function deploy() { // распаковть в buildpad $bp = PackageManager::getBuildpadDir()->getDir($this->name . '_' . $this->version); PackageManager::getRollback()->push('delete', $bp); Packer::unpack($this->file, $bp); // Вырезать нужный кусок их Package.xml $rp = new DOMXPath($this->xml); $nodes = $rp->query('//deploy'); if ($nodes->length == 0) { return io::out('Nothing to deploy') | 0; } $tasks = $nodes->item(0)->childNodes; // создать deployer $d = new Deployer($bp); $d->setTaskList($tasks); $d->executeTasks(); // удалить директорию в билдпаде $bp->delete(); }
function cmdFlush() { io::out('Flushing repository information...', false); $this->rl->flushRepositories(); io::done(); }
public function process() { Console::initCore(); $version = array(); exec('tidy -v 2>&1', $version, $ret); $version = implode("\n", $version); if ($ret != 0) { return io::out("You should install tidy to use converter. Exiting.") | 1; } $ah = ArgsHolder::get(); $this->show_body_only = $ah->getOption('show-body-only'); $this->tidy_only = $ah->getOption('tidy-only'); if ($f = ArgsHolder::get()->getOption('output')) { $this->output_file = trim($f, "/"); } if (($filename = ArgsHolder::get()->shiftCommand()) === false) { $this->cmdHelp(); return io::out("Choose file to convert. Exiting.", IO::MESSAGE_FAIL) | 2; } if (!file_exists($filename)) { $filename = getcwd() . "/" . trim($filename, "/"); } touch($filename); if (!file_exists($filename)) { return io::out("File " . $filename . " not found", IO::MESSAGE_FAIL) | 2; } if (!empty($this->output_file)) { if (dirname($this->output_file) == "") { $this->output_file = getcwd() . "/" . $this->output_file; } if (!is_dir(dirname($this->output_file))) { return io::out("Output direcotory doesn't exists", IO::MESSAGE_FAIL) | 4; } touch($this->output_file); } $output = $ret = null; exec("tidy -config " . escapeshellarg(dirname(__FILE__) . "/tidy.config") . " -q " . ($this->show_body_only ? " --show-body-only yes " : " ") . (" --error-file " . escapeshellarg(dirname(__FILE__)) . "/error.log ") . escapeshellarg($filename), $output, $ret); if ($ret == 0) { io::done('Tidy-ize done. '); } elseif ($ret == 1) { io::out('Tidy-ize done, but with warnings. (' . dirname(__FILE__) . "/error.log) ", IO::MESSAGE_WARN); } else { return io::out("Tidy-ize failed. ", IO::MESSAGE_FAIL) | 3; } if ($this->tidy_only) { if (!empty($this->output_file)) { io::out('Writing html to file '); $_r = file_put_contents($this->output_file, implode("\n", $output)); if ($_r === false) { return io::out("Can't write to file. May be permission denied? ", IO::MESSAGE_FAIL) | 5; } io::done(); } else { echo implode("\n", $output) . "\n"; } return 0; } $doc = new DOMDocument('1.0', 'utf-8'); $doc->loadHTML(implode("\n", $output)); $doc->encoding = "utf-8"; $subst = array("a" => "WHyperLink", "td" => "WTableColumn", "tr" => "WTableRow", "th" => "WTableHeader", "table" => "WTable", "br" => "WText:br:1", "img" => "WImage", "abbr" => "WText:abbr:1", "acronym" => "WText:acronym:1", "address" => "WText:address:1", "b" => "WText:b:1", "big" => "WText:big:1", "blockquote" => "WText:blockquote:1", "button" => "WButton:type:button", "cite" => "WText:cite:1", "code" => "WText:code:1", "div" => "WBlock", "dfn" => "WText:dfn:1", "em" => "WText:em:1", "fieldset" => "WFieldSet", "form" => "WForm", "h1" => "WText:h:1", "h2" => "WText:h:2", "h3" => "WText:h:3", "h4" => "WText:h:4", "h5" => "WText:h:5", "h6" => "WText:h:6", "hr" => "WText:hr:1", "i" => "WText:i:1", "input" => "WEdit", "ins" => "WText:ins:1", "kbd" => "WText:kbd:1", "li" => "WListItem", "ol" => "WList:ol:1", "option" => "WSelectOption", "p" => "WText:p:1", "pre" => "WText:pre:1", "q" => "WText:q:1", "samp" => "WText:samp:1", "script" => "WInlineScript", "select" => "WSelect", "small" => "WText:small:1", "span" => "WText", "strike" => "WText:strike:1", "strong" => "WText:strong:1", "style" => "WCSS", "sub" => "WText:sub:1", "sup" => "WText:sup:1", "textarea" => "WTextarea", "ul" => "WList", "var" => "WText:var:1", "body" => "root"); foreach ($subst as $replace_from => $replace_to) { @(list($replace_to, $new_attr_name, $new_attr_value) = explode(":", $replace_to)); $nl = $doc->getElementsByTagName($replace_from); for ($i = 0, $c = $nl->length; $i < $c; $i++) { $n_dn = $doc->createElement($replace_to); $cn = $nl->item(0); $cnl = $cn->childNodes; if ($cn->hasAttributes()) { foreach ($cn->attributes as $attrName => $attrNode) { if (substr((string) $attrNode->value, 0, 2) != "__" && !empty($attrNode->value)) { $n_dn->setAttribute((string) $attrName, $attrNode->value); } } } if (isset($new_attr_value, $new_attr_name)) { $n_dn->setAttribute($new_attr_name, $new_attr_value); } for ($j = 0; $j < $cnl->length; $j++) { if ($cnl->item($j) instanceof DOMText) { $n_dn->appendChild($doc->createTextNode($cnl->item($j)->nodeValue)); } else { $n_dn->appendChild($cnl->item($j)->cloneNode(true)); } } $cn->parentNode->replaceChild($n_dn, $cn); } } io::out('Dumping XML...', false); if ($this->show_body_only) { if (!empty($this->output_file)) { file_put_contents($this->output_file, utf8_decode($doc->saveXML($doc->getElementsByTagName("root")->item(0)))); } else { echo utf8_decode($doc->saveXML($doc->getElementsByTagName("root")->item(0))); } } else { if (!empty($this->output_file)) { $doc->save($this->output_file); } else { echo $doc->saveXML(); } } io::done(); }
/** * Удаление пакета */ static function uninstall($package) { $nvr = PackageManager::parseNRV($package); // проверка обратных зависимостей $res = Deps::isNoNeeded($nvr, $unstatisfied); if (count($res) == 0) { return IO::out('Packages to uninstall not found', IO::MESSAGE_FAIL); } if ($res === false) { io::out('Unable uninstall package ~WHITE~' . $nvr['name'] . '~~~ because', IO::MESSAGE_FAIL); foreach ($unstatisfied as $p => $d) { io::out('Package ' . $p . ' require ' . implode(', ', array_keys($d))); } return false; } io::out('Packages to be removed: ', false); foreach ($res as $p) { io::out($p->name . '(' . $p->version . ') ', false); } io::out(); if (IO::NO == io::dialog('Continue?', IO::YES | IO::NO, IO::NO)) { return 1; } foreach ($res as $p) { io::out('~WHITE~Undeploying ' . $p->name . '(' . $p->version . '):~~~'); $r = Deployer::undeploy(Deployer::getPackageRollbackDir($p)); if ($r || IO::OK != IO::dialog('Some part of rollback failed. Remove anyway?', IO::YES | IO::NO, IO::YES)) { Deployer::getPackageRollbackDir($p)->delete(); $p->file->delete(); PackageManager::get()->packagesSequence->removePackage($p->name, $p->version); } } }
function FileUpadter() { FileSystemObject::setRoot(dirname(__FILE__)); $d = new Dir('files'); $fu = new FileUpdater($d->getDir('source/includes'), $d->getDir('target/includes'), $d->getDir('backup/includes')); $command = ArgsHolder::get()->shiftCommand(); if ($command == 'cdo') { $fu->copyDo(); } elseif ($command == 'cundo') { $fu->copyUndo(); } elseif ($command == 'undo') { $fu->undo(); } elseif ($command == 'do') { $fu->run(); } else { io::out('command not found'); } }
public function cmdPassword() { try { $login = ArgsHolder::get()->shiftCommand(); $password = ArgsHolder::get()->shiftCommand(); if ($login === false) { return io::out('Incorrect param count', IO::MESSAGE_FAIL) | 1; } if ($user = User::findBy("login", $login)) { if (!$password) { IO::out('New password: '******'Confirm New password: '******'Passwords not match.', IO::MESSAGE_FAIL) | 2; } } $user->setPassword($password); } else { return io::out(PHP_EOL . 'User ~WHITE~' . $login . '~~~ not found', IO::MESSAGE_FAIL) | 3; } } catch (UserException $e) { return io::out($e->getMessage(), IO::MESSAGE_FAIL) | 127; } }
/** * Доставка пакетa на локальную машину * */ function fetch($package, $version, $rel, $targetDir) { // normalize NRV if (is_null($version)) { $version = '0.0'; $rel = '>='; } elseif (is_null($rel)) { $rel = '='; } // Search matched name packages $l = $this->path->ls('*.lst'); $res = array(); foreach ($l as $list) { io::out('Processing ' . basename($list, '.lst'), false) . ': '; $dom = new DomDocument(); $dom->load($list); $xp = new DOMXPath($dom); $r = $xp->query("//package[name='" . $package . "']"); for ($i = 0, $c = $r->length; $i < $c; $i++) { $e = $r->item($i); $ver = $e->getElementsByTagName('version')->item(0)->nodeValue; io::out(' ' . $ver . ' ', false); $res[$ver][] = $this->buildPackageUrl($list, $package, $ver); } io::out(); } if (!count($res)) { throw new RepositoryListException('Package ' . $package . ' not found.'); } krsort($res); foreach ($res as $v => $urls) { if (version_compare($v, $version, $rel)) { //IO::OUt($v. ' '.$rel.' '.$version); $f = $targetDir->getFile($package . '_' . $v . '.tbz'); foreach ($urls as $url) { try { $f = $this->download($url, $f); $remoteMd5 = $this->getRemoteMd5($url, true); if ($remoteMd5 == md5_file($f)) { return $f; } else { io::out('Downloaded file ' . $f . ' not correspond to its md5 sum(' . $remoteMd5 . ')'); } } catch (RepositoryListException $e) { if ($e->getCode() != 100) { throw $e; } } } } } throw new RepositoryListException('Package ' . $package . $rel . $version . ' not found'); }
private function delete($param) { if (!isset($param['key'])) { throw new ConfigTaskException('Key name not set in "' . __FUNCTION__ . '" operation. File(' . basename($this->file) . ')'); } $key = $param['key']; if (!isset($param['section'])) { foreach ($this->pattern as $sect => $keys) { if (isset($this->pattern[$sect][$key])) { $param['section'] = $sect; $this->delete($param); } } return; } $section = $param['section']; io::info("\t[~PURPLE~D~~~] [" . $section . "] " . $key); if (!isset($this->pattern[$section][$key])) { return io::out('Config key [' . $section . '][' . $key . '] not found.', IO::MESSAGE_WARN); } $this->addRollbackOperation('create', array('key' => $key, 'value' => $this->pattern[$section][$key], 'section' => $section)); $lines = $this->lines; unset($lines[$this->k2l[$section][$key]]); $newini = $this->getPattern(array_values($lines)); $diff = self::diffArray($newini, $this->pattern); if ($diff['del'] != 1 || $diff['add'] != 0 || $diff['modify'] != 0) { throw new ConfigTaskException('Error while delete constant. Given diff: ' . implode('-', $diff)); } $this->lines = $this->processLines($lines, $newK2l); $this->pattern = $newini; $this->k2l = $newK2l; }
/** * Делает резервную копию файлов преде удалением * */ private function backup() { $ol = array(); // list of backuped files and dirs foreach ($this->list as $path) { //io::out("\tBackup: ", false); // создание директории отката if (($parentDir = dirname($path)) != '.' && !$this->backup->getDir($parentDir)->exists()) { $this->backup->mkdir($parentDir); } $df = $this->target->getDir($path); if (!$df->exists()) { io::out($df . ' not found', IO::MESSAGE_WARN); continue; } elseif (is_file($df)) { $df = $this->target->getFile($path); $backupObject = $this->backup->getFile($path); //io::out ('[F] ', false); } else { $backupObject = $this->backup->getDir(dirname($path)); //io::out('[D] ', false); } //io::out($path."\t" , false); $ol[] = $df; try { $df->copy($backupObject); } catch (FileSystemException $e) { return io::Out(PHP_EOL . 'Backuping fail at ' . $df . ' With message ' . $e->getMessage(), IO::MESSAGE_FAIL); } //IO::out(' ', IO::MESSAGE_OK); } return $ol; }
/** * Производит откат исходя из информации сохраненной в директории отката $dir * * В случае успешного отката возвоащает true, false - в случае если при откате * одной из задач было выброшено исключение * * @param Dir $dir * @return bool */ static function undeploy($dir) { if (!$dir->exists()) { return io::out('Rollback dir(' . $dir . ') not exists.', IO::MESSAGE_WARN) | 2; } $list = Dir::get($dir, true)->ls('*', Dir::LS_DIR); if (count($list) == 0) { return io::out('Undeploy list is empty'); } Autoload::addDir(t(new File(__FILE__, true))->getParent()->getDir('deployTasks')); $steps = array(); foreach ($list as $d) { $steps[$d->getName()] = array('class' => file_get_contents($d->getFile('.class')), 'dir' => $d); } krsort($steps); foreach ($steps as $s) { try { call_user_func($s['class'] . '::undeploy', $s['dir']); } catch (Exception $e) { io::out($e->getMessage(), IO::MESSAGE_FAIL); $fail = true; } } return isset($fail) ? false : true; }