dolibarr  x.y.z
ProductAttribute.class.php
1 <?php
2 /* Copyright (C) 2016 Marcos GarcĂ­a <marcosgdf@gmail.com>
3  * Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
19 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
25 {
30  public $db;
34  public $module = 'variants';
35 
39  public $element = 'productattribute';
40 
44  public $table_element = 'product_attribute';
45 
49  public $table_element_line = 'product_attribute_value';
50 
54  public $fk_element = 'fk_product_attribute';
55 
60  public $ismultientitymanaged = 1;
61 
65  public $isextrafieldmanaged = 0;
66 
70  public $picto = 'product';
71 
100  public $fields=array(
101  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
102  'ref' => array('type'=>'varchar(255)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''),
103  'ref_ext' => array('type' => 'varchar(255)', 'label' => 'ExternalRef', 'enabled' => 1, 'visible' => 0, 'position' => 20, 'searchall'=>1),
104  'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'help'=>"", 'showoncombobox'=>'1',),
105  'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>40, 'notnull'=>1,),
106  );
107  public $id;
108  public $ref;
109  public $ref_ext;
110  public $label;
111  public $position;
112 
116  public $lines = array();
120  public $line;
121 
125  public $is_used_by_products;
126 
127 
133  public function __construct(DoliDB $db)
134  {
135  global $conf, $langs;
136 
137  $this->db = $db;
138  $this->entity = $conf->entity;
139 
140  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
141  $this->fields['rowid']['visible'] = 0;
142  }
143  if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
144  $this->fields['entity']['enabled'] = 0;
145  }
146 
147  // Unset fields that are disabled
148  foreach ($this->fields as $key => $val) {
149  if (isset($val['enabled']) && empty($val['enabled'])) {
150  unset($this->fields[$key]);
151  }
152  }
153 
154  // Translate some data of arrayofkeyval
155  if (is_object($langs)) {
156  foreach ($this->fields as $key => $val) {
157  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
158  foreach ($val['arrayofkeyval'] as $key2 => $val2) {
159  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
160  }
161  }
162  }
163  }
164  }
165 
173  public function create(User $user, $notrigger = 0)
174  {
175  global $langs;
176  $error = 0;
177 
178  // Clean parameters
179  $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
180  $this->label = trim($this->label);
181  $this->position = $this->position > 0 ? $this->position : 0;
182 
183  // Position to use
184  if (empty($this->position)) {
185  $positionmax = $this->getMaxAttributesPosition();
186  $this->position = $positionmax + 1;
187  }
188 
189  // Check parameters
190  if (empty($this->ref)) {
191  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
192  $error++;
193  }
194  if (empty($this->label)) {
195  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
196  $error++;
197  }
198  if ($error) {
199  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
200  return -1;
201  }
202 
203  $this->db->begin();
204 
205  $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " (";
206  $sql .= " ref, ref_ext, label, entity, position";
207  $sql .= ")";
208  $sql .= " VALUES (";
209  $sql .= " '" . $this->db->escape($this->ref) . "'";
210  $sql .= ", '" . $this->db->escape($this->ref_ext) . "'";
211  $sql .= ", '" . $this->db->escape($this->label) . "'";
212  $sql .= ", " . ((int) $this->entity);
213  $sql .= ", " . ((int) $this->position);
214  $sql .= ")";
215 
216  dol_syslog(__METHOD__, LOG_DEBUG);
217  $resql = $this->db->query($sql);
218  if (!$resql) {
219  $this->errors[] = "Error " . $this->db->lasterror();
220  $error++;
221  }
222 
223  if (!$error) {
224  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
225  }
226 
227  if (!$error && !$notrigger) {
228  // Call trigger
229  $result = $this->call_trigger('PRODUCT_ATTRIBUTE_CREATE', $user);
230  if ($result < 0) {
231  $error++;
232  }
233  // End call triggers
234  }
235 
236  if (!$error) {
237  $this->db->commit();
238  return $this->id;
239  } else {
240  $this->db->rollback();
241  return -1 * $error;
242  }
243  }
244 
251  public function fetch($id)
252  {
253  global $langs;
254  $error = 0;
255 
256  // Clean parameters
257  $id = $id > 0 ? $id : 0;
258 
259  // Check parameters
260  if (empty($id)) {
261  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
262  $error++;
263  }
264  if ($error) {
265  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
266  return -1;
267  }
268 
269  $sql = "SELECT rowid, ref, ref_ext, label, position";
270  $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
271  $sql .= " WHERE rowid = " . ((int) $id);
272  $sql .= " AND entity IN (" . getEntity('product') . ")";
273 
274  dol_syslog(__METHOD__, LOG_DEBUG);
275  $resql = $this->db->query($sql);
276  if (!$resql) {
277  $this->errors[] = "Error " . $this->db->lasterror();
278  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
279  return -1;
280  }
281 
282  $numrows = $this->db->num_rows($resql);
283  if ($numrows) {
284  $obj = $this->db->fetch_object($resql);
285 
286  $this->id = $obj->rowid;
287  $this->ref = $obj->ref;
288  $this->ref_ext = $obj->ref_ext;
289  $this->label = $obj->label;
290  $this->rang = $obj->position; // deprecated
291  $this->position = $obj->position;
292  }
293  $this->db->free($resql);
294 
295  return $numrows;
296  }
297 
303  public function fetchAll()
304  {
305  $return = array();
306 
307  $sql = "SELECT rowid, ref, ref_ext, label, position";
308  $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
309  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
310  $sql .= $this->db->order("position", "asc");
311 
312  dol_syslog(__METHOD__, LOG_DEBUG);
313  $resql = $this->db->query($sql);
314  if (!$resql) {
315  $this->errors[] = "Error " . $this->db->lasterror();
316  dol_print_error($this->db);
317  return $return;
318  }
319 
320  while ($obj = $this->db->fetch_object($resql)) {
321  $tmp = new ProductAttribute($this->db);
322 
323  $tmp->id = $obj->rowid;
324  $tmp->ref = $obj->ref;
325  $tmp->ref_ext = $obj->ref_ext;
326  $tmp->label = $obj->label;
327  $tmp->rang = $obj->position; // deprecated
328  $tmp->position = $obj->position;
329 
330  $return[] = $tmp;
331  }
332 
333  return $return;
334  }
335 
343  public function update(User $user, $notrigger = 0)
344  {
345  global $langs;
346  $error = 0;
347 
348  // Clean parameters
349  $this->id = $this->id > 0 ? $this->id : 0;
350  $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
351  $this->label = trim($this->label);
352 
353  // Check parameters
354  if (empty($this->id)) {
355  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
356  $error++;
357  }
358  if (empty($this->ref)) {
359  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
360  $error++;
361  }
362  if (empty($this->label)) {
363  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
364  $error++;
365  }
366  if ($error) {
367  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
368  return -1;
369  }
370 
371  $this->db->begin();
372 
373  $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET";
374 
375  $sql .= " ref = '" . $this->db->escape($this->ref) . "'";
376  $sql .= ", ref_ext = '" . $this->db->escape($this->ref_ext) . "'";
377  $sql .= ", label = '" . $this->db->escape($this->label) . "'";
378  $sql .= ", position = " . ((int) $this->position);
379 
380  $sql .= " WHERE rowid = " . ((int) $this->id);
381 
382  dol_syslog(__METHOD__, LOG_DEBUG);
383  $resql = $this->db->query($sql);
384  if (!$resql) {
385  $this->errors[] = "Error " . $this->db->lasterror();
386  $error++;
387  }
388 
389  if (!$error && !$notrigger) {
390  // Call trigger
391  $result = $this->call_trigger('PRODUCT_ATTRIBUTE_MODIFY', $user);
392  if ($result < 0) {
393  $error++;
394  }
395  // End call triggers
396  }
397 
398  if (!$error) {
399  $this->db->commit();
400  return 1;
401  } else {
402  $this->db->rollback();
403  return -1 * $error;
404  }
405  }
406 
414  public function delete(User $user, $notrigger = 0)
415  {
416  global $langs;
417  $error = 0;
418 
419  // Clean parameters
420  $this->id = $this->id > 0 ? $this->id : 0;
421 
422  // Check parameters
423  if (empty($this->id)) {
424  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
425  $error++;
426  }
427  if ($error) {
428  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
429  return -1;
430  }
431 
432  $result = $this->isUsed();
433  if ($result < 0) {
434  return -1;
435  } elseif ($result > 0) {
436  $this->errors[] = $langs->trans('ErrorAttributeIsUsedIntoProduct');
437  return -1;
438  }
439 
440  $this->db->begin();
441 
442  if (!$notrigger) {
443  // Call trigger
444  $result = $this->call_trigger('PRODUCT_ATTRIBUTE_DELETE', $user);
445  if ($result < 0) {
446  $error++;
447  }
448  // End call triggers
449  }
450 
451  if (!$error) {
452  // Delete values
453  $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element_line;
454  $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
455 
456  dol_syslog(__METHOD__ . ' - Delete values', LOG_DEBUG);
457  $resql = $this->db->query($sql);
458  if (!$resql) {
459  $this->errors[] = "Error " . $this->db->lasterror();
460  $error++;
461  }
462  }
463 
464  if (!$error) {
465  $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element;
466  $sql .= " WHERE rowid = " . ((int) $this->id);
467 
468  dol_syslog(__METHOD__ . ' - Delete attribute', LOG_DEBUG);
469  $resql = $this->db->query($sql);
470  if (!$resql) {
471  $this->errors[] = "Error " . $this->db->lasterror();
472  $error++;
473  }
474  }
475 
476  if (!$error) {
477  $this->db->commit();
478  return 1;
479  } else {
480  $this->db->rollback();
481  return -1 * $error;
482  }
483  }
484 
485  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
492  public function fetch_lines($filters = '')
493  {
494  // phpcs:enable
495  global $langs;
496 
497  $this->lines = array();
498 
499  $error = 0;
500 
501  // Clean parameters
502  $this->id = $this->id > 0 ? $this->id : 0;
503 
504  // Check parameters
505  if (empty($this->id)) {
506  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
507  $error++;
508  }
509  if ($error) {
510  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
511  return -1;
512  }
513 
514  $sql = "SELECT td.rowid, td.fk_product_attribute, td.ref, td.value, td.position";
515  $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element_line . " AS td";
516  $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $this->table_element . " AS t ON t.rowid = td." . $this->fk_element;
517  $sql .= " WHERE t.rowid = " . ((int) $this->id);
518  $sql .= " AND t.entity IN (" . getEntity('product') . ")";
519  if ($filters) {
520  $sql .= $filters;
521  }
522  $sql .= $this->db->order("td.position", "asc");
523 
524  dol_syslog(__METHOD__, LOG_DEBUG);
525  $resql = $this->db->query($sql);
526  if (!$resql) {
527  $this->errors[] = "Error " . $this->db->lasterror();
528  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
529  return -3;
530  }
531 
532  $num = $this->db->num_rows($resql);
533  if ($num) {
534  $i = 0;
535  while ($i < $num) {
536  $obj = $this->db->fetch_object($resql);
537 
538  $line = new ProductAttributeValue($this->db);
539 
540  $line->id = $obj->rowid;
541  $line->fk_product_attribute = $obj->fk_product_attribute;
542  $line->ref = $obj->ref;
543  $line->value = $obj->value;
544  $line->position = $obj->position;
545 
546  $this->lines[$i] = $line;
547  $i++;
548  }
549  }
550  $this->db->free($resql);
551 
552  return $num;
553  }
554 
561  public function getLinesArray($filters = '')
562  {
563  return $this->fetch_lines($filters);
564  }
565 
579  public function addLine($ref, $value, $position = -1, $notrigger = 0)
580  {
581  global $langs, $user;
582  dol_syslog(__METHOD__ . " id={$this->id}, ref=$ref, value=$value, notrigger=$notrigger");
583  $error = 0;
584 
585  // Clean parameters
586  $this->id = $this->id > 0 ? $this->id : 0;
587 
588  // Check parameters
589  if (empty($this->id)) {
590  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
591  $error++;
592  }
593  if ($error) {
594  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
595  return -1;
596  }
597 
598  $this->db->begin();
599 
600  //Fetch current line from the database and then clone the object and set it in $oldcopy property
601  $this->line = new ProductAttributeValue($this->db);
602 
603  // Position to use
604  $positiontouse = $position;
605  if ($positiontouse == -1) {
606  $positionmax = $this->line_max(0);
607  $positiontouse = $positionmax + 1;
608  }
609 
610  $this->line->context = $this->context;
611  $this->line->fk_product_attribute = $this->id;
612  $this->line->ref = $ref;
613  $this->line->value = $value;
614  $this->line->position = $positiontouse;
615 
616  $result = $this->line->create($user, $notrigger);
617 
618  if ($result < 0) {
619  $this->error = $this->line->error;
620  $this->errors = $this->line->errors;
621  $this->db->rollback();
622  return -1;
623  } else {
624  $this->db->commit();
625  return $this->line->id;
626  }
627  }
628 
629 
639  public function updateLine($lineid, $ref, $value, $notrigger = 0)
640  {
641  global $user;
642 
643  dol_syslog(__METHOD__ . " lineid=$lineid, ref=$ref, value=$value, notrigger=$notrigger");
644 
645  // Clean parameters
646  $lineid = $lineid > 0 ? $lineid : 0;
647 
648  $this->db->begin();
649 
650  //Fetch current line from the database and then clone the object and set it in $oldcopy property
651  $this->line = new ProductAttributeValue($this->db);
652  $result = $this->line->fetch($lineid);
653  if ($result > 0) {
654  $this->line->oldcopy = clone $this->line;
655 
656  $this->line->context = $this->context;
657  $this->line->ref = $ref;
658  $this->line->value = $value;
659 
660  $result = $this->line->update($user, $notrigger);
661  }
662 
663  if ($result < 0) {
664  $this->error = $this->line->error;
665  $this->errors = $this->line->errors;
666  $this->db->rollback();
667  return -1;
668  } else {
669  $this->db->commit();
670  return $result;
671  }
672  }
673 
682  public function deleteLine(User $user, $lineid, $notrigger = 0)
683  {
684  dol_syslog(__METHOD__ . " lineid=$lineid, notrigger=$notrigger");
685 
686  // Clean parameters
687  $lineid = $lineid > 0 ? $lineid : 0;
688 
689  $this->db->begin();
690 
691  //Fetch current line from the database
692  $this->line = new ProductAttributeValue($this->db);
693  $result = $this->line->fetch($lineid);
694  if ($result > 0) {
695  $this->line->context = $this->context;
696 
697  $result = $this->line->delete($user, $notrigger);
698  }
699 
700  if ($result < 0) {
701  $this->error = $this->line->error;
702  $this->errors = $this->line->errors;
703  $this->db->rollback();
704  return -1;
705  } else {
706  $this->db->commit();
707  return $result;
708  }
709  }
710 
716  public function countChildValues()
717  {
718  global $langs;
719  $error = 0;
720  $count = 0;
721 
722  // Clean parameters
723  $this->id = $this->id > 0 ? $this->id : 0;
724 
725  // Check parameters
726  if (empty($this->id)) {
727  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
728  $error++;
729  }
730  if ($error) {
731  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
732  return -1;
733  }
734 
735  $sql = "SELECT COUNT(*) AS count";
736  $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element_line;
737  $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
738 
739  dol_syslog(__METHOD__, LOG_DEBUG);
740  $resql = $this->db->query($sql);
741  if (!$resql) {
742  $this->errors[] = "Error " . $this->db->lasterror();
743  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
744  return -1;
745  }
746 
747  if ($obj = $this->db->fetch_object($resql)) {
748  $count = $obj->count;
749  }
750 
751  return $count;
752  }
753 
759  public function countChildProducts()
760  {
761  global $langs;
762  $error = 0;
763  $count = 0;
764 
765  // Clean parameters
766  $this->id = $this->id > 0 ? $this->id : 0;
767 
768  // Check parameters
769  if (empty($this->id)) {
770  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
771  $error++;
772  }
773  if ($error) {
774  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
775  return -1;
776  }
777 
778  $sql = "SELECT COUNT(*) AS count";
779  $sql .= " FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val AS pac2v";
780  $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination AS pac ON pac2v.fk_prod_combination = pac.rowid";
781  $sql .= " WHERE pac2v.fk_prod_attr = " . ((int) $this->id);
782  $sql .= " AND pac.entity IN (" . getEntity('product') . ")";
783 
784  dol_syslog(__METHOD__, LOG_DEBUG);
785  $resql = $this->db->query($sql);
786  if (!$resql) {
787  $this->errors[] = "Error " . $this->db->lasterror();
788  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
789  return -1;
790  }
791 
792  if ($obj = $this->db->fetch_object($resql)) {
793  $count = $obj->count;
794  }
795 
796  return $count;
797  }
798 
804  public function isUsed()
805  {
806  global $langs;
807  $error = 0;
808 
809  // Clean parameters
810  $this->id = $this->id > 0 ? $this->id : 0;
811 
812  // Check parameters
813  if (empty($this->id)) {
814  $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
815  $error++;
816  }
817  if ($error) {
818  dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
819  return -1;
820  }
821 
822  $sql = "SELECT COUNT(*) AS nb FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_attr = " . ((int) $this->id);
823 
824  dol_syslog(__METHOD__, LOG_DEBUG);
825  $resql = $this->db->query($sql);
826  if (!$resql) {
827  $this->errors[] = "Error " . $this->db->lasterror();
828  return -1;
829  }
830 
831  $used = 0;
832  if ($obj = $this->db->fetch_object($resql)) {
833  $used = $obj->nb;
834  }
835 
836  return $used ? 1 : 0;
837  }
838 
847  public function attributeOrder($renum = false, $rowidorder = 'ASC')
848  {
849  // Count number of attributes to reorder (according to choice $renum)
850  $nl = 0;
851  $sql = "SELECT count(rowid) FROM " . MAIN_DB_PREFIX . $this->table_element;
852  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
853  if (!$renum) {
854  $sql .= " AND position = 0";
855  } else {
856  $sql .= " AND position <> 0";
857  }
858 
859  dol_syslog(__METHOD__, LOG_DEBUG);
860  $resql = $this->db->query($sql);
861  if ($resql) {
862  $row = $this->db->fetch_row($resql);
863  $nl = $row[0];
864  } else {
865  dol_print_error($this->db);
866  }
867  if ($nl > 0) {
868  // The goal of this part is to reorder all attributes.
869  $rows = array();
870 
871  // We first search all attributes
872  $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . $this->table_element;
873  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
874  $sql .= " ORDER BY position ASC, rowid " . $rowidorder;
875 
876  dol_syslog(__METHOD__ . " search all attributes", LOG_DEBUG);
877  $resql = $this->db->query($sql);
878  if ($resql) {
879  $i = 0;
880  $num = $this->db->num_rows($resql);
881  while ($i < $num) {
882  $row = $this->db->fetch_row($resql);
883  $rows[] = $row[0]; // Add attributes into array rows
884  $i++;
885  }
886 
887  // Now we set a new number for each attributes
888  if (!empty($rows)) {
889  foreach ($rows as $key => $row) {
890  $this->updatePositionOfAttribute($row, ($key + 1));
891  }
892  }
893  } else {
894  dol_print_error($this->db);
895  }
896  }
897  return 1;
898  }
899 
907  public function updatePositionOfAttribute($rowid, $position)
908  {
909  global $hookmanager;
910 
911  $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position);
912  $sql .= " WHERE rowid = " . ((int) $rowid);
913 
914  dol_syslog(__METHOD__, LOG_DEBUG);
915  if (!$this->db->query($sql)) {
916  dol_print_error($this->db);
917  return -1;
918  } else {
919  $parameters = array('rowid' => $rowid, 'position' => $position);
920  $action = '';
921  $reshook = $hookmanager->executeHooks('afterPositionOfAttributeUpdate', $parameters, $this, $action);
922  return 1;
923  }
924  }
925 
932  public function getPositionOfAttribute($rowid)
933  {
934  $sql = "SELECT position FROM " . MAIN_DB_PREFIX . $this->table_element;
935  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
936 
937  dol_syslog(__METHOD__, LOG_DEBUG);
938  $resql = $this->db->query($sql);
939  if ($resql) {
940  $row = $this->db->fetch_row($resql);
941  return $row[0];
942  }
943 
944  return 0;
945  }
946 
953  public function attributeMoveUp($rowid)
954  {
955  $this->attributeOrder(false, 'ASC');
956 
957  // Get position of attribute
958  $position = $this->getPositionOfAttribute($rowid);
959 
960  // Update position of attribute
961  $this->updateAttributePositionUp($rowid, $position);
962  }
963 
970  public function attributeMoveDown($rowid)
971  {
972  $this->attributeOrder(false, 'ASC');
973 
974  // Get position of line
975  $position = $this->getPositionOfAttribute($rowid);
976 
977  // Get max value for position
978  $max = $this->getMaxAttributesPosition();
979 
980  // Update position of attribute
981  $this->updateAttributePositionDown($rowid, $position, $max);
982  }
983 
991  public function updateAttributePositionUp($rowid, $position)
992  {
993  if ($position > 1) {
994  $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position);
995  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
996  $sql .= " AND position = " . ((int) ($position - 1));
997  if ($this->db->query($sql)) {
998  $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) ($position - 1));
999  $sql .= " WHERE rowid = " . ((int) $rowid);
1000  if (!$this->db->query($sql)) {
1001  dol_print_error($this->db);
1002  }
1003  } else {
1004  dol_print_error($this->db);
1005  }
1006  }
1007  }
1008 
1017  public function updateAttributePositionDown($rowid, $position, $max)
1018  {
1019  if ($position < $max) {
1020  $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position);
1021  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
1022  $sql .= " AND position = " . ((int) ($position + 1));
1023  if ($this->db->query($sql)) {
1024  $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) ($position + 1));
1025  $sql .= " WHERE rowid = " . ((int) $rowid);
1026  if (!$this->db->query($sql)) {
1027  dol_print_error($this->db);
1028  }
1029  } else {
1030  dol_print_error($this->db);
1031  }
1032  }
1033  }
1034 
1040  public function getMaxAttributesPosition()
1041  {
1042  // Search the last position of attributes
1043  $sql = "SELECT max(position) FROM " . MAIN_DB_PREFIX . $this->table_element;
1044  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
1045 
1046  dol_syslog(__METHOD__, LOG_DEBUG);
1047  $resql = $this->db->query($sql);
1048  if ($resql) {
1049  $row = $this->db->fetch_row($resql);
1050  return $row[0];
1051  }
1052 
1053  return 0;
1054  }
1055 
1062  public function attributesAjaxOrder($rows)
1063  {
1064  $num = count($rows);
1065  for ($i = 0; $i < $num; $i++) {
1066  $this->updatePositionOfAttribute($rows[$i], ($i + 1));
1067  }
1068  }
1069 
1080  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1081  {
1082  global $conf, $langs, $hookmanager;
1083 
1084  if (!empty($conf->dol_no_mouse_hover)) {
1085  $notooltip = 1; // Force disable tooltips
1086  }
1087 
1088  $result = '';
1089 
1090  $label = img_picto('', $this->picto) . ' <u>' . $langs->trans("ProductAttribute") . '</u>';
1091  if (isset($this->status)) {
1092  $label .= ' ' . $this->getLibStatut(5);
1093  }
1094  $label .= '<br>';
1095  $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
1096  if (!empty($this->label)) {
1097  $label .= '<br><b>' . $langs->trans('Label') . ':</b> ' . $this->label;
1098  }
1099 
1100  $url = dol_buildpath('/variants/card.php', 1) . '?id=' . $this->id;
1101 
1102  if ($option != 'nolink') {
1103  // Add param to save lastsearch_values or not
1104  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1105  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1106  $add_save_lastsearch_values = 1;
1107  }
1108  if ($url && $add_save_lastsearch_values) {
1109  $url .= '&save_lastsearch_values=1';
1110  }
1111  }
1112 
1113  $linkclose = '';
1114  if (empty($notooltip)) {
1115  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1116  $label = $langs->trans("ShowProductAttribute");
1117  $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
1118  }
1119  $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
1120  $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
1121  } else {
1122  $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
1123  }
1124 
1125  if ($option == 'nolink' || empty($url)) {
1126  $linkstart = '<span';
1127  } else {
1128  $linkstart = '<a href="' . $url . '"';
1129  }
1130  $linkstart .= $linkclose . '>';
1131  if ($option == 'nolink' || empty($url)) {
1132  $linkend = '</span>';
1133  } else {
1134  $linkend = '</a>';
1135  }
1136 
1137  $result .= $linkstart;
1138 
1139  if (empty($this->showphoto_on_popup)) {
1140  if ($withpicto) {
1141  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1142  }
1143  } else {
1144  if ($withpicto) {
1145  require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1146 
1147  list($class, $module) = explode('@', $this->picto);
1148  $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
1149  $filearray = dol_dir_list($upload_dir, "files");
1150  $filename = $filearray[0]['name'];
1151  if (!empty($filename)) {
1152  $pospoint = strpos($filearray[0]['name'], '.');
1153 
1154  $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
1155  if (empty($conf->global->{strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS'})) {
1156  $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo' . $module . '" alt="No photo" border="0" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div></div>';
1157  } else {
1158  $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div>';
1159  }
1160 
1161  $result .= '</div>';
1162  } else {
1163  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1164  }
1165  }
1166  }
1167 
1168  if ($withpicto != 2) {
1169  $result .= $this->ref;
1170  }
1171 
1172  $result .= $linkend;
1173  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1174 
1175  global $action, $hookmanager;
1176  $hookmanager->initHooks(array('variantsdao'));
1177  $parameters = array('id' => $this->id, 'getnomurl' => $result);
1178  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1179  if ($reshook > 0) {
1180  $result = $hookmanager->resPrint;
1181  } else {
1182  $result .= $hookmanager->resPrint;
1183  }
1184 
1185  return $result;
1186  }
1187 
1194  public function getLabelStatus($mode = 0)
1195  {
1196  return $this->LibStatut(0, $mode);
1197  }
1198 
1205  public function getLibStatut($mode = 0)
1206  {
1207  return $this->LibStatut(0, $mode);
1208  }
1209 
1210  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1218  public function LibStatut($status, $mode = 1)
1219  {
1220  // phpcs:enable
1221  return '';
1222  }
1223 
1224  // --------------------
1225  // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
1226  // --------------------
1227 
1228  /* This is to show add lines */
1229 
1239  public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/variants/tpl')
1240  {
1241  global $conf, $user, $langs, $object, $hookmanager;
1242  global $form;
1243 
1244  // Output template part (modules that overwrite templates must declare this into descriptor)
1245  // Use global variables + $dateSelector + $seller and $buyer
1246  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
1247  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
1248  foreach ($dirtpls as $module => $reldir) {
1249  if (!empty($module)) {
1250  $tpl = dol_buildpath($reldir . '/productattributevalueline_create.tpl.php');
1251  } else {
1252  $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_create.tpl.php';
1253  }
1254 
1255  if (empty($conf->file->strict_mode)) {
1256  $res = @include $tpl;
1257  } else {
1258  $res = include $tpl; // for debug
1259  }
1260  if ($res) {
1261  break;
1262  }
1263  }
1264  }
1265 
1266  /* This is to show array of line of details */
1267 
1283  public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/variants/tpl', $addcreateline = 0)
1284  {
1285  global $conf, $hookmanager, $langs, $user, $form, $object;
1286  global $mysoc;
1287  // TODO We should not use global var for this
1288  global $disableedit, $disablemove, $disableremove;
1289 
1290  $num = count($this->lines);
1291 
1292  $parameters = array('num' => $num, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
1293  $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1294  if (empty($reshook)) {
1295  // Output template part (modules that overwrite templates must declare this into descriptor)
1296  // Use global variables + $dateSelector + $seller and $buyer
1297  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
1298  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
1299  foreach ($dirtpls as $module => $reldir) {
1300  if (!empty($module)) {
1301  $tpl = dol_buildpath($reldir . '/productattributevalueline_title.tpl.php');
1302  } else {
1303  $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_title.tpl.php';
1304  }
1305  if (empty($conf->file->strict_mode)) {
1306  $res = @include $tpl;
1307  } else {
1308  $res = include $tpl; // for debug
1309  }
1310  if ($res) {
1311  break;
1312  }
1313  }
1314  }
1315 
1316 
1317  if ($addcreateline) {
1318  // Form to add new line
1319  if ($action != 'selectlines') {
1320  if ($action != 'editline') {
1321  // Add products/services form
1322 
1323  $parameters = array();
1324  $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1325  if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1326  if (empty($reshook))
1327  $object->formAddObjectLine(1, $mysoc, $buyer);
1328  }
1329  }
1330  }
1331 
1332  $i = 0;
1333 
1334  print "<!-- begin printObjectLines() -->\n";
1335  foreach ($this->lines as $line) {
1336  if (is_object($hookmanager)) { // Old code is commented on preceding line.
1337  $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'selected' => $selected, 'table_element_line' => $line->table_element);
1338  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1339  }
1340  if (empty($reshook)) {
1341  $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, null, $defaulttpldir);
1342  }
1343 
1344  $i++;
1345  }
1346  print "<!-- end printObjectLines() -->\n";
1347  }
1348 
1366  public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/variants/tpl')
1367  {
1368  global $conf, $langs, $user, $object, $hookmanager;
1369  global $form;
1370  global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
1371 
1372  $object_rights = $user->rights->variants;
1373 
1374  // Line in view mode
1375  if ($action != 'editline' || $selected != $line->id) {
1376  // Output template part (modules that overwrite templates must declare this into descriptor)
1377  // Use global variables + $dateSelector + $seller and $buyer
1378  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
1379  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
1380  foreach ($dirtpls as $module => $reldir) {
1381  if (!empty($module)) {
1382  $tpl = dol_buildpath($reldir . '/productattributevalueline_view.tpl.php');
1383  } else {
1384  $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_view.tpl.php';
1385  }
1386 
1387  if (empty($conf->file->strict_mode)) {
1388  $res = @include $tpl;
1389  } else {
1390  $res = include $tpl; // for debug
1391  }
1392  if ($res) {
1393  break;
1394  }
1395  }
1396  }
1397 
1398  // Line in update mode
1399  if ($action == 'editline' && $selected == $line->id) {
1400  // Output template part (modules that overwrite templates must declare this into descriptor)
1401  // Use global variables + $dateSelector + $seller and $buyer
1402  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
1403  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
1404  foreach ($dirtpls as $module => $reldir) {
1405  if (!empty($module)) {
1406  $tpl = dol_buildpath($reldir . '/productattributevalueline_edit.tpl.php');
1407  } else {
1408  $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_edit.tpl.php';
1409  }
1410 
1411  if (empty($conf->file->strict_mode)) {
1412  $res = @include $tpl;
1413  } else {
1414  $res = include $tpl; // for debug
1415  }
1416  if ($res) {
1417  break;
1418  }
1419  }
1420  }
1421  }
1422 
1423  /* This is to show array of line of details of source object */
1424 }
$object ref
Definition: info.php:78
Parent class of all other business classes (invoices, contracts, proposals, orders,...
errorsToString()
Method to output saved errors.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
Class ProductAttribute Used to represent a product attribute.
updateAttributePositionDown($rowid, $position, $max)
Update position of attribute (down)
updatePositionOfAttribute($rowid, $position)
Update position of line (rang)
addLine($ref, $value, $position=-1, $notrigger=0)
attributeMoveDown($rowid)
Update a attribute to have a lower position.
fetch($id)
Fetches the properties of a product attribute.
update(User $user, $notrigger=0)
Updates a product attribute.
attributeOrder($renum=false, $rowidorder='ASC')
Save a new position (field position) for details lines.
fetchAll()
Returns an array of all product variants.
updateAttributePositionUp($rowid, $position)
Update position of attribute (up)
isUsed()
Test if used by a product.
updateLine($lineid, $ref, $value, $notrigger=0)
Update a line.
__construct(DoliDB $db)
Constructor.
getMaxAttributesPosition()
Get max value used for position of attributes.
LibStatut($status, $mode=1)
Return label of a status.
attributesAjaxOrder($rows)
Update position of attributes with ajax.
getLinesArray($filters='')
Retrieve an array of proposal lines.
fetch_lines($filters='')
Load array lines.
attributeMoveUp($rowid)
Update a attribute to have a higher position.
create(User $user, $notrigger=0)
Creates a product attribute.
countChildProducts()
Returns the number of products that are using this attribute.
deleteLine(User $user, $lineid, $notrigger=0)
Delete a line.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/variants/tpl')
Show add free and predefined products/services form.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
getLibStatut($mode=0)
Return label of status of product attribute.
getPositionOfAttribute($rowid)
Get position of attribute.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/variants/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir='/variants/tpl', $addcreateline=0)
Return HTML table for object lines TODO Move this into an output class file (htmlline....
getLabelStatus($mode=0)
Return the label of the status.
countChildValues()
Returns the number of values for this attribute.
Class ProductAttributeValue Used to represent a product attribute value.
Class to manage Dolibarr users.
Definition: user.class.php:45
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:61
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
$conf db
API class for accounts.
Definition: inc.php:41