Completed
Push — master ( d208aa...25518b )
by Lars
12:37
created

Product::getAttributeGroups()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.0261

Importance

Changes 0
Metric Value
cc 3
eloc 14
nc 3
nop 0
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
ccs 12
cts 14
cp 0.8571
crap 3.0261
1
<?php
2
/**
3
 * Product
4
 *
5
 * Bruges til at holde styr p� varerne.
6
 *
7
 * @package Intraface_Product
8
 * @author Lars Olesen <[email protected]>
9
 * @see ProductDetail
10
 * @see Stock
11
 */
12
require_once 'Intraface/modules/product/ProductDetail.php';
13
14
class Product extends Intraface_Standard
15
{
16
    /**
17
     * @var object
18
     */
19
    public $kernel;
20
21
    /**
22
     * @var object
23
     */
24
    public $user;
25
26
    /**
27
     * @var integer
28
     */
29
    private $id;
30
31
    /**
32
     * @var object
33
     */
34
    private $detail;
35
36
    /**
37
     * @var integer
38
     */
39
    private $old_product_detail_id;
40
41
    /**
42
     * @var array
43
     */
44
    public $value = array();
45
46
    /**
47
     * Fields to update
48
     * @var array
49
     */
50
    private $fields;
51
52
    /**
53
     * @var object
54
     */
55
    private $db;
56
57
    /**
58
     * @var object
59
     *
60
     * Made private now. Please use getStock() instead.
61
     */
62
    private $stock;
63
64
    /**
65
     * @var object
66
     */
67
    public $error;
68
69
    /**
70
     * @var object
71
     */
72
    public $keywords;
73
74
    /**
75
     * @var object
76
     */
77
    private $dbquery;
78
79
    /**
80
     * Constructor
81
     *
82
     * @param object  $kernel                The kernel object
83
     * @param integer $product_id            The product id
84
     * @param integer $old_product_detail_id If we want to find old details, e.g. for an invoice
85
     *
86
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
87
     */
88 67
    function __construct($kernel, $product_id = 0, $old_product_detail_id = 0)
89
    {
90 67
        $this->kernel                = $kernel;
91 67
        $this->user                  = $kernel->user;
92 67
        $this->intranet              = $kernel->intranet;
0 ignored issues
show
Bug introduced by
The property intranet does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
93 67
        $this->db                    = new DB_Sql;
94 67
        $this->id                    = (int)$product_id;
95 67
        $this->old_product_detail_id = (int)$old_product_detail_id;
96 67
        $this->fields                = array('do_show', 'stock', 'has_variation');
97 67
        $this->error                 = new Intraface_Error;
98
99 67
        if ($this->id > 0) {
100 42
            $this->id = $this->load();
101 42
        }
102 67
    }
103
104
    /**
105
     * Used by Keyword
106
     *
107
     * @see Keyword
108
     *
109
     * @return string
110
     */
111 1
    function identify()
112
    {
113 1
        return 'product';
114
    }
115
116
    /**
117
     * Creates the dbquery object
118
119
     * @return void
120
     */
121
    public function getDBQuery()
122
    {
123
        if ($this->dbquery) {
124
            return $this->dbquery;
125
        }
126
127
        $gateway = new Intraface_modules_product_Gateway($this->kernel);
128
        return $this->dbquery = $gateway->getDBQuery();
129
130
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
131
        $this->dbquery = new Intraface_DBQuery($this->kernel, "product", "product.active = 1 AND product.intranet_id = ".$this->intranet->getId());
132
        $this->dbquery->setJoin("LEFT", "product_detail detail", "detail.product_id = product.id", "detail.active = 1");
133
        //$this->dbquery->setFindCharacterFromField("detail.name");
134
        $this->dbquery->useErrorObject($this->error);
135
        return $this->dbquery;
136
        */
137
    }
138
139
    /**
140
     * Loads data into an array
141
     *
142
     * Should load both the specific product details, but also the product details
143
     *
144
     * @return integer product id or 0
145
     */
146 66
    public function load()
147
    {
148 66
        $this->db->query("SELECT id, active, locked, changed_date, ".implode(',', $this->fields)." FROM product
149 66
                WHERE intranet_id = " . $this->kernel->intranet->getId() . "
150 66
                    AND id = " . $this->id . " LIMIT 1");
151
152 66
        if (!$this->db->nextRecord()) {
153
            $this->value['id'] = 0;
154 18
            return 0;
155
        }
156
157
        // TODO HACK::HACK::HACK::HACK::HACK::HACK::HACK*
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
158
        //
159
        //  Vi bliver n�dt til at hente value['id'] b�de f�r og efter,
160
        //  for n�r jeg k�rer arrayet fra produktdetaljerne ind i value
161
        //  s� sletter det gamle array. Derfor hentes det f�r og efter
162
        //
163
        // HACK::HACK::HACK::HACK::HACK::HACK::HACK*
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
164
165
        // hente id
166 66
        $this->value['id'] = $this->db->f('id');
167
168
        // hente produktdetaljerne
169 66
        $this->detail = $this->getDetails();
170 66
        $this->value  = $this->detail->get();
171
        // hente id igen for ovenst�ende har overskrevet det
172 66
        $this->value['id']           = $this->db->f('id');
173 66
        $this->value['locked']       = $this->db->f('locked');
174 66
        $this->value['changed_date'] = $this->db->f('changed_date');
175 66
        $this->value['active']       = $this->db->f('active');
176
177
        // udtr�k af produktdetaljer
178 66 View Code Duplication
        for ($i = 0, $max = count($this->fields); $i < $max; $i++) {
179 66
            $this->value[$this->fields[$i]] = $this->db->f($this->fields[$i]);
180 66
        }
181
182
        // We now remove stock from load. It can be obtained manaully!
183
        // $this->getStock();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
184
185
        // desuden skal copy lige opdateres!
186
        // hvad med at vi bruger det �verste billede som primary. Det betyder dog, at
187
        // der skal laves noget position p� AppendFile, men det er jo ogs� smart nok.
188
189 66
        $this->value['id'] = $this->db->f('id');
190
191 66
        $this->db->free();
192 66
        return $this->value['id'];
193
    }
194
195
    /**
196
     * Gets the stock module
197
     *
198
     * @return object
199
     */
200 8
    public function getStock()
201
    {
202 8
        if ($this->hasVariation()) {
203
            throw new Exception('You cannot get stock from product with variations. Use stock for variation');
204
        }
205
206 8
        if (isset($this->value['stock']) and $this->value['stock'] == 0 and isset($this->value['do_show']) and $this->value['do_show'] == 1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
207 8
            $this->value['stock_status'] = array('for_sale' => 100); // kun til at stock_status
208 8
        }
209
        // hvis det er en lagervare og intranettet har adgang til stock skal det startes op
210
211 8
        if ($this->kernel->intranet->hasModuleAccess('stock') and $this->get('stock') == 1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
212
            if (!is_object($this->stock)) {
213
                // hvis klassen ikke er startet op skal det ske
214
                $module = $this->kernel->useModule('stock', true); // true ignorere bruger adgang
0 ignored issues
show
Unused Code introduced by
$module is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
215
                $this->stock                 = new Stock($this);
216
                $this->value['stock_status'] = $this->stock->get();
217
            }
218
            return $this->stock;
219
        }
220 8
        return false;
221
    }
222
223 1
    function getKernel()
224
    {
225 1
        return $this->kernel;
226
    }
227
228
    /**
229
     * @todo How should we handle the function to get pictures?
230
     */
231 18
    function getNewPictures()
232
    {
233
        require_once 'Intraface/modules/filemanager/AppendFile.php';
234
        //$filehandler = new Ilib_Filehandler($this->kernel);
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
235
        $append_file = new AppendFile($this->kernel, 'product', $this->get('id'));
236
        $appendix_list = $append_file->getList();
237
238 18
        $this->value['pictures'] = array();
239
240 View Code Duplication
        if (count($appendix_list) > 0) {
241
            foreach ($appendix_list as $key => $appendix) {
242
                $tmp_filehandler = new Ilib_Filehandler($this->kernel, $appendix['file_handler_id']);
243
                $this->value['pictures'][$key]['id']                   = $appendix['file_handler_id'];
244
                $this->value['pictures'][$key]['original']['icon_uri'] = $tmp_filehandler->get('icon_uri');
245
                $this->value['pictures'][$key]['original']['name']     = $tmp_filehandler->get('file_name');
246
                $this->value['pictures'][$key]['original']['width']    = $tmp_filehandler->get('width');
247
                $this->value['pictures'][$key]['original']['height']   = $tmp_filehandler->get('height');
248
                $this->value['pictures'][$key]['original']['file_uri'] = $tmp_filehandler->get('file_uri');
249
                $this->value['pictures'][$key]['appended_file_id']     = $appendix['id'];
250
251
                if ($tmp_filehandler->get('is_image')) {
252
                    $tmp_filehandler->createInstance();
0 ignored issues
show
Deprecated Code introduced by
The method Ilib_Filehandler::createInstance() has been deprecated.

This method has been deprecated.

Loading history...
253
                    $instances = $tmp_filehandler->instance->getList('include_hidden');
254
                    foreach ($instances as $instance) {
255
                        $this->value['pictures'][$key][$instance['name']]['file_uri'] = $instance['file_uri'];
256
                        $this->value['pictures'][$key][$instance['name']]['name']     = $instance['name'];
257
                        $this->value['pictures'][$key][$instance['name']]['width']    = $instance['width'];
258
                        $this->value['pictures'][$key][$instance['name']]['height']   = $instance['height'];
259
                    }
260
                }
261
            }
262
        }
263
        return $this->value['pictures'];
264
    }
265
266
    /**
267
     * Gets pictures for the product
268
     *
269
     * @return array
270
     */
271 19
    function getPictures()
272
    {
273 19
        $shared_filehandler = $this->kernel->useModule('filemanager');
274 19
        $shared_filehandler->includeFile('AppendFile.php');
275
276 19
        $filehandler = new FileHandler($this->kernel);
0 ignored issues
show
Unused Code introduced by
$filehandler is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
277 19
        $append_file = new AppendFile($this->kernel, 'product', $this->get('id'));
278 19
        $appendix_list = $append_file->getList();
279
280 19
        $this->value['pictures'] = array();
281
282 19 View Code Duplication
        if (count($appendix_list) > 0) {
283 18
            foreach ($appendix_list as $key => $appendix) {
284 18
                $tmp_filehandler = new FileHandler($this->kernel, $appendix['file_handler_id']);
285 18
                $this->value['pictures'][$key]['id']                   = $appendix['file_handler_id'];
286 18
                $this->value['pictures'][$key]['original']['icon_uri'] = $tmp_filehandler->get('icon_uri');
287 18
                $this->value['pictures'][$key]['original']['name']     = $tmp_filehandler->get('file_name');
288 18
                $this->value['pictures'][$key]['original']['width']    = $tmp_filehandler->get('width');
289 18
                $this->value['pictures'][$key]['original']['height']   = $tmp_filehandler->get('height');
290 18
                $this->value['pictures'][$key]['original']['file_uri'] = $tmp_filehandler->get('file_uri');
291 18
                $this->value['pictures'][$key]['appended_file_id']     = $appendix['id'];
292
293 18
                if ($tmp_filehandler->get('is_image')) {
294 18
                    $tmp_filehandler->createInstance();
295 18
                    $instances = $tmp_filehandler->instance->getList('include_hidden');
296 18
                    foreach ($instances as $instance) {
297 18
                        $this->value['pictures'][$key][$instance['name']]['file_uri'] = $instance['file_uri'];
298 18
                        $this->value['pictures'][$key][$instance['name']]['name']     = $instance['name'];
299 18
                        $this->value['pictures'][$key][$instance['name']]['width']    = $instance['width'];
300 18
                        $this->value['pictures'][$key][$instance['name']]['height']   = $instance['height'];
301 18
                    }
302 18
                }
303 18
                $tmp_filehandler->__destruct();
304 18
                unset($tmp_filehandler);
305 18
            }
306 18
        }
307 19
        return $this->value['pictures'];
308
    }
309
310
    /**
311
     * Validates
312
     *
313
     * @param array $array_var The array to validate
314
     *
315
     * @return boolean
316
     */
317 66
    private function validate($array_var)
318
    {
319 66
        if (!is_array($array_var)) {
320
            throw new Exception('Product::save() skal have et array');
321
        }
322
323 66
        $validator = new Intraface_Validator($this->error);
324
325 66
        if (!$this->isNumberFree($array_var['number'])) {
326
            $this->error->set('Produktnummeret er ikke frit');
327
        }
328
329 66
        $validator->isNumeric($array_var['number'], 'Produktnummeret skal v�re et tal');
330 66
        settype($array_var['stock'], 'integer');
331 66
        $validator->isNumeric($array_var['stock'], 'stock', 'allow_empty');
332 66
        settype($array_var['do_show'], 'integer');
333 66
        $validator->isNumeric($array_var['do_show'], 'do_show', 'allow_empty');
334
335 66
        if ($this->error->isError()) {
336
            return false;
337
        }
338
339 66
        return true;
340
    }
341
342
    /**
343
     * Saves product
344
     *
345
     * @param array $array_var Array with details to save, @see $this->fields
346
     *
347
     * @return integer 0 on error
348
     */
349 66
    public function save($array_var)
350
    {
351 66
        if ($this->id > 0 and $this->get('locked') == 1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
352
            $this->error->set('Produktet er l�st og kan ikke opdateres');
353
            return 0;
354
        }
355
356 66
        if (empty($array_var['number']) and $this->get('number') > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
357 2
            $array_var['number'] = $this->get('number');
358 2
        }
359
360 66
        if (empty($array_var['number'])) {
361 65
            $array_var['number'] = $this->getMaxNumber() + 1;
362 65
        }
363
364 66
        if (!$this->validate($array_var)) {
365
            return 0;
366
        }
367
368
        // lave sql-s�tningen
369 66
        $sql = '';
370
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
371
        for ($i=0, $max = sizeof($this->fields); $i<$max; $i++) {
372
            if (!array_key_exists($this->fields[$i], $array_var)) {
373
                continue;
374
            }
375
376
            if (isset($array_var[$this->fields[$i]])) {
377
                $sql .= $this->fields[$i]." = '".safeToDb($array_var[$this->fields[$i]])."', ";
378
            } else {
379
                $sql .= $this->fields[$i]." = '', ";
380
            }
381
        }
382
        */
383
384 66
        foreach ($this->fields as $field) {
385 66
            if (!array_key_exists($field, $array_var)) {
386 66
                continue;
387
            }
388
389 10
            if (isset($array_var[$field])) {
390 10
                $sql .= $field." = '".safeToDb($array_var[$field])."', ";
391 10
            } else {
392
                $sql .= $field." = '', ";
393
            }
394 66
        }
395
396 66
        if ($this->id > 0) {
397 4
            $sql_type = "UPDATE ";
398 4
            $sql_end  = " WHERE id = " . $this->id . " AND intranet_id = " . $this->intranet->getId();
399 4
        } else {
400 66
            $sql_type = "INSERT INTO";
401 66
            $sql_end  = ", intranet_id = " . $this->intranet->getId();
402
        }
403
404 66
        $this->db->query($sql_type . " product SET ".$sql." changed_date = NOW()"    . $sql_end);
405
406 66
        if (empty($this->id)) {
407 66
            $this->id = $this->db->insertedId();
408 66
        }
409
410 66
        $this->load();
411
412
        // gemme produktdetaljerne
413 66
        $product_detail = new ProductDetail($this);
414 66
        $product_detail->save($array_var);
415
416 66
        if ($this->error->isError()) {
417
            return 0;
418
        }
419 66
        $this->load();
420
421
        // should return id
422 66
        return $this->id;
423
    }
424
425
    /**
426
     * Copies product to a new product
427
     *
428
     * @return integer Id for the new product
429
     */
430 1
    public function copy()
431
    {
432 1
        $product = new Product($this->kernel);
433 1
        $product->getKeywords();
0 ignored issues
show
Deprecated Code introduced by
The method Product::getKeywords() has been deprecated.

This method has been deprecated.

Loading history...
434
435 1
        $new_id = $product->save(
436
            array(
437 1
                'name' => $this->get('name') . ' (kopi)',
438 1
                'description' => $this->get('description'),
439 1
                'price' => amountToForm($this->get('price')), // make sure that this is formatted to local format
440 1
                'weight' => (float)$this->get('weight'),
441 1
                'unit' => $this->get('unit_key'),
442 1
                'vat' => $this->get('vat'),
443 1
                'state_account_id' => $this->get('state_account_id'),
444 1
                'stock' => $this->get('stock')
445 1
            )
446 1
        );
447
448
        // Relaterede produkter
449 1
        $related = $this->getRelatedProducts();
450 1
        if (is_array($related) and count($related) > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
451
            foreach ($related as $p) {
452
                $product->setRelatedProduct($p['id']);
453
            }
454
        }
455
456
        // N�gleord
457 1
        $appender = $this->getKeywordAppender();
458 1
        $this->getKeywords();
0 ignored issues
show
Deprecated Code introduced by
The method Product::getKeywords() has been deprecated.

This method has been deprecated.

Loading history...
459 1
        $keywords = $appender->getConnectedKeywords();
460
461
        // @todo does not transfer keywords correctly
462 1
        if (is_array($keywords)) {
463 1
            $appender = $product->getKeywordAppender();
464 1
            foreach ($keywords as $k) {
465
                $appender->addKeyword(new Keyword($this, $k['id']));
466 1
            }
467 1
        }
468
469
        // Billede
470 1
        $shared_filehandler = $this->kernel->useModule('filemanager');
471 1
        $shared_filehandler->includeFile('AppendFile.php');
472
473 1
        $append_file = new AppendFile($this->kernel, 'product', $product->get('id'));
474
475 1
        $pictures = $this->getPictures();
476 1
        if (is_array($pictures)) {
477 1
            foreach ($pictures as $pic) {
478 1
                $append_file->addFile(new FileHandler($this->kernel, $pic['id']));
479 1
            }
480 1
        }
481
482 1
        return $new_id;
483
    }
484
485
    /**
486
     * Deletes product
487
     *
488
     * Only set active to 0. Products must never be deleted from the database. It should always be
489
     * possible to go back to earlier products.
490
     *
491
     * @return boolean
492
     */
493 30
    public function delete()
494
    {
495 30
        if ($this->id == 0) {
496
            $this->error->set('Produktet kan ikke slettes, for produktid er ikke sat');
497
            return false;
498
        }
499 30
        if ($this->get('locked') == 1) {
500
            $this->error->set('Produktet kan ikke slettes, for det er l�st.');
501
            return false;
502
        }
503
504 30
        $db = new Db_Sql;
505
        $sql = "UPDATE product
506
            SET active = 0
507 30
            WHERE id = " . $this->id. "
508 30
                AND intranet_id = " . $this->intranet->getId() . "
509 30
                AND locked = 0";
510 30
        $db->query($sql);
511
512 30
        $this->value['active'] = 0;
513 30
        return true;
514
    }
515
516
    /**
517
     * Undeletes a product
518
     *
519
     * @return boolean
520
     */
521 1
    public function undelete()
522
    {
523 1
        if ($this->id == 0) {
524
            $this->error->set('Produktet kan ikke findes igen, for produktid er ikke sat');
525
526
            return false;
527
        }
528 1
        $db = new Db_Sql;
529
        $sql = "UPDATE product
530
            SET active = 1
531 1
            WHERE id = " . $this->id. "
532 1
                AND intranet_id = " . $this->intranet->getId();
533 1
        $db->query($sql);
534 1
        $this->value['active'] = 1;
535 1
        return true;
536
    }
537
538
    /**
539
     * Returnerer det h�jeste produktnummer
540
     *
541
     * @return integer produktnummer
542
     */
543 66 View Code Duplication
    public function getMaxNumber()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
544
    {
545 66
        $db = new DB_Sql;
546
        $sql = "SELECT product_detail.number
547
            FROM product
548
            INNER JOIN product_detail
549
                ON product_detail.product_id = product.id
550 66
            WHERE product.intranet_id = " . $this->intranet->getId() . "
551 66
            ORDER BY product_detail.number DESC LIMIT 1";
552 66
        $db->query($sql);
553 66
        if (!$db->nextRecord()) {
554 65
            return 0;
555
        }
556 10
        return $db->f('number');
557
    }
558
559
    /**
560
     * Checks whether number is free
561
     *
562
     * @param integer $product_number Product number to check
563
     *
564
     * @return boolean
565
     */
566 66
    public function isNumberFree($product_number)
567
    {
568 66
        $product_number = (int)$product_number;
569
570 66
        $db = new DB_Sql;
571
         $sql = "SELECT product.id FROM product
572
          INNER JOIN product_detail detail
573
            ON product.id = detail.product_id
574 66
            WHERE detail.number = '" . $product_number . "'
575 66
                AND detail.product_id <> " . $this->id . "
576
                AND detail.active = 1
577
                AND product.active=1
578 66
                AND product.intranet_id = ".$this->intranet->getId()." LIMIT 1";
579 66
        $db->query($sql);
580 66
        if ($db->numRows() == 0) {
581 66
            return true;
582
        }
583
584
        return false;
585
    }
586
587
    /**
588
     * Get keywords object
589
     *
590
     * @deprecated
591
     *
592
     * @return object
593
     */
594
    public function getKeywords()
595
    {
596
        return ($this->keywords = new Keyword($this));
597
    }
598
599
    /**
600
     * Get keywords object
601
     *
602
     * @return object
603
     */
604
    public function getKeyword()
605
    {
606
        return ($this->keywords = new Keyword($this));
607
    }
608
609
610 1
    public function getKeywordAppender()
611
    {
612 1
        return new Intraface_Keyword_Appender($this);
613
    }
614
615
    /**
616
     * Set related product
617
     *
618
     * @param integer $id     Product id to relate to this product
619
     * @param string  $status Can be relate or remove
620
     *
621
     * @return boolean
622
     */
623 1
    public function setRelatedProduct($id, $status = 'relate')
624
    {
625 1
        if (empty($status)) {
626
            $status = 'remove';
627
        }
628
629 1
        $db = new DB_Sql;
630
631 1
        if ($status == 'relate') {
632 1
            $db->query("SELECT * FROM product_related WHERE product_id=" . $this->id  . " AND related_product_id = " . (int)$id . " AND intranet_id =" .$this->intranet->getId());
633 1
            if ($db->nextRecord()) {
634
                return true;
635
            }
636 1
            if ($id == $this->id) {
637
                return false;
638
            }
639 1
            $db->query("INSERT INTO product_related SET product_id = " . $this->id . ", related_product_id = " . (int)$id . ", intranet_id = " . $this->intranet->getId());
640 1
            return true;
641
        } else {
642
            $db->query("DELETE FROM product_related WHERE product_id = " . $this->id . " AND intranet_id = " . $this->intranet->getId() . " AND related_product_id = " . (int)$id);
643
            return true;
644
        }
645
    }
646
647
    /**
648
     * Delete related product
649
     *
650
     * @param integer $id     Product id to relate to this product
651
     *
652
     * @return boolean
653
     */
654
    public function deleteRelatedProduct($id)
655
    {
656
        $db = new DB_Sql;
657
        $db->query("DELETE FROM product_related WHERE product_id = " . $this->id . " AND intranet_id = " . $this->intranet->getId() . " AND related_product_id = " . (int)$id);
658
        return true;
659
    }
660
661
    /**
662
     * Delete all related product
663
     *
664
     * @param integer $id     Product id to relate to this product
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
665
     *
666
     * @return boolean
667
     */
668
    public function deleteRelatedProducts()
669
    {
670
        $db = new DB_Sql;
671
        $db->query("DELETE FROM product_related WHERE product_id = " . $this->id . " AND intranet_id = " . $this->intranet->getId());
672
        return true;
673
    }
674
675
    /**
676
     * Get all related products
677
     *
678
     * @return array
679
     */
680 2
    public function getRelatedProducts($currencies = false, $show = 'all')
681
    {
682 2
        $products = array();
683 2
        $key      = 0;
684 2
        $ids      = array();
0 ignored issues
show
Unused Code introduced by
$ids is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
685 2
        $db       = new DB_Sql;
686 2
        $sql      = "SELECT related_product_id FROM product_related WHERE product_id = " . $this->id . " AND intranet_id = " . $this->intranet->getId();
687 2
        $db->query($sql);
688
689
        // r�kkef�lgen er vigtig - f�rst hente fra product og bagefter tilf�je nye v�rdier til arrayet
690 2
        while ($db->nextRecord()) {
691 1
            $product                      = new Product($this->kernel, $db->f('related_product_id'));
692 1
            if ($product->get('id') == 0 || $product->get('active') == 0 || ($show == 'webshop' && $product->get('do_show') == 0)) {
693
                continue;
694
            }
695 1
            $products[$key]               = $product->get();
696 1
            $products[$key]['related_id'] = $db->f('related_product_id');
697
698 1
            $products[$key]['currency']['DKK']['price'] = $product->getDetails()->getPrice();
699 1
            $products[$key]['currency']['DKK']['price_incl_vat'] = $product->getDetails()->getPriceIncludingVat();
700 1
            $products[$key]['currency']['DKK']['before_price'] = $product->getDetails()->getBeforePrice();
701 1
            $products[$key]['currency']['DKK']['before_price_incl_vat'] = $product->getDetails()->getBeforePriceIncludingVat();
702
703 1
            $products[$key]['pictures'] = $product->getPictures();
704
705 1 View Code Duplication
            if ($currencies && $currencies->count() > 0) {
0 ignored issues
show
Bug introduced by
The method count cannot be called on $currencies (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
706
                foreach ($currencies as $currency) {
0 ignored issues
show
Bug introduced by
The expression $currencies of type boolean is not traversable.
Loading history...
707
                    $products[$key]['currency'][$currency->getType()->getIsoCode()]['price'] = $product->getDetails()->getPriceInCurrency($currency);
708
                    $products[$key]['currency'][$currency->getType()->getIsoCode()]['price_incl_vat'] = $product->getDetails()->getPriceIncludingVatInCurrency($currency);
709
                    $products[$key]['currency'][$currency->getType()->getIsoCode()]['before_price'] = $product->getDetails()->getBeforePriceInCurrency($currency);
710
                    $products[$key]['currency'][$currency->getType()->getIsoCode()]['before_price_incl_vat'] = $product->getDetails()->getBeforePriceIncludingVatInCurrency($currency);
711
                }
712
            }
713
714 1
            if (!$product->hasVariation() and is_object($product->getStock())) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
715
                $products[$key]['stock_status'] = $product->getStock()->get();
716 View Code Duplication
            } else {
717
                // alle ikke lagervarer der skal vises i webshop skal have en for_sale
718 1
                if ($product->get('stock') == 0 and $product->get('do_show') == 1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
719 1
                    $products[$key]['stock_status'] = array('for_sale' => 100); // kun til at stock_status
720 1
                } else {
721
                    $products[$key]['stock_status'] = array();
722
                }
723
            }
724
            // den her skal vist lige kigges igennem, for den tager jo alt med p� nettet?
725
            // 0 = only stock
726 1 View Code Duplication
            if ($this->kernel->setting->get('intranet', 'webshop.show_online') == 0 and !empty($which) and $which=='webshop') { // only stock
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
727
                if (array_key_exists('for_sale', $products[$key]['stock_status']) and $products[$key]['stock_status']['for_sale'] <= 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
728
                    continue;
729
                }
730
            }
731 1
            $key++;
732 1
        }
733 2
        return $products;
734
    }
735
736 21
    function hasVariation()
737
    {
738 21
        return $this->get('has_variation');
739
    }
740
741
    /**
742
     * Set attribute for product
743
     *
744
     * @param integer $id     Attribute id to relate to this product
745
     *
746
     * @return boolean
747
     */
748 9
    public function setAttributeGroup($id)
749
    {
750 9
        if (!$this->get('has_variation')) {
751 1
            throw new Exception('You can not set attribute group for a product without variations!');
752
        }
753
754 8
        $db = MDB2::singleton(DB_DSN);
755 8
        $result = $db->query("SELECT id FROM product_x_attribute_group WHERE intranet_id = ".$db->quote($this->intranet->getId())." AND product_id=" . $this->getId()  . " AND product_attribute_group_id = " . (int)$id);
756 8
        if (PEAR::isError($result)) {
757
            throw new Exception('Error in query :'.$result->getUserInfo());
758
        }
759
760 8
        if ($result->numRows() > 0) {
761
            return true;
762
        }
763 8
        $result = $db->exec("INSERT INTO product_x_attribute_group SET product_id = " . $this->getId() . ", product_attribute_group_id = " . (int)$id . ", intranet_id = " . $this->intranet->getId());
764 8
        if (PEAR::isError($result)) {
765
            throw new Exception('Error in insert :'.$result->getUserInfo());
766
        }
767
768 8
        return true;
769
    }
770
771
    /**
772
     * Remove attribute for product
773
     *
774
     * @param integer $id     Attribute id to relate to this product
775
     *
776
     * @return boolean
777
     */
778 1
    public function removeAttributeGroup($id)
779
    {
780 1
        if (!$this->get('has_variation')) {
781
            throw new Exception('You can not remove attribute group for a product without variations!');
782
        }
783
784 1
        $db = MDB2::singleton(DB_DSN);
785 1
        $result = $db->exec("DELETE FROM product_x_attribute_group WHERE intranet_id = ".$db->quote($this->intranet->getId())." AND product_id=" . $this->getId()  . " AND product_attribute_group_id = " . (int)$id);
786 1
        if (PEAR::isError($result)) {
787
            throw new Exception('Error in query :'.$result->getUserInfo());
788
        }
789
790 1
        return ($result > 0);
791
    }
792
793
    /**
794
     * Get all attributes related to the product
795
     *
796
     * @todo Rewrite product_x_attribute_group to Doctrine.
797
     * @todo Add a field named attribute_number to product_x_attribute_group, to be sure
798
     *       that a attribute always relates to the correct attribute number on the variation.
799
     *
800
     * @return array
801
     */
802 7
    public function getAttributeGroups()
803
    {
804 7
        if (!$this->get('has_variation')) {
805
            throw new Exception('You can not get attribute groups for a product without variations!');
806
        }
807
808
        // takes groups despite the are deleted. That is probably the best behaviour for now
809
        // NOTE: Very important that it is ordered by product_attribute_group.id so the groups
810
        // does always get attached to the correct attribute number on the variation. Se above todo in method doc
811 7
        $db = MDB2::singleton(DB_DSN);
812 7
        $result = $db->query("SELECT product_attribute_group.* FROM product_x_attribute_group " .
813 7
                "INNER JOIN product_attribute_group " .
814 7
                    "ON product_x_attribute_group.product_attribute_group_id = product_attribute_group.id " .
815 7
                    "AND product_attribute_group.intranet_id = ".$db->quote($this->intranet->getId())." " .
816 7
                "WHERE product_x_attribute_group.intranet_id = ".$db->quote($this->intranet->getId())." " .
817 7
                    "AND product_x_attribute_group.product_id=" . $this->getId()  . " " .
818 7
                 "ORDER BY product_attribute_group.id");
819
820 7
        if (PEAR::isError($result)) {
821
            throw new Exception('Error in query :'.$result->getUserInfo());
822
        }
823
824 7
        return $result->fetchAll(MDB2_FETCHMODE_ASSOC);
825
    }
826
827
    /**
828
     * returns variation
829
     */
830 6 View Code Duplication
    public function getVariation($id = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
831
    {
832 6
        $gateway = new Intraface_modules_product_Variation_Gateway($this);
833 5
        if (intval($id) > 0) {
834 3
            return $gateway->findById($id);
835
        }
836 5
        $object = $gateway->getObject();
837 5
        unset($gateway);
838 5
        $object->product_id = $this->getId();
839 5
        return $object;
840
    }
841
842
    /**
843
     * Returns variation on the basis of attributes
844
     *
845
     * @param array $attributes Attributes to find variation from
846
     *        array('attribte1' => [id1], 'attribute2' => [id2]);
847
     */
848
    public function getVariationFromAttributes($attributes)
849
    {
850
        $gateway = new Intraface_modules_product_Variation_Gateway($this);
851
        return $gateway->findByAttributes($attributes);
852
    }
853
854
    /**
855
     * Returns all variations on product
856
     */
857 1
    public function getVariations()
858
    {
859 1
        $gateway = new Intraface_modules_product_Variation_Gateway($this);
860 1
        return $gateway->findAll();
861
    }
862
863
    /**
864
     * Checks whether any products has been created before
865
     *
866
     * @return integer
867
     */
868 1 View Code Duplication
    public function isFilledIn()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
869
    {
870 1
        $db = new DB_Sql;
871 1
        $db->query("SELECT count(*) AS antal FROM product WHERE intranet_id = " . $this->intranet->getId());
872 1
        if ($db->nextRecord()) {
873 1
            return $db->f('antal');
874
        }
875
        return 0;
876
    }
877
878
    /**
879
     * Checks whether there is any active products. Differs from isFilledIn() by checking for active = 1
880
     *
881
     * @return integer
882
     */
883
    public function any()
884
    {
885
        $db = new DB_Sql;
886
        $db->query("SELECT id FROM product WHERE intranet_id = " . $this->intranet->getId()." AND active = 1");
887
        return $db->numRows();
888
    }
889
890 2
    public function isActive()
891
    {
892 2
        if ($this->value['active'] == 0) {
893 2
            return false;
894
        }
895
896 1
        return true;
897
    }
898
899
    /**
900
     * Public: Finde data til en liste
901
     *
902
     * Hvis den er fra webshop b�r den faktisk opsamle oplysninger om s�gningen
903
     * s� man kan se, hvad folk er interesseret i.
904
     * S�gemaskinen skal v�re tolerant for stavefejl
905
     *
906
     * @todo It is wrong to give currencies as parameter. Instead the list should
907
     *       be given as an object collection, and then currency should be given
908
     *       to the getPrice method.
909
     *
910
     * @param string $which valgfri s�geparameter - ikke aktiv endnu
911
     * @param object $currencies Collection of valid currencies.
912
     * @return array indeholdende kundedata til liste
913
     */
914
    function getList($which = 'all', $currencies = false)
915
    {
916
        $gateway = new Intraface_modules_product_Gateway($this->kernel);
917
        $gateway->setDBQuery($this->getDBQuery());
918
        return $gateway->getAllProducts($which, $currencies);
919
920
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
921
        switch ($this->getDBQuery()->getFilter('sorting')) {
922
            case 'date':
923
                    $this->getDBQuery()->setSorting("product.changed_date DESC");
924
                break;
925
            default:
926
                    $this->getDBQuery()->setSorting("detail.name ASC");
927
                break;
928
        }
929
930
        if ($search = $this->getDBQuery()->getFilter("search")) {
931
            $this->getDBQuery()->setCondition("detail.number = '".$search."'
932
                OR detail.name LIKE '%".$search."%'
933
                OR detail.description LIKE '%".$search."%'");
934
        }
935
        if ($keywords = $this->getDBQuery()->getFilter("keywords")) {
936
            $this->getDBQuery()->setKeyword($keywords);
937
        }
938
939
        if ($this->getDBQuery()->checkFilter('shop_id') && $this->getDBQuery()->checkFilter('category')) {
940
            $category_type = new Intraface_Category_Type('shop', $this->getDBQuery()->getFilter('shop_id'));
941
            $this->getDBQuery()->setJoin(
942
                'INNER',
943
                'ilib_category_append',
944
                'ilib_category_append.object_id = product.id',
945
                'ilib_category_append.intranet_id = '.$this->kernel->intranet->getId());
946
            $this->getDBQuery()->setJoin(
947
                'INNER',
948
                'ilib_category',
949
                'ilib_category_append.category_id = ilib_category.id',
950
                'ilib_category.intranet_id = '.$this->kernel->intranet->getId(). ' ' .
951
                    'AND ilib_category.belong_to = '.$category_type->getBelongTo().' ' .
952
                    'AND ilib_category.belong_to_id = '.$category_type->getBelongToId());
953
954
            $this->getDBQuery()->setCondition('ilib_category.id = '.$this->getDBQuery()->getFilter("category"));
955
956
        }
957
958
        if ($ids = $this->getDBQuery()->getFilter("ids")) {
959
            if (is_array($ids) && count($ids) > 0) {
960
                $this->getDBQuery()->setCondition("product.id IN (".implode(', ', $ids).")");
961
            } else {
962
                $this->getDBQuery()->setCondition('1 = 0');
963
            }
964
        }
965
966
        // @todo DEN OUTPUTTER IKKE DET RIGTIGE VED KEYWORD
967
        switch ($which) {
968
            case 'webshop':
969
                $this->getDBQuery()->setCondition("product.do_show = 1");
970
                break;
971
            case 'stock':
972
                $this->getDBQuery()->setCondition("product.stock = 1");
973
                break;
974
            case 'notpublished':
975
                $this->getDBQuery()->setCondition("product.do_show = 0");
976
                break;
977
            case 'all': // fall through
978
            default:
979
                $sql = '';
980
             break;
981
        }
982
983
        $i        = 0; // til at give arrayet en key
984
        $db       = $this->getDBQuery()->getRecordset("product.id", "", false);
985
        $products = array();
986
987
        while ($db->nextRecord()) {
988
            $product = new Product($this->kernel, $db->f("id"));
989
            $product->getPictures();
990
            $products[$i] = $product->get();
991
992
            $products[$i]['currency']['DKK']['price'] = $product->getDetails()->getPrice();
993
            $products[$i]['currency']['DKK']['price_incl_vat'] = $product->getDetails()->getPriceIncludingVat();
994
            $products[$i]['currency']['DKK']['before_price'] = $product->getDetails()->getBeforePrice();
995
            $products[$i]['currency']['DKK']['before_price_incl_vat'] = $product->getDetails()->getBeforePriceIncludingVat();
996
            if ($currencies && $currencies->count() > 0) {
997
                foreach ($currencies AS $currency) {
998
                    $products[$i]['currency'][$currency->getType()->getIsoCode()]['price'] = $product->getDetails()->getPriceInCurrency($currency);
999
                    $products[$i]['currency'][$currency->getType()->getIsoCode()]['price_incl_vat'] = $product->getDetails()->getPriceIncludingVatInCurrency($currency);
1000
                    $products[$i]['currency'][$currency->getType()->getIsoCode()]['before_price'] = $product->getDetails()->getBeforePriceInCurrency($currency);
1001
                    $products[$i]['currency'][$currency->getType()->getIsoCode()]['before_price_incl_vat'] = $product->getDetails()->getBeforePriceIncludingVatInCurrency($currency);
1002
                }
1003
            }
1004
1005
            if (!$product->get('has_variation') AND is_object($product->getStock()) AND strtolower(get_class($product->getStock())) == "stock") {
1006
                $products[$i]['stock_status'] = $product->getStock()->get();
1007
            } else {
1008
                // alle ikke lagervarer der skal vises i webshop skal have en for_sale
1009
                if ($product->get('stock') == 0 AND $product->get('do_show') == 1) {
1010
                    $products[$i]['stock_status'] = array('for_sale' => 100); // kun til at stock_status
1011
                } else {
1012
                    $products[$i]['stock_status'] = array();
1013
                }
1014
1015
            }
1016
1017
            // den her skal vist lige kigges igennem, for den tager jo alt med p� nettet?
1018
            // 0 = only stock
1019
            if ($this->kernel->setting->get('intranet', 'webshop.show_online') == 0 AND $which=='webshop') { // only stock
1020
                if (array_key_exists('for_sale', $products[$i]['stock_status']) AND $products[$i]['stock_status']['for_sale'] <= 0) {
1021
                    continue;
1022
                }
1023
            }
1024
            $i++;
1025
        }
1026
        $db->free();
1027
        return $products;
1028
        */
1029
    }
1030
1031
    /**
1032
     * Gets id
1033
     *
1034
     * @return integer
1035
     */
1036 27
    function getId()
1037
    {
1038 27
        return $this->id;
1039
    }
1040
1041
    /**
1042
     * Gets the details
1043
     *
1044
     * @return object
1045
     */
1046 66
    function getDetails()
1047
    {
1048 66
        return new ProductDetail($this, $this->old_product_detail_id);
1049
    }
1050
1051
    /**
1052
     * returns the possible units
1053
     *
1054
     * @return array units
1055
     */
1056
    public static function getUnits()
1057
    {
1058
        return ProductDetail::getUnits();
1059
    }
1060
}
1061