Completed
Branch develop (b10682)
by
unknown
26:44
created

Dolistore::get_previous_link()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * Copyright (C) 2017		 Oscss-Shop       <[email protected]>.
4
 *
5
 * This program is free software; you can redistribute it and/or modifyion 2.0 (the "License");
6
 * it under the terms of the GNU General Public License as published bypliance with the License.
7
 * the Free Software Foundation; either version 3 of the License, or
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 * or see http://www.gnu.org/
17
 */
18
19
include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
20
include_once DOL_DOCUMENT_ROOT.'/admin/dolistore/class/PSWebServiceLibrary.class.php';
21
22
23
/**
24
 * Class Dolistore
25
 */
26
class Dolistore
27
{
28
    /**
29
     * beginning of pagination
30
     * @var int
31
     */
32
33
     public $start;
34
    /**
35
     * end of pagination
36
     * @var int
37
     */
38
    public $end;
39
40
	public $per_page;    // pagination: display per page
41
	public $categorie;   // the current categorie
42
	public $search;      // the search keywords
43
44
	// setups
45
	public $url;         // the url of this page
46
	public $shop_url;    // the url of the shop
47
	public $lang;        // the integer representing the lang in the store
48
	public $debug_api;   // usefull if no dialog
49
50
51
	/**
52
	 * Constructor
53
	 *
54
	 * @param	boolean		$debug		Enable debug of request on screen
55
	 */
56
	public function __construct($debug = false)
57
	{
58
		global $conf, $langs;
59
60
		$this->url       = DOL_URL_ROOT.'/admin/modules.php?mode=marketplace';
61
		$this->shop_url  = 'https://www.dolistore.com/index.php?controller=product&id_product=';
62
		$this->debug_api = $debug;
63
64
		$langtmp    = explode('_', $langs->defaultlang);
65
		$lang       = $langtmp[0];
66
		$lang_array = array('en'=>1, 'fr'=>2, 'es'=>3, 'it'=>4, 'de'=>5);	// Into table ps_lang of Prestashop - 1
67
		if (! in_array($lang, array_keys($lang_array))) $lang = 'en';
68
		$this->lang = $lang_array[$lang];
69
	}
70
71
	/**
72
	 * Load data from remote Dolistore market place.
73
	 * This fills ->categories
74
	 *
75
	 * @return	void
76
	 */
77
	public function getRemoteCategories()
78
	{
79
	    global $conf;
80
81
	    try {
82
	        $this->api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $this->debug_api);
83
	        dol_syslog("Call API with MAIN_MODULE_DOLISTORE_API_SRV = ".$conf->global->MAIN_MODULE_DOLISTORE_API_SRV);
84
	        // $conf->global->MAIN_MODULE_DOLISTORE_API_KEY is for the login of basic auth. There is no password as it is public data.
85
86
	        // Here we set the option array for the Webservice : we want categories resources
87
	        $opt              = array();
88
	        $opt['resource']  = 'categories';
89
	        $opt['display']   = '[id,id_parent,nb_products_recursive,active,is_root_category,name,description]';
90
	        $opt['sort']      = 'id_asc';
91
92
	        // Call
93
	        dol_syslog("Call API with opt = ".var_export($opt, true));
94
	        $xml              = $this->api->get($opt);
95
	        $this->categories = $xml->categories->children();
96
	    } catch (PrestaShopWebserviceException $e) {
97
	        // Here we are dealing with errors
98
	        $trace = $e->getTrace();
99
	        if ($trace[0]['args'][0] == 404) die('Bad ID');
100
	        elseif ($trace[0]['args'][0] == 401) die('Bad auth key');
101
	        else
102
	        {
103
	            print 'Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'<br>';
104
	            print $e->getMessage();
105
	        }
106
	    }
107
	}
108
109
	/**
110
	 * Load data from remote Dolistore market place.
111
	 * This fills ->products
112
	 *
113
	 * @param 	array 	$options	Options. If 'categorie' is defined, we filter products on this category id
114
	 * @return	void
115
	 */
116
	public function getRemoteProducts($options = array('start' => 0, 'end' => 10, 'per_page' => 50, 'categorie' => 0, 'search' => ''))
117
	{
118
		global $conf, $langs;
119
120
		$this->start     = $options['start'];
121
		$this->end       = $options['end'];
122
		$this->per_page  = $options['per_page'];
123
		$this->categorie = $options['categorie'];
124
		$this->search    = $options['search'];
125
126
		if ($this->end == 0) {
127
			$this->end = $this->per_page;
128
		}
129
130
		try {
131
			$this->api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $this->debug_api);
132
			dol_syslog("Call API with MAIN_MODULE_DOLISTORE_API_SRV = ".$conf->global->MAIN_MODULE_DOLISTORE_API_SRV);
133
			// $conf->global->MAIN_MODULE_DOLISTORE_API_KEY is for the login of basic auth. There is no password as it is public data.
134
135
			// Here we set the option array for the Webservice : we want products resources
136
			$opt             = array();
137
			$opt['resource'] = 'products';
138
			$opt2            = array();
139
140
			// make a search to limit the id returned.
141
			if ($this->search != '') {
142
				$opt2['url'] = $conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'/api/search?query='.$this->search.'&language='.($this->lang);  // It seems for search, key start with
143
144
				// Call
145
				dol_syslog("Call API with opt2 = ".var_export($opt2, true));
146
				$xml         = $this->api->get($opt2);
147
148
				$products    = array();
149
				foreach ($xml->products->children() as $product) {
150
					$products[] = (int) $product['id'];
151
				}
152
				$opt['filter[id]'] = '['.implode('|', $products).']';
153
			} elseif ($this->categorie != 0) {   // We filter on category, so we first get list of product id in this category
154
			    // $opt2['url'] is set by default to $this->url.'/api/'.$options['resource'];
155
				$opt2['resource'] = 'categories';
156
				$opt2['id']       = $this->categorie;
157
158
				// Call
159
				dol_syslog("Call API with opt2 = ".var_export($opt2, true));
160
				$xml              = $this->api->get($opt2);
161
162
				$products         = array();
163
				foreach ($xml->category->associations->products->children() as $product) {
164
					$products[] = (int) $product->id;
165
				}
166
				$opt['filter[id]'] = '['.implode('|', $products).']';
167
			}
168
			$opt['display']        = '[id,name,id_default_image,id_category_default,reference,price,condition,show_price,date_add,date_upd,description_short,description,module_version,dolibarr_min,dolibarr_max]';
169
			$opt['sort']           = 'id_desc';
170
			$opt['filter[active]'] = '[1]';
171
			$opt['limit']          = "$this->start,$this->end";
172
			// $opt['filter[id]'] contais list of product id that are result of search
173
174
			// Call API to get the detail
175
			dol_syslog("Call API with opt = ".var_export($opt, true));
176
			$xml                   = $this->api->get($opt);
177
			$this->products        = $xml->products->children();
178
		} catch (PrestaShopWebserviceException $e) {
179
			// Here we are dealing with errors
180
			$trace = $e->getTrace();
181
			if ($trace[0]['args'][0] == 404) die('Bad ID');
182
			elseif ($trace[0]['args'][0] == 401) die('Bad auth key');
183
			else
184
			{
185
				print 'Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'<br>';
186
				print $e->getMessage();
187
			}
188
		}
189
	}
190
191
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
192
	/**
193
	 * Return tree of Dolistore categories. $this->categories must have been loaded before.
194
	 *
195
	 * @param 	int			$parent		Id of parent category
196
	 * @return 	string
197
	 */
198
	public function get_categories($parent = 0)
199
	{
200
        // phpcs:enable
201
		if (!isset($this->categories)) die('not possible');
202
		if ($parent != 0) {
203
			$html = '<ul>';
204
		} else {
205
			$html = '';
206
		}
207
208
		$nbofcateg = count($this->categories);
209
		for ($i = 0; $i < $nbofcateg; $i++)
210
		{
211
			$cat = $this->categories[$i];
212
			if ($cat->is_root_category == 1 && $parent == 0) {
213
				$html .= '<li class="root"><h3 class="nomargesupinf"><a class="nomargesupinf link2cat" href="?mode=marketplace&categorie='.$cat->id.'" '
214
					.'title="'.dol_escape_htmltag(strip_tags($cat->description->language[$this->lang - 1])).'"'
215
						.'>'.$cat->name->language[$this->lang - 1].' <sup>'.$cat->nb_products_recursive.'</sup></a></h3>';
216
						$html .= self::get_categories($cat->id);
217
						$html .= "</li>\n";
218
			} elseif (trim($cat->id_parent) == $parent && $cat->active == 1 && trim($cat->id_parent) != 0) { // si cat est de ce niveau
219
				$select = ($cat->id == $this->categorie) ? ' selected' : '';
220
				$html   .= '<li><a class="link2cat'.$select.'" href="?mode=marketplace&categorie='.$cat->id.'"'
221
					.' title="'.dol_escape_htmltag(strip_tags($cat->description->language[$this->lang - 1])).'" '
222
						.'>'.$cat->name->language[$this->lang - 1].' <sup>'.$cat->nb_products_recursive.'</sup></a>';
223
						$html   .= self::get_categories($cat->id);
224
						$html   .= "</li>\n";
225
			} else {
226
227
			}
228
		}
229
230
		if ($html == '<ul>') {
231
			return '';
232
		}
233
		if ($parent != 0) {
234
			return $html.'</ul>';
235
		} else {
236
			return $html;
237
		}
238
	}
239
240
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
241
	/**
242
	 * Return list of product formated for output
243
	 *
244
	 * @return string			HTML output
245
	 */
246
	public function get_products()
247
	{
248
        // phpcs:enable
249
		global $langs, $conf;
250
		$html       = "";
251
		$parity     = "pair";
252
		$last_month = time() - (30 * 24 * 60 * 60);
253
		foreach ($this->products as $product) {
254
			$parity = ($parity == "impair") ? 'pair' : 'impair';
255
256
			// check new product ?
257
			$newapp = '';
258
			if ($last_month < strtotime($product->date_add)) {
259
				$newapp .= '<span class="newApp">'.$langs->trans('New').'</span> ';
260
			}
261
262
			// check updated ?
263
			if ($last_month < strtotime($product->date_upd) && $newapp == '') {
264
				$newapp .= '<span class="updatedApp">'.$langs->trans('Updated').'</span> ';
265
			}
266
267
			// add image or default ?
268
			if ($product->id_default_image != '') {
269
				$image_url = DOL_URL_ROOT.'/admin/dolistore/ajax/image.php?id_product='.$product->id.'&id_image='.$product->id_default_image;
270
				$images    = '<a href="'.$image_url.'" class="fancybox" rel="gallery'.$product->id.'" title="'.$product->name->language[$this->lang - 1].', '.$langs->trans('Version').' '.$product->module_version.'">'.
271
					'<img src="'.$image_url.'&quality=home_default" style="max-height:250px;max-width: 210px;" alt="" /></a>';
272
			} else {
273
				$images = '<img src="'.DOL_URL_ROOT.'/admin/dolistore/img/NoImageAvailable.png" />';
274
			}
275
276
			// free or pay ?
277
			if ($product->price > 0) {
278
			    $price         = '<h3>'.price(price2num($product->price, 'MT'), 0, $langs, 1, -1, -1, 'EUR').' '.$langs->trans("HT").'</h3>';
279
				$download_link = '<a target="_blank" href="'.$this->shop_url.$product->id.'"><img width="32" src="'.DOL_URL_ROOT.'/admin/dolistore/img/follow.png" /></a>';
280
			} else {
281
				$price         = '<h3>'.$langs->trans('Free').'</h3>';
282
				$download_link = '<a target="_blank" href="'.$this->shop_url.$product->id.'"><img width="32" src="'.DOL_URL_ROOT.'/admin/dolistore/img/Download-128.png" /></a>';
283
				$download_link.= '<br><br><a target="_blank" href="'.$this->shop_url.$product->id.'"><img width="32" src="'.DOL_URL_ROOT.'/admin/dolistore/img/follow.png" /></a>';
284
			}
285
286
			//checking versions
287
			if ($this->version_compare($product->dolibarr_min, DOL_VERSION) <= 0) {
288
				if ($this->version_compare($product->dolibarr_max, DOL_VERSION) >= 0) {
289
					//compatible
290
                    $version = '<span class="compatible">'.$langs->trans('CompatibleUpTo', $product->dolibarr_max,
291
						$product->dolibarr_min, $product->dolibarr_max).'</span>';
292
					$compatible = '';
293
				} else {
294
					//never compatible, module expired
295
                    $version = '<span class="notcompatible">'.$langs->trans('NotCompatible', DOL_VERSION,
296
						$product->dolibarr_min, $product->dolibarr_max).'</span>';
297
					$compatible = 'NotCompatible';
298
				}
299
			} else {
300
				//need update
301
				$version    = '<span class="compatibleafterupdate">'.$langs->trans('CompatibleAfterUpdate', DOL_VERSION,
302
					$product->dolibarr_min, $product->dolibarr_max).'</span>';
303
				$compatible = 'NotCompatible';
304
			}
305
306
			//.'<br><a class="inline-block valignmiddle" target="_blank" href="'.$this->shop_url.$product->id.'"><span class="details button">'.$langs->trans("SeeInMarkerPlace").'</span></a>
307
308
			//output template
309
			$html .= '<tr class="app '.$parity.' '.$compatible.'">
310
                <td class="center" width="210"><div class="newAppParent">'.$newapp.$images.'</div></td>
311
                <td class="margeCote"><h2 class="appTitle">'.$product->name->language[$this->lang - 1]
312
						.'<br/><small>'.$version.'</small></h2>
313
                    <small> '.dol_print_date(dol_stringtotime($product->date_upd), 'dayhour').' - '.$langs->trans('Ref').': '.$product->reference.' - '.$langs->trans('Id').': '.$product->id.'</small><br><br>'.$product->description_short->language[$this->lang - 1].'</td>
314
                <td style="display:none;" class="long_description">'.$product->description->language[$this->lang - 1].'</td>
315
                <td class="margeCote center">'.$price.'
316
                </td>
317
                <td class="margeCote">'.$download_link.'</td>
318
                </tr>';
319
        }
320
        return $html;
321
    }
322
323
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
324
    /**
325
     * get previous link
326
     *
327
     * @param   string    $text     symbol previous
328
     * @return  string              html previous link
329
     */
330
	public function get_previous_link($text = '<<')
331
	{
332
        // phpcs:enable
333
		return '<a href="'.$this->get_previous_url().'" class="button">'.$text.'</a>';
334
	}
335
336
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
337
    /**
338
     * get next link
339
     *
340
     * @param   string    $text     symbol next
341
     * @return  string              html next link
342
     */
343
    public function get_next_link($text = '>>')
344
	{
345
        // phpcs:enable
346
		return '<a href="'.$this->get_next_url().'" class="button">'.$text.'</a>';
347
	}
348
349
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
350
    /**
351
     * get previous url
352
     *
353
     * @return string    previous url
354
     */
355
    public function get_previous_url()
356
    {
357
        // phpcs:enable
358
		$param_array = array();
359
		if ($this->start < $this->per_page) {
360
			$sub = 0;
361
		} else {
362
			$sub = $this->per_page;
363
		}
364
		$param_array['start'] = $this->start - $sub;
365
		$param_array['end']   = $this->end - $sub;
366
		if ($this->categorie != 0) {
367
			$param_array['categorie'] = $this->categorie;
368
		}
369
		$param = http_build_query($param_array);
370
		return $this->url."&".$param;
371
    }
372
373
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
374
    /**
375
     * get next url
376
     *
377
     * @return string    next url
378
     */
379
    public function get_next_url()
380
	{
381
        // phpcs:enable
382
		$param_array = array();
383
		if (count($this->products) < $this->per_page) {
384
			$add = 0;
385
		} else {
386
			$add = $this->per_page;
387
		}
388
		$param_array['start'] = $this->start + $add;
389
		$param_array['end']   = $this->end + $add;
390
		if ($this->categorie != 0) {
391
			$param_array['categorie'] = $this->categorie;
392
		}
393
		$param = http_build_query($param_array);
394
		return $this->url."&".$param;
395
	}
396
397
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
398
    /**
399
     * version compare
400
     *
401
     * @param   string  $v1     version 1
402
     * @param   string  $v2     version 2
403
     * @return int              result of compare
404
     */
405
	public function version_compare($v1, $v2)
406
	{
407
        // phpcs:enable
408
		$v1       = explode('.', $v1);
409
		$v2       = explode('.', $v2);
410
		$ret      = 0;
411
		$level    = 0;
412
		$count1   = count($v1);
413
		$count2   = count($v2);
414
		$maxcount = max($count1, $count2);
415
		while ($level < $maxcount) {
416
			$operande1 = isset($v1[$level]) ? $v1[$level] : 'x';
417
			$operande2 = isset($v2[$level]) ? $v2[$level] : 'x';
418
			$level++;
419
			if (strtoupper($operande1) == 'X' || strtoupper($operande2) == 'X' || $operande1 == '*' || $operande2 == '*') {
420
				break;
421
			}
422
			if ($operande1 < $operande2) {
423
				$ret = -$level;
424
				break;
425
			}
426
			if ($operande1 > $operande2) {
427
				$ret = $level;
428
				break;
429
			}
430
		}
431
		//print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'<br>'."\n";
432
		return $ret;
433
	}
434
}
435