<?
class MD_AUTH_HANDLER
{
var $error=null;
var $arData=array();
var $arFiles=array();
var $auth=false;
var $authHash=null;
var $APP;
var $DB;
var $USER;
var $action;
var $employee;
var $admin=false;
//construct
function __construct()
{
$this->APP=$GLOBALS["APPLICATION"];
$this->DB=$GLOBALS["DB"];
$this->USER=$GLOBALS["USER"];
$this->error=null;
Header('Content-Type: application/json; charset=utf-8');
$this->arData = $_SERVER['REQUEST_METHOD'] == 'POST' ? $_POST : $_GET;
$this->arFiles=$_FILES["files"];
$this->arData = $this->APP->ConvertCharsetArray($this->arData, 'UTF-8', LANG_CHARSET);
$this->productKey=$this->arData["access_key"];
$this->action=$this->arData["action"];
$this->AuthHttp();
$this->CheckAuth(false);
}
//auth http
function AuthHttp()
{
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER["PHP_AUTH_PW"]))
{
$rUser = new CUser();
if (($success = $rUser->Login($_SERVER['PHP_AUTH_USER'], $_SERVER["PHP_AUTH_PW"], 'N', 'Y')))
{
if($success==1){
$this->auth=true;
$this->CreateHash();
}
}
}
}
//check
function CheckAuth($show_success=false)
{
if($this->arData["login"] && $this->arData["password"])
{
$this->Authorize();
}elseif($this->arData["access_token"])
{
$this->LoginByHash();
}elseif(!$this->auth)
{
$this->ShowError(" LOGIN OR PASSWORD IS INCORRECT", 103);
}
if($this->auth && $show_success)
{
$this->ShowSuccess("AUTH IS SUCCESS", array());
}
}
//authorize
function Authorize()
{
$rUser = new CUser();
if (($error = $rUser->Login($this->arData['login'], $this->arData['password'], 'N', 'Y')) !== true)
{
$this->ShowError("LOGIN OR PASSWORD IS INCORRECT", 103);
}else{
$this->auth=true;
$this->CreateHash();
}
}
//Login by HASH
function LoginByHash(){
if (strlen($this->arData['access_token']) > 0)
{
$_REQUEST['bx_hit_hash'] = $this->arData['access_token'];
if($this->USER->LoginHitByHash()){
$this->auth=true;
}else
{
$this->auth=false;
$this->ShowError("INCORRECT HASH", 104);
}
}else{
$this->auth=false;
$this->ShowError("INCORRECT HASH", 104);
}
}
//Create auth hash
function CreateHash()
{
if(!$this->authHash)
$this->authHash=$this->USER->AddHitAuthHash($this->APP->GetCurPage());
}
//error send
function ShowError($str, $code)
{
$response=array(
"status"=>"error",
"statusCode"=>$code,
"message"=>$GLOBALS["APPLICATION"]->ConvertCharset($str, LANG_CHARSET, "UTF-8"),
"result"=>""
);
$GLOBALS["APPLICATION"]->RestartBuffer();
echo CUtil::PhpToJSObject($response);
exit();
}
//send success
function ShowSuccess($str, $result=array())
{
$response=array(
"status"=>"success",
"statusCode"=>"200",
"message"=>$GLOBALS["APPLICATION"]->ConvertCharset($str, LANG_CHARSET, "UTF-8"),
"result"=>$GLOBALS["APPLICATION"]->ConvertCharsetArray($result, LANG_CHARSET, "UTF-8"),
);
if($this->authHash)
{
$response["access_token"]=$this->authHash;
}
$GLOBALS["APPLICATION"]->RestartBuffer();
echo json_encode($response);
exit();
}
//upload photo
function GetScreen()
{
$this->isEmployee();
if(strtolower($this->arData["zip"])=="yes")
{
///work with zip file
$zip=new mData();
$zip->SetZipFile($this->arFiles);
$zip->Unzip();
$zip->SetEmploye($this->employee);
$zip->HandleIt();
}
else
{
if(!$this->arFiles) $this->ShowError("NO FILES TO UPLOAD", 301);
if($this->arFiles["error"]>0) $this->ShowError("ERROR IN UPLOADING FILE. ERROR NUMBER:".$this->arFiles["error"], 302);
CheckDirPath($_SERVER["DOCUMENT_ROOT"].self::IMG_PATH.$this->employee."/", true);
$path=self::IMG_PATH.$this->employee."/".date("dmyHis")."_".basename($this->arFiles["name"]);
$abs_path=$_SERVER["DOCUMENT_ROOT"].$path;
if(move_uploaded_file($this->arFiles["tmp_name"], $abs_path))
{
chmod($abs_path,0777);
$this->SaveScreenShot($path, true);
}else
{
$this->ShowError("ERROR IN SAVING FILE", 303);
}
}
}
///save images
function SaveScreenShot($file, $show_message=false)
{
CModule::IncludeModule("highloadblock");
// hlblock info
$hlblock_id = self::HIBLOCK;
$hlblock = Bitrix\Highloadblock\HighloadBlockTable::getById($hlblock_id)->fetch();
$entity = Bitrix\Highloadblock\HighloadBlockTable::compileEntity($hlblock);
if(!mData::isImage($file)) $this->ShowError("This is not photo", 304);
$arE=array(
"UF_DATE"=>date("d.m.Y H:i:s"),
"UF_DATE_"=>date("d.m.Y H:i:s"),
"UF_LOGIN"=>$this->employee,
"UF_FILE"=>$file,
);
$entity_data_class = $entity->getDataClass();
$id=$entity_data_class::add($arE);
$this->ShowSuccess("PHOTO SUCCESSFULLY UPLOADED");
}
}
//work with zip data
//work with data
class mData
{
public $zipfile;
public $abs;
public $arData=array(), $screens=array(), $csv=null,
$filename, $path, $employe;
const HIBLOCK=1;
const IMG_PATH="/upload/screens/";
const ARCH_PATH="/upload/screens/arch/";
function SetEmploye($employe)
{
$this->employe=$employe;
}
function SetZipFile($file)
{
if($file["error"]!=0) $this->ShowResult("error", "ZIP FILE IS NOT FOUND!", false, 310);
CheckDirPath($_SERVER["DOCUMENT_ROOT"].self::IMG_PATH."zip/", true);
$path=self::IMG_PATH."zip/".date("dmyHis")."_".basename($file["name"]);
$abs_path=$_SERVER["DOCUMENT_ROOT"].$path;
$this->filename=str_replace(".tar.gz", "", $file["name"]);
if(move_uploaded_file($file["tmp_name"], $abs_path))
{
chmod($abs_path,0777);
$this->zipfile=$path;
$this->abs=$abs_path;
}else
{
$this->ShowResult("error", "ERROR IN SAVING FILE", false, 303);
}
}
function ShowResult($status, $str="", $result=array(), $code=200)
{
$response=array();
if($status) $response["status"]=$status;
if($str) $response["message"]=$GLOBALS["APPLICATION"]->ConvertCharset($str, LANG_CHARSET, "UTF-8");
if($result) $response["result"]=$GLOBALS["APPLICATION"]->ConvertCharsetArray($result, LANG_CHARSET, "UTF-8");
$response["statusCode"]=$code;
$GLOBALS["APPLICATION"]->RestartBuffer();
echo json_encode($response);
exit();
}
function UnZip()
{
require_once($_SERVER["DOCUMENT_ROOT"].'/bitrix/modules/main/classes/general/tar_gz.php');
$tar=new CArchiver($this->abs);
$folder=$_SERVER["DOCUMENT_ROOT"].self::ARCH_PATH;
$tres=$tar->extractFiles($folder);
$error=&$tar->GetErrors();
if($error) $this->ShowResult("error", "Error while extracting...", false, 120);
unlink($this->abs);
$this->path=$folder.$this->filename."/";
if (is_dir($this->path))
{
if ($dir = opendir($this->path))
{
while (false !== $item = readdir($dir))
{
if ($item == '..' || $item == '.')
continue;
if(strpos($item, ".csv")!==FALSE)
{
$this->csv=$this->path.$item;
}elseif(mData::isImage($item))
{
$this->screens[]=$this->path.$item;
}
}
closedir($dir);
}
}
if(!$this->csv) $this->ShowResult("error", "CSV FILE IS NOT FOUND!", false, 311);
if(!$this->screens) $this->ShowResult("error", "NO FILES IN ARCHIVE", false, 310);
///parse CSV
$this->arData = $this->csv_to_array($this->csv);
unlink($this->csv);
}
function HandleIt()
{
CModule::IncludeModule("highloadblock");
// hlblock info
$hlblock_id = self::HIBLOCK;
$hlblock = Bitrix\Highloadblock\HighloadBlockTable::getById($hlblock_id)->fetch();
$entity = Bitrix\Highloadblock\HighloadBlockTable::compileEntity($hlblock);
if(is_array($this->arData))
{
foreach ($this->arData as $key=>$file)
{
CheckDirPath($_SERVER["DOCUMENT_ROOT"].self::IMG_PATH.$this->employe."/", true);
$path=self::IMG_PATH.$this->employe."/".date("dmyHis")."_".$file["FILE_NAME"];
$abs_path=$_SERVER["DOCUMENT_ROOT"].$path;
if(rename($this->path.$file["FILE_NAME"], $abs_path))
{
if(!mData::isImage($path)) continue;
unlink($this->path.$file["FILE_NAME"]);
chmod($abs_path,0777);
$arE=array(
"UF_DATE"=>$file["FILE_DATE"],
"UF_DATE_"=>$file["FILE_DATE"],
"UF_LOGIN"=>$this->employe,
"UF_FILE"=>$path,
);
$entity_data_class = $entity->getDataClass();
$id=$entity_data_class::add($arE);
}
}
rmdir($this->path);
$this->ShowResult("success", "FILES ARE UPLOADED");
}else
{
$this->ShowResult("error", "No FILES", false, 312);
}
}
function csv_to_array($filename='', $delimiter=';')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
//delete out of date data
function DelData()
{
$today=date("d.m.Y H:i:s");
$interval=COption::GetOptionString("micros.monitoring", "deleteFrequency");
if($interval)
{
$maxDate=date("d.m.Y", strtotime("- ".$interval." day ")). " 00:00:00";
CModule::IncludeModule("highloadblock");
// hlblock info
$hlblock_id = self::HIBLOCK;
$hlblock = Bitrix\Highloadblock\HighloadBlockTable::getById($hlblock_id)->fetch();
$entity = Bitrix\Highloadblock\HighloadBlockTable::compileEntity($hlblock);
$main_query = new Bitrix\Main\Entity\Query($entity);
$main_query->setSelect(array('ID', "UF_FILE", "UF_DATE_", "UF_DATE"));
$arFilt=array(
"<UF_DATE_"=>$maxDate
);
$main_query->setFilter($arFilt);
$main_query->setOrder(array('UF_DATE_' =>'DESC'));
$result = $main_query->exec();
$result = new CDBResult($result);
$del_cl=$entity->getDataClass();
while($row = $result->Fetch()):
$res=$del_cl::delete($row["ID"]);
unlink($_SERVER["DOCUMENT_ROOT"].$row["UF_FILE"]);
///delete resized cache
$pp=$_SERVER["DOCUMENT_ROOT"]."/upload/screens/resize/".$row["ID"]."/";
if (is_dir($pp))
{
if ($dir = opendir($pp))
{
while (false !== $item = readdir($dir))
{
if ($item == '..' || $item == '.')
continue;
unlink($pp.$item);
}
closedir($dir);
rmdir($pp);
}
}
if(!$res->isSuccess()){ //произошла ошибка
echo $res->getErrorMessages(); //выведем ошибку
} else {
echo 'ok';
}
endwhile;
}
return "mData::DelData();";
}
//migrate props
function MigrateDate()
{
CModule::IncludeModule("highloadblock");
// hlblock info
$hlblock_id = self::HIBLOCK;
$hlblock = Bitrix\Highloadblock\HighloadBlockTable::getById($hlblock_id)->fetch();
$entity = Bitrix\Highloadblock\HighloadBlockTable::compileEntity($hlblock);
$main_query = new Bitrix\Main\Entity\Query($entity);
$main_query->setSelect(array('ID', "UF_DATE"));
$main_query->setOrder(array('ID' =>'ASC'));
$result = $main_query->exec();
$result = new CDBResult($result);
$LANG_entity_data_class = $entity->getDataClass();
while($row = $result->Fetch()):
$res = $LANG_entity_data_class::update($row['ID'], array("UF_DATE_"=>$row["UF_DATE"]));
if(!$res->isSuccess()){ //произошла ошибка
echo $res->getErrorMessages(); //выведем ошибку
}
endwhile;
}
function Resize($path, $id, $width, $height, $type="BX_RESIZE_IMAGE_EXACT")
{
$a=explode(".", $path);
$ext=$a[count($a)-1];
CheckDirPath($_SERVER["DOCUMENT_ROOT"]."/upload/screens/resize/".$id."/", true);
$new_path="/upload/screens/resize/".$id."/resize_".$width."_".$height.".".$ext;
if(!file_exists($_SERVER["DOCUMENT_ROOT"].$new_path)){
$wmMini = CFile::ResizeImageFile(
$sourceFile = $_SERVER["DOCUMENT_ROOT"].$path,
$destinationFile =$_SERVER["DOCUMENT_ROOT"].$new_path,
$arSize = array('width'=>$width, 'height'=>$height),
$resizeType = BX_RESIZE_IMAGE_EXACT,
$arWaterMark = array(),
$jpgQuality=false,
$arFilters =false
);
}
return $new_path;
}
function isImage($path)
{
$ext=explode(".", $path);
$ext=$ext[count($ext)-1];
$imageArray=array("jpeg", "png", "gif", "bmp", "jpg");
//echo "<pre>";print_r(strtolower($ext));echo"</pre>";
if(in_array(strtolower($ext) ,$imageArray))
{
//echo "<pre>";print_r($imageArray);echo"</pre>";
return true;
}
return false;
}
}
//use
$rest=new MD_AUTH_HANDLER();
if($rest->auth)
{
$rest->GetScreen();
}
?>