-
Notifications
You must be signed in to change notification settings - Fork 306
/
magmi_productimportengine.php
executable file
·1921 lines (1789 loc) · 66 KB
/
magmi_productimportengine.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* MAGENTO MASS IMPORTER CLASS
*
* version : 1.7.8
* author : S.BRACQUEMONT aka dweeves
* updated : 2010-10-09
*
*/
/* use external file for db helper */
require_once ("magmi_engine.php");
require_once ("magmi_valueparser.php");
/**
*
*
* Magmi Product Import engine class
* This class handle product import
*
* @author dweeves
*
*/
class Magmi_ProductImportEngine extends Magmi_Engine
{
//attribute info cache
public $attrinfo = array();
//attribute info by type
public $attrbytype = array();
//attribute set cache
public $attribute_sets = array();
//product entity type
public $prod_etype;
//default attribute set id
public $default_asid;
//store id cache
public $sidcache = array();
//default mode
public $mode = "update";
//cache for column names that are not attributes
private $_notattribs = array();
//list of attribute handlers
private $_attributehandlers;
//current import row
private $_current_row;
//option id cache for select/multiselect
private $_optidcache = null;
//current item ids
private $_curitemids = array("sku"=>null);
//default store list to impact
private $_dstore = array();
//same flag if current import line is referencing same item than the previous one
private $_same;
//current product id
private $_currentpid;
//extra attributes to create
private $_extra_attrs;
//current import profile
private $_profile;
//Store ids cache for website scoped attributes
private $_sid_wsscope = array();
//Store ids cache for store scope attributes
private $_sid_sscope = array();
//magento product table columns list
private $_prodcols = array();
//magento stock related table columns list
private $_stockcols = array();
//stats
private $_skustats = array();
/**
* constructor
*
* @param string $conffile
* : configuration .ini filename
*/
public function __construct()
{
parent::__construct();
$this->setBuiltinPluginClasses("itemprocessors",
dirname(dirname(__FILE__)) .
"/plugins/inc/magmi_defaultattributehandler.php::Magmi_DefaultAttributeItemProcessor");
}
public function getSkuStats()
{
return $this->_skustats;
}
/**
* (non-PHPdoc)
*
* @see Magmi_Engine::getEngineInfo()
*/
public function getEngineInfo()
{
return array("name"=>"Magmi Product Import Engine","version"=>"1.8.2","author"=>"dweeves");
}
/**
* load properties
*
* @param string $conf
* : configuration .ini filename
*/
public function initProdType()
{
$tname = $this->tablename("eav_entity_type");
$this->prod_etype = $this->selectone("SELECT entity_type_id FROM $tname WHERE entity_type_code=?",
"catalog_product", "entity_type_id");
$this->default_asid = $this->getAttributeSetId('Default');
}
public function getPluginFamilies()
{
return array("datasources","general","itemprocessors");
}
public function registerAttributeHandler($ahinst, $attdeflist)
{
foreach ($attdeflist as $attdef)
{
$ad = explode(":", $attdef);
if (count($ad) != 2)
{
$this->log("Invalid registration string ($attdef) :" . get_class($ahinst), "warning");
}
else
{
$this->_attributehandlers[$attdef] = $ahinst;
}
}
}
/**
*
* Return list of store codes that share the same website than the stores passed as parameter
*
* @param string $scodes
* comma separated list of store view codes
*/
public function getStoreIdsForWebsiteScope($scodes)
{
if (!isset($this->_sid_wsscope[$scodes]))
{
$this->_sid_wsscope[$scodes] = array();
$wscarr = csl2arr($scodes);
$qcolstr = $this->arr2values($wscarr);
$cs = $this->tablename("core_store");
$sql = "SELECT csdep.store_id FROM $cs as csmain
JOIN $cs as csdep ON csdep.website_id=csmain.website_id
WHERE csmain.code IN ($qcolstr) ";
$sidrows = $this->selectAll($sql, $wscarr);
foreach ($sidrows as $sidrow)
{
$this->_sid_wsscope[$scodes][] = $sidrow["store_id"];
}
}
return $this->_sid_wsscope[$scodes];
}
/**
* Returns the list of store ids corresponding to the store view codes
* @param unknown $scodes
* @return multitype:
*/
public function getStoreIdsForStoreScope($scodes)
{
if (!isset($this->_sid_sscope[$scodes]))
{
$this->_sid_sscope[$scodes] = array();
$scarr = csl2arr($scodes);
$qcolstr = $this->arr2values($scarr);
$cs = $this->tablename("core_store");
$sql = "SELECT csmain.store_id from $cs as csmain WHERE csmain.code IN ($qcolstr)";
$sidrows = $this->selectAll($sql, $scarr);
foreach ($sidrows as $sidrow)
{
$this->_sid_sscope[$scodes][] = $sidrow["store_id"];
}
}
return $this->_sid_sscope[$scodes];
}
/**
* Returns Magento current data for given item
* @param unknown $item : item to get magento data from
* @param unknown $params : item metadata
* @param string $cols : columns list to return (if not set, all items column list)
* @return Ambigous <multitype:, multitype:unknown >
*/
public function getMagentoData($item, $params, $cols = null)
{
// out data
$out = array();
// if no specific columns set, use all item keys as base
if ($cols == null)
{
$cols = array_keys($item);
}
$this->initAttrInfos($cols);
// cross with defined attributes
$attrkeys = array_intersect($cols, array_keys($this->attrinfo));
// Create several maps:
// 1 per backend type => 1 request per backend type
// 1 to retrieve attribute code from attribute id (avoid a join since we already have the map)
$bta = array();
$idcodemap = array();
// Handle atribute retrieval
foreach ($attrkeys as $k)
{
$attrdata = $this->attrinfo[$k];
$bt = "" . $attrdata["backend_type"];
if ($bt != "static")
{
$attid = $attrdata["attribute_id"];
if (!isset($bta[$bt]))
{
$bta[$bt] = array();
}
$bta[$bt][] = $attid;
$idcodemap[$attid] = $k;
}
}
// Peform SQL "by type"
foreach (array_keys($bta) as $bt)
{
$cpet = $this->tablename("catalog_product_entity_$bt");
$storeids = $this->getItemStoreIds($item);
$sid = $storeids[0];
$sql = "SELECT attribute_id,value FROM $cpet WHERE entity_id=? AND store_id=? AND attribute_id IN (" .
$this->arr2values($bta[$bt]) . ")";
$tdata = $this->selectAll($sql, array_merge(array($params["product_id"],$sid), $bta[$bt]));
foreach ($tdata as $row)
{
$out[$idcodemap[$row["attribute_id"]]] = $row["value"];
}
unset($tdata);
}
// Check for qty attributes
$scols = array_intersect($cols, $this->getStockCols());
$sql = "SELECT " . implode(",", $scols) . " FROM " . $this->tablename("cataloginventory_stock_item") .
" WHERE product_id=?";
$tdata = $this->selectAll($sql, array($params["product_id"]));
if (count($tdata) > 0)
{
$out = array_merge($out, $tdata[0]);
}
unset($idcodemap);
unset($bta);
return $out;
}
/**
* returns mode
*/
public function getMode()
{
return $this->mode;
}
/**
* Adds an extra attribute to process
* Useful for some plugins if generating attribute values that are not in initial scanned list
* @param unknown $attr attribute code
*/
public function addExtraAttribute($attr)
{
$attinfo = $this->attrinfo[$attr];
$this->_extra_attrs[$attinfo["backend_type"]]["data"][] = $attinfo;
}
/**
* Returns the list of magento base product table columns
* @return multitype:
*/
public function getProdCols()
{
if (count($this->_prodcols) == 0)
{
$sql = 'DESCRIBE ' . $this->tablename('catalog_product_entity');
$rows = $this->selectAll($sql);
foreach ($rows as $row)
{
$this->_prodcols[] = $row['Field'];
}
}
return $this->_prodcols;
}
/**
* Returns the list of magento product item stock info table columns
* @return multitype:
*/
public function getStockCols()
{
if (count($this->_stockcols) == 0)
{
$sql = 'DESCRIBE ' . $this->tablename('cataloginventory_stock_item');
$rows = $this->selectAll($sql);
foreach ($rows as $row)
{
$this->_stockcols[] = $row['Field'];
}
}
return $this->_stockcols;
}
/**
* Initialize attribute infos to be used during import
*
* @param array $cols
* : array of attribute names
*/
public function checkRequired($cols)
{
$eav_attr = $this->tablename("eav_attribute");
$sql = "SELECT attribute_code FROM $eav_attr WHERE is_required=1
AND frontend_input!='' AND frontend_label!='' AND entity_type_id=?";
$required = $this->selectAll($sql, $this->prod_etype);
$reqcols = array();
foreach ($required as $line)
{
$reqcols[] = $line["attribute_code"];
}
$required = array_diff($reqcols, $cols);
return $required;
}
/**
*
* gets attribute metadata from DB and put it in attribute metadata caches
*
* @param array $cols
* list of attribute codes to get metadata from
* if in this list, some values are not attribute code, no metadata will be cached.
*/
public function initAttrInfos($cols)
{
if ($this->prod_etype == null)
{
// Find product entity type
$tname = $this->tablename("eav_entity_type");
$this->prod_etype = $this->selectone("SELECT entity_type_id FROM $tname WHERE entity_type_code=?",
"catalog_product", "entity_type_id");
}
// remove from candidates, those which we already know are not attributes
$candidates = array_diff($cols, $this->_notattribs);
// remove from candidates already known attributes
$candidates = array_diff($candidates, array_keys($this->attrinfo));
// now we have a count of "unknown columns" that are potential attributes
$toscan = array_values($candidates);
if (count($toscan) > 0)
{
// create statement parameter string ?,?,?.....
$qcolstr = $this->arr2values($toscan);
$tname = $this->tablename("eav_attribute");
if ($this->getMagentoVersion() != "1.3.x")
{
$extra = $this->tablename("catalog_eav_attribute");
// SQL for selecting attribute properties for all wanted attributes
$sql = "SELECT `$tname`.*,$extra.is_global,$extra.apply_to FROM `$tname`
LEFT JOIN $extra ON $tname.attribute_id=$extra.attribute_id
WHERE ($tname.attribute_code IN ($qcolstr)) AND (entity_type_id=?)";
}
else
{
$sql = "SELECT `$tname`.* FROM `$tname` WHERE ($tname.attribute_code IN ($qcolstr)) AND (entity_type_id=?)";
}
$toscan[] = $this->prod_etype;
$result = $this->selectAll($sql, $toscan);
$attrinfs = array();
// create an attribute code based array for the wanted columns
foreach ($result as $r)
{
$attrinfs[$r["attribute_code"]] = $r;
}
unset($result);
// create a backend_type based array for the wanted columns
// this will greatly help for optimizing inserts when creating attributes
// since eav_ model for attributes has one table per backend type
// skip already in attrinfo
foreach ($attrinfs as $k => $a)
{
if (!in_array($k, array_keys($this->attrinfo)))
{
$bt = $a["backend_type"];
if (!isset($this->attrbytype[$bt]))
{
$this->attrbytype[$bt] = array("data"=>array());
}
$this->attrbytype[$bt]["data"][] = $a;
$this->attrinfo[$k] = $a;
}
}
// now add a fast index in the attrbytype array to store id list in a comma separated form
foreach ($this->attrbytype as $bt => $test)
{
$idlist = array();
foreach ($test["data"] as $it)
{
$idlist[] = $it["attribute_id"];
}
$this->attrbytype[$bt]["ids"] = implode(",", $idlist);
}
// Important Bugfix, array_merge_recurvise to merge 2 dimenstional arrays.
$this->_notattribs = array_diff($cols, array_keys($this->attrinfo));
}
/*
* now we have 2 index arrays 1. $this->attrinfo which has the following structure: key : attribute_code value : attribute_properties 2. $this->attrbytype which has the following structure: key : attribute backend type value : array of : data => array of attribute_properties ,one for each attribute that match the backend type ids => list of attribute ids of the backend type
*/
}
/**
* retrieves attribute metadata
*
* @param string $attcode
* attribute code
* @param boolean $lookup
* if set, this will try to get info from DB otherwise will get from cache and may return null if not cached
* @return array attribute metadata info
*/
public function getAttrInfo($attcode, $lookup = true)
{
$attrinf = isset($this->attrinfo[$attcode]) ? $this->attrinfo[$attcode] : null;
if ($attrinf == null && $lookup)
{
$this->initAttrInfos(array($attcode));
}
if (isset($this->attrinfo[$attcode]))
{
$attrinf = $this->attrinfo[$attcode];
}
return $attrinf;
}
/**
* retrieves attribute set id for a given attribute set name
*
* @param string $asname
* : attribute set name
*/
public function getAttributeSetId($asname)
{
if (!isset($this->attribute_sets[$asname]))
{
$tname = $this->tablename("eav_attribute_set");
$asid = $this->selectone(
"SELECT attribute_set_id FROM $tname WHERE attribute_set_name=? AND entity_type_id=?",
array($asname,$this->prod_etype), 'attribute_set_id');
$this->attribute_sets[$asname] = $asid;
}
return $this->attribute_sets[$asname];
}
/**
* Retrieves product id for a given sku
*
* @param string $sku
* : sku of product to get id for
*/
public function getProductIds($sku)
{
$tname = $this->tablename("catalog_product_entity");
$result = $this->selectAll(
"SELECT sku,entity_id as pid,attribute_set_id as asid,type_id as type FROM $tname WHERE sku=?", $sku);
if (count($result) > 0)
{
$pids = $result[0];
$pids["__new"] = false;
return $pids;
}
else
{
return false;
}
}
/**
* creates a product in magento database
*
* @param array $item:
* product attributes as array with key:attribute name,value:attribute value
* @param int $asid
* : attribute set id for values
* @return : product id for newly created product
*/
public function createProduct($item, $asid)
{
// force item type if not exists
if (!isset($item["type"]))
{
$item["type"] = "simple";
}
$tname = $this->tablename('catalog_product_entity');
$item['type_id'] = $item['type'];
$item['attribute_set_id'] = $asid;
$item['entity_type_id'] = $this->prod_etype;
$item['created_at'] = strftime("%Y-%m-%d %H:%M:%S");
$item['updated_at'] = strftime("%Y-%m-%d %H:%M:%S");
$columns = array_intersect(array_keys($item), $this->getProdCols());
$values = $this->filterkvarr($item, $columns);
$sql = "INSERT INTO `$tname` (" . implode(",", $columns) . ") VALUES (" . $this->arr2values($columns) . ")";
$lastid = $this->insert($sql, array_values($values));
return $lastid;
}
/**
* Updateds product update time
*
* @param unknown_type $pid
* : entity_id of product
*/
public function touchProduct($pid)
{
$tname = $this->tablename('catalog_product_entity');
$this->update("UPDATE $tname SET updated_at=? WHERE entity_id=?", array(strftime("%Y-%m-%d %H:%M:%S"),$pid));
}
/**
* Get Option id for select attributes based on value
*
* @param int $attid
* : attribute id to find option id from value
* @param mixed $optval
* : value to get option id for
* @return : array of lines (should be as much as values found),"opvd"=>option_id for value on store 0,"opvs" option id for value on current store
*/
public function getOptionsFromValues($attid, $store_id, $optvals)
{
$ovstr = substr(str_repeat("?,", count($optvals)), 0, -1);
$t1 = $this->tablename('eav_attribute_option');
$t2 = $this->tablename('eav_attribute_option_value');
$sql = "SELECT optvals.option_id as opvs,optvals.value FROM $t2 as optvals";
$sql .= " JOIN $t1 as opt ON opt.option_id=optvals.option_id AND opt.attribute_id=?";
$sql .= " WHERE optvals.store_id=? AND BINARY optvals.value IN ($ovstr)";
return $this->selectAll($sql, array_merge(array($attid,$store_id), $optvals));
}
/* create a new option entry for an attribute */
public function createOption($attid)
{
$t = $this->tablename('eav_attribute_option');
$optid = $this->insert("INSERT INTO $t (attribute_id) VALUES (?)", $attid);
return $optid;
}
/**
* Creates a new option value for an option entry for a store
*
* @param int $optid
* : option entry id
* @param int $store_id
* : store id to add value for
* @param mixed $optval
* : new option value to add
* @return : option id for new created value
*/
public function createOptionValue($optid, $store_id, $optval)
{
$t = $this->tablename('eav_attribute_option_value');
$optval_id = $this->insert("INSERT INTO $t (option_id,store_id,value) VALUES (?,?,?)",
array($optid,$store_id,$optval));
return $optval_id;
}
/**
* Returns option ids for a given store for a set of values (for select/multiselect attributes)
* - Create new entries if values do not exist
*
* @param unknown $attid
* attribute id
* @param unknown $storeid
* store id
* @param unknown $values
* value to create options for
* @return Ambigous <multitype:, unknown>
*/
public function getOptionIds($attid, $storeid, $values)
{
$optids = array();
$svalues = array();
$avalues = array();
// Checking if we want to "translate" values existing in admin
foreach ($values as $val)
{
// if we have a reference value in admin
if (preg_match("|^(.*)::\[(.*)\]$|", $val, $matches))
{
// add translated value in store value array
$svalues[] = $matches[2];
// add admin value in admin value array
$avalues[] = $matches[1];
}
else
{
// if no translation, add values in both admin & current store array
$svalues[] = $val;
$avalues[] = $val;
}
}
// get Existing options for admin values & current attribute (store = 0)
$existing = $this->getOptionsFromValues($attid, 0, $avalues);
$exvals = array();
foreach ($existing as $optdesc)
{
$exvals[] = $optdesc["value"];
}
// new option values are option values that are in "admin" option values array & not in existing admin option values array
$new = array_merge(array_diff($avalues, $exvals));
// if we are on admin option values
if ($storeid == 0)
{
// for each new option value to create in admin
foreach ($new as $nval)
{
// create a new option with value
$row = array("opvs"=>$this->createOption($attid),"value"=>$nval);
// add an option value for current store
$this->createOptionValue($row["opvs"], $storeid, $nval);
// add this value to existing pool
$existing[] = $row;
}
// put this value in the option id cache
$this->cacheOptIds($attid, $existing);
}
else
// we are on a specific store , not admin
{
// get cached option ids for current attribute
$brows = $this->getCachedOptIds($attid);
// if none already exist
if (count($brows) == 0)
{
// try to find options matching given values (admin)
$existing = $this->getOptionsFromValues($attid, 0, $avalues);
// find non existing ones
$new = array_merge(array_diff($avalues, $exvals));
// for each new option value to create in admin
foreach ($new as $nval)
{
// create option
$row = array("opvs"=>$this->createOption($attid),"value"=>$nval);
// create option value for current store
$this->createOptionValue($row["opvs"], $storeid, $nval);
// add to exisiting pool
$existing[] = $row;
}
// add existing pool to cache
$this->cacheOptIds($attid, $existing);
// return cached option ids
$brows = $this->getCachedOptIds($attid);
}
// for all existing
foreach ($existing as $ex)
{
// remove from processing array
array_shift($brows);
}
// for all new
$cnew = count($new);
for ($i = 0; $i < $cnew; $i++)
{
$row = $brows[$i];
// if we don't have option
if (!isset($row["opvs"]))
{
// create option
$row["opvs"] = $this->createOption($attid);
// create option
$this->createOptionValue($row["opvs"], 0, $new[$i]);
}
// create option value for store
$this->createOptionValue($row["opvs"], $storeid, $new[$i]);
// add to existing pool
$existing[] = $row;
}
}
$optids = array();
// now all options are in existing & values are created
// builf and array with all option ids
foreach ($existing as $row)
{
$optids[] = $row["opvs"];
}
// remove existing
unset($existing);
// remove existing values
unset($exvals);
// remove temp array
unset($brows);
// return option ids
return $optids;
}
/**
* Adds a new option definition row in the cache
*
* @param unknown $attid
* attribute id
* @param unknown $row
* option definition
*/
public function cacheOptIds($attid, $row)
{
$this->_optidcache[$attid] = $row;
}
/**
* return cached option definition rows for a given attribute id
*
* @param unknown $attid
* attribute id
* @return NULL or option definition rows found
*/
public function getCachedOptIds($attid)
{
if (isset($this->_optidcache[$attid]))
{
return $this->_optidcache[$attid];
}
else
{
return null;
}
}
/**
* returns tax class id for a given tax class value
*
* @param $tcvalue :
* tax class value
*/
public function getTaxClassId($tcvalue)
{
// allow for ids in tax_class_id column , extending support
if (is_numeric($tcvalue))
{
$txid = $tcvalue;
}
else
{
$t = $this->tablename('tax_class');
$txid = $this->selectone("SELECT class_id FROM $t WHERE class_name=?", array($tcvalue), "class_id");
}
// bugfix for tax class id, if not found set it to none
if (!isset($txid))
{
$txid = 0;
}
return $txid;
}
/**
* parses a calculated value with tokens like {{ }} or {}
*
* @param unknown $pvalue
* parsing value
* @param unknown $item
* item for resolving {item.xxx} tokens
* @param unknown $params
* params for resolving {meta.xxx} tokens
* @return string resolved value
*/
public function parseCalculatedValue($pvalue, $item, $params)
{
$pvalue = Magmi_ValueParser::parseValue($pvalue, array("item"=>$item,"meta"=>$params));
return $pvalue;
}
/**
* Return affected store ids for a given item given an attribute scope
*
* @param array $item
* : item to get store for scope
* @param string $scope
* : scope to get stores from.
*/
public function getItemStoreIds($item, $scope = 0)
{
if (!isset($item['store']))
{
$item['store'] = "admin";
}
switch ($scope)
{
// global scope
case 1:
$bstore_ids = $this->getStoreIdsForStoreScope("admin");
break;
// store scope
case 0:
$bstore_ids = $this->getStoreIdsForStoreScope($item["store"]);
break;
// website scope
case 2:
$bstore_ids = $this->getStoreIdsForWebsiteScope($item["store"]);
break;
}
$itemstores = array_unique(array_merge($this->_dstore, $bstore_ids));
sort($itemstores);
return $itemstores;
}
/**
* Create product attribute from values for a given product id
*
* @param $pid :
* product id to create attribute values for
* @param $item :
* attribute values in an array indexed by attribute_code
*/
public function createAttributes($pid, &$item, $attmap, $isnew, $itemids)
{
/**
* get all store ids
*/
$this->_extra_attrs = array();
/* now is the interesring part */
/* iterate on attribute backend type index */
foreach ($attmap as $tp => $a)
{
/* for static types, do not insert into attribute tables */
if ($tp == "static")
{
continue;
}
// table name for backend type data
$cpet = $this->tablename("catalog_product_entity_$tp");
// data table for inserts
$data = array();
// inserts to perform on backend type eav
$inserts = array();
// deletes to perform on backend type eav
$deletes = array();
// use reflection to find special handlers
$typehandler = "handle" . ucfirst($tp) . "Attribute";
// iterate on all attribute descriptions for the given backend type
foreach ($a["data"] as $attrdesc)
{
// check item type is compatible with attribute apply_to
if ($attrdesc["apply_to"] != null &&
strpos($attrdesc["apply_to"], strtolower($itemids["type"])) === false)
{
// do not handle attribute if it does not apply to the product type
continue;
}
// get attribute id
$attid = $attrdesc["attribute_id"];
// get attribute value in the item to insert based on code
$atthandler = "handle" . ucfirst($attrdesc["attribute_code"]) . "Attribute";
$attrcode = $attrdesc["attribute_code"];
// if the attribute code is no more in item (plugins may have come into the way), continue
if (!in_array($attrcode, array_keys($item)))
{
continue;
}
// get the item value
$ivalue = $item[$attrcode];
// get item store id for the current attribute
$store_ids = $this->getItemStoreIds($item, $attrdesc["is_global"]);
// do not handle empty generic int values in create mode
if ($ivalue == "" && $this->mode != "update" && $tp == "int")
{
continue;
}
// for all store ids
foreach ($store_ids as $store_id)
{
// base output value to be inserted = base source value
$ovalue = $ivalue;
// check for attribute handlers for current attribute
foreach ($this->_attributehandlers as $match => $ah)
{
$matchinfo = explode(":", $match);
$mtype = $matchinfo[0];
$mtest = $matchinfo[1];
unset($matchinfo);
unset($hvalue);
if (preg_match("/$mtest/", $attrdesc[$mtype]))
{
// if there is a specific handler for attribute, use it
if (method_exists($ah, $atthandler))
{
$hvalue = $ah->$atthandler($pid, $item, $store_id, $attrcode, $attrdesc, $ivalue);
}
else
// use generic type attribute
if (method_exists($ah, $typehandler))
{
$hvalue = $ah->$typehandler($pid, $item, $store_id, $attrcode, $attrdesc, $ivalue);
}
// if handlers returned a value that is not "__MAGMI_UNHANDLED__" , we have our output value
if (isset($hvalue) && $hvalue != "__MAGMI_UNHANDLED__")
{
$ovalue = $hvalue;
break;
}
}
}
// if __MAGMI_UNHANDLED__ ,don't insert anything
if ($ovalue == "__MAGMI_UNHANDLED__")
{
$ovalue = false;
}
// force null value => to delete
if ($ovalue == "__NULL__")
{
$ovalue = "__MAGMI_DELETE__";
}
// if handled value is a "DELETE"
if ($ovalue == "__MAGMI_DELETE__")
{
$deletes[] = $attid;
// do not handle value in insert
$ovalue = null;
}
// if we have something to do with this value
if ($ovalue !== false && $ovalue != null)
{
$data[] = $this->prod_etype;
$data[] = $attid;
$data[] = $store_id;
$data[] = $pid;
$data[] = $ovalue;
$insstr = "(?,?,?,?,?)";
$inserts[] = $insstr;
}
// if one of the store in the list is admin
if ($store_id == 0)
{
$sids = $store_ids;
// remove all values bound to the other stores for this attribute,so that they default to "use admin value"
array_shift($sids);
if (count($sids) > 0)
{
$sidlist = implode(",", $sids);
$ddata = array($this->prod_etype,$attid,$pid);
$sql = "DELETE FROM $cpet WHERE entity_type_id=? AND attribute_id=? AND store_id IN ($sidlist) AND entity_id=?";
$this->delete($sql, $ddata);
unset($ddata);
}
unset($sids);
break;
}
}
}
//if we have values to insert or update
if (!empty($inserts))
{
// now perform insert for all values of the the current backend type in one
// single insert
$sql = "INSERT INTO $cpet
(`entity_type_id`, `attribute_id`, `store_id`, `entity_id`, `value`)
VALUES ";
$sql .= implode(",", $inserts);
// this one taken from mysql log analysis of magento import
// smart one :)
$sql .= " ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)";
$this->insert($sql, $data);
}
//if we have values to delete
if (!empty($deletes))
{
$sidlist = implode(",", $store_ids);
$attidlist = implode(",", $deletes);
$sql = "DELETE FROM $cpet WHERE entity_type_id=? AND attribute_id IN ($attidlist) AND store_id IN ($sidlist) AND entity_id=?";
$this->delete($sql, array($this->prod_etype,$pid));
}
//if no values inserted or deleted on a new item, we have a problem
if (empty($deletes) && empty($inserts) && $isnew)
{
//in fact we have a problem if we have a really new item
if (!$this->_same)
{