dolibarr 25.0.0-alpha
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-2026 Charlene Benke <charlene@patas-monkey.com>
13 * Copyright (C) 2018-2026 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-2026 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 const TYPE_SUPPLIER_PROPOSAL = 'supplier_proposal';
73 const TYPE_PROPOSAL = 'propal';
74 const TYPE_PROJECT_TASK = 'project_task';
75 const TYPE_MO = 'mo';
76
77
81 public $picto = 'category';
82
83
87 public $MAP_ID = array(
88 'product' => 0,
89 'service' => 0,
90 'supplier' => 1,
91 'customer' => 2,
92 'member' => 3,
93 'contact' => 4,
94 'bank_account' => 5,
95 'project' => 6,
96 'user' => 7,
97 'bank_line' => 8,
98 'warehouse' => 9,
99 'actioncomm' => 10,
100 'website_page' => 11,
101 'ticket' => 12,
102 'knowledgemanagement' => 13,
103 'fichinter' => 14,
104 'order' => 16,
105 'invoice' => 17,
106 'supplier_order' => 20,
107 'supplier_invoice' => 21,
108 'supplier_proposal' => 22,
109 'propal' => 23,
110 'project_task' => 24,
111 'mo' => 25,
112 );
113
119 /*
120 public static $MAP_ID_TO_CODE = array(
121 0 => 'product',
122 1 => 'supplier',
123 2 => 'customer',
124 3 => 'member',
125 4 => 'contact',
126 5 => 'bank_account',
127 6 => 'project',
128 7 => 'user',
129 8 => 'bank_line',
130 9 => 'warehouse',
131 10 => 'actioncomm',
132 11 => 'website_page',
133 12 => 'ticket',
134 13 => 'knowledgemanagement',
135 14 => 'fichinter',
136 16 => 'order',
137 17 => 'invoice',
138 20 => 'supplier_order',
139 21 => 'supplier_invoice',
140 22 => 'supplier_proposal',
141 23 => 'propal',
142 24 => 'project_task'
143 );
144 */
145
149 public $MAP_CAT_FK = array(
150 'customer' => 'soc',
151 'supplier' => 'soc',
152 'contact' => 'socpeople',
153 'bank_account' => 'account',
154 );
155
159 public $MAP_CAT_TABLE = array(
160 'customer' => 'societe',
161 'supplier' => 'fournisseur',
162 'bank_account' => 'account',
163 );
164
168 public $MAP_OBJ_CLASS = array(
169 'product' => 'Product',
170 'service' => 'Product',
171 'customer' => 'Societe',
172 'supplier' => 'Fournisseur',
173 'member' => 'Adherent',
174 'contact' => 'Contact',
175 'user' => 'User',
176 'account' => 'Account', // old for bank account
177 'bank_account' => 'Account',
178 'project' => 'Project',
179 'warehouse' => 'Entrepot',
180 'actioncomm' => 'ActionComm',
181 'website_page' => 'WebsitePage',
182 'ticket' => 'Ticket',
183 'knowledgemanagement' => 'KnowledgeRecord',
184 'fichinter' => 'Fichinter',
185 'order' => 'Commande',
186 'invoice' => 'Facture',
187 'supplier_order' => 'CommandeFournisseur',
188 'supplier_invoice' => 'FactureFournisseur',
189 'supplier_proposal' => 'SupplierProposal',
190 'propal' => 'Propal',
191 'project_task' => 'Task',
192 'mo' => 'Mo',
193 );
194
198 public static $MAP_TYPE_TITLE_AREA = array(
199 'product' => 'Products',
200 'service' => 'Services',
201 'customer' => 'ProspectsOrCustomers',
202 'supplier' => 'Suppliers',
203 'member' => 'Members',
204 'contact' => 'Contacts',
205 'user' => 'Users',
206 'account' => 'Accounts', // old for bank account
207 'bank_account' => 'BankAccounts',
208 'bank_line' => 'BankTransactions',
209 'project' => 'Projects',
210 'warehouse' => 'Warehouse',
211 'actioncomm' => 'AgendaEvents',
212 'website_page' => 'WebsitePages',
213 'ticket' => 'Tickets',
214 'knowledgemanagement' => 'KnowledgeRecords',
215 'fichinter' => 'Interventions',
216 'order' => 'Orders',
217 'invoice' => 'Invoices',
218 'supplier_order' => 'SuppliersOrders',
219 'supplier_invoice' => 'SuppliersInvoices',
220 'propal' => 'Proposals',
221 'supplier_proposal' => 'SupplierProposals',
222 'project_task' => 'Tasks',
223 'mo' => 'MOs'
224 );
225
230 public $MAP_OBJ_TABLE = array(
231 'customer' => 'societe',
232 'supplier' => 'societe',
233 'member' => 'adherent',
234 'contact' => 'socpeople',
235 'account' => 'bank_account', // old for bank account
236 'project' => 'projet',
237 'warehouse' => 'entrepot',
238 'knowledgemanagement' => 'knowledgemanagement_knowledgerecord',
239 'fichinter' => 'fichinter',
240 'order' => 'commande',
241 'invoice' => 'facture',
242 'supplier_order' => 'commande_fournisseur',
243 'supplier_invoice' => 'facture_fourn',
244 'project_task' => 'projet_task',
245 'mo' => 'mrp_mo'
246 );
247
251 public $element = 'category';
252
256 public $table_element = 'categorie';
257
261 public $fk_parent;
262
266 public $label;
267
271 public $description;
272
276 public $color;
277
281 public $position;
282
286 public $visible;
287
291 public $socid;
292
316 public $type;
317
321 public $cats = array();
322
326 public $motherof = array();
327
331 public $childs = array();
332
336 public $multilangs = array();
337
341 public $imgWidth;
342
346 public $imgHeight;
347
372 public $fields = array(
373 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'visible' => 0,),
374 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'default' => '1', 'notnull' => 1, 'index' => 1, 'position' => 5),
375 'fk_parent' => array('type' => 'integer', 'label' => 'ParentCategory', 'enabled' => 1, 'position' => 20, 'notnull' => 1, 'visible' => 0, 'css' => 'maxwidth500 widthcentpercentminusxx',),
376 '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),
377 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'position' => 30, 'notnull' => 0, 'visible' => 0, 'alwayseditable' => 1,),
378 'type' => array('type' => 'integer', 'label' => 'Type', 'enabled' => 1, 'position' => 35, 'notnull' => 1, 'visible' => 0, 'alwayseditable' => 1,),
379 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'position' => 40, 'notnull' => 0, 'visible' => 1, 'alwayseditable' => 1,),
380 'color' => array('type' => 'varchar(8)', 'label' => 'Color', 'enabled' => 1, 'position' => 45, 'notnull' => 0, 'visible' => 1, 'alwayseditable' => 1,),
381 'position' => array('type' => 'integer', 'label' => 'Position', 'enabled' => 1, 'position' => 50, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
382 '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',),
383 'visible' => array('type' => 'integer', 'label' => 'Visible', 'enabled' => 1, 'position' => 60, 'notnull' => 1, 'visible' => 0, 'alwayseditable' => 1,),
384 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 900, 'notnull' => 0, 'visible' => -2, 'alwayseditable' => 1,),
385 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 70, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
386 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 75, 'notnull' => 1, 'visible' => -1, 'alwayseditable' => 1,),
387 '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',),
388 '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',),
389 );
390
396 public function __construct($db)
397 {
398 global $hookmanager;
399
400 $this->db = $db;
401
402 $this->ismultientitymanaged = 1;
403 $this->isextrafieldmanaged = 1;
404
405 if (is_object($hookmanager)) {
406 $hookmanager->initHooks(array('category'));
407 $parameters = array();
408 $reshook = $hookmanager->executeHooks('constructCategory', $parameters, $this); // Note that $action and $object may have been modified by some hooks
409 if ($reshook >= 0 && !empty($hookmanager->resArray)) {
410 foreach ($hookmanager->resArray as $mapList) {
412 $mapId = $mapList['id'];
413 $mapCode = $mapList['code'];
414 //self::$MAP_ID_TO_CODE[$mapId] = $mapCode;
415 $this->MAP_ID[$mapCode] = $mapId;
416 $this->MAP_CAT_FK[$mapCode] = isset($mapList['cat_fk']) ? $mapList['cat_fk'] : null; // @phan-suppress-current-line SqlInjection
417 $this->MAP_CAT_TABLE[$mapCode] = isset($mapList['cat_table']) ? $mapList['cat_table'] : null; // @phan-suppress-current-line SqlInjection
418 $this->MAP_OBJ_CLASS[$mapCode] = $mapList['obj_class']; // @phan-suppress-current-line SqlInjection
419 $this->MAP_OBJ_TABLE[$mapCode] = $mapList['obj_table']; // @phan-suppress-current-line SqlInjection
420 self::$MAP_TYPE_TITLE_AREA[$mapCode] = isset($mapList['label']) ? $mapList['label'] : null;
421 }
422 }
423 }
424 }
425
431 public function getMapList()
432 {
433 $mapList = array();
434
435 foreach ($this->MAP_ID as $mapCode => $mapId) {
436 $mapList[] = array(
437 'id' => $mapId,
438 'code' => $mapCode,
439 'cat_fk' => (empty($this->MAP_CAT_FK[$mapCode]) ? $mapCode : $this->MAP_CAT_FK[$mapCode]),
440 'cat_table' => (empty($this->MAP_CAT_TABLE[$mapCode]) ? $mapCode : $this->MAP_CAT_TABLE[$mapCode]),
441 'obj_class' => (empty($this->MAP_OBJ_CLASS[$mapCode]) ? $mapCode : $this->MAP_OBJ_CLASS[$mapCode]),
442 'obj_table' => (empty($this->MAP_OBJ_TABLE[$mapCode]) ? $mapCode : $this->MAP_OBJ_TABLE[$mapCode]),
443 );
444 }
445
446 return $mapList;
447 }
448
454 public function getMapId()
455 {
456 return $this->MAP_ID;
457 }
458
468 public function fetch($id, $label = '', $type = null, $ref_ext = '')
469 {
470 // Check parameters
471 if (empty($id) && empty($label) && empty($ref_ext)) {
472 $this->error = "No category to search for";
473 return -1;
474 }
475 if (!is_null($type) && !is_numeric($type)) {
476 $type = $this->MAP_ID[$type];
477 }
478
479 $sql = "SELECT rowid, fk_parent, entity, label, description, color, position, fk_soc, visible, type, ref_ext";
480 $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif, import_key";
481 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
482 if ($id) {
483 $sql .= " WHERE rowid = ".((int) $id);
484 } elseif (!empty($ref_ext)) {
485 $sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'";
486 } else {
487 $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")";
488 if (!is_null($type)) {
489 $sql .= " AND type = ".((int) $type);
490 }
491 }
492
493 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
494 $resql = $this->db->query($sql);
495 if ($resql) {
496 if ($this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
497 $this->id = $res['rowid'];
498 //$this->ref = $res['rowid'];
499 $this->fk_parent = (int) $res['fk_parent'];
500 $this->label = $res['label'];
501 $this->description = $res['description'];
502 $this->color = $res['color'];
503 $this->position = $res['position'];
504 $this->socid = (int) $res['fk_soc'];
505 $this->visible = (int) $res['visible'];
506 $this->type = $res['type'];
507 $this->ref_ext = $res['ref_ext'];
508 $this->entity = (int) $res['entity'];
509 $this->date_creation = $this->db->jdate($res['date_creation']);
510 $this->date_modification = $this->db->jdate($res['tms']);
511 $this->user_creation_id = (int) $res['fk_user_creat'];
512 $this->user_modification_id = (int) $res['fk_user_modif'];
513 $this->import_key = $res['import_key'];
514
515 // Retrieve all extrafields
516 // fetch optionals attributes and labels
517 $this->fetch_optionals();
518
519 $this->db->free($resql);
520
521 // multilangs
522 if (getDolGlobalInt('MAIN_MULTILANGS')) {
523 $this->getMultiLangs();
524 }
525
526 return 1;
527 } else {
528 $this->error = "No category found";
529 return 0;
530 }
531 } else {
532 dol_print_error($this->db);
533 $this->error = $this->db->lasterror;
534 $this->errors[] = $this->db->lasterror;
535 return -1;
536 }
537 }
538
549 public function create($user, $notrigger = 0)
550 {
551 global $conf, $langs;
552 $langs->load('categories');
553
554 $type = $this->type;
555
556 if (!is_numeric($type)) {
557 $type = $this->MAP_ID[$type];
558 }
559
560 $error = 0;
561
562 dol_syslog(get_class($this).'::create', LOG_DEBUG);
563
564 // Clean parameters
565 $this->label = trim((string) $this->label);
566 $this->description = trim((string) $this->description);
567 $this->color = trim((string) $this->color);
568 $this->position = (int) $this->position;
569 if (isset($this->import_key)) {
570 $this->import_key = trim($this->import_key);
571 }
572 $this->ref_ext = trim((string) $this->ref_ext);
573 if (empty($this->visible)) {
574 $this->visible = 0;
575 }
576 $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
577
578 if ($this->already_exists()) {
579 $this->error = $langs->trans("ImpossibleAddCat", $this->label);
580 $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
581 dol_syslog($this->error, LOG_WARNING);
582 return -4;
583 }
584
585 $this->db->begin();
586 $now = dol_now();
587 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie (";
588 $sql .= "fk_parent,";
589 $sql .= " label,";
590 $sql .= " description,";
591 $sql .= " color,";
592 $sql .= " position,";
593 if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
594 $sql .= "fk_soc,";
595 }
596 $sql .= " visible,";
597 $sql .= " type,";
598 $sql .= " import_key,";
599 $sql .= " ref_ext,";
600 $sql .= " entity,";
601 $sql .= " date_creation,";
602 $sql .= " fk_user_creat";
603 $sql .= ") VALUES (";
604 $sql .= (int) $this->fk_parent.",";
605 $sql .= "'".$this->db->escape($this->label)."', ";
606 $sql .= "'".$this->db->escape($this->description)."', ";
607 $sql .= "'".$this->db->escape($this->color)."', ";
608 $sql .= (int) $this->position.",";
609 if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
610 $sql .= ($this->socid > 0 ? ((int) $this->socid) : 'null').", ";
611 }
612 $sql .= "'".$this->db->escape((string) $this->visible)."', ";
613 $sql .= ((int) $type).", ";
614 $sql .= (!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : 'null').", ";
615 $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : 'null').", ";
616 $sql .= (int) $conf->entity.", ";
617 $sql .= "'".$this->db->idate($now)."', ";
618 $sql .= (int) $user->id;
619 $sql .= ")";
620
621 $res = $this->db->query($sql);
622 if ($res) {
623 $id = $this->db->last_insert_id(MAIN_DB_PREFIX."categorie");
624
625 if ($id > 0) {
626 $this->id = $id;
627
628 $action = 'create';
629
630 // Actions on extra fields
631 $result = $this->insertExtraFields();
632 if ($result < 0) {
633 $error++;
634 }
635
636 if (!$error && !$notrigger) {
637 // Call trigger
638 $result = $this->call_trigger('CATEGORY_CREATE', $user);
639 if ($result < 0) {
640 $error++;
641 }
642 // End call triggers
643 }
644
645 if (!$error) {
646 $this->db->commit();
647 return $id;
648 } else {
649 $this->db->rollback();
650 return -3;
651 }
652 } else {
653 $this->db->rollback();
654 return -2;
655 }
656 } else {
657 $this->error = $this->db->error();
658 $this->db->rollback();
659 return -1;
660 }
661 }
662
672 public function update(User $user, $notrigger = 0)
673 {
674 global $langs;
675
676 $error = 0;
677
678 // Clean parameters
679 $this->label = trim((string) $this->label);
680 $this->description = trim((string) $this->description);
681 $this->ref_ext = trim((string) $this->ref_ext);
682 $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
683 $this->visible = ($this->visible != "" ? intval($this->visible) : 0);
684
685 if ($this->fk_parent > 0 && $this->fk_parent == $this->id) {
686 $langs->load('categories');
687 $this->error = $langs->trans("ErrorCategoryCannotBeItsOwnParent");
688 dol_syslog($this->error, LOG_WARNING);
689 return -1;
690 }
691 // Nor one of its descendants, which would detach both from the tree and make a loop: go up from the new parent
692 // (only when the parent changes, or when we do not know the previous parent)
693 if (empty($this->oldcopy) || $this->fk_parent != $this->oldcopy->fk_parent) {
694 $ancestorid = $this->fk_parent;
695 $protection = 1000;
696 while ($ancestorid > 0 && $protection-- > 0) {
697 $resql = $this->db->query("SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie WHERE rowid = ".((int) $ancestorid));
698 $obj = $resql ? $this->db->fetch_object($resql) : null;
699 $ancestorid = $obj ? (int) $obj->fk_parent : 0;
700 if ($ancestorid == $this->id) {
701 $langs->load('categories');
702 $this->error = $langs->trans("ErrorCategoryCannotBeMovedIntoItsDescendant");
703 dol_syslog($this->error, LOG_WARNING);
704 return -1;
705 }
706 }
707 }
708
709 if ($this->already_exists()) {
710 $this->error = $langs->trans("ImpossibleUpdateCat");
711 $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
712 return -1;
713 }
714
715 $this->db->begin();
716
717 $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
718 $sql .= " SET label = '".$this->db->escape($this->label)."',";
719 $sql .= " description = '".$this->db->escape($this->description)."',";
720 $sql .= " ref_ext = '".$this->db->escape($this->ref_ext)."',";
721 $sql .= " color = '".$this->db->escape($this->color)."'";
722 $sql .= ", position = ".(int) $this->position;
723 if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
724 $sql .= ", fk_soc = ".($this->socid > 0 ? ((int) $this->socid) : 'null');
725 }
726 $sql .= ", visible = ".(int) $this->visible;
727 $sql .= ", fk_parent = ".(int) $this->fk_parent;
728 $sql .= ", fk_user_modif = ".(int) $user->id;
729 $sql .= " WHERE rowid = ".((int) $this->id);
730
731 dol_syslog(get_class($this)."::update", LOG_DEBUG);
732 if ($this->db->query($sql)) {
733 // Multilangs
734 if (getDolGlobalInt('MAIN_MULTILANGS')) {
735 if ($this->setMultiLangs($user, $notrigger) < 0) {
736 $this->db->rollback();
737 return -2;
738 }
739 }
740
741 $action = 'update';
742
743 // Actions on extra fields
744 $result = $this->insertExtraFields();
745 if ($result < 0) {
746 $error++;
747 }
748
749 if (!$error && !$notrigger) {
750 // Call trigger
751 $result = $this->call_trigger('CATEGORY_MODIFY', $user);
752 if ($result < 0) {
753 $error++;
754 }
755 // End call triggers
756 }
757
758 if (!$error) {
759 $this->db->commit();
760 return 1;
761 } else {
762 $this->db->rollback();
763 return -1;
764 }
765 } else {
766 $this->db->rollback();
767 dol_print_error($this->db);
768 return -1;
769 }
770 }
771
779 public function delete($user, $notrigger = 0)
780 {
781 $error = 0;
782
783 // Clean parameters
784 $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
785
786 dol_syslog(get_class($this)."::remove");
787
788 $this->db->begin();
789
790 if (/* !$error && */ !$notrigger) {
791 // Call trigger
792 $result = $this->call_trigger('CATEGORY_DELETE', $user);
793 if ($result < 0) {
794 $error++;
795 }
796 // End call triggers
797 }
798
799 /* FIX #1317 : Check for child category and move up 1 level*/
800 if (!$error) {
801 $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
802 $sql .= " SET fk_parent = ".((int) $this->fk_parent);
803 $sql .= " WHERE fk_parent = ".((int) $this->id);
804
805 if (!$this->db->query($sql)) {
806 $this->error = $this->db->lasterror();
807 $error++;
808 }
809 }
810
811 $arraydelete = array(
812 'categorie_account' => 'fk_categorie',
813 'categorie_actioncomm' => 'fk_categorie',
814 'categorie_contact' => 'fk_categorie',
815 'categorie_fournisseur' => 'fk_categorie',
816 'categorie_knowledgemanagement' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('knowledgemanagement')),
817 'categorie_fichinter' => array('field' => 'fk_categorie', 'enabled' => false ), // not yet fully implemented (wait 22) isModEnabled('intervention')),
818 'categorie_member' => 'fk_categorie',
819 'categorie_user' => 'fk_categorie',
820 'categorie_product' => 'fk_categorie',
821 'categorie_project' => 'fk_categorie',
822 'categorie_project_task' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('project')),
823 'categorie_societe' => 'fk_categorie',
824 'categorie_ticket' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('ticket')),
825 'categorie_warehouse' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('stock')),
826 'categorie_website_page' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('website')),
827 'category_bankline' => 'fk_categ',
828 'categorie_lang' => 'fk_category',
829 'categorie' => 'rowid',
830 );
831 // The links of the category are in the table of its own type: make sure that table is purged even when it is
832 // missing from the list above or disabled there, otherwise its foreign key refuses to delete the category.
833 $typecode = is_numeric($this->type) ? array_search((int) $this->type, $this->MAP_ID) : $this->type;
834 if (!empty($typecode) && $typecode != 'bank_line') { // the links of bank lines are in category_bankline, already in the list
835 $linktable = 'categorie_'.(empty($this->MAP_CAT_TABLE[$typecode]) ? $typecode : $this->MAP_CAT_TABLE[$typecode]);
836 if (array_key_exists($linktable, $arraydelete)) {
837 $arraydelete[$linktable] = 'fk_categorie';
838 } else {
839 $arraydelete = array($linktable => 'fk_categorie') + $arraydelete;
840 }
841 }
842 foreach ($arraydelete as $key => $value) {
843 $sanitizedvalue = $value;
844 if (is_array($value)) {
845 if (empty($value['enabled'])) {
846 continue;
847 }
848 $sanitizedvalue = $value['field']; // From explicit array above @phan-suppress-current-line SqlInjection
849 }
850
851 $sql = "DELETE FROM ".$this->db->sanitize(MAIN_DB_PREFIX.$key);
852 $sql .= " WHERE ".$this->db->sanitize($sanitizedvalue)." = ".((int) $this->id);
853 if (!$this->db->query($sql)) {
854 $this->errors[] = $this->db->lasterror();
855 dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR);
856 $error++;
857 }
858 }
859
860 // Removed extrafields
861 if (!$error) {
862 $result = $this->deleteExtraFields();
863 if ($result < 0) {
864 $error++;
865 dol_syslog(get_class($this)."::delete erreur ".$this->error, LOG_ERR);
866 }
867 }
868
869 if (!$error) {
870 $this->db->commit();
871 return 1;
872 } else {
873 $this->db->rollback();
874 return -1;
875 }
876 }
877
878 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
888 public function add_type($obj, $type = '', $notrigger = 0)
889 {
890 // phpcs:enable
891 global $user;
892
893 $error = 0;
894
895 if ($this->id == -1) {
896 return -2;
897 }
898
899 if (empty($type)) {
900 $type = $obj->element;
901 }
902
903 dol_syslog(get_class($this).'::add_type', LOG_DEBUG);
904
905 $this->db->begin();
906
907 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
908 $sql .= " (fk_categorie, fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]).")";
909 $sql .= " VALUES (".((int) $this->id).", ".((int) $obj->id).")";
910
911 if ($this->db->query($sql)) {
912 if (getDolGlobalString('CATEGORIE_RECURSIV_ADD')) {
913 $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie';
914 $sql .= " WHERE rowid = ".((int) $this->id);
915
916 dol_syslog(get_class($this)."::add_type", LOG_DEBUG);
917 $resql = $this->db->query($sql);
918 if ($resql) {
919 if ($this->db->num_rows($resql) > 0) {
920 $objparent = $this->db->fetch_object($resql);
921
922 if (!empty($objparent->fk_parent)) {
923 $cat = new Categorie($this->db);
924 $cat->id = $objparent->fk_parent;
925 if (!$cat->containsObject($type, $obj->id)) {
926 $result = $cat->add_type($obj, $type);
927 if ($result < 0) {
928 $this->error = $cat->error;
929 $error++;
930 }
931 }
932 }
933 }
934 } else {
935 $error++;
936 $this->error = $this->db->lasterror();
937 }
938
939 if ($error) {
940 $this->db->rollback();
941 return -1;
942 }
943 }
944
945 // Call trigger
946 if (empty($notrigger)) {
947 $this->context = array('linkto' => $obj); // Save object we want to link category to into category instance to provide information to trigger
948 $result = $this->call_trigger('CATEGORY_MODIFY', $user);
949 if ($result < 0) {
950 $error++;
951 }
952 }
953 // End call triggers
954
955 if (!$error) {
956 $this->db->commit();
957 return 1;
958 } else {
959 $this->db->rollback();
960 return -2;
961 }
962 } else {
963 $this->db->rollback();
964 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
965 $this->error = $this->db->lasterrno();
966 return -3;
967 } else {
968 $this->error = $this->db->lasterror();
969 }
970 return -1;
971 }
972 }
973
974 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
984 public function del_type($obj, $type, $notrigger = 0)
985 {
986 // phpcs:enable
987 global $user;
988
989 $error = 0;
990
991 // For backward compatibility
992 if ($type == 'societe') {
993 $type = 'customer';
994 dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
995 } elseif ($type == 'fournisseur') {
996 $type = 'supplier';
997 dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
998 }
999
1000 $this->db->begin();
1001
1002 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
1003 $sql .= " WHERE fk_categorie = ".((int) $this->id);
1004 $sql .= " AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $obj->id);
1005
1006 dol_syslog(get_class($this).'::del_type', LOG_DEBUG);
1007 if ($this->db->query($sql)) {
1008 // Call trigger
1009 if (empty($notrigger)) {
1010 $this->context = array('unlinkoff' => $obj); // Save object we want to link category to into category instance to provide information to trigger
1011 $result = $this->call_trigger('CATEGORY_MODIFY', $user);
1012 if ($result < 0) {
1013 $error++;
1014 }
1015 }
1016 // End call triggers
1017
1018 if (!$error) {
1019 $this->db->commit();
1020 return 1;
1021 } else {
1022 $this->db->rollback();
1023 return -2;
1024 }
1025 } else {
1026 $this->db->rollback();
1027 $this->error = $this->db->lasterror();
1028 return -1;
1029 }
1030 }
1031
1050 public function getObjectsInCateg($type, $onlyids = 0, $limit = 0, $offset = 0, $sortfield = '', $sortorder = 'ASC', $filter = '', $filtermode = 'AND', $filterlang = '')
1051 {
1052 global $user;
1053
1054 if (empty($onlyids)) {
1055 dol_syslog("getObjectsInCateg: This method used with parameter onlyids=0 is deprecated. Try by using instead getListForItem().", LOG_WARNING);
1056 }
1057
1058 $objs = array();
1059
1060 $classnameforobj = $this->MAP_OBJ_CLASS[$type];
1061 if (!empty($classnameforobj) && class_exists($classnameforobj)) {
1062 $tmpobj = new $classnameforobj($this->db);
1065 $sql = "SELECT c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." as fk_object";
1066 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as c";
1067 $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." as o";
1068 if (!empty($filterlang)) {
1069 $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])."_lang as ol";
1070 }
1071 $sql .= " WHERE o.entity IN (".getEntity($tmpobj->element).")";
1072 $sql .= " AND c.fk_categorie = ".((int) $this->id);
1073 // Compatibility with actioncomm table which has id instead of rowid
1074 if ((array_key_exists($type, $this->MAP_OBJ_TABLE) && $this->MAP_OBJ_TABLE[$type] == "actioncomm") || $type == "actioncomm") {
1075 $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.id";
1076 } else {
1077 $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.rowid";
1078 }
1079 if (!empty($filterlang)) {
1080 $sql .= " AND ol.fk_".(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." = o.rowid";
1081 $sql .= " AND ol.lang = '".$this->db->escape($filterlang)."'";
1082 }
1083 // Protection for external users
1084 if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) {
1085 $sql .= " AND o.rowid = ".((int) $user->socid);
1086 }
1087
1088 // Add where from hooks (for example to restrict to objects an external module shares
1089 // with the current entity by a granularity finer than this category's own)
1090 global $hookmanager;
1091 if (is_object($hookmanager)) {
1092 $parameters = array('type' => $type, 'alias' => 'o');
1093 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this);
1094 $sql .= $hookmanager->resPrint;
1095 }
1096
1097 $errormessage = '';
1098 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
1099 if ($errormessage) {
1100 $this->errors[] = $errormessage;
1101 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
1102 return -1;
1103 }
1104
1105 $sql .= $this->db->order($sortfield, $sortorder);
1106 if ($limit > 0 || $offset > 0) {
1107 $sql .= $this->db->plimit($limit + 1, $offset);
1108 }
1109
1110 dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
1111
1112 $resql = $this->db->query($sql);
1113 if ($resql) {
1114 while ($rec = $this->db->fetch_array($resql)) {
1115 if ($onlyids) {
1116 $objs[] = $rec['fk_object'];
1117 } else {
1118 $tmpobj = new $classnameforobj($this->db);
1119 $tmpobj->fetch($rec['fk_object']); // The fetch will set $tmpobj->id only if it succeed.
1120 // @phpstan-ignore-next-line
1121 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.
1122 $objs[] = $tmpobj;
1123 }
1124 }
1125 }
1126 } else {
1127 $this->error = $this->db->error().' sql='.$sql;
1128 return -1;
1129 }
1130 }
1131
1132 return $objs;
1133 }
1134
1143 public function containsObject($type, $object_id)
1144 {
1145 $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
1146 $sql .= " WHERE fk_categorie = ".((int) $this->id)." AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $object_id);
1147
1148 dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
1149
1150 $resql = $this->db->query($sql);
1151 if ($resql) {
1152 return $this->db->fetch_object($resql)->nb;
1153 } else {
1154 $this->error = $this->db->error();
1155 return -1;
1156 }
1157 }
1158
1171 public function getListForItem($id, $type = 'customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
1172 {
1173 $categories = array();
1174
1175 $type = sanitizeVal($type, 'aZ09');
1176
1177 $sub_type = $type;
1178 $subcol_name = "fk_".$type;
1179 if ($type == "customer") {
1180 $sub_type = "societe";
1181 $subcol_name = "fk_soc";
1182 }
1183 if ($type == "supplier") {
1184 $sub_type = "fournisseur";
1185 $subcol_name = "fk_soc";
1186 }
1187 if ($type == "contact") {
1188 $subcol_name = "fk_socpeople";
1189 }
1190
1191 $idoftype = (int) (array_key_exists($type, $this->MAP_ID) ? $this->MAP_ID[$type] : -1);
1192
1193 $sql = "SELECT s.rowid";
1194 $sqlfields = $sql; // $sql fields to remove for count total
1195 $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s, ".MAIN_DB_PREFIX."categorie_".$this->db->sanitize($sub_type)." as sub";
1196 $sql .= ' WHERE s.entity IN ('.getEntity('category').')';
1197 $sql .= ' AND s.type = '.((int) $idoftype);
1198 $sql .= ' AND s.rowid = sub.fk_categorie';
1199 $sql .= " AND sub.".$this->db->sanitize($subcol_name)." = ".((int) $id);
1200
1201 $offset = 0;
1202 $nbtotalofrecords = '';
1203 if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
1204 $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
1205 $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
1206
1207 $resql = $this->db->query($sqlforcount);
1208 if ($resql) {
1209 $objforcount = $this->db->fetch_object($resql);
1210 $nbtotalofrecords = $objforcount->nbtotalofrecords;
1211 } else {
1212 dol_print_error($this->db);
1213 }
1214
1215 if (($limit >= (int) $nbtotalofrecords) && $page > 0) {
1216 return [];
1217 }
1218
1219 if (($page * $limit) >= (int) $nbtotalofrecords) { // if total resultset is smaller or equal then paging size (filtering), goto and load page 0
1220 $page = 0;
1221 $offset = 0;
1222 }
1223 $this->db->free($resql);
1224 }
1225
1226 $sql .= $this->db->order($sortfield, $sortorder);
1227 if ($limit) {
1228 if ($page < 0) {
1229 $page = 0;
1230 }
1231 $offset = $limit * $page;
1232
1233 $sql .= $this->db->plimit($limit + 1, $offset);
1234 }
1235
1236 $result = $this->db->query($sql);
1237 if ($result) {
1238 $i = 0;
1239 $num = $this->db->num_rows($result);
1240 $min = min($num, ($limit <= 0 ? $num : $limit));
1241 while ($i < $min) {
1242 $obj = $this->db->fetch_object($result);
1243 $category_static = new Categorie($this->db);
1244 if ($category_static->fetch($obj->rowid)) {
1245 $categories[$i]['id'] = $category_static->id;
1246 $categories[$i]['fk_parent'] = $category_static->fk_parent;
1247 $categories[$i]['label'] = $category_static->label;
1248 $categories[$i]['description'] = $category_static->description;
1249 $categories[$i]['color'] = $category_static->color;
1250 $categories[$i]['position'] = $category_static->position;
1251 $categories[$i]['socid'] = $category_static->socid;
1252 $categories[$i]['ref_ext'] = $category_static->ref_ext;
1253 $categories[$i]['visible'] = $category_static->visible;
1254 $categories[$i]['type'] = $category_static->type;
1255 $categories[$i]['entity'] = $category_static->entity;
1256 $categories[$i]['array_options'] = $category_static->array_options;
1257
1258 // multilangs
1259 if (getDolGlobalInt('MAIN_MULTILANGS') && isset($category_static->multilangs)) {
1260 $categories[$i]['multilangs'] = $category_static->multilangs;
1261 }
1262 }
1263 $i++;
1264 }
1265 } else {
1266 $this->error = $this->db->lasterror();
1267 return -1;
1268 }
1269 if (!count($categories)) {
1270 return [];
1271 }
1272
1273 return $categories;
1274 }
1275
1276 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1282 public function get_filles()
1283 {
1284 // phpcs:enable
1285 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1286 $sql .= " WHERE fk_parent = ".((int) $this->id);
1287 $sql .= " AND entity IN (".getEntity('category').")";
1288
1289 $res = $this->db->query($sql);
1290 if ($res) {
1291 $cats = array();
1292 while ($rec = $this->db->fetch_array($res)) {
1293 $cat = new Categorie($this->db);
1294 $cat->fetch($rec['rowid']);
1295 $cats[] = $cat;
1296 }
1297 return $cats;
1298 } else {
1299 dol_print_error($this->db);
1300 return -1;
1301 }
1302 }
1303
1304 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1311 protected function load_motherof()
1312 {
1313 // phpcs:enable
1314 $this->motherof = array();
1315
1316 // Load array[child]=parent
1317 $sql = "SELECT fk_parent as id_parent, rowid as id_son";
1318 $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
1319 $sql .= " WHERE fk_parent <> 0";
1320 $sql .= " AND entity IN (".getEntity('category').")";
1321
1322 dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
1323 $resql = $this->db->query($sql);
1324 if ($resql) {
1325 while ($obj = $this->db->fetch_object($resql)) {
1326 $this->motherof[$obj->id_son] = $obj->id_parent;
1327 }
1328 return 1;
1329 } else {
1330 dol_print_error($this->db);
1331 return -1;
1332 }
1333 }
1334
1335 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1356 public function get_full_arbo($type, $fromid = 0, $include = 0, $forcelangcode = '')
1357 {
1358 // phpcs:enable
1359 global $langs;
1360
1361 if (!is_numeric($type)) {
1362 $type = isset($this->MAP_ID[$type]) ? $this->MAP_ID[$type] : null;
1363 }
1364 if (is_null($type)) {
1365 $this->error = 'BadValueForParameterType';
1366 return -1;
1367 }
1368
1369 if (is_string($fromid)) {
1370 $fromid = explode(',', $fromid);
1371 } elseif (is_numeric($fromid)) {
1372 if ($fromid > 0) {
1373 $fromid = array($fromid);
1374 } else {
1375 $fromid = array();
1376 }
1377 } elseif (!is_array($fromid)) {
1378 $fromid = array();
1379 }
1380
1381 $this->cats = array();
1382 $nbcateg = 0;
1383
1384 // Init this->motherof that is array(id_son=>id_parent, ...)
1385 $this->load_motherof();
1386
1387 if ($forcelangcode) {
1388 $current_lang = $forcelangcode;
1389 } else {
1390 $current_lang = $langs->getDefaultLang();
1391 }
1392
1393 // Init $this->cats array
1394 // Note: The DISTINCT reduces pb with old tables with duplicates but should not be used
1395 $sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.position, c.fk_parent, c.visible, c.entity";
1396 if (getDolGlobalInt('MAIN_MULTILANGS') && $current_lang !== 'none') {
1397 $sql .= ", t.label as label_trans, t.description as description_trans";
1398 }
1399 $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
1400 if (getDolGlobalInt('MAIN_MULTILANGS') && $current_lang !== 'none') {
1401 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category = c.rowid AND t.lang = '".$this->db->escape($current_lang)."'";
1402 }
1403 $sql .= " WHERE c.entity IN (".getEntity('category').")";
1404 $sql .= " AND c.type = ".(int) $type;
1405
1406 dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
1407
1408 $resql = $this->db->query($sql);
1409 if ($resql) {
1410 $i = 0;
1411 $nbcateg = $this->db->num_rows($resql);
1412
1413 while ($obj = $this->db->fetch_object($resql)) {
1414 $this->cats[(int) $obj->rowid]
1415 = array(
1416 'rowid' => (int) $obj->rowid,
1417 'id' => (int) $obj->rowid,
1418 'fk_parent' => (int) $obj->fk_parent,
1419 'label' => !empty($obj->label_trans) ? (string) $obj->label_trans : (string) $obj->label,
1420 'description' => !empty($obj->description_trans) ? (string) $obj->description_trans : (string) $obj->description,
1421 'color' => (string) $obj->color,
1422 'position' => (string) $obj->position,
1423 'visible' => (int) $obj->visible,
1424 'ref_ext' => (string) $obj->ref_ext,
1425 'entity' => (int) $obj->entity,
1426 'picto' => 'category',
1427 // fields are filled with buildPathFromId later
1428 'fullpath' => '',
1429 'fulllabel' => '',
1430 'level' => null,
1431 );
1432 $i++;
1433 }
1434 } else {
1435 dol_print_error($this->db);
1436 return -1;
1437 }
1438
1439 // Let external modules complete or filter the tree (for example to restrict categories
1440 // coming from other entities according to a sharing granularity they manage)
1441 global $hookmanager;
1442 if (is_object($hookmanager)) {
1443 $parameters = array('cats' => &$this->cats, 'motherof' => &$this->motherof, 'type' => $type);
1444 $reshook = $hookmanager->executeHooks('completeCategoryFullTree', $parameters, $this);
1445 if ($reshook < 0) {
1446 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1447 }
1448 }
1449
1450 // We add the fullpath property to each elements of first level (no parent exists)
1451 dol_syslog(get_class($this)."::get_full_arbo call to buildPathFromId", LOG_DEBUG);
1452
1453 foreach ($this->cats as $key => $val) {
1454 //print 'key='.$key.'<br>'."\n";
1455 $this->buildPathFromId($key, $nbcateg); // Process a branch from the root category key (this category has no parent) and adds level to $this->cats items
1456 }
1457
1458 // Include or exclude leaf (including $fromid) from tree
1459 if (count($fromid) > 0) {
1460 $keyfiltercatid = '('.implode('|', $fromid).')';
1461
1462 //print "Look to discard category ".$fromid."\n";
1463 $keyfilter1 = '^'.$keyfiltercatid.'$';
1464 $keyfilter2 = '_'.$keyfiltercatid.'$';
1465 $keyfilter3 = '^'.$keyfiltercatid.'_';
1466 $keyfilter4 = '_'.$keyfiltercatid.'_';
1467 foreach (array_keys($this->cats) as $key) {
1468 $fullpath = (string) $this->cats[$key]['fullpath'];
1469 $test = (preg_match('/'.$keyfilter1.'/', $fullpath) || preg_match('/'.$keyfilter2.'/', $fullpath)
1470 || preg_match('/'.$keyfilter3.'/', $fullpath) || preg_match('/'.$keyfilter4.'/', $fullpath));
1471
1472 if (($test && !$include) || (!$test && $include)) {
1473 unset($this->cats[$key]); // @phpstan-ignore-line
1474 }
1475 }
1476 }
1477
1478 dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
1479
1480 $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', 1, 0, 1); // Sort on full label like "Label 1 >> Sublabel a >> Subsublabel"
1481
1482 return $this->cats;
1483 }
1484
1495 private function buildPathFromId($id_categ, $protection = 1000)
1496 {
1497 //dol_syslog(get_class($this)."::buildPathFromId id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
1498
1499 if (!empty($this->cats[$id_categ]['fullpath'])) {
1500 // Already defined
1501 dol_syslog(get_class($this)."::buildPathFromId fullpath and fulllabel already defined", LOG_WARNING);
1502 return -1;
1503 }
1504
1505 // $this->cats[$id_categ] is supposed to be already an array. We just want to complete it with property fullpath and fulllabel
1506
1507 // Define fullpath and fulllabel
1508 $this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
1509 $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
1510 $i = 0;
1511 $cursor_categ = $id_categ;
1512 //print 'Work for id_categ='.$id_categ.'<br>'."\n";
1513 while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) {
1514 //print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
1515 $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
1516 $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'];
1517 //print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
1518 $i++;
1519 $cursor_categ = $this->motherof[$cursor_categ];
1520 }
1521 //print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'<br>'."\n";
1522
1523 // We count number of _ to have level
1524 $nbunderscore = substr_count($this->cats[$id_categ]['fullpath'], '_');
1525 $this->cats[$id_categ]['level'] = ($nbunderscore ? $nbunderscore : null);
1526
1527 return 1;
1528 }
1529
1530
1531 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1539 public function get_all_categories($type = null, $parent = false)
1540 {
1541 // phpcs:enable
1542 if (!is_numeric($type) && !is_null($type)) {
1543 $type = $this->MAP_ID[$type];
1544 }
1545
1546 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1547 $sql .= " WHERE entity IN (".getEntity('category').")";
1548 if (!is_null($type)) {
1549 $sql .= " AND type = ".(int) $type;
1550 }
1551 if ($parent) {
1552 $sql .= " AND fk_parent = 0";
1553 }
1554
1555 $res = $this->db->query($sql);
1556 if ($res) {
1557 $cats = array();
1558 while ($rec = $this->db->fetch_array($res)) {
1559 $cat = new Categorie($this->db);
1560 $cat->fetch($rec['rowid']);
1561 $cats[$rec['rowid']] = $cat;
1562 }
1563 return $cats;
1564 } else {
1565 dol_print_error($this->db);
1566 return -1;
1567 }
1568 }
1569
1570 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1577 public function get_main_categories($type = null)
1578 {
1579 // phpcs:enable
1580 return $this->get_all_categories($type, true);
1581 }
1582
1583 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1589 public function already_exists()
1590 {
1591 // phpcs:enable
1592 $type = $this->type;
1593
1594 if (!is_numeric($type)) {
1595 $type = $this->MAP_ID[$type];
1596 }
1597
1598 /* We have to select any rowid from llx_categorie which category's mother and label
1599 * are equals to those of the calling category
1600 */
1601 $sql = "SELECT c.rowid";
1602 $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c ";
1603 $sql .= " WHERE c.entity IN (".getEntity('category').")";
1604 $sql .= " AND c.type = ".((int) $type);
1605 $sql .= " AND c.fk_parent = ".((int) $this->fk_parent);
1606 $sql .= " AND c.label = '".$this->db->escape($this->label)."'";
1607
1608 dol_syslog(get_class($this)."::already_exists", LOG_DEBUG);
1609
1610 $resql = $this->db->query($sql);
1611 if ($resql) {
1612 if ($this->db->num_rows($resql) > 0) { // Checking for empty resql
1613 $obj = $this->db->fetch_object($resql);
1614 /* If object called create, obj cannot have is id.
1615 * If object called update, he mustn't have the same label as an other category for this mother.
1616 * 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.
1617 */
1618 if (!empty($obj) && $obj->rowid > 0 && $obj->rowid != $this->id) {
1619 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);
1620 return 1;
1621 }
1622 }
1623 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);
1624 return 0;
1625 } else {
1626 $this->error = $this->db->error();
1627 return -1;
1628 }
1629 }
1630
1631
1632 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1644 public function print_all_ways($sep = 'auto', $url = '', $nocolor = 0, $addpicto = 0, $notrunc = 0)
1645 {
1646 // phpcs:enable
1647 $ways = array();
1648
1649 if ($sep == 'auto') {
1650 $sep = '&gt;';
1651 }
1652
1653 $all_ways = $this->get_all_ways(); // Load array of categories from database to reach this->id
1654
1655 foreach ($all_ways as $way) { // It seems we always have 1 entry in this array.
1656 $w = array();
1657 $i = 0;
1658 $forced_color = '';
1659 foreach ($way as $cat) { // Loop on each successive categories to reach the target of current category
1660 $i++;
1661
1662 if (empty($nocolor)) {
1663 $forced_color = 'colortoreplace';
1664 if ($i == count($way)) { // Last category in hierarchy
1665 // Check contrast with background and correct text color
1666 $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.
1667 if ($cat->color && colorIsLight($cat->color)) {
1668 $forced_color = 'categtextblack';
1669 }
1670 }
1671 }
1672
1673 if ($url == '') {
1674 if (($i < count($way) && empty($notrunc)) && $i > 1) {
1675 $link = '';
1676 $linkend = '';
1677 } else {
1678 $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.((int) $cat->id).'&type='.urlencode($cat->type).'" class="'.(($i < count($way) && empty($notrunc)) ? 'small ' : '').$forced_color.'">';
1679 $linkend = '</a>';
1680 }
1681 $s = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '');
1682 $s .= (($i < count($way) && empty($notrunc)) ? ($i == 1 ? dol_trunc($cat->label, 3) : '') : $cat->label);
1683 $s .= $linkend;
1684 $w[] = $s;
1685 } elseif ($url == 'none') {
1686 if (($i < count($way) && empty($notrunc)) && $i > 1) {
1687 $link = '';
1688 $linkend = '';
1689 } else {
1690 $link = '<span class="valignmiddle '.($i < count($way) ? 'small ' : '').$forced_color.'">';
1691 $linkend = '</span>';
1692 }
1693 $s = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '');
1694 $s .= (($i < count($way) && empty($notrunc)) ? ($i == 1 ? dol_trunc($cat->label, 3) : '') : $cat->label);
1695 $s .= $linkend;
1696 $w[] = $s;
1697 } else {
1698 $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>';
1699 }
1700 }
1701 $newcategwithpath = preg_replace('/colortoreplace/', $forced_color, implode('<span class="inline-block valignmiddle paddingleft paddingright small '.$forced_color.'">'.$sep.'</span>', $w));
1702
1703 $ways[] = $newcategwithpath;
1704 }
1705
1706 return $ways;
1707 }
1708
1709
1710 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1717 public function get_meres()
1718 {
1719 // phpcs:enable
1720 $parents = array();
1721
1722 $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie";
1723 $sql .= " WHERE rowid = ".((int) $this->id);
1724
1725 $res = $this->db->query($sql);
1726
1727 if ($res) {
1728 while ($rec = $this->db->fetch_array($res)) {
1729 if ($rec['fk_parent'] > 0) {
1730 $cat = new Categorie($this->db);
1731 $cat->fetch($rec['fk_parent']);
1732 $parents[] = $cat;
1733 }
1734 }
1735 return $parents;
1736 } else {
1737 dol_print_error($this->db);
1738 return -1;
1739 }
1740 }
1741
1742 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1749 public function get_all_ways()
1750 {
1751 // phpcs:enable
1752 $ways = array();
1753
1754 $parents = $this->get_meres();
1755 if (is_array($parents)) {
1756 foreach ($parents as $parent) {
1757 $all_ways = $parent->get_all_ways(); // recursivity. TODO Add a protection for infinite loop
1758 foreach ($all_ways as $way) {
1759 $w = $way;
1760 $w[] = $this;
1761 $ways[] = $w;
1762 }
1763 }
1764 }
1765
1766 if (count($ways) == 0) {
1767 $ways[0][0] = $this;
1768 }
1769
1770 return $ways;
1771 }
1772
1783 public function containing($id, $type, $mode = 'object')
1784 {
1785 $cats = array();
1786
1787 if (is_numeric($type)) {
1788 $type = array_search($type, $this->MAP_ID);
1789 }
1790
1791 if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this after migration of llx_category_bankline into llx_categorie_bankline
1792 // Load bank categories
1793 $sql = "SELECT c.label, c.rowid";
1794 $sql .= " FROM ".MAIN_DB_PREFIX."category_bankline as a, ".MAIN_DB_PREFIX."categorie as c";
1795 $sql .= " WHERE a.lineid=".((int) $id)." AND a.fk_categ = c.rowid";
1796 $sql .= " AND c.entity IN (".getEntity('category').")";
1797 $sql .= " ORDER BY c.label";
1798
1799 $res = $this->db->query($sql);
1800 if ($res) {
1801 while ($obj = $this->db->fetch_object($res)) {
1802 if ($mode == 'id') {
1803 $cats[] = $obj->rowid;
1804 } elseif ($mode == 'label') {
1805 $cats[] = $obj->label;
1806 } else {
1807 $cat = new Categorie($this->db);
1808 $cat->id = $obj->rowid;
1809 $cat->label = $obj->label;
1810 $cats[] = $cat;
1811 }
1812 }
1813 } else {
1814 dol_print_error($this->db);
1815 return -1;
1816 }
1817 } else {
1818 $sql = "SELECT ct.fk_categorie, c.label, c.rowid";
1819 $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";
1820 $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".(int) $id;
1821 // This seems useless because the table already contains id of category of 1 unique type. So commented.
1822 // So now it works also with external added categories.
1823 //$sql .= " AND c.type = ".((int) $this->MAP_ID[$type]);
1824 $sql .= " AND c.entity IN (".getEntity('category').")";
1825
1826 $res = $this->db->query($sql);
1827 if ($res) {
1828 while ($obj = $this->db->fetch_object($res)) {
1829 if ($mode == 'id') {
1830 $cats[] = $obj->rowid;
1831 } elseif ($mode == 'label') {
1832 $cats[] = $obj->label;
1833 } else {
1834 $cat = new Categorie($this->db);
1835 $cat->fetch($obj->fk_categorie);
1836 $cats[] = $cat;
1837 }
1838 }
1839 } else {
1840 dol_print_error($this->db);
1841 return -1;
1842 }
1843 }
1844
1845 return $cats;
1846 }
1847
1859 public function rechercher($id, $nom, $type, $exact = false, $case = false)
1860 {
1861 // Deprecation warning
1862 if (is_numeric($type)) {
1863 dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING);
1864 }
1865
1866 $cats = array();
1867
1868 // For backward compatibility
1869 if (is_numeric($type)) {
1870 // We want to reverse lookup
1871 $map_type = array_flip($this->MAP_ID);
1872 $type = $map_type[$type];
1873 dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING);
1874 }
1875
1876 // Generation requete recherche
1877 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1878 $sql .= " WHERE type = ".((int) $this->MAP_ID[$type]);
1879 $sql .= " AND entity IN (".getEntity('category').")";
1880 if ($nom) {
1881 if (!$exact) {
1882 $nom = '%'.$this->db->escape(str_replace('*', '%', $nom)).'%';
1883 }
1884 if (!$case) {
1885 $sql .= " AND label LIKE '".$this->db->escape($nom)."'";
1886 } else {
1887 $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
1888 }
1889 }
1890 if ($id) {
1891 $sql .= " AND rowid = ".((int) $id);
1892 }
1893
1894 $res = $this->db->query($sql);
1895 if ($res) {
1896 while ($rec = $this->db->fetch_array($res)) {
1897 $cat = new Categorie($this->db);
1898 $cat->fetch($rec['rowid']);
1899 $cats[] = $cat;
1900 }
1901
1902 return $cats;
1903 } else {
1904 $this->error = $this->db->error().' sql='.$sql;
1905 return -1;
1906 }
1907 }
1908
1915 public function isAnyPhotoAvailable($sdir)
1916 {
1917 include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1918 include_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php';
1919
1920 $sdir .= '/' . get_exdir($this->id, 2, 0, 0, $this, 'category') . $this->id . "/photos/";
1921
1922 $dir_osencoded = dol_osencode($sdir);
1923 if (file_exists($dir_osencoded)) {
1924 $handle = opendir($dir_osencoded);
1925 if (is_resource($handle)) {
1926 while (($file = readdir($handle)) !== false) {
1927 if (!utf8_check($file)) {
1928 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // To be sure data is stored in UTF8 in memory
1929 }
1930 if (dol_is_file($sdir . $file) && image_format_supported($file) >= 0) {
1931 return true;
1932 }
1933 }
1934 }
1935 }
1936 return false;
1937 }
1938
1945 public function getTooltipContentArray($params)
1946 {
1947 global $langs;
1948
1949 $langs->load('categories');
1950
1951 $datas = [];
1952
1953 $datas['label'] = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
1954
1955 return $datas;
1956 }
1957
1971 public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $moreparam = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = 0)
1972 {
1973 global $conf, $langs, $hookmanager;
1974
1975 if (!empty($conf->dol_no_mouse_hover)) {
1976 $notooltip = 1; // Force disable tooltips
1977 }
1978
1979 $result = '';
1980 $params = [
1981 'id' => $this->id,
1982 'objecttype' => $this->element,
1983 'option' => $option,
1984 ];
1985 $classfortooltip = 'classfortooltip';
1986 $dataparams = '';
1987 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1988 $classfortooltip = 'classforajaxtooltip';
1989 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1990 $label = '';
1991 } else {
1992 $label = implode($this->getTooltipContentArray($params));
1993 }
1994
1995 $url = DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : ''));
1996
1997 if ($option !== 'nolink') {
1998 // Add param to save lastsearch_values or not
1999 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2000 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2001 $add_save_lastsearch_values = 1;
2002 }
2003 if (/* $url && */ $add_save_lastsearch_values) {
2004 $url .= '&save_lastsearch_values=1';
2005 }
2006 }
2007
2008 // Check contrast with background and correct text color
2009 $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.
2010 if ($this->color) {
2011 if (colorIsLight($this->color)) { // If color is light, we force color to dark
2012 $forced_color = 'categtextblack';
2013 }
2014 }
2015
2016 $linkclose = '';
2017 if (empty($notooltip)) {
2018 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2019 $label = $langs->trans("ShowCategory");
2020 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2021 }
2022 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2023 $linkclose .= $dataparams.' class="'.$classfortooltip.' '.$forced_color.($morecss ? ' '.$morecss : '').'"';
2024 } else {
2025 $linkclose = ' class="'.$forced_color.($morecss ? ' '.$morecss : '').'"';
2026 }
2027
2028 if ($option == 'nolink' /* || empty($url) */) {
2029 $linkstart = '<span';
2030 } else {
2031 $linkstart = '<a href="'.$url.'"';
2032 }
2033 $linkstart .= $linkclose.'>';
2034 if ($option == 'nolink' /* || empty($url) */) {
2035 $linkend = '</span>';
2036 } else {
2037 $linkend = '</a>';
2038 }
2039
2040 $result .= $linkstart;
2041
2042 if ($withpicto) {
2043 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2044 }
2045
2046 if ($withpicto != 2) {
2047 $result .= dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength);
2048 }
2049
2050 $result .= $linkend;
2051
2052 global $action;
2053 $hookmanager->initHooks(array($this->element . 'dao'));
2054 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2055 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2056 if ($reshook > 0) {
2057 $result = $hookmanager->resPrint;
2058 } else {
2059 $result .= $hookmanager->resPrint;
2060 }
2061 return $result;
2062 }
2063
2064
2065 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2073 public function add_photo($sdir, $file)
2074 {
2075 // phpcs:enable
2076 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2077
2078 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
2079 $dir .= "photos/";
2080
2081 if (!file_exists($dir)) {
2082 dol_mkdir($dir);
2083 }
2084
2085 if (file_exists($dir)) {
2086 if (is_array($file['name'])) {
2087 $nbfile = count($file['name']);
2088 for ($i = 0; $i < $nbfile; $i++) {
2089 $originImage = $dir.$file['name'][$i];
2090
2091 // Cree fichier en taille origine
2092 dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
2093
2094 if (file_exists($originImage)) {
2095 // Create thumbs
2096 $this->addThumbs($originImage);
2097 }
2098 }
2099 } else {
2100 $originImage = $dir.$file['name'];
2101
2102 // Cree fichier en taille origine
2103 dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
2104
2105 if (file_exists($originImage)) {
2106 // Create thumbs
2107 $this->addThumbs($originImage);
2108 }
2109 }
2110 }
2111 }
2112
2113 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2121 public function liste_photos($dir, $nbmax = 0)
2122 {
2123 // phpcs:enable
2124 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2125
2126 $nbphoto = 0;
2127 $tabobj = array();
2128
2129 $dirthumb = $dir.'thumbs/';
2130
2131 if (file_exists($dir)) {
2132 $handle = opendir($dir);
2133 if (is_resource($handle)) {
2134 while (($file = readdir($handle)) !== false) {
2135 if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) {
2136 $nbphoto++;
2137 $photo = $file;
2138
2139 // On determine nom du fichier vignette
2140 $photo_vignette = '';
2141 $regs = array();
2142 if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) {
2143 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
2144 }
2145
2146 // Object
2147 $obj = array();
2148 $obj['photo'] = $photo;
2149 if ($photo_vignette && is_file($dirthumb.$photo_vignette)) {
2150 $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
2151 } else {
2152 $obj['photo_vignette'] = "";
2153 }
2154
2155 $tabobj[$nbphoto - 1] = $obj;
2156
2157 // On continue ou on arrete de boucler
2158 if ($nbmax && $nbphoto >= $nbmax) {
2159 break;
2160 }
2161 }
2162 }
2163
2164 closedir($handle);
2165 }
2166 }
2167
2168 return $tabobj;
2169 }
2170
2171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2178 public function delete_photo($file)
2179 {
2180 // phpcs:enable
2181 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2182
2183 $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
2184 $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
2185 $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
2186
2187 // On efface l'image d'origine
2188 dol_delete_file($file, 0); // do not use disableglob, ecmfiles will not be deleted
2189
2190 // Si elle existe, on efface la vignette
2191 $regs = array();
2192 if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs)) {
2193 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
2194 if (file_exists($dirthumb.$photo_vignette)) {
2195 dol_delete_file($dirthumb.$photo_vignette, 1);
2196 }
2197 }
2198 }
2199
2200 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2207 public function get_image_size($file)
2208 {
2209 // phpcs:enable
2210 $infoImg = getimagesize($file); // Recuperation des infos de l'image
2211 $this->imgWidth = $infoImg[0]; // Largeur de l'image
2212 $this->imgHeight = $infoImg[1]; // Hauteur de l'image
2213 }
2214
2223 public function setMultiLangs(User $user, $notrigger = 0)
2224 {
2225 global $langs;
2226
2227 $langs_available = $langs->get_available_languages();
2228 $current_lang = $langs->getDefaultLang();
2229
2230 foreach ($langs_available as $key => $value) {
2231 $sql = "SELECT rowid";
2232 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
2233 $sql .= " WHERE fk_category=".((int) $this->id);
2234 $sql .= " AND lang = '".$this->db->escape($key)."'";
2235
2236 $result = $this->db->query($sql);
2237
2238 if ($key == $current_lang) {
2239 $sql2 = '';
2240 if ($this->db->num_rows($result)) { // if there is already a description line for this language
2241 $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
2242 $sql2 .= " SET label = '".$this->db->escape($this->label)."',";
2243 $sql2 .= " description = '".$this->db->escape($this->description)."'";
2244 $sql2 .= " WHERE fk_category = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
2245 } else { // if no line in database
2246 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
2247 $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->label)."'";
2248 $sql2 .= ", '".$this->db->escape($this->description)."')";
2249 }
2250 dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
2251 if (!$this->db->query($sql2)) {
2252 $this->error = $this->db->lasterror();
2253 return -1;
2254 }
2255 $this->multilangs[$key]["label"] = $this->label;
2256 $this->multilangs[$key]["description"] = $this->description;
2257 } elseif (isset($this->multilangs[$key])) { // if there is already a description line for this language
2258 if ($this->db->num_rows($result)) {
2259 $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
2260 $sql2 .= " SET label='".$this->db->escape($this->multilangs[$key]["label"])."',";
2261 $sql2 .= " description='".$this->db->escape($this->multilangs[$key]["description"])."'";
2262 $sql2 .= " WHERE fk_category=".((int) $this->id)." AND lang='".$this->db->escape($key)."'";
2263 } else { // if no line in database
2264 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
2265 $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->multilangs[$key]["label"])."'";
2266 $sql2 .= ",'".$this->db->escape($this->multilangs[$key]["description"])."')";
2267 }
2268
2269 // We do not save if main fields are empty
2270 if ($this->multilangs[$key]["label"] || $this->multilangs[$key]["description"]) {
2271 dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
2272 }
2273 if (!$this->db->query($sql2)) {
2274 $this->error = $this->db->lasterror();
2275 return -1;
2276 }
2277 }
2278 }
2279
2280 // Call trigger
2281 if (!$notrigger) {
2282 $result = $this->call_trigger('CATEGORY_SET_MULTILANGS', $user);
2283 if ($result < 0) {
2284 $this->error = $this->db->lasterror();
2285 return -1;
2286 }
2287 }
2288 // End call triggers
2289
2290 return 1;
2291 }
2292
2302 public function delMultiLangs($langtodelete, $user, $notrigger = 0)
2303 {
2304 $sql = "DELETE FROM ".$this->db->prefix()."categorie_lang";
2305 $sql .= " WHERE fk_category = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
2306
2307 dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
2308 $result = $this->db->query($sql);
2309 if ($result) {
2310 if (empty($notrigger)) {
2311 // Call trigger
2312 $result = $this->call_trigger('CATEGORY_DEL_MULTILANGS', $user);
2313 if ($result < 0) {
2314 $this->error = $this->db->lasterror();
2315 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2316 return -1;
2317 }
2318 // End call triggers
2319 }
2320 return 1;
2321 } else {
2322 $this->error = $this->db->lasterror();
2323 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2324 return -1;
2325 }
2326 }
2327
2333 public function getMultiLangs()
2334 {
2335 global $langs;
2336
2337 $current_lang = (is_object($langs) ? $langs->getDefaultLang() : ''); // $langs may be null when called from a page with NOREQUIRETRAN
2338
2339 $sql = "SELECT lang, label, description";
2340 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
2341 $sql .= " WHERE fk_category=".((int) $this->id);
2342
2343 $result = $this->db->query($sql);
2344 if ($result) {
2345 while ($obj = $this->db->fetch_object($result)) {
2346 //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
2347 if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
2348 $this->label = $obj->label;
2349 $this->description = $obj->description;
2350 }
2351 $this->multilangs[$obj->lang]["label"] = $obj->label;
2352 $this->multilangs[$obj->lang]["description"] = $obj->description;
2353 }
2354 return 1;
2355 } else {
2356 $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
2357 return -1;
2358 }
2359 }
2360
2367 public function getLibStatut($mode)
2368 {
2369 return '';
2370 }
2371
2372
2380 public function initAsSpecimen()
2381 {
2382 dol_syslog(get_class($this)."::initAsSpecimen");
2383
2384 // Initialise parameters
2385 $this->id = 0;
2386 $this->fk_parent = 0;
2387 $this->label = 'SPECIMEN';
2388 $this->specimen = 1;
2389 $this->description = 'This is a description';
2390 $this->socid = 1;
2391 $this->type = self::TYPE_PRODUCT;
2392
2393 return 1;
2394 }
2395
2404 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2405 {
2406 $tables = array(
2407 'categorie_societe'
2408 );
2409
2410 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables, 1);
2411 }
2412
2421 public static function getFilterJoinQuery($type, $rowIdName)
2422 {
2423 if ($type == 'bank_account') {
2424 $type = 'account';
2425 }
2426
2427 return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type;
2428 }
2429
2439 public static function getFilterSelectQuery($type, $rowIdName, $searchList)
2440 {
2441 if ($type == 'bank_account') {
2442 $type = 'account';
2443 }
2444 if ($type == 'customer') {
2445 $type = 'societe';
2446 }
2447 if ($type == 'supplier') {
2448 $type = 'fournisseur';
2449 }
2450
2451 if (empty($searchList) && !is_array($searchList)) {
2452 return "";
2453 }
2454
2455 $searchCategorySqlList = array();
2456 foreach ($searchList as $searchCategory) {
2457 if (intval($searchCategory) == -2) {
2458 $searchCategorySqlList[] = " cp.fk_categorie IS NULL";
2459 } elseif (intval($searchCategory) > 0) {
2460 $searchCategorySqlList[] = " ".$rowIdName." IN (SELECT fk_".$type." FROM ".MAIN_DB_PREFIX."categorie_".$type." WHERE fk_categorie = ".((int) $searchCategory).")";
2461 }
2462 }
2463
2464 if (!empty($searchCategorySqlList)) {
2465 return " AND (".implode(' AND ', $searchCategorySqlList).")";
2466 } else {
2467 return "";
2468 }
2469 }
2470
2476 public function countNbOfCategories()
2477 {
2478 dol_syslog(get_class($this)."::count_all_categories", LOG_DEBUG);
2479 $sql = "SELECT COUNT(rowid) FROM ".MAIN_DB_PREFIX."categorie";
2480 $sql .= " WHERE entity IN (".getEntity('category').")";
2481
2482 $res = $this->db->query($sql);
2483 if ($res) {
2484 $obj = $this->db->fetch_object($res);
2485 return $obj->count;
2486 } else {
2487 dol_print_error($this->db);
2488 return -1;
2489 }
2490 }
2491}
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
print $object position
Definition edit.php:206
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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, $notrigger=0)
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.
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)
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',....
print_all_ways($sep='auto', $url='', $nocolor=0, $addpicto=0, $notrunc=0)
Returns the path of the category, with the names of the categories separated by $sep (" >> " by defau...
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.
delMultiLangs($langtodelete, $user, $notrigger=0)
Delete a language for this category.
add_type($obj, $type='', $notrigger=0)
Link an object to the category.
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.
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.
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_now($mode='gmt')
Return date for now.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
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...
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
colorIsLight($stringcolor)
Return true if the color is light.
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.
isModEnabled($module)
Is Dolibarr module enabled.
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.