#===================================================================
493477
public static function getCharset($str) {
    if (empty($str)) {
      throw new Exception('Argument str cannot be empty');
    }
    $ord = self::unistr2ords($str);
    return self::getDominant($ord);
  }
1248802
function _fetch($ignore_fields=false)
	{
		# KMN # if ($this->connection->debug) ADOConnection::outp("_fetch()");
		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
			if ($this->fetchMode & ADODB_FETCH_NUM) {
				//# KMN # if ($this->connection->debug) ADOConnection::outp("fetch mode: both");
				$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_BOTH);
			} else {
				//# KMN # if ($this->connection->debug) ADOConnection::outp("fetch mode: assoc");
				$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_ASSOC);
			}

			if (is_array($this->fields)) {
				if (ADODB_ASSOC_CASE == 0) {
					foreach($this->fields as $k=>$v) {
						$this->fields[strtolower($k)] = $v;
					}
				} else if (ADODB_ASSOC_CASE == 1) {
					foreach($this->fields as $k=>$v) {
						$this->fields[strtoupper($k)] = $v;
					}
				}
			}
		} else {
			//# KMN # if ($this->connection->debug) ADOConnection::outp("fetch mode: num");
			$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_NUMERIC);
		}
		if(is_array($this->fields) && array_key_exists(1,$this->fields) && !array_key_exists(0,$this->fields)) {//fix fetch numeric keys since they're not 0 based
			$arrFixed = array();
			foreach($this->fields as $key=>$value) {
				if(is_numeric($key)) {
					$arrFixed[$key-1] = $value;
				} else {
					$arrFixed[$key] = $value;
				}
			}
			//if($this->connection->debug) ADOConnection::outp("<hr>fixing non 0 based return array, old: ".print_r($this->fields,true)." new: ".print_r($arrFixed,true));
			$this->fields = $arrFixed;
		}
		if(is_array($this->fields)) {
			foreach($this->fields as $key=>$value) {
				if (is_object($value) && method_exists($value, 'format')) {//is DateTime object
					$this->fields[$key] = $value->format("Y-m-d\TH:i:s\Z");
				}
			}
		}
		if($this->fields === null) $this->fields = false;
		# KMN # if ($this->connection->debug) ADOConnection::outp("<hr>after _fetch, fields: <pre>".print_r($this->fields,true)." backtrace: ".adodb_backtrace(false));
		return $this->fields;
	}
669302
public function run()
    {
        $pattern = [
            '/(?:is\s+null)|(like\s+null)|'.
            '(?:(?:^|\W)in[+\s]*\([\s\d"]+[^()]*\))/ims',
        ];
        $this->value = preg_replace($pattern, '"=0', $this->value);

        $this->value = preg_replace('/[^\w\)]+\s*like\s*[^\w\s]+/ims', '1" OR "1"', $this->value);
        $this->value = preg_replace('/null([,"\s])/ims', '0$1', $this->value);
        $this->value = preg_replace('/\d+\./ims', ' 1', $this->value);
        $this->value = preg_replace('/,null/ims', ',0', $this->value);
        $this->value = preg_replace('/(?:between)/ims', 'or', $this->value);
        $this->value = preg_replace('/(?:and\s+(\d+)\.?\d*)/ims', ' and $1', $this->value);
        $this->value = preg_replace('/(?:\s+and\s+)/ims', ' or ', $this->value);

        $pattern = [
            '/(?:not\s+between)|(?:is\s+not)|(?:not\s+in)|'.
            '(?:xor|<>|rlike(?:\s+binary)?)|'.
            '(?:regexp\s+binary)|'.
            '(?:sounds\s+like)/ims',
        ];
        $this->value = preg_replace($pattern, '!', $this->value);
        $this->value = preg_replace('/"\s+\d/', '"', $this->value);
        $this->value = preg_replace('/(\W)div(\W)/ims', '$1 OR $2', $this->value);
        $this->value = preg_replace('/\/(?:\d+|null)/', null, $this->value);

        return $this->value;
    }
53774
public function process()
    {
        parent::process();

        try {
            $value = $this->getNumericValue($this->value);
        } catch (SwatIntegerOverflowException $e) {
            $value = null;
        }

        if ($value !== null) {
            if (
                $this->minimum_value !== null &&
                $value < $this->minimum_value
            ) {
                $message = $this->getValidationMessage('below-minimum');
                $minimum_value = str_replace(
                    '%',
                    '%%',
                    $this->getDisplayValue($this->minimum_value)
                );

                $message->primary_content = sprintf(
                    $message->primary_content,
                    $minimum_value
                );

                $this->addMessage($message);
            }
            if (
                $this->maximum_value !== null &&
                $value > $this->maximum_value
            ) {
                $message = $this->getValidationMessage('above-maximum');
                $maximum_value = str_replace(
                    '%',
                    '%%',
                    $this->getDisplayValue($this->maximum_value)
                );

                $message->primary_content = sprintf(
                    $message->primary_content,
                    $maximum_value
                );

                $this->addMessage($message);
            }
        }
    }
992092
public function getData()
    {
        $this->validate(
            'username',
            'password',
            'transactionId',
            'amount',
            'currency',
            'clientIp',
            'returnUrl',
            'cancelUrl',
            'notifyUrl',
            'clientMerchantId'
        );

        $document = new \DOMDocument('1.0', 'utf-8');
        $document->formatOutput = false;
        $document->createElement('soapenv:Header');

        $envelope = $document->appendChild(
            $document->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'soapenv:Envelope')
        );
        $envelope->setAttribute('xmlns:urn', 'urn:pscservice');

        $body = $envelope->appendChild(
            $document->createElement('soapenv:Body')
        );

        $disposition = $body->appendChild(
            $document->createElement('urn:createDisposition')
        );

        $disposition->appendChild(
            $document->createElement('urn:username', $this->getUsername())
        );

        $disposition->appendChild(
            $document->createElement('urn:password', $this->getPassword())
        );

        $disposition->appendChild(
            $document->createElement('urn:mtid', $this->getTransactionId())
        );

        $disposition->appendChild(
            $document->createElement('urn:subId', $this->getSubId())
        );

        $disposition->appendChild(
            $document->createElement('urn:amount', $this->getAmount())
        );

        $disposition->appendChild(
            $document->createElement('urn:currency', $this->getCurrency())
        );

        $disposition->appendChild(
            $document->createElement('urn:okUrl', rawurlencode($this->getReturnUrl()))
        );

        $disposition->appendChild(
            $document->createElement('urn:nokUrl', rawurlencode($this->getCancelUrl()))
        );

        $disposition->appendChild(
            $document->createElement('urn:pnUrl', rawurlencode($this->getNotifyUrl()))
        );

        $disposition->appendChild(
            $document->createElement('urn:shopId', $this->getShopId())
        );

        $disposition->appendChild(
            $document->createElement('urn:shopLabel', $this->getShopLabel())
        );

        $disposition->appendChild(
            $document->createElement('urn:merchantclientid', $this->getClientMerchantId())
        );

        if ($countryRestrictionValues = $this->getCountryRestrictions()) {
            $countryRestriction = $disposition->appendChild(
                $document->createElement('urn:dispositionRestrictions')
            );

            $countryRestriction->appendChild(
                $document->createElement('urn:key', 'COUNTRY')
            );

            $countryRestriction->appendChild(
                $document->createElement('urn:value', implode(',', $countryRestrictionValues))
            );
        }

        if ($minAgeRestrictionValue = $this->getMinAgeRestriction()) {
            $minAgeRestriction = $disposition->appendChild(
                $document->createElement('urn:dispositionRestrictions')
            );

            $minAgeRestriction->appendChild(
                $document->createElement('urn:key', 'MIN_AGE')
            );

            $minAgeRestriction->appendChild(
                $document->createElement('urn:value', $minAgeRestrictionValue)
            );
        }

        if ($minKycLevelRestrictionValue = $this->getMinKycLevelRestriction()) {
            $minKycLevelRestriction = $disposition->appendChild(
                $document->createElement('urn:dispositionRestrictions')
            );

            $minKycLevelRestriction->appendChild(
                $document->createElement('urn:key', 'MIN_KYC_LEVEL')
            );

            $minKycLevelRestriction->appendChild(
                $document->createElement('urn:value', $minKycLevelRestrictionValue)
            );
        }

        return $document->saveXML();
    }
139001
public function init()
	{
		if(isset($this->checkBoxHtmlOptions['name']))
			$name=$this->checkBoxHtmlOptions['name'];
		else
		{
			$name=$this->id;
			if(substr($name,-2)!=='[]')
				$name.='[]';
			$this->checkBoxHtmlOptions['name']=$name;
		}
		$name=strtr($name,array('['=>"\\[",']'=>"\\]"));

		if($this->selectableRows===null)
		{
			if(isset($this->checkBoxHtmlOptions['class']))
				$this->checkBoxHtmlOptions['class'].=' select-on-check';
			else
				$this->checkBoxHtmlOptions['class']='select-on-check';
			return;
		}

		$cball=$cbcode='';
		if($this->selectableRows==0)
		{
			//.. read only
			$cbcode="return false;";
		}
		elseif($this->selectableRows==1)
		{
			//.. only one can be checked, uncheck all other
			$cbcode="jQuery(\"input:not(#\"+this.id+\")[name='$name']\").prop('checked',false);";
		}
		elseif(strpos($this->headerTemplate,'{item}')!==false)
		{
			//.. process check/uncheck all
			$cball=<<<CBALL
jQuery(document).on('click','#{$this->id}_all',function() {
	var checked=this.checked;
	jQuery("input[name='$name']:enabled").each(function() {this.checked=checked;});
});

CBALL;
			$cbcode="jQuery('#{$this->id}_all').prop('checked', jQuery(\"input[name='$name']\").length==jQuery(\"input[name='$name']:checked\").length);";
		}

		if($cbcode!=='')
		{
			$js=$cball;
			$js.=<<<EOD
jQuery(document).on('click', "input[name='$name']", function() {
	$cbcode
});
EOD;
			Yii::app()->getClientScript()->registerScript(__CLASS__.'#'.$this->id,$js);
		}
	}
736202
public function index() {
        $wt_tree = Globals::getTree();
        $controller = new PageController();
        $controller
        ->setPageTitle(I18N::translate('Sosa Configuration'))
        ->restrictAccess(Auth::check())
        ->addExternalJavascript(WT_AUTOCOMPLETE_JS_URL)
        ->addInlineJavascript('autocomplete();')
        ->addInlineJavascript('
            $( document ).ready(function() {
                $("#bt_sosa_compute").click(function() {
                    majComputeSosa($("#maj_sosa_input_userid, #maj-sosa-config-select option:selected").val());
                 });
            });
            
            function majComputeSosa(user_id) {
                jQuery("#bt_sosa_compute").prop( "disabled", true );
                jQuery("#bt_sosa_computing").empty().html("<i class=\"icon-loading-small\"></i>&nbsp;'. I18N::translate('Computing...') .'");
                jQuery("#bt_sosa_computing").load(
		          "module.php?mod='.$this->module->getName().'&mod_action=SosaConfig@computeAll&ged='.$wt_tree->getNameUrl().'&userid=" + user_id,
		          function() {
			         jQuery("#bt_sosa_compute").prop( "disabled", false );
                  });
            }');
        
        $action = Filter::post('action');
        if($action === 'update') $this->update($controller);
        
        $view_bag = new ViewBag();
        $view_bag->set('title', $controller->getPageTitle());
        $view_bag->set('tree', $wt_tree);
        $view_bag->set('form_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaConfig&ged='.$wt_tree->getNameUrl());
        
        $users_root = array();
        $users_js_array = 'var users_array = [];';
        if(Auth::check()) {
            $root_id = $wt_tree->getUserPreference(Auth::user(), 'MAJ_SOSA_ROOT_ID');
            $users_root[] = array( 'user' => Auth::user(), 'rootid' => $root_id);
            $users_js_array .=  'users_array["'.Auth::user()->getUserId().'"] = "' . $root_id . '";';
            
            if(Auth::isManager($wt_tree)) {
                $default_user = User::find(-1);
                $default_root_id = $wt_tree->getUserPreference($default_user, 'MAJ_SOSA_ROOT_ID');
                $users_root[] = array( 'user' => $default_user, 'rootid' => $default_root_id);
                $users_js_array .=  'users_array["'.$default_user->getUserId().'"] = "' . $default_root_id . '";';
            }
        }
        $view_bag->set('users_settings', $users_root);       
        
        $controller->addInlineJavascript($users_js_array . '            
                $("#maj-sosa-config-select").change(function() {
                    $("#rootid").val(users_array[this.value]);
                });
             ');
        
        ViewFactory::make('SosaConfig', $this, $controller, $view_bag)->render();   
    }
1296919
public function index()
    {
        $this->loadModel('System.Options');
        $languages = LocaleToolbox::languagesList();
        $arrayContext = [
            'schema' => [
                'site_title' => 'string',
                'site_slogan' => 'string',
                'site_description' => 'string',
                'site_email' => 'string',
                'site_contents_home' => 'integer',

                'site_maintenance' => 'boolean',
                'site_maintenance_ip' => 'string',
                'site_maintenance_message' => 'string',

                'default_language' => 'string',
                'url_locale_prefix' => 'string',
            ],
            'defaults' => [],
            'errors' => [],
        ];
        $variables = $this->Options
            ->find()
            ->where(['name IN' => array_keys($arrayContext['schema'])])
            ->all();

        foreach ($variables as $var) {
            $arrayContext['defaults'][$var->name] = $var->value;
        }

        if ($this->request->data()) {
            $validator = $this->_mockValidator();
            $errors = $validator->errors($this->request->data());

            if (empty($errors)) {
                foreach ($this->request->data() as $k => $v) {
                    $this->Options->update($k, $v, null, false);
                }
                snapshot();
                $this->Flash->success(__d('system', 'Configuration successfully saved!'));
                $this->redirect($this->referer());
            } else {
                $arrayContext['errors'] = $errors;
                $this->Flash->danger(__d('system', 'Configuration could not be saved, please check your information.'));
            }
        }

        $pluginSettings = plugin()
            ->filter(function ($plugin) {
                return !$plugin->isTheme && $plugin->hasSettings;
            });

        $this->title(__d('system', 'Site’ Configuration'));
        $this->set(compact('arrayContext', 'languages', 'variables', 'pluginSettings'));
        $this->Breadcrumb->push('/admin/system/configuration');
    }
534033
public function parse()
    {
        // Fetch the basic values from possible user defined values.
        if ($this->entity->hasConfig("labels")) {
            if ($this->entity->hasConfig("labels.singular_name")) {
                $this->singular = $this->entity->getConfig("labels.singular_name");
            } elseif ($this->entity->hasConfig("labels.name")) {
                $this->plural = $this->entity->getConfig("labels.name");
            }
        }

        if (!empty($this->singular) && empty($this->plural)) {
            $this->plural = Inflector::pluralize($this->singular);
        }

        if (!empty($this->plural) && empty($this->singular)) {
            $this->singular = Inflector::singularize($this->plural);
        }

        // If nothing is sent in, guess the name from the object name.
        if (empty($this->plural) && empty($this->singular)) {
            $this->singular   = ucfirst(Inflector::singularize($this->entity->getShortName()));
            $this->plural     = ucfirst(Inflector::pluralize($this->entity->getShortName()));
        }
    }
1280950
public function setupObject()
    {
        parent::setupObject();
        $this->commonName = $this->getDatabase()->getTablePrefix() . $this->getAttribute("name");
        $this->nonPrefixedName = $this->getAttribute('name');

        // retrieves the method for converting from specified name to a PHP name.
        $this->phpNamingMethod = $this->getAttribute("phpNamingMethod", $this->getDatabase()->getDefaultPhpNamingMethod());

        $this->phpName = $this->getAttribute("phpName", $this->buildPhpName($this->getStdSeparatedName()));

        $this->idMethod = $this->getAttribute("idMethod", $this->getDatabase()->getDefaultIdMethod());
        $this->allowPkInsert = $this->booleanValue($this->getAttribute("allowPkInsert"));

        $this->skipSql = $this->booleanValue($this->getAttribute("skipSql"));
        $this->readOnly = $this->booleanValue($this->getAttribute("readOnly"));

        $this->abstractValue = $this->booleanValue($this->getAttribute("abstract"));
        $this->baseClass = $this->getAttribute("baseClass");
        $this->basePeer = $this->getAttribute("basePeer");
        $this->alias = $this->getAttribute("alias");

        $this->heavyIndexing = ($this->booleanValue($this->getAttribute("heavyIndexing")) || ("false" !== $this->getAttribute("heavyIndexing") && $this->getDatabase()->isHeavyIndexing()));
        $this->description = $this->getAttribute("description");
        $this->interface = $this->getAttribute("interface"); // sic ('interface' is reserved word)
        $this->treeMode = $this->getAttribute("treeMode");

        $this->reloadOnInsert = $this->booleanValue($this->getAttribute("reloadOnInsert"));
        $this->reloadOnUpdate = $this->booleanValue($this->getAttribute("reloadOnUpdate"));
        $this->isCrossRef = $this->booleanValue($this->getAttribute("isCrossRef", false));
        $this->defaultStringFormat = $this->getAttribute('defaultStringFormat');
    }
597487
public function getCode()
    {
        if (!$this->isSuccessful() && isset($this->data['error']) && isset($this->data['error']['code'])) {
            return $this->data['error']['code'];
        }

        return null;
    }
491783
public function index()
    {
        $this->requireAdmin();

        $this->layout->title = Lang::get('settings');

        $this->view->settings = $this->settings;

        $basicSettings = array();
        if (isset($this->settings['phpci']['basic'])) {
            $basicSettings = $this->settings['phpci']['basic'];
        }

        $buildSettings = array();
        if (isset($this->settings['phpci']['build'])) {
            $buildSettings = $this->settings['phpci']['build'];
        }

        $latestBuildsSettings = array();
        if (isset($this->settings['phpci']['latest_builds'])) {
            $latestBuildsSettings = $this->settings['phpci']['latest_builds'];
        }

        $emailSettings = array();
        if (isset($this->settings['phpci']['email_settings'])) {
            $emailSettings = $this->settings['phpci']['email_settings'];
        }

        $authSettings = array();
        if (isset($this->settings['phpci']['authentication_settings'])) {
            $authSettings = $this->settings['phpci']['authentication_settings'];
        }

        $this->view->configFile = PHPCI_CONFIG_FILE;
        $this->view->basicSettings = $this->getBasicForm($basicSettings);
        $this->view->latestBuildsSettings = $this->getLatestBuildsForm($latestBuildsSettings);
        $this->view->buildSettings = $this->getBuildForm($buildSettings);
        $this->view->github = $this->getGithubForm();
        $this->view->emailSettings = $this->getEmailForm($emailSettings);
        $this->view->authenticationSettings = $this->getAuthenticationForm($authSettings);
        $this->view->isWriteable = $this->canWriteConfig();

        if (!empty($this->settings['phpci']['github']['token'])) {
            $this->view->githubUser = $this->getGithubUser($this->settings['phpci']['github']['token']);
        }

        return $this->view->render();
    }
1257040
public function getData()
    {
        if (isset($this->functions) || isset($this->constructor)) {
            $arguments = func_get_args();
            $functionData = '';

            if (empty($this->toAddress) && !empty($this->bytecode)) {
                $constructor = $this->constructor;

                if (count($arguments) < count($constructor['inputs'])) {
                    throw new InvalidArgumentException('Please make sure you have put all constructor params and callback.');
                }
                if (!isset($this->bytecode)) {
                    throw new \InvalidArgumentException('Please call bytecode($bytecode) before getData().');
                }
                $params = array_splice($arguments, 0, count($constructor['inputs']));
                $data = $this->ethabi->encodeParameters($constructor, $params);
                $functionData = $this->bytecode . Utils::stripZero($data);
            } else {
                $method = array_splice($arguments, 0, 1)[0];

                if (!is_string($method)) {
                    throw new InvalidArgumentException('Please make sure the method is string.');
                }
    
                $functions = [];
                foreach ($this->functions as $function) {
                    if ($function["name"] === $method) {
                        $functions[] = $function;
                    }
                };
                if (count($functions) < 1) {
                    throw new InvalidArgumentException('Please make sure the method exists.');
                }
    
                $params = $arguments;
                $data = "";
                $functionName = "";
                foreach ($functions as $function) {
                    if (count($arguments) !== count($function['inputs'])) {
                        continue;
                    }
                    try {
                        $data = $this->ethabi->encodeParameters($function, $params);
                        $functionName = Utils::jsonMethodToString($function);
                    } catch (InvalidArgumentException $e) {
                        continue;
                    }
                    break;
                }
                if (empty($data) || empty($functionName)) {
                    throw new InvalidArgumentException('Please make sure you have put all function params and callback.');
                }
                $functionSignature = $this->ethabi->encodeFunctionSignature($functionName);
                $functionData = Utils::stripZero($functionSignature) . Utils::stripZero($data);
            }
            return $functionData;
        }
    }
541721
public function create()
    {
        $content = '';
        $pageNumber = $this->getPageNumber();

        if ($pageNumber === 0) {
            $pageNumber = 1;
        }

        if ($this->lastPage > 1) {
            $content .= "<div class='pagination'>";

            $content .= $this->renderPreviousLink($pageNumber);

            //not enough pages to bother breaking it up
            if ($this->lastPage < 7 + ($this->adjacent * 2)) {
                for ($counter = 1; $counter <= $this->lastPage; $counter++) {
                    $content .= $this->createCurrentActiveLink($pageNumber, $counter);
                }
            } elseif ($this->lastPage > 5 + ($this->adjacent * 2)) {
                //close to beginning; only hide later pages
                if ($pageNumber < 1 + ($this->adjacent * 2)) {
                    for ($counter = 1; $counter < 4 + ($this->adjacent * 2); $counter++) {
                        $content .= $this->createCurrentActiveLink($pageNumber, $counter);
                    }
                    $content .= '...';
                    $content .= $this->createSecondLink();
                } elseif (
                    $this->lastPage - ($this->adjacent * 2) > $pageNumber
                    && $pageNumber > ($this->adjacent * 2)
                ) {
                    $content .= $this->createPrimaryLink();
                    $content .= '...';

                    for (
                        $counter = $pageNumber - $this->adjacent;
                        $counter <= $pageNumber + $this->adjacent;
                        $counter++
                    ) {
                        $content .= $this->createCurrentActiveLink($pageNumber, $counter);
                    }

                    $content .= '...';
                    $content .= $this->createPrimaryLink();
                    $content .= $this->createSecondLink();
                } else {
                    //close to end; only hide early pages

                    $content .= $this->createPrimaryLink();

                    $content .= '...';
                    for (
                        $counter = $this->lastPage - (2 + ($this->adjacent * 2));
                        $counter <= $this->lastPage;
                        $counter++
                    ) {
                        $content .= $this->createCurrentActiveLink($pageNumber, $counter);
                    }
                }
            }

            $content .= $this->renderNextLink($counter, $pageNumber);
        }

        $this->paginationLinks = $content;
    }
397793
private function Initialize()
    {
        if (!$this->initialized)
        {
            $schema = $this->GetSchema();
            $t = $schema->Table();
            $sql = $schema->SqlBuilder();
           
            $what = $t->ToSelectList();
            $where = $sql->Equals($t->Field($schema->KeyField()), $sql->Value($this->KeyValue()));
            $select = $sql->Select(false, $what, $t, $where);
            $reader = $schema->Connection()->ExecuteQuery((string)$select);
            if ($reader->Read())
                $this->InitFromReader($reader);

            $reader->Close();
        }
    }
535142
public function init()
	{
		if(isset($this->htmlOptions['id']))
			$id=$this->htmlOptions['id'];
		else
			$id=$this->htmlOptions['id']=$this->getId();
		if($this->url!==null)
			$this->url=CHtml::normalizeUrl($this->url);
		$cs=Yii::app()->getClientScript();
		$cs->registerCoreScript('treeview');
		$options=$this->getClientOptions();
		$options=$options===array()?'{}' : CJavaScript::encode($options);
		$cs->registerScript('Yii.CTreeView#'.$id,"jQuery(\"#{$id}\").treeview($options);");
		if($this->cssFile===null)
			$cs->registerCssFile($cs->getCoreScriptUrl().'/treeview/jquery.treeview.css');
		elseif($this->cssFile!==false)
			$cs->registerCssFile($this->cssFile);

		echo CHtml::tag('ul',$this->htmlOptions,false,false)."\n";
		echo self::saveDataAsHtml($this->data);
	}
838092
public function execute() {
        $this->log
            ->printAsMessage()
            ->info($this->getDescription())
            ->printEmptyLine()
            ->printAsOutput();

        $appName = $this->config['composer']['extra']['name'];

        $configDir = '.';

        switch (strtolower(substr(PHP_OS, 0, 3))) {
            case 'win':
                if (array_key_exists('LOCALAPPDATA', $_SERVER) &&
                    is_string($_SERVER['LOCALAPPDATA']) &&
                    strlen($_SERVER['LOCALAPPDATA']) > 0) {
                    $configDir = sprintf('%s\\%s', $_SERVER['LOCALAPPDATA'], $appName);
                }
                break;
            default:
                if (array_key_exists('USER', $_SERVER) &&
                    $_SERVER['USER'] !== 'root' &&
                    array_key_exists('HOME', $_SERVER) &&
                    is_string($_SERVER['HOME']) &&
                    strlen($_SERVER['HOME']) > 0) {
                    $configDir = sprintf('%s/.%s', $_SERVER['HOME'], $appName);
                } elseif (array_key_exists('USER', $_SERVER) &&
                    $_SERVER['USER'] === 'root') {
                    $configDir = sprintf('/etc/%s', $appName);
                }
                break;
        }

        $configFile = $configDir . DIRECTORY_SEPARATOR . 'config.json';

        $schemaFile = $this->config['appDir'] . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'schema.json';

        $this->log->notice('This command will ask you several questions.');
        $this->log->notice(
            'After that a configuration file will be written to %s.',
            $configFile
        );
        $this->log->notice('If you are unsure what to do please refer to the documentation.');

        if (file_exists($configFile)) {
            $this->log->notice('Configuration file already exists.');

            if (!$this->askForPermission('Do you want to overwrite it?')) {
                $this->log->notice('Skipping');
                return $this;
            }

            $this->log->debug('Create backup of old configuration file…');
        }

        $rules = JSONFile::read($schemaFile);

        $config = $this->walk($rules, $this->config);

        $this->createDir($configDir);

        if (file_exists($configFile)) {
            $backupFile = sprintf(
                '%s%sconfig_%s.json',
                DIRECTORY_SEPARATOR,
                $configDir,
                date('Y-m-d_His')
            );

            $this->log->info(
                'Create backup of old configuration file and write it to "%s"…',
                $backupFile
            );

            $this->copyFile($configFile, $backupFile);
        }

        $this->log->info('Write configuration settings to file…');

        JSONFile::write($configFile, $config);

        $this->log->info(
            'All configuration steps completed. Your settings are stored to:

    %1$s

Validate your configuration settings with:

    %2$s configtest',
            $configFile,
            $this->config['args'][0]
        );

        return $this;
    }