Exemple #1
0
function MoveAndUpdate($CatId, $ImageFile, $FolderName)
{
    $FileName = substr($ImageFile, 2);
    $subDir = "";
    // Determine the destination directory
    //$randomDir = strtolower(chr(rand(65, 90)));
    $subDir = $FolderName;
    $destPath = realpath(ISC_BASE_PATH . '/' . 'category_images');
    if (!is_dir($destPath . '/' . $subDir)) {
        if (!mkdir($destPath . '/' . $subDir, 0777)) {
            $subDir = '';
        }
    }
    $destFile = GenRandFileName($FileName, 'cat');
    $destPath = $destPath . '/' . $subDir . '/' . $destFile;
    $returnPath = $subDir . '/' . $destFile;
    //echo ISC_BASE_PATH.'/' . 'product_images'. '/' .$ImageFile;
    if (file_exists(ISC_BASE_PATH . '/' . 'product_images' . '/' . $ImageFile)) {
        if (copy(ISC_BASE_PATH . '/' . 'product_images' . '/' . $ImageFile, $destPath)) {
            $query2 = "UPDATE isc_categories SET catimagefile='{$returnPath}' WHERE categoryid ='{$CatId}'";
            $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query2);
            return true;
        }
    }
}
 private function SaveQValueAssociationImage()
 {
     if (!array_key_exists('associationimage', $_FILES) || $_FILES['associationimage']['error'] !== 0 || strtolower(substr($_FILES['associationimage']['type'], 0, 6)) !== 'image/') {
         return false;
     }
     // Attempt to set the memory limit
     setImageFileMemLimit($_FILES['associationimage']['tmp_name']);
     // Generate the destination path
     $randomDir = strtolower(chr(rand(65, 90)));
     $destPath = realpath(ISC_BASE_PATH . '/' . GetConfig('ImageDirectory'));
     if (!is_dir($destPath . '/' . $randomDir)) {
         if (!@mkdir($destPath . '/' . $randomDir, 0777)) {
             $randomDir = '';
         }
     }
     $destFile = GenRandFileName($_FILES['associationimage']['name'], 'category');
     $destPath = $destPath . '/' . $randomDir . '/' . $destFile;
     $returnPath = $randomDir . '/' . $destFile;
     $tmp = explode('.', $_FILES['associationimage']['name']);
     $ext = strtolower($tmp[count($tmp) - 1]);
     if ($ext == 'jpg') {
         $srcImg = imagecreatefromjpeg($_FILES['associationimage']['tmp_name']);
     } else {
         if ($ext == 'gif') {
             $srcImg = imagecreatefromgif($_FILES['associationimage']['tmp_name']);
             if (!function_exists('imagegif')) {
                 $gifHack = 1;
             }
         } else {
             $srcImg = imagecreatefrompng($_FILES['associationimage']['tmp_name']);
         }
     }
     $srcWidth = imagesx($srcImg);
     $srcHeight = imagesy($srcImg);
     $widthLimit = GetConfig('BrandImageWidth');
     $heightLimit = GetConfig('BrandImageHeight');
     // If the image is small enough, simply move it and leave it as is
     if ($srcWidth <= $widthLimit && $srcHeight <= $heightLimit) {
         imagedestroy($srcImg);
         move_uploaded_file($_FILES['associationimage']['tmp_name'], $destPath);
         return $returnPath;
     }
     // Otherwise, the image needs to be resized
     $attribs = getimagesize($_FILES['associationimage']['tmp_name']);
     $width = $attribs[0];
     $height = $attribs[1];
     if ($width > $widthLimit) {
         $height = ceil($widthLimit / $width * $height);
         $width = $widthLimit;
     }
     if ($height > $heightLimit) {
         $width = ceil($heightLimit / $height * $width);
         $height = $heightLimit;
     }
     $dstImg = imagecreatetruecolor($width, $height);
     if ($ext == "gif" && !isset($gifHack)) {
         $colorTransparent = imagecolortransparent($srcImg);
         imagepalettecopy($srcImg, $dstImg);
         imagecolortransparent($dstImg, $colorTransparent);
         imagetruecolortopalette($dstImg, true, 256);
     } else {
         if ($ext == "png") {
             ImageColorTransparent($dstImg, ImageColorAllocate($dstImg, 0, 0, 0));
             ImageAlphaBlending($dstImg, false);
         }
     }
     imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
     if ($ext == "jpg") {
         imagejpeg($dstImg, $destPath, 100);
     } else {
         if ($ext == "gif") {
             if (isset($gifHack) && $gifHack == true) {
                 $thumbFile = isc_substr($destPath, 0, -3) . "jpg";
                 imagejpeg($dstImg, $destPath, 100);
             } else {
                 imagegif($dstImg, $destPath);
             }
         } else {
             imagepng($dstImg, $destPath);
         }
     }
     @imagedestroy($dstImg);
     @imagedestroy($srcImg);
     @unlink($_FILES['associationimage']['tmp_name']);
     // Change the permissions on the thumbnail file
     isc_chmod($returnPath, ISC_WRITEABLE_FILE_PERM);
     return $returnPath;
 }
 private function DownloadVideo($url, $FileType = FT_VIDEO)
 {
     include ISC_BASE_PATH . "/livevideos/phptube.php";
     include ISC_BASE_PATH . "/livevideos/functions.php";
     @clearstatcache();
     @ini_set('output_buffering', 'off');
     // output buffer fix
     @ini_set('max_execution_time', 0);
     // time limit fix
     @ini_set('memory_limit', '1024M');
     // memory problem fix
     //error_reporting(1);
     @ignore_user_abort(1);
     @set_time_limit(0);
     //@ob_end_clean();
     @ob_implicit_flush(TRUE);
     $pattern = getPatternFromUrl($url);
     if ($FileType == FT_INSVIDEO) {
         $dir = GetConfig('InstallVideoDirectory');
     } else {
         $dir = GetConfig('VideoDirectory');
     }
     if (is_dir(sprintf("../%s", $dir))) {
         // Images and downloads will be stored within a directory randomly chosen from a-z.
         $randomDir = strtolower(chr(rand(65, 90)));
         if (!is_dir("../" . $dir . "/" . $randomDir)) {
             if (!@mkdir("../" . $dir . "/" . $randomDir, 0777)) {
                 $randomDir = '';
             }
         }
     }
     $patternName = $pattern . ".flv";
     //
     $randomFileName = GenRandFileName($patternName);
     $fileName = $randomDir . "/" . $randomFileName;
     $dest = realpath(ISC_BASE_PATH . "/" . $dir);
     while (file_exists($dest . "/" . $fileName)) {
         $fileName = basename($randomFileName);
         $fileName = substr_replace($randomFileName, "-" . rand(0, 10000000000.0), strrpos($randomFileName, "."), 0);
         $fileName = $randomDir . "/" . $fileName;
     }
     $dest .= "/" . $fileName;
     $tube = new PHPTube();
     $flv_http_path = $tube->download($pattern);
     $data = file_get_contents($flv_http_path);
     file_put_contents($dest, $data);
     return $fileName;
     if (filesize($dest) > 0) {
         return $fileName;
     } else {
         return "failed";
     }
 }
 protected function _ImportRecord($record)
 {
     $loggedid = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUserId();
     static $categoryCache;
     if (!is_array($categoryCache)) {
         $categoryCache = array();
     }
     /*
     		if(!isset($record['prodname']) || empty($record['prodname'])) {
     			$this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang('ImportProductsMissingName');
     			return;
     		}
     
     	if ($message = strtokenize($_REQUEST, '#')) {
     			$this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang(B('UmVhY2hlZFByb2R1Y3RMaW1pdA=='));
     			return;
     		}*/
     if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
         $vendorId = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId();
     } else {
         $vendorId = (int) @$record['prodvendorid'];
     }
     if (!is_int($record['prodvendorid'])) {
         $query = "SELECT vendorid FROM [|PREFIX|]vendors WHERE vendorname='" . $record['prodvendorid'] . "'";
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $vendorId = $row['vendorid'];
         }
     }
     /*
     $record['category1'] = str_replace("/", "SlaSH", $record['category1']);
     $record['category2'] = str_replace("/", "SlaSH", $record['category2']);
     $record['category3'] = str_replace("/", "SlaSH", $record['category3']);
     */
     // Automatically fetching categories based on CSV field
     if (isset($this->ImportSession['AutoCategory'])) {
         // We specified more than one level for the category back in the configuration
         if (isset($record['category1'])) {
             $record['category'] = array($record['category1']);
             if (isset($record['category2']) && $record['category2'] != '') {
                 $record['category'][] = $record['category2'];
             }
             //if(isset($record['category3']) && $record['category3'] != '') {
             //$record['category'][] = $record['category3'];
             //}
             $record['category'] = implode("/#/", $record['category']);
         }
         if (!$record['category']) {
             $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportProductsMissingCategory');
             return;
         }
         // Import the categories for the products too
         $categoryList = explode(";", $record['category']);
         $cats = array();
         foreach ($categoryList as $importCategory) {
             $categories = explode("/#/", $importCategory);
             $parentId = 0;
             $lastCategoryId = 0;
             if (!isset($categoryCache[$importCategory])) {
                 foreach ($categories as $category) {
                     $category = trim($category);
                     if ($category == '') {
                         continue;
                     }
                     //$category = str_replace("SlaSH", "/", $category);
                     $query = "SELECT categoryid, catparentlist FROM [|PREFIX|]categories WHERE LOWER(catname)='" . $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($category)) . "' AND catparentid='" . $parentId . "'";
                     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
                     $existingCategory = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
                     if (!$existingCategory['categoryid']) {
                         // Create the category .But no need to create any category while import since all possiple categories are added to the db. blessen
                         $lastCategoryId = -2;
                     } else {
                         $lastCategoryId = $existingCategory['categoryid'];
                     }
                     $parentId = $lastCategoryId;
                 }
                 if ($lastCategoryId) {
                     $categoryCache[$importCategory] = $lastCategoryId;
                     $cats[] = $lastCategoryId;
                 }
             } else {
                 $cats[] = $categoryCache[$importCategory];
             }
         }
     } else {
         $cats = array($this->ImportSession['CategoryId']);
     }
     $cat_condition = false;
     if (isset($this->ImportSession['PreCategory'])) {
         $cat_condition = $cats[0] == -2 || !in_array($cats[0], $this->ImportSession['PreCategory']) ? true : false;
         // checking for  invalid category and selected category
     } else {
         $cat_condition = $cats[0] == -2 ? true : false;
     }
     if ($cat_condition) {
         $this->writetherejected($record['original_record'], 'Un defined Category', $vendorId, $loggedid);
         return;
     }
     // Does the brand already exist?
     $brandId = 0;
     if (isset($record['brandname']) && $record['brandname'] != '') {
         $query = sprintf("select brandid from [|PREFIX|]brands where lower(brandname)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['brandname'])));
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $brandId = $row['brandid'];
         } else {
             $this->writetherejected($record['original_record'], 'Brand Does not exist', $vendorId, $loggedid);
             return;
         }
     }
     //reject if vendor prefix is not present
     $prodvendorprefix = strtolower($record['prodvendorprefix']);
     if ($prodvendorprefix == "") {
         $this->writetherejected($record['original_record'], 'Vendor Prefix is Missing', $vendorId, $loggedid);
         return;
     }
     $prodmake = $record['prodmake'];
     $prodsubmodel = $record['prodsubmodel'];
     $prodmodel = $record['prodmodel'];
     $prodstartyear = $record['prodstartyear'];
     $prodendyear = $record['prodendyear'];
     //$catuniversal = $existingCategory['catuniversal'];
     $query4 = "SELECT catuniversal , catcombine, catparentid, Productname  FROM [|PREFIX|]categories WHERE categoryid = '" . $cats[0] . "' ";
     $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
     $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
     $catuniversal = $eng_row['catuniversal'];
     $catparentid = $eng_row['catparentid'];
     $Productname_elements = explode(",", $eng_row['Productname']);
     if (in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
         $catcombine = $eng_row['catcombine'];
     } else {
         $catcombine = "";
     }
     // no need to store products under root category if any subcategory exist.
     if ($catparentid == 0) {
         //check for subcategories
         $query4 = "SELECT count(catparentid) as subcnt  FROM [|PREFIX|]categories WHERE catparentid = '" . $cats[0] . "' ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         $subcnt = $eng_row['subcnt'];
         if ($subcnt > 0) {
             //if any subcategory exist, Reject it.
             $this->writetherejected($record['original_record'], 'Products cannot store directly to the root category ', $vendorId, $loggedid);
             return;
         }
     }
     //Reject data if invalid Year make Model and submodel except for universal categories.
     if ($catuniversal == 0) {
         // no need Universal Products with non-universal category
         if (strtolower($prodstartyear) == "all" || strtolower($prodendyear) == "all" || strtolower($prodmodel) == "all" || strtolower($prodmake) == "non-spec vehicle") {
             $this->writetherejected($record['original_record'], 'Universal Products with non-universal category', $vendorId, $loggedid);
             return;
         }
         $query2 = "SELECT id FROM [|PREFIX|]product_mmy  WHERE (year  = '" . $prodstartyear . "' or year  = '" . $prodendyear . "' ) and model   = '" . $prodmodel . "' and submodel = '" . $prodsubmodel . "' and make   = '" . $prodmake . "' limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query2);
         if ($GLOBALS['ISC_CLASS_DB']->CountResult($result2) == 0) {
             // 09495245211
             $this->writetherejected($record['original_record'], 'Invalid MMY and Submodel List', $vendorId, $loggedid);
             return;
         } else {
             $row_ymm_id = $GLOBALS["ISC_CLASS_DB"]->Fetch($result2);
             $ymm_id = $row_ymm_id['id'];
         }
     }
     $productId = 0;
     $hasThumb = false;
     $productFiles = array();
     $productImages = array();
     $existing = null;
     $generalize_bedvalue = "";
     $generalize_cabvalue = "";
     // genarating prod name added by blessen
     $subcat = strtolower($record['category2']);
     $cat = strtolower($record['category1']);
     $partnumber = $record['prodcode'];
     $product_series = strtolower($record['product_series']);
     $brand = $record['brandname'];
     $selected = array_values(array_intersect($_SESSION['assocvqpq'][$cats[0]], $_SESSION['qualifiers']));
     //$selected = $_SESSION['assocvqpq'][$cats[0]];
     if (!isset($selected)) {
         $selected = array();
     }
     if (in_array('VQliter', $selected) and $catuniversal == 0 and $record['VQliter'] != "") {
         $query4 = "SELECT liter FROM [|PREFIX|]engine_table WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         $liter = $eng_row['liter'];
     }
     if (in_array('VQenginetype', $selected) and $catuniversal == 0 and $record['VQenginetype'] != "") {
         $query4 = "SELECT engtype FROM [|PREFIX|]engine_table WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         $engtype = $eng_row['engtype'];
     }
     // this is for cabsize traslation
     if (in_array('VQcabsize', $selected) and $record['VQcabsize'] != "") {
         $cabsize_pieces = preg_split("/[;,]/", $record['VQcabsize']);
         $end = end($cabsize_pieces);
         if (empty($end)) {
             array_pop($cabsize_pieces);
         }
         foreach ($cabsize_pieces as $key => $value) {
             $query4 = "SELECT id,generalize_value FROM [|PREFIX|]cabsize_translation WHERE prodstartyear = '" . $prodstartyear . "' and prodendyear = '" . $prodendyear . "'  and prodmake  = '" . $prodmake . "' and prodmodel  = '" . $prodmodel . "' and irregular_value = '" . $value . "'  limit 0,1 ";
             $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
             $cab_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
             $generalize_cabvalue .= $cab_row['generalize_value'] . ";";
         }
         $generalize_cabvalue = trim($generalize_cabvalue, ";");
     }
     // this is for bedsize traslation
     if (in_array('VQbedsize', $selected) and $record['VQbedsize'] != "") {
         $bedsize_pieces = preg_split("/[;,]/", $record['VQbedsize']);
         $end = end($bedsize_pieces);
         if (empty($end)) {
             array_pop($bedsize_pieces);
         }
         foreach ($bedsize_pieces as $key => $value) {
             $query3 = "SELECT id,generalize_value FROM [|PREFIX|]bedsize_translation WHERE irregular_value = '" . $value . "'  limit 0,1 ";
             $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query3);
             $bed_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
             $generalize_bedvalue .= $bed_row['generalize_value'] . ";";
         }
         $generalize_bedvalue = trim($generalize_bedvalue, ";");
         // and checking for repeated values is not done
     }
     if (in_array('VQcabsize', $selected) and $generalize_cabvalue == "" and $catuniversal == 0 and $record['VQcabsize'] != "") {
         $query4 = "SELECT cabsize  FROM [|PREFIX|]cabbed_table  WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         if ($eng_row['cabsize'] != "") {
             $generalize_cabvalue = $eng_row['cabsize'];
         }
     }
     if ($generalize_bedvalue == "" and in_array('VQbedsize', $selected) and $catuniversal == 0 and $record['VQbedsize'] != "") {
         $query4 = "SELECT bedsize  FROM [|PREFIX|]cabbed_table  WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         if ($eng_row['bedsize'] != "") {
             $generalize_bedvalue = $eng_row['bedsize'];
         }
     }
     // $Productname_elements
     // $pnamearray = array('Category Name', 'Sub Category Name', 'Brand Name','Series Name', 'Part Number', 'Product Code','Product color', 'Product Material', 'Product Style');
     //key = 0,1,2,3,4,5,6,7,8
     //0,2,3,5,6,8
     // this is for cat-subcat combined name
     if ($catcombine == "" and in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
         //$sc = str_word_count($subcat, 1);
         $sc = explode(" ", $subcat);
         foreach ($sc as $value) {
             $cat = str_ireplace($value, " ", $cat);
         }
         $c = str_word_count($cat, 1, "1234567890'-_");
         foreach ($c as $value) {
             $subcat = str_ireplace($value . "s", " ", $subcat);
             $subcat = str_ireplace($value . "es", " ", $subcat);
         }
         if (trim($cat) == "s" || trim($cat) == "S") {
             $cat = "";
         }
         $catcombine = $subcat . " " . $cat;
     }
     if (in_array(0, $Productname_elements) and !in_array(1, $Productname_elements)) {
         $catcombine = $cat;
     } else {
         if (!in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
             $catcombine = $subcat;
         }
     }
     if (in_array(3, $Productname_elements) and in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
         $product_series = str_word_count($product_series, 1, "1234567890'-_");
         $subcatcomp = str_word_count($catcombine, 1, "1234567890'-_");
         $product_series = array_diff($product_series, $subcatcomp);
         $product_series = implode(" ", $product_series);
     } else {
         if (!in_array(3, $Productname_elements)) {
             $product_series = "";
         }
     }
     // process 3
     if (isset($record['PQcolor']) and in_array(6, $Productname_elements)) {
         $prodcolor = rtrim(strtolower($record['PQcolor']), ";");
     } else {
         $prodcolor = "";
     }
     if (isset($record['PQmaterial']) and in_array(7, $Productname_elements)) {
         $prodmaterial = rtrim(strtolower($record['PQmaterial']), ";");
     } else {
         $prodmaterial = "";
     }
     if (isset($record['PQstyle']) and in_array(8, $Productname_elements)) {
         $prodstyle = rtrim(strtolower($record['PQstyle']), ";");
     } else {
         $prodstyle = "";
     }
     if (in_array(4, $Productname_elements) and in_array(5, $Productname_elements)) {
         $PartNumberTXT = " Part Number ";
     } else {
         $PartNumberTXT = " ";
     }
     if (!in_array(5, $Productname_elements)) {
         $partnumber = "";
     }
     if (!in_array(2, $Productname_elements)) {
         $brand = "";
     }
     $prodname = $catcombine . " " . $brand . " " . $product_series . $PartNumberTXT . $partnumber . " " . $prodcolor . " " . $prodmaterial . " " . $prodstyle;
     $prodname = str_replace("/", " ", $prodname);
     $prodname = preg_replace('/(\\s+)/', ' ', $prodname);
     $newprodname = trim($prodname);
     $newprodname = ucwords($newprodname);
     array_push($selected, "prodmake", "prodmodel", "prodsubmodel", "prodstartyear", "prodendyear");
     // Is there an existing product with the same name?
     $query = sprintf("SELECT * FROM [|PREFIX|]products WHERE LOWER(prodcode)='%s' and LOWER(prodvendorprefix) = '" . $prodvendorprefix . "'  ", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['prodcode'])));
     $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
     if ($existing = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) {
         $query2 = "SELECT id FROM [|PREFIX|]import_variations  WHERE prodstartyear = '" . $prodstartyear . "' and prodendyear = '" . $prodendyear . "' and prodmodel  = '" . $prodmodel . "' and prodsubmodel  = '" . $prodsubmodel . "' and prodmake  = '" . $prodmake . "' and prodcode  = '" . $record['prodcode'] . "' limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query2);
         if ($GLOBALS['ISC_CLASS_DB']->CountResult($result2) == 0) {
             $sqlinsert2 = "INSERT INTO `isc_import_variations` ( `productid`, `prodcode` , ";
             $values = ") VALUES (" . $existing['productid'] . ", '" . $record['prodcode'] . "' ,";
             for ($i = 0; $i < count($selected); $i++) {
                 $fieldname = $selected[$i];
                 $thevalue = rtrim($record[$fieldname], ";");
                 $sqlinsert2 .= "`" . $fieldname . "` ,";
                 $values .= "'" . $thevalue . "',";
                 // VQenginetype validation checking
                 if ($fieldname == "VQenginetype" and $thevalue != "") {
                     $thevalue = $engtype;
                 }
                 // VQliter validation checking
                 if ($fieldname == "VQliter" and $thevalue != "") {
                     $thevalue = $liter;
                 }
                 // this table is only for to make search fast
                 if ($thevalue != "") {
                     $sql = "INSERT INTO `isc_qualifier_value` (`pid`, `qid`, `q_value` , `row_no`) VALUES ('" . $existing['productid'] . "', '" . $_SESSION['qualifiers_name'][$fieldname] . "', '" . $thevalue . "' ,  '" . $_SESSION['row_no'] . "')";
                     mysql_query($sql);
                 }
                 // only for search fast end
             }
             $_SESSION['row_no']++;
             $sqlinsert2 .= "`bedsize_generalname` , `cabsize_generalname` ";
             $values .= "'" . $generalize_bedvalue . "', '" . $generalize_cabvalue . "'";
             $joinedsql = $sqlinsert2 . $values . " ) ";
             mysql_query($joinedsql);
             //complementary items  ;
             $record['complementaryitems'] = str_replace('”', '"', $record['complementaryitems']);
             $record['complementaryitems'] = str_replace('“', '"', $record['complementaryitems']);
             $comData = array("complementaryitems" => $record['complementaryitems'], "variationid" => mysql_insert_id(), "productid" => $existing['productid']);
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("application_data", $comData);
         } else {
             if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
                 $existing_iv = $GLOBALS["ISC_CLASS_DB"]->Fetch($result2);
                 $ivid = $existing_iv['id'];
                 $sqlupdate = "Update  `isc_import_variations` set ";
                 for ($i = 0; $i < count($selected); $i++) {
                     $thevalue = $record[$selected[$i]];
                     if ($thevalue != "") {
                         $fieldname = $selected[$i];
                         if ($thevalue == "<BLANK>") {
                             $thevalue = "";
                         }
                         $sqlup = "update `isc_qualifier_value` set  `q_value` = " . $thevalue . "  where `pid` = " . $productId . " and `qid` = '" . $_SESSION['qualifiers_name'][$fieldname] . "' and `row_no` = " . $ivid;
                         mysql_query($sqlup);
                         $sqlupdate .= "`" . $fieldname . "` = '" . $thevalue . "',";
                     }
                 }
                 $sqlupdate .= " productid = " . $existing['productid'] . " where id = " . $ivid;
                 mysql_query($sqlupdate);
                 //complementary items  ;
                 $record['complementaryitems'] = str_replace('”', '"', $record['complementaryitems']);
                 $record['complementaryitems'] = str_replace('“', '"', $record['complementaryitems']);
                 $comData = array("complementaryitems" => $record['complementaryitems']);
                 $GLOBALS['ISC_CLASS_DB']->UpdateQuery("application_data", $comData, "variationid = '{$ivid}' ");
             }
         }
         // Overriding existing products, set the product id
         if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
             $productId = $existing['productid'];
             //$cats = null;  // blessen
             //$cats = "";   let the category change in re-import blessen 22-10 as per client req.
             if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() && $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() != $existing['prodvendorid']) {
                 $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportProductInvalidVendor');
                 return;
             }
             $this->ImportSession['Results']['Updates'][] = $record['prodcode'];
         } else {
             //$this->ImportSession['Results']['Duplicates'][] = $record['prodcode'];
             ++$this->ImportSession['Results']['Imported'];
             return;
         }
     }
     // Do we have a product file? We need to deal with it now damn it!
     if (isset($record['prodfile']) && $record['prodfile'] != '') {
         // Is this a remote file?
         $downloadDirectory = ISC_BASE_PATH . "/" . GetConfig('DownloadDirectory');
         if (isc_substr(isc_strtolower($record['prodfile']), 0, 7) == "http://") {
             // Need to fetch the remote file
             $file = PostToRemoteFileAndGetResponse($record['prodfile']);
             if ($file) {
                 // Place it in our downloads directory
                 $randomDir = strtolower(chr(rand(65, 90)));
                 if (!is_dir($downloadDirectory . $randomDir)) {
                     if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                         $randomDir = '';
                     }
                 }
                 // Generate a random filename
                 $fileName = $randomDir . "/" . GenRandFileName(basename($record['prodfile']));
                 if (!@file_put_contents($downloadDirectory . "/" . $fileName, $file)) {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileUnableToMove');
                 } else {
                     $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['prodfile']), "downdescription" => "");
                 }
             } else {
                 $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileDoesntExist');
             }
         } else {
             // This file exists, can be imported
             if (file_exists($downloadDirectory . "/import/" . $record['prodfile'])) {
                 // Move it to our images directory
                 $randomDir = strtolower(chr(rand(65, 90)));
                 if (!is_dir("../" . $downloadDirectory . "/" . $randomDir)) {
                     if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                         $randomDir = '';
                     }
                 }
                 // Generate a random filename
                 $fileName = $randomDir . "/" . GenRandFileName($record['prodfile']);
                 if (!@copy($downloadDirectory . "/import/" . $record['prodfile'], $downloadDirectory . "/" . $fileName)) {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileUnableToMove');
                 } else {
                     $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['prodfile']), "downdescription" => "");
                 }
             } else {
                 $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileDoesntExist');
             }
         }
     }
     // Do we have an image? We need to deal with it before we do anything else
     $productImages = array();
     if (isset($record['prodimagefile']) && $record['prodimagefile'] != '') {
         // Is this a remote file?
         $imageDirectory = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory');
         if (isc_substr(isc_strtolower($record['prodimagefile']), 0, 7) == "http://") {
             // Need to fetch the remote file
             $image_pieces = preg_split("/[;,]/", $record['prodimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 $image = PostToRemoteFileAndGetResponse($value);
                 if ($image) {
                     // Place it in our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($imageDirectory . "/" . $randomDir)) {
                         if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                     if (!@file_put_contents($imageDirectory . "/" . $fileName, $image)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         if (!is_array(@getimagesize($imageDirectory . "/" . $fileName))) {
                             @unlink($imageDirectory . "/" . $fileName);
                             $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageInvalidFile');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                             $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             if ($hasThumb == false) {
                                 if ($key == 0) {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                     if ($thumbName) {
                                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                                 $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                                 if ($mediumName) {
                                     $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                 } else {
                                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                 }
                             }
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         } else {
             // This file exists, can be imported
             $image_pieces = preg_split("/[;,]/", $record['prodimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 if (file_exists($imageDirectory . "/import/" . $value)) {
                     // Move it to our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($imageDirectory . "/" . $randomDir)) {
                         if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $baseFileName = basename($value);
                     if ($baseFileName != $value) {
                         $localDirectory = dirname($value) . "/";
                     } else {
                         $localDirectory = '';
                     }
                     $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                     if (!@copy($imageDirectory . "/import/" . $value, $imageDirectory . "/" . $fileName)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                         // Does a thumbnail file exist?
                         $thumbFile = "thumb_" . $baseFileName;
                         if ($key == 0) {
                             if (file_exists($imageDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                 $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                 if (@copy($imageDirectory . "/import/" . $localDirectory . $thumbFile, $imageDirectory . "/" . $thumbName)) {
                                     $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                 if ($thumbName) {
                                     $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                                 // Still need to generate "tiny" thumbnail
                                 $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                 if ($tinyName) {
                                     $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                 }
                             }
                         }
                         $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                         if ($mediumName) {
                             $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         }
     }
     // Do we have an install image? We need to deal with it after product images added by blessen
     $productInstallImages = array();
     if (isset($record['prodinstallimagefile']) && $record['prodinstallimagefile'] != '') {
         // Is this a remote file?
         $InstallDirectory = ISC_BASE_PATH . "/install_images";
         if (isc_substr(isc_strtolower($record['prodinstallimagefile']), 0, 7) == "http://") {
             // Need to fetch the remote file
             $image_pieces = preg_split("/[;,]/", $record['prodinstallimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 $image = PostToRemoteFileAndGetResponse($value);
                 if ($image) {
                     // Place it in our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                         if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                     if (!@file_put_contents($InstallDirectory . "/" . $fileName, $image)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         if (!is_array(@getimagesize($InstallDirectory . "/" . $fileName))) {
                             @unlink($InstallDirectory . "/" . $fileName);
                             $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageInvalidFile');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                             $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             if ($hasThumb == false) {
                                 if ($key == 0) {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                     if ($thumbName) {
                                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                                 $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                                 if ($mediumName) {
                                     $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                 } else {
                                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                 }
                             }
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         } else {
             // This file exists, can be imported
             $image_pieces = preg_split("/[;,]/", $record['prodinstallimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 if (file_exists($InstallDirectory . "/import/" . $value)) {
                     // Move it to our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                         if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $baseFileName = basename($value);
                     if ($baseFileName != $value) {
                         $localDirectory = dirname($value) . "/";
                     } else {
                         $localDirectory = '';
                     }
                     $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                     if (!@copy($InstallDirectory . "/import/" . $value, $InstallDirectory . "/" . $fileName)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                         // Does a thumbnail file exist?
                         $thumbFile = "thumb_" . $baseFileName;
                         if ($key == 0) {
                             if (file_exists($InstallDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                 $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                 if (@copy($InstallDirectory . "/import/" . $localDirectory . $thumbFile, $InstallDirectory . "/" . $thumbName)) {
                                     $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                 if ($thumbName) {
                                     $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                                 // Still need to generate "tiny" thumbnail
                                 $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                 if ($tinyName) {
                                     $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                 }
                             }
                         }
                         $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                         if ($mediumName) {
                             $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         }
     }
     // If this is an update then we have to merge in the existing information that is NOT in the CSV file
     if (is_array($existing)) {
         $record = $record + $existing;
     }
     // Apply any default data
     $defaults = array('prodistaxable' => 1, 'prodprice' => 0, 'prodcostprice' => 0, 'prodretailprice' => 0, 'prodsaleprice' => 0, 'prodsearchkeywords' => '', 'prodsortorder' => 0, 'prodvisible' => 1, 'prodfeatured' => 0, 'prodrelatedproducts' => '', 'prodoptionsrequired' => 0, 'prodfreeshipping' => 0, 'prodlayoutfile' => '', 'prodtags' => '', 'prodmyobasset' => '', 'prodmyobincome' => '', 'prodmyobexpense' => '', 'prodpeachtreegl' => '', 'price_log' => '', 'SKU_last_update_time' => '', 'price_update_time' => '', 'unilateralprice' => '', 'testdata' => 'No', 'prodalternates' => '', 'skubarcode' => '');
     $record += $defaults;
     // Does the series already exist? //blessen
     $seriesId = 0;
     if (isset($record['product_series']) && $record['product_series'] != '') {
         $query = sprintf("select seriesid from [|PREFIX|]brand_series where lower(seriesname)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['product_series'])));
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $seriesId = $row['seriesid'];
         } else {
             $newSeries = array("brandid" => $brandId, "seriesname" => $record['product_series']);
             $seriesId = $GLOBALS['ISC_CLASS_DB']->InsertQuery("brand_series", $newSeries);
             $seriesId = $GLOBALS['ISC_CLASS_DB']->LastId();
         }
     }
     if (!isset($record['prodinvtrack'])) {
         $record['prodinvtrack'] = 0;
     }
     if (isset($record['prodfile']) && $record['prodfile'] != '') {
         $productType = 2;
     } else {
         if (isset($existing['prodtype']) && isId($existing['prodtype'])) {
             $productType = (int) $existing['prodtype'];
         } else {
             $productType = 1;
         }
     }
     if (isset($record['prodistaxable'])) {
         $record['prodistaxable'] = $this->StringToYesNoInt($record['prodistaxable']);
     }
     $record['proddesc'] = str_replace("®", "&reg;", $record['proddesc']);
     // This is our product
     $productData = array("prodname" => $newprodname, "prodcode" => @$record['prodcode'], "proddesc" => @$record['proddesc'], "prodsearchkeywords" => @$record['prodsearchkeywords'], "prodtype" => $productType, "prodprice" => DefaultPriceFormat($record['prodprice']), "prodcostprice" => DefaultPriceFormat($record['prodcostprice']), "prodretailprice" => DefaultPriceFormat($record['prodretailprice']), "prodsaleprice" => DefaultPriceFormat($record['prodsaleprice']), "prodavailability" => @$record['prodavailability'], "prodsortorder" => $record['prodsortorder'], "prodvisible" => $record['prodvisible'], "prodfeatured" => $record['prodfeatured'], "prodrelatedproducts" => $record['prodrelatedproducts'], "prodinvtrack" => (int) @$record['prodinvtrack'], "prodcurrentinv" => (int) @$record['prodcurrentinv'], "prodlowinv" => (int) @$record['prodlowinv'], "prodoptionsrequired" => $record['prodoptionsrequired'], "prodwarranty" => @$record['prodwarranty'], "prodheight" => (double) @$record['prodheight'], "prodweight" => (double) @$record['prodweight'], "prodwidth" => (double) @$record['prodwidth'], "proddepth" => (double) @$record['proddepth'], "prodfreeshipping" => $record['prodfreeshipping'], "prodfixedshippingcost" => DefaultPriceFormat(@$record['prodfixedshippingcost']), "prodbrandid" => (int) $brandId, "prodcats" => $cats, "prodpagetitle" => @$record['prodpagetitle'], "prodmetakeywords" => @$record['prodmetakeywords'], "prodmetadesc" => @$record['prodmetadesc'], "prodlayoutfile" => $record['prodlayoutfile'], "prodistaxable" => $record['prodistaxable'], 'prodvendorid' => $vendorId, 'prodtags' => $record['prodtags'], "prodvendorprefix" => $record['prodvendorprefix'], "proddescfeature" => $record['proddescfeature'], "prodmfg" => $record['prodmfg'], "jobberprice" => $record['jobberprice'], "mapprice" => $record['mapprice'], "alternativecategory" => $record['alternativecategory'], "complementaryupcharge" => $record['complementaryupcharge'], "ourcost" => $record['ourcost'], "package_length" => $record['package_length'], "package_height" => $record['package_height'], "package_weight" => $record['package_weight'], "package_width" => $record['package_width'], "brandseriesid" => $seriesId, "future_retail_price" => $record['future_retail_price'], "future_jobber_price" => $record['future_jobber_price'], "prod_instruction" => $record['prod_instruction'], "prod_article" => $record['prod_article'], "skubarcode" => $record['skubarcode'], "install_time" => $record['install_time']);
     /**
      * The variation is part of the product record, so it will have to be attached to the record if this is an
      * update AND the existing product already has a variation
      */
     if (is_array($existing) && isId($existing['prodvariationid'])) {
         $productData['prodvariationid'] = $existing['prodvariationid'];
     }
     if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
         $productData['prodvendorid'] = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId();
     }
     $empty = array();
     // Save it
     $err = '';
     if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
         foreach ($productData as $key => $value) {
             if ($value == "" and isset($existing[$key])) {
                 $productData[$key] = $existing[$key];
             }
             if ($value == "<BLANK>") {
                 $productData[$key] = "";
             }
         }
         $pricelog = $existing['price_log'];
         $pricelogtime = $existing['price_update_time'];
         $splitprice = split(',', $pricelog);
         $oldprice = end($splitprice);
         if ($oldprice != $productData['prodprice']) {
             $productData['price_log'] = $pricelog . "," . $productData['prodprice'];
             $productData['price_update_time'] = date('Y-m-d H:i:s');
         } else {
             $productData['price_log'] = $pricelog;
             $productData['price_update_time'] = $pricelogtime;
         }
         //fixed values in re-import
         $productData['SKU_last_update_time'] = date('Y-m-d H:i:s');
         if ($existing['prodcode'] != "") {
             $productData['prodcode'] = $existing['prodcode'];
         }
         if ($existing['prodvendorid'] != "") {
             $productData['prodvendorid'] = $existing['prodvendorid'];
         }
         if ($existing['prodbrandid'] != "") {
             $productData['prodbrandid'] = $existing['prodbrandid'];
         }
     }
     // temp declaraton to avoid entering in to system log.
     $productData += $defaults;
     foreach ($productData as $key => $value) {
         if (!isset($productData[$key])) {
             $productData[$key] = "";
         }
     }
     if ($this->ImportSession['Importastest'] == 1) {
         $productData['testdata'] = "Yes";
         $productData['prodvisible'] = 0;
     }
     $added_or_not = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_CommitImportProduct($productId, $productData, $empty, $empty, $empty, $empty, $err, $empty, true);
     if ($added_or_not == 1) {
         // there is a problem , if multiple category present
         if (isset($GLOBALS['NewProductId']) and $GLOBALS['NewProductId'] != "") {
             $sqlinsert2 = "INSERT INTO `isc_import_variations` ( `productid`, `prodcode` , ";
             $values = ") VALUES (" . $GLOBALS['NewProductId'] . ", '" . $record['prodcode'] . "' ,";
             for ($i = 0; $i < count($selected); $i++) {
                 $fieldname = $selected[$i];
                 $thevalue = rtrim($record[$fieldname], ";");
                 $sqlinsert2 .= "`" . $fieldname . "` ,";
                 $values .= "'" . $thevalue . "',";
                 // VQenginetype validation checking
                 if ($fieldname == "VQenginetype" and $thevalue != "") {
                     $thevalue = $engtype;
                 }
                 // VQliter validation checking
                 if ($fieldname == "VQliter" and $thevalue != "") {
                     $thevalue = $liter;
                 }
                 // only for make search fast
                 if ($thevalue != "") {
                     $sql = "INSERT INTO `isc_qualifier_value` (`pid`, `qid`, `q_value` , `row_no`) VALUES ('" . $GLOBALS['NewProductId'] . "', '" . $_SESSION['qualifiers_name'][$fieldname] . "', '" . $thevalue . "' , '" . $_SESSION['row_no'] . "')";
                     mysql_query($sql);
                 }
                 // only for made search fast end
             }
             $_SESSION['row_no']++;
             $sqlinsert2 .= "`bedsize_generalname` , `cabsize_generalname` ";
             $values .= "'" . $generalize_bedvalue . "', '" . $generalize_cabvalue . "'";
             $joinedsql = $sqlinsert2 . $values . " ) ";
             mysql_query($joinedsql);
             //complementary items  ;
             $record['complementaryitems'] = str_replace('”', '"', $record['complementaryitems']);
             $record['complementaryitems'] = str_replace('“', '"', $record['complementaryitems']);
             $comData = array("complementaryitems" => $record['complementaryitems'], "variationid" => mysql_insert_id(), "productid" => $GLOBALS['NewProductId']);
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("application_data", $comData);
         }
     }
     if ($productId == 0) {
         $productId = $GLOBALS['NewProductId'];
     }
     // Are there any images?
     if (count($productImages) > 0) {
         $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_images', "WHERE imageprodid='" . $productId . "'");
         foreach ($productImages as $image) {
             $image['imageprodid'] = $productId;
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_images", $image);
         }
     }
     // Are there any Install images? blessen
     if (count($productInstallImages) > 0) {
         $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_images', "WHERE imageprodid='" . $productId . "'");
         foreach ($productInstallImages as $image) {
             $image['imageprodid'] = $productId;
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_images", $image);
         }
     }
     // Are there any Install videos ? blessen
     if ($record['prodinstallvideo'] != "") {
         $productInstallVideos = array();
         $video_pieces = preg_split("/[;,]/", $record['prodinstallvideo']);
         $end = end($video_pieces);
         if (empty($end)) {
             array_pop($video_pieces);
         }
         foreach ($video_pieces as $key => $values) {
             $productInstallVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
         }
         if (count($productInstallVideos) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_videos', "WHERE videoprodid='" . $productId . "'");
             foreach ($productInstallVideos as $video) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_videos", $video);
             }
         }
     }
     // Are there any product videos ? blessen audio_clip
     if ($record['prodvideo'] != "") {
         $productVideos = array();
         $video_pieces = preg_split("/[;,]/", $record['prodvideo']);
         $end = end($video_pieces);
         if (empty($end)) {
             array_pop($video_pieces);
         }
         foreach ($video_pieces as $key => $values) {
             $productVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
         }
         if (count($productVideos) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_videos', "WHERE videoprodid='" . $productId . "'");
             foreach ($productVideos as $video) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_videos", $video);
             }
         }
     }
     // Are there any product audio_clip ? blessen
     if ($record['audio_clip'] != "") {
         $product_audio_clip = array();
         $audio_pieces = preg_split("/[;,]/", $record['audio_clip']);
         $end = end($audio_pieces);
         if (empty($end)) {
             array_pop($audio_pieces);
         }
         foreach ($audio_pieces as $key => $values) {
             $product_audio_clip[] = array("audiofile" => $values, "audiotype" => 1, "audioprodid" => $productId);
         }
         if (count($product_audio_clip) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('audio_clips', "WHERE audioprodid='" . $productId . "'");
             foreach ($product_audio_clip as $audio) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("audio_clips", $audio);
             }
         }
     }
     // Are there any product article file ? blessen
     if ($record['article_file'] != "") {
         $product_article = array();
         $article_pieces = preg_split("/[;,]/", $record['article_file']);
         $end = end($article_pieces);
         if (empty($end)) {
             array_pop($article_pieces);
         }
         foreach ($article_pieces as $key => $values) {
             $product_article[] = array("articlefile" => $values, "articletype" => 1, "articleprodid" => $productId);
         }
         if (count($product_article) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('article_files', "WHERE articleprodid='" . $productId . "'");
             foreach ($product_article as $article) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("article_files", $article);
             }
         }
     }
     // Are there any product instruction_file  ? blessen
     if ($record['instruction_file'] != "") {
         $product_instruction = array();
         $instruction_pieces = preg_split("/[;,]/", $record['instruction_file']);
         $end = end($instruction_pieces);
         if (empty($end)) {
             array_pop($instruction_pieces);
         }
         foreach ($instruction_pieces as $key => $values) {
             $product_instruction[] = array("instructionfile" => $values, "instructiontype" => 1, "instructionprodid" => $productId);
         }
         if (count($product_instruction) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('instruction_files', "WHERE instructionprodid='" . $productId . "'");
             foreach ($product_instruction as $instruction) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("instruction_files", $instruction);
             }
         }
     }
     // Are there any product files?
     if (count($productFiles) > 0) {
         foreach ($productFiles as $file) {
             $file['productid'] = $productId;
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_downloads", $file);
         }
     }
     ++$this->ImportSession['Results']['Imported'];
     ++$this->ImportSession['Results']['SuccessCount'];
 }
 /**
  * Commit a gift wrapping type to the database (either create a new one or update an existing one)
  *
  * @param array An array of data about the gift wrapping type.
  * @param int If updating an existing wrap, the ID.
  * @return boolean True if successful, false if not.
  */
 private function CommitWrap($data, $wrapId = 0)
 {
     if (!isset($data['wrapvisible'])) {
         $data['wrapvisible'] = 0;
     }
     if (!isset($data['wrapallowcomments'])) {
         $data['wrapallowcomments'] = '';
     }
     if (isset($_FILES['wrapimage']) && is_array($_FILES['wrapimage']) && $_FILES['wrapimage']['name'] != '') {
         // Clean up the incoming file name a bit
         $_FILES['wrapimage']['name'] = preg_replace("#[^\\w.]#i", "_", $_FILES['wrapimage']['name']);
         $_FILES['wrapimage']['name'] = preg_replace("#_{1,}#i", "_", $_FILES['wrapimage']['name']);
         $randomFileName = GenRandFileName($_FILES['wrapimage']['name']);
         $imageLocation = 'wrap_images/' . $randomFileName;
         $dest = ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/' . $imageLocation;
         if (move_uploaded_file($_FILES['wrapimage']['tmp_name'], $dest)) {
             isc_chmod($dest, ISC_WRITEABLE_FILE_PERM);
             $data['wrappreview'] = $imageLocation;
         }
     }
     $wrapData = array('wrapname' => $data['wrapname'], 'wrapprice' => DefaultPriceFormat($data['wrapprice']), 'wrapvisible' => (int) $data['wrapvisible'], 'wrapallowcomments' => (int) $data['wrapallowcomments']);
     if (isset($data['wrappreview'])) {
         $wrapData['wrappreview'] = $data['wrappreview'];
     }
     if ($wrapId == 0) {
         $wrapId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('gift_wrapping', $wrapData);
     } else {
         $GLOBALS['ISC_CLASS_DB']->UpdateQuery('gift_wrapping', $wrapData, "wrapid='" . (int) $wrapId . "'");
     }
     $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateGiftWrapping();
     // Couldn't save? return an error message
     if ($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()) {
         return false;
     }
     return true;
 }
	/**
	 * Validate the passed input for a gift wrapping type for errors.
	 *
	 * @param array An array of data about the gift wrapping type.
	 * @param string An error message (if any) from validation errors (on return false - by reference)
	 * @return boolean True if successful, false if not.
	 */
	private function ValidateWrap($data, &$error)
	{
		$requiredFields = array(
			'wrapname' => GetLang('EnterGiftWrapName'),
			'wrapprice' => GetLang('EnterGiftWrapPrice')
		);
		foreach($requiredFields as $field => $message) {
			if(!isset($data[$field]) || trim($data[$field]) == '') {
				$error = $message;
				return false;
			}
		}

		// Does a wrapping type exist with the same name?
		$wrapIdQuery = '';
		if(isset($data['wrapId']) && $data['wrapId'] > 0) {
			$wrapIdQuery = " AND wrapid!='".(int)$data['wrapId']."'";
		}

		// Check that a duplicate wrapping type doesn't exist with this name
		$query = "
			SELECT wrapid
			FROM [|PREFIX|]gift_wrapping
			WHERE wrapname='".$GLOBALS['ISC_CLASS_DB']->Quote($data['wrapname'])."'".$wrapIdQuery;

		// if an image was uploaded, validate that
		try {
			$files = ISC_UPLOADHANDLER::getUploadedFiles();
			foreach ($files as /** @var UploadHandlerFile */$file) {
				if ($file->fieldName == 'wrapimage') {
					$dest = ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/wrap_images/' . GenRandFileName($file->name);
					$file->moveAs($dest);
					$image = @getimagesize($dest);
					if ($image === false) {
						unlink($dest);
						$error = GetLang("WrapImageInvalid");
						return false;
					}
					isc_chmod($dest, ISC_WRITEABLE_FILE_PERM);
					break;
				}
			}
		} catch (UploadHandlerException $exception) {
			$error = $exception->getMessage();
			return false;
		}

		if($GLOBALS['ISC_CLASS_DB']->FetchOne($query)) {
			$error = GetLang('DuplicateGiftWrapName');
			return false;
		}

		// Otherwise it's valid
		return true;
	}
 protected function ProcessImg()
 {
     $sql = "select * from [|PREFIX|]import_products where flag=0 order by tempid asc";
     $query = $GLOBALS['ISC_CLASS_DB']->Query($sql);
     while ($record = $GLOBALS['ISC_CLASS_DB']->Fetch($query)) {
         // Do we have a product file? We need to deal with it now damn it!
         if (isset($record['product_file']) && $record['product_file'] != '') {
             // Is this a remote file?
             $downloadDirectory = ISC_BASE_PATH . "/" . GetConfig('DownloadDirectory');
             if (isc_substr(isc_strtolower($record['product_file']), 0, 7) == "http://") {
                 // Need to fetch the remote file
                 $file = PostToRemoteFileAndGetResponse($record['product_file']);
                 if ($file) {
                     // Place it in our downloads directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($downloadDirectory . $randomDir)) {
                         if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName(basename($record['product_file']));
                     if (!@file_put_contents($downloadDirectory . "/" . $fileName, $file)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileUnableToMove');
                     } else {
                         $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['product_file']), "downdescription" => "");
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileDoesntExist');
                 }
             } else {
                 // This file exists, can be imported
                 if (file_exists($downloadDirectory . "/import/" . $record['product_file'])) {
                     // Move it to our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir("../" . $downloadDirectory . "/" . $randomDir)) {
                         if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName($record['product_file']);
                     if (!@copy($downloadDirectory . "/import/" . $record['product_file'], $downloadDirectory . "/" . $fileName)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileUnableToMove');
                     } else {
                         $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['product_file']), "downdescription" => "");
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileDoesntExist');
                 }
             }
         }
         // Do we have an image? We need to deal with it before we do anything else
         $productImages = array();
         if (isset($record['product_images']) && $record['product_images'] != '') {
             // Is this a remote file?
             $imageDirectory = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory');
             if (isc_substr(isc_strtolower($record['product_images']), 0, 7) == "http://") {
                 // Need to fetch the remote file
                 $image_pieces = preg_split("/[;,]/", $record['product_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     $image = PostToRemoteFileAndGetResponse($value);
                     if ($image) {
                         // Place it in our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($imageDirectory . "/" . $randomDir)) {
                             if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                         if (!@file_put_contents($imageDirectory . "/" . $fileName, $image)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             if (!is_array(@getimagesize($imageDirectory . "/" . $fileName))) {
                                 @unlink($imageDirectory . "/" . $fileName);
                                 $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageInvalidFile');
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                                 $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                                 if ($hasThumb == false) {
                                     if ($key == 0) {
                                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                         if ($thumbName) {
                                             $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                         $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                         if ($tinyName) {
                                             $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                     }
                                     $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                                     if ($mediumName) {
                                         $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             } else {
                 // This file exists, can be imported
                 $image_pieces = preg_split("/[;,]/", $record['product_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     if (file_exists($imageDirectory . "/import/" . $value)) {
                         // Move it to our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($imageDirectory . "/" . $randomDir)) {
                             if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $baseFileName = basename($value);
                         if ($baseFileName != $value) {
                             $localDirectory = dirname($value) . "/";
                         } else {
                             $localDirectory = '';
                         }
                         $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                         if (!@copy($imageDirectory . "/import/" . $value, $imageDirectory . "/" . $fileName)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                             $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             // Does a thumbnail file exist?
                             $thumbFile = "thumb_" . $baseFileName;
                             if ($key == 0) {
                                 if (file_exists($imageDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                     $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                     if (@copy($imageDirectory . "/import/" . $localDirectory . $thumbFile, $imageDirectory . "/" . $thumbName)) {
                                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                 } else {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                     if ($thumbName) {
                                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                     // Still need to generate "tiny" thumbnail
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     }
                                 }
                             }
                             $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                             if ($mediumName) {
                                 $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             }
         }
         // Do we have an install image? We need to deal with it after product images added by blessen
         $productInstallImages = array();
         if (isset($record['install_images']) && $record['install_images'] != '') {
             // Is this a remote file?
             $InstallDirectory = ISC_BASE_PATH . "/install_images";
             if (isc_substr(isc_strtolower($record['install_images']), 0, 7) == "http://") {
                 // Need to fetch the remote file
                 $image_pieces = preg_split("/[;,]/", $record['install_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     $image = PostToRemoteFileAndGetResponse($value);
                     if ($image) {
                         // Place it in our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                             if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                         if (!@file_put_contents($InstallDirectory . "/" . $fileName, $image)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             if (!is_array(@getimagesize($InstallDirectory . "/" . $fileName))) {
                                 @unlink($InstallDirectory . "/" . $fileName);
                                 $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageInvalidFile');
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                                 $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                                 if ($hasThumb == false) {
                                     if ($key == 0) {
                                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                         if ($thumbName) {
                                             $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                         $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                         if ($tinyName) {
                                             $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                     }
                                     $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                                     if ($mediumName) {
                                         $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             } else {
                 // This file exists, can be imported
                 $image_pieces = preg_split("/[;,]/", $record['install_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     if (file_exists($InstallDirectory . "/import/" . $value)) {
                         // Move it to our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                             if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $baseFileName = basename($value);
                         if ($baseFileName != $value) {
                             $localDirectory = dirname($value) . "/";
                         } else {
                             $localDirectory = '';
                         }
                         $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                         if (!@copy($InstallDirectory . "/import/" . $value, $InstallDirectory . "/" . $fileName)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                             $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             // Does a thumbnail file exist?
                             $thumbFile = "thumb_" . $baseFileName;
                             if ($key == 0) {
                                 if (file_exists($InstallDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                     $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                     if (@copy($InstallDirectory . "/import/" . $localDirectory . $thumbFile, $InstallDirectory . "/" . $thumbName)) {
                                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                 } else {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                     if ($thumbName) {
                                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                     // Still need to generate "tiny" thumbnail
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     }
                                 }
                             }
                             $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                             if ($mediumName) {
                                 $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             }
         }
         //fetch the new insert product id.
         $query = "SELECT productid,prodcode,prodvendorprefix FROM [|PREFIX|]products_statistics WHERE prodcode='" . $GLOBALS['ISC_CLASS_DB']->Quote($record['partnumber']) . "' and prodvendorprefix = '" . $record['vendorprefix'] . "'";
         $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
         while ($rs = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $productId = $rs['productid'];
         }
         if (empty($productId) || $productId == "") {
             $productid = 0;
         }
         // Are there any images?
         if (count($productImages) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_images', "WHERE imageprodid='" . $productId . "'");
             foreach ($productImages as $image) {
                 $image['imageprodid'] = $productId;
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_images", $image);
             }
         }
         // Are there any Install images? blessen
         if (count($productInstallImages) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_images', "WHERE imageprodid='" . $productId . "'");
             foreach ($productInstallImages as $image) {
                 $image['imageprodid'] = $productId;
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_images", $image);
             }
         }
         // Are there any Install videos ? blessen
         if ($record['install_video'] != "") {
             $productInstallVideos = array();
             $video_pieces = preg_split("/[;,]/", $record['install_video']);
             $end = end($video_pieces);
             if (empty($end)) {
                 array_pop($video_pieces);
             }
             foreach ($video_pieces as $key => $values) {
                 $productInstallVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
             }
             if (count($productInstallVideos) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_videos', "WHERE videoprodid='" . $productId . "'");
                 foreach ($productInstallVideos as $video) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_videos", $video);
                 }
             }
         }
         // Are there any product videos ? blessen audio_clip
         if ($record['product_video'] != "") {
             $productVideos = array();
             $video_pieces = preg_split("/[;,]/", $record['product_video']);
             $end = end($video_pieces);
             if (empty($end)) {
                 array_pop($video_pieces);
             }
             foreach ($video_pieces as $key => $values) {
                 $productVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
             }
             if (count($productVideos) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_videos', "WHERE videoprodid='" . $productId . "'");
                 foreach ($productVideos as $video) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_videos", $video);
                 }
             }
         }
         // Are there any product audio_clip ? blessen
         if ($record['audio_clip'] != "") {
             $product_audio_clip = array();
             $audio_pieces = preg_split("/[;,]/", $record['audio_clip']);
             $end = end($audio_pieces);
             if (empty($end)) {
                 array_pop($audio_pieces);
             }
             foreach ($audio_pieces as $key => $values) {
                 $product_audio_clip[] = array("audiofile" => $values, "audiotype" => 1, "audioprodid" => $productId);
             }
             if (count($product_audio_clip) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('audio_clips', "WHERE audioprodid='" . $productId . "'");
                 foreach ($product_audio_clip as $audio) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("audio_clips", $audio);
                 }
             }
         }
         // Are there any product article file ? blessen
         if ($recordval[$head['article_file']] != "") {
             $product_article = array();
             $article_pieces = preg_split("/[;,]/", $recordval[$head['article_file']]);
             $end = end($article_pieces);
             if (empty($end)) {
                 array_pop($article_pieces);
             }
             foreach ($article_pieces as $key => $values) {
                 $product_article[] = array("articlefile" => $values, "articletype" => 1, "articleprodid" => $productId);
             }
             if (count($product_article) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('article_files', "WHERE articleprodid='" . $productId . "'");
                 foreach ($product_article as $article) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("article_files", $article);
                 }
             }
         }
         // Are there any product instruction_file  ? blessen
         if ($recordval[$head['instruction_file']] != "") {
             $product_instruction = array();
             $instruction_pieces = preg_split("/[;,]/", $recordval[$head['instruction_file']]);
             $end = end($instruction_pieces);
             if (empty($end)) {
                 array_pop($instruction_pieces);
             }
             foreach ($instruction_pieces as $key => $values) {
                 $product_instruction[] = array("instructionfile" => $values, "instructiontype" => 1, "instructionprodid" => $productId);
             }
             if (count($product_instruction) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('instruction_files', "WHERE instructionprodid='" . $productId . "'");
                 foreach ($product_instruction as $instruction) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("instruction_files", $instruction);
                 }
             }
         }
         // Are there any product files?
         if (count($productFiles) > 0) {
             foreach ($productFiles as $file) {
                 $file['productid'] = $productId;
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_downloads", $file);
             }
         }
         //when finish image,prodfile,etc. processed,then update the import_products flag=1;
         $updatesql = "update [|PREFIX|]import_products set flag=1 where tempid=" . $record['tempid'];
         $GLOBALS['ISC_CLASS_DB']->Query($updatesql);
     }
     //this record process over!
 }
 function build_series_path($prefix, $FileName, $Append = "")
 {
     require_once LOCAL_LIB . 'general.php';
     $FileName = $prefix . '__' . $FileName;
     return GenRandFileName($FileName, $Append);
 }
Exemple #9
0
 public function _StoreCSVfile($FileName)
 {
     $dir = "ymmfiles";
     $MsgStatus = "";
     if (is_array($_FILES[$FileName]) && $_FILES[$FileName]['name'] != "") {
         if (isc_strtolower(isc_substr($_FILES[$FileName]['name'], -3)) != "csv") {
             echo $GLOBALS['Message'] = MessageBox("Please upload a csv file as YMM data", $MsgStatus);
             return "";
         }
         if (!is_dir(sprintf("../%s", $dir))) {
             @mkdir("../" . $dir, 0777);
         }
         // Clean up the incoming file name a bit
         $_FILES[$FileName]['name'] = preg_replace("#[^\\w.]#i", "_", $_FILES[$FileName]['name']);
         $_FILES[$FileName]['name'] = preg_replace("#_{1,}#i", "_", $_FILES[$FileName]['name']);
         $randomFileName = GenRandFileName($_FILES[$FileName]['name']);
         $dest = realpath(ISC_BASE_PATH . "/" . $dir);
         $dest .= "/" . $randomFileName;
         if (move_uploaded_file($_FILES[$FileName]["tmp_name"], $dest)) {
             isc_chmod($dest, ISC_WRITEABLE_FILE_PERM);
             // The file was moved successfully
             return $randomFileName;
         } else {
             // Couldn't move the file, maybe the directory isn't writable?
             return "";
         }
     } else {
         // The file doesn't exist in the $_FILES array
         return "";
     }
 }
 /**
  * @desc : Used for Magnaflow videos and other files also
  * @url : File URL
  * @FileType : table name of the file
  */
 private function DownloadMagnaflow($url, $FileType = "product_videos")
 {
     @clearstatcache();
     @ini_set('output_buffering', 'off');
     // output buffer fix
     @ini_set('max_execution_time', 0);
     // time limit fix
     @ini_set('memory_limit', '1024M');
     // memory problem fix
     error_reporting(1);
     @ignore_user_abort(1);
     @set_time_limit(0);
     //@ob_end_clean();
     //@ob_implicit_flush(TRUE);
     if ($FileType == "product_videos") {
         $dir = GetConfig('VideoDirectory');
     } else {
         if ($FileType == "install_videos") {
             $dir = GetConfig('InstallVideoDirectory');
         } else {
             if ($FileType == "audio_clips") {
                 $dir = "audio_clips";
             } else {
                 if ($FileType == "instruction_files") {
                     $dir = "instruction_file";
                 } else {
                     if ($FileType == "article_files") {
                         $dir = "article_file";
                     }
                 }
             }
         }
     }
     //$patternName = "magnaflow.swf";
     $patternName = substr($url, strrpos($url, "/") + 1);
     $randomFileName = GenRandFileName($patternName);
     if ($FileType == "product_videos" || $FileType == "install_videos") {
         if (is_dir(sprintf(ISC_BASE_PATH . "/" . "%s", $dir))) {
             // Images and downloads will be stored within a directory randomly chosen from a-z.
             $randomDir = strtolower(chr(rand(65, 90)));
             if (!is_dir(ISC_BASE_PATH . "/" . $dir . "/" . $randomDir)) {
                 if (!@mkdir(ISC_BASE_PATH . "/" . $dir . "/" . $randomDir, 0777)) {
                     $randomDir = '';
                 }
             }
         }
         $fileName = $randomDir . "/" . $randomFileName;
         $dest = realpath(ISC_BASE_PATH . "/" . $dir);
         while (file_exists($dest . "/" . $fileName)) {
             $fileName = basename($randomFileName);
             $fileName = substr_replace($randomFileName, "-" . rand(0, 10000000000.0), strrpos($randomFileName, "."), 0);
             $fileName = $randomDir . "/" . $fileName;
         }
     } else {
         //if($FileType == "audio_clips" || $FileType == "instruction_files")   for else if
         $fileName = $randomFileName;
         $dest = realpath(ISC_BASE_PATH . "/" . $dir);
         while (file_exists($dest . "/" . $fileName)) {
             $fileName = basename($randomFileName);
             $fileName = substr_replace($randomFileName, "-" . rand(0, 10000000000.0), strrpos($randomFileName, "."), 0);
             $fileName = $fileName;
         }
     }
     $dest .= "/" . $fileName;
     ini_set("display_errors", 1);
     $flv_http_path = $url;
     $data = file_get_contents($flv_http_path);
     file_put_contents($dest, $data);
     if (filesize($dest) > 1 * 1024) {
         return $fileName;
     } else {
         return "failed";
     }
 }
Exemple #11
0
	private function _ImportFile($record, $index = '')
	{
		$productFileName = $record['prodfile' . $index];

		$fileDescription = '';
		if (!empty($record['prodfiledescription' . $index])) {
			$fileDescription = $record['prodfiledescription' . $index];
		}

		$fileMaxDownloads = 0;
		if (!empty($record['prodfilemaxdownloads' . $index])) {
			$fileMaxDownloads = (int)$record['prodfilemaxdownloads' . $index];
		}

		$fileExpiresAfter = 0;
		if (!empty($record['prodfileexpiresafter' . $index])) {
			if (preg_match('/([0-9]+) (days|weeks|months|years)/i', $record['prodfileexpiresafter' . $index], $matches)) {
				$quantity = $matches[1];
				$unit = strtolower($matches[2]);

				switch ($unit) {
					case 'days':
						$fileExpiresAfter = 86400 * $quantity;
						break;
					case 'weeks':
						$fileExpiresAfter = 604800 * $quantity;
						break;
					case 'months':
						$fileExpiresAfter = 2592000 * $quantity; //assumed to be 30 days, as per class.product.php
						break;
					case 'years':
						$fileExpiresAfter = 31536000 * $quantity;
						break;
				}
			}
		}

		$productFile = false;

		// Is this a remote file?
		$downloadDirectory = ISC_BASE_PATH."/".GetConfig('DownloadDirectory');
		if(isc_substr(isc_strtolower($productFileName), 0, 7) == "http://") {
			// Need to fetch the remote file
			$file = PostToRemoteFileAndGetResponse($productFileName);
			if($file) {
				// Place it in our downloads directory
				$randomDir = strtolower(chr(rand(65, 90)));
				if(!is_dir($downloadDirectory.$randomDir)) {
					if(!isc_mkdir($downloadDirectory."/".$randomDir)) {
						$randomDir = '';
					}
				}

				// Generate a random filename
				$fileName = $randomDir . "/" . GenRandFileName(basename($productFileName));
				if(!@file_put_contents($downloadDirectory."/".$fileName, $file)) {
					$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileUnableToMove');
				}
				else {
					$productFile = array(
						"prodhash" => "",
						"downfile" => $fileName,
						"downdateadded" => time(),
						"downmaxdownloads" => $fileMaxDownloads,
						"downexpiresafter" => $fileExpiresAfter,
						"downfilesize" => filesize($downloadDirectory."/".$fileName),
						"downname" => basename($productFileName),
						"downdescription" => $fileDescription
					);
				}
			}
			else {
				$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileDoesntExist');
			}
		}
		// Treating the file as a local file, in the product_fules/import directory
		else {
			// This file exists, can be imported
			if(file_exists($downloadDirectory."/import/".$productFileName)) {

				// Move it to our images directory
				$randomDir = strtolower(chr(rand(65, 90)));
				if(!is_dir("../".$downloadDirectory."/".$randomDir)) {
					if(!isc_mkdir($downloadDirectory."/".$randomDir)) {
						$randomDir = '';
					}
				}

				// Generate a random filename
				$fileName = $randomDir . "/" . GenRandFileName($productFileName);
				if(!@copy($downloadDirectory."/import/".$productFileName, $downloadDirectory."/".$fileName)) {
					$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileUnableToMove');
				}
				else {
					$productFile = array(
						"prodhash" => "",
						"downfile" => $fileName,
						"downdateadded" => time(),
						"downmaxdownloads" => $fileMaxDownloads,
						"downexpiresafter" => $fileExpiresAfter,
						"downfilesize" => filesize($downloadDirectory."/".$fileName),
						"downname" => basename($productFileName),
						"downdescription" => $fileDescription
					);
				}
			}
			else {
				$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileDoesntExist');
			}
		}

		return $productFile;
	}
Exemple #12
0
 public function _StoreFileAndReturnId($FileName)
 {
     // This function takes a file name as its arguement and stores
     // this file in the /downloads or /images directory depending
     // on the $FileType enumeration value
     $dir = "series_images";
     if (is_array($_FILES[$FileName]) && $_FILES[$FileName]['name'] != "") {
         // If it's an image, make sure it's a valid image type
         if (isc_strtolower(isc_substr($_FILES[$FileName]['type'], 0, 5)) != "image") {
             return "";
         }
         if (is_dir(sprintf("../%s", $dir))) {
             // Clean up the incoming file name a bit
             $_FILES[$FileName]['name'] = preg_replace("#[^\\w.]#i", "_", $_FILES[$FileName]['name']);
             $_FILES[$FileName]['name'] = preg_replace("#_{1,}#i", "_", $_FILES[$FileName]['name']);
             $randomFileName = GenRandFileName($_FILES[$FileName]['name']);
             $fileName = $randomFileName;
             $dest = realpath(ISC_BASE_PATH . "/" . $dir);
             while (file_exists($dest . "/" . $fileName)) {
                 $fileName = basename($randomFileName);
                 $fileName = substr_replace($randomFileName, "-" . rand(0, 10000000000.0), strrpos($randomFileName, "."), 0);
                 $fileName = $randomDir . "/" . $fileName;
             }
             $dest .= "/" . $fileName;
             if (move_uploaded_file($_FILES[$FileName]["tmp_name"], $dest)) {
                 isc_chmod($dest, ISC_WRITEABLE_FILE_PERM);
                 // The file was moved successfully
                 return $fileName;
             } else {
                 // Couldn't move the file, maybe the directory isn't writable?
                 return "";
             }
         } else {
             // The directory doesn't exist
             return "";
         }
     } else {
         // The file doesn't exist in the $_FILES array
         return "";
     }
 }
 /**
  * Insert an imported product in to the database. This function also performs any necessary validation & error checking.
  * It also handles inserting product images, downloads, custom fields, options and other product information.
  *
  * @param int The ID of the product from the existing system.
  * @param array Array of product information to insert.
  * @param string The import error message (returned by reference)
  * @return boolean True if successful, false on failure.
  */
 public function InsertProduct($productId, $productData, &$err)
 {
     if (!isset($productData['prodname']) || $productData['prodname'] == '') {
         $err = sprintf(GetLang('ImportProductErrorInvalid'), $productId);
         $this->_LogImportError('invalid', $err);
         return false;
     }
     if (!isset($productData['categories']) || count($productData['categories']) == 0) {
         $err = sprintf(GetLang('ImportProductErrorInvalidCategory'), $productData['prodname']);
         $this->_LogImportError('invalid', $err);
         return false;
     }
     if (!isset($productData['prodprice'])) {
         $err = sprintf(GetLang('ImportProductErrorInvalidPrice'), $productData['prodname']);
         $this->_LogImportError('invalid', $err);
         return false;
     }
     if ($this->IsDuplicateProduct($productData['prodname'])) {
         $err = sprintf(GetLang('ImportProductErrorDuplicate'), $productData['prodname']);
         $this->_LogImportError('duplicates', $err);
         return false;
     }
     if (isset($productData['downloads']) && count($productData['downloads']) > 0) {
         $productData['prodtype'] = 2;
     } else {
         $productData['prodtype'] = 1;
     }
     // We have a brand name and we've also chosen to import brand names
     if (isset($productData['prodbrandid'])) {
         $brandId = $this->GetImportBrandId($productData['prodbrandid']);
     } else {
         $brandId = 0;
     }
     if (!isset($productData['prodvisible']) || $productData['prodvisible'] != 0) {
         $productData['prodvisible'] = 1;
     }
     if (!isset($productData['prodfeatured']) || $productData['prodfeatured'] != 1) {
         $productData['prodfeatured'] = 0;
     }
     if (!isset($productData['prodfreeshipping']) || $productData['prodfreeshipping'] != 1) {
         $productData['prodfreeshipping'] = 0;
     }
     if (!isset($productData['prodinvtrack']) || $productData['prodinvtrack'] != 1 && $productData['prodinvtrack'] != 2) {
         $productData['prodinvtrack'] = 0;
     }
     if (!isset($productData['prodsearchkeywords'])) {
         $productData['prodsearchkeywords'] = '';
     }
     if (!isset($productData['prodavailability'])) {
         $productData['prodavailability'] = '';
     }
     if (!isset($productData['prodsaleprice'])) {
         $productData['prodsaleprice'] = 0;
     }
     if (!isset($productData['prodcostprice'])) {
         $productData['prodcostprice'] = 0;
     }
     if (!isset($productData['prodretailprice'])) {
         $productData['prodretailprice'] = 0;
     }
     if (!isset($productData['prodsortorder'])) {
         $productData['prodsortorder'] = 0;
     }
     if (!isset($productData['prodrelatedproducts'])) {
         $productData['prodrelatedproducts'] = -1;
     } else {
         if (is_array($productData['prodrelatedproducts'])) {
             $productData['prodrelatedproducts'] = implode(",", $productData['prodrelatedproducts']);
         }
     }
     if (!isset($productData['prodwarranty'])) {
         $productData['prodwarranty'] = '';
     }
     if (!isset($productData['prodwidth'])) {
         $productData['prodwidth'] = 0;
     }
     if (!isset($productData['proddepth'])) {
         $productData['proddepth'] = 0;
     }
     if (!isset($productData['prodheight'])) {
         $productData['prodheight'] = 0;
     }
     if (!isset($productData['prodfixedshippingcost'])) {
         $productData['prodfixedshippingcost'] = 0;
     }
     if (!isset($productData['prodoptionsrequired'])) {
         $productData['prodoptionsrequired'] = 0;
     }
     if (!isset($productData['prodnumviews'])) {
         $productData['prodnumviews'] = 0;
     }
     if (!isset($productData['prodmetakeywords'])) {
         $productData['prodmetakeywords'] = '';
     }
     if (!isset($productData['prodmetadesc'])) {
         $productData['prodmetadesc'] = '';
     }
     if (!isset($productData['prodlayoutfile'])) {
         $productData['prodlayoutfile'] = 0;
     }
     $calculatedPrice = CalcRealPrice($productData['prodprice'], @$productData['prodretailprice'], @$productData['prodretailprice'], @$productData['prodistaxable']);
     $prodCats = array();
     // Insert any category associations
     foreach ($productData['categories'] as $catId) {
         $categoryId = $this->GetImportCategoryId($catId);
         $prodCats[] = $categoryId;
     }
     $prodCatsCSV = implode(',', $prodCats);
     $product = array("importproductid" => $productId, "prodname" => $productData['prodname'], "prodtype" => (int) $productData['prodtype'], "prodcode" => $productData['prodcode'], "proddesc" => $productData['proddesc'], "prodsearchkeywords" => $productData['prodsearchkeywords'], "prodavailability" => $productData['prodavailability'], "prodprice" => (double) $productData['prodprice'], "prodcostprice" => (double) $productData['prodcostprice'], "prodretailprice" => (double) $productData['prodretailprice'], "prodsaleprice" => (double) $productData['prodsaleprice'], "prodcalculatedprice" => (double) $calculatedPrice, "prodsortorder" => (int) $productData['prodsortorder'], "prodvisible" => $productData['prodvisible'], "prodfeatured" => $productData['prodfeatured'], "prodrelatedproducts" => $productData['prodrelatedproducts'], "prodcurrentinv" => (int) $productData['prodcurrentinv'], "prodlowinv" => (int) $productData['prodlowinv'], "prodoptionsrequired" => $productData['prodoptionsrequired'], "prodwarranty" => $productData['prodwarranty'], "prodweight" => (double) $productData['prodweight'], "prodwidth" => (double) $productData['prodwidth'], "prodheight" => (double) $productData['prodheight'], "proddepth" => (double) $productData['proddepth'], "prodfixedshippingcost" => (double) $productData['prodfixedshippingcost'], "prodfreeshipping" => $productData['prodfreeshipping'], "prodinvtrack" => $productData['prodinvtrack'], "prodratingtotal" => 0, "prodnumratings" => 0, "prodnumsold" => (int) $productData['prodnumsold'], "proddateadded" => (int) $productData['proddateadded'], "prodbrandid" => $brandId, "prodnumviews" => (int) $productData['prodnumviews'], "prodmetakeywords" => $productData['prodmetakeywords'], "prodmetadesc" => $productData['prodmetadesc'], "prodcatids" => $prodCatsCSV, "prodmyobasset" => '', "prodmyobincome" => '', "prodmyobexpense" => '', "prodpeachtreegl" => '');
     $productId = $this->ConvertedInsertQuery("products", $product);
     if (!$productId) {
         $err = "Failed to insert product (DEBUG)";
         $this->_LogImportError('invalid', $err);
         return false;
     }
     // Insert any category associations
     foreach ($prodCats as $categoryId) {
         $association = array("productid" => $productId, "categoryid" => $categoryId);
         $this->ConvertedInsertQuery("categoryassociations", $association);
     }
     // Are there any product images that need to be inserted?
     $has_thumb = false;
     $has_tiny = false;
     $thumb_file = '';
     $tiny_file = '';
     $firstImage = '';
     if (is_array($productData['images'])) {
         $GLOBALS['ISC_CLASS_ADMIN_PRODUCT'] = GetClass('ISC_ADMIN_PRODUCT');
         foreach ($productData['images'] as $k => $image) {
             // Only copy across product images that exist
             if (isset($image['imagefile']) && !file_exists($image['imagefile'])) {
                 continue;
             }
             // Copy the file across to the store
             $randomDir = strtolower(chr(rand(65, 90)));
             if (!is_dir(ISC_BASE_PATH . "/" . GetConfig('ImageDirectory') . "/" . $randomDir)) {
                 if (!@mkdir(ISC_BASE_PATH . "/" . GetConfig('ImageDirectory') . "/" . $randomDir, 0777)) {
                     $randomDir = '';
                 }
             }
             if (isset($image['imagedata']) && $image['imagedata'] !== '') {
                 $fileName = $randomDir . "/" . GenRandFileName($image['imagefilename']);
             } else {
                 $fileName = $randomDir . "/" . GenRandFileName(basename($image['imagefile']));
             }
             $dest = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory');
             $dest .= "/" . $fileName;
             if (isset($image['imagedata']) && $image['imagedata'] !== '') {
                 file_put_contents($dest, $image['imagedata']);
             } else {
                 copy($image['imagefile'], $dest);
             }
             // Is this image supposed to be a thumbnail?
             if (isset($image['imageisthumb']) && $image['imageisthumb'] == 1) {
                 if (!$has_thumb) {
                     $has_thumb = true;
                     $thumb_file = $fileName;
                 }
                 continue;
             }
             // Is this image supposed to be a tiny version?
             if (isset($image['imageisthumb']) && $image['imageisthumb'] == 2) {
                 if (!$has_tiny) {
                     $has_tiny = true;
                     $tiny_file = $fileName;
                 }
                 continue;
             }
             if ($firstImage == '') {
                 $firstImage = $fileName;
             }
             // A normal product image
             $newImage = array("imageprodid" => $productId, "imagefile" => $fileName, "imageisthumb" => $image['imageisthumb'], "imagesort" => $k + 1);
             $this->ConvertedInsertQuery("product_images", $newImage);
         }
         // Now the main images are done, we can build the thumbnails
         if ($firstImage && !$thumb_file) {
             $thumb_file = $firstImage;
             $thumb = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($firstImage, "thumb");
         } else {
             // Override the existing thumbnail image with the smaller version
             $thumb = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($thumb_file, "thumb", true);
         }
         if ($thumb) {
             $newImage = array("imageprodid" => $productId, "imagefile" => $thumb, "imageisthumb" => 1, "imagesort" => 0);
             $this->ConvertedInsertQuery("product_images", $newImage);
             // If we don't have a tiny version, default to the thumb size and we'll generate it below
             if (!$tiny_file) {
                 $tiny_file = $thumb;
             }
         }
         if ($tiny_file != '') {
             $thumb = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($tiny_file, "tiny");
             if ($thumb) {
                 $newImage = array("imageprodid" => $productId, "imagefile" => $thumb, "imageisthumb" => 2, "imagesort" => 0);
                 $this->ConvertedInsertQuery("product_images", $newImage);
             }
         }
     }
     // Are there any custom fields that need to be inserted for this product?
     if (isset($productData['customfields']) && is_array($productData['customfields'])) {
         foreach ($productData['customfields'] as $name => $value) {
             if ($name === '') {
                 continue;
             }
             $newField = array("fieldprodid" => $productId, "fieldname" => $name, "fieldvalue" => $value);
             $this->ConvertedInsertQuery("product_customfields", $newField);
         }
     }
     $variationId = 0;
     // Are there any variations for this product?
     if (isset($productData['variations']) && is_array($productData['variations'])) {
         // Create a variation group for this set of variations
         $newVariation = array("vname" => $productData['prodname'] . " Options", "vnumoptions" => 0);
         $variationId = $this->ConvertedInsertQuery("product_variations", $newVariation);
         // Insert the different combinations we have
         $vOptions = array();
         foreach ($productData['variations'] as $variation) {
             if (!isset($variation['vcsku'])) {
                 $variation['vcsku'] = '';
             }
             if (!isset($variation['vcpricediff'])) {
                 $variation['vcpricediff'] = '';
             }
             if (!isset($variation['vcprice'])) {
                 $variation['vcpricediff'] = 0;
             }
             if (!isset($variation['vcweightdiff'])) {
                 $variation['vcweightdiff'] = '';
             }
             if (!isset($variation['vcweight'])) {
                 $variation['vcweight'] = 0;
             }
             if (!isset($variation['vcstock'])) {
                 $variation['vcstock'] = 0;
             }
             if (!isset($variation['vclowstock'])) {
                 $variation['vclowstock'] = 0;
             }
             $imageFile = '';
             $thumbFile = '';
             // This variation has an image, we need to copy it across
             if (isset($variation['vcimage']) && $variation['vcimage'] != '') {
                 if (file_exists($variation['vcimage'])) {
                     // Copy across to the store
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir(ISC_BASE_PATH . "/" . GetConfig('ImageDirectory') . "/" . $randomDir)) {
                         if (!@mkdir(ISC_BASE_PATH . "/" . GetConfig('ImageDirectory') . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     $fileName = $randomDir . "/" . GenRandFileName(basename($variation['vcimage']));
                     $dest = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory');
                     $dest .= "/" . $fileName;
                     if (!copy($variation['vcimage'], $dest)) {
                         $imageFile = '';
                         $mainDest = $dest;
                     } else {
                         $imageFile = $fileName;
                         if (!isset($variation['vcthumb']) || $variation['vcthumb'] == '') {
                             $variation['vcthumb'] = $dest;
                         }
                     }
                 }
             }
             // This variation has a thumb
             if (isset($variation['vcthumb']) && $variation['vcthumb'] != '') {
                 if (file_exists($variation['vcthumb'])) {
                     // Copy across to the store
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir(ISC_BASE_PATH . "/" . GetConfig('ImageDirectory') . "/" . $randomDir)) {
                         if (!@mkdir(ISC_BASE_PATH . "/" . GetConfig('ImageDirectory') . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     $fileName = $randomDir . "/" . GenRandFileName(basename($variation['vcthumb']));
                     $dest = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory');
                     $dest .= "/" . $fileName;
                     // Copied across the image
                     if (copy($variation['vcthumb'], $dest)) {
                         // Now we need to resize it
                         $thumbFile = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($dest, "thumb", true);
                     }
                 }
             }
             // Build the list of option IDs
             $optionIds = array();
             foreach ($variation['options'] as $optName => $optValue) {
                 if (!isset($vOptions[$optName][$optValue])) {
                     // Creating a new option
                     $newOption = array("vovariationid" => $variationId, "voname" => $optName, "vovalue" => $optValue);
                     $vOptions[$optName][$optValue] = $this->ConvertedInsertQuery("product_variation_options", $newOption);
                 }
                 $optionIds[] = $vOptions[$optName][$optValue];
             }
             $optionIds = implode(",", $optionIds);
             // Now insert the actual combination
             $newCombination = array("vcproductid" => $productId, "vcvariationid" => $variationId, "vcenabled" => 1, "vcoptionids" => $optionIds, "vcsku" => $variation['vcsku'], "vcpricediff" => $variation['vcpricediff'], "vcprice" => $variation['vcprice'], "vcweightdiff" => $variation['vcweightdiff'], "vcweight" => $variation['vcweight'], "vcimage" => $imageFile, "vcthumb" => $thumbFile, "vcstock" => $variation['vcstock'], "vclowstock" => $variation['vclowstock']);
             // Insert the combination
             $this->ConvertedInsertQuery("product_variation_combinations", $newCombination);
         }
         $updatedProduct = array("prodvariationid" => $variationId);
         $GLOBALS['ISC_CLASS_DB']->UpdateQuery("products", $updatedProduct, "productid='" . $productId . "'");
         // Set the number of options for this variation set
         $updatedVariation = array("vnumoptions" => count($vOptions));
         $GLOBALS['ISC_CLASS_DB']->UpdateQuery("product_variations", $updatedVariation, "variationid='" . $variationId . "'");
     }
     // Are there any downloads for this product?
     if (isset($productData['downloads']) && is_array($productData['downloads'])) {
         foreach ($productData['downloads'] as $download) {
             if (!isset($download['downname']) || empty($download['downname'])) {
                 $download['downname'] = basename($download['downfile']);
             }
             $download['downfile'] = realpath($download['downfile']);
             // Only copy across product images that exist
             if (!file_exists($download['downfile']) || !is_file($download['downfile'])) {
                 continue;
             }
             // Copy the file across to the store
             $fileName = GenRandFileName(basename($download['downfile']));
             $dest = realpath(dirname(__FILE__) . "/../../../" . GetConfig('DownloadDirectory'));
             $dest .= "/" . $fileName;
             copy($download['downfile'], $dest);
             if (!isset($download['downdateadded'])) {
                 $download['downdateadded'] = time();
             }
             if (!isset($download['downmaxdownloads'])) {
                 $download['downmaxdownloads'] = 0;
             }
             if (!isset($download['downexpiresafter'])) {
                 $download['downexpiresafter'] = 0;
             }
             if (!isset($download['downdescription'])) {
                 $download['downdescription'] = basename($download['downfile']);
             }
             if (!isset($download['downfilezie'])) {
                 $download['downfilesize'] = filesize($download['downfile']);
             }
             $newDownload = array("prodhash" => '', "productid" => $productId, "downfile" => $fileName, "downdateadded" => (int) $download['downdateadded'], "downmaxdownloads" => (int) $download['downmaxdownloads'], "downexpiresafter" => (int) $download['downexpiresafter'], "downfilesize" => (int) $download['downfilesize'], "downname" => basename($download['downname']), "downdescription" => $download['downdescription']);
             $this->ConvertedInsertQuery("product_downloads", $newDownload);
         }
     }
     // Insert the search data for this product
     $searchData = array("productid" => $productId, "prodname" => $productData['prodname'], "prodcode" => $productData['prodcode'], "proddesc" => $productData['proddesc'], "prodsearchkeywords" => $productData['prodsearchkeywords']);
     $this->ConvertedInsertQuery("product_search", $searchData);
     // Build the product words list
     $GLOBALS['ISC_CLASS_ADMIN_PRODUCT'] = GetClass('ISC_ADMIN_PRODUCT');
     $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->SaveProductWords($GLOBALS['ISC_CLASS_DB']->Quote($productData['prodname']), $productId, "adding");
     return $productId;
 }