Browse code

Initial commit

Benjamin Roth authored on26/11/2015 10:33:32
Showing1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,844 @@
1
+<?php
2
+/**
3
+ * OXID CSV Export
4
+ *
5
+ * Exportscript für das exportieren von Artikeldaten in eine CSV-Datei.
6
+ * 
7
+ * @author Benjamin Roth [benjamin@esales-media.de]
8
+ * @version 0.1.11.1.25
9
+ * @copyright 2011 eSales Media [www.esales-media.de]
10
+ * @package OXID-Export
11
+ */
12
+
13
+/* CONFIGURATION START */
14
+
15
+define('ES_CSV_EXPORT_HASH', 'c0cc283ff8985384c0f43ff0d8f91708'); // MD5::bergstraesserwinzer
16
+ 
17
+/**
18
+ * DB Settings
19
+ */
20
+ 
21
+$DB = array
22
+(
23
+	'host'     => 'localhost:/tmp/mysql5.sock',
24
+	'database' => 'db530504992',
25
+	'username' => 'dbo530504992',
26
+	'password' => 'Kh78886Fe45Sd'
27
+);
28
+
29
+/**
30
+ * Load configuration or exit
31
+ */
32
+if (!isset($_GET['config']) && !isset($_SERVER['argv'][1]))
33
+	die('No configuration file specified');
34
+
35
+if (isset($_GET['config']))
36
+{
37
+	$config = basename($_GET['config']);
38
+} else {
39
+	$config = basename($_SERVER['argv'][1]);
40
+}
41
+
42
+if (!strlen($config) || !file_exists(dirname(__FILE__).'/conf/'.$config))
43
+	die('Configuration file not found');
44
+
45
+require_once(dirname(__FILE__).'/conf/'.$config);
46
+
47
+if (!isset($CONFIG) || !isset($EXPORT))
48
+	die('Missing configuration');
49
+
50
+/* CONFIGURATION END */
51
+
52
+/* OXID INIT START */
53
+
54
+/**
55
+ * Returns false.
56
+ *
57
+ * @return boolean
58
+ */
59
+error_reporting( E_ALL ^ E_NOTICE );
60
+ini_set('display_errors',true);
61
+
62
+define('OX_BASE_PATH', dirname(__FILE__) .'/../' ); 
63
+
64
+// custom functions file 
65
+require OX_BASE_PATH . 'bootstrap.php'; 
66
+
67
+// error reporting level
68
+error_reporting(E_ALL ^ E_NOTICE);
69
+
70
+// Generic utility method file including autoloading definition
71
+require_once OX_BASE_PATH . 'core/oxfunctions.php';
72
+
73
+/* OXID INIT END */
74
+
75
+
76
+/**
77
+ * Export Class
78
+ *
79
+ * @package OXID-Export
80
+ * @author  Benjamin Roth
81
+ */
82
+class Export extends oxUBase {
83
+	
84
+	protected $_aOrders= array();
85
+
86
+	protected $_aArticles = array();
87
+
88
+	protected $_aCategories = array();
89
+	
90
+	protected $db;
91
+	
92
+	protected $oOxidConfig;
93
+	
94
+	protected $currentArticle = array();
95
+
96
+	protected $arrDefaultSettings = array
97
+	(
98
+		'field_encloser'     => '"',
99
+		'field_terminator'   => ';',
100
+		'escape_char'        => '\\',
101
+		'filename'           => 'esm_export/csv/export.csv',
102
+		'encoding'           => 'UTF-8',
103
+		'stripHTML'          => true,
104
+		'strictStrip'        => true,
105
+		'doublets'           => true,
106
+		'languageid'         => 0,
107
+		'includeHeader'      => true,
108
+		'activeOnly'         => true,
109
+		'activeArticleField' => 'OXACTIVE',
110
+		'activeCatField'     => 'OXACTIVE',
111
+		'onStockOnly'        => false,
112
+		'skipLastTerminator' => true,
113
+		'noVariants'         => false,
114
+		'excludeParent'      => true,
115
+		'catPathSeparator'   => ">",
116
+		'customSqlCondition' => '',
117
+		'eol'                => 'LF',
118
+		'notCancelledOnly'   => false,
119
+		'cancelledOderField' => 'OXSTORNO',
120
+);
121
+
122
+	protected $arrConfig = array();
123
+
124
+	protected $blnSkipTrim = false;
125
+
126
+	public function __construct()
127
+	{
128
+		// Get shop config object
129
+		$this->oOxidConfig = $this->getConfig();
130
+
131
+		// Set job config
132
+		$this->arrConfig = array_merge($this->arrDefaultSettings,(is_array($GLOBALS['CONFIG']) ? $GLOBALS['CONFIG'] : array()));
133
+		
134
+		// DB initialization
135
+		$this->db = oxDb::getDb();
136
+		$this->db->SetFetchMode(ADODB_FETCH_ASSOC);
137
+//		$this->db->query("SET character_set_results = '".strtoupper($this->arrConfig['encoding'])."'");
138
+
139
+		// Check config vars
140
+		$blnNotCancelledOnly = ($this->arrConfig['notCancelled'] === true ? true : false);
141
+		$blnCustomSqlCond = ($this->arrConfig['customSqlCondition'] ? true : false);
142
+
143
+		$order_where = '';
144
+		if (count($GLOBALS['EXPORT']['folders']['exclude']) > 0)
145
+		{
146
+			$order_excludes_array = array();
147
+			foreach($GLOBALS['EXPORT']['folders']['exclude_ids'] as $folder)
148
+			{
149
+				$order_excludes_array[] = "'".strtoupper($folder)."'";
150
+			}
151
+			$order_excludes = implode(',',$order_excludes_array);
152
+			$order_where .= ' AND oo.OXFOLDER NOT IN ('.$order_excludes.')';
153
+		}
154
+		if (count($GLOBALS['EXPORT']['folders']['include']) > 0)
155
+		{
156
+			$order_includes_array = array();
157
+			foreach($GLOBALS['EXPORT']['folders']['include'] as $folder)
158
+			{
159
+				$order_includes_array[] = "'".strtoupper($folder)."'";
160
+			}
161
+			$order_includes = implode(',',$order_includes_array);
162
+			$order_where .= ' AND oo.OXFOLDER IN ('.$order_includes.')';
163
+		}
164
+		if ($blnNotCancelledOnly)
165
+		{
166
+			$order_where .= ' AND oo.'.$this->arrConfig['cancelledOderField'].' = 1';
167
+		}
168
+		if ($blnCustomSqlCond)
169
+		{
170
+			$order_where .= ' AND '.$this->arrConfig['customSqlCondition'];
171
+		}
172
+		
173
+		$sql = "SELECT oo.OXID, oo.OXUSERID FROM oxorder AS oo WHERE oo.oxesexported != 1".($order_where ? ' AND '.$order_where : '')." ORDER BY oo.OXORDERDATE";
174
+//		$sql = "SELECT oo.OXID, oo.OXUSERID FROM oxorder AS oo".($order_where ? ' WHERE '.$order_where : '')." ORDER BY oo.OXORDERDATE";
175
+		$rs = $this->db->execute($sql);
176
+
177
+		while($rs && !$rs->EOF)
178
+		{
179
+			$arrRow = $rs->fetchRow();
180
+			$this->_aOrders[] = array('user' => $arrRow['OXUSERID'], 'order' => $arrRow['OXID']);
181
+		}
182
+
183
+
184
+	}
185
+
186
+	function __call($name, $arguments)
187
+	{
188
+		switch ($name)
189
+		{
190
+			case 'getConfigParam':
191
+				return (array_key_exists($arguments[0],$this->arrConfig) ? $this->arrConfig[$arguments[0]] : false);
192
+			break;
193
+
194
+			case 'getJobConfig':
195
+				return $this->arrConfig;
196
+			break;
197
+
198
+			default:
199
+				throw new BadFunctionCallException('Method "'.$name.'" does not exist');
200
+		}
201
+	}
202
+
203
+
204
+	/**
205
+	 * function getCategory
206
+	 *
207
+	 * @return object
208
+	 */
209
+	function getCategory($oxid)
210
+	{
211
+		if (isset($this->_aCategories[$oxid]) && is_object($this->_aCategories[$oxid]))
212
+			return $this->_aCategories[$oxid];
213
+		
214
+		$oCategory = oxNew('oxcategory');
215
+		$oCategory->setLanguage($this->arrConfig['languageid']);
216
+		$oCategory->load($oxid);
217
+
218
+		$this->_aCategories[$oxid] = $oCategory;
219
+		return $this->_aCategories[$oxid];
220
+	}
221
+
222
+	function getCategoryPath($oxid)
223
+	{
224
+		$arrPath = array();
225
+		if (isset($this->_aCategories[$oxid]) && is_object($this->_aCategories[$oxid]))
226
+		{
227
+			$oCategory = &$this->_aCategories[$oxid];
228
+		} else {
229
+			$oCategory = oxNew('oxcategory');
230
+			$oCategory->setLanguage($this->arrConfig['languageid']);
231
+			$oCategory->load($oxid);
232
+
233
+			$this->_aCategories[$oxid] = $oCategory;
234
+
235
+		}
236
+
237
+		$arrPath[] = trim($oCategory->oxcategories__oxtitle->value);
238
+
239
+		if ($oCategory->oxcategories__oxparentid->value != 'oxrootid')
240
+		{
241
+			$arrPath = array_merge($arrPath,$this->getCategoryPath($oCategory->oxcategories__oxparentid->value));
242
+		}
243
+
244
+		return array_reverse($arrPath);
245
+	}
246
+
247
+	/**
248
+	 * function replaceTags
249
+	 *
250
+	 * @return string
251
+	 */
252
+	protected function replaceTags($strBuffer)
253
+	{
254
+		//$tags = preg_split('/{{([^}]+)}}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
255
+		$tags = preg_split('/\{\{(([^\{\}]*|(?R))*)\}\}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
256
+
257
+		$strBuffer = '';
258
+		$arrCache = array();
259
+
260
+		for($_rit=0, $_cnt=count($tags); $_rit<$_cnt; $_rit+=3)
261
+		{
262
+			/*if (!isset($tags[$_rit+1]))
263
+			{
264
+				continue;
265
+			}*/
266
+
267
+			$strBuffer .= $tags[$_rit];
268
+			$strTag = (isset($tags[$_rit+1]) ? $tags[$_rit+1] : '');
269
+
270
+			// Skip empty tags
271
+			if (!strlen($strTag))
272
+			{
273
+				continue;
274
+			}
275
+
276
+			// Load value from cache array
277
+			if (isset($arrCache[$strTag]))
278
+			{
279
+				$strBuffer .= $arrCache[$strTag];
280
+				continue;
281
+			}
282
+
283
+			// Run the replacement again if there are more tags (see #4402)
284
+			if (strpos($strTag, '{{') !== false)
285
+			{
286
+				$strTag = $this->replaceTags($strTag);
287
+			}
288
+
289
+			$elements = explode('::', $strTag);
290
+
291
+			$arrCache[$strTag] = '';
292
+
293
+			// Replace tag
294
+			switch (strtolower($elements[0]))
295
+			{
296
+				case 'parent':
297
+					if (is_null($this->currentArticle['parent']))
298
+					{
299
+						if (is_null($this->currentArticle['article']))
300
+						{
301
+							$this->currentArticle['article'] = $this->currentArticle['orderarticle']->getArticle();
302
+						}
303
+						if (!is_null($this->currentArticle['article']))
304
+						{
305
+							$this->currentArticle['parent'] = $this->currentArticle['article']->getParentArticle();
306
+						}
307
+					}
308
+					if (!is_null($this->currentArticle['parent']))
309
+					{
310
+						$arrCache[$strTag] = $this->currentArticle['parent']->{'oxarticles__'.strtolower($elements[1])}->value;
311
+					}
312
+					break;
313
+
314
+				case 'article':
315
+					if (is_null($this->currentArticle['article']))
316
+					{
317
+						$this->currentArticle['article'] = $this->currentArticle['orderarticle']->getArticle();
318
+					}
319
+					if (!is_null($this->currentArticle['article']))
320
+					{
321
+						$arrCache[$strTag] = $this->currentArticle['article']->{'oxarticles__' . strtolower($elements[1])}->value;
322
+					}
323
+					break;
324
+
325
+				case 'orderarticle':
326
+					$arrCache[$strTag] = $this->currentArticle['orderarticle']->{'oxorderarticles__'.strtolower($elements[1])}->value;
327
+					break;
328
+
329
+				case 'orderarticlepos':
330
+					$arrCache[$strTag] = $this->currentArticle['orderarticlepos'];
331
+					break;
332
+
333
+				case 'order':
334
+					$arrCache[$strTag] = $this->currentArticle['order']->{'oxorder__'.strtolower($elements[1])}->value;
335
+					break;
336
+
337
+				case 'user':
338
+					$arrCache[$strTag] = $this->currentArticle['user']->{'oxuser__'.strtolower($elements[1])}->value;
339
+					break;
340
+
341
+				case 'inheritance':
342
+					if (!$this->currentArticle['article']->{'oxarticles__'.strtolower($elements[1])}->value)
343
+					{
344
+						if (is_null($this->currentArticle['parent']))
345
+						{
346
+							if (is_null($this->currentArticle['article']))
347
+							{
348
+								$this->currentArticle['article'] = $this->currentArticle['orderarticle']->getArticle();
349
+							}
350
+							if (!is_null($this->currentArticle['article']))
351
+							{
352
+								$this->currentArticle['parent'] = $this->currentArticle['article']->getParentArticle();
353
+							}
354
+						}
355
+						$arrCache[$strTag] = (!$this->currentArticle['parent'] ? '' : $this->currentArticle['parent']->{'oxarticles__'.strtolower($elements[1])}->value);
356
+					} else {
357
+						$arrCache[$strTag] = $this->currentArticle['article']->{'oxarticles__'.strtolower($elements[1])}->value;
358
+					}
359
+					break;
360
+
361
+				case 'category':
362
+					if (is_null($this->currentArticle['category']))
363
+					{
364
+						if (is_null($this->currentArticle['article']))
365
+						{
366
+							$this->currentArticle['article'] = $this->currentArticle['orderarticle']->getArticle();
367
+						}
368
+						if (!is_null($this->currentArticle['article']))
369
+						{
370
+							$this->currentArticle['category'] = $this->currentArticle['article']->getCategory();
371
+						}
372
+					}
373
+					if (!is_null($this->currentArticle['category']))
374
+					{
375
+						$arrCache[$strTag] = $this->currentArticle['category']->{'oxcategories__' . strtolower($elements[1])}->value;
376
+					}
377
+					break;
378
+
379
+				case 'categorypath':
380
+					$arrCache[$strTag] = implode($this->arrConfig['catPathSeparator'],$this->getCategoryPath($this->currentArticle['category']->oxcategories__oxid->value));
381
+					break;
382
+
383
+				case 'crossselling':
384
+					$oCrossSelling = $this->currentArticle['article']->getCrossSelling();
385
+					$arrCrossSelling = array();
386
+					if (!is_null($oCrossSelling) && $intLimit = $oCrossSelling->count())
387
+					{
388
+						if (isset($elements[1]))
389
+						{
390
+							$intLimit = intval($elements[1]);
391
+						}
392
+
393
+						$i=0;
394
+						while ($oCrossSelling->valid() && $i < $intLimit)
395
+						{
396
+							if ($oCrossSelling->current()->getVariants())
397
+							{
398
+								$arrCrossSelling[] = $oCrossSelling->current()->oxarticles__oxartnum->value.'__parent';
399
+							} else {
400
+								$arrCrossSelling[] = $oCrossSelling->current()->oxarticles__oxartnum->value;
401
+							}
402
+							$oCrossSelling->next();
403
+							$i++;
404
+						}
405
+					}
406
+					$arrCache[$strTag] = implode(',',$arrCrossSelling);
407
+					break;
408
+					
409
+				case 'db_foreign':
410
+					if (isset($elements[1]) && isset($elements[2]) && ($chunks = explode('=',$elements[1])))
411
+					{
412
+						list($foreign_table, $foreign_field) = explode('.',$chunks[0]);
413
+						$foreign_keyValue = $this->currentArticle['article']->{'oxarticles__'.strtolower($chunks[1])}->value;
414
+						if (($sViewName = getViewName($foreign_table, $this->arrConfig['languageid'])))
415
+						{
416
+							$sDbValue = $this->db->getOne("select ".$elements[2]." from {$sViewName} where ".$foreign_field." = " . $this->db->quote($foreign_keyValue));
417
+
418
+						} else {
419
+							$sDbValue = $this->db->getOne("select ".$elements[2]." from {$foreign_table} where ".$foreign_field." = " . $this->db->quote($foreign_keyValue));
420
+
421
+						}/* else {
422
+							$sql = "SELECT * FROM ".$foreign_table." WHERE ".$foreign_field."='".$foreign_keyValue."'";
423
+
424
+							$resSql = $this->db->execute($sql);
425
+
426
+							$arrCache[$strTag] = ($resSql->recordCount() < 1) ? '' : $resSql->fields($elements[2]);
427
+						}*/
428
+						if ($sDbValue)
429
+						{
430
+							$oForeign = new oxField();
431
+							$oForeign->setValue($sDbValue, oxField::T_RAW);
432
+
433
+							$arrCache[$strTag] = $oForeign->value;
434
+						}
435
+
436
+
437
+						unset($resSql,$oForeign);
438
+					}
439
+					break;
440
+
441
+				case 'link':
442
+					switch(strtolower($elements[1]))
443
+					{
444
+						case 'article':
445
+							if ( oxRegistry::getUtils()->seoIsActive() )
446
+							{
447
+								$arrCache[$strTag] = preg_replace('/(?<=\.html)\?.*$/', '', $this->currentArticle['article']->getMainLink());
448
+							} else {
449
+								$arrCache[$strTag] = $this->currentArticle['article']->getMainLink();
450
+							}
451
+							break;
452
+						case 'category':
453
+							if ( oxRegistry::getUtils()->seoIsActive() )
454
+							{
455
+								$arrCache[$strTag] = preg_replace('/(?<=\.html)\?.*$/', '', $this->currentArticle['category']->getMainLink());
456
+							} else {
457
+								$arrCache[$strTag] = $this->currentArticle['category']->getMainLink();
458
+							}
459
+							break;
460
+					}
461
+					break;
462
+
463
+				case 'image':
464
+					switch(strtolower($elements[1]))
465
+					{
466
+						case 'article':
467
+							switch(strtolower($elements[2]))
468
+							{
469
+								case 'thumb':
470
+									$arrCache[$strTag] = $this->currentArticle['article']->getThumbnailUrl();
471
+									break;
472
+								case 'icon':
473
+									$arrCache[$strTag] = $this->currentArticle['article']->getIconUrl();
474
+									break;
475
+								default:
476
+									$arrCache[$strTag] = ($this->currentArticle['article']->{'oxarticles__oxpic'.$elements[2]}->value ? $this->currentArticle['article']->getZoomPictureUrl(intval($elements[2])) : '');
477
+									break;
478
+							}
479
+							break;
480
+						case 'category':
481
+							$arrCache[$strTag] = '';
482
+							break;
483
+					}
484
+					break;
485
+
486
+				case 'db_if':
487
+					if (isset($elements[1]) && isset($elements[2]) && isset($elements[3]) && isset($elements[4]))
488
+					{
489
+						
490
+						$db_value = $this->currentArticle['article']->{'oxarticles__'.strtolower($elements[1])}->value;
491
+						if (isset($elements[5]))
492
+						{
493
+							$varVal = $elements[4];
494
+							$varAltVal = $elements[5];
495
+						} else {
496
+							$varVal = $db_value;
497
+							$varAltVal = $elements[4];
498
+						}
499
+						switch($elements[2])
500
+						{
501
+							case '>':
502
+								$arrCache[$strTag] = ($db_value > $elements[3]) ? $varVal : $varAltVal;
503
+								break;
504
+							case '>=':
505
+								$arrCache[$strTag] = ($db_value >= $elements[3]) ? $varVal : $varAltVal;
506
+								break;
507
+							case '<':
508
+								$arrCache[$strTag] = ($db_value < $elements[3]) ? $varVal : $varAltVal;
509
+								break;
510
+							case '<=':
511
+								$arrCache[$strTag] = ($db_value <= $elements[3]) ? $varVal : $varAltVal;
512
+								break;
513
+							case '=':
514
+								$arrCache[$strTag] = ($db_value == $elements[3]) ? $varVal : $varAltVal;
515
+								break;
516
+							case '!=':
517
+								$arrCache[$strTag] = ($db_value != $elements[3]) ? $varVal : $varAltVal;
518
+								break;
519
+						}
520
+					}
521
+					break;
522
+
523
+				case 'not_empty':
524
+					if (isset($elements[1]) && isset($elements[2]))
525
+					{
526
+						if ($elements[1])
527
+						{
528
+							$arrCache[$strTag] = $elements[2];
529
+						} else {
530
+							$arrCache[$strTag] = '';
531
+						}
532
+					}
533
+					break;
534
+
535
+				case 'fixval':
536
+					$arrCache[$strTag] = $elements[1];
537
+					break;
538
+
539
+				case 'has_variants':
540
+					if (isset($elements[1]) && isset($elements[2]))
541
+					{
542
+						$arrCache[$strTag] = ($this->currentArticle['hasVariants'] ? $elements[1] : $elements[2]);
543
+					}
544
+					break;
545
+
546
+				case 'parse_smarty':
547
+					$arrCache[$strTag] = oxRegistry::get("oxUtilsView")->parseThroughSmarty($elements[1], basename($this->arrConfig['filename']) . $this->arrConfig['languageid'], null, true);
548
+					break;
549
+
550
+				case 'fstring':
551
+					if (isset($elements[1]) && isset($elements[2]))
552
+					{
553
+						$this->blnSkipTrim = true;
554
+						//$strFstring = call_user_func_array("sprintf",array_slice($elements,1,2));
555
+						$strFstring = sprintf($elements[1],$this->convert($elements[2]));
556
+						if (isset($elements[3]))
557
+						{
558
+							$strFstring = substr($strFstring,0,$elements[3]);
559
+						}
560
+						$arrCache[$strTag] = $this->convert($strFstring,'utf-8');
561
+					}
562
+					break;
563
+
564
+				case 'fdate':
565
+					if (isset($elements[1]) && isset($elements[2]))
566
+					{
567
+						$oDate = new DateTime($elements[2]);
568
+						if (is_object($oDate))
569
+						$arrCache[$strTag] = $oDate->format($elements[1]);
570
+					}
571
+					break;
572
+
573
+				case 'price':
574
+					if (isset($elements[1]))
575
+					{
576
+						$oPrice = oxNew( 'oxPrice' );
577
+						$blPriceNet = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
578
+						if ($blPriceNet)
579
+						{
580
+							$oPrice->setNettoPriceMode();
581
+						} else {
582
+							$oPrice->setBruttoPriceMode();
583
+						}
584
+
585
+						$oPrice->setPrice(doubleval($elements[1]));
586
+
587
+						if (isset($elements[2]))
588
+						{
589
+							switch ($elements[2])
590
+							{
591
+								case 'net':
592
+								case 'netto':
593
+									$arrCache[$strTag] = $oPrice->getNettoPrice();
594
+									break;
595
+
596
+								case 'gross':
597
+								case 'brutto':
598
+									$arrCache[$strTag] = $oPrice->getBruttoPrice();
599
+									break;
600
+
601
+								default:
602
+									$arrCache[$strTag] = $oPrice->getPrice();
603
+									break;
604
+							}
605
+						}
606
+					}
607
+					break;
608
+
609
+				case 'oxcountry':
610
+					if (isset($elements[1]) && isset($elements[2]))
611
+					{
612
+						$oCountry = oxNew('oxcountry');
613
+						$oCountry->load($elements[2]);
614
+
615
+						$arrCache[$strTag] = $oCountry->{'oxcountry__'.strtolower($elements[1])}->value;
616
+					}
617
+					break;
618
+
619
+				case 'translate':
620
+					if (isset($elements[1]) && isset($elements[2]))
621
+					{
622
+						if (isset($GLOBALS['EXPORT']['translate'][$elements[1]][$elements[2]]))
623
+						{
624
+							$arrCache[$strTag] = $GLOBALS['EXPORT']['translate'][$elements[1]][$elements[2]];
625
+						}
626
+					}
627
+					break;
628
+
629
+				case 'eval':
630
+					if (isset($elements[1]))
631
+					{
632
+						ob_start();
633
+						eval('echo ('.$elements[1].');');
634
+
635
+						$arrCache[$strTag] = ob_get_contents();
636
+						ob_end_clean();
637
+					}
638
+					break;
639
+			}
640
+
641
+			$strBuffer .= $arrCache[$strTag];
642
+		}
643
+
644
+		return $strBuffer;
645
+	}
646
+	
647
+	protected function parseLine($arrArticle,$strFieldConf='fields')
648
+	{
649
+
650
+		$oArticle = oxNew('oxorderarticle');
651
+		$oArticle->load($arrArticle['orderarticle']);
652
+		$oOrder = oxNew('oxorder');
653
+		$oOrder->load($arrArticle['order']);
654
+		$oUser = oxNew('oxuser');
655
+		$oUser->load($arrArticle['user']);
656
+
657
+		$this->currentArticle = array
658
+		(
659
+			'order'           => $oOrder,
660
+			'orderarticle'    => $oArticle,
661
+			'orderarticlepos' => $arrArticle['orderarticlepos'],
662
+			'user'            => $oUser,
663
+			'article'         => null,
664
+			'category'        => null,
665
+			'parent'          => null
666
+		);
667
+
668
+		$this->blnSkipTrim = false;
669
+		$strLine = '';
670
+		$index = 0;
671
+		foreach($GLOBALS['EXPORT'][$strFieldConf] as $field)
672
+		{
673
+			$field = $this->replaceTags($field);
674
+			$field = $this->encapsulate($field, ($this->arrConfig['skipLastTerminator'] && ++$index == count($GLOBALS['EXPORT']['fields']) ? true : false));
675
+//			$field = mb_convert_encoding($field, strtoupper($this->arrConfig['encoding']), 'UTF-8');
676
+			$strLine .= $this->convert($field);
677
+		}
678
+		return $strLine.(strtoupper($this->arrConfig['eol']) == 'CRLF' ? "\r\n" : "\n");
679
+	}
680
+	
681
+	public function encapsulate($strVal, $blnSkipTerminator=false)
682
+	{
683
+		$strSrcEncoding = mb_detect_encoding($strVal,"UTF-8,".$this->arrConfig['encoding'].",cp1252,cp1251,cp1250,iso-8859-1,iso-8859-15",true);
684
+
685
+		if (!$this->blnSkipTrim)
686
+		{
687
+			$strVal = trim($strVal);
688
+		}
689
+		$strVal = preg_replace('/[\\n\\r]/', '<br />', $strVal);
690
+		if ($this->arrConfig['stripHTML'])
691
+		{
692
+			if ($this->arrConfig['strictStrip']) {
693
+				$strVal = preg_replace('/(<br\s*(|\/)\s*>)+/i', ' ', $strVal);
694
+				$strVal = preg_replace('/(<p\s*(|\/)\s*>)+/i', ' ', $strVal);
695
+				$strVal = strip_tags($strVal);
696
+				$strVal = mb_convert_encoding($strVal, 'HTML-ENTITIES', $strSrcEncoding);
697
+				if (!$this->blnSkipTrim)
698
+				{
699
+					$strVal = trim(preg_replace('/[\xa0\s]+/', ' ', $strVal));
700
+				}
701
+				$strVal = str_ireplace('&nbsp;','',$strVal);
702
+			} else {
703
+				$strVal = strip_tags($strVal,'<br><p>');
704
+				$strVal = preg_replace('/(<br\s*(|\/)\s*>){2,}/', '<br>', $strVal);
705
+			}
706
+		}
707
+		$strVal = str_replace($this->arrConfig['field_encloser'],$this->arrConfig['escape_char'].$this->arrConfig['field_encloser'],$strVal);
708
+		if (strlen($strVal))
709
+		{
710
+			$strVal = preg_replace('/(^|$)/',$this->arrConfig['field_encloser'],$strVal);
711
+		} else {
712
+			$strVal = $this->arrConfig['field_encloser'].$this->arrConfig['field_encloser'];
713
+		}
714
+		
715
+		return $strVal.($blnSkipTerminator ? '' : $this->arrConfig['field_terminator']);
716
+	}
717
+
718
+	protected function convert($strValue, $strCharset = null)
719
+	{
720
+		if (is_null($strCharset))
721
+		{
722
+			$strCharset = strtoupper($this->arrConfig['encoding']);
723
+		} else {
724
+			$strCharset = strtoupper($strCharset);
725
+		}
726
+
727
+		$strSrcEncoding = mb_detect_encoding($strValue,"UTF-8,".$this->arrConfig['encoding'].",cp1252,cp1251,cp1250,iso-8859-1,iso-8859-15",true);
728
+		return ($strSrcEncoding == $strCharset) ? $strValue : mb_convert_encoding($strValue, $strCharset, $strSrcEncoding);
729
+	}
730
+
731
+	protected function getHeader()
732
+	{
733
+		$strHeader = '';
734
+		$index = 0;
735
+		foreach(array_keys($GLOBALS['EXPORT']['fields']) as $field)
736
+		{
737
+			$field = $this->encapsulate($field, ($this->arrConfig['skipLastTerminator'] && ++$index == count($GLOBALS['EXPORT']['fields']) ? true : false));
738
+			$strHeader .= $this->convert($field);
739
+		}
740
+		return $strHeader."\n";
741
+	}
742
+	
743
+	public function getCSV()
744
+	{
745
+		// echo 'Datensätze: '.count($this->arrDB)."\n";
746
+		$strBuffer = ($this->arrConfig['includeHeader']) ? $this->getHeader() : '';
747
+		foreach($this->arrDB as $this->arrRow)
748
+		{
749
+			$strBuffer .= $this->parseLine($this->arrRow);
750
+		}
751
+		return $strBuffer;
752
+	}
753
+	
754
+	public function saveCSV()
755
+	{
756
+		$tmpname = sys_get_temp_dir().'/'.hash('crc32', uniqid(microtime()));
757
+		$count = 0;
758
+
759
+		if (count($this->_aOrders) < 1)
760
+		{
761
+			return $count;
762
+		}
763
+
764
+		//$fh = fopen($tmpname,"a");
765
+		$fh = fopen(getShopBasePath() . $this->arrConfig['filename'],"a");
766
+		
767
+		fputs($fh,(($this->arrConfig['includeHeader']) ? $this->getHeader() : ''));
768
+
769
+		foreach($this->_aOrders as $order)
770
+		{
771
+			$this->_aArticles = array();
772
+			$sql = "SELECT OXID FROM oxorderarticles AS ooa WHERE ooa.OXORDERID = " . $this->db->quote($order['order']) . " ORDER BY ooa.OXARTNUM";
773
+			$rs = $this->db->execute($sql);
774
+
775
+			while ($rs && !$rs->EOF)
776
+			{
777
+				$arrRow = $rs->fetchRow();
778
+				$this->_aArticles[] = array_merge($order,array('orderarticle'=>$arrRow['OXID'], 'orderarticlepos'=>count($this->_aArticles)+1));
779
+			}
780
+
781
+			foreach ($this->_aArticles as $article)
782
+			{
783
+				// echo $article['article']->oxarticles__oxtitle->value."\n";
784
+				// echo $article['category']->oxcategories__oxtitle->value."\n\n";
785
+				fputs($fh, $this->parseLine($article));
786
+			}
787
+
788
+			// Shipping costs
789
+			$aShipping = $article;
790
+			$aShipping['orderarticlepos'] = $aShipping['orderarticlepos']+1;
791
+			fputs($fh, $this->parseLine($aShipping,'shipping'));
792
+
793
+			$sql = "UPDATE oxorder SET oxesexported = 1 WHERE oxid = " . $this->db->quote($order['order']) . "";
794
+			$rs = $this->db->execute($sql);
795
+
796
+			$count += count($this->_aArticles);
797
+		}
798
+		
799
+		fclose($fh);
800
+		/*if (!rename($tmpname, getShopBasePath() . $this->arrConfig['filename']))
801
+		{
802
+			die('Export file could not be created');
803
+		}*/
804
+			
805
+		return $count;
806
+	}
807
+}
808
+
809
+
810
+$Export = new Export();
811
+$intArticles = $Export->saveCSV();
812
+
813
+header('Content-Type: text/plain; charset='.$Export->getConfigParam['encoding']);
814
+echo "Items exported: " . $intArticles."\n";
815
+
816
+$intMemory = memory_get_peak_usage(true);
817
+$hrsize = function($intMemory) {
818
+	$kilobyte = 1024;
819
+	$megabyte = $kilobyte * 1024;
820
+	$gigabyte = $megabyte * 1024;
821
+	$terabyte = $gigabyte * 1024;
822
+	$precision = 2;
823
+	$bytes = $intMemory;
824
+
825
+	if (($bytes >= 0) && ($bytes < $kilobyte)) {
826
+		return $bytes . ' B';
827
+
828
+	} elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
829
+		return round($bytes / $kilobyte, $precision) . ' KB';
830
+
831
+	} elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
832
+		return round($bytes / $megabyte, $precision) . ' MB';
833
+
834
+	} elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
835
+		return round($bytes / $gigabyte, $precision) . ' GB';
836
+
837
+	} elseif ($bytes >= $terabyte) {
838
+		return round($bytes / $terabyte, $precision) . ' TB';
839
+	} else {
840
+		return $bytes . ' B';
841
+	}
842
+};
843
+
844
+echo "Memory used for export: " . $hrsize($intMemory)."\n";
0 845
\ No newline at end of file