· 6 years ago · Jun 11, 2019, 03:22 PM
1session_start();
2require_once 'vendor/autoload.php';
3require_once 'utils.php';
4
5$clientBuilder = new ClientBuilder($params);
6$client = $clientBuilder->build();
7
8$_SESSION["php-oauth-client"] = array();
9
10// OwnServerDB MySQL Connection
11require('mysql_login.php');
12require('mysql_connection.php');
13
14require_once 'ownServerGetId.php';
15
16// WooCommerce Connection
17
18require 'wooApi/vendor/autoload.php';
19use Automattic\WooCommerce\Client;
20use Automattic\WooCommerce\HttpClient\HttpClientException;
21
22// Connection to WooCommerce
23$woocommerce = new Client(
24'https://4-gamers-shop.com',
25[
26'wp_api' => true,
27'version' => 'wc/v3',
28'query_string_auth' => true // Force Basic Authentication as query string true and using under HTTPS
29]
30);
31
32
33
34
35
36// Get Products from LIEFERANT
37
38try {
39
40$getProductId = "";
41
42$countIndex = 0;
43
44$products = $client->getProducts(); // All Products as an object
45foreach ($products as $product) {
46echo "IndexIndex : ".$countIndex."\n";
47$getProductId = $product->getProductId();
48$sql = "SELECT productId FROM `product` WHERE productId = '".$getProductId."'";
49$result = $conn->query($sql);
50
51echo $getOfficialTitle = addslashes($product->getName());
52echo "\n";
53echo $getProductId."\n";
54
55if ($result->num_rows == 0) {
56echo "CREATE_ NEW PRODUCT IN TABLE > P R O D U C T < ======";
57
58// Date and Time
59$dateToday = date("d.m.Y");
60$timeNow = date("H:i:s");
61// Source : $product
62
63// $getOfficialTitle = addslashes($product->getName());
64
65$getStockQ = getStockQ($product);
66
67$getDefaultPrice = getDefaultPrice($product);
68
69$getLanguages = getLanguages($product); // ARR
70
71$getRegion = getRegion($product); // ARR
72
73$getPrice = getPrice($product); // ARR
74
75$getGamePlatform = getGamePlatform($product);
76
77$getGamePlatformId = getGamePlatformId($getGamePlatform);
78
79$getReleaseDate = getReleaseDate($product);
80//$getProductId = $product->getProductId();
81// Length of the ArrayOutput
82$getLanguagesLength = count($getLanguages);
83
84$getRegionLength = count($getRegion);
85
86$getPriceLength = count($getPrice);
87// INSERT PRODUCT
88$insertProduct = "INSERT INTO product (productId,officialTitle,stock,defaultPrice,developer,pegi,developerHomepage,price_1_9,price_10_99,price_100,releaseDate,platform,platformId,createDate,createTime)
89VALUES ('".$getProductId."', '".$getOfficialTitle."','".$getStockQ."','".$getDefaultPrice."',NULL,NULL,NULL,'".$getPrice[1]."','".$getPrice[0]."','".$getPrice[2]."','".$getReleaseDate."','".$getGamePlatform."','".$getGamePlatformId."','".$dateToday."','".$timeNow."')";
90
91if ($conn->query($insertProduct) === TRUE) {
92
93} else {
94echo "Error: " . $insertProduct . "<br>" . $conn->error;
95}
96
97sleep(2);
98//Insert Language
99for($i = 0; $i < $getLanguagesLength; $i++){
100$insertLanguage = "INSERT INTO language_product_ass (lp_id,languageId,productId) VALUES (NULL,'".getLanguageId($getLanguages[$i])."','".$getProductId."')";
101
102if ($conn->query($insertLanguage) === TRUE) {
103
104} else {
105echo "</br>Error: ". $conn->error."</br>";
106
107}
108}
109sleep(2);
110//Insert Region
111for($i = 0; $i < $getRegionLength; $i++){
112
113$insertRegion = "INSERT INTO region_product_ass (rp_id,regionId,productId) VALUES (NULL,'".getRegionId($getRegion[$i])."','".$getProductId."')";
114
115
116$getRegion[$i];
117if ($conn->query($insertRegion) === TRUE) {
118
119} else {
120echo "</br>Error: ". $conn->error."</br>";
121}
122}
123
124sleep(4);
125}
126
127//* After insert product to TABLE 'product'
128/* Check Shop_Product_Ass */
129$checkShopProductAss = "SELECT productId from shop_product_ass WHERE productId ='".$getProductId."'";
130$resultShopProductAss = $conn->query($checkShopProductAss);
131
132if ($resultShopProductAss->num_rows == 1) {
133//Already uploaded to Shop
134echo "ALREADY UPLOADED TO SHOP ! \n";
135echo $getProductId;
136}
137else{ //NOT include in Shop
138echo "NOT UPLOADED TO SHOP ! \n";
139echo $getProductId;
140// Check exists images, description
141$checkExistsImages = "SELECT * FROM images WHERE productId = '".$getProductId."'";
142
143$resultExistsImages = $conn->query($checkExistsImages);
144
145if ($resultExistsImages->num_rows == 0) { // Images not exists
146echo "Images don't exists for ProductId : ".$getProductId;
147echo "=>=>=>=>=>=>=>==>=>=>=>=>=>=>=>==>=>=>=>";
148echo "=>=>=>=>=>=>=>==>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>";
149
150// Open URL to import to Database
151echo "Try to open Index : ".$countIndex."\n";
152
153set_error_handler(
154function ($severity, $message, $file, $line) {
155throw new ErrorException($message, $severity, $severity, $file, $line);
156}
157);
158$open_url = ''; // URL aufrufen um restliche Productdetails vom Lieferanten aus der Datenbank zu holen
159$open_url = $open_url.$countIndex;
160try {
161file_get_contents($open_url);
162}
163catch (Exception $e) {
164echo $e->getMessage();
165}
166restore_error_handler();
167
168}
169else{ // Images exists
170
171}
172// Download images if in database
173
174$resultExistsImages = $conn->query($checkExistsImages);
175
176if ($resultExistsImages->num_rows > 0) {
177$selectGaleryImages = "SELECT * FROM images WHERE productId = '".$getProductId."'";
178
179$resultSelectGaleryImages = $conn->query($selectGaleryImages);
180
181if ($resultSelectGaleryImages->num_rows > 0) {
182
183echo "Image exists in Database => ";
184echo $row['imgUrl']."\n";
185
186$s1 = "../../../var/www/html/importProductsAuto/images/".$getProductId."/";
187
188if (!file_exists($s1)) {
189mkdir($s1, 0777, true);
190}
191
192$imagesCount = 0;
193
194while($row = $resultSelectGaleryImages->fetch_assoc()) {
195if($row['type'] == "EBAY_GALLERY" || $row['type'] == "SCREEN_SHOT_LARGE" || $row['type'] == "SCREEN_SHOT_THUMB"){
196$temp_name = "gallery";
197$imagesCount++;
198}
199else{
200$temp_name = "cover";
201$imagesCount++;
202}
203
204$fileName = $temp_name.$imagesCount.".jpg";
205
206$imageUrl = $row['imgUrl'];
207
208$openLink = $s1.$fileName;
209
210echo "Try to Download Image =>=>=>=>=>=>=>\n";
211
212$ch = curl_init($imageUrl);
213
214$fp = fopen($openLink, "wb");
215curl_setopt($ch, CURLOPT_FILE, $fp);
216curl_setopt($ch, CURLOPT_HEADER, 0);
217curl_exec($ch);
218curl_close($ch);
219
220//checkfilesize
221if(filesize($openLink) < 300){
222echo "Datei zu klein \n";
223unlink($openLink);
224echo "Datei geloescht : ".$openLink."\n";
225//Delete File
226}
227}
228
229// After download images
230/* COMPARE IMAGE SIZE */
231echo ">>>>>>> START COMPARE IMAGES <<<<<<";
232
233$filesArr = array();
234
235$folder = $s1;
236$fileType = '.jpg';
237
238$verzeichnis = $folder;
239
240if ( is_dir ( $verzeichnis )){
241// öffnen des Verzeichnisses
242if ( $handle = opendir($verzeichnis) ){
243$x = 0;
244while (($file = readdir($handle)) !== false){
245if($file != "." and $file != ".."){
246$filesArr[$x][0] = $file;
247$filesArr[$x][1] = filesize($folder.$file)."\n";
248$x++;
249}
250}
251}
252}
253closedir($handle);
254
255$filesArrSize1d = count($filesArr);
256
257
258$toDeleteImages = array();
259$t = 0;
260
261for($lx = 0;$lx < $filesArrSize1d;$lx++){
262//echo "$filesArr[$lx][0]."\n"";
263for($sx = $filesArrSize1d-1;$sx > 0;$sx--){
264// echo "Vergleich ".$filesArr[$lx][0]." mit ".$filesArr[$sx][0]."\n";
265if($filesArr[$lx][1] == $filesArr[$sx][1]){
266if($lx != $sx){
267if($filesArr[$lx][0] == "cover1.jpg"){
268$toDeleteImagesLength = count($toDeleteImages);
269$rm = 0;
270for($rt = 0;$rt < $toDeleteImagesLength;$rt++){
271if($toDeleteImages[$rt] == $filesArr[$sx][0]){
272$rm = 1; // file exists in toDeleteImages ARR
273}
274}
275if($rm == 0){
276$toDeleteImages[$t] = $filesArr[$sx][0];
277// echo $folder.$filesArr[$lx][0]." ist identisch mit ".$folder.$filesArr[$sx][0]."\n";
278$t++;
279}
280}
281else if($filesArr[$lx][0] != "cover1.jpg"){
282if($filesArr[$lx][0] != $filesArr[$sx][0]){
283$toDeleteImagesLength = count($toDeleteImages);
284$rm = 0;
285for($rt = 0;$rt < $toDeleteImagesLength;$rt++){
286if($toDeleteImages[$rt] == $filesArr[$lx][0] or $toDeleteImages[$rt] == $filesArr[$sx][0]){
287$rm = 1;
288}
289}
290if($rm == 0){
291$toDeleteImages[$t] = $filesArr[$sx][0];
292echo $folder.$filesArr[$lx][0]." ist identisch mit ".$folder.$filesArr[$sx][0]."\n";
293$t++;
294}
295}
296}
297}
298}
299}
300}
301
302$toDeleteImagesLength2 = count($toDeleteImages);
303
304for($ab = 0;$ab < $toDeleteImagesLength2;$ab++){
305echo $getProductId."\n";
306echo $toDeleteImages[$ab]."\n";
307unlink('../../../var/www/html/importProductsAuto/images/'.$getProductId.'/'.$toDeleteImages[$ab]);
308}
309
310/* COMPARE IMAGE SIZE END */
311
312/* COMPARE COVER IMAGE SIZE */
313
314$coverFilesArr = array();
315
316$folder = $s1;
317$fileType = '.jpg';
318
319$verzeichnis = $folder;
320
321if ( is_dir ( $verzeichnis )){
322// öffnen des Verzeichnisses
323if ( $handle = opendir($verzeichnis) ){
324$x = 0;
325while (($file = readdir($handle)) !== false){
326if($file != "." and $file != ".."){
327if(strpos($file,"cover")!==false){
328$coverFilesArr[$x][0] = $file;
329$coverFilesArr[$x][1] = filesize($folder.$file);
330$x++;
331}
332}
333}
334}
335closedir($handle);
336
337echo "LENGTH OF COVER ARRAY : ";
338echo $coverFilesArrLength = count($coverFilesArr);
339
340echo "\n";
341
342$dontDeleteImage = "";
343$maxSizeCover = 0;
344
345for($i = 0;$i < $coverFilesArrLength;$i++){
346if($maxSizeCover < $coverFilesArr[$i][1]){
347$dontDeleteImage = $coverFilesArr[$i][0];
348$maxSizeCover = $coverFilesArr[$i][1];
349}
350}
351
352//delete all other cover
353for($i = 0;$i < $coverFilesArrLength;$i++){
354if($coverFilesArr[$i][0] != $dontDeleteImage){
355unlink('../../../var/www/html/importProductsAuto/images/'.$getProductId.'/'.$coverFilesArr[$i][0]);
356echo "SELECTED : ".$dontDeleteImage."\n";
357echo "DELETES ".$coverFilesArr[$i][0]."\n";
358}
359}
360
361}
362
363/* COMPARE COVER IMAGE SIZE END */
364} // ImageExists
365}
366
367// CHECK : Upload to Shop ?
368$uploadToShop = 0; // $uploadToShop = 0 => Don't upload to Shop ; $uploadToShop = 1 => Upload to Shop
369
370$selectProductFromOwn = "SELECT * FROM product WHERE productId = '".$getProductId."'";
371
372$resultSelectProductFromOwn = $conn->query($selectProductFromOwn);
373
374$productArr = array();
375
376
377
378while($row = $resultSelectProductFromOwn->fetch_assoc()) {
379
380
381$productArr[0] = $row['productId'];
382$productArr[1] = $row['officialTitle'];
383$productArr[2] = $row['price_100'] * 1.4;
384if($row['platformId'] == 1 || $row['platformId'] == 5 || $row['platformId'] == 6 || $row['platformId'] == 7 || $row['platformId'] == 9 || $row['platformId'] == 10 || $row['platformId'] == 13){
385if($row['stock'] >= 3){
386
387$directory = "../../../var/www/html/importProductsAuto/images/".$getProductId."/";
388
389$countFiles = 0;
390
391if(is_dir($directory)){
392if ( $handle = opendir($directory) ){
393while (($file = readdir($handle)) !== false){
394$countFiles++;
395}
396}
397if($countFiles > 2){
398$uploadToShop = 1;
399}
400}
401}
402}
403}
404
405echo "§§§§§§§§§ Upload to Shop : ".$uploadToShop;
406
407// CHECK : UPLOAD TO SHOP ? END
408
409if($uploadToShop == 1){
410// Insert to Shop_Product_Ass
411
412$insertToShopProductAss = "INSERT INTO
413shop_product_ass (sz_id,productId,coverImageUrl,productTitle,shopId,sellprice,priceCalculation,available,shopDescription,shortShopDescription,importDateOwn,importTimeOwn,importDateBillbee,importTimeBillbee,online)
414VALUES
415(NULL,'".$productArr[0]."',NULL,'".$productArr[1]."',5,'".$productArr[2]."',1,1,NULL,NULL,NULL,NULL,NULL,NULL,1)";
416
417if ($conn->query($insertToShopProductAss) === TRUE) {
418echo "\n New record created successfully \n";
419} else {
420//echo "Error: " . $sql . "<br>" . $conn->error;
421}
422
423// Import to Woo Shop
424
425$productDataArray = array();
426
427$selectProductData = "SELECT product.productId, product.officialTitle, product.pegi, platform.platform, region.region, product.stock, product.price_100 , default_description.dDescription FROM product INNER JOIN platform ON product.platformId = platform.platformId INNER JOIN region_product_ass ON product.productId = region_product_ass.productId INNER JOIN region ON region_product_ass.regionId = region.regionId INNER JOIN default_description ON product.productId = default_description.productId WHERE product.productId = '".$getProductId."' AND default_description.ter_id = 4 LIMIT 1";
428
429$resultSelectProductData = $conn->query($selectProductData);
430
431if($resultSelectProductData->num_rows > 0){
432while($row = $resultSelectProductData->fetch_assoc()){
433$productDataArray[0] = $row['productId'];
434$productDataArray[1] = $row['officialTitle'];
435$productDataArray[2] = $row['pegi'];
436$productDataArray[3] = $row['platform'];
437$productDataArray[4] = $row['region'];
438$productDataArray[5] = $row['stock'];
439$productDataArray[6] = $row['price_100'] * 1.4;
440$productDataArray[6] = number_format($productDataArray[6] , 0, '', '' );
441
442$productDataArray[7] = $row['dDescription'];
443}
444
445$categoryArray = array();
446
447$selectCategorys = "SELECT * FROM category_product_ass INNER JOIN category ON category_product_ass.catId = category.catId WHERE category_product_ass.productId = '".$getProductId."'";
448
449$resultSelectCategorys = $conn->query($selectCategorys);
450
451if($resultSelectCategorys->num_rows > 0){
452$x = 0;
453while($row = $resultSelectCategorys->fetch_assoc()){
454$categoryArray[$x]['id'] = $row['catId_woo'];
455$x++;
456}
457}
458
459$languagesArray = array();
460
461$selectLanguages = "SELECT * FROM language_product_ass INNER JOIN language ON language_product_ass.languageId = language.languageId WHERE language_product_ass.productId = '".$getProductId."'";
462$resultSelectLanguages = $conn->query($selectLanguages);
463
464if($resultSelectLanguages->num_rows > 0){
465$x = 0;
466while($row = $resultSelectLanguages->fetch_assoc()){
467$languagesArray[$x] = $row['shortLang'];
468$x++;
469}
470}
471
472
473$coverFileName = "";
474$galleryArray = array();
475
476$directory = "../../../var/www/html/importProductsAuto/images/".$getProductId."/";
477
478//get cover filename
479
480if ( is_dir ( $directory )){
481// open directory
482if ( $handle = opendir($directory) ){
483while (($file = readdir($handle)) !== false){
484if($file != "." and $file != ".."){
485if(strpos($file,"cover")!==false){
486$coverFileName = $file;
487}
488}
489}
490}
491}
492closedir($handle);
493
494if(empty($coverFileName)){
495if ( is_dir ( $directory )){
496// open directory
497if ( $handle = opendir($directory) ){
498while (($file = readdir($handle)) !== false){
499if($file != "." and $file != ".."){
500$coverFileName = $file;
501}
502}
503}
504}
505closedir($handle);
506}
507
508// get cover filename END
509
510// get gallery images
511
512if ( is_dir ( $directory )){
513// open directory
514if ( $handle = opendir($directory) ){
515$x = 0;
516while (($file = readdir($handle)) !== false){
517if($file != "." && $file != ".." && $file != $coverFileName){
518$galleryArray[$x] = $file;
519$x++;
520}
521}
522}
523}
524closedir($handle);
525
526// END OF get gallery images
527
528################# CREATE Images Array FOR WOOCOMMERCE #####################
529
530$wooImagesArray = array();
531
532$countGalleryArray = count($galleryArray);
533
534$x = 0;
535if(!empty($coverFileName)){
536$wooImagesArray[$x]['src'] = "SERVERURL/importProductsAuto/images/".$getProductId."/".$coverFileName;
537$x++;
538}
539for($i = 0;$i < $countGalleryArray;$i++){
540$wooImagesArray[$x]['src'] = "SERVERURL/importProductsAuto/images/".$getProductId."/".$galleryArray[$i];
541$x++;
542}
543
544############################################################################
545
546################# CREATE Attributes Array FOR WOOCOMMERCE ##################
547$attributesArray = array();
548
549### => Languages
550
551$countLanguagesArray = count($languagesArray);
552
553$languagesString = "";
554
555for($i = 0;$i < $countLanguagesArray;$i++){
556if($i == 0){
557$languagesString = $languagesArray[$i];
558}
559else{
560$languagesString = $languagesString.",".$languagesArray[$i];
561}
562}
563
564$attributesArray[0]['id'] = 5;
565$attributesArray[0]['options'] = $languagesString;
566//$attributesArray[0]['options'] = "de,en";
567
568### => Platform
569
570$attributesArray[1]['id'] = 3;
571$attributesArray[1]['options'] = $productDataArray[3];
572//$attributesArray[1]['options'] = "Steam";
573
574### => Region
575
576$attributesArray[2]['id'] = 4;
577$attributesArray[2]['options'] = $productDataArray[4];
578//$attributesArray[2]['options'] = "WORLDWIDE";
579
580
581### => Pegi
582
583$attributesArray[3]['id'] = 8;
584$attributesArray[3]['options'] = $productDataArray[2];
585//$attributesArray[3]['options'] = 18;
586
587############################################################################
588
589################# BUILD DATA ARRAY FOR WOOCOMMERCE #########################
590
591
592
593
594try{
595echo "\n START UPLOAD : ";
596echo $sku = $productDataArray[0];
597echo "\n";
598
599$title = $productDataArray[1];
600$price = $productDataArray[6];
601$description = $productDataArray[7];
602$stock = $productDataArray[5];
603$data = [
604'sku' => $sku,
605'status' => 'publish',
606'catalog_visibility' => 'visible',
607'name' => $title,
608'type' => 'simple',
609'regular_price' => $price,
610'short_description' => '',
611'manage_stock' => true,
612'stock_quantity' => $stock,
613'categories' => $categoryArray,
614'description' => $description,
615'images' => $wooImagesArray,
616'attributes' => $attributesArray
617];
618
619//sleep(5);
620//echo "\n \n \n \n \n \n \n \n \n \n \n \n";
621
622//print_r($data);
623
624//echo "\n \n \n \n \n \n \n \n \n \n \n \n";
625$woocommerce->post('products', $data);
626
627sleep(5);
628
629} // Try END
630catch (HttpClientException $e) {
631echo '<pre><code>' . print_r( $e->getMessage(), true ) . '</code><pre>'; // Error message.
632echo '<pre><code>' . print_r( $e->getRequest(), true ) . '</code><pre>'; // Last request data.
633echo '<pre><code>' . print_r( $e->getResponse(), true ) . '</code><pre>'; // Last response data.
634}
635
636############################################################################
637
638}
639}
640} //NOT include in Shop END
641
642echo "\n ~~~~~~~~~~~~~~~ N E X T ~~~ P R O D U C T ~~~~~~~~~~~~~~~~~~~~";
643$countIndex++;
644}
645}
646catch (\\Resource\ResourceError $e) {
647
648if($e->isInvalidToken()) {
649echo "if you are using SessionStorage refresh your session and try one more time.";
650}
651
652echo $e->getCode();
653echo $e->getErrorCode();
654echo $e->getMoreInfo();
655echo $e->getDeveloperMessage();
656echo $e->getMessage();
657}
658
659?>