<?php
error_reporting(E_ERROR | E_PARSE);
if (!class_exists('crm_hardlock')) require_once("common_cadline_libraries/crm_hardlock.class.php");
require_once('config.php');
require_once('libraries/phpmailer/PHPMailerAutoload.php');
class Version
{
    var $hibajelentes = array('2013' => 1, '2014' => 1, '2015' => 1);
    var $aktivalasihibak = array(
        'error: nincs ilyen password',  // ok
        'error: nem aktiv a program', // ok
        'error: nincs vasarlasi idopont', // ok
        'error: hianyzo kod', // ok
        'error: masik gep van regisztralva', // ok
        'error: nem aktiv regisztracio',
        'error: nincs kifizetve',
        'error: tul sok telepites'
    );
    /*
nincs benne :
error: win10 creator

*/

    // constructor
    function __construct()
    {
    }

    public static function get_latest($project, $pkgid, $sorozatszam, $teszt = '0')
    {
        crm_database::getInstance()->query("SELECT * FROM `" . JMLADATBAZIS . "`.`version` WHERE (`usertype` LIKE '%;" . $sorozatszam . ";%' OR `usertype` LIKE '%;" . substr($sorozatszam, 0, 2) . ";%' OR `usertype` LIKE '%all%' ) AND projectid = '" . $project . "' AND teszt = '" . $teszt . "' AND `deleted` = '0' AND `aktiv` = '1' ORDER BY pkgid DESC");
        $res    = crm_database::getInstance()->fetchAssoc();
        $re     = (object)$res[0];
        $ret    = (isset($re->fajl) ? $re : false);

        return ($ret);
    }


    public static function _plusznap($password)
    {
        $ret = (substr($password, 0, 2) == "99" ? 0 : 60 * 60 * 24 * 30);
        return ($ret);
    }


    // excel elofizetok modositasa, tobb lanos programokhoz + visszamenoleg 2013-ig
    public static function _modosit($kulcs, $utfizu, $tipus, $info)
    {
        print " modosit ";

        if (!$kulcs)
            return false;

        if (!$utfizu || !$tipus) {
            crm_hardlock::_Hibajelento("elofizkarbxml", $kulcs, "valamelyik adat hianyzik:\nfizetes: {$utfizu},\nkapcsolat: {$tipus}");
            return false;
        }

        // kifizetve datum novelese
        $fizetvetime = strtotime($utfizu);
        $utfizu = date('Y-m-d', $fizetvetime + self::_plusznap($program->prPass));

        // legalabb 13-as verzioja programok, amelyeknek a kulcsa aktiv
        crm_database::getInstance()->query("SELECT prID, prPass, prSellDate, prHlNum, prVerID, prStat, prActCode, twtw, prFizetve
            FROM `" . CRMADATBAZIS . "`.`h_programs`
            WHERE prVerID >=13 AND prHlNum IS NOT NULL AND prHlNum = (select hlNum FROM `" . CRMADATBAZIS . "`.`hardlock` WHERE `hlNum`='{$kulcs}' AND `hlStat`=1)");
        $programok = crm_database::getInstance()->fetchAssoc();

        foreach ($programok as $prog) {
            $program = (object)$prog;

            $eladas = $program->prSellDate;

            // van-e eladasi datum
            if ($eladas == '' || $eladas == '0000-00-00') {
                crm_hardlock::_Hibajelento("elofizkarbxml", $kulcs, "hianyzik az eladas datuma: {$kulcs}");
                continue;
            }

            // ha vegleges kodja van akkor ne irja felul
            $harmas = substr($program->prActCode, 10, 3);
            if ($harmas == "999" || $harmas == "NFF" || $program->prFizetve == '2050-01-01') {
                print "mar van vegleges kodja<br>";
                continue;
            }

            // fizetesi datum beirasa, es az aktivalo kod torlese (inditaskor a CRM tobbi resze megoldja a kodgeneralast)
            crm_database::getInstance()->update(CRMADATBAZIS . ".`h_programs`", array("prFizetve" => $utfizu, "prActCode" => null), array("prID" => $program->prID));

            /*$szoftveres = Codegen::IsSoftwareKey($program->prPass);

            if($szoftveres) {
                if(Codegen::IsValidTimeCode($program->prActCode))
                    $isid = crm_hardlock::GetIsidFromTimeCode($program->prActCode);
                else
                    continue;

                crm_database::getInstance()->query("SELECT * FROM `".CRMADATBAZIS."`.`p_serial_isid` WHERE serial='".$program->prPass."' AND isid ='".$isid."' AND aktiv = 1 AND isid IS NOT NULL ORDER BY datum DESC");
                $res=crm_database::getInstance()->fetchAssoc();
                if(empty($res))
                    continue;

                $telepites2 = (object)$res[0];
                $telepites = $telepites2->datum;
            } else {
                $isid = crm_hardlock::GetIsidFromPasswordForHardwareKeys($program->prPass);
                $telepites = $program->prSellDate;
            }

            print " , fizetes: ".$utfizu;

            // regisztralva legyen
            if(!$telepites) {
                // ha hardverkulcsos akkor regisztr�lom a vasarlasi idoponttal
                if ($szoftveres == false) {
                    $isid = crm_hardlock::GetIsidFromPasswordForHardwareKeys($program->prPass);
                    $telepites = $program->prSellDate;
                } else {
                    print "nincs telepitve!";
                    crm_hardlock::_Hibajelento("elofizkarbxml",$kulcs,"szoftveres, nincs telepitve! (nincs isid)");
                    continue;
		        }
            }

            //$eladas = substr($eladas,0,11);
            $telepites = substr($telepites,0,11);
            $maxdatetelepites = (max($eladas,$telepites));

            // kodgeneralas, ha a fizetve idopont kesobbi mint a jelenlegi datum
            if (strtotime($utfizu) > time()) {
                $napok = Codegen::GetDayInterval($maxdatetelepites, $utfizu);
                $aktkod = Codegen::GenerateTimeCode($program->prPass, $isid, $napok);

                // felvenni az adatbazisba
                $query=($szoftveres == false ?
                    "UPDATE `".CRMADATBAZIS."`.`h_programs` SET prActCode='{$aktkod}' WHERE prPass='".$program->prPass."'" :
                    "UPDATE `".CRMADATBAZIS."`.`h_programs` SET prActCode='{$aktkod}' WHERE prPass='".$program->prPass."' AND SUBSTRING(prActCode,6,4)='{$isid}'");
                crm_database::getInstance()->query($query);

                crm_hardlock::_Hibajelento("elofizkarbxml",$kulcs,"felvettem: {$query}");
                // print "<br> &nbsp;feltolt: ".$query;
            } else {
                crm_hardlock::_Hibajelento("elofizkarbxml",$kulcs,"nem kapott kodot, nincs befizetve");
                print "<br>reg volt rendzve ";
            }*/
        }

        return $utfizu;
    }

    public static function _getfizhonap($honap, $kapcs)
    {
        $honap = self::_ekezet($honap);

        if ($kapcs == "elofizetes" || $kapcs == "tanfolyam") {
            $tomb['jan'] = '01';
            $tomb['feb'] = '02';
            $tomb['mar'] = '03';
            $tomb['apr'] = '04';
            $tomb['maj'] = '05';
            $tomb['jun'] = '06';
            $tomb['jul'] = '07';
            $tomb['aug'] = '08';
            $tomb['sze'] = '09';
            $tomb['okt'] = 10;
            $tomb['nov'] = 11;
            $tomb['dec'] = 12;
            $ertek = substr($honap, 5, 3);
        } elseif ($kapcs == "karbantartas") {
            $tomb['1.n.'] = '03';
            $tomb['2.n.'] = '06';
            $tomb['3.n.'] = '09';
            $tomb['4.n.'] = 12;
            $ertek = substr($honap, 5, 4);
        }

        //$ho = $this->_ekezet( iconv("ISO-8859-1", "UTF-8", $ertek) );
        $ho = self::_ekezet($ertek);
        $datum = substr($honap, 0, 4) . "-" . $tomb[$ho] . "-28";
        return substr($honap, 0, 4) . "-" . $tomb[$ho] . "-" . date('t', strtotime($datum));    // h�nap utols� napj�t adja vissza
    }


    public static function _ekezet($input)
    {
        $mit = array("/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/", "/�/");
        $mire = array("a", "A", "e", "E", "i", "I", "o", "O", "o", "O", "o", "O", "u", "U", "u", "U", "u", "U");
        $output = preg_replace($mit, $mire, $input);
        return $output;
    }

    public static function warehousedownloadlink($link, $archlineversion)
    {
        $pDownloadSignString1 = "https://3dwarehouse.sketchup.com/3dw/getpubliccontent";
        $pDownloadSignString2 = "https://3dwarehouse.sketchup.com/3dw/getbinary";
        $pDownloadSignString3 = "https://3dwarehouse.sketchup.com/warehouse/getpubliccontent";
        $pDownloadSignString4 = "https://3dwarehouse.sketchup.com/warehouse/getbinary";
        $link = base64_decode($link);

        if (strstr($link, $pDownloadSignString1)) {
            print "true";
        } elseif (strstr($link, $pDownloadSignString2)) {
            print "true";
        } elseif (strstr($link, $pDownloadSignString3)) {
            print "true";
        } elseif (strstr($link, $pDownloadSignString4)) {
            print "true";
        } else {
            //ba 2018 build619 elotti valtozatok:
            if ($archlineversion === NULL) {
                if (strstr($link, "https://3dwarehouse.sketchup.com/warehouse/") && strstr($link, "s18?download=true"))
                    print "true";
                else
                    print "false";
            } else {
                if (strstr($link, "https://3dwarehouse.sketchup.com/warehouse/") && strstr($link, "download=true"))
                    print "true";
                else
                    print "false";
            }
        }
    }

    public static function warehouseparsesource()
    {
        $archlineversion = filter_input(INPUT_POST, 'archlineversion', FILTER_SANITIZE_NUMBER_INT);
        $src = $_POST["source"];
        $src = str_replace(" ", "+", $src);
        $decoded = "";
        for ($i = 0; $i < ceil(strlen($src) / 256); $i++)
            $decoded = $decoded . base64_decode(substr($src, $i * 256, 256));

        $link = $_POST['link'];
        $link = base64_decode($link);

        $sendemail = false;
        $id = "";
        if ($archlineversion >= 36) {
            $toFind = 'https://3dwarehouse.sketchup.com/warehouse/v1.0/entities/';
            $posStart = strpos($link, $toFind);
            if (($posStart !== false) && ($posStart >= 0)) {
                $posStart += strlen($toFind);
                $posEnd = strpos($link, '/binaries/', $posStart);
                if (($posEnd !== false) && ($posEnd >= 0)) {
                    $id = substr($link, $posStart, $posEnd - $posStart);
                } else
                    $sendemail = true;
            } else
                $sendemail = true;
        }

        $modelViewerIdentData = 'href="https://3dwarehouse.sketchup.com/model';
        $posModelIdent = strpos($decoded, $modelViewerIdentData);
        $isViewingModel = $posModelIdent > 0;
        $returnString = "<3DWarehouseHtmlData>";
        $timestamp = time();
        $name = "untitled";
        $name .= $timestamp;
        $author = "";
        $toFind = '<title data-vue-meta="true">';
        $posStart = strpos($decoded, $toFind);
        $returnString .= "<Name>";

        if ($isViewingModel && ($posStart !== false) && ($posStart >= 0)) {
            $posStart += strlen($toFind);
            $posEnd = strpos($decoded, ' |', $posStart);
            if (($posEnd !== false) && ($posEnd >= 0)) {
                $name = substr($decoded, $posStart, $posEnd - $posStart);
                $name = iconv("UTF-8", "ISO-8859-2", $name);
            }
        } else {
            if ($id != "") {
                $toFind = '<a href="/model/';
                $toFind .= $id;
                $toFind .= '/';
                $posStart = strpos($decoded, $toFind);
                if ($posStart === false) {
                    $toFind = '<title>';
                    $posStart = strpos($decoded, $toFind);
                    if ($posStart !== false) {
                        $posStart += strlen($toFind);
                        $posEnd = strpos($decoded, ' | 3D Warehouse</title>', $posStart);
                        if (($posEnd !== false) && ($posEnd >= 0)) {
                            $name = substr($decoded, $posStart, $posEnd - $posStart);
                            $name = iconv("UTF-8", "ISO-8859-2", $name);
                        }
                    }
                } else {
                    $posStart += strlen($toFind);
                    $posEnd = strpos($decoded, '">', $posStart);
                    if (($posEnd !== false) && ($posEnd >= 0)) {
                        $name = substr($decoded, $posStart, $posEnd - $posStart);
                        $name = iconv("UTF-8", "ISO-8859-2", $name);
                    }
                }
            }
        }
        $returnString .= base64_encode($name);
        $returnString .= "</Name>";

        $toFind = '<meta data-vue-meta="true" name="author" content="';
        $posStart = strpos($decoded, $toFind);
        if ($isViewingModel && ($posStart !== false) && ($posStart >= 0)) {
            $posStart += strlen($toFind);
            $posEnd = strpos($decoded, '">', $posStart);
            if (($posEnd !== false) && ($posEnd >= 0)) {
                $author = substr($decoded, $posStart, $posEnd - $posStart);
                $returnString .= "<Author>";
                $returnString .= base64_encode($author);
                $returnString .= "</Author>";
            }
        }
        if ($archlineversion >= 36) {
            $returnString .= "<ID>";
            $returnString .= $id;
            $returnString .= "</ID>";

            crm_database::getInstance()->insert(JMLADATBAZIS . ".warehouse_stat", array(
                'archlineversion' => $archlineversion,
                'time' => date('Y-m-d H:i:s', time()),
                'objectname' => $name,
                'objectid' => $id,
            ));

            if ($sendemail) {
                $message = "Hiba tortent egy 3DWarehouse letoltesnel a link feldolgozasaban.\n";
                $message .= "Ez volt a link, amibol nem sikerult kiszedni az id-t:\n" . $link;
                $mail = new PHPMailer;
                $mail->isSMTP();
                $mail->SMTPAuth = true;
                $mail->CharSet = 'UTF-8';
                $mail->Host = $mailconfig['Host'];
                $mail->Username = $mailconfig['Username'];
                $mail->Password = $mailconfig['Password'];
                $mail->SMTPSecure = $mailconfig['SMTPSecure'];
                $mail->Port = $mailconfig['Port'];
                $mail->isHTML(TRUE);
                $mail->setFrom(DEFAULT_EMAIL);
                $mail->addAddress('battila@cadline.hu');
                $mail->Subject = 'ARCHLine.XP 3DWarehouse link problema';
                $mail->msgHTML($message);
                $mail->AltBody = strip_tags($message);
                $mail->send();
                unset($mail);
            }
        }

        $returnString .= "</3DWarehouseHtmlData>";
        print $returnString;
    }
} // end of class
