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


// Splits a coordinates-string (scheme A10,20;30,40;55,75; ... Ax,y;...) into an array
function splitRawCoordinates ($stringToSplit) {
	
   $retArray = array();
   $stringToSplit = trim($stringToSplit);
	
   // A vector-cluster is a set of bound coordinate-pairs.
   $vectorCluster = spliti("A",$stringToSplit);
   $vcLen = count($vectorCluster);
   for ($i = 0; $i < $vcLen; $i++) {
       // Split the cluster into pairs
       $tmpArray = spliti(";",$vectorCluster[$i]);
       $retArray[] = $tmpArray;
   }                     
   return $retArray;
}


function checkMaxCoordinates ($coordinatesArray) {
	
   $xMax = 0;
   $yMax = 0;

   $caLen = count($coordinatesArray);
   for ($i = 0; $i < $caLen; $i++) {
   	$tmpArray = $coordinatesArray[$i];
   	$taLen = count($tmpArray);
   	for ($j = 0; $j < $taLen; $j++) {
   	    $coordPair = spliti(",",$coordinatesArray[$i][$j]);
   	    if (mcArrIsSet($coordPair, 0, 0) > $xMax) : $xMax = $coordPair[0]; endif;
   	    if (mcArrIsSet($coordPair, 1, 0) > $yMax) : $yMax = $coordPair[1]; endif;
        }
   }
   return array($xMax+1, $yMax+1);
}


function createSignImage ($coordinatesArray) {
	
   $maxCoordinates = checkMaxCoordinates ($coordinatesArray);
   $im = @imagecreate ($maxCoordinates[0],$maxCoordinates[1]) or die ("Cannot Initialize new GD image stream");
   $background_color = imagecolorallocate ($im, 255, 255, 255);
   $lineCol = imagecolorallocate ($im, 0, 0, 0);
      
   $caLen = count($coordinatesArray);      
   for ($i = 0; $i < $caLen; $i++) {
 	     $tmpArray = $coordinatesArray[$i];
   	   $taLen = count($tmpArray);
   	   // do not use the last component because of the split above it will always be zero !!!
   	   for ($j = 0; $j < $taLen-2; $j++) {
   	       $coordPair1 = spliti(",",$coordinatesArray[$i][$j]);
   	       $coordPair2 = spliti(",",$coordinatesArray[$i][$j+1]);   	    
           imageline ($im, $coordPair1[0], $coordPair1[1], $coordPair2[0], $coordPair2[1], $lineCol);            
       }
   }   
   return $im;
}


function createImage ($imgFilename = "", $xCoord = "100", $yCoord = "100", $size = "25", $angle = "45", $text = "", $retMode = "0", $x = 30, $y = 80) {

   if ($text == "") : $text = rand(1000,9999); endif;
	 if ($imgFilename == "") :
      $imgFilename = "../temp/captchas/" . date("YmdHis", mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("y"))) . ".png";
   endif;
   $im = imagecreate ($xCoord, $yCoord) or die ("Cannot Initialize new GD image stream");
   $background_color = imagecolorallocate ($im, 255, 255, 255);
   $lineCol = imagecolorallocate ($im, 0, 0, 0);
   imagettftext ($im, $size, $angle, $x, $y, $lineCol, "../include/arial.ttf", $text);
   imagepng ($im, $imgFilename);

   if ($retMode == "1") :
      return $im;
   else :
      $imgTag = "<img src=\"" . $imgFilename . "\" border=\"0\" height=\"" . $yCoord . "\" width=\"" . $xCoord . "\">\n";
      imagedestroy ($im);
      return array($imgFilename, $text, $imgTag);
   endif;
}


// Create a captcha image
function createCaptchaImage ($imgFilename = "", $xCoord = "100", $yCoord = "100", $size = "25", $angle = "45", $text = "") {

	$img = createImage ($imgFilename, $xCoord, $yCoord, $size, $angle, $text);
	return $img;
}


// Creates the image map according to the size parameter
function createMapImageFromFile ($mapFileName) {

   $mapFileName = "../images/" . $mapFileName;
   $im = "";
   if (file_exists($mapFileName)) :

      $im = @ImageCreateFromJPEG ($mapFileName);   // Create image from file   
   endif;  // Check file does exist
   
   return $im;
}	


// Returns the "pixel-point" according to the "geo-point" and the size of the current image map
function getMapImagePoint ($mapSizeMode = "2", $geoCoordX, $geoCoordY, $noDecimals = "1") {

   $mapPointX = "0";   $mapPointY = "0";
  
   if ($mapSizeMode != "1" && $mapSizeMode != "2" && $mapSizeMode != "3") : $mapSizeMode = "2"; endif;
   
   if ($geoCoordX != "" && $geoCoordY != "") :
   
      // Calibration parameters
      // Hamburg  	10.0011036114924  	53.5541579534295  	20095
      // Magdeburg  	11.6407479374166  	52.1217786614182  	39104
      // 1.6396443259242  Delta X   ~   +104 P.   =>   1.0  ~   63.4284
      // 1.4323792920113  Delta Y   ~   -149 P.   =>   1.0  ~  104.0227
      
      $geoCoordConstX = "10.0011036114924";   $geoCoordConstY = "53.5541579534295";
      $mapPointConstX = "280";                $mapPointConstY = "164";
      $mapPointConstDeltaX = "63.4284";       $mapPointConstDeltaY = "104.0227";
      
      // Resolution factor
      if ($mapSizeMode == "1") :
         // 622 x 833
         $mapPointConstX *= "1";              $mapPointConstY *= "1";
         $mapPointConstDeltaX *= "1.09";      $mapPointConstDeltaY *= "1.02";
      endif;
      if ($mapSizeMode == "2") :
         // 673 x 900
         $mapPointConstX = "305";                 $mapPointConstY = "176";
         $mapPointConstDeltaX *= "1.18";      $mapPointConstDeltaY *= "1.10";
      endif;
      if ($mapSizeMode == "3") :
         // 765 x 1024
         $mapPointConstX = "344";                 $mapPointConstY = "201";
         $mapPointConstDeltaX *= "1.33";         $mapPointConstDeltaY *= "1.255";
      endif;
   
      $mapPointX = $mapPointConstX + (($geoCoordX - $geoCoordConstX) * $mapPointConstDeltaX);
      $mapPointY = $mapPointConstY + (($geoCoordConstY - $geoCoordY) * $mapPointConstDeltaY);

      if ($noDecimals == "1") :
         if (!(strpos($mapPointX, ".") === FALSE)) :
            $mapPointX = substr($mapPointX, 0, strpos($mapPointX, "."));         
         endif;
         if (!(strpos($mapPointY, ".") === FALSE)) :
            $mapPointY = substr($mapPointY, 0, strpos($mapPointY, "."));
         endif;
      endif;
   
   endif;  // Check file does exist
   
   return array($mapPointX, $mapPointY);
}	


// Makes an image more transparent
function getTransparency ($im, $scalingFactorPercent = "0") {
   
   if ($im) :
      // Get size of the original image
      $imSizeX = imagesx($im);
      $imSizeY = imagesy($im);

      // Create a new white temporary image for merging with original image
      // $imTmp = @imagecreate ($imSizeX, $imSizeY) or die ("Cannot Initialize new GD image stream");
      $imTmp = @imagecreate ("200", "200") or die ("Cannot Initialize new GD image stream");
      imagecolorallocate ($imTmp, 255, 255, 255);
      // int ImageCopy ( int dst_im, int src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h);
      imagecopymerge ( $im, $imTmp, 0, 0, 0, 0, $imSizeX, $imSizeY, $scalingFactorPercent);
   endif;

   return $im;
}	


// Displays box around a text
function setTextBox ($im, $boxPointsArray, $boxBorder = "0", $lineCol = "") {
   
   if ($im && count($boxPointsArray) > 0) :
      if ($lineCol == "") : $lineCol = imagecolorallocate ($im, 0, 0, 0); endif;

      // bottom line (left to right)
      imageline ($im, $boxPointsArray[0] - $boxBorder, $boxPointsArray[1] + $boxBorder, $boxPointsArray[2] + $boxBorder, $boxPointsArray[3] + $boxBorder, $lineCol);
      // right line (bottom to top)
      imageline ($im, $boxPointsArray[2] + $boxBorder, $boxPointsArray[3] + $boxBorder, $boxPointsArray[4] + $boxBorder, $boxPointsArray[5] - $boxBorder, $lineCol);
      // top line (right to left)
      imageline ($im, $boxPointsArray[4] + $boxBorder, $boxPointsArray[5] - $boxBorder, $boxPointsArray[6] - $boxBorder, $boxPointsArray[7] - $boxBorder, $lineCol);
      // left line (top to bottom)
      imageline ($im, $boxPointsArray[6] - $boxBorder, $boxPointsArray[7] - $boxBorder, $boxPointsArray[0] - $boxBorder, $boxPointsArray[1] + $boxBorder, $lineCol);
   endif;

   return $im;
}	


// Displays a crosshairs of a special point
function setCrosshairs ($im, $point, $expansion = "30", $lineCol = "") {
   
   if ($im && count($point) > 0) :         
      // Get size of the original image
      $imSizeX = imagesx($im);
      $imSizeY = imagesy($im);
      
      if ($lineCol == "") : $lineCol = imagecolorallocate ($im, 0, 0, 0); endif;

      imageline ($im, $point[0], $point[1] - $expansion, $point[0], $point[1] + $expansion, $lineCol);
      imageline ($im, $point[0] - $expansion, $point[1], $point[0] + $expansion, $point[1], $lineCol);
   endif;

   return $im;
}	


function getGeoCoordinatesFromZipcode($zipcode = "") {
	global $srvp_longitude, $srvp_latitude, $plzg_laenge, $plzg_breite;

  $retArray = array();
  if (is_numeric($zipcode)) : 
     getDbFieldValues("serviceplz",array("srvp_longitude","srvp_latitude"),array("srvp_plz",$zipcode));
     $zipLong = $srvp_longitude;
     $zipLat = $srvp_latitude;
     if ($zipLong == "" || $zipLat == "") :
        getDbFieldValues("phoenix_special.plz_geodb",array("plzg_laenge","plzg_breite"),array("plzg_code",$zipcode));
        $zipLong = $plzg_laenge;
        $zipLat = $plzg_breite;
     endif;
     $retArray = array($zipLong, $zipLat);
  endif;
  return $retArray;
}


function getMapCoordinatesFromZipcode($zipcode = "", $mapSizeMode = "2") {

  $retArray = array();
  if (is_numeric($zipcode)) :
     // Get geo coordinates from zipcode
     $zipGeoCoord = getGeoCoordinatesFromZipcode($zipcode);
     if ($zipGeoCoord[0] != "" && $zipGeoCoord[1] != "") :
        // Get map coordinates
        $retArray = getMapImagePoint($mapSizeMode, $zipGeoCoord[0], $zipGeoCoord[1]);
     endif;
  endif;
  return $retArray;
}


function saveImageToFile($retVal, $filename, $systemPath = "..", $imgWidthNew = "", $imgHeightNew = "") {
	global $hq_id;
	if ($retVal != "" && $filename != "") :
	   if ($systemPath == "") : $systemPath = ".."; endif;
     $rawCoord = splitRawCoordinates($retVal);
     $maxCoord = checkMaxCoordinates($rawCoord);
     $tmpSignPath = getParameterValue("0", "SIGNS_PATH", $hq_id);
     if ($tmpSignPath == "") : $tmpSignPath = getParameterValue("0", "SIGNS_PATH", "0"); endif;
     if ($tmpSignPath == "") : $tmpSignPath = "../temp/signs/"; endif;
     $imgFilename = $tmpSignPath . $filename;
     $im = createSignImage($rawCoord);
     $boolImg = true;
     if (!file_exists($imgFilename)) :
        $boolImg = imagepng($im, $imgFilename);
     endif;
     // Overwrite width and height
     $imgWidth = $maxCoord[0];
     $imgHeight = $maxCoord[1];
     if ($imgWidthNew != "" && is_numeric($imgWidthNew)) : $imgWidth = $imgWidthNew; endif;
     if ($imgHeightNew != "" && is_numeric($imgHeightNew)) : $imgHeight = $imgHeightNew; endif;
     if ($boolImg) :
        if ($systemPath == "..") :
           $retVal = "<img src=\"" . $imgFilename . "\" border=\"0\" height=\"" . $imgHeight . "\" width=\"" . $imgWidth . "\">";
        else :
           $retVal = "<img src=\"<PATH_ABS>" . $imgFilename . "</PATH_ABS>\" border=\"0\" height=\"" . $imgHeight . "\" width=\"" . $imgWidth . "\">";
        endif;
     else :
        $retVal = "";
     endif;
  endif;
  return $retVal;
}


// Gets an image (e.g. photo) out of the database (table "b2b_objects"), generate a file and returns the filename
function getImageFromB2bObjects ($objId, $parPodPath = "", $objType = "tr", $fileName = "") {
	global $db, $dbConnectionHistory, $hq_id;
	$db_conn = $db;
	$retVal = "";
  if ($objId != "" && is_numeric($objId) && $objId > "0") :
     $objIdLen = strlen(strval($objId));
     $b2bTableName = "phoenix_log.b2b_objects";

     // Get path for proof of delivery photo
     if ($parPodPath == "") :
        $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", $hq_id);
        if ($parPodPath == "") : $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", "0"); endif;
        if ($parPodPath == "") : $parPodPath = "../temp/photos/"; endif;
     endif;

     // Check filter by single filename
     $whereClause = "";
     if ($fileName != "") :
        $whereClause = " AND bo_obj_data = '" . $fileName . "' ";
     endif;

     // Get ID to identify the image chunks
     $imageFilename = getOneStmt("SELECT bo_obj_data FROM " . $b2bTableName . " WHERE bo_ext_id0 = '" . $objId . "' AND bo_type = '101'" . $whereClause, "bo_obj_data");
     if ($imageFilename != "") :
        $boId = getOneStmt("SELECT bo_id FROM " . $b2bTableName . " WHERE bo_ext_id0 = '" . $objId . "' AND bo_type = '101'" . $whereClause, "bo_id");
     else : 
        $imageFilename = getOneStmt("SELECT bo_obj_data FROM " . $b2bTableName . " WHERE LEFT(bo_obj_data," . $objIdLen . ") = '" . $objId . "' AND bo_type = '101'", "bo_obj_data");
        $boId = getOneStmt("SELECT bo_id FROM " . $b2bTableName . " WHERE LEFT(bo_obj_data," . $objIdLen . ") = '" . $objId . "' AND bo_type = '101'", "bo_id");
     endif;

     // If data not found try to get from b2b_objects history table
if (false) :
     if ($boId == "") :
        // Get connection to b2b_objects history database
        $db_conn = getDbHistoryConnection($dbHistoryConnection);
        if (is_object($db_conn)) :
           // Get ID to identify the image chunks
           $b2bTableName = "phoenix_log.b2b_objects_2015";
           $imageFilename = getOneStmt("SELECT bo_obj_data FROM " . $b2bTableName . " WHERE bo_ext_id0 = '" . $objId . "' AND bo_type = '101'" . $whereClause, "bo_obj_data", $db_conn);
           if ($imageFilename != "") :
              $boId = getOneStmt("SELECT bo_id FROM " . $b2bTableName . " WHERE bo_ext_id0 = '" . $objId . "' AND bo_type = '101'" . $whereClause, "bo_id", $db_conn);
           else : 
              $imageFilename = getOneStmt("SELECT bo_obj_data FROM " . $b2bTableName . " WHERE LEFT(bo_obj_data," . $objIdLen . ") = '" . $objId . "' AND bo_type = '101'", "bo_obj_data", $db_conn);
              $boId = getOneStmt("SELECT bo_id FROM " . $b2bTableName . " WHERE LEFT(bo_obj_data," . $objIdLen . ") = '" . $objId . "' AND bo_type = '101'", "bo_id", $db_conn);           
           endif;
        endif;
     endif;
endif;

     if ($boId != "") :
        // Get encodes chunks of the image
        $boObjDataArray = getColVectorFromDB2ArrayByClause($b2bTableName, "bo_obj_data", "bo_type = '102' AND bo_ext_id0 = '" . $boId . "'", "bo_ext_id2", "bo_ext_id2", "", $db_conn);

        // Get encoded image data
        $encodedImageData = "";
        $boObjDataArrayLen = count($boObjDataArray);
        if ($boObjDataArrayLen > 0) :
           for ($i = 0; $i < $boObjDataArrayLen; $i++) {
               $encodedImageData .= substr($boObjDataArray[$i],9,-3);    // Remove "<![CDATA[" from the beginning and "]]>" from the end
           }
           if ($encodedImageData != "") :
              // Decode image data
              $decodedImageData = base64_decode($encodedImageData);

              // Generate output file
              if (file_exists($parPodPath . $imageFilename)) :
                 unlink($parPodPath . $imageFilename);
              endif;
              writeToFile($parPodPath . $imageFilename, $decodedImageData);

              $retVal = $imageFilename;
           endif;
        endif;
     endif;
  endif;
  return $retVal;
}


// Gets images (e.g. photos) out of the database (table "b2b_objects")
function getImagesFromB2bObjects ($objId, $parPodPath = "", $objType = "tr") {
	global $db, $dbConnectionHistory, $hq_id;
	$db_conn = $db;
	$retArray = array();
  if ($objId != "" && is_numeric($objId) && $objId > "0") :
     $objIdLen = strlen(strval($objId));
     $b2bTableName = "phoenix_log.b2b_objects";

     // Get filenames of the specified object ID (job, tour, etc.)
     $boFilenames = getColVectorFromDB2ArrayByClause($b2bTableName, "bo_obj_data", "bo_type = '101' AND bo_ext_id0 = '" . $objId . "'");
     $boFilenamesLen = count($boFilenames);
if (false) :
     if ($boFilenamesLen == 0) :
        // Get connection to b2b_objects history database
        $db_conn = getDbHistoryConnection($dbHistoryConnection);
        if (is_object($db_conn)) :
           $b2bTableName = "phoenix_log.b2b_objects_2015";
           $boFilenames = getColVectorFromDB2ArrayByClause($b2bTableName, "bo_obj_data", "bo_type = '101' AND bo_ext_id0 = '" . $objId . "'", "", "", "", $db_conn);
           $boFilenamesLen = count($boFielenames);
        endif;
     endif;
endif;

     if ($boFilenamesLen > 0) :
         for ($i = 0; $i < $boFilenamesLen; $i++) :
             $fileName = getImageFromB2bObjects($objId, $parPodPath, $objType, $boFilenames[$i]);
             if ($fileName != "") :
                $retArray[] = $fileName;
             endif;
         endfor;
     endif;
  endif;
  return $retArray;
}

// Gets an image (e.g. photo) out of the database (table "b2b_objects"), generate a file and returns the filename
function getImageFromPic ($objId, $parPodPath = "", $objType = "tr", $picID = "", $useDbHistoryTable = false) {
	global $db, $dbConnectionHistory, $hq_id;
	$db_conn = $db;
	$retVal = "";

  if ($objId != "" && is_numeric($objId) && $objId > "0") :
     $objIdLen = strlen(strval($objId));
     $picTableName = "phoenix_log.pic";
     $filenamePrefix = "pic_tr_photo_";
     $filenameSuffix = ".jpg";
     $imageFilename = $filenamePrefix . $picID . $filenameSuffix;
     // Get connection to pic history database if needed
     if ($useDbHistoryTable) :
        $db_conn = getDbHistoryConnection($dbHistoryConnection);
     endif;

     // Get path for proof of delivery photo
     if ($parPodPath == "") :
        $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", $hq_id);
        if ($parPodPath == "") : $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", "0"); endif;
        if ($parPodPath == "") : $parPodPath = "../temp/photos/"; endif;
     endif;

     // If data not found try to get from b2b_objects history table
     if ($picID != "") :

        // Get encoded image data
        $picData = getFieldValueFromId($picTableName,"pic_id",$picID,"pic_data");
        // Get encoded image data
        $decodedImageData = base64_decode($picData);

        // Generate output file
        if (file_exists($parPodPath . $imageFilename)) :
           unlink($parPodPath . $imageFilename);
        endif;
        writeToFile($parPodPath . $imageFilename, $decodedImageData);

        $retVal = $imageFilename;
     endif;
  endif;
  return $retVal;
}

// Gets images (e.g. photos) out of the database (table "pic")
function getImagesFromPic ($objId, $parPodPath = "", $objType = "tr") {
	global $db, $dbConnectionHistory, $hq_id;
	$db_conn = $db;
	$retArray = array();
  if ($objId != "" && is_numeric($objId) && $objId > "0") :
     $objIdLen = strlen(strval($objId));
     $picTableName = "phoenix_log.pic";
     $useDbHistoryTable = false;

     // Get filenames of the specified object ID (job, tour, etc.)
     $picIDs = getColVectorFromDB2ArrayByClause($picTableName, "pic_id", "tr_id = '" . $objId . "'");
     $picIDsLen = count($picIDs);
     /*
     if ($picIDsLen == 0) :
        // Get connection to b2b_objects history database
        $db_conn = getDbHistoryConnection($dbHistoryConnection);
        if (is_object($db_conn)) :
           $picTableName = "phoenix_log.pic_20XX";
           $picIDs = getColVectorFromDB2ArrayByClause($picTableName, "pic_id", "tr_id = '" . $objId . "'", "", "", "", $db_conn);
           $picIDsLen = count($picIDs);
           if ($picIDsLen > 0) :
              $useDbHistoryTable = true;
           endif;
        endif;
     endif;
     */
     if ($picIDsLen > 0) :
         for ($i = 0; $i < $picIDsLen; $i++) :
             $fileName = getImageFromPic($objId, $parPodPath, $objType, $picIDs[$i], $useDbHistoryTable);
             if ($fileName != "") :
                $retArray[] = $fileName;
             endif;
         endfor;
     endif;
  endif;
  return $retArray;
}
?>