<?php
/*
* Поиск файлов INI уточняется.
*/
function search_ini_file ( $filename, $search_param, $return_section = false )
{
$search_key = (isset($search_param['key'])?$search_param['key']:false);
$search_value = (isset($search_param['value'])?$search_param['value']:false);
if ( !($search_key !==false || $search_value !==false) ){
return false;
}
$retvalue = false;
$handle = fopen($filename, 'r');
if ( ($search_key !== false) && ($search_value !== false) ){
$key_found = false;
$retvalue['key'] = false;
$retvalue['value'] = false;
while( !feof($handle) ) {
$line = trim(fgets($handle, 4096));
if (preg_match("/^\[$search_key\].*?$/s",$line)){
$key_found = true;
$retvalue['key'] = true;
continue;
}
if ($key_found){
if (preg_match("/^\[.*?$/", trim($line))){
break;
}else{
if ($return_section){
if ($line != '') {
list($k, $v) = split("=", $line);
$retvalue[$search_key][$k] = preg_replace("/;.*$/", "", $v);
} } }
if (preg_match("/^$search_value\s*?=.*$/", $line)){
$retvalue['value'] = true;
break;
} } }
}elseif ($search_key !== false){
$keyfound = false;
while ( !feof($handle) ){
$line = trim(fgets($handle, 4096));
if (preg_match("/^\[$search_key\].*?$/s",$line)){
$retvalue = true;
if (!$return_section){
break;
}else{
$retvalue = Array();
$keyfound = true;
continue;
} }
if ( $keyfound ){
if (preg_match("/^\[.*?$/", trim($line))){
break;
}else{
if ($return_section){
if ($line != ''){
list($k, $v) = split("=", $line);
$retvalue[$search_key][$k] = preg_replace("/;.*$/", "", $v);
} } } } }
}elseif ($search_value !== false){
while ( !feof($handle) ){
$line = trim(fgets($handle, 4096));
if (preg_match("/^$search_value\s*?=.*$/", $line)){
$retvalue = true;
if ($return_section){
$retvalue = array();
if ($line != ''){
list($k, $v) = split("=", $line);
$retvalue[$k] = preg_replace("/;.*$/", "", $v);
} }
break;
} } }
fclose($handle);
return $retvalue;
}
abstract class ini {
static function value_encode($str) {
$str = str_replace(array("\r", "\n", "\t"), array('\r', '\n', '\t'), $str);
return htmlentities($str, ENT_QUOTES, 'UTF-8');
}
static function value_decode($str) {
$str = str_replace(array('\r', '\n', '\t'), array("\r", "\n", "\t"), $str);
return html_entity_decode($str, ENT_QUOTES, 'UTF-8');
}
static function openString($string, $sect = false) {
$tmp_file = TMP . '/' . passgen() . '.tmp';
if (!@file_put_contents($tmp_file, $string)) {
return false;
}
$ini = self::read($tmp_file, $sect);
unlink($tmp_file);
return $ini;
}
static function read($file, $sect = false) {
$arr = @parse_ini_file($file, $sect);
if ($arr) {
if ($sect) {
foreach ($arr as $key => $value) {
foreach ($value as $key2 => $value2) {
$arr [$key] [$key2] = self::value_decode($value2);
}
}
} else {
foreach ($arr as $key => $value) {
$arr [$key] = self::value_decode($value);
}
}
}
return $arr;
}
static function save($file, $array, $sect = false) {
$tmp_file = TMP . '/tmp.' . passgen() . '.ini';
$ini = array();
$ini[] = "; SHCMS_ENGINE ini_class";
if ($sect) {
foreach ($array as $key => $value) {
$ini [] = '[' . self::value_encode($key) . ']';
foreach ($value as $key2 => $value2) {
$ini [] = "$key2 = \"" . self::value_encode($value2) . "\";";
}
}
} else {
foreach ($array as $key => $value) {
$ini [] = "$key = \"" . self::value_encode($value) . "\";";
}
}
if (!@file_put_contents($tmp_file, implode("\r\n", $ini))) {
return false;
}
@chmod($tmp_file, filesystem::getChmodToWrite());
if (IS_WINDOWS) {
if (@file_exists($file) && !@unlink($file)) {
return false;
}
}
if (!@rename($tmp_file, $file)) {
return false;
}
return true;
}
}
class Configuration {
const AUTO = 0;
const JSON = 2;
const PHP_INI = 4;
const XML = 16;
static private $CONF_EXT_RELATION = array(
'json' => 2, // JSON
'ini' => 4, // PHP_INI
'xml' => 16 // XML
);
static private $instances;
private $data;
static public function objectToArray($obj) {
$arr = (is_object($obj))?
get_object_vars($obj) :
$obj;
foreach ($arr as $key => $val) {
$arr[$key] = ((is_array($val)) || (is_object($val)))?
self::objectToArray($val) :
$val;
}
return $arr;
}
private function __construct($file, $type = Configuration::AUTO) {
if ($type == self::AUTO) {
$type = self::$CONF_EXT_RELATION[pathinfo($file, PATHINFO_EXTENSION)];
}
switch($type) {
case self::JSON:
$this->data = json_decode(file_get_contents($file), true);
break;
case self::PHP_INI:
$this->data = parse_ini_file($file, true);
break;
case self::XML:
$this->data = self::objectToArray(simplexml_load_file($file));
break;
}
}
static public function & getInstance($file, $type = Configuration::AUTO) {
if(! isset(self::$instances[$file])) {
self::$instances[$file] = new Configuration($file, $type);
}
return self::$instances[$file];
}
public function __get($section) {
if ((is_array($this->data)) &&
(array_key_exists($section, $this->data))) {
return $this->data[$section];
}
}
public function getAvailableSections() {
return array_keys($this->data);
}
}
$configuration = Configuration::getInstance(/*configuration filename*/);
foreach($configuration->getAvailableSections() as $pos => $sectionName) {
var_dump($sectionName);
var_dump($configuration->{$sectionName});
}
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime();
do
{ $canWrite = flock($fp, LOCK_EX);
// Если замок не получается спать 0 - 100 миллисекунд, чтобы избежать столкновения и загрузки процессора
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime()-$startTime) < 1000));
//Файл был заперт так что теперь мы можем хранить информацию
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
?>