Files
cmp-php-util/cmpUtil.php
T
2022-07-11 12:31:43 +12:00

328 lines
7.4 KiB
PHP

<?php
trait cmpUtil {
var $gitStatus = "Unknown";
var $gitDate = "";
var $gitTime = "";
var $gitTimeStamp = "";
var $gitCommit = "";
var $gitComment = "";
function toArray($obj) {
$re = array();
$in = null;
if(is_array($obj))
$in = $obj;
if(is_object($obj))
$in = get_object_vars($obj);
if(is_string($obj)) return $obj;
if(is_float($obj)) return $obj;
if(is_bool($obj)) return $obj;
if(is_int($obj)) return $obj;
foreach((array) $in as $k => $v) {
if(is_array($in[$k])) {
// echo "$k array\n";
$re[$k] = $this->toArray($v);
continue;
}
if(is_object($in[$k])) {
// echo "$k object\n";
$re[$k] = $this->toArray($v);
continue;
}
// echo "$k string?\n";
$re[$k] = $v;
}
return $re;
}
function errorJSON($err, $f = 2) {
switch($err) {
case JSON_ERROR_NONE : $this->e('Ошибок нет' , $f); break;
case JSON_ERROR_DEPTH : $this->e('Достигнута максимальная глубина стека' , $f); break;
case JSON_ERROR_STATE_MISMATCH : $this->e('Некорректные разряды или не совпадение режимов' , $f); break;
case JSON_ERROR_CTRL_CHAR : $this->e('Некорректный управляющий символ' , $f); break;
case JSON_ERROR_SYNTAX : $this->e('Синтаксическая ошибка, не корректный JSON' , $f); break;
case JSON_ERROR_UTF8 : $this->e('Некорректные символы UTF-8, возможно неверная кодировка' , $f); break;
case JSON_ERROR_RECURSION : $this->e('Одна или несколько зацикленных ссылок в кодируемом значении' , $f); break;
case JSON_ERROR_INF_OR_NAN : $this->e('Одно или несколько значений NAN или INF в кодируемом значении' , $f); break;
case JSON_ERROR_UNSUPPORTED_TYPE : $this->e('Передано значение с неподдерживаемым типом' , $f); break;
case JSON_ERROR_INVALID_PROPERTY_NAME : $this->e('Имя свойства не может быть закодировано' , $f); break;
case JSON_ERROR_UTF16 : $this->e('Некорректный символ UTF-16, возможно некорректно закодирован' , $f); break;
default : $this->e('Неизвестная ошибка' , $f); break;
}
}
function decodeJSONRaw($str, $f = 2) {
$obj = json_decode(
$str , // string $json
true , // ?bool $associative = null
512 , // int $depth = 512
JSON_INVALID_UTF8_IGNORE // int $flags = 0
);
$err = json_last_error();
if($err === JSON_ERROR_NONE)
return $this->toArray($obj);
$this->errorJSON($err, $f + 1);
$this->d("Invalid JSON: " . $str, $f);
return null;
}
function decodeJSON($str, $d = 0) {
$m = array();
// eq '/[[:cntrl:]]/u';
// $re = '/[\x00-\x1F\x7F]/u';
// Add ignore 0x09, 0x0a, 0x0d
$re = '/[\x00-\x08\x0b-\x0c\x0e-\x1F\x7F]/u';
// $ign = array("0x09", "0x0a", "0x0d");
if(preg_match_all($re, $str, $m)) {
$tr = array();
for($i = 0; $i < count($m[0]); $i++) {
$bin = $m[0][$i];
if(isset($tr[$bin]))
continue;
$hex = "0x" . bin2hex($bin);
// if(in_array($hex, $ign))
// continue;
$tr[$bin] = $hex;
if($d)
$this->d("decodeJSON: Translate " . $hex);
}
$str = strtr($str, $tr);
}
return $this->decodeJSONRaw($str, 6);
}
function encodeJSON($obj) {
$text = json_encode($obj, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$err = json_last_error();
if($err === JSON_ERROR_NONE)
return $text;
$this->errorJSON($err);
return null;
}
function readFile($file) {
return @file_get_contents(
$file , // string
false , // bool $use_include_path
null , // ?resource $context
0 , // int $offset
$this->parm["maxFileSize"] , // ?int $length
);
}
function readJSON($file) {
$raw = $this->readFile($file);
if(!$raw) {
$this->e("Can't read '$file'");
return false;
}
$obj = $this->decodeJSON($raw, 1);
if(!$obj) {
$this->e("Invalid JSON '$file'");
return false;
}
// var_export($obj);
return $obj;
}
function readJSONConf($file) {
$obj = $this->readJSON($file);
if(!$obj)
return false;
foreach($obj as $k => $v) {
// $this->d("Set parm .$k to $v");
$this->parm[$k] = $v;
}
if(@$this->parm["timezone"]) {
$this->d("Set timezone '" . $this->parm["timezone"] . "'");
date_default_timezone_set($this->parm["timezone"]);
}
if(!@$this->parm["maxFileSize"])
$this->parm["maxFileSize"] = 1048576;
$this->d("Set maxFileSize '" . $this->parm["maxFileSize"] . "'");
if(is_array(@$this->parm["php_ini"])) {
foreach($this->parm["php_ini"] as $k => $v) {
ini_set($k, $v);
}
}
return true;
}
function fgExec($cmd) {
$cmd .= " 2>/tmp/fgExec.err";
$this->d("fgExec: $cmd");
ob_start();
passthru($cmd, $ret);
$out = ob_get_contents();
ob_end_clean();
$a = array(
"return" => $ret,
"stderr" => array(),
"output" => $out
);
$err = @file("/tmp/fgExec.err");
// var_export($err);
for($i = 0; $i < count($err); $i++) {
$str = trim($err[$i], "\r\n");
// $this->d($str);
$a["stderr"][] = $str;
}
@unlink("/tmp/fgExec.err");
return $a;
}
function getGitStatus() {
$ret = $this->fgExec("git status");
// $this->d(join("\n", $ret));
$out = trim($ret["output"], "\n \t\r");
if(!$out) {
$this->d($ret["stderr"][0]);
return false;
}
$lin = explode("\n", $out);
$cnt = count($lin);
if($lin[$cnt-1] == "nothing to commit, working tree clean") {
$this->gitStatus = "treeClean";
$this->d("Git tree clean");
} else {
$this->gitStatus = "treeModified";
$this->d("Last string: " . $lin[$cnt-1]);
}
return;
}
function getGitLog1() {
$ret = $this->fgExec("git log -1");
// $this->d(join("\n", $ret));
$out = trim($ret["output"], "\n \t\r");
if(!$out) {
$this->d($ret["stderr"][0]);
return false;
}
$lin = explode("\n", $out);
$cnt = count($lin);
$wrd = explode(" ", $lin[0]);
$this->gitCommit = $wrd[1];
$this->gitComment = $lin[$cnt-1];
$wrd = explode(" ", $lin[2]);
array_shift($wrd);
$this->gitTimeStamp = strtotime(join(" ", $wrd));
return;
}
function isMD5($str) {
if(preg_match("/^[0-9a-f]{32}$/", $str))
return true;
return false;
}
function isUNID($str) {
return $this->isMD5($str);
}
function isDateFT($str) {
if(preg_match("/^(20[0-9]{2}-[01][0-9]-[0-3][0-9]) ([0-2][0-9]:[0-5][0-9]:[0-5][0-9])$/", $str))
return true;
return false;
}
function isP7Phone($str) {
if(preg_match("/^\+7(9[0-9]{2})([0-9]{7})$/", $str))
return true;
return false;
}
function isPxPhone($str) {
if(preg_match("/^\+7(9[0-9]{2})([0-9]+)$/", $str)) {
return true;
}
if(preg_match("/^\+([0-9]+)$/", $str)) {
$this->d("Wild number $str");
return true;
}
return false;
}
function normalizePhone($inp) {
if(preg_match("/^((\+7)|8)?(\d{3})(\d{7,8})$/", $inp, $m)) {
return "+7" . $m[3] . $m[4];
}
return null;
}
// END
}
?>