<?php

include_once("constants.inc");
include_once("Spreadsheet/Excel/Writer.php");
include_once("PHPExcel/PHPExcel.php"); 
include_once("PHPExcel/PHPExcel/IOFactory.php");


function clean($input, $maxlength) {
  $input = substr($input,0,$maxlength);
  $input = EscapeShellCmd($input);
  return ($input);
}

function logincheck() {
  $a = session_id();
  if ($a == '')
    session_start();

  if ($_SERVER["REMOTE_ADDR"] == SERVER_IPADDRESS && isset($_POST["securitycode"])) {
    if ($_POST["securitycode"] != SECURITY_CODE) {
      header("Location: /login");
    }
  } else {
    $sessionLife = SESSION_EXPIRE + 1;
    if (isset($_SESSION['timeout']))
      $sessionLife = time() - $_SESSION['timeout'];
  
    if ($sessionLife > SESSION_EXPIRE || !isset($_SESSION['user']))
      header("Location: /login");
  }
}

function login($username, $password) {
  $options = ['cost' => HASH_OPTIONS_COST, 'salt' => HASH_OPTIONS_SALT];
  $user = GetUserByLogin($username, password_hash($password, PASSWORD_BCRYPT, $options));
  $user2 = GetUserByLogin($username, md5($password));

  if ((count($user) > 0 && $user["user_id"] > 0) || (count($user2) > 0 && $user2["user_id"] > 0)) {
    if (count($user) > 0) {
      if (strtolower($username) == strtolower($password))
        $user["goodpassword"] = false;
      else
        $user["goodpassword"] = true;
    
      $_SESSION["user"] = $user;
    } else {
      if (strtolower($username) == strtolower($password))
        $user2["goodpassword"] = false;
      else
        $user2["goodpassword"] = true;

      $_SESSION["user"] = $user2;
      UpdateUserPassword($user2["user_id"], password_hash($password, PASSWORD_BCRYPT, $options));
      errorlog("Uj hash pw mentve: " . $username);
    }
  } else
    $user = null;

  return $user;
}

function logoff() {
  $a = session_id();
  if ($a == '')
    session_start();
  session_unset();
  session_destroy();
  header("Location: index.php");
}

function errorlog($error) {
  $fa = fopen(ERRORLOGFILE,"a");

  if ($fa) {
    fwrite($fa,date("Y.m.d H:i:s", time()) . " " . $error . "\n");
    fclose($fa);
  }
  return false;
}

function errorlogdev($error) {
  $fa = fopen("log/bigteam_dev.log", "a");

  if ($fa) {
    fwrite($fa,date("Y.m.d H:i:s", time()) . " " . $error . "\n");
    fclose($fa);
  }
  return false;
}

// kep file keszitese stringbol fotoalbumhoz
function generateimagefromstring($oldimage, $tmp_file) {
  $ret = true;

  $image = imagecreatefromstring($oldimage);

  // fajlba mentjuk a kepet
  $ret = imagejpeg($image, TMP_DIRECTORY . $tmp_file . "_fa.jpg", 60);

  imagedestroy($image);

  return $ret;
}

// preview (small) kep keszitese
function generateSmallImageFromFile($oldimage, $filename) {
  $ret = true;

  if (!file_exists($oldimage))
    return false;

  list($width, $height, $type) = getimagesize($oldimage);

  // kep generalasa
  switch ($type) {
    case 1:
      $image = imagecreatefromgif($oldimage);
      break;
    case 2:
      $image = imagecreatefromjpeg($oldimage);
      break;
    case 3:
      $image = imagecreatefrompng($oldimage);
      break;
  }

  // fajlba mentjuk a kepet
  $ret = imagejpeg($image, TMP_DIRECTORY . $filename, 40);

  imagedestroy($image);

  return $ret;
}

// preview (small) kep keszitese 2
function generateSmallImageFromFile2($oldimage, $filename) {
  $ret = true;

  $maxWidth = 1024;
  $maxHeight = 768;

  if (!file_exists($oldimage))
    return false;

  $image = new Imagick($oldimage);
  $geo = $image->getImageGeometry();
  $sizex = $geo['width'];
  $sizey = $geo['height'];

  $image->setImageCompression(Imagick::COMPRESSION_JPEG);
  $image->setImageCompressionQuality(90);

  if ($sizex > $maxWidth || $sizey > $maxHeight) {
    if ($sizex / $maxWidth >= $sizey / $maxHeight) {
      $image->resizeImage($maxWidth, $sizey / ($sizex / $maxWidth), Imagick::FILTER_LANCZOS, 1);
//      $image->adaptiveResizeImage($maxWidth, $sizey / ($sizex / $maxWidth));
    } else {
      $image->resizeImage($sizex / ($sizey / $maxHeight), $maxHeight, Imagick::FILTER_LANCZOS, 1);
//      $image->adaptiveResizeImage($sizex / ($sizey / $maxHeight), $maxHeight);
    }
    $ret = $image->writeImage(TMP_DIRECTORY . $filename);
  } else
    $ret = copy($oldimage, TMP_DIRECTORY . $filename);
  
  $image->clear();
  $image->destroy();

  return $ret;
}

// feluletek rendezesekor hivom
function cmpi($a, $b) {
  global $sidx;
  $str1 = iconv('utf-8', 'ascii//TRANSLIT', $a[$sidx]);
  $str2 = iconv('utf-8', 'ascii//TRANSLIT', $b[$sidx]); 
  return strcmp($str1, $str2);
}

function sendEmail($body) {
  mail(RECIPIENTMAIL, MAILSUBJECT, $body, MAILHEADER);
}

// kilepeskor toroljuk a feltoltott kepeket, atmeneti allomanyokat
function deletePhotos($felhasznaloid = 0) {
  //tmp dir
  $handler = opendir(TMP_DIRECTORY);
  while ($file = readdir($handler)) {
    if (substr($file,0,strlen("".$felhasznaloid)+1) == $felhasznaloid . "_")
    unlink(TMP_DIRECTORY . $file);
  }
  closedir($handler);

  //upload dir
  $handler = opendir(UPLOAD_DIRECTORY);
  while ($file = readdir($handler)) {
    if (substr($file,0,strlen("".$felhasznaloid)+1) == $felhasznaloid . "_")
    unlink(UPLOAD_DIRECTORY . $file);
  }
  closedir($handler);
}

function encrypt($str) {
  $skey = 'TRCUserModule';
  $wkey = shl(10,8);
  $c1 = 52845;
  $result = $str;
  if (strlen($str) > 0) {
    for ($i = 0; $i < strlen($str); $i++) {
      $result[$i] = chr(ord($str[$i]) ^ shr($wkey,8));
      $s = (((ord($result[$i]) + $wkey) * $c1) + ord($skey[$i % strlen($skey)])) & 65535;
      $wkey = $s;
    }
  }
  return $result;
}

function strToHex($str) {
  $hex = '';
  for ($i = 0; $i < strlen($str); $i++) {
    $byte = strtoupper(dechex(ord($str[$i])));
    $byte = str_repeat('0', 2 - strlen($byte)).$byte;
    $hex .= substr($byte,1,1) . substr($byte,0,1);
  }
  return $hex;
}

// bitwise shift to left
function shl($x, $n) {
  return $x << $n;
}

// bitwise shift to right
function shr($x, $n) {
  return $x >> $n;
}

function ftp_mkdir_($connId, $path) {
  $dir = split("/", $path);
  $path = "";
  $ret = true;

  for ($i = 0; $i < count($dir); $i++) {
    $path.="/".$dir[$i];
    if(!@ftp_chdir($connId, $path)) {
      @ftp_chdir($connId, "/");
      if (!@ftp_mkdir($connId, $path)) {
        $ret = false;
        break;
      }
    }
  }
  return $ret;
}

function sortPhotos($photos) {
  set_time_limit(300);

  $photos1_ = array();
  $photos2_ = array();
  foreach ($photos as $photo) {
    $image_parts = pathinfo($photo);
    if (isset($image_parts["filename"]) && isset($image_parts["extension"])) {
      $photos1_[] = $image_parts["filename"];
      $photos2_[$image_parts["filename"]] = $image_parts["extension"];
    }
  }
  sort($photos1_);
  
  $photos = array();
  foreach ($photos1_ as $photo) {
    $photos[] = $photo . "." . $photos2_[$photo];
  }

  set_time_limit(30);
  
  return $photos;
}

function removeAccent($str) {
  return strtr($str, array("Á" => "A", "É" => "E", "Ú" => "U", "Ő" => "O", "Ű" => "U", "Ó" => "O", "Ü" => "U", "Ö" => "O", "Í" => "I", "á" => "a", "é" => "e", "ú" => "u", "ő" => "o", "ű" => "u", "ó" => "o", "ü" => "u", "ö" => "o", "í" => "i", "'" => "", " " => ""));
}

function base64_encode_image($filename, $filetype) {
  if (file_exists($filename)) {
    $isEncodedSuccess = false;
    $encodedImage = "";
    $encodedImageHash = "";
    $encodedImageHashes = array();
    $i = 0;
    while ($i < 10 && !$isEncodedSuccess) {
      $encodedImageHashes = array();
      // encode image 3 times
      for ($j = 0; $j < 3; $j++) {
//        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        $imgbinary = file_get_contents($filename);
        $encodedImage = base64_encode($imgbinary);
        $encodedImageHashes[] = md5($encodedImage);
      }
      
      // check md5 hashes
      $encodedImageHash = $encodedImageHashes[0];
      $ok = true;
      for ($k = 1; $k < 3; $k++) {
        if ($encodedImageHash != $encodedImageHashes[$k])
          $ok = false;
      }
      if ($ok)
        $isEncodedSuccess = true;
      $i++;
    }
    if (!$isEncodedSuccess)
      $encodedImage = "-";
    return 'data:image/' . $filetype . ';base64,' . $encodedImage;
  }
}

function base64_decode_image($str) {
  $ret = '';
  if (strpos($str, 'data:image') === false) {
    $ret = $str;
  } else {
    $imageStr = base64_decode($str);
    $outputFile = $outputFile = 'tmp/img_' . uniqid();
    if (strpos($str, 'data:image/jpeg') !== false) {
      $outputFile .= '.jpg';
      $str = substr($str, 23);
    } else if (strpos($str, 'data:image/jpg') !== false) {
      $outputFile .= '.jpg';
      $str = substr($str, 22);
    } else if (strpos($str, 'data:image/png') !== false) {
      $outputFile .= '.png';
      $str = substr($str, 22);
    } else if (strpos($str, 'data:image/gif') !== false) {
      $outputFile .= '.gif';
      $str = substr($str, 22);
    } else if (strpos($str, 'data:image/tif') !== false) {
      $outputFile .= '.tif';
      $str = substr($str, 22);
    } else if (strpos($str, 'data:image/bmp') !== false) {
      $outputFile .= '.bmp';
      $str = substr($str, 22);
    }

    $ifp = fopen($outputFile, "wb");
    fwrite($ifp, base64_decode($str));
    fclose($ifp);
    $ret = $outputFile;
  }
  return $ret;
} 

function importRagLista($xlsFile, $date, $cegId = 0) {
  $errorImport = false;
  $ret = "";
  
  if (file_exists($xlsFile)) {
    
    try {
      $inputFileType = PHPExcel_IOFactory::identify($xlsFile);
      $objReader = PHPExcel_IOFactory::createReader($inputFileType);
      $objPHPExcel = $objReader->load($xlsFile);

      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow();
      $highestColumn = $sheet->getHighestColumn();
      $headerData = $sheet->rangeToArray('A1:' . $highestColumn . '1', NULL, TRUE, FALSE);
  
      if (isset($headerData[0][12]) && $headerData[0][12] == "JELL5")
        $xlsType = 1;
      else 
        $xlsType = 2;

      $isGPSEmbedded = false;
      if (isset($headerData[0][21]) && ($headerData[0][21] == "GPSKOORDINATAX" || $headerData[0][21] == "GPSKOORDINATAY"))
        $isGPSEmbedded = true;

      for ($row = 1; $row <= $highestRow; $row++) {
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
        if ($row > 1 && trim($rowData[0][0]) != "") {
          if (!isset($rowData[0][6]) || (isset($rowData[0][6]) && trim($rowData[0][6]) == "")) { // nincs felhasznalo
            $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A ragasztó nincs megadva!)\n";
            $errorImport = true;
          } else {
            if (!SERVER_SIDE || (SERVER_SIDE && strpos(strtolower($rowData[0][7]), "atfuto") === false && strpos(strtolower($rowData[0][7]), "átfutó") === false && (strpos(strtolower($rowData[0][6]), "bigteam") !== false || strpos(strtolower($rowData[0][6]), "big team") !== false))) {
              $user = GetUserByName(trim($rowData[0][6]));
              if (count($user) > 0) {
                $userId = $user["user_id"];
              } else {
                $userId = InsertUser(trim($rowData[0][6]), removeAccent(trim($rowData[0][6])), removeAccent(trim($rowData[0][6])), 0, 0);
              }
              
              $varosId = GetVarosId($rowData[0][5]);
              if ($varosId == 0)
                $varosId = InsertVaros($rowData[0][5]);
              
              $isValidDate = validateDate($date, "Y.m.d.");
              
              $feluletKod = str_replace("/", "_", $rowData[0][0]);
              if ($userId > 0 && $isValidDate) {
                $feluletId = GetFeluletId($feluletKod, $date);
                $db = 0;
                $isInsert = true;
    
                $isNeedPhoto = '0';
                $gpsLat = 'null';
                $gpsLon = 'null';
                if ($xlsType == 1) {
                  if (isset($rowData[0][20]))
                    $isNeedPhoto = $rowData[0][20];
                  if ($isGPSEmbedded) {
                    if (isset($rowData[0][21]) && trim($rowData[0][21]) != "" && is_numeric(str_replace(',', '.', $rowData[0][21])))
                      $gpsLat = str_replace(',', '.', $rowData[0][21]);
                    if (isset($rowData[0][22]) && trim($rowData[0][22]) != "" && is_numeric(str_replace(',', '.', $rowData[0][22])))
                      $gpsLon = str_replace(',', '.', $rowData[0][22]);
                  }
                } else {
                  if (isset($rowData[0][19]))
                    $isNeedPhoto = $rowData[0][19];
                  if ($isGPSEmbedded) {
                    if (isset($rowData[0][20]) && trim($rowData[0][20]) != "" && is_numeric(str_replace(',', '.', $rowData[0][20])))
                      $gpsLat = str_replace(',', '.', $rowData[0][20]);
                    if (isset($rowData[0][21]) && trim($rowData[0][21]) != "" && is_numeric(str_replace(',', '.', $rowData[0][21])))
                      $gpsLon = str_replace(',', '.', $rowData[0][21]);
                  }
                }
    
                if ($feluletId > 0) {
                  $isInsert = false;
                  $felulet = GetFelulet($feluletId);
                  
                  if ($cegId == 0 || $felulet["ceg_id"] == $cegId) {
                    if (is_array($felulet) && isset($felulet["uploadedphoto"]) && $felulet["uploadedphoto"] > 0) {
                      $ret .= "Az alábbi felület frissítése sikertelen: " . $rowData[0][0] . " (A felülethez már van fotó feltöltve!)\n";
                    } else {
                      if ($xlsType == 1) {
                        if (count($felulet) > 0) {
                          if ($rowData[0][9] != $felulet["felulettipus"] || $rowData[0][4] != $felulet["kampany_id"] || $rowData[0][13] != $felulet["kampany_nev"] || $varosId != $felulet["varos_id"] || $rowData[0][1] != $felulet["felulet_cim"] || $rowData[0][7] != $felulet["plakat"] || $isNeedPhoto != $felulet["isneedphoto"] || $userId != $felulet["user_id"])
                            $db = UpdateRagacsList($feluletId, $rowData[0][9], $rowData[0][4], str_replace("'", "\'", $rowData[0][13]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId);
                          else
                            $db = 1;
                        } else
                          $db = UpdateRagacsList($feluletId, $rowData[0][9], $rowData[0][4], str_replace("'", "\'", $rowData[0][13]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId);
                      } else {
                        if (count($felulet) > 0) {
                          if ($rowData[0][9] != $felulet["felulettipus"] || $rowData[0][4] != $felulet["kampany_id"] || $rowData[0][12] != $felulet["kampany_nev"] || $varosId != $felulet["varos_id"] || $rowData[0][1] != $felulet["felulet_cim"] || $rowData[0][7] != $felulet["plakat"] || $isNeedPhoto != $felulet["isneedphoto"] || $userId != $felulet["user_id"])
                            $db = UpdateRagacsList($feluletId, $rowData[0][9], $rowData[0][4], str_replace("'", "\'", $rowData[0][12]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId);
                          else
                            $db = 1;
                        } else
                          $db = UpdateRagacsList($feluletId, $rowData[0][9], $rowData[0][4], str_replace("'", "\'", $rowData[0][12]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId);
                      }
                    }
                  } else {
                    $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A felület már létezik másik cegnél!)\n";
                    $errorImport = true;
                  }
                } else {
                  if ($xlsType == 1) {
                    if ($isGPSEmbedded)
                      $feluletId = InsertRagacsList($feluletKod, trim($rowData[0][24]), trim($rowData[0][9]), $rowData[0][4], str_replace("'", "\'", $rowData[0][13]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId, $date, $cegId, $gpsLat, $gpsLon);
                    else
                      $feluletId = InsertRagacsList($feluletKod, trim($rowData[0][22]), trim($rowData[0][9]), $rowData[0][4], str_replace("'", "\'", $rowData[0][13]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId, $date, $cegId, $gpsLat, $gpsLon);
                  } else {
                    if ($isGPSEmbedded)
                      $feluletId = InsertRagacsList($feluletKod, trim($rowData[0][23]), trim($rowData[0][9]), $rowData[0][4], str_replace("'", "\'", $rowData[0][12]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId, $date, $cegId, $gpsLat, $gpsLon);
                    else
                      $feluletId = InsertRagacsList($feluletKod, trim($rowData[0][21]), trim($rowData[0][9]), $rowData[0][4], str_replace("'", "\'", $rowData[0][12]), $varosId, str_replace("'", "\'", $rowData[0][1]), str_replace("'", "\'", $rowData[0][7]), $isNeedPhoto, $userId, $date, $cegId, $gpsLat, $gpsLon);
                  }
                }
    
                if ($isInsert) {
                  if ($feluletId == 0) {
                    $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . "\n";
                    $errorImport = true;
                  }
                } else {
                  if ($db == 0) {
                    $ret .= "Az alábbi felület frissítése sikertelen: " . $rowData[0][0] . "\n";
                    $errorImport = true;
                  }
                }
              } else {
                if ($userId == 0)
                  $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A ragasztó nem létezik!)\n";
                if (!$isValidDate)
                  $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (Hibás dátum: " . $date . ")\n";
                $errorImport = true;
              }
            }
          }
        }
      }
      $objPHPExcel = null;
      $objReader = null;
    } catch(Exception $ex) {
      $ret = "Az xls feldolgozása nem sikerült!";
      errorlog($ret . " - " . $ex);
      return $ret;
    }

    if (!$errorImport)
      return "1";
    else {
      errorlog($ret);
      return $ret;
    }
  } else {
    $ret .= "Az xls file nem található!";
    errorlog($ret);
  }
  
  return $ret;
}

function importRagLista2($xlsFile, $date, $cegId = 0) {
  $errorImport = false;
  $ret = "";
  
  if (file_exists($xlsFile)) {
    
    try {
      $inputFileType = PHPExcel_IOFactory::identify($xlsFile);
      $objReader = PHPExcel_IOFactory::createReader($inputFileType);
      $objPHPExcel = $objReader->load($xlsFile);

      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow();
      $highestColumn = $sheet->getHighestColumn();
      $headerData = $sheet->rangeToArray('A1:' . $highestColumn . '1', NULL, TRUE, FALSE);
  
      for ($row = 1; $row <= $highestRow; $row++) {
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
        if ($row > 1 && trim($rowData[0][0]) != "") {
          if (true) {
            if (true) {
              $feluletKod = str_replace("/", "_", $rowData[0][0]);
              if (true) {
                $feluletId = GetFeluletId($feluletKod, $date);
    
                $gpsLat = $rowData[0][2];
                $gpsLon = $rowData[0][3];
                $sajatKod = $rowData[0][4];
    
                if ($feluletId > 0)
                  UpdateRagacsList3($feluletId, $sajatKod, $gpsLat, $gpsLon);
                else
      errorlog("Nincs feluletId: " . $feluletKod);
              }
            }
          }
        }
      }
      $objPHPExcel = null;
      $objReader = null;
    } catch(Exception $ex) {
      $ret = "Az xls feldolgozása nem sikerült!";
      errorlog($ret . " - " . $ex);
      return $ret;
    }
  } else {
    $ret .= "Az xls file nem található!";
    errorlog($ret);
  }
  
  return $ret;
}

function importServerSideRagLista($xlsFile, $date = "", $cegId = 0) {
  $errorImport = false;
  $ret = "";
  
  if (file_exists($xlsFile)) {
    
    try {
      $inputFileType = PHPExcel_IOFactory::identify($xlsFile);
      $objReader = PHPExcel_IOFactory::createReader($inputFileType);
      $objPHPExcel = $objReader->load($xlsFile);

      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow();
      $highestColumn = $sheet->getHighestColumn();
      $headerData = $sheet->rangeToArray('A1:' . $highestColumn . '1', NULL, TRUE, FALSE);
  
      for ($row = 1; $row <= $highestRow; $row++) {
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
        if ($row > 1 && trim($rowData[0][0]) != "") {
          if (!isset($rowData[0][8]) || (isset($rowData[0][8]) && trim($rowData[0][8]) == "")) { // nincs felhasznalo
            $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A ragasztó nincs megadva!)\n";
            $errorImport = true;
          } else {
            if (SERVER_SIDE) {
              $user = GetUserByName(trim($rowData[0][8]));
              if (count($user) > 0) {
                $userId = $user["user_id"];
              } else {
                $userId = InsertUser(trim($rowData[0][8]), removeAccent(trim($rowData[0][8])), removeAccent(trim($rowData[0][8])), 0, 0);
              }
              
              $varosId = GetVarosId($rowData[0][5]);
              if ($varosId == 0)
                $varosId = InsertVaros($rowData[0][5]);
  
              $date = "";
              if (trim($rowData[0][10]) != "" && trim($rowData[0][10]) > 0) {
                $unixDate = (trim($rowData[0][10]) - 25569) * 86400;
                $date = date("Y.m.d.", $unixDate);
              }
  
              $cegId = 0;
              if (trim($rowData[0][11]) != "")
                $cegId = GetCegIdByName(trim($rowData[0][11]));

              $isValidDate = true;
              if ($date != "")
                $isValidDate = validateDate($date, "Y.m.d.");

              $feluletKod = str_replace("/", "_", $rowData[0][0]);
              if ($userId > 0 && $date != "" && $isValidDate && $cegId > 0) {
                $feluletId = GetFeluletId($feluletKod, $date);
                $db = 0;
                $isInsert = true;
    
                $isNeedPhoto = $rowData[0][9];

                $gpsLat = 'null';
                $gpsLon = 'null';

                if ($feluletId > 0) {
                  $isInsert = false;
                  $felulet = GetFelulet($feluletId);
                  
                  if ($felulet["ceg_id"] == $cegId) {
                    if (is_array($felulet) && isset($felulet["uploadedphoto"]) && $felulet["uploadedphoto"] > 0) {
                      $ret .= "Az alábbi felület frissítése sikertelen: " . $rowData[0][0] . " (A felülethez már van fotó feltöltve!)\n";
                    } else {
                      if (count($felulet) > 0) {
                        if ($rowData[0][2] != $felulet["felulettipus"] || $rowData[0][3] != $felulet["kampany_id"] || $rowData[0][4] != $felulet["kampany_nev"] || $varosId != $felulet["varos_id"] || $rowData[0][6] != $felulet["felulet_cim"] || $rowData[0][7] != $felulet["plakat"] || $isNeedPhoto != $felulet["isneedphoto"] || $userId != $felulet["user_id"])
                          $db = UpdateRagacsList($feluletId, $rowData[0][2], $rowData[0][3], str_replace("'", "\'", $rowData[0][4]), $varosId, str_replace("'", "\'", $rowData[0][6]), str_replace("'", "\'", $rowData[0][7]), $rowData[0][9], $userId);
                        else
                          $db = 1;
                      } else
                        $db = UpdateRagacsList($feluletId, $rowData[0][2], $rowData[0][3], str_replace("'", "\'", $rowData[0][4]), $varosId, str_replace("'", "\'", $rowData[0][6]), str_replace("'", "\'", $rowData[0][7]), $rowData[0][9], $userId);
                    }
                  } else {
                    $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A felület már létezik másik cegnél!)\n";
                    $errorImport = true;
                  }
                } else {
                  $feluletId = InsertRagacsList($feluletKod, trim($rowData[0][1]), trim($rowData[0][2]), $rowData[0][3], str_replace("'", "\'", $rowData[0][4]), $varosId, str_replace("'", "\'", $rowData[0][6]), str_replace("'", "\'", $rowData[0][7]), $rowData[0][9], $userId, $date, $cegId, $gpsLat, $gpsLon);
                }
    
                if ($isInsert) {
                  if ($feluletId == 0) {
                    $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . "\n";
                    $errorImport = true;
                  }
                } else {
                  if ($db == 0) {
                    $ret .= "Az alábbi felület frissítése sikertelen: " . $rowData[0][0] . "\n";
                    $errorImport = true;
                  }
                }
              } else {
                if ($userId == 0) {
                  $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A ragasztó nem létezik!)\n";
                }
                if ($date == "" || !$isValidDate) {
                  $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A ragasztási dátum hibás!)\n";
                }
                if ($cegId == 0) {
                  $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A partner nem létezik!)\n";
                }
                $errorImport = true;
              }
            }
          }
        }
      }
      $objPHPExcel = null;
      $objReader = null;
    } catch (Exception $ex) {
      $ret = "Az xls feldolgozása sikertelen!";
      errorlog($ret . " - " . $ex);
    }
  
    if (!$errorImport)
      return "1";
    else
      return $ret;
  } else {
    $ret .= "Az xls file nem található!";
    errorlog($ret);
  }
  
  return $ret;
}

function importOsztoLista($xlsFile) {
  $errorImport = false;
  $ret = "";
  $retXls = array();
  
  if (file_exists($xlsFile)) {
    
    try {
      $inputFileType = PHPExcel_IOFactory::identify($xlsFile);
      $objReader = PHPExcel_IOFactory::createReader($inputFileType);
      $objPHPExcel = $objReader->load($xlsFile);
    } catch(Exception $ex) {
      $ret = "Az xls betöltése nem sikerült!";
      errorlog($ret);
      return $ret;
    }

    $sheet = $objPHPExcel->getSheet(0);
    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();
    $headerData = $sheet->rangeToArray('A1:' . $highestColumn . '1', NULL, TRUE, FALSE);

    for ($row = 1; $row <= $highestRow; $row++) {
      $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
      if ($row > 1 && trim($rowData[0][0]) != "") {
        if (!isset($rowData[0][11]) || (isset($rowData[0][11]) && trim($rowData[0][11]) == "")) { // nincs felhasznalo
          $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " (A ragasztó nincs megadva!)\n";
          $retXls[] = array("A felület nem importálható.", $rowData[0][0], "A ragasztó nincs megadva!");
          $errorImport = true;
        } else {
          $user = GetUserByName(trim($rowData[0][11]));
          if (count($user) > 0) {
            $userId = $user["user_id"];
          } else {
            $userId = InsertUser(trim($rowData[0][11]), removeAccent(trim($rowData[0][11])), removeAccent(trim($rowData[0][11])), 0, 0);
          }

          $date = "";
          if (trim($rowData[0][12]) != "" && trim($rowData[0][12]) > 0) {
            $unixDate = (trim($rowData[0][12]) - 25569) * 86400;
            $date = date("Y.m.d.", $unixDate);
          }

          $feluletKod = trim(str_replace("/", "_", $rowData[0][0]));
          if ($userId > 0 && $date != "") {
            $feluletId = GetFeluletId($feluletKod, $date);
            $db = 0;

            if ($feluletId > 0) {
              $isInsert = false;
              $felulet = GetFelulet($feluletId);
              
              if (count($felulet) > 0) {
                if ($rowData[0][9] != $felulet["plakat"] || $userId != $felulet["user_id"]) {
                  $felulet = GetFelulet($feluletId);
                  InsertRagacsListBackup($feluletId, $felulet["ceg_id"], $felulet["felulet_kod"], $felulet["sajat_kod"], $felulet["felulettipus"], $felulet["kampany_id"], $felulet["kampany_nev"], $felulet["varos_id"], $felulet["felulet_cim"], $felulet["plakat"], $felulet["user_id"], $felulet["ragasztas_datum"], $felulet["lezarva"], $felulet["lastuploadedphoto_datum"], $felulet["uploadedphoto"], $felulet["isneedphoto"], $felulet["kihelyezesi_foto_datumok"], $felulet["javito_foto_datumok"]);
                  $db = UpdateRagacsList2($feluletId, str_replace("'", "\'", $rowData[0][9]), $userId);
                } else
                  $db = 1;
              } else {
                $felulet = GetFelulet($feluletId);
                InsertRagacsListBackup($feluletId, $felulet["ceg_id"], $felulet["felulet_kod"], $felulet["sajat_kod"], $felulet["felulettipus"], $felulet["kampany_id"], $felulet["kampany_nev"], $felulet["varos_id"], $felulet["felulet_cim"], $felulet["plakat"], $felulet["user_id"], $felulet["ragasztas_datum"], $felulet["lezarva"], $felulet["lastuploadedphoto_datum"], $felulet["uploadedphoto"], $felulet["isneedphoto"], $felulet["kihelyezesi_foto_datumok"], $felulet["javito_foto_datumok"]);
                $db = UpdateRagacsList2($feluletId, str_replace("'", "\'", $rowData[0][9]), $userId);
              }
            }

            if ($db == 0) {
              $ret .= "Az alábbi felület frissítése sikertelen: " . $rowData[0][0] . " - " . $date . " A felület nem található!\n";
              $retXls[] = array("A felület frissítése sikertelen.", $rowData[0][0], $date, "A felület nem található!");
              $errorImport = true;
            }
          } else {
            if ($userId == 0) {
              $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " - " . $date . " (A ragasztó nem létezik!)\n";
              $retXls[] = array("A felület nem importálható.", $rowData[0][0], $date, "A ragasztó nem létezik!");
            }
            if ($date == "") {
              $ret .= "Az alábbi felület nem importálható: " . $rowData[0][0] . " - " . $date . " (A ragasztási dátum hibás!)\n";
              $retXls[] = array("A felület nem importálható.", $rowData[0][0], $date, "A ragasztási dátum hibás!");
            }
            $errorImport = true;
          }
        }
      }
    }
    
    $objPHPExcel = null;
    $objReader = null;

    if (!$errorImport)
      return array("ret" => "1", "filename" => "");
    else {
      $pathParts = pathinfo($xlsFile);
      $file = TMP_DIRECTORY . $pathParts["filename"] . "_error_" . uniqid() . ".xls";
      $workbook = new Spreadsheet_Excel_Writer($file);
      $workbook->setVersion(8);
      $worksheet =& $workbook->addWorksheet('Osztolista importalas jelentes');
      $worksheet->setInputEncoding('UTF-8');
      $cim_format =& $workbook->addFormat();
      $cim_format->setBold();
      $header_format =& $workbook->addFormat();
      $header_format->setBold();
      $header_format->setAlign("center");
      $format_center =& $workbook->addFormat();
      $format_center->setAlign("center");
      $worksheet->setColumn(0, 0, 40);
      $worksheet->setColumn(1, 1, 20);
      $worksheet->setColumn(2, 2, 20);
      $worksheet->setColumn(3, 3, 40);
      $worksheet->write(0, 0, 'Üzenet', $header_format);
      $worksheet->write(0, 1, 'Felületkód', $header_format);
      $worksheet->write(0, 2, 'Dátum', $header_format);
      $worksheet->write(0, 3, 'Hiba', $header_format);
      $sor = 1;
      foreach($retXls as $row) {
        $worksheet->writeString($sor, 0, $row[0]);
        $worksheet->writeString($sor, 1, $row[1], $format_center);
        $worksheet->writeString($sor, 2, $row[2], $format_center);
        $worksheet->writeString($sor, 3, $row[3]);
        $sor++;
      }
      $workbook->close();
      return array("ret" => $ret, "filename" => $file);
    }
  } else {
    $ret = array("ret" => "Az xls file nem található!", "filename" => "");
    errorlog($ret["ret"]);
  }
  
  return $ret;
}

function isFeluletExists($elements, $element) {
  $isExist = false;
  foreach ($elements as $row) {
    if ($row["ragacslist_id"] == $element["ragacslist_id"])
      $isExist = true;
  }
  
  return $isExist;
}

function ftpFileIsExists($file) {
  $isExists = false;
  if (FTP_USE_SSL)
    $conn_id = ftp_ssl_connect(FTP_SERVER) or die("Couldn't connect to " . FTP_SERVER);
  else
    $conn_id = ftp_connect(FTP_SERVER, FTP_PORT) or die("Couldn't connect to " . FTP_SERVER);
  $isFtpConnected = ftp_login($conn_id, FTP_USERNAME, FTP_PASSWORD);
  
  if ($isFtpConnected) {
    ftp_pasv($conn_id, true);
    $pathParts = pathinfo($file);
    
    if (@ftp_chdir($conn_id, $pathParts['dirname'])) {
      $files = ftp_nlist($conn_id, '.');
      for ($i = 0; $i < count($files); $i++) {
        if ($files[$i] == $pathParts['basename'])
          $isExists = true;
      }
    }
  }

  if ($conn_id)
    ftp_close($conn_id);

  return $isExists;
}

# ftp-re feltoltott zip file rendben van-e
function ftpIsZipFileComplete($file) {
  $ret = array();
  $isComplete = false;
  $downloadFile = "";
  
  $conn_id = null;
  if (FTP_USE_SSL)
    $conn_id = ftp_ssl_connect(FTP_SERVER) or die("Couldn't connect to " . FTP_SERVER);
  else
    $conn_id = ftp_connect(FTP_SERVER, FTP_PORT) or die("Couldn't connect to " . FTP_SERVER);
  $isFtpConnected = ftp_login($conn_id, FTP_USERNAME, FTP_PASSWORD);

  if ($isFtpConnected) {
    ftp_pasv($conn_id, true);
    $pathParts = pathinfo($file);
    
    $isExists = false;
    if (@ftp_chdir($conn_id, $pathParts['dirname'])) {
      $files = ftp_nlist($conn_id, '.');
      for ($i = 0; $i < count($files); $i++) {
        if ($files[$i] == $pathParts['basename'])
          $isExists = true;
      }

      if ($isExists) {
        $downloadFile = dirname(__DIR__) . "/" . TMP_DIRECTORY . $pathParts['basename'];
        if (ftp_get($conn_id, $downloadFile, $pathParts['basename'], FTP_BINARY, 0)) {
          $zip = new ZipArchive();
          $res = $zip->open($downloadFile, ZipArchive::CHECKCONS);
          if ($res !== true) {
            switch($res) {
              case ZipArchive::ER_NOZIP:
                errorlog('not a zip archive: ' . $downloadFile);
              case ZipArchive::ER_INCONS :
                errorlog('consistency check failed: ' . $downloadFile);
              case ZipArchive::ER_CRC :
                errorlog('checksum failed: ' . $downloadFile);
              default:
                errorlog('error: ' . $res . " " . $downloadFile);
            }
          } else {
            $isComplete = true;
            $zip->close();
          }
        }
      }
    }
  }

  if ($conn_id)
    ftp_close($conn_id);

  $ret = array("isComplete" => $isComplete, "file" => $downloadFile);

  return $ret;
}

function importZipFile($file) {
  $ret = ftpIsZipFileComplete($file);
  
  if ($ret["isComplete"] && $ret["file"] != "") {
    $zip = new ZipArchive();
    $res = $zip->open($ret["file"], ZipArchive::CHECKCONS);
    if ($res === true) {
      for ($i = 0; $i < $zip->numFiles; $i++) {
        $entry = $zip->statIndex($i);
        $f = $zip->getNameIndex($i);
        $pathPart = pathinfo(str_replace("\\", "/", $f));
        $dir = dirname(__DIR__) . "/" . IMPORT_FELDOLGOZANDO_DIRECTORY . $pathPart["dirname"];
        if (!file_exists($dir)) {
          mkdir($dir, 0777, true);
          chown($dir, "www-data");
          chgrp($dir, "www-data");
        }
        if (!copy("zip://" . $ret["file"] . "#" . $f, $dir . "/" . $pathPart["basename"]))
          errorlog("Hiba a fajl kibontasa soran: " . $ret["file"] . " - " . $pathPart["basename"]);
      }
      $zip->close();
    }
  }

  return $ret;
}

function validateDate($date, $format = 'Y-m-d H:i:s') {
  $d = DateTime::createFromFormat($format, $date);
  return $d && $d->format($format) == $date;
}

function recurseChownChgrp($path, $uid, $gid) {
  if (file_exists($path)) {
    $d = opendir($path);
    while (($file = readdir($d)) !== false) {
      if ($file != "." && $file != "..") {
        $typePath = $path . "/" . $file;
  
        chown($typePath, $uid);
        chgrp($typePath, $gid);
        if (filetype($typePath) == 'dir') {
          recurseChownChgrp($typePath, $uid, $gid);
        }
      }
    }
  }
}

function isAddFile($file, $onlyRepairedPhoto, $onlyStationPhoto, $fkezdodatumAsTimeStamp, $fvegsodatumAsTimeStamp) {
  $isAddFile = false;
  $isAddFileTemp = false;

  if ($fkezdodatumAsTimeStamp > 0 && $fvegsodatumAsTimeStamp > 0) {
    if ($fkezdodatumAsTimeStamp <= filemtime($file) && filemtime($file) <= $fvegsodatumAsTimeStamp)
      $isAddFileTemp = true;
  } else if ($fkezdodatumAsTimeStamp > 0) {
    if ($fkezdodatumAsTimeStamp <= filemtime($file))
      $isAddFileTemp = true;
  } else if ($fvegsodatumAsTimeStamp > 0) {
    if (filemtime($file) <= $fvegsodatumAsTimeStamp)
      $isAddFileTemp = true;
  } else
    $isAddFileTemp = true;

  if ($isAddFileTemp) {
    if (!$onlyRepairedPhoto && !$onlyStationPhoto)
      $isAddFile = true;
    else if ($onlyRepairedPhoto && strpos($file, "_J.") !== false)
      $isAddFile = true;
    else if ($onlyStationPhoto && strpos($file, "_J.") === false)
      $isAddFile = true;
  }

  return $isAddFile;
}

function updateFotoDatumok($feluletId) {
  $surface = null;
  if ($feluletId > 0)
    $surface = GetFelulet($feluletId);
//  else if ($feluletKod != "" && $ragacsDatum != "")
//    $surface = GetFeluletByFeluletKodRagasztasiDatum($feluletKod, $ragacsDatum);
  
  if (is_array($surface)) {
    $feluletKod = $surface["felulet_kod"];
    $sajatKod = $surface["sajat_kod"];
    $kampanyId = $surface["kampany_id"];
    $ragacsDatumAsTimeStamp = strtotime($surface["ragasztas_datum"]);
    $ragasztasDatum = date("Y.m.d.", $ragacsDatumAsTimeStamp);
  
    $folder = PHOTO_DIRECTORY . date("Y", $ragacsDatumAsTimeStamp) . "/" . date("m", $ragacsDatumAsTimeStamp) . "/" . $kampanyId . "/" . $ragasztasDatum;
  
    $kKepek = "";
    $jKepek = "";
    if (file_exists($folder)) {
      $fnames = scandir($folder);
      $fnames = sortPhotos($fnames);
  
      $kKepek_ = array();
      $jKepek_ = array();
      foreach ($fnames as $fname) {
        if (($fname != '.') && ($fname != '..') && ($fname != basename($_SERVER['PHP_SELF']))) {
          if (!is_dir($folder . "/" . $fname) && (fnmatch(strtoupper($feluletKod . ".jpg"), strtoupper(basename($fname))) !== false || fnmatch(strtoupper($feluletKod . "_J.jpg"), strtoupper(basename($fname))) !== false || fnmatch(strtoupper($feluletKod . "-F*.jpg"), strtoupper(basename($fname))) !== false || (trim($sajatKod) != "" && (fnmatch(strtoupper($sajatKod . ".jpg"), strtoupper(basename($fname))) !== false || fnmatch(strtoupper($sajatKod . "_J.jpg"), strtoupper(basename($fname))) !== false || fnmatch(strtoupper($sajatKod . "-F*.jpg"), strtoupper(basename($fname))) !== false)))) {
            $img = $folder . "/" . $fname;
            if (strpos($fname, "_J.jpg") === false)
              $kKepek_[] = array("img" => basename($img), "timestamp" => date("Y.m.d. H:i", filemtime($img)));
            else
              $jKepek_[] = array("img" => basename($img), "timestamp" => date("Y.m.d. H:i", filemtime($img)));
          }
        }
      }
      
      if (count($kKepek_) > 0)
        $kKepek = json_encode($kKepek_);
      if (count($jKepek_) > 0)
        $jKepek = json_encode($jKepek_);
  
      UpdatePhotoDates($feluletId, $kKepek, $jKepek);
    }
  }
}

?>
