<?php

function TP_getVal($src, $type) {
	$temp=explode($type."=",$src);
	if (isset($temp[1])) {
		$temp=explode("\"",$temp[1]);
		if (isset($temp[1])) {
			return $temp[1];
		} else return "";
	} else return "";
}
function TP_getName($src) {
	$temp=explode("</",$src);
	if (isset($temp[1])) {
		$temp=explode(">",$temp[1]);
		if (isset($temp[0])) {
			return $temp[0];
		} else return "";
	} else return "";
}
function TP_isDivider($key) {
	$previousAipType="";
	$nextAipType="";
	$curr=$GLOBALS["megaprom"][$key];
	$currContent=TP_getVal($curr,"content");
	$currAipType=TP_getVal($curr,"aip-type");
	if (isset($GLOBALS["megaprom"][$key-1])) {
		$prev=$GLOBALS["megaprom"][$key-1];
		$previousAipType=TP_getVal($prev,"aip-type");
	}
	if (isset($GLOBALS["megaprom"][$key+1])) {
		$next=$GLOBALS["megaprom"][$key+1];
		$nextAipType=TP_getVal($next,"aip-type");
	}
	$isDivider="";
	if ($currAipType!="text_hesla") {
		$isDivider="no";
	} else {
		if ($currAipType=='text_hesla') {
			if (strlen($currContent)!=1) {
				$isDivider="no";
			} else {
				if ($previousAipType=='text_hesla') {
					$isDivider="no";
				} else {
					if ($nextAipType=='text_hesla') {
						$isDivider="no";
					} else {
						if ($currContent==';' || $currContent=='-' || $currContent=='.' || $currContent==',' || $currContent==':' || $currContent=='�') {
							$isDivider="yes";
						}
					}
				}
			}
		}
	}
	if ($isDivider=="yes") {
		return "yes";
	} else {
		return "no";
	}
}
function TP_addAttrs($node,$props) {
	$attrs="";
	foreach ($props as $propName => $val) {
		$attrs.=" php-".$propName."=\"".$val."\"";
	}
	return "<span".$attrs." ".$node;
}
function TP_preprocessData($data) {
	$blocks=explode("<block>",$data);
	$data=$blocks[0];
	foreach ($blocks as $blockKey => $blockText) {
		if ($blockKey>0) {
			$data.="<block>";
			$GLOBALS["megaprom"]=explode("<span ",$blockText);
			$count=count($GLOBALS["megaprom"])-1;

			foreach ($GLOBALS["megaprom"] as $key => $node) {
				$props["nextAipType"]="";
				$props["nextAipSubtype"]="";
				$props["nextName"]="";
				$props["nextIsDivider"]="";
				$props["previousAipType"]="";
				$props["previousAipSubtype"]="";
				$props["previousName"]="";
				$props["previousIsDivider"]="";
				if ($key!=0) {
					if ($key==1) {

						$next=$GLOBALS["megaprom"][$key+1];
						$props["nextAipType"]=TP_getVal($next,"aip-type");
						$props["nextAipSubtype"]=TP_getVal($next,"aip-subtype");
						$props["nextName"]=TP_getName($next);
						$props["nextIsDivider"]=TP_isDivider($key+1);
						$data.=TP_addAttrs($node,$props);
					} else {

						$prev=$GLOBALS["megaprom"][$key-1];
						$props["previousAipType"]=TP_getVal($prev,"aip-type");
						$props["previousAipSubtype"]=TP_getVal($prev,"aip-subtype");
						$props["previousName"]=TP_getName($prev);
						$props["previousIsDivider"]=TP_isDivider($key-1);
						if ($key==$count) {

						} else {
							$next=$GLOBALS["megaprom"][$key+1];
							$props["nextAipType"]=TP_getVal($next,"aip-type");
							$props["nextAipSubtype"]=TP_getVal($next,"aip-subtype");
							$props["nextName"]=TP_getName($next);
							$props["nextIsDivider"]=TP_isDivider($key+1);
						}
						$data.=TP_addAttrs($node,$props);
					}
				} else {

					$data.=$node;
				}
			}
		}
	}
	return $data;
}
function TP_addBlocks($data) {
			$megaprom=explode("<span",$data);
			$data="";
			foreach ($megaprom as $key => $node) {
				if ($key==0) {
					$data.=$node;
				} else {
					$nearestImportantPreType="";
					if ($key>1) {
						$i=$key-1;
						while ($nearestImportantPreType=="" && $i>0) {
						    $testElm=$megaprom[$i];
						    $name=TP_getName($testElm);
						    if ($name != "TAB" && $name != "NEWLINE" && $name != "BIGSKIP" && $name != "start" && $name != "end") {
						    	$nearestImportantPreType=TP_getVal($megaprom[$i],"aip-type");
						    }
						    $i--;
						}
					}
					$data.="<span php-NIPT=\"".$nearestImportantPreType."\"".$node;
				}
	}


	$data=str_replace("<start","<block",$data);
	$data=str_replace("</start>","",$data);
	$data=str_replace("<end","</block><end",$data);
	return $data;
}

$data = "";
switch($_POST['req']){
    case "html":
        $xsl = new DOMDocument;
        $xsl->load($_POST['file1']);
        $xsl2 = new DOMDocument;
        $xsl2->load($_POST['file2']);
        $xsl3 = new DOMDocument;
        $xsl3->load($_POST['file3']);
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl);
        $proc2 = new XSLTProcessor;
        $proc2->importStyleSheet($xsl2);
        $proc3 = new XSLTProcessor;
        $proc3->importStyleSheet($xsl3);
    		$prvni_html = simplexml_load_string(TP_addBlocks($_POST['html']));
				$druhy_xml  = $proc2->transformToXML(simplexml_load_string(TP_preprocessData($proc->transformToXML($prvni_html))));
       	$data = $proc3->transformToXML(simplexml_load_string($druhy_xml));

        break;
    case "show_source":
        $xsl = new DOMDocument;
        $xsl->load($_POST['file1']);
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl);
        $data = $proc->transformToXML(simplexml_load_string($_POST['xml']));
        break;
    case "part_html":
        $xsl = new DOMDocument;
        $xsl->load($_POST['file1']);
        $xsl2 = new DOMDocument;
        $xsl2->load($_POST['file2']);
        $xsl3 = new DOMDocument;
        $xsl3->load($_POST['file3']);
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl);
        $proc2 = new XSLTProcessor;
        $proc2->importStyleSheet($xsl2);
        $doc = new DOMDocument();
        $doc2 = new DOMDocument();
        $doc->loadXML($_POST['html']);
       $data['data'] = $proc->transformToXML($doc);
        break;
    case "files":
        $xml = new DOMDocument;
        $xml->load($_POST['file1']);
        $xsl = new DOMDocument;
        $xsl->load($_POST['file2']);
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl);
        $data = $proc->transformToXML($xml);
        break;
    case "load_xml":
        $data['data'] = scandir('xml/');
        break;
    case "validate_xml_html":
        libxml_use_internal_errors(true);
        $xml = new DOMDocument();
        $xml->loadXML($_POST['html']);
        if (!$xml->schemaValidate($_POST['file1'])) {
            $data['data'] = libxml_display_errors();
        }
        break;
    case "validate_xml_file":
        libxml_use_internal_errors(true);
        $xml = new DOMDocument();
        $xml->loadXML($_POST['file1']);
        if (!$xml->schemaValidate($_POST['file2'])) {
            $data['data'] = libxml_display_errors();
        }
        break;
    case "part1":
        $xsl = new DOMDocument;
        $xsl->load($_POST['file1']);
        $xsl2 = new DOMDocument;
        $xsl2->load($_POST['file2']);
        $xsl3 = new DOMDocument;
        $xsl3->load($_POST['file3']);
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl);
        $proc2 = new XSLTProcessor;
        $proc2->importStyleSheet($xsl2);
        $proc3 = new XSLTProcessor;
        $proc3->importStyleSheet($xsl3);
        $data = $proc->transformToXML(simplexml_load_string(TP_addBlocks($_POST['html'])));
        break;
    case "part2":
        $xsl = new DOMDocument;
        $xsl->load($_POST['file1']);
        $xsl2 = new DOMDocument;
        $xsl2->load($_POST['file2']);
        $xsl3 = new DOMDocument;
        $xsl3->load($_POST['file3']);
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl);
        $proc2 = new XSLTProcessor;
        $proc2->importStyleSheet($xsl2);
        $proc3 = new XSLTProcessor;
        $proc3->importStyleSheet($xsl3);
        $data = $proc2->transformToXML(simplexml_load_string(TP_preprocessData($proc->transformToXML(simplexml_load_string(TP_addBlocks($_POST['html']))))));
        break;
    case "part3":
        $xsl = new DOMDocument;
        $xsl->load($_POST['file1']);
        $xsl2 = new DOMDocument;
        $xsl2->load($_POST['file2']);
        $xsl3 = new DOMDocument;
        $xsl3->load($_POST['file3']);
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl);
        $proc2 = new XSLTProcessor;
        $proc2->importStyleSheet($xsl2);
        $proc3 = new XSLTProcessor;
        $proc3->importStyleSheet($xsl3);
        $data = $proc3->transformToXML(simplexml_load_string($proc2->transformToXML(simplexml_load_string(TP_preprocessData($proc->transformToXML(simplexml_load_string(TP_addBlocks($_POST['html']))))))));
        break;



    case "send_backup_report":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $uid = $_POST['uid'];
        $email = $_POST['email'];
        $result = $conn->query("SELECT `xml`,`user_json` FROM gorazd_editor.editor_cache WHERE `id`='$id'");
        $d = $result->fetch_assoc();
        $date = date("YmdHis");
        $path = 'send_report_backups/'.$uid.'_backup_'.$id.'_'.$date.'.txt';
        if($d['xml'] != "null" && $d['xml'] != null){
            file_put_contents($path, $d['xml']);
            $user = json_decode($d['user_json']);
            $text = "Backup report from ".PHP_EOL."uid: ".$user->{'uid'}.PHP_EOL."email: ".$user->{'email'}.PHP_EOL."nick: ".$user->{'name'}.PHP_EOL;
            foreach(json_decode($email) as $email_){
                mail_attachment($email_,'Report from "Gorazd editor"',$text,'gorazdeditor@aipberoun.cz',$path);
            }
            $data['resp'] = true;
        }else{
            $data['resp'] = false;
        }
        break;

    case "remove_backup":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $uid = $_POST['uid'];
        $result = $conn->query("SELECT `user_json` FROM gorazd_editor.editor_cache WHERE `id`='$id'");
        $res = $result->fetch_assoc();
        if($res != null){
            if(json_decode($res['user_json'])->{'uid'} == $uid){
               $conn->query("DELETE FROM gorazd_editor.editor_cache WHERE `id`='$id'");
            }else{
                $data = "USER NOT OWNER";
            }
        }else{
           $data = $res;
        }
        break;

    case "set_error":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $result = $conn->query("UPDATE gorazd_editor.editor_cache SET `status`='error' WHERE `id`='$id'");
        break;

    case "set_saving":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $result = $conn->query("UPDATE gorazd_editor.editor_cache SET `status`='saving' WHERE `id`='$id'");
        break;

    case "check_backup":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $result = $conn->query("SELECT `status`,`user_json` FROM gorazd_editor.editor_cache WHERE `id`='$id'");
        $data = json_encode($result->fetch_assoc());
        break;

    case "load_backup":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $result = $conn->query("SELECT * FROM gorazd_editor.editor_cache WHERE `id`='$id'");
        $data = json_encode($result->fetch_assoc());
        break;

    case "save_backup":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $status = $_POST['save'];
        $user = $_POST['user_json'];
        $html= $_POST['html'];
        $img= $_POST['img'];
        if($user != "" && $user != undefined && $img != "" && $img != undefined){
             $conn->query("INSERT INTO `gorazd_editor`.`editor_cache` (`id`, `time`, `status`, `xml`, `user_json`,`img_json`) VALUES ('$id',DEFAULT, '$status', '$html', '$user','$img') ON DUPLICATE KEY UPDATE `time`=DEFAULT,`status`='$status' , `xml`='$html' , `user_json` = '$user', `img_json`='$img' ;");
             $data['resp'] = true;
        }else{
             $data['resp'] = false;
        }

        break;

    case "store_clipboard":
        require 'mysql_config.php';
        $id = $_POST['id'];
        $uid = $_POST['uid'];
        $html= $_POST['html'];
        $conn->query("INSERT INTO `editor_clipboard`(`uid`, `html`, `date`, `from`) VALUES ('$uid','$html',DEFAULT,'$id') ON DUPLICATE KEY UPDATE `date`=DEFAULT,`from`='$id',`html`='$html' ;");
        break;

    case "load_clipboard":
        require 'mysql_config.php';
        $uid = $_POST['uid'];
        $result = $conn->query("SELECT * FROM gorazd_editor.editor_clipboard WHERE `uid`='$uid'");
        $resp = array();
        $resp = $result->fetch_assoc();
        if($resp){
            $current_timestamp = time();
            $resp['time'] = secondsToTime($current_timestamp - strtotime($resp['date']));
            $data = json_encode($resp);
        }
        break;
}

echo json_encode($data);


function secondsToTime($seconds) {
    $dtF = new \DateTime('@0');
    $dtT = new \DateTime("@$seconds");
    $resp = array();
    $resp['day'] = $dtF->diff($dtT)->format('%a');
    $resp['hour'] = $dtF->diff($dtT)->format('%h');
    $resp['minit'] = $dtF->diff($dtT)->format('%i');
    $resp['second'] = $dtF->diff($dtT)->format('%s');
    return $resp;
}


function libxml_display_error($error){
    $return = "<br/>\n";
    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "<b>Warning $error->code</b>: ";
            break;
        case LIBXML_ERR_ERROR:
            $return .= "<b>Error $error->code</b>: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "<b>Fatal Error $error->code</b>: ";
            break;
    }
    $return .= trim($error->message);
    if ($error->file) {
        $return .=    " in <b>$error->file</b>";
    }
    $return .= " on line <b>$error->line</b>\n";
    return $return;
}



function libxml_display_errors() {
    $resp = "";
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        $resp .= libxml_display_error($error);
    }
    libxml_clear_errors();
    return $resp;

}

function mail_attachment($to, $subject, $message, $from, $file) {
  $filename = basename($file);
  $file_size = filesize($file);
  $content = chunk_split(base64_encode(file_get_contents($file)));
  $uid = md5(uniqid(time()));
  $from = str_replace(array("\r", "\n"), '', $from);
  $header = "From: ".$from."\r\n"
      ."MIME-Version: 1.0\r\n"
      ."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"
      ."This is a multi-part message in MIME format.\r\n"
      ."--".$uid."\r\n"
      ."Content-type:text/plain; charset=iso-8859-1\r\n"
      ."Content-Transfer-Encoding: 7bit\r\n\r\n"
      .$message."\r\n\r\n"
      ."--".$uid."\r\n"
      ."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
      ."Content-Transfer-Encoding: base64\r\n"
      ."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
      .$content."\r\n\r\n"
      ."--".$uid."--";
  return mail($to, $subject, "", $header);
}




?>
