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