示例#1
0
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $names = StringTools::Delimit($input->getArgument('name'), ',');
     $user = $input->getArgument('user');
     $group = $input->getArgument('group');
     $parent = $input->getOption('parent');
     // TODO support
     if (!empty($parent)) {
         var_dump($parent);
     }
     foreach ($names as $website) {
         // adding website
         //$website = $name['text'];
         LogCLI::Message('Adding website: ' . $website, 0);
         LogCLI::MessageResult('Group and user: '******'/' . $user, 2, LogCLI::INFO);
         $path = Paths::$db . Paths::$separator . $group . Paths::$separator . $user . Paths::$separator;
         if (file_exists($path)) {
             if (!file_exists($path . $website . '.yml') && Paths::getFullPath($website) === false) {
                 FileOperation::CreateEmptyFile($path . $website . '.yml');
                 LogCLI::Result(LogCLI::OK);
             } else {
                 LogCLI::Fail('Website ' . $website . ', under ' . $group . '/' . $user . ' already exists!');
                 LogCLI::Result(LogCLI::FAIL);
             }
         } else {
             LogCLI::Fail('Group and/or user ' . $group . '/' . $user . ' does not exist!');
             LogCLI::Result(LogCLI::FAIL);
         }
     }
 }
示例#2
0
文件: Stems.php 项目: niieani/napkin
 public static function LoadDefinitions($application)
 {
     foreach (glob(HC_DIR . '/stems/' . $application . "/*.php") as $filename) {
         try {
             LogCLI::Message("Loading definitions from file: {$filename}", 2);
             include $filename;
             LogCLI::Result(LogCLI::OK);
         } catch (Exception $e) {
             LogCLI::Result(LogCLI::FAIL);
             LogCLI::Fatal('Caught exception - ' . $e->getMessage());
         }
     }
     /*
     $file = HC_DIR.'/stems/'.$application.'/definitions.php';
     echo $file;
     if(file_exists($file))
     {
         try { 
             include_once($file);
         } catch (Exception $e) {
             echo 'Caught exception: ',  $e->getMessage(), "\n";
         }
     }
     */
 }
示例#3
0
    protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
    {
        $filename = $input->getArgument('filename');
        $contents = 'location / {
   if (GET) {
      echo_exec @memcache;
   }
   if (POST) {
      echo_exec @application;
   }
}

location @memcache {
   if (notfound) {
       echo_exec @application;
   }
}
location @application {
   # forwarding request to application
}
';
        //        $output->writeln('Hello World!');
        LogCLI::Message('Listing available settings: ', 0);
        var_dump(ParseNginxConfig::doParse($contents));
    }
示例#4
0
 public function set(array $params)
 {
     //var_dump($params);
     foreach ($params as $setting => $value) {
         //if(!(is_array($this->params[$setting])))
         $this->params[$setting] = $value;
         LogCLI::MessageResult("Setting {$setting}", 6, LogCLI::INFO);
         // this is currently setting too many settings than required
         // which is not optimal, but works
     }
 }
示例#5
0
 public function AddFromFiles(array $files)
 {
     foreach ($files as $file) {
         LogCLI::Message('Loading template file: ' . LogCLI::BLUE . $file . LogCLI::RESET, 2);
         if (file_exists($file)) {
             $this->AddFromFile($file);
             LogCLI::Result(LogCLI::OK);
         } else {
             LogCLI::Result(LogCLI::FAIL);
             LogCLI::Fatal("No such file: {$file}");
         }
     }
 }
示例#6
0
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $application = $input->getArgument('application');
     //        $output->writeln('Hello World!');
     LogCLI::Message('Listing available settings: ', 0);
     $configScopesNginx = ApplicationsDB::LoadApplication($application);
     //        $settingsNginx = ApplicationsDB::GetSettingsList('nginx', 'server');
     $settingsNginx = ApplicationsDB::GetSettingsList($application);
     $settings = ArrayTools::GetMultiDimentionalElements($settingsNginx, true, true);
     //        $settings = ArrayTools::GetMultiDimentionalElementsWithChildren(&$settingsNginx);
     foreach ($settings as $setting) {
         LogCLI::MessageResult(LogCLI::BLUE . $setting, 0, LogCLI::INFO);
     }
     LogCLI::Result(LogCLI::OK);
 }
示例#7
0
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     //var_dump($input->getArgument('name'));
     $names = StringTools::Delimit($input->getArgument('name'), ',');
     $group = $input->getArgument('group');
     foreach ($names as $username) {
         // adding user
         //LogCLI::MessageResult('Exclamation: '.$name['exclamation'], 2, LogCLI::INFO);
         //$username = $name['text'];
         LogCLI::Message('Adding user: '******'Creating directory: ' . $structure, 2, LogCLI::INFO);
         if (@mkdir($structure, 0755, true)) {
             LogCLI::Result(LogCLI::OK);
         } else {
             LogCLI::Fail('User ' . $username . ' already exists!');
             LogCLI::Result(LogCLI::FAIL);
         }
     }
 }
示例#8
0
#!/usr/bin/env php
<?php 
//require_once 'Parser/ConfigParser.php';
require_once __DIR__ . '/autoload.php';
use Tools\LogCLI;
use ConfigParser\ConfigParser;
use ConfigScopes\ConfigScopes;
use Tools\FileOperation;
//require_once 'Parser/ConfigParser/Action/IPPort.php';
//require_once 'Console/CommandLine.php';
//$actionInfo = \Console_CommandLine::$actions;
//var_dump($actionInfo);
LogCLI::SetVerboseLevel(5);
$config['root'] = array('user' => 'testowy', 'group' => 'group');
$config['events'] = array('connections' => 1024, 'multi_accept' => false);
//$config['http'] = array('user' => 'testowy', 'group' => 'group');
//$config['server'][0][] = array('domain'=>'koma.net');
$config['server'][0] = array('domain' => 'komalol.net');
$config['server'][0]['listen'][0] = array('ip' => '10.0.0.1', 'port' => '80');
$config['server'][0]['listen'][1] = array('ip' => '10.0.0.1', 'port' => '81');
$config['server'][0]['listen'][2] = array('ip' => '10.0.0.1', 'port' => '81');
$config['server'][1] = array('domain' => 'moma.com');
$config['server'][1]['listen'][0] = array('ip' => '192.168.0.1', 'port' => '80');
$config['server'][1]['listen'][1] = array('ip' => '192.168.0.2', 'port' => '81');
$config['server'][2] = array('domain' => 'jajco.com');
FileOperation::ToYAMLFile($config, true);
/*$template = '
user [[%(user)s]][[ %(group)s]];
listen [[%(listen)s]][[ %(listen_options)s]];';
*/
/*
示例#9
0
 private function parseWithConfig($configuration, $result)
 {
     $output = null;
     foreach ($this->options as $option) {
         /*
          * if there are multiple paths for one setting
          */
         if (is_array($option->path)) {
             foreach ($option->path as $config => $path) {
                 //($setting = ArrayTools::accessArrayElementByPath($configuration, $path)) !== null ?: $setting = $option->default[$config];
                 $setting = ArrayTools::accessArrayElementByPath($configuration, $path);
                 if ($setting === null) {
                     if ($option->default[$config] !== null) {
                         LogCLI::MessageResult('Setting ' . $config . ' not set, defaulting to: ' . $option->default[$config], 7, LogCLI::OK);
                     }
                     $setting = $option->default[$config];
                 }
                 $values[$config] = $setting;
             }
             $this->_dispatchAction($option, $values, $result);
         } else {
             //($setting = ArrayTools::accessArrayElementByPath($configuration, $option->path)) !== null ?: $setting = $option->default;
             $setting = ArrayTools::accessArrayElementByPath($configuration, $option->path);
             if ($setting === null) {
                 $option->setDefaults();
                 if ($option->default !== null) {
                     LogCLI::MessageResult('Setting ' . $option->name . ' not set, defaulting to: ' . $option->default, 7, LogCLI::OK);
                 }
                 $setting = $option->default;
             }
             //var_dump($setting);
             /*
              *  If we got an array, how do we divide it?
              *  By default by ' ' (space), but sometimes we want eg. PHP_EOL, or comma.
              */
             $value = StringTools::makeList($setting, $option->divideBy);
             $this->_dispatchAction($option, $value, $result);
         }
     }
     //foreach(preg_split("/(\r?\n)/", $this->template) as $line)
     foreach (explode(PHP_EOL, $this->template) as $line) {
         //$parsedline = ParseTools::sprintfn($line, $result->options);
         $parsedline = ParseTools::parseStringWithReplacementList($line, $result->options);
         // if all we got is whitespace, don't add it
         if (strlen(rtrim($parsedline)) < 1) {
             continue;
         }
         // if we got a multiline responds we have to indent it
         // TODO: maybe explode "\n" or PHP_EOL would be better?
         //            if(count($lines = preg_split("/(\r?\n)/", $parsedline)) > 1)
         if (count($lines = explode(PHP_EOL, $parsedline)) > 1) {
             $indentedlines = array_shift($lines) . PHP_EOL;
             foreach ($lines as &$multiline) {
                 $indentedlines .= StringTools::indentLinesToMatchOther(trim($line), $line, $multiline) . PHP_EOL;
             }
             $parsedline = rtrim($indentedlines);
         }
         $output .= $parsedline . PHP_EOL;
     }
     return $output;
 }
示例#10
0
文件: Add.php 项目: niieani/napkin
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $names = StringTools::TypeList($input->getArgument('name'), '@', ',');
     $userorgroup = $input->getArgument('userorgroup');
     //        $group = $input->getArgument('group');
     //        $group =
     //        $directories = $input->getArgument('directories');
     //        $files = array();
     //ApplicationsDB::LoadAll();
     foreach ($names as $name) {
         if ($name['exclamation'] !== false) {
             // adding user
             LogCLI::MessageResult('Exclamation: ' . $name['exclamation'], 2, LogCLI::INFO);
             $username = $name['text'];
             LogCLI::Message('Adding user: '******'Creating directory: ' . $structure, 2, LogCLI::INFO);
             if (@mkdir($structure, 0755, true)) {
                 LogCLI::Result(LogCLI::OK);
             } else {
                 LogCLI::Result(LogCLI::FAIL);
                 LogCLI::Fail('User ' . $username . ' already exists!');
                 //LogCLI::Fail($e->getMessage());
             }
         } else {
             // adding website
             $website = $name['text'];
             LogCLI::Message('Adding website: ' . $website, 0);
             $username = !empty($userorgroup) ? $userorgroup : Paths::$defaultUser;
             $group = Paths::$defaultGroup;
             LogCLI::MessageResult('User and group: ' . $username . '/' . $group, 2, LogCLI::INFO);
             $path = Paths::$db . Paths::$separator . $group . Paths::$separator . $username . Paths::$separator;
             if (file_exists($path)) {
                 if (!file_exists($path . $website . '.yml') && Paths::getFullPath($website) === false) {
                     FileOperation::CreateEmptyFile($path . $website . '.yml');
                     LogCLI::Result(LogCLI::OK);
                 } else {
                     LogCLI::Result(LogCLI::FAIL);
                     LogCLI::Fail('Website ' . $website . ', under ' . $group . '/' . $username . ' already exists!');
                 }
             } else {
                 LogCLI::Result(LogCLI::FAIL);
                 LogCLI::Fail('Group and/or user ' . $group . '/' . $username . ' does not exist!');
             }
         }
     }
 }
示例#11
0
 public static function StripTag($format, $origin = false)
 {
     /*
             while (($posRight = strpos($reversed, ']]', $posRight+$i)) !== false)
             {
                 if($lastPosRight != 0)
                     $fragment = substr($reversed, 0, $lastPosRight);
                 else $fragment = '';
                 
                 if($fragment != '') 
                 {
                     LogCLI::Message('Cutting: '.LogCLI::GREEN_LIGHT.(strrev($fragment)).LogCLI::RESET, 5);
                     self::StripTag(strrev($fragment));
                     LogCLI::Result(LogCLI::OK);
                 }
                 $i = 2;
                 $lastPosRight = $posRight;
                 
             }*/
     //$path = new MakePath();
     $lastPosLeft = $posLeft = 0;
     $i = 0;
     $finitoLeft = false;
     $level = 0;
     $posLeftAcc = array();
     $posRightAcc = array();
     $iterationLeft = 0;
     while ($posLeft + $i <= strlen($format)) {
         $posLeft = strpos($format, '[[', $posLeft + $i);
         if ($posLeft === false) {
             $posLeft = strlen($format);
             $finitoLeft = true;
         }
         //if($lastPosLeft != 0)
         //var_dump($posLeft);
         //$fragment = substr($format, $posLeft, strlen($format)-$posLeft);
         $fragment = substr($format, $lastPosLeft, $posLeft - $lastPosLeft);
         //$reversed = strrev($format);
         //else $fragment = '';
         if ($fragment != '') {
             //self::StripTag($fragment);
             //$path->begin($fragment);
             $level++;
             LogCLI::Message('    ' . $level . ') Start: ' . LogCLI::GREEN_LIGHT . $fragment . LogCLI::RESET, 5);
             $iterationLeft++;
             $lastPosRight = $posRight = 0;
             $j = 0;
             //$finitoRight = false;
             $iterationRight = 0;
             while ($posRight + $j <= strlen($fragment)) {
                 $posRight = strpos($fragment, ']]', $posRight + $j);
                 //if($posRight === false) { $posRight = strlen($fragment); $finitoRight = true; }
                 if ($posRight === false) {
                     break;
                 }
                 $iterationRight++;
                 $posLeftAcc[$level][$iterationLeft] = $lastPosLeft + $lastPosRight;
                 $posRightAcc[$level][$iterationLeft] = strlen($fragment) - $lastPosRight;
                 //$posRightAcc[$level][$iterationLeft][$iterationRight] = $lastPosLeft+($posRight-$lastPosRight);
                 /* napisać klasę w stylu MakePath z trzema poleceniami: start, end - start powieksza level i dokleja zawartość do niższego lvlu */
                 LogCLI::MessageResult('Pos: ' . $posRight . ' LastPos: ' . $lastPosRight, 5);
                 $subfragment = substr($fragment, $lastPosRight, $posRight - $lastPosRight);
                 LogCLI::MessageResult($level . ') End: ' . LogCLI::GREEN_LIGHT . $subfragment . ']]' . LogCLI::RESET, 5);
                 //$path->begin($subfragment);
                 //$path->end();
                 $level--;
                 LogCLI::Result(LogCLI::OK);
                 $j = 2;
                 $lastPosRight = $posRight;
                 //if($finitoRight === true) break;
             }
             //LogCLI::Result(LogCLI::OK);
         }
         $i = 2;
         $lastPosLeft = $posLeft;
         if ($finitoLeft === true) {
             break;
         }
     }
     LogCLI::Result(LogCLI::OK);
     //var_dump($posLeftAcc);
     //var_dump($posRightAcc);
     foreach ($posLeftAcc as $level => $listLeft) {
         foreach ($listLeft as $n => $posLeft) {
             var_dump($fragment = substr($format, $posLeft, $posRightAcc[$level][$n]));
         }
     }
     //$path->end();
     //var_dump($path->getPaths());
 }
示例#12
0
文件: napkin.php 项目: niieani/napkin
<?php

/**
 * User: NIXin
 * Date: 23.09.2011
 * Time: 00:30
 */
require_once __DIR__ . '/autoload.php';
use Tools\LogCLI;
//use Tools\Errors;
//use HypoConf\Commands;
use HypoConf\Paths;
use Tools\XFormatterHelper;
use Symfony\Component\Console;
set_error_handler('\\Tools\\Errors::Handle');
Paths::$root = __DIR__;
Paths::$db = __DIR__ . '/database';
LogCLI::SetVerboseLevel(6);
$application = new Console\Application('NAPKIN', '0.9.1');
$application->setHelperSet(new Console\Helper\HelperSet(array(new Console\Helper\FormatterHelper(), new Console\Helper\DialogHelper(), new XFormatterHelper())));
$application->add(new HypoConf\ConsoleCommands\ListSettings());
$application->add(new HypoConf\ConsoleCommands\LoadSetAndSave());
$application->add(new HypoConf\ConsoleCommands\Generate());
$application->add(new HypoConf\ConsoleCommands\AddSite());
$application->add(new HypoConf\ConsoleCommands\AddUser());
$application->run();
//$shell = new Console\Shell($application);
//$shell->run();
示例#13
0
 public static function Add($arguments)
 {
     foreach (StringTools::TypeList($arguments['name'], '@') as $argument) {
         $name = $argument['text'];
         if ($argument['exclamation'] !== false) {
             LogCLI::MessageResult('Exclamation: ' . $argument['exclamation'], 2, LogCLI::INFO);
             $username = $name;
             LogCLI::Message('Adding user: '******'name2']) ? $arguments['name2'] : Paths::$defaultGroup;
             $structure = Paths::$db . Paths::$separator . $group . Paths::$separator . $username;
             LogCLI::MessageResult('Creating directory: ' . $structure, 2, LogCLI::INFO);
             if (@mkdir($structure, 0755, true)) {
                 LogCLI::Result(LogCLI::OK);
             } else {
                 LogCLI::Result(LogCLI::FAIL);
                 LogCLI::Fail('User ' . $username . ' already exists!');
                 //LogCLI::Fail($e->getMessage());
             }
         } else {
             // adding website
             $website = $name;
             LogCLI::Message('Adding website: ' . $website, 0);
             $username = isset($arguments['name2']) ? $arguments['name2'] : Paths::$defaultUser;
             $group = Paths::$defaultGroup;
             LogCLI::MessageResult('Username and group: ' . $username . '/' . $group, 2, LogCLI::INFO);
             $path = Paths::$db . Paths::$separator . $group . Paths::$separator . $username . Paths::$separator;
             if (file_exists($path)) {
                 if (!file_exists($path . $website . '.yml') && Paths::getFullPath($website) === false) {
                     FileOperation::CreateEmptyFile($path . $website . '.yml');
                     LogCLI::Result(LogCLI::OK);
                 } else {
                     LogCLI::Result(LogCLI::FAIL);
                     LogCLI::Fail('Website ' . $website . ', under ' . $group . '/' . $username . ' already exists!');
                 }
             } else {
                 LogCLI::Result(LogCLI::FAIL);
                 LogCLI::Fail('Group and/or user ' . $group . '/' . $username . ' does not exist!');
             }
         }
     }
 }
示例#14
0
文件: hc.php 项目: niieani/napkin
                if ($result->command->args) {
                    Commands::GenerateParsed($result->command->args);
                }
                break;
            case 'add':
                if ($result->command->args) {
                    Commands::Add($result->command->args);
                }
                break;
            default:
                displayHelp('_NotImplemented');
        }
    } else {
        displayHelp();
    }
    LogCLI::Result(LogCLI::INFO);
} catch (Exception $exc) {
    $parser->displayError($exc->getMessage());
}
function displayHelp($setting = false)
{
    echo PHP_EOL . 'HypoConf Manual' . PHP_EOL;
    switch ($setting) {
        case '_NotImplemented':
            echo 'Sorry, that function has not been implemented yet!' . PHP_EOL;
            break;
        case '_NoArgs':
            echo 'You haven\'t provided enough arguments!' . PHP_EOL;
            break;
        case '_Unknown':
            echo 'Unknown function!' . PHP_EOL;
示例#15
0
<?php

/**
 * Created by Bazyli Brzoska
 * Date: 27.02.11
 * Time: 21:24
 */
require_once '../autoload.php';
use Tools\LogCLI;
use Tools\ParseTools;
LogCLI::SetVerboseLevel(10);
class SuperStack
{
    public $superStack = array();
    protected $level = -1;
    protected $currentPointer;
    protected $parentID = array();
    public function __construct()
    {
        $this->Begin();
    }
    public function Add($value)
    {
        $this->currentPointer[] = $value;
    }
    public function Begin()
    {
        $this->level++;
        $next = count($this->currentPointer);
        $this->currentPointer[$next] = array();
        $this->parentID[$this->level] = count($this->superStack);
示例#16
0
 /**
  * similar to makeTree, but also parses the tree and puts the actual elements in place
  *
  * @param string $scope
  * @param bool $parseResult
  * @param int $depth
  * @param bool $parentIterative
  * @param string $parent
  * @return array
  */
 public function parseTree($scope, $parseResult = false, $depth = 0, $parentIterative = false, $parent = '')
 {
     $parentDisplay = null;
     ++$depth;
     $return = array();
     if (!empty($parent)) {
         $fullScopePath = $parent . '/' . $scope;
         $parentDisplay = LogCLI::GREEN . $parent . LogCLI::RESET . ' => ';
     } else {
         $fullScopePath = $scope;
     }
     if ($parseResult === false) {
         $pregSubject =& $this->templates[$scope];
     } elseif (isset($this->results[$scope])) {
         $pregSubject =& $this->results[$scope];
     } else {
         return $return;
     }
     preg_match_all('/<<(?<name>\\w+)>>/', $pregSubject, $matches);
     preg_match_all('/<!<(?<name>\\w+)>!>/', $pregSubject, $matchesIterative);
     if (!empty($matches['name'])) {
         foreach ($matches['name'] as $match) {
             if (!$this->patterns[$match]) {
                 $this->patterns[$match] = '<<' . $match . '>>';
             }
             LogCLI::Message('(' . $depth . ') Non-iterative match: ' . $parentDisplay . LogCLI::BLUE . $scope . LogCLI::RESET . " => " . LogCLI::YELLOW . $match . LogCLI::RESET, 2);
             $children = $this->parseTree($match, false, $depth, $parentIterative, $scope);
             LogCLI::Result(LogCLI::INFO);
             if ($parentIterative === true) {
                 $path = $scope . '/' . $match;
                 if (!$this->parsers[$match]->loadConfiguration($this->config, $path)) {
                     LogCLI::MessageResult('No configuration data for: ' . LogCLI::BLUE . $scope . LogCLI::RESET, LogCLI::INFO);
                 }
                 LogCLI::Message("Ordering parsing of: " . LogCLI::BLUE . $path . LogCLI::RESET . " at depth = {$depth}", 3);
                 LogCLI::MessageResult('Parent scope is iterative: ' . LogCLI::BLUE . $scope . LogCLI::RESET, LogCLI::INFO);
                 $this->results[$path] = $this->parsers[$match]->getParsed();
                 LogCLI::Result(LogCLI::INFO);
             } elseif (!isset($this->results[$match])) {
                 $this->parsers[$match]->loadConfiguration($this->config, $match);
                 LogCLI::Message("Ordering parsing of: " . LogCLI::BLUE . $match . LogCLI::RESET . " at depth = {$depth}", 3);
                 LogCLI::MessageResult('Parent scope is not iterative: ' . LogCLI::BLUE . $scope . LogCLI::RESET, LogCLI::INFO);
                 $this->results[$match] = $this->parsers[$match]->getParsed();
                 foreach ($children as $child) {
                     //LogCLI::MessageResult("Inserting: $child to ".LogCLI::BLUE.$match.LogCLI::RESET." at depth = $depth", 5);
                     $this->results[$match] = $this->insertScope($child, $match, $this->patterns[$child]);
                 }
                 LogCLI::Result(LogCLI::INFO);
             }
         }
         $return = $matches['name'];
     }
     if (!empty($matchesIterative['name'])) {
         foreach ($matchesIterative['name'] as $match) {
             $path = $fullScopePath . '/' . $match;
             $this->patterns[$match] = '<!<' . $match . '>!>';
             $this->results[$match] = null;
             $this->results[$path] = null;
             /*
              * recursive iterative matching
              */
             //$currentConfig = $this->parsers[$match]->loadConfiguration(&$this->config, $path, $match);
             $currentConfig =& ArrayTools::accessArrayElementByPath($this->config, $path);
             //$parentConfig = ArrayTools::accessArrayElementByPath(&$this->config, $fullScopePath);
             // translation:
             if (!ArrayTools::isIterativeScope($currentConfig)) {
                 LogCLI::MessageResult('Non-iterative format, translating path: ' . LogCLI::BLUE . $path . LogCLI::RESET, LogCLI::INFO);
                 //ArrayTools::replaceArrayElementByPath(&$this->config, $path, ArrayTools::translateToIterativeScope($match, $currentConfig));
                 $currentConfig = ArrayTools::translateToIterativeScope($match, $currentConfig);
             }
             foreach (array_keys($currentConfig) as $id) {
                 LogCLI::Message('(' . $depth . ') ' . $parentDisplay . LogCLI::BLUE . $scope . LogCLI::RESET . " => " . LogCLI::YELLOW . $match . LogCLI::RESET . " => [" . LogCLI::GREEN_LIGHT . $id . LogCLI::RESET . "]", 2);
                 LogCLI::MessageResult("Ordering parsing of: " . LogCLI::BLUE . "{$match}" . LogCLI::RESET . " at depth = {$depth}", 3);
                 $iterativePath = "{$fullScopePath}/{$match}/{$id}";
                 $this->parsers[$match]->loadConfiguration($this->config, $iterativePath);
                 // at this moment it's still the same configuration, just cut out
                 $this->results[$iterativePath] = $this->parsers[$match]->getParsed();
                 /**
                  * let's parse all the children
                  */
                 LogCLI::Message('(' . $depth . ') ' . $parentDisplay . LogCLI::BLUE . $scope . LogCLI::RESET . " => " . LogCLI::YELLOW . $match . LogCLI::RESET . " => " . LogCLI::RED . '[iterative]' . LogCLI::RESET, 2);
                 $children = $this->parseTree($iterativePath, true, $depth, true, '');
                 //LogCLI::MessageResult("Child's path: ".LogCLI::YELLOW.$iterativePath.LogCLI::RESET, 7);
                 foreach ($children as $child) {
                     $this->results[$iterativePath] = $this->insertScope("{$iterativePath}/{$child}", $iterativePath, $this->patterns[$child], $this->results[$iterativePath]);
                 }
                 LogCLI::MessageResult("Adding up the iterative scope values: " . LogCLI::YELLOW . $iterativePath . LogCLI::RESET, 5);
                 $this->results[$path] .= trim($this->results[$iterativePath]) . PHP_EOL;
                 LogCLI::Result(LogCLI::INFO);
                 // end children parse
                 LogCLI::Result(LogCLI::INFO);
                 // end iteration
             }
             $this->results[$match] = rtrim($this->results[$path]);
         }
         $return = array_merge($return, $matchesIterative['name']);
     }
     if ($depth == 1) {
         $this->parsers[$scope]->loadConfiguration($this->config, $scope);
         $this->results[$scope] = $this->parsers[$scope]->getParsed();
         $all_matches = array_merge_recursive($matches, $matchesIterative);
         if (!empty($all_matches['name'])) {
             foreach ($all_matches['name'] as $match) {
                 //LogCLI::MessageResult("Inserting: $match to ".LogCLI::BLUE.$scope.LogCLI::RESET, 5);
                 $this->results[$scope] = $this->insertScope($match, $scope);
             }
         }
     }
     return $return;
 }
示例#17
0
文件: Nginx.php 项目: niieani/napkin
 public function ParseFromYAMLs(array $files)
 {
     $this->SetAutomatedValues();
     //Stems::LoadDefinitions('nginx');
     $last = false;
     $total = count($files) - 1;
     $sites_defaults = array();
     foreach ($files as $i => $file) {
         if ($total == $i) {
             $last = true;
         }
         LogCLI::Message('Loading file: ' . LogCLI::BLUE . $file . LogCLI::RESET, 1);
         if (file_exists($file)) {
             LogCLI::Result(LogCLI::OK);
             LogCLI::Message('Parsing file: ' . LogCLI::BLUE . $file . LogCLI::RESET, 1);
             try {
                 $config = YAML::load($file);
                 LogCLI::Result(LogCLI::OK);
             } catch (Exception $e) {
                 LogCLI::Result(LogCLI::FAIL);
                 LogCLI::Fail($e->getMessage());
             }
             if (isset($config['nginx'])) {
                 // adding to main DB
                 $this->settingsDB = System::MergeArrays($this->settingsDB, $config);
                 foreach ($this->usableScopes as $arrayPath) {
                     //LogCLI::MessageResult($arrayPath);
                     //var_dump(self::getArrayElementByPath($config['nginx'], $arrayPath, 1));
                     /*
                     foreach(self::accessArrayElementByPath($config['nginx'], $arrayPath) as $scope => $scopeConfig)
                     {
                         echo("skope ".$scope.":\n");
                     }
                     */
                     //LogCLI::MessageResult('Path: '.LogCLI::BLUE.$arrayPath.LogCLI::RESET, 6, LogCLI::INFO);
                     foreach (self::getArrayElementByPath($config['nginx'], $arrayPath, true) as $scope => $scopeConfig) {
                         if ($scopeConfig !== false) {
                             //echo("skope ".$scope.":\n");
                             //var_dump($scopeConfig);
                             if (is_array($scopeConfig) && $scope != 'sites') {
                                 //LogCLI::MessageResult("Number of dimentions in scope [$scope]: ".self::array_dimen_count($scopeConfig), 3);
                                 //self::array_dimen_count($scopeConfig);
                                 //var_dump($scopeConfig);
                                 //LogCLI::MessageResult($scope);
                                 NginxConfig::setAll(self::accessArrayElementByPath($config['nginx'], $arrayPath), self::accessArrayElementByPath($this->nginx, $arrayPath));
                                 if ($last) {
                                     //LogCLI::MessageResult($scope);
                                     LogCLI::Message("Generating scope: [{$arrayPath}]", 3);
                                     NginxScope::addAllStems(self::accessArrayElementByPath($this->nginx, $arrayPath), $this->confScope);
                                     LogCLI::Result(LogCLI::INFO);
                                 }
                             }
                         }
                     }
                 }
                 // sites scopes
                 if (isset($config['nginx']['sites']['_defaults'])) {
                     $config['nginx']['sites']['_defaults'] = self::ConformizeConfigSite($config['nginx']['sites']['_defaults']);
                     $sites_defaults = System::MergeArrays($sites_defaults, $config['nginx']['sites']['_defaults']);
                 }
                 if (isset($config['nginx']['sites'])) {
                     foreach ($config['nginx']['sites'] as $key => $site) {
                         if ($key != '_defaults') {
                             $site = self::ConformizeConfigSite($site);
                             $siteScope[$key] = new NginxScope();
                             LogCLI::Message("Pushing defaults for subscope [server]: {$key}", 3);
                             NginxConfig::resetAll($this->nginx['sites']);
                             if (isset($sites_defaults)) {
                                 NginxConfig::setAll($sites_defaults, $this->nginx['sites']);
                             }
                             LogCLI::Result(LogCLI::INFO);
                             LogCLI::Message("Setting in subscope [server]: {$key}", 3);
                             //$siteScope[$key] = new NginxScope;
                             NginxConfig::setAll($site, $this->nginx['sites']);
                             LogCLI::Result(LogCLI::INFO);
                             LogCLI::Message("Adding subscope [server]: {$key}", 3);
                             NginxScope::addAllStems($this->nginx['sites'], $siteScope[$key]);
                             LogCLI::Result(LogCLI::INFO);
                         }
                     }
                 }
                 if (isset($siteScope)) {
                     foreach ($siteScope as $scope) {
                         LogCLI::Message("Adding scope: [server]", 3);
                         $this->confScope->addStem(array('scope' => 'http', 'output' => $scope->returnScopes(), 'level' => 1));
                         LogCLI::Result(LogCLI::INFO);
                     }
                 }
                 $this->confScope->orderScopes(array('_ROOT', 'events', 'http'));
             }
         } else {
             LogCLI::Result(LogCLI::FAIL);
             LogCLI::Fatal("No such file: {$file}");
         }
     }
     //return false;
 }
示例#18
0
 /**
  * version of sprintf for cases where named arguments are desired (python syntax)
  *
  * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
  *
  * with sprintfn: sprintfn('second: %(second)s ; first: %(first)s', array(
  *  'first' => '1st',
  *  'second'=> '2nd'
  * ));
  *
  * @static
  * @param string $format sprintf format string, with any number of named arguments
  * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
  * @return string|false result of sprintf call, or bool false on error
  */
 public static function sprintfn($format, array $args = array())
 {
     LogCLI::Message('Parsing: ' . LogCLI::GREEN_LIGHT . $format . LogCLI::RESET, 5);
     // map of argument names to their corresponding sprintf numeric argument value
     $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);
     // find the next named argument. each search starts at the end of the previous replacement.
     for ($pos = 0; preg_match('/(?<=%)\\(([a-zA-Z_]\\w*)\\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
         $arg_pos = $match[0][1];
         $arg_len = strlen($match[0][0]);
         $arg_key = $match[1][0];
         LogCLI::Message('Parsing argument: ' . LogCLI::YELLOW . $arg_key . LogCLI::RESET, 6);
         // programmer did not supply a value for the named argument found in the format string
         if (!array_key_exists($arg_key, $arg_nums)) {
             //var_dump($arg_nums);
             //$arg_nums[$arg_key] = false;
             ////array_push($arg_nums, $arg_key);
             //var_dump($arg_nums);
             LogCLI::MessageResult('Not set: ' . LogCLI::YELLOW . $arg_key . LogCLI::RESET . ', skipping', 4, LogCLI::INFO);
             //user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_NOTICE);
             //return false;
             $format = substr_replace($format, $replace = '', $arg_pos - 1, $arg_len + 2);
         } else {
             //$posLeft = strlen($format)-strpos(strrev($format), '[[', strlen($format)-$arg_pos);
             $posLeft = strlen($format) - strpos(strrev($format), '[[', strlen($format) - $arg_pos);
             $posRight = strpos($format, ']]', $arg_pos);
             LogCLI::MessageResult('Original left position: ' . LogCLI::BLUE . $arg_pos . LogCLI::RESET, 6, LogCLI::INFO);
             LogCLI::MessageResult('Found left position:    ' . LogCLI::YELLOW . $posLeft . LogCLI::RESET, 6, LogCLI::INFO);
             LogCLI::MessageResult('Found right position:   ' . LogCLI::YELLOW . $posRight . LogCLI::RESET, 6, LogCLI::INFO);
             $format = substr_replace($format, '', $posRight, 2);
             $format = substr_replace($format, '', $posLeft - 2, 2);
             $arg_pos = $posLeft - 2 + ($arg_pos - $posLeft);
             //$format = str_replace(']]', 'a', $format);
             // replace the named argument with the corresponding numeric one
             $format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len);
         }
         $pos = $arg_pos + strlen($replace);
         // skip to end of replacement for next iteration
         LogCLI::Result(LogCLI::INFO);
     }
     $format = preg_replace('#\\[\\[.*?\\]\\]#', '', $format);
     LogCLI::Result(LogCLI::INFO);
     return vsprintf($format, array_values($args));
 }
示例#19
0
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $name = $input->getArgument('name');
     $settingPath = $input->getArgument('path');
     $values = $input->getArgument('values');
     //        $multiline = $input->getOption('multiline');
     if (empty($values)) {
         // enable multiline input
         $dialog = $this->getHelperSet()->get('dialog');
         if (!$dialog->askConfirmation($output, '<question>Would you like to provide multiline input? Answering no, quits the command. (y/n) </question> ', false)) {
             return;
         } else {
             $input = array();
             $output->writeln('Type <info>EOT</info> in a new line when you finished inputting all the options.');
             while (1) {
                 $input[] = $dialog->ask($output, null, 'foo');
                 if (end($input) == 'EOT') {
                     array_pop($input);
                     break;
                 }
             }
             $values[] = implode(PHP_EOL, $input);
             //                $values = $input;
             //var_dump($values);
         }
     }
     ApplicationsDB::LoadAll();
     foreach (StringTools::TypeList($name) as $argument) {
         if ($argument['exclamation'] !== false) {
             // TODO: actually handle the exclamators
             LogCLI::MessageResult('Exclamation: ' . $argument['exclamation'], 4, LogCLI::INFO);
         } else {
             //siteYML
             $file = Paths::getFullPath($argument['text']);
             if ($file !== false) {
                 $application = 'nginx';
                 $basicScope = 'server';
                 $settings = ApplicationsDB::GetSettingsList($application, $basicScope);
                 $value = ArrayTools::dearraizeIfNotRequired($values);
                 //$chain = StringTools::Delimit($chain, '.');
                 //$settingPath = implode('/', $chain);
                 LogCLI::MessageResult('Path of the setting: ' . $settingPath, 4, LogCLI::INFO);
                 if ($path = SettingsDB::findPathForSetting($settings, $settingPath, $basicScope)) {
                     $settingsDB = new ConfigScopes\SettingsDB();
                     // load the original file first
                     $settingsDB->mergeFromYAML($file);
                     $currentSetting = $settingsDB->returnOneByPath($settingPath);
                     /**
                      * if there is a difference
                      * TODO: probably dearraize not required here
                      */
                     if (ArrayTools::dearraizeIfNotRequired($currentSetting) != $value) {
                         $formatter = $this->getHelperSet()->get('xformatter');
                         $displayValues = array();
                         foreach ($values as $valueLine) {
                             $displayValues = array_merge($displayValues, StringTools::multilineStringToArray($valueLine));
                         }
                         $displayCurrentSetting = array();
                         foreach ((array) $currentSetting as $valueLine) {
                             $displayCurrentSetting = array_merge($displayCurrentSetting, StringTools::multilineStringToArray($valueLine));
                         }
                         $toFormat = array(array('messages' => $displayCurrentSetting, 'style' => 'error'), array('messages' => array('> >'), 'style' => 'fg=yellow;bg=black;other=blink;other=bold', 'large' => false), array('messages' => $displayValues, 'style' => 'fg=black;bg=yellow;other=bold'));
                         //array_merge(array('With the following data:'), (array) $values)
                         $output->writeln($formatter->formatMultipleBlocks($toFormat, ' ', true));
                         $dialog = $this->getHelperSet()->get('dialog');
                         if (!$dialog->askConfirmation($output, 'Are you sure that you want to make this change? (type "y" to confirm) ', false)) {
                             return;
                         }
                         // make the tree
                         $setting = Tree::addToTreeAndSet(explode('/', $path), $value);
                         //var_dump($setting);
                         // add/replace the setting
                         $settingsDB->mergeFromArray($setting);
                         // save the file with the new setting
                         $settingsDB->returnYAML($file);
                     } else {
                         /**
                          * nothing to do, it's all the same
                          */
                         $output->writeln('<fg=yellow;other=bold>No need to change, the values are already identical!</fg=yellow;other=bold>');
                     }
                 } else {
                     // TODO
                 }
             } else {
                 LogCLI::Fail('Sorry, no site by name: ' . $argument['text']);
             }
         }
     }
 }
示例#20
0
 /**
  * @param string $file          path to a YAML file
  * @param string|bool $path     start the merge at designated settings path
  * @param bool $applyDefaults
  * @param bool $mergeDefaults
  * @param bool $createNewIfNonexistant
  * @param bool $addFilename
  * @return void
  */
 public function mergeFromYAML($file, $path = false, $applyDefaults = false, $mergeDefaults = true, $createNewIfNonexistant = false, $addFilename = false)
 {
     LogCLI::Message('Loading file: ' . LogCLI::BLUE . $file . LogCLI::RESET, 1);
     if (file_exists($file)) {
         LogCLI::Result(LogCLI::OK);
         LogCLI::Message('Parsing YAML file: ' . LogCLI::BLUE . $file . LogCLI::RESET, 1);
         try {
             //$config = YAML::load($file);
             $config = Yaml::parse($file);
             //                 if the file is empty create an empty array:
             //                    $config = array();
             if (!empty($config)) {
                 if ($path === false) {
                     $this->DB = ArrayTools::MergeArrays($this->DB, $config);
                     if ($mergeDefaults === true) {
                         $this->mergeDefinitionsDB($config, $this->defaultsDefinitions, $applyDefaults, 'defaults');
                     }
                 } else {
                     if ($addFilename === true) {
                         $fileInfo = FileOperation::pathinfo_utf($file);
                         $config['filename'] = $fileInfo['filename'];
                         //$config['filename'] = $file;
                     }
                     if (!isset($config['template']) && (!isset($config['disabled']) || $config['disabled'] == false)) {
                         $iteration = $this->mergeOneIterativeByPath($path, $config);
                         //var_dump($this->defaultsDefinitions);
                         /**
                          * applying parents as defaults
                          */
                         if (isset($config['parent'])) {
                             foreach ((array) $config['parent'] as $parentName) {
                                 if (is_array($parentFiles = FileOperation::findFile($parentName, Paths::$db))) {
                                     if (count($parentFiles) > 1) {
                                         LogCLI::MessageResult('You have to be more specific in the way you specify the parent, found more than one file under this name: ' . $parentName, 0, LogCLI::INFO);
                                     } else {
                                         $parentFile =& current($parentFiles);
                                         LogCLI::Message('Parent definition found: ' . LogCLI::BLUE . $parentFile . LogCLI::RESET . ', parsing and merging.', 2);
                                         if (!isset($this->parentDefinitions[$parentFile])) {
                                             $parentConfig = array('parent' => Yaml::parse($parentFile));
                                             $this->parentDefinitions[$parentFile] = array();
                                             $this->mergeDefinitionsDB($parentConfig, $this->parentDefinitions[$parentFile], false, 'parent');
                                         }
                                         $this->applyDefaults($this->DB, $this->parentDefinitions[$parentFile], $path . '/' . $iteration, 'parent', true, false);
                                         LogCLI::Result(LogCLI::OK);
                                     }
                                     //var_dump($this->parentDefinitions);
                                 }
                             }
                         }
                         if ($applyDefaults === true) {
                             $this->applyDefaults($this->DB, $this->defaultsDefinitions, $path . '/' . $iteration, 'defaults', false, false);
                         }
                     }
                 }
                 LogCLI::MessageResult('Settings DB populated with new data!', 5, LogCLI::INFO);
             } else {
                 LogCLI::MessageResult('File empty, ignoring', 5, LogCLI::INFO);
             }
             LogCLI::Result(LogCLI::OK);
         } catch (\Exception $e) {
             LogCLI::Result(LogCLI::FAIL);
             LogCLI::Fail($e->getMessage());
         }
     } else {
         LogCLI::Result(LogCLI::FAIL);
         LogCLI::Fail("No such file: {$file}");
         if ($createNewIfNonexistant === true) {
             LogCLI::Message('Creating a new empty file.', 0);
             try {
                 //fclose(fopen($file, 'x'));
                 FileOperation::CreateEmptyFile($file);
                 $this->mergeFromYAML($file, $path, $applyDefaults, $mergeDefaults, false);
                 LogCLI::Result(LogCLI::OK);
             } catch (\Exception $e) {
                 LogCLI::Result(LogCLI::FAIL);
                 LogCLI::Fail($e->getMessage());
             }
         }
     }
 }
示例#21
0
 public static function setAll($data, array $appconfs)
 {
     foreach ($appconfs as $setting) {
         //var_dump($setting);
         //this is dirty, fix me (so many copies of the yaml array!)
         if (is_array($setting) && isset($setting['_definition']) && is_object($setting['_definition'])) {
             LogCLI::MessageResult('Setting according to _definition!', 6, LogCLI::INFO);
             $setting['_definition']->set($data);
         } elseif (is_object($setting)) {
             $setting->set($data);
         }
     }
 }