dolibarr 22.0.5
categorie.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005 Matthieu Valleton <mv@seeschloss.org>
3 * Copyright (C) 2005 Davoleau Brice <brice.davoleau@gmail.com>
4 * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
5 * Copyright (C) 2006-2012 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
7 * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
8 * Copyright (C) 2013-2016 Juanjo Menent <jmenent@2byte.es>
9 * Copyright (C) 2013-2018 Philippe Grand <philippe.grand@atoo-net.com>
10 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
11 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
12 * Copyright (C) 2016-2024 Charlene Benke <charlene@patas-monkey.com>
13 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
14 * Copyright (C) 2022-2023 Solution Libre SAS <contact@solution-libre.fr>
15 * Copyright (C) 2023-2024 Benjamin Falière <benjamin.faliere@altairis.fr>
16 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
17 * Copyright (C) 2025 Alexandre Spangaro <alexandre@inovea-conseil.com>
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 3 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <https://www.gnu.org/licenses/>.
31 */
32
39require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
40require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
41require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
42require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
43require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
44require_once DOL_DOCUMENT_ROOT.'/knowledgemanagement/class/knowledgerecord.class.php';
45
46
51{
52 // Categories types (we use string because we want to accept any modules/types in a future)
53 const TYPE_PRODUCT = 'product';
54 const TYPE_SUPPLIER = 'supplier';
55 const TYPE_CUSTOMER = 'customer';
56 const TYPE_MEMBER = 'member';
57 const TYPE_CONTACT = 'contact';
58 const TYPE_USER = 'user';
59 const TYPE_PROJECT = 'project';
60 const TYPE_ACCOUNT = 'bank_account';
61 const TYPE_BANK_LINE = 'bank_line';
62 const TYPE_WAREHOUSE = 'warehouse';
63 const TYPE_ACTIONCOMM = 'actioncomm';
64 const TYPE_WEBSITE_PAGE = 'website_page';
65 const TYPE_TICKET = 'ticket';
66 const TYPE_KNOWLEDGEMANAGEMENT = 'knowledgemanagement';
67 const TYPE_FICHINTER = 'fichinter';
68 const TYPE_ORDER = 'order';
69 const TYPE_INVOICE = 'invoice';
70 const TYPE_SUPPLIER_ORDER = 'supplier_order';
71 const TYPE_SUPPLIER_INVOICE = 'supplier_invoice';
72
73
77 public $picto = 'category';
78
79
83 public $MAP_ID = array(
84 'product' => 0,
85 'service' => 0,
86 'supplier' => 1,
87 'customer' => 2,
88 'member' => 3,
89 'contact' => 4,
90 'bank_account' => 5,
91 'project' => 6,
92 'user' => 7,
93 'bank_line' => 8,
94 'warehouse' => 9,
95 'actioncomm' => 10,
96 'website_page' => 11,
97 'ticket' => 12,
98 'knowledgemanagement' => 13,
99 'fichinter' => 14,
100 'order' => 16,
101 'invoice' => 17,
102 'supplier_order' => 20,
103 'supplier_invoice' => 21
104 );
105
111 public static $MAP_ID_TO_CODE = array(
112 0 => 'product',
113 1 => 'supplier',
114 2 => 'customer',
115 3 => 'member',
116 4 => 'contact',
117 5 => 'bank_account',
118 6 => 'project',
119 7 => 'user',
120 8 => 'bank_line',
121 9 => 'warehouse',
122 10 => 'actioncomm',
123 11 => 'website_page',
124 12 => 'ticket',
125 13 => 'knowledgemanagement',
126 14 => 'fichinter',
127 16 => 'order',
128 17 => 'invoice',
129 20 => 'supplier_order',
130 21 => 'supplier_invoice'
131 );
132
138 public $MAP_CAT_FK = array(
139 'customer' => 'soc',
140 'supplier' => 'soc',
141 'contact' => 'socpeople',
142 'bank_account' => 'account',
143 );
144
150 public $MAP_CAT_TABLE = array(
151 'customer' => 'societe',
152 'supplier' => 'fournisseur',
153 'bank_account' => 'account',
154 );
155
161 public $MAP_OBJ_CLASS = array(
162 'product' => 'Product',
163 'service' => 'Product',
164 'customer' => 'Societe',
165 'supplier' => 'Fournisseur',
166 'member' => 'Adherent',
167 'contact' => 'Contact',
168 'user' => 'User',
169 'account' => 'Account', // old for bank account
170 'bank_account' => 'Account',
171 'project' => 'Project',
172 'warehouse' => 'Entrepot',
173 'actioncomm' => 'ActionComm',
174 'website_page' => 'WebsitePage',
175 'ticket' => 'Ticket',
176 'knowledgemanagement' => 'KnowledgeRecord',
177 'fichinter' => 'Fichinter',
178 'order' => 'Commande',
179 'invoice' => 'Facture',
180 'supplier_order' => 'CommandeFournisseur',
181 'supplier_invoice' => 'FactureFournisseur'
182 );
183
189 public static $MAP_TYPE_TITLE_AREA = array(
190 'product' => 'Products',
191 'service' => 'Services',
192 'customer' => 'ProspectsOrCustomers',
193 'supplier' => 'Suppliers',
194 'member' => 'Members',
195 'contact' => 'Contacts',
196 'user' => 'Users',
197 'account' => 'Accounts', // old for bank account
198 'bank_account' => 'BankAccounts',
199 'bank_line' => 'BankTransactions',
200 'project' => 'Projects',
201 'warehouse' => 'Warehouse',
202 'actioncomm' => 'AgendaEvents',
203 'website_page' => 'WebsitePages',
204 'ticket' => 'Tickets',
205 'knowledgemanagement' => 'KnowledgeRecords',
206 'fichinter' => 'Interventions',
207 'order' => 'Orders',
208 'invoice' => 'Invoices',
209 'supplier_order' => 'SuppliersOrders',
210 'supplier_invoice' => 'SuppliersInvoices'
211 );
212
217 public $MAP_OBJ_TABLE = array(
218 'customer' => 'societe',
219 'supplier' => 'societe',
220 'member' => 'adherent',
221 'contact' => 'socpeople',
222 'account' => 'bank_account', // old for bank account
223 'project' => 'projet',
224 'warehouse' => 'entrepot',
225 'knowledgemanagement' => 'knowledgemanagement_knowledgerecord',
226 'fichinter' => 'fichinter',
227 'order' => 'commande',
228 'invoice' => 'facture',
229 'supplier_order' => 'commande_fournisseur',
230 'supplier_invoice' => 'facture_fourn'
231 );
232
236 public $element = 'category';
237
241 public $table_element = 'categorie';
242
246 public $fk_parent;
247
251 public $label;
252
256 public $description;
257
261 public $color;
262
266 public $position;
267
271 public $visible;
272
276 public $socid;
277
300 public $type;
301
305 public $cats = array();
306
310 public $motherof = array();
311
315 public $childs = array();
316
320 public $multilangs = array();
321
325 public $imgWidth;
326
330 public $imgHeight;
331
356 public $fields = array(
357 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'visible' => 0,),
358 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'default' => '1', 'notnull' => 1, 'index' => 1, 'position' => 5),
359 'fk_parent' => array('type' => 'integer', 'label' => 'ParentCategory', 'enabled' => 1, 'position' => 20, 'notnull' => 1, 'visible' => 0, 'css' => 'maxwidth500 widthcentpercentminusxx',),
360 'label' => array('type' => 'varchar(180)', 'label' => 'Ref', 'enabled' => 1, 'position' => 25, 'notnull' => 1, 'visible' => 1, 'alwayseditable' => 1, 'css' => 'minwidth300', 'cssview' => 'wordbreak', 'csslist' => 'tdoverflowmax150', 'showoncombobox' => 1),
361 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'position' => 30, 'notnull' => 0, 'visible' => 0, 'alwayseditable' => 1,),
362 'type' => array('type' => 'integer', 'label' => 'Type', 'enabled' => 1, 'position' => 35, 'notnull' => 1, 'visible' => 0, 'alwayseditable' => 1,),
363 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'position' => 40, 'notnull' => 0, 'visible' => 1, 'alwayseditable' => 1,),
364 'color' => array('type' => 'varchar(8)', 'label' => 'Color', 'enabled' => 1, 'position' => 45, 'notnull' => 0, 'visible' => 1, 'alwayseditable' => 1,),
365 'position' => array('type' => 'integer', 'label' => 'Position', 'enabled' => 1, 'position' => 50, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
366 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'picto' => 'company', 'enabled' => 1, 'position' => 55, 'notnull' => 0, 'visible' => 0, 'alwayseditable' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150',),
367 'visible' => array('type' => 'integer', 'label' => 'Visible', 'enabled' => 1, 'position' => 60, 'notnull' => 1, 'visible' => 0, 'alwayseditable' => 1,),
368 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 900, 'notnull' => 0, 'visible' => -2, 'alwayseditable' => 1,),
369 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 70, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
370 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 75, 'notnull' => 1, 'visible' => -1, 'alwayseditable' => 1,),
371 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'position' => 80, 'notnull' => 0, 'visible' => -2, 'alwayseditable' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150',),
372 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 85, 'notnull' => -1, 'visible' => -2, 'alwayseditable' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150',),
373 );
374
380 public function __construct($db)
381 {
382 global $hookmanager;
383
384 $this->db = $db;
385
386 $this->ismultientitymanaged = 1;
387 $this->isextrafieldmanaged = 1;
388
389 if (is_object($hookmanager)) {
390 $hookmanager->initHooks(array('category'));
391 $parameters = array();
392 $reshook = $hookmanager->executeHooks('constructCategory', $parameters, $this); // Note that $action and $object may have been modified by some hooks
393 if ($reshook >= 0 && !empty($hookmanager->resArray)) {
394 foreach ($hookmanager->resArray as $mapList) {
395 $mapId = $mapList['id'];
396 $mapCode = $mapList['code'];
397 self::$MAP_ID_TO_CODE[$mapId] = $mapCode;
398 $this->MAP_ID[$mapCode] = $mapId;
399 $this->MAP_CAT_FK[$mapCode] = isset($mapList['cat_fk']) ? $mapList['cat_fk'] : null;
400 $this->MAP_CAT_TABLE[$mapCode] = isset($mapList['cat_table']) ? $mapList['cat_table'] : null;
401 $this->MAP_OBJ_CLASS[$mapCode] = $mapList['obj_class'];
402 $this->MAP_OBJ_TABLE[$mapCode] = $mapList['obj_table'];
403 }
404 }
405 }
406 }
407
413 public function getMapList()
414 {
415 $mapList = array();
416
417 foreach ($this->MAP_ID as $mapCode => $mapId) {
418 $mapList[] = array(
419 'id' => $mapId,
420 'code' => $mapCode,
421 'cat_fk' => (empty($this->MAP_CAT_FK[$mapCode]) ? $mapCode : $this->MAP_CAT_FK[$mapCode]),
422 'cat_table' => (empty($this->MAP_CAT_TABLE[$mapCode]) ? $mapCode : $this->MAP_CAT_TABLE[$mapCode]),
423 'obj_class' => (empty($this->MAP_OBJ_CLASS[$mapCode]) ? $mapCode : $this->MAP_OBJ_CLASS[$mapCode]),
424 'obj_table' => (empty($this->MAP_OBJ_TABLE[$mapCode]) ? $mapCode : $this->MAP_OBJ_TABLE[$mapCode])
425 );
426 }
427
428 return $mapList;
429 }
430
436 public function getMapId()
437 {
438 return $this->MAP_ID;
439 }
440
450 public function fetch($id, $label = '', $type = null, $ref_ext = '')
451 {
452 // Check parameters
453 if (empty($id) && empty($label) && empty($ref_ext)) {
454 $this->error = "No category to search for";
455 return -1;
456 }
457 if (!is_null($type) && !is_numeric($type)) {
458 $type = $this->MAP_ID[$type];
459 }
460
461 $sql = "SELECT rowid, fk_parent, entity, label, description, color, position, fk_soc, visible, type, ref_ext";
462 $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif";
463 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
464 if ($id) {
465 $sql .= " WHERE rowid = ".((int) $id);
466 } elseif (!empty($ref_ext)) {
467 $sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'";
468 } else {
469 $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")";
470 if (!is_null($type)) {
471 $sql .= " AND type = ".((int) $type);
472 }
473 }
474
475 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
476 $resql = $this->db->query($sql);
477 if ($resql) {
478 if ($this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
479 $this->id = $res['rowid'];
480 //$this->ref = $res['rowid'];
481 $this->fk_parent = (int) $res['fk_parent'];
482 $this->label = $res['label'];
483 $this->description = $res['description'];
484 $this->color = $res['color'];
485 $this->position = $res['position'];
486 $this->socid = (int) $res['fk_soc'];
487 $this->visible = (int) $res['visible'];
488 $this->type = $res['type'];
489 $this->ref_ext = $res['ref_ext'];
490 $this->entity = (int) $res['entity'];
491 $this->date_creation = $this->db->jdate($res['date_creation']);
492 $this->date_modification = $this->db->jdate($res['tms']);
493 $this->user_creation_id = (int) $res['fk_user_creat'];
494 $this->user_modification_id = (int) $res['fk_user_modif'];
495
496 // Retrieve all extrafield
497 // fetch optionals attributes and labels
498 $this->fetch_optionals();
499
500 $this->db->free($resql);
501
502 // multilangs
503 if (getDolGlobalInt('MAIN_MULTILANGS')) {
504 $this->getMultiLangs();
505 }
506
507 return 1;
508 } else {
509 $this->error = "No category found";
510 return 0;
511 }
512 } else {
513 dol_print_error($this->db);
514 $this->error = $this->db->lasterror;
515 $this->errors[] = $this->db->lasterror;
516 return -1;
517 }
518 }
519
530 public function create($user, $notrigger = 0)
531 {
532 global $conf, $langs;
533 $langs->load('categories');
534
535 $type = $this->type;
536
537 if (!is_numeric($type)) {
538 $type = $this->MAP_ID[$type];
539 }
540
541 $error = 0;
542
543 dol_syslog(get_class($this).'::create', LOG_DEBUG);
544
545 // Clean parameters
546 $this->label = trim($this->label);
547 $this->description = trim($this->description);
548 $this->color = trim($this->color);
549 $this->position = (int) $this->position;
550 if (isset($this->import_key)) {
551 $this->import_key = trim($this->import_key);
552 }
553 $this->ref_ext = trim($this->ref_ext);
554 if (empty($this->visible)) {
555 $this->visible = 0;
556 }
557 $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
558
559 if ($this->already_exists()) {
560 $this->error = $langs->trans("ImpossibleAddCat", $this->label);
561 $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
562 dol_syslog($this->error, LOG_WARNING);
563 return -4;
564 }
565
566 $this->db->begin();
567 $now = dol_now();
568 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie (";
569 $sql .= "fk_parent,";
570 $sql .= " label,";
571 $sql .= " description,";
572 $sql .= " color,";
573 $sql .= " position,";
574 if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
575 $sql .= "fk_soc,";
576 }
577 $sql .= " visible,";
578 $sql .= " type,";
579 $sql .= " import_key,";
580 $sql .= " ref_ext,";
581 $sql .= " entity,";
582 $sql .= " date_creation,";
583 $sql .= " fk_user_creat";
584 $sql .= ") VALUES (";
585 $sql .= (int) $this->fk_parent.",";
586 $sql .= "'".$this->db->escape($this->label)."', ";
587 $sql .= "'".$this->db->escape($this->description)."', ";
588 $sql .= "'".$this->db->escape($this->color)."', ";
589 $sql .= (int) $this->position.",";
590 if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
591 $sql .= ($this->socid > 0 ? $this->socid : 'null').", ";
592 }
593 $sql .= "'".$this->db->escape((string) $this->visible)."', ";
594 $sql .= ((int) $type).", ";
595 $sql .= (!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : 'null').", ";
596 $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : 'null').", ";
597 $sql .= (int) $conf->entity.", ";
598 $sql .= "'".$this->db->idate($now)."', ";
599 $sql .= (int) $user->id;
600 $sql .= ")";
601
602 $res = $this->db->query($sql);
603 if ($res) {
604 $id = $this->db->last_insert_id(MAIN_DB_PREFIX."categorie");
605
606 if ($id > 0) {
607 $this->id = $id;
608
609 $action = 'create';
610
611 // Actions on extra fields
612 $result = $this->insertExtraFields();
613 if ($result < 0) {
614 $error++;
615 }
616
617 if (!$error && !$notrigger) {
618 // Call trigger
619 $result = $this->call_trigger('CATEGORY_CREATE', $user);
620 if ($result < 0) {
621 $error++;
622 }
623 // End call triggers
624 }
625
626 if (!$error) {
627 $this->db->commit();
628 return $id;
629 } else {
630 $this->db->rollback();
631 return -3;
632 }
633 } else {
634 $this->db->rollback();
635 return -2;
636 }
637 } else {
638 $this->error = $this->db->error();
639 $this->db->rollback();
640 return -1;
641 }
642 }
643
653 public function update(User $user, $notrigger = 0)
654 {
655 global $langs;
656
657 $error = 0;
658
659 // Clean parameters
660 $this->label = trim($this->label);
661 $this->description = trim($this->description);
662 $this->ref_ext = trim($this->ref_ext);
663 $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
664 $this->visible = ($this->visible != "" ? intval($this->visible) : 0);
665
666 if ($this->already_exists()) {
667 $this->error = $langs->trans("ImpossibleUpdateCat");
668 $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
669 return -1;
670 }
671
672 $this->db->begin();
673
674 $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
675 $sql .= " SET label = '".$this->db->escape($this->label)."',";
676 $sql .= " description = '".$this->db->escape($this->description)."',";
677 $sql .= " ref_ext = '".$this->db->escape($this->ref_ext)."',";
678 $sql .= " color = '".$this->db->escape($this->color)."'";
679 $sql .= ", position = ".(int) $this->position;
680 if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
681 $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : 'null');
682 }
683 $sql .= ", visible = ".(int) $this->visible;
684 $sql .= ", fk_parent = ".(int) $this->fk_parent;
685 $sql .= ", fk_user_modif = ".(int) $user->id;
686 $sql .= " WHERE rowid = ".((int) $this->id);
687
688 dol_syslog(get_class($this)."::update", LOG_DEBUG);
689 if ($this->db->query($sql)) {
690 $action = 'update';
691
692 // Actions on extra fields
693 $result = $this->insertExtraFields();
694 if ($result < 0) {
695 $error++;
696 }
697
698 if (!$error && !$notrigger) {
699 // Call trigger
700 $result = $this->call_trigger('CATEGORY_MODIFY', $user);
701 if ($result < 0) {
702 $error++;
703 }
704 // End call triggers
705 }
706
707 if (!$error) {
708 $this->db->commit();
709 return 1;
710 } else {
711 $this->db->rollback();
712 return -1;
713 }
714 } else {
715 $this->db->rollback();
716 dol_print_error($this->db);
717 return -1;
718 }
719 }
720
728 public function delete($user, $notrigger = 0)
729 {
730 $error = 0;
731
732 // Clean parameters
733 $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
734
735 dol_syslog(get_class($this)."::remove");
736
737 $this->db->begin();
738
739 if (/* !$error && */ !$notrigger) {
740 // Call trigger
741 $result = $this->call_trigger('CATEGORY_DELETE', $user);
742 if ($result < 0) {
743 $error++;
744 }
745 // End call triggers
746 }
747
748 /* FIX #1317 : Check for child category and move up 1 level*/
749 if (!$error) {
750 $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
751 $sql .= " SET fk_parent = ".((int) $this->fk_parent);
752 $sql .= " WHERE fk_parent = ".((int) $this->id);
753
754 if (!$this->db->query($sql)) {
755 $this->error = $this->db->lasterror();
756 $error++;
757 }
758 }
759
760 $arraydelete = array(
761 'categorie_account' => 'fk_categorie',
762 'categorie_actioncomm' => 'fk_categorie',
763 'categorie_contact' => 'fk_categorie',
764 'categorie_fournisseur' => 'fk_categorie',
765 'categorie_knowledgemanagement' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('knowledgemanagement')),
766 'categorie_fichinter' => array('field' => 'fk_categorie', 'enabled' => false ), // not yet fully implemented (wait 22) isModEnabled('intervention')),
767 'categorie_member' => 'fk_categorie',
768 'categorie_user' => 'fk_categorie',
769 'categorie_product' => 'fk_categorie',
770 'categorie_project' => 'fk_categorie',
771 'categorie_societe' => 'fk_categorie',
772 'categorie_ticket' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('ticket')),
773 'categorie_warehouse' => 'fk_categorie',
774 'categorie_website_page' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('website')),
775 'category_bankline' => 'fk_categ',
776 'categorie_lang' => 'fk_category',
777 'categorie' => 'rowid',
778 );
779 // The links of the category are in the table of its own type: make sure that table is purged even when it is
780 // missing from the list above or disabled there, otherwise its foreign key refuses to delete the category.
781 $typecode = is_numeric($this->type) ? array_search((int) $this->type, $this->MAP_ID) : $this->type;
782 if (!empty($typecode) && $typecode != 'bank_line') { // the links of bank lines are in category_bankline, already in the list
783 $linktable = 'categorie_'.(empty($this->MAP_CAT_TABLE[$typecode]) ? $typecode : $this->MAP_CAT_TABLE[$typecode]);
784 if (array_key_exists($linktable, $arraydelete)) {
785 $arraydelete[$linktable] = 'fk_categorie';
786 } else {
787 $arraydelete = array($linktable => 'fk_categorie') + $arraydelete;
788 }
789 }
790 foreach ($arraydelete as $key => $value) {
791 if (is_array($value)) {
792 if (empty($value['enabled'])) {
793 continue;
794 }
795 $value = $value['field'];
796 }
797 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$key;
798 $sql .= " WHERE ".$value." = ".((int) $this->id);
799 if (!$this->db->query($sql)) {
800 $this->errors[] = $this->db->lasterror();
801 dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR);
802 $error++;
803 }
804 }
805
806 // Removed extrafields
807 if (!$error) {
808 $result = $this->deleteExtraFields();
809 if ($result < 0) {
810 $error++;
811 dol_syslog(get_class($this)."::delete erreur ".$this->error, LOG_ERR);
812 }
813 }
814
815 if (!$error) {
816 $this->db->commit();
817 return 1;
818 } else {
819 $this->db->rollback();
820 return -1;
821 }
822 }
823
824 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
833 public function add_type($obj, $type = '')
834 {
835 // phpcs:enable
836 global $user;
837
838 $error = 0;
839
840 if ($this->id == -1) {
841 return -2;
842 }
843
844 if (empty($type)) {
845 $type = $obj->element;
846 }
847
848 dol_syslog(get_class($this).'::add_type', LOG_DEBUG);
849
850 $this->db->begin();
851
852 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
853 $sql .= " (fk_categorie, fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]).")";
854 $sql .= " VALUES (".((int) $this->id).", ".((int) $obj->id).")";
855
856 if ($this->db->query($sql)) {
857 if (getDolGlobalString('CATEGORIE_RECURSIV_ADD')) {
858 $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie';
859 $sql .= " WHERE rowid = ".((int) $this->id);
860
861 dol_syslog(get_class($this)."::add_type", LOG_DEBUG);
862 $resql = $this->db->query($sql);
863 if ($resql) {
864 if ($this->db->num_rows($resql) > 0) {
865 $objparent = $this->db->fetch_object($resql);
866
867 if (!empty($objparent->fk_parent)) {
868 $cat = new Categorie($this->db);
869 $cat->id = $objparent->fk_parent;
870 if (!$cat->containsObject($type, $obj->id)) {
871 $result = $cat->add_type($obj, $type);
872 if ($result < 0) {
873 $this->error = $cat->error;
874 $error++;
875 }
876 }
877 }
878 }
879 } else {
880 $error++;
881 $this->error = $this->db->lasterror();
882 }
883
884 if ($error) {
885 $this->db->rollback();
886 return -1;
887 }
888 }
889
890 // Call trigger
891 $this->context = array('linkto' => $obj); // Save object we want to link category to into category instance to provide information to trigger
892 $result = $this->call_trigger('CATEGORY_MODIFY', $user);
893 if ($result < 0) {
894 $error++;
895 }
896 // End call triggers
897
898 if (!$error) {
899 $this->db->commit();
900 return 1;
901 } else {
902 $this->db->rollback();
903 return -2;
904 }
905 } else {
906 $this->db->rollback();
907 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
908 $this->error = $this->db->lasterrno();
909 return -3;
910 } else {
911 $this->error = $this->db->lasterror();
912 }
913 return -1;
914 }
915 }
916
917 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
926 public function del_type($obj, $type)
927 {
928 // phpcs:enable
929 global $user;
930
931 $error = 0;
932
933 // For backward compatibility
934 if ($type == 'societe') {
935 $type = 'customer';
936 dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
937 } elseif ($type == 'fournisseur') {
938 $type = 'supplier';
939 dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
940 }
941
942 $this->db->begin();
943
944 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
945 $sql .= " WHERE fk_categorie = ".((int) $this->id);
946 $sql .= " AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $obj->id);
947
948 dol_syslog(get_class($this).'::del_type', LOG_DEBUG);
949 if ($this->db->query($sql)) {
950 // Call trigger
951 $this->context = array('unlinkoff' => $obj); // Save object we want to link category to into category instance to provide information to trigger
952 $result = $this->call_trigger('CATEGORY_MODIFY', $user);
953 if ($result < 0) {
954 $error++;
955 }
956 // End call triggers
957
958 if (!$error) {
959 $this->db->commit();
960 return 1;
961 } else {
962 $this->db->rollback();
963 return -2;
964 }
965 } else {
966 $this->db->rollback();
967 $this->error = $this->db->lasterror();
968 return -1;
969 }
970 }
971
990 public function getObjectsInCateg($type, $onlyids = 0, $limit = 0, $offset = 0, $sortfield = '', $sortorder = 'ASC', $filter = '', $filtermode = 'AND', $filterlang = '')
991 {
992 global $user;
993
994 if (empty($onlyids)) {
995 dol_syslog("getObjectsInCateg: This method used with parameter onlyids=0 is deprecated. Try by using instead getListForItem().", LOG_WARNING);
996 }
997
998 $objs = array();
999
1000 $classnameforobj = $this->MAP_OBJ_CLASS[$type];
1001 if (!empty($classnameforobj) && class_exists($classnameforobj)) {
1002 $tmpobj = new $classnameforobj($this->db);
1005 $sql = "SELECT c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." as fk_object";
1006 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as c";
1007 $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." as o";
1008 if (!empty($filterlang)) {
1009 $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])."_lang as ol";
1010 }
1011 $sql .= " WHERE o.entity IN (".getEntity($tmpobj->element).")";
1012 $sql .= " AND c.fk_categorie = ".((int) $this->id);
1013 // Compatibility with actioncomm table which has id instead of rowid
1014 if ((array_key_exists($type, $this->MAP_OBJ_TABLE) && $this->MAP_OBJ_TABLE[$type] == "actioncomm") || $type == "actioncomm") {
1015 $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.id";
1016 } else {
1017 $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.rowid";
1018 }
1019 if (!empty($filterlang)) {
1020 $sql .= " AND ol.fk_".(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." = o.rowid";
1021 $sql .= " AND ol.lang = '".$this->db->escape($filterlang)."'";
1022 }
1023 // Protection for external users
1024 if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) {
1025 $sql .= " AND o.rowid = ".((int) $user->socid);
1026 }
1027
1028 $errormessage = '';
1029 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
1030 if ($errormessage) {
1031 $this->errors[] = $errormessage;
1032 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
1033 return -1;
1034 }
1035
1036 $sql .= $this->db->order($sortfield, $sortorder);
1037 if ($limit > 0 || $offset > 0) {
1038 $sql .= $this->db->plimit($limit + 1, $offset);
1039 }
1040
1041 dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
1042
1043 $resql = $this->db->query($sql);
1044 if ($resql) {
1045 while ($rec = $this->db->fetch_array($resql)) {
1046 if ($onlyids) {
1047 $objs[] = $rec['fk_object'];
1048 } else {
1049 $tmpobj->id = 0;
1050 $tmpobj->fetch($rec['fk_object']); // The fetch will erase $tmpobj->id only if it succeed.
1051 // @phpstan-ignore-next-line
1052 if ($tmpobj->id > 0) { // Failing fetch may happen for example when a category supplier was set and third party was moved as customer only. The object supplier can't be loaded.
1053 $objs[] = clone $tmpobj;
1054 }
1055 }
1056 }
1057 } else {
1058 $this->error = $this->db->error().' sql='.$sql;
1059 return -1;
1060 }
1061 }
1062
1063 return $objs;
1064 }
1065
1074 public function containsObject($type, $object_id)
1075 {
1076 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
1077 $sql .= " WHERE fk_categorie = ".((int) $this->id)." AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $object_id);
1078
1079 dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
1080
1081 $resql = $this->db->query($sql);
1082 if ($resql) {
1083 return $this->db->fetch_object($resql)->nb;
1084 } else {
1085 $this->error = $this->db->error();
1086 return -1;
1087 }
1088 }
1089
1102 public function getListForItem($id, $type = 'customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
1103 {
1104 $categories = array();
1105
1106 $type = sanitizeVal($type, 'aZ09');
1107
1108 $sub_type = $type;
1109 $subcol_name = "fk_".$type;
1110 if ($type == "customer") {
1111 $sub_type = "societe";
1112 $subcol_name = "fk_soc";
1113 }
1114 if ($type == "supplier") {
1115 $sub_type = "fournisseur";
1116 $subcol_name = "fk_soc";
1117 }
1118 if ($type == "contact") {
1119 $subcol_name = "fk_socpeople";
1120 }
1121
1122 $idoftype = (int) (array_key_exists($type, $this->MAP_ID) ? $this->MAP_ID[$type] : -1);
1123
1124 $sql = "SELECT s.rowid";
1125 $sqlfields = $sql; // $sql fields to remove for count total
1126 $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s, ".MAIN_DB_PREFIX."categorie_".$this->db->sanitize($sub_type)." as sub";
1127 $sql .= ' WHERE s.entity IN ('.getEntity('category').')';
1128 $sql .= ' AND s.type = '.((int) $idoftype);
1129 $sql .= ' AND s.rowid = sub.fk_categorie';
1130 $sql .= " AND sub.".$this->db->sanitize($subcol_name)." = ".((int) $id);
1131
1132 $offset = 0;
1133 $nbtotalofrecords = '';
1134 if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
1135 $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
1136 $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
1137
1138 $resql = $this->db->query($sqlforcount);
1139 if ($resql) {
1140 $objforcount = $this->db->fetch_object($resql);
1141 $nbtotalofrecords = $objforcount->nbtotalofrecords;
1142 } else {
1143 dol_print_error($this->db);
1144 }
1145
1146 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
1147 $page = 0;
1148 $offset = 0;
1149 }
1150 $this->db->free($resql);
1151 }
1152
1153 $sql .= $this->db->order($sortfield, $sortorder);
1154 if ($limit) {
1155 if ($page < 0) {
1156 $page = 0;
1157 }
1158 $offset = $limit * $page;
1159
1160 $sql .= $this->db->plimit($limit + 1, $offset);
1161 }
1162
1163 $result = $this->db->query($sql);
1164 if ($result) {
1165 $i = 0;
1166 $num = $this->db->num_rows($result);
1167 $min = min($num, ($limit <= 0 ? $num : $limit));
1168 while ($i < $min) {
1169 $obj = $this->db->fetch_object($result);
1170 $category_static = new Categorie($this->db);
1171 if ($category_static->fetch($obj->rowid)) {
1172 $categories[$i]['id'] = $category_static->id;
1173 $categories[$i]['fk_parent'] = $category_static->fk_parent;
1174 $categories[$i]['label'] = $category_static->label;
1175 $categories[$i]['description'] = $category_static->description;
1176 $categories[$i]['color'] = $category_static->color;
1177 $categories[$i]['position'] = $category_static->position;
1178 $categories[$i]['socid'] = $category_static->socid;
1179 $categories[$i]['ref_ext'] = $category_static->ref_ext;
1180 $categories[$i]['visible'] = $category_static->visible;
1181 $categories[$i]['type'] = $category_static->type;
1182 $categories[$i]['entity'] = $category_static->entity;
1183 $categories[$i]['array_options'] = $category_static->array_options;
1184
1185 // multilangs
1186 if (getDolGlobalInt('MAIN_MULTILANGS') && isset($category_static->multilangs)) {
1187 $categories[$i]['multilangs'] = $category_static->multilangs;
1188 }
1189 }
1190 $i++;
1191 }
1192 } else {
1193 $this->error = $this->db->lasterror();
1194 return -1;
1195 }
1196 if (!count($categories)) {
1197 return [];
1198 }
1199
1200 return $categories;
1201 }
1202
1203 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1209 public function get_filles()
1210 {
1211 // phpcs:enable
1212 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1213 $sql .= " WHERE fk_parent = ".((int) $this->id);
1214 $sql .= " AND entity IN (".getEntity('category').")";
1215
1216 $res = $this->db->query($sql);
1217 if ($res) {
1218 $cats = array();
1219 while ($rec = $this->db->fetch_array($res)) {
1220 $cat = new Categorie($this->db);
1221 $cat->fetch($rec['rowid']);
1222 $cats[] = $cat;
1223 }
1224 return $cats;
1225 } else {
1226 dol_print_error($this->db);
1227 return -1;
1228 }
1229 }
1230
1231 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1238 protected function load_motherof()
1239 {
1240 // phpcs:enable
1241 $this->motherof = array();
1242
1243 // Load array[child]=parent
1244 $sql = "SELECT fk_parent as id_parent, rowid as id_son";
1245 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
1246 $sql .= " WHERE fk_parent <> 0";
1247 $sql .= " AND entity IN (".getEntity('category').")";
1248
1249 dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
1250 $resql = $this->db->query($sql);
1251 if ($resql) {
1252 while ($obj = $this->db->fetch_object($resql)) {
1253 $this->motherof[$obj->id_son] = $obj->id_parent;
1254 }
1255 return 1;
1256 } else {
1257 dol_print_error($this->db);
1258 return -1;
1259 }
1260 }
1261
1262 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1283 public function get_full_arbo($type, $fromid = 0, $include = 0, $forcelangcode = '')
1284 {
1285 // phpcs:enable
1286 global $langs;
1287
1288 if (!is_numeric($type)) {
1289 $type = isset($this->MAP_ID[$type]) ? $this->MAP_ID[$type] : null;
1290 }
1291 if (is_null($type)) {
1292 $this->error = 'BadValueForParameterType';
1293 return -1;
1294 }
1295
1296 if (is_string($fromid)) {
1297 $fromid = explode(',', $fromid);
1298 } elseif (is_numeric($fromid)) {
1299 if ($fromid > 0) {
1300 $fromid = array($fromid);
1301 } else {
1302 $fromid = array();
1303 }
1304 } elseif (!is_array($fromid)) {
1305 $fromid = array();
1306 }
1307
1308 $this->cats = array();
1309 $nbcateg = 0;
1310
1311 // Init this->motherof that is array(id_son=>id_parent, ...)
1312 $this->load_motherof();
1313
1314 if ($forcelangcode) {
1315 $current_lang = $forcelangcode;
1316 } else {
1317 $current_lang = $langs->getDefaultLang();
1318 }
1319
1320 // Init $this->cats array
1321 // Note: The DISTINCT reduces pb with old tables with duplicates but should not be used
1322 $sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.position, c.fk_parent, c.visible";
1323 if (getDolGlobalInt('MAIN_MULTILANGS') && $current_lang !== 'none') {
1324 $sql .= ", t.label as label_trans, t.description as description_trans";
1325 }
1326 $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
1327 if (getDolGlobalInt('MAIN_MULTILANGS') && $current_lang !== 'none') {
1328 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category = c.rowid AND t.lang = '".$this->db->escape($current_lang)."'";
1329 }
1330 $sql .= " WHERE c.entity IN (".getEntity('category').")";
1331 $sql .= " AND c.type = ".(int) $type;
1332
1333 dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
1334
1335 $resql = $this->db->query($sql);
1336 if ($resql) {
1337 $i = 0;
1338 $nbcateg = $this->db->num_rows($resql);
1339
1340 while ($obj = $this->db->fetch_object($resql)) {
1341 $this->cats[$obj->rowid]['rowid'] = $obj->rowid;
1342 $this->cats[$obj->rowid]['id'] = $obj->rowid;
1343 $this->cats[$obj->rowid]['fk_parent'] = $obj->fk_parent;
1344 $this->cats[$obj->rowid]['label'] = !empty($obj->label_trans) ? $obj->label_trans : $obj->label;
1345 $this->cats[$obj->rowid]['description'] = !empty($obj->description_trans) ? $obj->description_trans : $obj->description;
1346 $this->cats[$obj->rowid]['color'] = $obj->color;
1347 $this->cats[$obj->rowid]['position'] = $obj->position;
1348 $this->cats[$obj->rowid]['visible'] = $obj->visible;
1349 $this->cats[$obj->rowid]['ref_ext'] = $obj->ref_ext;
1350 $this->cats[$obj->rowid]['picto'] = 'category';
1351 // fields are filled with buildPathFromId later
1352 $this->cats[$obj->rowid]['fullpath'] = '';
1353 $this->cats[$obj->rowid]['fulllabel'] = '';
1354 $i++;
1355 }
1356 } else {
1357 dol_print_error($this->db);
1358 return -1;
1359 }
1360
1361 // We add the fullpath property to each elements of first level (no parent exists)
1362 dol_syslog(get_class($this)."::get_full_arbo call to buildPathFromId", LOG_DEBUG);
1363
1364 foreach ($this->cats as $key => $val) {
1365 //print 'key='.$key.'<br>'."\n";
1366 $this->buildPathFromId($key, $nbcateg); // Process a branch from the root category key (this category has no parent) and adds level to $this->cats items
1367 }
1368
1369 // Include or exclude leaf (including $fromid) from tree
1370 if (count($fromid) > 0) {
1371 $keyfiltercatid = '('.implode('|', $fromid).')';
1372
1373 //print "Look to discard category ".$fromid."\n";
1374 $keyfilter1 = '^'.$keyfiltercatid.'$';
1375 $keyfilter2 = '_'.$keyfiltercatid.'$';
1376 $keyfilter3 = '^'.$keyfiltercatid.'_';
1377 $keyfilter4 = '_'.$keyfiltercatid.'_';
1378 foreach (array_keys($this->cats) as $key) {
1379 $fullpath = (string) $this->cats[$key]['fullpath'];
1380 $test = (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
1381 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath));
1382
1383 if (($test && !$include) || (!$test && $include)) {
1384 unset($this->cats[$key]); // @phpstan-ignore-line
1385 }
1386 }
1387 }
1388
1389 dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
1390
1391 $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', 1, 0, 1); // Sort on full label like "Label 1 >> Sublabel a >> Subsublabel"
1392
1393 return $this->cats;
1394 }
1395
1406 private function buildPathFromId($id_categ, $protection = 1000)
1407 {
1408 //dol_syslog(get_class($this)."::buildPathFromId id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
1409
1410 if (!empty($this->cats[$id_categ]['fullpath'])) {
1411 // Already defined
1412 dol_syslog(get_class($this)."::buildPathFromId fullpath and fulllabel already defined", LOG_WARNING);
1413 return -1;
1414 }
1415
1416 // $this->cats[$id_categ] is supposed to be already an array. We just want to complete it with property fullpath and fulllabel
1417
1418 // Define fullpath and fulllabel
1419 $this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
1420 $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
1421 $i = 0;
1422 $cursor_categ = $id_categ;
1423 //print 'Work for id_categ='.$id_categ.'<br>'."\n";
1424 while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) {
1425 //print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
1426 $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
1427 $this->cats[$id_categ]['fulllabel'] = (empty($this->cats[$this->motherof[$cursor_categ]]) ? 'NotFound' : $this->cats[$this->motherof[$cursor_categ]]['label']).' >> '.$this->cats[$id_categ]['fulllabel'];
1428 //print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
1429 $i++;
1430 $cursor_categ = $this->motherof[$cursor_categ];
1431 }
1432 //print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'<br>'."\n";
1433
1434 // We count number of _ to have level
1435 $nbunderscore = substr_count($this->cats[$id_categ]['fullpath'], '_');
1436 $this->cats[$id_categ]['level'] = ($nbunderscore ? $nbunderscore : null);
1437
1438 return 1;
1439 }
1440
1441
1442 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1450 public function get_all_categories($type = null, $parent = false)
1451 {
1452 // phpcs:enable
1453 if (!is_numeric($type) && !is_null($type)) {
1454 $type = $this->MAP_ID[$type];
1455 }
1456
1457 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1458 $sql .= " WHERE entity IN (".getEntity('category').")";
1459 if (!is_null($type)) {
1460 $sql .= " AND type = ".(int) $type;
1461 }
1462 if ($parent) {
1463 $sql .= " AND fk_parent = 0";
1464 }
1465
1466 $res = $this->db->query($sql);
1467 if ($res) {
1468 $cats = array();
1469 while ($rec = $this->db->fetch_array($res)) {
1470 $cat = new Categorie($this->db);
1471 $cat->fetch($rec['rowid']);
1472 $cats[$rec['rowid']] = $cat;
1473 }
1474 return $cats;
1475 } else {
1476 dol_print_error($this->db);
1477 return -1;
1478 }
1479 }
1480
1481 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1488 public function get_main_categories($type = null)
1489 {
1490 // phpcs:enable
1491 return $this->get_all_categories($type, true);
1492 }
1493
1494 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1500 public function already_exists()
1501 {
1502 // phpcs:enable
1503 $type = $this->type;
1504
1505 if (!is_numeric($type)) {
1506 $type = $this->MAP_ID[$type];
1507 }
1508
1509 /* We have to select any rowid from llx_categorie which category's mother and label
1510 * are equals to those of the calling category
1511 */
1512 $sql = "SELECT c.rowid";
1513 $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c ";
1514 $sql .= " WHERE c.entity IN (".getEntity('category').")";
1515 $sql .= " AND c.type = ".((int) $type);
1516 $sql .= " AND c.fk_parent = ".((int) $this->fk_parent);
1517 $sql .= " AND c.label = '".$this->db->escape($this->label)."'";
1518
1519 dol_syslog(get_class($this)."::already_exists", LOG_DEBUG);
1520
1521 $resql = $this->db->query($sql);
1522 if ($resql) {
1523 if ($this->db->num_rows($resql) > 0) { // Checking for empty resql
1524 $obj = $this->db->fetch_object($resql);
1525 /* If object called create, obj cannot have is id.
1526 * If object called update, he mustn't have the same label as an other category for this mother.
1527 * So if the result has the same id, update is not for label, and if result has an other one, update may be for label.
1528 */
1529 if (!empty($obj) && $obj->rowid > 0 && $obj->rowid != $this->id) {
1530 dol_syslog(get_class($this)."::already_exists category with name=".$this->label." and parent ".$this->fk_parent." exists: rowid=".$obj->rowid." current_id=".$this->id, LOG_DEBUG);
1531 return 1;
1532 }
1533 }
1534 dol_syslog(get_class($this)."::already_exists no category with same name=".$this->label." and same parent ".$this->fk_parent." than category id=".$this->id, LOG_DEBUG);
1535 return 0;
1536 } else {
1537 $this->error = $this->db->error();
1538 return -1;
1539 }
1540 }
1541
1542
1543 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1554 public function print_all_ways($sep = '&gt;&gt;', $url = '', $nocolor = 0, $addpicto = 0)
1555 {
1556 // phpcs:enable
1557 $ways = array();
1558
1559 $all_ways = $this->get_all_ways(); // Load array of categories to reach this->id
1560
1561 foreach ($all_ways as $way) { // It seems we always have 1 entry in this array.
1562 $w = array();
1563 $i = 0;
1564 $forced_color = '';
1565 foreach ($way as $cat) { // Loop on each successive categories to reach the target of current category
1566 $i++;
1567
1568 if (empty($nocolor)) {
1569 $forced_color = 'colortoreplace';
1570 if ($i == count($way)) { // Last category in hierarchy
1571 // Check contrast with background and correct text color
1572 $forced_color = 'categtextwhite'; // We want color white because the getNomUrl of a tag is always called inside a dark background like '<span color="bbb"></span>' to show it as a tag. TODO Add this in param to force when called outside of span.
1573 if ($cat->color) {
1574 if (colorIsLight($cat->color)) {
1575 $forced_color = 'categtextblack';
1576 }
1577 }
1578 }
1579 }
1580
1581 if ($url == '') {
1582 $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.((int) $cat->id).'&type='.urlencode($cat->type).'" class="'.($i < count($way) ? 'small ' : '').$forced_color.'">';
1583 $linkend = '</a>';
1584 $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
1585 } elseif ($url == 'none') {
1586 $link = '<span class="valignmiddle '.($i < count($way) ? 'small ' : '').$forced_color.'">';
1587 $linkend = '</span>';
1588 $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
1589 } else {
1590 $w[] = '<a class="valignmiddle '.($i < count($way) ? 'small ' : '').$forced_color.'" href="'.DOL_URL_ROOT.'/'.$url.'?catid='.((int) $cat->id).'">'.($addpicto ? img_object('', 'category') : '').$cat->label.'</a>';
1591 }
1592 }
1593 $newcategwithpath = preg_replace('/colortoreplace/', $forced_color, implode('<span class="inline-block valignmiddle paddingleft paddingright '.$forced_color.'">'.$sep.'</span>', $w));
1594
1595 $ways[] = $newcategwithpath;
1596 }
1597
1598 return $ways;
1599 }
1600
1601
1602 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1609 public function get_meres()
1610 {
1611 // phpcs:enable
1612 $parents = array();
1613
1614 $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie";
1615 $sql .= " WHERE rowid = ".((int) $this->id);
1616
1617 $res = $this->db->query($sql);
1618
1619 if ($res) {
1620 while ($rec = $this->db->fetch_array($res)) {
1621 if ($rec['fk_parent'] > 0) {
1622 $cat = new Categorie($this->db);
1623 $cat->fetch($rec['fk_parent']);
1624 $parents[] = $cat;
1625 }
1626 }
1627 return $parents;
1628 } else {
1629 dol_print_error($this->db);
1630 return -1;
1631 }
1632 }
1633
1634 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1641 public function get_all_ways()
1642 {
1643 // phpcs:enable
1644 $ways = array();
1645
1646 $parents = $this->get_meres();
1647 if (is_array($parents)) {
1648 foreach ($parents as $parent) {
1649 $all_ways = $parent->get_all_ways(); // recursivity. TODO Add a protection for infinite loop
1650 foreach ($all_ways as $way) {
1651 $w = $way;
1652 $w[] = $this;
1653 $ways[] = $w;
1654 }
1655 }
1656 }
1657
1658 if (count($ways) == 0) {
1659 $ways[0][0] = $this;
1660 }
1661
1662 return $ways;
1663 }
1664
1675 public function containing($id, $type, $mode = 'object')
1676 {
1677 $cats = array();
1678
1679 if (is_numeric($type)) {
1680 $type = array_search($type, $this->MAP_ID);
1681 }
1682
1683 if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this after migration of llx_category_bankline into llx_categorie_bankline
1684 // Load bank categories
1685 $sql = "SELECT c.label, c.rowid";
1686 $sql .= " FROM ".MAIN_DB_PREFIX."category_bankline as a, ".MAIN_DB_PREFIX."categorie as c";
1687 $sql .= " WHERE a.lineid=".((int) $id)." AND a.fk_categ = c.rowid";
1688 $sql .= " AND c.entity IN (".getEntity('category').")";
1689 $sql .= " ORDER BY c.label";
1690
1691 $res = $this->db->query($sql);
1692 if ($res) {
1693 while ($obj = $this->db->fetch_object($res)) {
1694 if ($mode == 'id') {
1695 $cats[] = $obj->rowid;
1696 } elseif ($mode == 'label') {
1697 $cats[] = $obj->label;
1698 } else {
1699 $cat = new Categorie($this->db);
1700 $cat->id = $obj->rowid;
1701 $cat->label = $obj->label;
1702 $cats[] = $cat;
1703 }
1704 }
1705 } else {
1706 dol_print_error($this->db);
1707 return -1;
1708 }
1709 } else {
1710 $sql = "SELECT ct.fk_categorie, c.label, c.rowid";
1711 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as ct, ".MAIN_DB_PREFIX."categorie as c";
1712 $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".(int) $id;
1713 // This seems useless because the table already contains id of category of 1 unique type. So commented.
1714 // So now it works also with external added categories.
1715 //$sql .= " AND c.type = ".((int) $this->MAP_ID[$type]);
1716 $sql .= " AND c.entity IN (".getEntity('category').")";
1717
1718 $res = $this->db->query($sql);
1719 if ($res) {
1720 while ($obj = $this->db->fetch_object($res)) {
1721 if ($mode == 'id') {
1722 $cats[] = $obj->rowid;
1723 } elseif ($mode == 'label') {
1724 $cats[] = $obj->label;
1725 } else {
1726 $cat = new Categorie($this->db);
1727 $cat->fetch($obj->fk_categorie);
1728 $cats[] = $cat;
1729 }
1730 }
1731 } else {
1732 dol_print_error($this->db);
1733 return -1;
1734 }
1735 }
1736
1737 return $cats;
1738 }
1739
1751 public function rechercher($id, $nom, $type, $exact = false, $case = false)
1752 {
1753 // Deprecation warning
1754 if (is_numeric($type)) {
1755 dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING);
1756 }
1757
1758 $cats = array();
1759
1760 // For backward compatibility
1761 if (is_numeric($type)) {
1762 // We want to reverse lookup
1763 $map_type = array_flip($this->MAP_ID);
1764 $type = $map_type[$type];
1765 dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING);
1766 }
1767
1768 // Generation requete recherche
1769 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1770 $sql .= " WHERE type = ".((int) $this->MAP_ID[$type]);
1771 $sql .= " AND entity IN (".getEntity('category').")";
1772 if ($nom) {
1773 if (!$exact) {
1774 $nom = '%'.$this->db->escape(str_replace('*', '%', $nom)).'%';
1775 }
1776 if (!$case) {
1777 $sql .= " AND label LIKE '".$this->db->escape($nom)."'";
1778 } else {
1779 $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
1780 }
1781 }
1782 if ($id) {
1783 $sql .= " AND rowid = ".((int) $id);
1784 }
1785
1786 $res = $this->db->query($sql);
1787 if ($res) {
1788 while ($rec = $this->db->fetch_array($res)) {
1789 $cat = new Categorie($this->db);
1790 $cat->fetch($rec['rowid']);
1791 $cats[] = $cat;
1792 }
1793
1794 return $cats;
1795 } else {
1796 $this->error = $this->db->error().' sql='.$sql;
1797 return -1;
1798 }
1799 }
1800
1807 public function isAnyPhotoAvailable($sdir)
1808 {
1809 include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1810 include_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php';
1811
1812 $sdir .= '/' . get_exdir($this->id, 2, 0, 0, $this, 'category') . $this->id . "/photos/";
1813
1814 $dir_osencoded = dol_osencode($sdir);
1815 if (file_exists($dir_osencoded)) {
1816 $handle = opendir($dir_osencoded);
1817 if (is_resource($handle)) {
1818 while (($file = readdir($handle)) !== false) {
1819 if (!utf8_check($file)) {
1820 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // To be sure data is stored in UTF8 in memory
1821 }
1822 if (dol_is_file($sdir . $file) && image_format_supported($file) >= 0) {
1823 return true;
1824 }
1825 }
1826 }
1827 }
1828 return false;
1829 }
1830
1837 public function getTooltipContentArray($params)
1838 {
1839 global $langs;
1840
1841 $langs->load('categories');
1842
1843 $datas = [];
1844
1845 $datas['label'] = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
1846
1847 return $datas;
1848 }
1849
1863 public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $moreparam = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = 0)
1864 {
1865 global $conf, $langs, $hookmanager;
1866
1867 if (!empty($conf->dol_no_mouse_hover)) {
1868 $notooltip = 1; // Force disable tooltips
1869 }
1870
1871 $result = '';
1872 $params = [
1873 'id' => $this->id,
1874 'objecttype' => $this->element,
1875 'option' => $option,
1876 ];
1877 $classfortooltip = 'classfortooltip';
1878 $dataparams = '';
1879 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1880 $classfortooltip = 'classforajaxtooltip';
1881 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1882 $label = '';
1883 } else {
1884 $label = implode($this->getTooltipContentArray($params));
1885 }
1886
1887 $url = DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : ''));
1888
1889 if ($option !== 'nolink') {
1890 // Add param to save lastsearch_values or not
1891 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1892 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1893 $add_save_lastsearch_values = 1;
1894 }
1895 if (/* $url && */ $add_save_lastsearch_values) {
1896 $url .= '&save_lastsearch_values=1';
1897 }
1898 }
1899
1900 // Check contrast with background and correct text color
1901 $forced_color = 'categtextwhite'; // We want color white because the getNomUrl of a tag is always called inside a dark background like '<span color="bbb"></span>' to show it as a tag. TODO Add this in param to force when called outside of span.
1902 if ($this->color) {
1903 if (colorIsLight($this->color)) { // If color is light, we force color to dark
1904 $forced_color = 'categtextblack';
1905 }
1906 }
1907
1908 $linkclose = '';
1909 if (empty($notooltip)) {
1910 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1911 $label = $langs->trans("ShowMyObject");
1912 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1913 }
1914 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1915 $linkclose .= $dataparams.' class="'.$classfortooltip.' '.$forced_color.($morecss ? ' '.$morecss : '').'"';
1916 } else {
1917 $linkclose = ' class="'.$forced_color.($morecss ? ' '.$morecss : '').'"';
1918 }
1919
1920 if ($option == 'nolink' /* || empty($url) */) {
1921 $linkstart = '<span';
1922 } else {
1923 $linkstart = '<a href="'.$url.'"';
1924 }
1925 $linkstart .= $linkclose.'>';
1926 if ($option == 'nolink' /* || empty($url) */) {
1927 $linkend = '</span>';
1928 } else {
1929 $linkend = '</a>';
1930 }
1931
1932 $result .= $linkstart;
1933
1934 if ($withpicto) {
1935 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
1936 }
1937
1938 if ($withpicto != 2) {
1939 $result .= dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength);
1940 }
1941
1942 $result .= $linkend;
1943
1944 global $action;
1945 $hookmanager->initHooks(array($this->element . 'dao'));
1946 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1947 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1948 if ($reshook > 0) {
1949 $result = $hookmanager->resPrint;
1950 } else {
1951 $result .= $hookmanager->resPrint;
1952 }
1953 return $result;
1954 }
1955
1956
1957 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1965 public function add_photo($sdir, $file)
1966 {
1967 // phpcs:enable
1968 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1969
1970 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
1971 $dir .= "photos/";
1972
1973 if (!file_exists($dir)) {
1974 dol_mkdir($dir);
1975 }
1976
1977 if (file_exists($dir)) {
1978 if (is_array($file['name'])) {
1979 $nbfile = count($file['name']);
1980 for ($i = 0; $i < $nbfile; $i++) {
1981 $originImage = $dir.$file['name'][$i];
1982
1983 // Cree fichier en taille origine
1984 dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
1985
1986 if (file_exists($originImage)) {
1987 // Create thumbs
1988 $this->addThumbs($originImage);
1989 }
1990 }
1991 } else {
1992 $originImage = $dir.$file['name'];
1993
1994 // Cree fichier en taille origine
1995 dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
1996
1997 if (file_exists($originImage)) {
1998 // Create thumbs
1999 $this->addThumbs($originImage);
2000 }
2001 }
2002 }
2003 }
2004
2005 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2013 public function liste_photos($dir, $nbmax = 0)
2014 {
2015 // phpcs:enable
2016 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2017
2018 $nbphoto = 0;
2019 $tabobj = array();
2020
2021 $dirthumb = $dir.'thumbs/';
2022
2023 if (file_exists($dir)) {
2024 $handle = opendir($dir);
2025 if (is_resource($handle)) {
2026 while (($file = readdir($handle)) !== false) {
2027 if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) {
2028 $nbphoto++;
2029 $photo = $file;
2030
2031 // On determine nom du fichier vignette
2032 $photo_vignette = '';
2033 $regs = array();
2034 if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) {
2035 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
2036 }
2037
2038 // Object
2039 $obj = array();
2040 $obj['photo'] = $photo;
2041 if ($photo_vignette && is_file($dirthumb.$photo_vignette)) {
2042 $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
2043 } else {
2044 $obj['photo_vignette'] = "";
2045 }
2046
2047 $tabobj[$nbphoto - 1] = $obj;
2048
2049 // On continue ou on arrete de boucler
2050 if ($nbmax && $nbphoto >= $nbmax) {
2051 break;
2052 }
2053 }
2054 }
2055
2056 closedir($handle);
2057 }
2058 }
2059
2060 return $tabobj;
2061 }
2062
2063 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2070 public function delete_photo($file)
2071 {
2072 // phpcs:enable
2073 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2074
2075 $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
2076 $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
2077 $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
2078
2079 // On efface l'image d'origine
2080 dol_delete_file($file, 0); // do not use disableglob, ecmfiles will not be deleted
2081
2082 // Si elle existe, on efface la vignette
2083 $regs = array();
2084 if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs)) {
2085 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
2086 if (file_exists($dirthumb.$photo_vignette)) {
2087 dol_delete_file($dirthumb.$photo_vignette, 1);
2088 }
2089 }
2090 }
2091
2092 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2099 public function get_image_size($file)
2100 {
2101 // phpcs:enable
2102 $infoImg = getimagesize($file); // Recuperation des infos de l'image
2103 $this->imgWidth = $infoImg[0]; // Largeur de l'image
2104 $this->imgHeight = $infoImg[1]; // Hauteur de l'image
2105 }
2106
2115 public function setMultiLangs(User $user, $notrigger = 0)
2116 {
2117 global $langs;
2118
2119 $langs_available = $langs->get_available_languages();
2120 $current_lang = $langs->getDefaultLang();
2121
2122 foreach ($langs_available as $key => $value) {
2123 $sql = "SELECT rowid";
2124 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
2125 $sql .= " WHERE fk_category=".((int) $this->id);
2126 $sql .= " AND lang = '".$this->db->escape($key)."'";
2127
2128 $result = $this->db->query($sql);
2129
2130 if ($key == $current_lang) {
2131 $sql2 = '';
2132 if ($this->db->num_rows($result)) { // if no line in database
2133 $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
2134 $sql2 .= " SET label = '".$this->db->escape($this->label)."',";
2135 $sql2 .= " description = '".$this->db->escape($this->description)."'";
2136 $sql2 .= " WHERE fk_category = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
2137 } elseif (isset($this->multilangs[$key])) {
2138 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
2139 $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->label)."'";
2140 $sql2 .= ", '".$this->db->escape($this->multilangs[$key]["description"])."')";
2141 }
2142 dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
2143 if ($sql2 && !$this->db->query($sql2)) {
2144 $this->error = $this->db->lasterror();
2145 return -1;
2146 }
2147 } elseif (isset($this->multilangs[$key])) {
2148 if ($this->db->num_rows($result)) { // if no line in database
2149 $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
2150 $sql2 .= " SET label='".$this->db->escape($this->multilangs[$key]["label"])."',";
2151 $sql2 .= " description='".$this->db->escape($this->multilangs[$key]["description"])."'";
2152 $sql2 .= " WHERE fk_category=".((int) $this->id)." AND lang='".$this->db->escape($key)."'";
2153 } else {
2154 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
2155 $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->multilangs[$key]["label"])."'";
2156 $sql2 .= ",'".$this->db->escape($this->multilangs[$key]["description"])."')";
2157 }
2158
2159 // on ne sauvegarde pas des champs vides
2160 if ($this->multilangs[$key]["label"] || $this->multilangs[$key]["description"] || $this->multilangs[$key]["note"]) {
2161 dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
2162 }
2163 if (!$this->db->query($sql2)) {
2164 $this->error = $this->db->lasterror();
2165 return -1;
2166 }
2167 }
2168 }
2169
2170 // Call trigger
2171 if (!$notrigger) {
2172 $result = $this->call_trigger('CATEGORY_SET_MULTILANGS', $user);
2173 if ($result < 0) {
2174 $this->error = $this->db->lasterror();
2175 return -1;
2176 }
2177 }
2178 // End call triggers
2179
2180 return 1;
2181 }
2182
2191 public function delMultiLangs($langtodelete, $user)
2192 {
2193 $sql = "DELETE FROM ".$this->db->prefix()."categorie_lang";
2194 $sql .= " WHERE fk_category = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
2195
2196 dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
2197 $result = $this->db->query($sql);
2198 if ($result) {
2199 // Call trigger
2200 $result = $this->call_trigger('CATEGORY_DEL_MULTILANGS', $user);
2201 if ($result < 0) {
2202 $this->error = $this->db->lasterror();
2203 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2204 return -1;
2205 }
2206 // End call triggers
2207 return 1;
2208 } else {
2209 $this->error = $this->db->lasterror();
2210 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2211 return -1;
2212 }
2213 }
2214
2220 public function getMultiLangs()
2221 {
2222 global $langs;
2223
2224 $current_lang = $langs->getDefaultLang();
2225
2226 $sql = "SELECT lang, label, description";
2227 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
2228 $sql .= " WHERE fk_category=".((int) $this->id);
2229
2230 $result = $this->db->query($sql);
2231 if ($result) {
2232 while ($obj = $this->db->fetch_object($result)) {
2233 //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
2234 if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
2235 $this->label = $obj->label;
2236 $this->description = $obj->description;
2237 }
2238 $this->multilangs[$obj->lang]["label"] = $obj->label;
2239 $this->multilangs[$obj->lang]["description"] = $obj->description;
2240 }
2241 return 1;
2242 } else {
2243 $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
2244 return -1;
2245 }
2246 }
2247
2254 public function getLibStatut($mode)
2255 {
2256 return '';
2257 }
2258
2259
2267 public function initAsSpecimen()
2268 {
2269 dol_syslog(get_class($this)."::initAsSpecimen");
2270
2271 // Initialise parameters
2272 $this->id = 0;
2273 $this->fk_parent = 0;
2274 $this->label = 'SPECIMEN';
2275 $this->specimen = 1;
2276 $this->description = 'This is a description';
2277 $this->socid = 1;
2278 $this->type = self::TYPE_PRODUCT;
2279
2280 return 1;
2281 }
2282
2291 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2292 {
2293 $tables = array(
2294 'categorie_societe'
2295 );
2296
2297 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables, 1);
2298 }
2299
2308 public static function getFilterJoinQuery($type, $rowIdName)
2309 {
2310 if ($type == 'bank_account') {
2311 $type = 'account';
2312 }
2313
2314 return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type;
2315 }
2316
2326 public static function getFilterSelectQuery($type, $rowIdName, $searchList)
2327 {
2328 if ($type == 'bank_account') {
2329 $type = 'account';
2330 }
2331 if ($type == 'customer') {
2332 $type = 'societe';
2333 }
2334 if ($type == 'supplier') {
2335 $type = 'fournisseur';
2336 }
2337
2338 if (empty($searchList) && !is_array($searchList)) {
2339 return "";
2340 }
2341
2342 $searchCategorySqlList = array();
2343 foreach ($searchList as $searchCategory) {
2344 if (intval($searchCategory) == -2) {
2345 $searchCategorySqlList[] = " cp.fk_categorie IS NULL";
2346 } elseif (intval($searchCategory) > 0) {
2347 $searchCategorySqlList[] = " ".$rowIdName." IN (SELECT fk_".$type." FROM ".MAIN_DB_PREFIX."categorie_".$type." WHERE fk_categorie = ".((int) $searchCategory).")";
2348 }
2349 }
2350
2351 if (!empty($searchCategorySqlList)) {
2352 return " AND (".implode(' AND ', $searchCategorySqlList).")";
2353 } else {
2354 return "";
2355 }
2356 }
2357
2363 public function countNbOfCategories()
2364 {
2365 dol_syslog(get_class($this)."::count_all_categories", LOG_DEBUG);
2366 $sql = "SELECT COUNT(rowid) FROM ".MAIN_DB_PREFIX."categorie";
2367 $sql .= " WHERE entity IN (".getEntity('category').")";
2368
2369 $res = $this->db->query($sql);
2370 if ($res) {
2371 $obj = $this->db->fetch_object($res);
2372 return $obj->count;
2373 } else {
2374 dol_print_error($this->db);
2375 return -1;
2376 }
2377 }
2378}
print $object position
Definition edit.php:206
$object ref
Definition info.php:90
Class to manage categories.
getListForItem($id, $type='customer', $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Return the list of the categories of a given element (a product, a customer, ...).
get_image_size($file)
Load size of image file.
load_motherof()
Load the array this->motherof that is array(id_son=>id_parent, ...), so array of all child categories...
getLibStatut($mode)
Return label of contact status.
delete_photo($file)
Efface la photo de la categorie et sa vignette.
containing($id, $type, $mode='object')
Return list of categories (object instances or labels) linked to a given object having id $id and typ...
getTooltipContentArray($params)
getTooltipContentArray
countNbOfCategories()
Count all categories.
del_type($obj, $type)
Delete object from category.
buildPathFromId($id_categ, $protection=1000)
For category id_categ and its children available in this->cats, define property fullpath and fulllabe...
static getFilterSelectQuery($type, $rowIdName, $searchList)
Return the additional SQL SELECT query for filtering a list by a category.
delMultiLangs($langtodelete, $user)
Delete a language for this category.
create($user, $notrigger=0)
Add category into database.
rechercher($id, $nom, $type, $exact=false, $case=false)
Returns categories whose id or name matches.
getMultiLangs()
Load array this->multilangs.
isAnyPhotoAvailable($sdir)
Return if at least one photo is available.
already_exists()
Check if a category with same label already exists for this cat's parent or root and for this cat's t...
get_filles()
Return direct children ids of a category into an array.
initAsSpecimen()
Initialise an instance with random values.
get_all_categories($type=null, $parent=false)
Returns all categories.
static getFilterJoinQuery($type, $rowIdName)
Return the additional SQL JOIN query for filtering a list by a category.
containsObject($type, $object_id)
Check for the presence of a given object in the current category.
get_main_categories($type=null)
Returns the first level categories (which are not child)
__construct($db)
Constructor.
getMapId()
Get MAP_ID.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
setMultiLangs(User $user, $notrigger=0)
Create or Update translations of categories labels.
getMapList()
Get map list.
$fields
'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter...
get_meres()
Returns an array containing the list of parent categories Note: A category can only have one parent b...
get_full_arbo($type, $fromid=0, $include=0, $forcelangcode='')
Rebuilding the category tree as an array Return an array of table('id','id_mere',....
add_type($obj, $type='')
Link an object to the category.
update(User $user, $notrigger=0)
Update category.
liste_photos($dir, $nbmax=0)
Return an array with all photos inside the directory.
get_all_ways()
Returns in a array all possible paths to go to the category starting with the major categories repres...
getNomUrl($withpicto=0, $option='', $maxlength=0, $moreparam='', $notooltip=0, $morecss='', $save_lastsearch_value=0)
Return name and link of category (with picto) Use ->id, ->ref, ->label, ->color.
print_all_ways($sep='&gt;&gt;', $url='', $nocolor=0, $addpicto=0)
Returns the path of the category, with the names of the categories separated by $sep (" >> " by defau...
add_photo($sdir, $file)
Add the image uploaded as $file to the directory $sdir/<category>-<id>/photos/.
fetch($id, $label='', $type=null, $ref_ext='')
Load category into memory from database.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
addThumbs($file, $quality=50)
Build thumb.
Class to manage Dolibarr database access.
Class to manage Dolibarr users.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
colorIsLight($stringcolor)
Return true if the color is light.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
utf8_check($str)
Check if a string is in UTF8.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
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.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:158