<?php
/*=======================================================================
 *
 * inc_file.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


// *************
// * FUNCTIONS *
// *************

function myStrCheck($aStr)
{
  if (!(strpos($aStr, "Ã") === FALSE)) :		
     $aStr = utf8_decode($aStr);
  endif;
  $aStr = mysql_escape_string($aStr);  
  return $aStr;
}

function removeFieldSigns ($text) {
  $text = trim($text);
  if (substr($text, 0, 1) == "\"" && substr($text, -1) == "\"") :
    $text = substr($text, 1, -1);
  endif;
  return $text;
}

// Gets number of lines of a (csv-)file
function getNumOfLinesOfFile ($filename) {
	$count = -1;
	if ($filename != "") :
     $count = 0;
     $fp = fopen($filename, "r");
     while(!feof($fp)){
       $line = fgets($fp);
       $count++;
     }
     fclose($fp);
  endif;
  return $count;
}

// Gets number of (virtual) chunks of a (csv-)file
// E.g. [1. chunk: lines 0....4999], [2. chunk: lines 5000....9999],....
function getChunksOfFile ($filename, $chunkSize) {
	$numOfFileChunks = -1;
	if ($chunkSize == "") : $chunkSize = 5000; endif;
	$numOfLines = getNumOfLinesOfFile($filename);
	if ($numOfLines != -1) :
	   $numOfFileChunks = round(($numOfLines / $chunkSize),0) + 1;
  endif;
  return $numOfFileChunks;
}

function importCSV ($filename, $delimiter = ";", $removeDbSigns = "", $lineRangeFrom = 0, $lineRangeTo = PHP_INT_MAX) {

   if ($lineRangeFrom == "" || !is_numeric($lineRangeFrom)) : $lineRangeFrom = 0; endif;
   if ($lineRangeTo == "" || !is_numeric($lineRangeTo)) : $lineRangeTo = PHP_INT_MAX; endif;
   if ($lineRangeFrom > $lineRangeTo) : $lineRangeFrom = 0; $lineRangeTo = PHP_INT_MAX; endif;

   $fp = @fopen($filename, "r" ) or die("Konnte Datei nicht öffnen.");   
   $data = array();   // Empty array for data

   // loop to eof
   $i = 0;
   $count = 0;
   while(!feof($fp)) {
       $line = fgetcsv($fp, 4096, $delimiter);   // Read line with delimiter  (default = ";")
       if (!is_array($line)) continue;

       // Check range
       $doRead = true;
       if ($count < $lineRangeFrom) : $doRead = false; endif;
       if ($count > $lineRangeTo) : $doRead = false; endif;

       // Matrix of data (each element of data is a row, one row is a array of fields)
       if ($doRead) :
          $lineLen = count($line);
          for ($j = 0; $j < $lineLen; $j++) {
          	   if ($removeDbSigns != "") :
          	      $line[$j] = str_replace("'", "", $line[$j]);
          	   endif;
          	   $data[$i][$j] = myStrCheck($line[$j]);
          }              
          $i++;
       endif;
       $count++;
   }

   fclose($fp);
   return $data;
}

function importDataset ($filename) {

   $fp = @fopen($filename, "r" ) or die("Konnte Datei nicht öffnen.");   
   $data = array();   // Empty array for data

   // loop to eof
   $i = 0;
   while(!feof($fp)) {
       $line = fgets($fp);             // Read line
       $line = trim($line);
       if ($line != "") :
          $data[$i] = myStrCheck($line);  // Escape string
          $i++;
       endif;
   }

   fclose($fp);
   return $data;
}

function writeExportLog($logText) {  
  global $write2logfile, $db_log_file;
  
  if ($write2logfile == "1") :     
     $fileHandle = fopen($db_log_file, 'a');
     fwrite($fileHandle, $logText . "\n");
     fclose($fileHandle);
  endif;
return;
}

function writeImportLog($logText) {  
  global $write2logfile, $logFile;
  
  if ($write2logfile == "1") :     
     $fileHandle = fopen($logFile, 'a');
     fwrite($fileHandle, $logText . "\n");
     fclose($fileHandle);
  endif;
return;
}

function removeFile($fileName, $path = "", $pathSeparator = "/") {
	$retVal = "";
	if ($fileName != "") :	   	
	   // Set complete path
	   if ($path != "") :
	      if (substr($path, -1) != $pathSeparator ) : 
	         $path .= $pathSeparator;
	      endif;
	      $fileName = $path . $fileName;
	   endif;

     // Check existence of the file
     if (file_exists($fileName)) :
        unlink($fileName);
        $retVal = "0";
     else :
        $retVal = "-2";   // No file in directory
     endif;	
  else :
     $retVal = "-1";   // No file name specified
  endif;
  return $retVal;
}

function getNumOfFilesInFolder($path) {
  $retVal = 0;
  if (file_exists($path)) :
     if ($handle = opendir($path)) :
        while (false !== ($file = readdir($handle))) :
           if ($file != "." && $file != "..") {
              $retVal++;
           }
         endwhile;
         closedir($handle);
     endif;
  else :
     $retVal = "-1";  // Folder does not exist
  endif;
  return $retVal;
}

function getNumOfFilesByFilterInFolder($path, $filter = "", $prefix = "") {
  $retVal = 0;
  if (file_exists($path)) :
     if ($handle = opendir($path)) :
        while (false !== ($file = readdir($handle))) :
           if ($file != "." && $file != "..") {
           	  if ($filter == "") :
                 $retVal++;
              else :
                 // Count files according to filter in "$filter" only
                 if ($prefix = "1") :
                    if (substr($file,0,strlen($filter)) == $filter) :
                       $retVal++;
                    endif;
                 else :
                    if (!(strpos($file, $filter) === FALSE)) :
                       $retVal++;
                    endif;
                 endif;
              endif;
           }
         endwhile;
         closedir($handle);
     endif;
  else :
     $retVal = "-1";  // Folder does not exist
  endif;
  return $retVal;
}

function getFilenamesInFolder($path) {
  $retVal = array();
  if (file_exists($path)) :
     if ($handle = opendir($path)) :
        while (false !== ($file = readdir($handle))) :
           if ($file != "." && $file != "..") {
              $retVal[] = $file;
           }
         endwhile;
         closedir($handle);
     endif;
  else :
     $retVal = "-1";  // Folder does not exist
  endif;
  return $retVal;
}

// Find files in a specified directory with specified extensions (searches recursive in subfolders)
// Call function with :
// $htmlfiles = findfile('/some/dir','/\.(htm|html)$/');
function findfile($location='',$fileregex='') {
   if (!$location or !is_dir($location) or !$fileregex) {
       return false;
   } 
   $matchedfiles = array();
   $all = opendir($location);
   while ($file = readdir($all)) {
       if (is_dir($location.'/'.$file) and $file <> ".." and $file <> ".") {
         $subdir_matches = findfile($location.'/'.$file,$fileregex);
         $matchedfiles = array_merge($matchedfiles,$subdir_matches);
         unset($file);
       }
       elseif (!is_dir($location.'/'.$file)) {
         if (preg_match($fileregex,$file)) {
             array_push($matchedfiles,$location.'/'.$file);
         }
       }
   }
   closedir($all);
   unset($all);
   return $matchedfiles;
 }

function deleteTables($tableName, $whereClause = "") {
  global $db, $PHP_SELF;
  $sqlquery = "DELETE FROM " . $tableName;
  if ($whereClause != "") : $sqlquery .= " WHERE " . $whereClause; endif;
  $result = $db->query($sqlquery);
  if (DB::isError($result)) die ("$PHP_SELF:<br>$sqlquery<br>" . $result->getMessage());  
  writeExportLog("DELETE TABLE " . $tableName);
  echo "DELETE TABLE: " . $tableName . "<br>";
}

// Depending on the mode some directories are excluded by navigation except the current employee is administrator
function checkForPredefinedDirectories($pathToCompare) {
	global $hq_id;
	$retBool = true;
	// Check for path to customer data
  $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_CS", $hq_id);
  if ($dirSpecialForObjType == "") : $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_CS", "0"); endif;
  if ($dirSpecialForObjType == "") : $dirSpecialForObjType = "90b1a8efc903576bbb2d6e2a79b00a5e"; endif;
  if ($pathToCompare == $dirSpecialForObjType) : $retBool = false; endif;
  // Check for path to courier data
  if ($retBool) :
     $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_CR", $hq_id);
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_CR", "0"); endif;
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = "f697836ccbee1a08ff752f5510049f6e"; endif;
     if ($pathToCompare == $dirSpecialForObjType) : $retBool = false; endif;
  endif;
  // Check for path to couriervehicle data
  if ($retBool) :
     $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_CRVH", $hq_id);
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_CRVH", "0"); endif;
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = "7bb0357ar00a5u89ob1e3c9b2d6e2a79"; endif;
     if ($pathToCompare == $dirSpecialForObjType) : $retBool = false; endif;
  endif;
  // Check for path to employee data
  if ($retBool) :
     $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_EMP", $hq_id);
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_EMP", "0"); endif;
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = "yxj5fr3gz7uau378cf4gh2fcnh67i7gh"; endif;
     if ($pathToCompare == $dirSpecialForObjType) : $retBool = false; endif;
  endif;
  // Check for path to job data
  if ($retBool) :
     $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_JB", $hq_id);
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_JB", "0"); endif;
     if ($dirSpecialForObjType == "") : $dirSpecialForObjType = "a547bc4b2a91355a3aba3ed0827cf6f2"; endif;
     if ($pathToCompare == $dirSpecialForObjType) : $retBool = false; endif;
  endif;
  // ...
	return $retBool;
}


// Get path for object data (e.g. customer data with objType = "CS")
function getPathForObjectData ($basePath, $objType = "CS") {
	global $hq_id;
	$basePath = trim($basePath);
	if ($basePath != "") :
     $objDirSpecial = getParameterValue("0", "DATATRANSFER_DIRECTORY_" . $objType, $hq_id);
     if ($objDirSpecial == "") : $objDirSpecial = getParameterValue("0", "DATATRANSFER_DIRECTORY_" . $objType, "0"); endif;
     if ($objDirSpecial != "") : 
        $basePath .= $objDirSpecial . "/";
     endif;
     // Get parameter for usage the headquarters as sub-paths
     $parUseHqPath = getParameterValue("0", "DATATRANSFER_HQ_PATH_" . $objType . "_ENABLED", $hq_id);
     if ($parUseHqPath == "") : $parUseHqPath = getParameterValue("0", "DATATRANSFER_HQ_PATH_" . $objType . "_ENABLED", "0"); endif;
     if ($parUseHqPath == "1") :
        $hqMnemonic = getFieldValueFromId("headquarters","hq_id",$hq_id,"hq_mnemonic");
        if ($hqMnemonic != "") : 
           $basePath .= $hqMnemonic . "/";
        endif;
     endif;
  endif;
  return $basePath;
}


// If uploaded file is associated to a special object (e.g. customer document, courier document, etc.), 
// insert or update in REDUNDANT structure ("gdc") because of performance by displaying lists (customer list, courier list, job list, etc.)!
function gdcSetNumberOfDocuments ($docLocalDirCurrent, $objType, $objId, $fileFilterPrefix) {
  if ($docLocalDirCurrent != "" && $objType != "" && $objId != "" && $fileFilterPrefix != "") :
    $objType = strtolower($objType);
    $objNumOfFiles = getNumOfFilesByFilterInFolder($docLocalDirCurrent, $fileFilterPrefix, "1");
    if (existsEntry("genericdatacontainer", array("gdc_obj_type", $objType, "gdc_gen_fieldname", "num_of_documents", "gdc_obj_id", $objId))) :
       updateStmt("genericdatacontainer", "gdc_obj_id", $objId, array("gdc_content",$objNumOfFiles), "gdc_obj_type = '" . $objType . "' AND gdc_gen_fieldname = 'num_of_documents'");
    else :
       insertStmt("genericdatacontainer", array("gdc_obj_type", $objType, "gdc_gen_fieldname", "num_of_documents", "gdc_obj_id", $objId, "gdc_content", $objNumOfFiles, "gdc_context", ""));
    endif;
  endif;
}
?>
