Projekt

Allgemein

Profil

GX-Bug #60215 » functions.php

Wilken Haase, 18.05.2019 22:57

 
1
<?php
2
/* --------------------------------------------------------------
3
   Yoochoose GmbH
4
   http://www.yoochoose.com
5
   Copyright (c) 2011 Yoochoose GmbH
6
   Released under the GNU General Public License (Version 2)
7
   [http://www.gnu.org/licenses/gpl-2.0.html]
8
   -------------------------------------------------------------- */
9

    
10

    
11
define('YOOCHOOSE_VERSION', '1.0.0');
12

    
13
define('YOOCHOOSE_PHP_REQUIRED', '5.2.0');
14

    
15

    
16
define('YOOCHOOSE_HOMEPAGE_PERSONALIZED_STRATEGY',    'landing_page_personalized');
17
define('YOOCHOOSE_HOMEPAGE_TOPSELLERS_STRATEGY',      'landing_page_topsellers');
18
define('YOOCHOOSE_CATEGORY_TOPSELLERS_STRATEGY',      'category_topsellers');
19
define('YOOCHOOSE_PRODUCT_ALSO_PURCHASED_STRATEGY',   'also_purchased');
20
define('YOOCHOOSE_PRODUCT_ALSO_INTERESTING_STRATEGY', 'also_interesting');
21
define('YOOCHOOSE_SHOPPING_CART_STRATEGY',            'shopping_cart');
22

    
23
define('YOOCHOOSE_EVENT_SERVER_DEFAULT', 'https://event.yoochoose.net');
24
define('YOOCHOOSE_RECO_SERVER_DEFAULT', 'https://reco.yoochoose.net');
25
define('YOOCHOOSE_REG_SERVER_DEFAULT', 'https://config.yoochoose.net');
26

    
27

    
28
function yoochooseDefaultHeader($box_name, $lang_id = -1) {
29

    
30
	$result = array();
31

    
32
	$result['HOMEPAGE_PERSONALIZED']   = array(1 => "Recommendations for you",
33
		                                       2 => "Empfehlungen für Sie");
34
	$result['HOMEPAGE_TOPSELLERS']     = array(1 => "Bestsellers",
35
		                                       2 => "Bestsellers");
36
	$result['CATEGORY_TOPSELLERS']     = array(1 => "Bestsellers in {0}",
37
		                                       2 => "Bestsellers in {0}");
38
	$result['PRODUCT_ALSO_INTERESTING']= array(1 => "It could be also interesting for you",
39
		                                       2 => "Das könnte Sie auch interessieren");
40
	$result['SHOPPING_CART']           = array(1 => "It could be also interesting for you",
41
		                                       2 => "Das könnte Sie auch interessieren");
42

    
43
	$result_default = array(1 => "We recommend",
44
                            2 => "Wir empfehlen");
45

    
46
    $lang_id = $lang_id != -1 ? $lang_id : $_SESSION['languages_id'];
47

    
48
	if (array_key_exists($box_name, $result)) {
49
		if (array_key_exists($lang_id, $result[$box_name])) {
50
			return $result[$box_name][$lang_id];
51
		} else {
52
			return $result[$box_name][1];
53
		}
54
	} else {
55
		if (array_key_exists($lang_id, $result_default)) {
56
			return $result_default[$lang_id];
57
		} else {
58
			return $result_default[1];
59
		}
60
	}
61
}
62

    
63

    
64
function yoochooseUnwrapId($recomendedObjects) {
65
	$in = array();
66
	if ($recomendedObjects) {
67
		foreach ($recomendedObjects as $item) {
68
			$itemId = $item["PRODUCTS_ID"];
69
		    $in[] = $itemId;
70
		}
71
	}
72
	return $in;
73
}
74

    
75

    
76
/** Returns language object by gambio language numeric ID.
77
 *  Returns current language (from SESSION), if no ID specified.
78
 **/
79
function yoochooseLang($lang_id = -1) {
80
	global $languages;
81

    
82
	$lang_id = $lang_id != -1 ? $lang_id : $_SESSION['languages_id'];
83

    
84
	$default = null;
85

    
86
    foreach ($languages as $lang) {
87
    	$id = $lang['id'];
88
    	if ($id == $lang_id) {
89
    		return $lang;
90
    	}
91
    	if ($default = null || $default['id'] > $id) {
92
    		$default = $lang;
93
    	}
94
    }
95

    
96
    return $default;
97
}
98

    
99

    
100
function getYoochooseHeader($box_name, $lang_id = -1) {
101
	$header_key = getYoochooseHeaderConstantName($box_name);
102

    
103
	$id = $lang_id != -1 ? $lang_id : $_SESSION['languages_id'];
104

    
105
	$from_db = gm_get_content($header_key, $id);
106

    
107
	return $from_db ? $from_db : yoochooseDefaultHeader($box_name, $lang_id);
108
}
109

    
110

    
111
/** Returns an amount of items to show in Top Selling box. */
112
function getBoxTopSellingMaxDisplay() {
113
    $srvEvent;
114
    if (defined('YOOCHOOSE_BOX_TOP_SELLING_MAX_DISPLAY')) {
115
       $srvEvent = YOOCHOOSE_BOX_TOP_SELLING_MAX_DISPLAY;
116
    } else {
117
       $srvEvent = YOOCHOOSE_BOX_TOP_SELLING_MAX_DISPLAY_DEFAULT;
118
    }
119
    return trimSlash($srvEvent);
120
}
121

    
122

    
123
function getMaxDisplayConstantName($box_name) {
124
	return 'YOOCHOOSE_'.$box_name.'_MAX_DISPLAY';
125
}
126

    
127

    
128
function getYoochooseStategyConstantName($box_name) {
129
	return 'YOOCHOOSE_'.$box_name.'_STRATEGY';
130
}
131

    
132

    
133
function getYoochooseHeaderConstantName($box_name) {
134
	return 'YOOCHOOSE_'.$box_name.'_HEADER';
135
}
136

    
137

    
138
/** Returns an amount of items to show in Top Selling box. */
139
function getYoochooseStrategy($box_name) {
140
	return constant('YOOCHOOSE_'.$box_name.'_STRATEGY');
141
}
142

    
143

    
144
function getMaxDisplayDefaultValue($box_name) {
145
    if ($box_name == 'BOX_TOP_SELLING' || $box_name == 'BOX_ALSO_CLICKED') {
146
    	return 0;
147
    } else {
148
    	return 4;
149
    }
150
}
151

    
152

    
153
/** Returns an amount of items to show in Top Selling box. */
154
function getMaxDisplay($box_name) {
155

    
156
	$const = getMaxDisplayConstantName($box_name);
157
    $srvEvent;
158
    if (defined($const)) {
159
       $srvEvent = constant($const);
160
    } else {
161
        $srvEvent = getMaxDisplayDefaultValue($box_name);
162
    }
163
    return trimSlash($srvEvent);
164
}
165

    
166

    
167
// for backward compatibility
168
function getAlsoPurchasedStrategy() {
169
	return 'also_purchased';
170
}
171

    
172

    
173
function phpVersionAsInt($phpVersion) {
174
    $version = explode('.', $phpVersion);
175
    return $version[0] * 10000 + @$version[1] * 100 + @$version[2];
176
}
177

    
178

    
179

    
180
/** Loads URL as JSON object.
181
 *  Throws IOException or JSONException, if problems. */
182
function load_json_url_ex(
183
        $url,
184
        array $options = array()) {
185

    
186
    $loaded = load_url_ex($url, $options);
187
    $result = json_decode($loaded);
188
    if ($result == null) {
189
    	$errorMessage = "Unable to decode JSON decode the text [".trimLoaded($loaded)."].";
190
    	if (function_exists("json_last_error")) {
191
    		$errorMessage .= " Cause: ".JSONException::decodeJSONMessage(json_last_error());
192
    		throw new JSONException($errorMessage, json_last_error());
193
    	} else {
194
    		$errorMessage .= " Cause is unavaliable.";
195
    		throw new JSONException($errorMessage, 0);
196
    	}
197
    }
198
    return $result;
199
}
200

    
201

    
202
/** Trims and cuts first 20 symbols from the specified string.
203
 *  Adds trailing "...", if the trimmed string was longer.
204
 */
205
function trimLoaded($loaded) {
206

    
207
	$resultLength = 20;
208
	$trimmed = trim($loaded);
209
	$result = substr($trimmed, 0, $resultLength);
210

    
211
	return strlen($trimmed) > $resultLength ? $result.'...' : $result;
212
}
213

    
214

    
215

    
216
/**
217
 * Send a GET requst using cURL
218
 * Throws IOException, if something goes worng
219
 *
220
 * @param string $url to request
221
 * @param array $options for cURL
222
 */
223
function load_url_ex($url, array $options = array()) {
224
    if (!defined('YOOCHOOSE_ID') || defined (!'YOOCHOOSE_SECRET')){
225
		return;
226
	}
227
	
228
	$def_user = YOOCHOOSE_ID;
229
    $def_pw   = YOOCHOOSE_SECRET;
230
    $defaults = array(
231
        CURLOPT_URL => $url,
232
        CURLOPT_HEADER => 0,
233
        CURLOPT_RETURNTRANSFER => TRUE,
234
        CURLOPT_TIMEOUT => 5,
235
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
236
        CURLOPT_USERPWD => "$def_user:$def_pw",
237
        CURLOPT_SSL_VERIFYPEER => FALSE,
238
        CURLOPT_FAILONERROR => TRUE
239
   		// CURLOPT_FOLLOWLOCATION - not allowed
240
   		// See http://slopjong.de/2012/03/31/curl-follow-locations-with-safe_mode-enabled-or-open_basedir-set
241
    );
242

    
243
    just_log_recommendation(E_NOTICE, "Requesting: [".$url."] as [".$def_user."].");
244

    
245
    $ch = curl_init();
246
    $options = $options + $defaults; // numeric arrays. Do not use merge_arrays!
247
    curl_setopt_array($ch, $options);
248
    if (!$result = curl_exec($ch)) {
249
        throwIO(curl_error($ch), curl_errno($ch));
250
    }
251
    curl_close($ch);
252

    
253
    return $result;
254
}
255

    
256

    
257

    
258
/**
259
 * Creates a string containing the category path to the current product.
260
 * It relies on the current status of $breadcrumb.
261
 *
262
 * The path is already URL-encoded.
263
 */
264
function getCurrentPath() {
265
	global $breadcrumb;
266
	global $product;
267

    
268
	if (! isset($breadcrumb)) {
269
		return null;
270
	}
271

    
272
	$prod = isset($product) && $product->isProduct() ? 1 : 0;
273

    
274
    $raw_path = $breadcrumb->_trail;
275
    if (count($raw_path)<2) return "";
276
    $result = '';
277
    for ($i=1 ; $i<=count($raw_path)-1-$prod ; $i++) {
278
        $result .= '/'.$raw_path[$i]['title'];
279
    }
280
    return urlencode($result);
281
}
282

    
283

    
284

    
285

    
286
/** Returns an URL to event server (without a trailing slash).
287
 *  Returns a property from the database or a default value. */
288
function getEventServerUrl() {
289
	$srvEvent;
290
	if (defined('YOOCHOOSE_EVENT_SERVER')) {
291
	   $srvEvent = YOOCHOOSE_EVENT_SERVER;
292
	} else {
293
	   $srvEvent = YOOCHOOSE_EVENT_SERVER_DEFAULT;
294
	}
295
	return trimSlash($srvEvent);
296
}
297

    
298

    
299
/** Returns an URL to reco server (without a trailing slash).
300
 *  Returns a property from the database or a default value. */
301
function getRecoServerUrl() {
302
    $srvEvent;
303
    if (defined('YOOCHOOSE_RECO_SERVER')) {
304
       $srvEvent = YOOCHOOSE_RECO_SERVER;
305
    } else {
306
       $srvEvent = YOOCHOOSE_RECO_SERVER_DEFAULT;
307
    }
308
    return trimSlash($srvEvent);
309
}
310

    
311

    
312
/** Returns an URL to reg server (without a trailing slash).
313
 *  Returns a property from the database or a default value. */
314
function getRegServerUrl() {
315
    $srvEvent;
316
    if (defined('YOOCHOOSE_REG_SERVER')) {
317
       $srvEvent = YOOCHOOSE_REG_SERVER;
318
    } else {
319
       $srvEvent = YOOCHOOSE_REG_SERVER_DEFAULT;
320
    }
321
    return trimSlash($srvEvent);
322
}
323

    
324

    
325
define('YOOCHOOSE_LOG_LEVEL_DEFAULT', E_ERROR + E_WARNING);
326

    
327

    
328
/** Returns a bit mask defines the messages to log.<br>
329
 *  There is thee types: E_ERROR, E_WARNING, E_NOTICE<br>
330
 *  By default returns: E_ERROR + E_WARNING<br>
331
 *  */
332
function getYooLogLevel() {
333
    $result;
334
    if (defined('YOOCHOOSE_LOG_LEVEL')) {
335
       $result = YOOCHOOSE_LOG_LEVEL;
336
    } else {
337
       $result = YOOCHOOSE_LOG_LEVEL_DEFAULT;
338
    }
339
    return $result;
340
}
341

    
342

    
343

    
344

    
345
/** Returns true, if the admin mode was activated. To activate the database
346
 *  set the property YOOCHOOSE_ADMIN_MODE to true.
347
 */
348
function isAdminMode() {
349
    if (defined('YOOCHOOSE_ADMIN_MODE')) {
350
        return YOOCHOOSE_ADMIN_MODE ? true : false;
351
    } else {
352
        return false;
353
    }
354
}
355

    
356

    
357

    
358
/** Trims all the traling slashes (both back and forward slashes).
359
 *  Useful, if you have a path and do not know, if if ends with a slash or not. */
360
function trimSlash($path) {
361
    return rtrim($path,'/\\');
362
}
363

    
364

    
365
function yooProductProperty($item, $property) {
366
	if (is_object($item)) {
367
		$item = $item->data;
368
	}
369

    
370
	if (is_array($item)) {
371
		foreach ($item as $key => $value) {
372
			if (strtolower($key) == strtolower($property)) {
373
				return $value;
374
			}
375
		}
376
	}
377

    
378
	return null;
379
}
380

    
381

    
382

    
383
/**
384
 * Creates the tracking URL based on given parameters
385
 */
386
function getTrackingURL($event_type, $item) {
387

    
388
	$item_id = yooProductProperty($item, 'products_id');
389

    
390
	$userid = getCurrentUserId();
391

    
392
    $result = getEventServerUrl().'/ebl/'.YOOCHOOSE_ID.'/'.$event_type.'/'.$userid .'/1/'.$item_id;
393

    
394
    $query_string = array();
395

    
396
    if ($event_type == 'click') {
397
	    $category_path = getCurrentPath();
398
	    if ($category_path) {
399
	        $query_string['categorypath'] = $category_path;
400
	    }
401
    }
402

    
403
    if ($event_type == 'buy') {
404
    	$p = yooProductProperty($item, 'products_price');
405
    	if ($p) {
406
    		$query_string['fullprice'] = $p;
407
    	}
408
    	$q = yooProductProperty($item, 'products_quantity');
409
    	if ($q) {
410
    		$query_string['quantity'] = $q ;
411
    	}
412
    }
413

    
414
    if ($event_type == 'follow' && array_key_exists('ycr', $_GET)) {
415
    	$query_string['scenario'] = $_GET['ycr'] ;
416
    }
417

    
418
    if (sizeof($query_string) > 0) {
419
    	$result = $result.'?'.http_build_query($query_string);
420
    }
421

    
422
    just_log_recommendation(E_NOTICE, "Created URL: ".$result);
423

    
424
    return $result;
425
}
426

    
427

    
428
/**
429
 * Creates the tracking URL for connecting anonymous and logged user
430
 */
431
function getTransferURL($anonymousid, $userid) {
432
    $result = getEventServerUrl().'/ebl/'.YOOCHOOSE_ID.'/transfer/'.$anonymousid.'/'.$userid.'/';
433

    
434
    just_log_recommendation(E_NOTICE, "Created URL: ".$result);
435

    
436
    return $result;
437
}
438

    
439
/**
440
 *  return the ID of the logged user, or empty string
441
 */
442
function getLoggedUserId() {
443
    if (array_key_exists('customer_id', $_SESSION)) {
444
		return $_SESSION['customer_id'];
445
    } else {
446
	    return "";
447
	}
448
}
449

    
450
/**
451
 *  return the ID of the anonymous user (as defined in cookie 'XTCsid' or 'PHPSESSID'), or empty string
452
 */
453
function getAnonymousUserId() {
454
    $id = $_COOKIE['XTCsid'];
455
   if (!empty($id)) {return $id;}
456
    return $_COOKIE['PHPSESSID'];
457
}
458

    
459
/**
460
 *  return the ID of the logged user, or the anonymous user as a fallback
461
 */
462
function getCurrentUserId() {
463
   $id = getLoggedUserId();
464
   if (!empty($id)) {return $id;}
465
   return getAnonymousUserId();
466
}
467

    
468

    
469
/** Logs an error using FileLog('error') class.
470
 *  Does nothing except that (so screen output, no mails).
471
 */
472
function just_log_error($message, Exception $e) {
473
    $coo_log = new FileLog('errors');
474
    $coo_log->write("================================================================================\n");
475
    $coo_log->write(date('Y-m-j H-i-s')."\n");
476
    $coo_log->write("ERROR: ".$message."\n");
477
    $coo_log->write("Backtrace:\n");
478
    $coo_log->write(yoo_logbacktrace(debug_backtrace())."\n");
479
    $coo_log->write("\n");
480
    if ($e) {
481
        $coo_log->write("Cause: " . $e->getMessage() . " (" . $e->getFile() . ":" . $e->getLine() . ")\n");
482
        $coo_log->write("Backtrace:\n");
483
        $coo_log->write(yoo_logbacktrace($e->getTrace())."\n");
484
        $coo_log->write("\n");
485
    }
486
}
487

    
488

    
489
/** Logs an recommendation event using FileLog('recommendations') class.
490
 *  Does nothing except that (so screen output, no mails).
491
 *
492
 *  @param $log_level
493
 *      E_ERROR, E_WARNING or E_NOTICE
494
 */
495
function just_log_recommendation($log_level, $message, Exception $e = null) {
496

    
497
	if (getYooLogLevel() & $log_level > 0) {
498
	    $coo_log = new FileLog('recommendations');
499
	    $coo_log->write(date('Y-m-j H-i-s')." LEVEL $log_level: ".$message."\n");
500

    
501
	    if ($e) {
502
		    $coo_log->write("Cause: " . $e->getMessage() . " (" . $e->getFile() . ":" . $e->getLine() . ")\n");
503
		    $coo_log->write("Backtrace:\n");
504
		    $coo_log->write(yoo_logbacktrace($e->getTrace())."\n");
505
		    $coo_log->write("\n");
506
	    }
507
	}
508
}
509

    
510

    
511
function yoo_logbacktrace($backtrace) {
512
	$run = 0;
513
	$backtracelines = "";
514
	foreach ($backtrace as $data) {
515
		if (empty($data['file'])) $data['file'] = 'unknown';
516
		if (empty($data['line'])) $data['line'] = 0;
517

    
518
		if(!empty($data['class'])) {
519
			$backtracelines .= '#'.$run.'  (#'.$data['class'].') '.$data['function'].' called at ['.$data['file'].':'.$data['line'].']';
520
		} else {
521
			$backtracelines .= '#'.$run.'  '.$data['function'].' called at ['.$data['file'].':'.$data['line'].']';
522
		}
523

    
524
		$backtracelines .= ($t_code_snippet != '') ? "\n" . $t_code_snippet : "\n";
525
		$run ++;
526
	}
527

    
528
	return $backtracelines;
529
}
530

    
531

    
532
    /** An I/O Exception. */
533
    class IOException extends Exception {
534
        public function __construct($message, $errorno = 0, Exception $previous = null) {
535
            parent::__construct($message, $errorno);
536
        }
537
    }
538

    
539
        /** An I/O Exception. */
540
    class JSONException2 extends Exception {
541
        public function __construct($message, $json_code, Exception $previous = null) {
542
            parent::__construct($message, $json_code);
543
        }
544
        public static function decodeJSONMessage($json_code) {
545
        	switch ($json_code) {
546
        		case JSON_ERROR_NONE:
547
        			return "No error has occurred.";
548
                case JSON_ERROR_DEPTH:
549
                	return "The maximum stack depth has been exceeded.";
550
                case JSON_ERROR_CTRL_CHAR:
551
                	return "Control character error, possibly incorrectly encoded.";
552
                case JSON_ERROR_STATE_MISMATCH:
553
                    return "Invalid or malformed JSON.";
554
                case JSON_ERROR_SYNTAX:
555
                	return "Syntax error.";
556
                case JSON_ERROR_UTF8:
557
                	return "Malformed UTF-8 characters, possibly incorrectly encoded.";
558
                default:
559
                	return "Unknown JSON code [$json_code]";
560
        	}
561
        }
562
    }
563

    
564

    
565
    /** Throws an IOException with the message specified. */
566
    function throwIO($message, $errorno = 0) {
567
        throw new IOException($message, $errorno);
568
    }
569

    
570

    
571
/** Renders recommendations */
572
class YoochooseProductView extends ContentView {
573
    protected $product;
574

    
575
	function YoochooseProductView() {
576
		$this->set_content_template('module/yoochoose_view_products.html');
577
		$this->set_flat_assigns(true);
578
	}
579

    
580
    public function setProduct($product)
581
    {
582
        $this->product = $product;
583
    }
584

    
585
	function get_html_custom($t_data_array, $box_name, $params = array()) {
586

    
587
		$lang_id = $_SESSION['languages_id'];
588

    
589
		$header_key = getYoochooseHeaderConstantName($box_name);
590
		$header = gm_get_content($header_key, $lang_id);
591
		$header = $header ? $header : yoochooseDefaultHeader($box_name);
592

    
593
		if (! is_array($params)) {
594
			$params = array($params);
595
		}
596

    
597
		foreach ($params as $i=>$v) {
598
			$header = str_replace("{".$i."}", $v, $header);
599
		}
600

    
601
		$t_html_output = '';
602

    
603
		if(count($t_data_array) > 0) {
604
			$this->set_content_data('HEADER', $header);
605
			$this->set_content_data('TRUNCATE_PRODUCTS_NAME', gm_get_conf('TRUNCATE_PRODUCTS_NAME'));
606
			$this->set_content_data('GM_THUMBNAIL_WIDTH', PRODUCT_IMAGE_THUMBNAIL_WIDTH + 10);
607
			$this->set_content_data('module_content', $this->generateYooChooseListing($t_data_array));
608

    
609
			$t_html_output = $this->build_html();
610
		}
611

    
612
		return $t_html_output;
613
	}
614
    
615
    protected function generateYooChooseListing($products)
616
    {
617
        $showRating = false;
618
        if(gm_get_conf('ENABLE_RATING') === 'true' && gm_get_conf('SHOW_RATING_IN_GRID_AND_LISTING') === 'true')
619
        {
620
            $showRating = true;
621
        }
622
    
623
        $fullscreenPage = $GLOBALS['coo_template_control']->findSettingValueByName('gx-product-info-full-width');
624
        
625
        $showManufacturerImages = gm_get_conf('SHOW_MANUFACTURER_IMAGE_LISTING');
626
        $showProductRibbons = gm_get_conf('SHOW_PRODUCT_RIBBONS');
627
        
628
        $swiperData = [
629
            'products'               => $products,
630
            'id'                     => 'specials',
631
            'hoverable'              => true,
632
            'template'               => 'snippets/product_listing/product_listing.html',
633
            'truncate'               => gm_get_conf('TRUNCATE_PRODUCTS_NAME'),
634
            'showRating'             => $showRating,
635
            'fullscreenPage'         => $fullscreenPage,
636
            'showManufacturerImages' => $showManufacturerImages,
637
            'showProductRibbons'     => $showProductRibbons,
638
        ];
639
        
640
        $swiperHtml = MainFactory::create_object('ProductsSwiperContentView', [$swiperData]);
641
        return $swiperHtml->get_html();
642
    }
643
}
644

    
645
function create_yoochoose_products_view_html($box_name, $products, $params = array()) {
646
	$view = new YoochooseProductView();
647
	return $view->get_html_custom($products, $box_name, $params);
648
}
(3-3/3)