categorie.class.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104
  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 Charlie Benke <charlie@patas-monkey.com>
  13. * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
  14. * Copyright (C) 2023 Benjamin Falière <benjamin.faliere@altairis.fr>
  15. *
  16. * This program is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 3 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  28. */
  29. /**
  30. * \file htdocs/categories/class/categorie.class.php
  31. * \ingroup categorie
  32. * \brief File of class to manage categories
  33. */
  34. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/knowledgemanagement/class/knowledgerecord.class.php';
  40. /**
  41. * Class to manage categories
  42. */
  43. class Categorie extends CommonObject
  44. {
  45. // Categories types (we use string because we want to accept any modules/types in a future)
  46. const TYPE_PRODUCT = 'product';
  47. const TYPE_SUPPLIER = 'supplier';
  48. const TYPE_CUSTOMER = 'customer';
  49. const TYPE_MEMBER = 'member';
  50. const TYPE_CONTACT = 'contact';
  51. const TYPE_USER = 'user';
  52. const TYPE_PROJECT = 'project';
  53. const TYPE_ACCOUNT = 'bank_account';
  54. const TYPE_BANK_LINE = 'bank_line';
  55. const TYPE_WAREHOUSE = 'warehouse';
  56. const TYPE_ACTIONCOMM = 'actioncomm';
  57. const TYPE_WEBSITE_PAGE = 'website_page';
  58. const TYPE_TICKET = 'ticket';
  59. const TYPE_KNOWLEDGEMANAGEMENT = 'knowledgemanagement';
  60. /**
  61. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  62. */
  63. public $picto = 'category';
  64. /**
  65. * @var array Table of mapping between type string and ID used for field 'type' in table llx_categories
  66. */
  67. protected $MAP_ID = array(
  68. 'product' => 0,
  69. 'supplier' => 1,
  70. 'customer' => 2,
  71. 'member' => 3,
  72. 'contact' => 4,
  73. 'bank_account' => 5,
  74. 'project' => 6,
  75. 'user' => 7,
  76. 'bank_line' => 8,
  77. 'warehouse' => 9,
  78. 'actioncomm' => 10,
  79. 'website_page' => 11,
  80. 'ticket' => 12,
  81. 'knowledgemanagement' => 13
  82. );
  83. /**
  84. * @var array Code mapping from ID
  85. *
  86. * @note This array should be removed in future, once previous constants are moved to the string value. Deprecated
  87. */
  88. public static $MAP_ID_TO_CODE = array(
  89. 0 => 'product',
  90. 1 => 'supplier',
  91. 2 => 'customer',
  92. 3 => 'member',
  93. 4 => 'contact',
  94. 5 => 'bank_account',
  95. 6 => 'project',
  96. 7 => 'user',
  97. 8 => 'bank_line',
  98. 9 => 'warehouse',
  99. 10 => 'actioncomm',
  100. 11 => 'website_page',
  101. 12 => 'ticket',
  102. 13 => 'knowledgemanagement'
  103. );
  104. /**
  105. * @var array Foreign keys mapping from type string when value does not match
  106. *
  107. * @todo Move to const array when PHP 5.6 will be our minimum target
  108. */
  109. public $MAP_CAT_FK = array(
  110. 'customer' => 'soc',
  111. 'supplier' => 'soc',
  112. 'contact' => 'socpeople',
  113. 'bank_account' => 'account',
  114. );
  115. /**
  116. * @var array Category tables mapping from type string (llx_categorie_...) when value does not match
  117. *
  118. * @note Move to const array when PHP 5.6 will be our minimum target
  119. */
  120. public $MAP_CAT_TABLE = array(
  121. 'customer' => 'societe',
  122. 'supplier' => 'fournisseur',
  123. 'bank_account'=> 'account',
  124. );
  125. /**
  126. * @var array Object class mapping from type string
  127. *
  128. * @note Move to const array when PHP 5.6 will be our minimum target
  129. */
  130. public $MAP_OBJ_CLASS = array(
  131. 'product' => 'Product',
  132. 'customer' => 'Societe',
  133. 'supplier' => 'Fournisseur',
  134. 'member' => 'Adherent',
  135. 'contact' => 'Contact',
  136. 'user' => 'User',
  137. 'account' => 'Account', // old for bank account
  138. 'bank_account' => 'Account',
  139. 'project' => 'Project',
  140. 'warehouse'=> 'Entrepot',
  141. 'actioncomm' => 'ActionComm',
  142. 'website_page' => 'WebsitePage',
  143. 'ticket' => 'Ticket',
  144. 'knowledgemanagement' => 'KnowledgeRecord'
  145. );
  146. /**
  147. * @var array Title Area mapping from type string
  148. *
  149. * @note Move to const array when PHP 5.6 will be our minimum target
  150. */
  151. public static $MAP_TYPE_TITLE_AREA = array(
  152. 'product' => 'ProductsCategoriesArea',
  153. 'customer' => 'CustomersCategoriesArea',
  154. 'supplier' => 'SuppliersCategoriesArea',
  155. 'member' => 'MembersCategoriesArea',
  156. 'contact' => 'ContactsCategoriesArea',
  157. 'user' => 'UsersCategoriesArea',
  158. 'account' => 'AccountsCategoriesArea', // old for bank account
  159. 'bank_account' => 'AccountsCategoriesArea',
  160. 'project' => 'ProjectsCategoriesArea',
  161. 'warehouse'=> 'StocksCategoriesArea',
  162. 'actioncomm' => 'ActioncommCategoriesArea',
  163. 'website_page' => 'WebsitePageCategoriesArea'
  164. );
  165. /**
  166. * @var array Object table mapping from type string (table llx_...) when value of key does not match table name.
  167. * This array may be completed by external modules with hook "constructCategory"
  168. */
  169. public $MAP_OBJ_TABLE = array(
  170. 'customer' => 'societe',
  171. 'supplier' => 'societe',
  172. 'member' => 'adherent',
  173. 'contact' => 'socpeople',
  174. 'account' => 'bank_account', // old for bank account
  175. 'project' => 'projet',
  176. 'warehouse'=> 'entrepot',
  177. 'knowledgemanagement' => 'knowledgemanagement_knowledgerecord'
  178. );
  179. /**
  180. * @var string ID to identify managed object
  181. */
  182. public $element = 'category';
  183. /**
  184. * @var string Name of table without prefix where object is stored
  185. */
  186. public $table_element = 'categorie';
  187. /**
  188. * @var int ID
  189. */
  190. public $fk_parent;
  191. /**
  192. * @var string Category label
  193. */
  194. public $label;
  195. /**
  196. * @var string description
  197. */
  198. public $description;
  199. /**
  200. * @var string Color
  201. */
  202. public $color;
  203. /**
  204. * @var int Visible
  205. */
  206. public $visible;
  207. /**
  208. * @var int Id of thirdparty when CATEGORY_ASSIGNED_TO_A_CUSTOMER is set
  209. */
  210. public $socid;
  211. /**
  212. * @var string Category type
  213. *
  214. * @see Categorie::TYPE_PRODUCT
  215. * @see Categorie::TYPE_SUPPLIER
  216. * @see Categorie::TYPE_CUSTOMER
  217. * @see Categorie::TYPE_MEMBER
  218. * @see Categorie::TYPE_CONTACT
  219. * @see Categorie::TYPE_USER
  220. * @see Categorie::TYPE_PROJECT
  221. * @see Categorie::TYPE_ACCOUNT
  222. * @see Categorie::TYPE_BANK_LINE
  223. * @see Categorie::TYPE_WAREHOUSE
  224. * @see Categorie::TYPE_ACTIONCOMM
  225. * @see Categorie::TYPE_WEBSITE_PAGE
  226. * @see Categorie::TYPE_TICKET
  227. */
  228. public $type;
  229. /**
  230. * @var array Categories table in memory
  231. */
  232. public $cats = array();
  233. /**
  234. * @var array Mother of table
  235. */
  236. public $motherof = array();
  237. /**
  238. * @var array Childs
  239. */
  240. public $childs = array();
  241. /**
  242. * @var array multilangs
  243. */
  244. public $multilangs;
  245. /**
  246. * @var int imgWidth
  247. */
  248. public $imgWidth;
  249. /**
  250. * @var int imgHeight
  251. */
  252. public $imgHeight;
  253. /**
  254. * Constructor
  255. *
  256. * @param DoliDB $db Database handler
  257. */
  258. public function __construct($db)
  259. {
  260. global $hookmanager;
  261. $this->db = $db;
  262. if (is_object($hookmanager)) {
  263. $hookmanager->initHooks(array('category'));
  264. $parameters = array();
  265. $reshook = $hookmanager->executeHooks('constructCategory', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  266. if ($reshook >= 0 && !empty($hookmanager->resArray)) {
  267. foreach ($hookmanager->resArray as $mapList) {
  268. $mapId = $mapList['id'];
  269. $mapCode = $mapList['code'];
  270. self::$MAP_ID_TO_CODE[$mapId] = $mapCode;
  271. $this->MAP_ID[$mapCode] = $mapId;
  272. $this->MAP_CAT_FK[$mapCode] = isset($mapList['cat_fk']) ? $mapList['cat_fk'] : null;
  273. $this->MAP_CAT_TABLE[$mapCode] = isset($mapList['cat_table']) ? $mapList['cat_table'] : null;
  274. $this->MAP_OBJ_CLASS[$mapCode] = $mapList['obj_class'];
  275. $this->MAP_OBJ_TABLE[$mapCode] = $mapList['obj_table'];
  276. }
  277. }
  278. }
  279. }
  280. /**
  281. * Get map list
  282. *
  283. * @return array
  284. */
  285. public function getMapList()
  286. {
  287. $mapList = array();
  288. foreach ($this->MAP_ID as $mapCode => $mapId) {
  289. $mapList[] = array(
  290. 'id' => $mapId,
  291. 'code' => $mapCode,
  292. 'cat_fk' => (empty($this->MAP_CAT_FK[$mapCode]) ? $mapCode : $this->MAP_CAT_FK[$mapCode]),
  293. 'cat_table' => (empty($this->MAP_CAT_TABLE[$mapCode]) ? $mapCode : $this->MAP_CAT_TABLE[$mapCode]),
  294. 'obj_class' => (empty($this->MAP_OBJ_CLASS[$mapCode]) ? $mapCode : $this->MAP_OBJ_CLASS[$mapCode]),
  295. 'obj_table' => (empty($this->MAP_OBJ_TABLE[$mapCode]) ? $mapCode : $this->MAP_OBJ_TABLE[$mapCode])
  296. );
  297. }
  298. return $mapList;
  299. }
  300. /**
  301. * Load category into memory from database
  302. *
  303. * @param int $id Id of category
  304. * @param string $label Label of category
  305. * @param string $type Type of category ('product', '...') or (0, 1, ...)
  306. * @param string $ref_ext External reference of object
  307. * @return int Return integer <0 if KO, >0 if OK
  308. */
  309. public function fetch($id, $label = '', $type = null, $ref_ext = '')
  310. {
  311. // Check parameters
  312. if (empty($id) && empty($label) && empty($ref_ext)) {
  313. $this->error = "No category to search for";
  314. return -1;
  315. }
  316. if (!is_null($type) && !is_numeric($type)) {
  317. $type = $this->MAP_ID[$type];
  318. }
  319. $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext";
  320. $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif";
  321. $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
  322. if ($id) {
  323. $sql .= " WHERE rowid = ".((int) $id);
  324. } elseif (!empty($ref_ext)) {
  325. $sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'";
  326. } else {
  327. $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")";
  328. if (!is_null($type)) {
  329. $sql .= " AND type = ".((int) $type);
  330. }
  331. }
  332. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  333. $resql = $this->db->query($sql);
  334. if ($resql) {
  335. if ($this->db->num_rows($resql) > 0) {
  336. $res = $this->db->fetch_array($resql);
  337. $this->id = $res['rowid'];
  338. //$this->ref = $res['rowid'];
  339. $this->fk_parent = (int) $res['fk_parent'];
  340. $this->label = $res['label'];
  341. $this->description = $res['description'];
  342. $this->color = $res['color'];
  343. $this->socid = (int) $res['fk_soc'];
  344. $this->visible = (int) $res['visible'];
  345. $this->type = (int) $res['type'];
  346. $this->ref_ext = $res['ref_ext'];
  347. $this->entity = (int) $res['entity'];
  348. $this->date_creation = $this->db->jdate($res['date_creation']);
  349. $this->date_modification = $this->db->jdate($res['tms']);
  350. $this->user_creation_id = (int) $res['fk_user_creat'];
  351. $this->user_modification_id = (int) $res['fk_user_modif'];
  352. // Retrieve all extrafield
  353. // fetch optionals attributes and labels
  354. $this->fetch_optionals();
  355. $this->db->free($resql);
  356. // multilangs
  357. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  358. $this->getMultiLangs();
  359. }
  360. return 1;
  361. } else {
  362. $this->error = "No category found";
  363. return 0;
  364. }
  365. } else {
  366. dol_print_error($this->db);
  367. $this->error = $this->db->lasterror;
  368. $this->errors[] = $this->db->lasterror;
  369. return -1;
  370. }
  371. }
  372. /**
  373. * Add category into database
  374. *
  375. * @param User $user Object user
  376. * @return int -1 : SQL error
  377. * -2 : new ID unknown
  378. * -3 : Invalid category
  379. * -4 : category already exists
  380. */
  381. public function create($user)
  382. {
  383. global $conf, $langs, $hookmanager;
  384. $langs->load('categories');
  385. $type = $this->type;
  386. if (!is_numeric($type)) {
  387. $type = $this->MAP_ID[$type];
  388. }
  389. $error = 0;
  390. dol_syslog(get_class($this).'::create', LOG_DEBUG);
  391. // Clean parameters
  392. $this->label = trim($this->label);
  393. $this->description = trim($this->description);
  394. $this->color = trim($this->color);
  395. $this->import_key = trim($this->import_key);
  396. $this->ref_ext = trim($this->ref_ext);
  397. if (empty($this->visible)) {
  398. $this->visible = 0;
  399. }
  400. $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
  401. if ($this->already_exists()) {
  402. $this->error = $langs->trans("ImpossibleAddCat", $this->label);
  403. $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
  404. dol_syslog($this->error, LOG_WARNING);
  405. return -4;
  406. }
  407. $this->db->begin();
  408. $now = dol_now();
  409. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie (";
  410. $sql .= "fk_parent,";
  411. $sql .= " label,";
  412. $sql .= " description,";
  413. $sql .= " color,";
  414. if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
  415. $sql .= "fk_soc,";
  416. }
  417. $sql .= " visible,";
  418. $sql .= " type,";
  419. $sql .= " import_key,";
  420. $sql .= " ref_ext,";
  421. $sql .= " entity,";
  422. $sql .= " date_creation,";
  423. $sql .= " fk_user_creat";
  424. $sql .= ") VALUES (";
  425. $sql .= (int) $this->fk_parent.",";
  426. $sql .= "'".$this->db->escape($this->label)."', ";
  427. $sql .= "'".$this->db->escape($this->description)."', ";
  428. $sql .= "'".$this->db->escape($this->color)."', ";
  429. if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
  430. $sql .= ($this->socid > 0 ? $this->socid : 'null').", ";
  431. }
  432. $sql .= "'".$this->db->escape($this->visible)."', ";
  433. $sql .= ((int) $type).", ";
  434. $sql .= (!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : 'null').", ";
  435. $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : 'null').", ";
  436. $sql .= (int) $conf->entity.", ";
  437. $sql .= "'".$this->db->idate($now)."', ";
  438. $sql .= (int) $user->id;
  439. $sql .= ")";
  440. $res = $this->db->query($sql);
  441. if ($res) {
  442. $id = $this->db->last_insert_id(MAIN_DB_PREFIX."categorie");
  443. if ($id > 0) {
  444. $this->id = $id;
  445. $action = 'create';
  446. // Actions on extra fields
  447. if (!$error) {
  448. $result = $this->insertExtraFields();
  449. if ($result < 0) {
  450. $error++;
  451. }
  452. }
  453. if (!$error) {
  454. // Call trigger
  455. $result = $this->call_trigger('CATEGORY_CREATE', $user);
  456. if ($result < 0) {
  457. $error++;
  458. }
  459. // End call triggers
  460. }
  461. if (!$error) {
  462. $this->db->commit();
  463. return $id;
  464. } else {
  465. $this->db->rollback();
  466. return -3;
  467. }
  468. } else {
  469. $this->db->rollback();
  470. return -2;
  471. }
  472. } else {
  473. $this->error = $this->db->error();
  474. $this->db->rollback();
  475. return -1;
  476. }
  477. }
  478. /**
  479. * Update category
  480. *
  481. * @param User $user Object user
  482. * @return int 1 : OK
  483. * -1 : SQL error
  484. * -2 : invalid category
  485. */
  486. public function update(User $user)
  487. {
  488. $error = 0;
  489. // Clean parameters
  490. $this->label = trim($this->label);
  491. $this->description = trim($this->description);
  492. $this->ref_ext = trim($this->ref_ext);
  493. $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
  494. $this->visible = ($this->visible != "" ? intval($this->visible) : 0);
  495. if ($this->already_exists()) {
  496. $this->error = $langs->trans("ImpossibleUpdateCat");
  497. $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
  498. return -1;
  499. }
  500. $this->db->begin();
  501. $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
  502. $sql .= " SET label = '".$this->db->escape($this->label)."',";
  503. $sql .= " description = '".$this->db->escape($this->description)."',";
  504. $sql .= " ref_ext = '".$this->db->escape($this->ref_ext)."',";
  505. $sql .= " color = '".$this->db->escape($this->color)."'";
  506. if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
  507. $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : 'null');
  508. }
  509. $sql .= ", visible = ".(int) $this->visible;
  510. $sql .= ", fk_parent = ".(int) $this->fk_parent;
  511. $sql .= ", fk_user_modif = ".(int) $user->id;
  512. $sql .= " WHERE rowid = ".((int) $this->id);
  513. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  514. if ($this->db->query($sql)) {
  515. $action = 'update';
  516. // Actions on extra fields
  517. if (!$error) {
  518. $result = $this->insertExtraFields();
  519. if ($result < 0) {
  520. $error++;
  521. }
  522. }
  523. if (!$error) {
  524. // Call trigger
  525. $result = $this->call_trigger('CATEGORY_MODIFY', $user);
  526. if ($result < 0) {
  527. $error++;
  528. }
  529. // End call triggers
  530. }
  531. if (!$error) {
  532. $this->db->commit();
  533. return 1;
  534. } else {
  535. $this->db->rollback();
  536. return -1;
  537. }
  538. } else {
  539. $this->db->rollback();
  540. dol_print_error($this->db);
  541. return -1;
  542. }
  543. }
  544. /**
  545. * Delete a category from database
  546. *
  547. * @param User $user Object user that ask to delete
  548. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  549. * @return int <0 KO >0 OK
  550. */
  551. public function delete($user, $notrigger = 0)
  552. {
  553. $error = 0;
  554. // Clean parameters
  555. $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
  556. dol_syslog(get_class($this)."::remove");
  557. $this->db->begin();
  558. if (!$error && !$notrigger) {
  559. // Call trigger
  560. $result = $this->call_trigger('CATEGORY_DELETE', $user);
  561. if ($result < 0) {
  562. $error++;
  563. }
  564. // End call triggers
  565. }
  566. /* FIX #1317 : Check for child category and move up 1 level*/
  567. if (!$error) {
  568. $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
  569. $sql .= " SET fk_parent = ".((int) $this->fk_parent);
  570. $sql .= " WHERE fk_parent = ".((int) $this->id);
  571. if (!$this->db->query($sql)) {
  572. $this->error = $this->db->lasterror();
  573. $error++;
  574. }
  575. }
  576. $arraydelete = array(
  577. 'categorie_account' => 'fk_categorie',
  578. 'categorie_actioncomm' => 'fk_categorie',
  579. 'categorie_contact' => 'fk_categorie',
  580. 'categorie_fournisseur' => 'fk_categorie',
  581. 'categorie_knowledgemanagement' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('knowledgemanagement')),
  582. 'categorie_member' => 'fk_categorie',
  583. 'categorie_user' => 'fk_categorie',
  584. 'categorie_product' => 'fk_categorie',
  585. 'categorie_project' => 'fk_categorie',
  586. 'categorie_societe' => 'fk_categorie',
  587. 'categorie_ticket' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('ticket')),
  588. 'categorie_warehouse' => 'fk_categorie',
  589. 'categorie_website_page' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('website')),
  590. 'bank_class' => 'fk_categ',
  591. 'categorie_lang' => 'fk_category',
  592. 'categorie' => 'rowid',
  593. );
  594. foreach ($arraydelete as $key => $value) {
  595. if (is_array($value)) {
  596. if (empty($value['enabled'])) {
  597. continue;
  598. }
  599. $value = $value['field'];
  600. }
  601. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$key;
  602. $sql .= " WHERE ".$value." = ".((int) $this->id);
  603. if (!$this->db->query($sql)) {
  604. $this->errors[] = $this->db->lasterror();
  605. dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR);
  606. $error++;
  607. }
  608. }
  609. // Removed extrafields
  610. if (!$error) {
  611. $result = $this->deleteExtraFields();
  612. if ($result < 0) {
  613. $error++;
  614. dol_syslog(get_class($this)."::delete erreur ".$this->error, LOG_ERR);
  615. }
  616. }
  617. if (!$error) {
  618. $this->db->commit();
  619. return 1;
  620. } else {
  621. $this->db->rollback();
  622. return -1;
  623. }
  624. }
  625. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  626. /**
  627. * Link an object to the category
  628. *
  629. * @param CommonObject $obj Object to link to category
  630. * @param string $type Type of category ('product', ...). Use '' to take $obj->element.
  631. * @return int 1 : OK, -1 : erreur SQL, -2 : id not defined, -3 : Already linked
  632. * @see del_type()
  633. */
  634. public function add_type($obj, $type = '')
  635. {
  636. // phpcs:enable
  637. global $user;
  638. $error = 0;
  639. if ($this->id == -1) {
  640. return -2;
  641. }
  642. if (empty($type)) {
  643. $type = $obj->element;
  644. }
  645. dol_syslog(get_class($this).'::add_type', LOG_DEBUG);
  646. $this->db->begin();
  647. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  648. $sql .= " (fk_categorie, fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]).")";
  649. $sql .= " VALUES (".((int) $this->id).", ".((int) $obj->id).")";
  650. if ($this->db->query($sql)) {
  651. if (getDolGlobalString('CATEGORIE_RECURSIV_ADD')) {
  652. $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie';
  653. $sql .= " WHERE rowid = ".((int) $this->id);
  654. dol_syslog(get_class($this)."::add_type", LOG_DEBUG);
  655. $resql = $this->db->query($sql);
  656. if ($resql) {
  657. if ($this->db->num_rows($resql) > 0) {
  658. $objparent = $this->db->fetch_object($resql);
  659. if (!empty($objparent->fk_parent)) {
  660. $cat = new Categorie($this->db);
  661. $cat->id = $objparent->fk_parent;
  662. if (!$cat->containsObject($type, $obj->id)) {
  663. $result = $cat->add_type($obj, $type);
  664. if ($result < 0) {
  665. $this->error = $cat->error;
  666. $error++;
  667. }
  668. }
  669. }
  670. }
  671. } else {
  672. $error++;
  673. $this->error = $this->db->lasterror();
  674. }
  675. if ($error) {
  676. $this->db->rollback();
  677. return -1;
  678. }
  679. }
  680. // Call trigger
  681. $this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
  682. $result = $this->call_trigger('CATEGORY_LINK', $user);
  683. if ($result < 0) {
  684. $error++;
  685. }
  686. // End call triggers
  687. if (!$error) {
  688. $this->db->commit();
  689. return 1;
  690. } else {
  691. $this->db->rollback();
  692. return -2;
  693. }
  694. } else {
  695. $this->db->rollback();
  696. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  697. $this->error = $this->db->lasterrno();
  698. return -3;
  699. } else {
  700. $this->error = $this->db->lasterror();
  701. }
  702. return -1;
  703. }
  704. }
  705. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  706. /**
  707. * Delete object from category
  708. *
  709. * @param CommonObject $obj Object
  710. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member')
  711. * @return int 1 if OK, -1 if KO
  712. * @see add_type()
  713. */
  714. public function del_type($obj, $type)
  715. {
  716. // phpcs:enable
  717. global $user;
  718. $error = 0;
  719. // For backward compatibility
  720. if ($type == 'societe') {
  721. $type = 'customer';
  722. dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
  723. } elseif ($type == 'fournisseur') {
  724. $type = 'supplier';
  725. dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
  726. }
  727. $this->db->begin();
  728. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  729. $sql .= " WHERE fk_categorie = ".((int) $this->id);
  730. $sql .= " AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $obj->id);
  731. dol_syslog(get_class($this).'::del_type', LOG_DEBUG);
  732. if ($this->db->query($sql)) {
  733. // Call trigger
  734. $this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
  735. $result = $this->call_trigger('CATEGORY_UNLINK', $user);
  736. if ($result < 0) {
  737. $error++;
  738. }
  739. // End call triggers
  740. if (!$error) {
  741. $this->db->commit();
  742. return 1;
  743. } else {
  744. $this->db->rollback();
  745. return -2;
  746. }
  747. } else {
  748. $this->db->rollback();
  749. $this->error = $this->db->lasterror();
  750. return -1;
  751. }
  752. }
  753. /**
  754. * Return list of fetched instance of elements having this category
  755. *
  756. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member', 'knowledge_management', ...)
  757. * @param int $onlyids Return only ids of objects (consume less memory)
  758. * @param int $limit Limit
  759. * @param int $offset Offset
  760. * @param string $sortfield Sort fields
  761. * @param string $sortorder Sort order ('ASC' or 'DESC');
  762. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customsql'=>...)
  763. * @param string $filtermode Filter mode (AND or OR)
  764. * @return array|int -1 if KO, array of instance of object if OK
  765. * @see containsObject()
  766. */
  767. public function getObjectsInCateg($type, $onlyids = 0, $limit = 0, $offset = 0, $sortfield = '', $sortorder = 'ASC', $filter = array(), $filtermode = 'AND')
  768. {
  769. global $user;
  770. $objs = array();
  771. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  772. $obj = new $classnameforobj($this->db);
  773. $sql = "SELECT c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]);
  774. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as c";
  775. $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." as o";
  776. $sql .= " WHERE o.entity IN (".getEntity($obj->element).")";
  777. $sql .= " AND c.fk_categorie = ".((int) $this->id);
  778. // Compatibility with actioncomm table which has id instead of rowid
  779. if ((array_key_exists($type, $this->MAP_OBJ_TABLE) && $this->MAP_OBJ_TABLE[$type] == "actioncomm") || $type == "actioncomm") {
  780. $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.id";
  781. } else {
  782. $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.rowid";
  783. }
  784. // Protection for external users
  785. if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) {
  786. $sql .= " AND o.rowid = ".((int) $user->socid);
  787. }
  788. // Manage filter
  789. $sqlwhere = array();
  790. if (count($filter) > 0) {
  791. foreach ($filter as $key => $value) {
  792. if ($key == 'o.rowid') {
  793. $sqlwhere[] = $key." = ".((int) $value);
  794. } elseif ($key == 'customsql') {
  795. $sqlwhere[] = $value;
  796. }
  797. }
  798. }
  799. if (count($sqlwhere) > 0) {
  800. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  801. }
  802. $sql .= $this->db->order($sortfield, $sortorder);
  803. if ($limit > 0 || $offset > 0) {
  804. $sql .= $this->db->plimit($limit + 1, $offset);
  805. }
  806. dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
  807. $resql = $this->db->query($sql);
  808. if ($resql) {
  809. while ($rec = $this->db->fetch_array($resql)) {
  810. if ($onlyids) {
  811. $objs[] = $rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])];
  812. } else {
  813. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  814. $obj = new $classnameforobj($this->db);
  815. $obj->fetch($rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]);
  816. $objs[] = $obj;
  817. }
  818. }
  819. return $objs;
  820. } else {
  821. $this->error = $this->db->error().' sql='.$sql;
  822. return -1;
  823. }
  824. }
  825. /**
  826. * Check for the presence of an object in a category
  827. *
  828. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member')
  829. * @param int $object_id Id of the object to search
  830. * @return int Number of occurrences
  831. * @see getObjectsInCateg()
  832. */
  833. public function containsObject($type, $object_id)
  834. {
  835. $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  836. $sql .= " WHERE fk_categorie = ".((int) $this->id)." AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $object_id);
  837. dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
  838. $resql = $this->db->query($sql);
  839. if ($resql) {
  840. return $this->db->fetch_object($resql)->nb;
  841. } else {
  842. $this->error = $this->db->error();
  843. return -1;
  844. }
  845. }
  846. /**
  847. * List categories of an element id
  848. *
  849. * @param int $id Id of element
  850. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact')
  851. * @param string $sortfield Sort field
  852. * @param string $sortorder Sort order
  853. * @param int $limit Limit for list
  854. * @param int $page Page number
  855. * @return array|int Array of categories, 0 if no cat, -1 on error
  856. */
  857. public function getListForItem($id, $type = 'customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  858. {
  859. $categories = array();
  860. $type = sanitizeVal($type, 'aZ09');
  861. $sub_type = $type;
  862. $subcol_name = "fk_".$type;
  863. if ($type == "customer") {
  864. $sub_type = "societe";
  865. $subcol_name = "fk_soc";
  866. }
  867. if ($type == "supplier") {
  868. $sub_type = "fournisseur";
  869. $subcol_name = "fk_soc";
  870. }
  871. if ($type == "contact") {
  872. $subcol_name = "fk_socpeople";
  873. }
  874. $idoftype = array_search($type, self::$MAP_ID_TO_CODE);
  875. $sql = "SELECT s.rowid";
  876. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s, ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub";
  877. $sql .= ' WHERE s.entity IN ('.getEntity('category').')';
  878. $sql .= ' AND s.type='.((int) $idoftype);
  879. $sql .= ' AND s.rowid = sub.fk_categorie';
  880. $sql .= " AND sub.".$subcol_name." = ".((int) $id);
  881. $sql .= $this->db->order($sortfield, $sortorder);
  882. $offset = 0;
  883. $nbtotalofrecords = '';
  884. if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
  885. $result = $this->db->query($sql);
  886. $nbtotalofrecords = $this->db->num_rows($result);
  887. if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
  888. $page = 0;
  889. $offset = 0;
  890. }
  891. }
  892. if ($limit) {
  893. if ($page < 0) {
  894. $page = 0;
  895. }
  896. $offset = $limit * $page;
  897. $sql .= $this->db->plimit($limit + 1, $offset);
  898. }
  899. $result = $this->db->query($sql);
  900. if ($result) {
  901. $i = 0;
  902. $num = $this->db->num_rows($result);
  903. $min = min($num, ($limit <= 0 ? $num : $limit));
  904. while ($i < $min) {
  905. $obj = $this->db->fetch_object($result);
  906. $category_static = new Categorie($this->db);
  907. if ($category_static->fetch($obj->rowid)) {
  908. $categories[$i]['id'] = $category_static->id;
  909. $categories[$i]['fk_parent'] = $category_static->fk_parent;
  910. $categories[$i]['label'] = $category_static->label;
  911. $categories[$i]['description'] = $category_static->description;
  912. $categories[$i]['color'] = $category_static->color;
  913. $categories[$i]['socid'] = $category_static->socid;
  914. $categories[$i]['ref_ext'] = $category_static->ref_ext;
  915. $categories[$i]['visible'] = $category_static->visible;
  916. $categories[$i]['type'] = $category_static->type;
  917. $categories[$i]['entity'] = $category_static->entity;
  918. $categories[$i]['array_options'] = $category_static->array_options;
  919. // multilangs
  920. if (getDolGlobalInt('MAIN_MULTILANGS') && isset($category_static->multilangs)) {
  921. $categories[$i]['multilangs'] = $category_static->multilangs;
  922. }
  923. }
  924. $i++;
  925. }
  926. } else {
  927. $this->error = $this->db->lasterror();
  928. return -1;
  929. }
  930. if (!count($categories)) {
  931. return 0;
  932. }
  933. return $categories;
  934. }
  935. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  936. /**
  937. * Return direct childs id of a category into an array
  938. *
  939. * @return array|int <0 KO, array ok
  940. */
  941. public function get_filles()
  942. {
  943. // phpcs:enable
  944. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  945. $sql .= " WHERE fk_parent = ".((int) $this->id);
  946. $sql .= " AND entity IN (".getEntity('category').")";
  947. $res = $this->db->query($sql);
  948. if ($res) {
  949. $cats = array();
  950. while ($rec = $this->db->fetch_array($res)) {
  951. $cat = new Categorie($this->db);
  952. $cat->fetch($rec['rowid']);
  953. $cats[] = $cat;
  954. }
  955. return $cats;
  956. } else {
  957. dol_print_error($this->db);
  958. return -1;
  959. }
  960. }
  961. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  962. /**
  963. * Load the array this->motherof that is array(id_son=>id_parent, ...)
  964. *
  965. * @return int Return integer <0 if KO, >0 if OK
  966. */
  967. protected function load_motherof()
  968. {
  969. // phpcs:enable
  970. $this->motherof = array();
  971. // Load array[child]=parent
  972. $sql = "SELECT fk_parent as id_parent, rowid as id_son";
  973. $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
  974. $sql .= " WHERE fk_parent != 0";
  975. $sql .= " AND entity IN (".getEntity('category').")";
  976. dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
  977. $resql = $this->db->query($sql);
  978. if ($resql) {
  979. while ($obj = $this->db->fetch_object($resql)) {
  980. $this->motherof[$obj->id_son] = $obj->id_parent;
  981. }
  982. return 1;
  983. } else {
  984. dol_print_error($this->db);
  985. return -1;
  986. }
  987. }
  988. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  989. /**
  990. * Rebuilding the category tree as an array
  991. * Return an array of table('id','id_mere',...) trie selon arbre et avec:
  992. * id = id de la categorie
  993. * id_mere = id de la categorie mere
  994. * id_children = tableau des id enfant
  995. * label = nom de la categorie
  996. * fulllabel = nom avec chemin complet de la categorie
  997. * fullpath = chemin complet compose des id
  998. *
  999. * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member', ...)
  1000. * @param int|string|array $markafterid Keep only or removed all categories including the leaf $markafterid in category tree (exclude) or Keep only of category is inside the leaf starting with this id.
  1001. * $markafterid can be an :
  1002. * - int (id of category)
  1003. * - string (categories ids separated by comma)
  1004. * - array (list of categories ids)
  1005. * @param int $include [=0] Removed or 1=Keep only
  1006. * @return array|int Array of categories. this->cats and this->motherof are set, -1 on error
  1007. */
  1008. public function get_full_arbo($type, $markafterid = 0, $include = 0)
  1009. {
  1010. // phpcs:enable
  1011. global $langs;
  1012. if (!is_numeric($type)) {
  1013. $type = $this->MAP_ID[$type];
  1014. }
  1015. if (is_null($type)) {
  1016. $this->error = 'BadValueForParameterType';
  1017. return -1;
  1018. }
  1019. if (is_string($markafterid)) {
  1020. $markafterid = explode(',', $markafterid);
  1021. } elseif (is_numeric($markafterid)) {
  1022. if ($markafterid > 0) {
  1023. $markafterid = array($markafterid);
  1024. } else {
  1025. $markafterid = array();
  1026. }
  1027. } elseif (!is_array($markafterid)) {
  1028. $markafterid = array();
  1029. }
  1030. $this->cats = array();
  1031. // Init this->motherof that is array(id_son=>id_parent, ...)
  1032. $this->load_motherof();
  1033. $current_lang = $langs->getDefaultLang();
  1034. // Init $this->cats array
  1035. $sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates
  1036. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1037. $sql .= ", t.label as label_trans, t.description as description_trans";
  1038. }
  1039. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
  1040. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1041. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'";
  1042. }
  1043. $sql .= " WHERE c.entity IN (".getEntity('category').")";
  1044. $sql .= " AND c.type = ".(int) $type;
  1045. dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
  1046. $resql = $this->db->query($sql);
  1047. if ($resql) {
  1048. $i = 0;
  1049. while ($obj = $this->db->fetch_object($resql)) {
  1050. $this->cats[$obj->rowid]['rowid'] = $obj->rowid;
  1051. $this->cats[$obj->rowid]['id'] = $obj->rowid;
  1052. $this->cats[$obj->rowid]['fk_parent'] = $obj->fk_parent;
  1053. $this->cats[$obj->rowid]['label'] = !empty($obj->label_trans) ? $obj->label_trans : $obj->label;
  1054. $this->cats[$obj->rowid]['description'] = !empty($obj->description_trans) ? $obj->description_trans : $obj->description;
  1055. $this->cats[$obj->rowid]['color'] = $obj->color;
  1056. $this->cats[$obj->rowid]['visible'] = $obj->visible;
  1057. $this->cats[$obj->rowid]['ref_ext'] = $obj->ref_ext;
  1058. $this->cats[$obj->rowid]['picto'] = 'category';
  1059. $i++;
  1060. }
  1061. } else {
  1062. dol_print_error($this->db);
  1063. return -1;
  1064. }
  1065. // We add the fullpath property to each elements of first level (no parent exists)
  1066. dol_syslog(get_class($this)."::get_full_arbo call to buildPathFromId", LOG_DEBUG);
  1067. foreach ($this->cats as $key => $val) {
  1068. //print 'key='.$key.'<br>'."\n";
  1069. $this->buildPathFromId($key, 0); // Process a branch from the root category key (this category has no parent)
  1070. }
  1071. // Include or exclude leaf including $markafterid from tree
  1072. if (count($markafterid) > 0) {
  1073. $keyfiltercatid = '('.implode('|', $markafterid).')';
  1074. //print "Look to discard category ".$markafterid."\n";
  1075. $keyfilter1 = '^'.$keyfiltercatid.'$';
  1076. $keyfilter2 = '_'.$keyfiltercatid.'$';
  1077. $keyfilter3 = '^'.$keyfiltercatid.'_';
  1078. $keyfilter4 = '_'.$keyfiltercatid.'_';
  1079. foreach ($this->cats as $key => $val) {
  1080. $test = (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
  1081. || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath']));
  1082. if (($test && !$include) || (!$test && $include)) {
  1083. unset($this->cats[$key]);
  1084. }
  1085. }
  1086. }
  1087. dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
  1088. $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
  1089. return $this->cats;
  1090. }
  1091. /**
  1092. * For category id_categ and its childs available in this->cats, define property fullpath and fulllabel.
  1093. * It is called by get_full_arbo()
  1094. * This function is a memory scan only from $this->cats and $this->motherof, no database access must be done here.
  1095. *
  1096. * @param int $id_categ id_categ entry to update
  1097. * @param int $protection Deep counter to avoid infinite loop
  1098. * @return int Return integer <0 if KO, >0 if OK
  1099. * @see get_full_arbo()
  1100. */
  1101. private function buildPathFromId($id_categ, $protection = 1000)
  1102. {
  1103. //dol_syslog(get_class($this)."::buildPathFromId id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
  1104. if (!empty($this->cats[$id_categ]['fullpath'])) {
  1105. // Already defined
  1106. dol_syslog(get_class($this)."::buildPathFromId fullpath and fulllabel already defined", LOG_WARNING);
  1107. return -1;
  1108. }
  1109. // First build full array $motherof
  1110. //$this->load_motherof(); // Disabled because already done by caller of buildPathFromId
  1111. // $this->cats[$id_categ] is supposed to be already an array. We just want to complete it with property fullpath and fulllabel
  1112. // Define fullpath and fulllabel
  1113. $this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
  1114. $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
  1115. $i = 0;
  1116. $cursor_categ = $id_categ;
  1117. //print 'Work for id_categ='.$id_categ.'<br>'."\n";
  1118. while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) {
  1119. //print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
  1120. $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
  1121. $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'];
  1122. //print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
  1123. $i++;
  1124. $cursor_categ = $this->motherof[$cursor_categ];
  1125. }
  1126. //print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'<br>'."\n";
  1127. // We count number of _ to have level
  1128. $nbunderscore = substr_count($this->cats[$id_categ]['fullpath'], '_');
  1129. $this->cats[$id_categ]['level'] = ($nbunderscore ? $nbunderscore : null);
  1130. return 1;
  1131. }
  1132. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1133. /**
  1134. * Returns all categories
  1135. *
  1136. * @param int $type Type of category (0, 1, ...)
  1137. * @param boolean $parent Just parent categories if true
  1138. * @return array|int Table of Object Category, -1 on error
  1139. */
  1140. public function get_all_categories($type = null, $parent = false)
  1141. {
  1142. // phpcs:enable
  1143. if (!is_numeric($type)) {
  1144. $type = $this->MAP_ID[$type];
  1145. }
  1146. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  1147. $sql .= " WHERE entity IN (".getEntity('category').")";
  1148. if (!is_null($type)) {
  1149. $sql .= " AND type = ".(int) $type;
  1150. }
  1151. if ($parent) {
  1152. $sql .= " AND fk_parent = 0";
  1153. }
  1154. $res = $this->db->query($sql);
  1155. if ($res) {
  1156. $cats = array();
  1157. while ($rec = $this->db->fetch_array($res)) {
  1158. $cat = new Categorie($this->db);
  1159. $cat->fetch($rec['rowid']);
  1160. $cats[$rec['rowid']] = $cat;
  1161. }
  1162. return $cats;
  1163. } else {
  1164. dol_print_error($this->db);
  1165. return -1;
  1166. }
  1167. }
  1168. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1169. /**
  1170. * Returns the top level categories (which are not child)
  1171. *
  1172. * @param int $type Type of category (0, 1, ...)
  1173. * @return array
  1174. */
  1175. public function get_main_categories($type = null)
  1176. {
  1177. // phpcs:enable
  1178. return $this->get_all_categories($type, true);
  1179. }
  1180. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1181. /**
  1182. * Check if no category with same label already exists for this cat's parent or root and for this cat's type
  1183. *
  1184. * @return integer 1 if already exist, 0 otherwise, -1 if error
  1185. */
  1186. public function already_exists()
  1187. {
  1188. // phpcs:enable
  1189. $type = $this->type;
  1190. if (!is_numeric($type)) {
  1191. $type = $this->MAP_ID[$type];
  1192. }
  1193. /* We have to select any rowid from llx_categorie which category's mother and label
  1194. * are equals to those of the calling category
  1195. */
  1196. $sql = "SELECT c.rowid";
  1197. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c ";
  1198. $sql .= " WHERE c.entity IN (".getEntity('category').")";
  1199. $sql .= " AND c.type = ".((int) $type);
  1200. $sql .= " AND c.fk_parent = ".((int) $this->fk_parent);
  1201. $sql .= " AND c.label = '".$this->db->escape($this->label)."'";
  1202. dol_syslog(get_class($this)."::already_exists", LOG_DEBUG);
  1203. $resql = $this->db->query($sql);
  1204. if ($resql) {
  1205. if ($this->db->num_rows($resql) > 0) { // Checking for empty resql
  1206. $obj = $this->db->fetch_array($resql);
  1207. /* If object called create, obj cannot have is id.
  1208. * If object called update, he mustn't have the same label as an other category for this mother.
  1209. * So if the result have the same id, update is not for label, and if result have an other one,
  1210. * update may be for label.
  1211. */
  1212. if ($obj[0] > 0 && $obj[0] != $this->id) {
  1213. dol_syslog(get_class($this)."::already_exists category with name=".$this->label." and parent ".$this->fk_parent." exists: rowid=".$obj[0]." current_id=".$this->id, LOG_DEBUG);
  1214. return 1;
  1215. }
  1216. }
  1217. 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);
  1218. return 0;
  1219. } else {
  1220. $this->error = $this->db->error();
  1221. return -1;
  1222. }
  1223. }
  1224. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1225. /**
  1226. * Returns the path of the category, with the names of the categories
  1227. * separated by $sep (" >> " by default)
  1228. *
  1229. * @param string $sep Separator
  1230. * @param string $url Url ('', 'none' or 'urltouse')
  1231. * @param int $nocolor 0
  1232. * @param string $addpicto Add picto into link
  1233. * @return array
  1234. */
  1235. public function print_all_ways($sep = '&gt;&gt;', $url = '', $nocolor = 0, $addpicto = 0)
  1236. {
  1237. // phpcs:enable
  1238. $ways = array();
  1239. $allways = $this->get_all_ways(); // Load array of categories
  1240. foreach ($allways as $way) {
  1241. $w = array();
  1242. $i = 0;
  1243. $forced_color = '';
  1244. foreach ($way as $cat) {
  1245. $i++;
  1246. if (empty($nocolor)) {
  1247. $forced_color = 'colortoreplace';
  1248. if ($i == count($way)) { // Last category in hierarchy
  1249. // Check contrast with background and correct text color
  1250. $forced_color = 'categtextwhite';
  1251. if ($cat->color) {
  1252. if (colorIsLight($cat->color)) {
  1253. $forced_color = 'categtextblack';
  1254. }
  1255. }
  1256. }
  1257. }
  1258. if ($url == '') {
  1259. $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$cat->id.'&type='.$cat->type.'" class="'.$forced_color.'">';
  1260. $linkend = '</a>';
  1261. $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
  1262. } elseif ($url == 'none') {
  1263. $link = '<span class="'.$forced_color.'">';
  1264. $linkend = '</span>';
  1265. $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
  1266. } else {
  1267. $w[] = '<a class="'.$forced_color.'" href="'.DOL_URL_ROOT.'/'.$url.'?catid='.$cat->id.'">'.($addpicto ? img_object('', 'category') : '').$cat->label.'</a>';
  1268. }
  1269. }
  1270. $newcategwithpath = preg_replace('/colortoreplace/', $forced_color, implode('<span class="inline-block valignmiddle paddingleft paddingright '.$forced_color.'">'.$sep.'</span>', $w));
  1271. $ways[] = $newcategwithpath;
  1272. }
  1273. return $ways;
  1274. }
  1275. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1276. /**
  1277. * Returns an array containing the list of parent categories
  1278. *
  1279. * @return int|array <0 KO, array OK
  1280. */
  1281. public function get_meres()
  1282. {
  1283. // phpcs:enable
  1284. $parents = array();
  1285. $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie";
  1286. $sql .= " WHERE rowid = ".((int) $this->id);
  1287. $res = $this->db->query($sql);
  1288. if ($res) {
  1289. while ($rec = $this->db->fetch_array($res)) {
  1290. if ($rec['fk_parent'] > 0) {
  1291. $cat = new Categorie($this->db);
  1292. $cat->fetch($rec['fk_parent']);
  1293. $parents[] = $cat;
  1294. }
  1295. }
  1296. return $parents;
  1297. } else {
  1298. dol_print_error($this->db);
  1299. return -1;
  1300. }
  1301. }
  1302. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1303. /**
  1304. * Returns in a table all possible paths to get to the category
  1305. * starting with the major categories represented by Tables of categories
  1306. *
  1307. * @return array
  1308. */
  1309. public function get_all_ways()
  1310. {
  1311. // phpcs:enable
  1312. $ways = array();
  1313. $parents = $this->get_meres();
  1314. if (is_array($parents)) {
  1315. foreach ($parents as $parent) {
  1316. $allways = $parent->get_all_ways();
  1317. foreach ($allways as $way) {
  1318. $w = $way;
  1319. $w[] = $this;
  1320. $ways[] = $w;
  1321. }
  1322. }
  1323. }
  1324. if (count($ways) == 0) {
  1325. $ways[0][0] = $this;
  1326. }
  1327. return $ways;
  1328. }
  1329. /**
  1330. * Return list of categories (object instances or labels) linked to element of id $id and type $type
  1331. * Should be named getListOfCategForObject
  1332. *
  1333. * @param int $id Id of element
  1334. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') or (0, 1, 2, ...)
  1335. * @param string $mode 'id'=Get array of category ids, 'object'=Get array of fetched category instances, 'label'=Get array of category
  1336. * labels, 'id'= Get array of category IDs
  1337. * @return Categorie[]|int Array of category objects or < 0 if KO
  1338. */
  1339. public function containing($id, $type, $mode = 'object')
  1340. {
  1341. $cats = array();
  1342. if (is_numeric($type)) {
  1343. $type = Categorie::$MAP_ID_TO_CODE[$type];
  1344. }
  1345. if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this with standard category code after migration of llx_bank_categ into llx_categorie
  1346. // Load bank categories
  1347. $sql = "SELECT c.label, c.rowid";
  1348. $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c";
  1349. $sql .= " WHERE a.lineid=".((int) $id)." AND a.fk_categ = c.rowid";
  1350. $sql .= " AND c.entity IN (".getEntity('category').")";
  1351. $sql .= " ORDER BY c.label";
  1352. $res = $this->db->query($sql);
  1353. if ($res) {
  1354. while ($obj = $this->db->fetch_object($res)) {
  1355. if ($mode == 'id') {
  1356. $cats[] = $obj->rowid;
  1357. } elseif ($mode == 'label') {
  1358. $cats[] = $obj->label;
  1359. } else {
  1360. $cat = new Categorie($this->db);
  1361. $cat->id = $obj->rowid;
  1362. $cat->label = $obj->label;
  1363. $cats[] = $cat;
  1364. }
  1365. }
  1366. } else {
  1367. dol_print_error($this->db);
  1368. return -1;
  1369. }
  1370. } else {
  1371. $sql = "SELECT ct.fk_categorie, c.label, c.rowid";
  1372. $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";
  1373. $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".(int) $id;
  1374. // This seems useless because the table already contains id of category of 1 unique type. So commented.
  1375. // So now it works also with external added categories.
  1376. //$sql .= " AND c.type = ".((int) $this->MAP_ID[$type]);
  1377. $sql .= " AND c.entity IN (".getEntity('category').")";
  1378. $res = $this->db->query($sql);
  1379. if ($res) {
  1380. while ($obj = $this->db->fetch_object($res)) {
  1381. if ($mode == 'id') {
  1382. $cats[] = $obj->rowid;
  1383. } elseif ($mode == 'label') {
  1384. $cats[] = $obj->label;
  1385. } else {
  1386. $cat = new Categorie($this->db);
  1387. $cat->fetch($obj->fk_categorie);
  1388. $cats[] = $cat;
  1389. }
  1390. }
  1391. } else {
  1392. dol_print_error($this->db);
  1393. return -1;
  1394. }
  1395. }
  1396. return $cats;
  1397. }
  1398. /**
  1399. * Returns categories whose id or name match
  1400. * add wildcards in the name unless $exact = true
  1401. *
  1402. * @param int $id Id
  1403. * @param string $nom Name
  1404. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  1405. * @param boolean $exact Exact string search (true/false)
  1406. * @param boolean $case Case sensitive (true/false)
  1407. * @return Categorie[]|int Array of Categorie, -1 if error
  1408. */
  1409. public function rechercher($id, $nom, $type, $exact = false, $case = false)
  1410. {
  1411. // Deprecation warning
  1412. if (is_numeric($type)) {
  1413. dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING);
  1414. }
  1415. $cats = array();
  1416. // For backward compatibility
  1417. if (is_numeric($type)) {
  1418. // We want to reverse lookup
  1419. $map_type = array_flip($this->MAP_ID);
  1420. $type = $map_type[$type];
  1421. dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING);
  1422. }
  1423. // Generation requete recherche
  1424. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  1425. $sql .= " WHERE type = ".((int) $this->MAP_ID[$type]);
  1426. $sql .= " AND entity IN (".getEntity('category').")";
  1427. if ($nom) {
  1428. if (!$exact) {
  1429. $nom = '%'.$this->db->escape(str_replace('*', '%', $nom)).'%';
  1430. }
  1431. if (!$case) {
  1432. $sql .= " AND label LIKE '".$this->db->escape($nom)."'";
  1433. } else {
  1434. $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
  1435. }
  1436. }
  1437. if ($id) {
  1438. $sql .= " AND rowid = ".((int) $id);
  1439. }
  1440. $res = $this->db->query($sql);
  1441. if ($res) {
  1442. while ($rec = $this->db->fetch_array($res)) {
  1443. $cat = new Categorie($this->db);
  1444. $cat->fetch($rec['rowid']);
  1445. $cats[] = $cat;
  1446. }
  1447. return $cats;
  1448. } else {
  1449. $this->error = $this->db->error().' sql='.$sql;
  1450. return -1;
  1451. }
  1452. }
  1453. /**
  1454. * getTooltipContentArray
  1455. * @param array $params params to construct tooltip data
  1456. * @since v18
  1457. * @return array
  1458. */
  1459. public function getTooltipContentArray($params)
  1460. {
  1461. global $langs;
  1462. $langs->load('categories');
  1463. $datas = [];
  1464. $datas['label'] = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
  1465. return $datas;
  1466. }
  1467. /**
  1468. * Return name and link of category (with picto)
  1469. * Use ->id, ->ref, ->label, ->color
  1470. *
  1471. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1472. * @param string $option Sur quoi pointe le lien ('', 'xyz')
  1473. * @param int $maxlength Max length of text
  1474. * @param string $moreparam More param on URL link
  1475. * @return string Chaine avec URL
  1476. */
  1477. public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $moreparam = '')
  1478. {
  1479. global $hookmanager;
  1480. $result = '';
  1481. $params = [
  1482. 'id' => $this->id,
  1483. 'objecttype' => $this->element,
  1484. 'option' => $option,
  1485. ];
  1486. $classfortooltip = 'classfortooltip';
  1487. $dataparams = '';
  1488. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  1489. $classfortooltip = 'classforajaxtooltip';
  1490. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  1491. $label = '';
  1492. } else {
  1493. $label = implode($this->getTooltipContentArray($params));
  1494. }
  1495. // Check contrast with background and correct text color
  1496. $forced_color = 'categtextwhite';
  1497. if ($this->color) {
  1498. if (colorIsLight($this->color)) {
  1499. $forced_color = 'categtextblack';
  1500. }
  1501. }
  1502. $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : ''));
  1503. $link .= '"'.$dataparams;
  1504. $link .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  1505. $link .= ' class="'.$classfortooltip.' '.$forced_color.'">';
  1506. $linkend = '</a>';
  1507. $picto = 'category';
  1508. if ($withpicto) {
  1509. $result .= ($link.img_object($label, $picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
  1510. }
  1511. if ($withpicto && $withpicto != 2) {
  1512. $result .= ' ';
  1513. }
  1514. if ($withpicto != 2) {
  1515. $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend;
  1516. }
  1517. global $action;
  1518. $hookmanager->initHooks(array($this->element . 'dao'));
  1519. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1520. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1521. if ($reshook > 0) {
  1522. $result = $hookmanager->resPrint;
  1523. } else {
  1524. $result .= $hookmanager->resPrint;
  1525. }
  1526. return $result;
  1527. }
  1528. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1529. /**
  1530. * Deplace fichier uploade sous le nom $file dans le repertoire sdir
  1531. *
  1532. * @param string $sdir Final destination directory
  1533. * @param array $file Uploaded file name
  1534. * @return void
  1535. */
  1536. public function add_photo($sdir, $file)
  1537. {
  1538. // phpcs:enable
  1539. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1540. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
  1541. $dir .= "photos/";
  1542. if (!file_exists($dir)) {
  1543. dol_mkdir($dir);
  1544. }
  1545. if (file_exists($dir)) {
  1546. if (is_array($file['name']) && count($file['name']) > 0) {
  1547. $nbfile = count($file['name']);
  1548. for ($i = 0; $i <= $nbfile; $i++) {
  1549. $originImage = $dir.$file['name'][$i];
  1550. // Cree fichier en taille origine
  1551. dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
  1552. if (file_exists($originImage)) {
  1553. // Create thumbs
  1554. $this->addThumbs($originImage);
  1555. }
  1556. }
  1557. } else {
  1558. $originImage = $dir.$file['name'];
  1559. // Cree fichier en taille origine
  1560. dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
  1561. if (file_exists($originImage)) {
  1562. // Create thumbs
  1563. $this->addThumbs($originImage);
  1564. }
  1565. }
  1566. }
  1567. }
  1568. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1569. /**
  1570. * Return tableau de toutes les photos de la categorie
  1571. *
  1572. * @param string $dir Repertoire a scanner
  1573. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  1574. * @return array Tableau de photos
  1575. */
  1576. public function liste_photos($dir, $nbmax = 0)
  1577. {
  1578. // phpcs:enable
  1579. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1580. $nbphoto = 0;
  1581. $tabobj = array();
  1582. $dirthumb = $dir.'thumbs/';
  1583. if (file_exists($dir)) {
  1584. $handle = opendir($dir);
  1585. if (is_resource($handle)) {
  1586. while (($file = readdir($handle)) !== false) {
  1587. if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) {
  1588. $nbphoto++;
  1589. $photo = $file;
  1590. // On determine nom du fichier vignette
  1591. $photo_vignette = '';
  1592. $regs = array();
  1593. if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) {
  1594. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
  1595. }
  1596. // Objet
  1597. $obj = array();
  1598. $obj['photo'] = $photo;
  1599. if ($photo_vignette && is_file($dirthumb.$photo_vignette)) {
  1600. $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
  1601. } else {
  1602. $obj['photo_vignette'] = "";
  1603. }
  1604. $tabobj[$nbphoto - 1] = $obj;
  1605. // On continue ou on arrete de boucler
  1606. if ($nbmax && $nbphoto >= $nbmax) {
  1607. break;
  1608. }
  1609. }
  1610. }
  1611. closedir($handle);
  1612. }
  1613. }
  1614. return $tabobj;
  1615. }
  1616. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1617. /**
  1618. * Efface la photo de la categorie et sa vignette
  1619. *
  1620. * @param string $file Path to file
  1621. * @return void
  1622. */
  1623. public function delete_photo($file)
  1624. {
  1625. // phpcs:enable
  1626. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1627. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  1628. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
  1629. $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
  1630. // On efface l'image d'origine
  1631. dol_delete_file($file, 1);
  1632. // Si elle existe, on efface la vignette
  1633. $regs = array();
  1634. if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs)) {
  1635. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
  1636. if (file_exists($dirthumb.$photo_vignette)) {
  1637. dol_delete_file($dirthumb.$photo_vignette, 1);
  1638. }
  1639. }
  1640. }
  1641. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1642. /**
  1643. * Load size of image file
  1644. *
  1645. * @param string $file Path to file
  1646. * @return void
  1647. */
  1648. public function get_image_size($file)
  1649. {
  1650. // phpcs:enable
  1651. $infoImg = getimagesize($file); // Recuperation des infos de l'image
  1652. $this->imgWidth = $infoImg[0]; // Largeur de l'image
  1653. $this->imgHeight = $infoImg[1]; // Hauteur de l'image
  1654. }
  1655. /**
  1656. * Update ou cree les traductions des infos produits
  1657. *
  1658. * @param User $user Object user
  1659. *
  1660. * @return int Return integer <0 if KO, >0 if OK
  1661. */
  1662. public function setMultiLangs($user)
  1663. {
  1664. global $langs;
  1665. $langs_available = $langs->get_available_languages();
  1666. $current_lang = $langs->getDefaultLang();
  1667. foreach ($langs_available as $key => $value) {
  1668. $sql = "SELECT rowid";
  1669. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
  1670. $sql .= " WHERE fk_category=".((int) $this->id);
  1671. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1672. $result = $this->db->query($sql);
  1673. if ($key == $current_lang) {
  1674. if ($this->db->num_rows($result)) { // si aucune ligne dans la base
  1675. $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
  1676. $sql2 .= " SET label = '".$this->db->escape($this->label)."',";
  1677. $sql2 .= " description = '".$this->db->escape($this->description)."'";
  1678. $sql2 .= " WHERE fk_category = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1679. } else {
  1680. $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
  1681. $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->label)."'";
  1682. $sql2 .= ", '".$this->db->escape($this->multilangs[$key]["description"])."')";
  1683. }
  1684. dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
  1685. if (!$this->db->query($sql2)) {
  1686. $this->error = $this->db->lasterror();
  1687. return -1;
  1688. }
  1689. } elseif (isset($this->multilangs[$key])) {
  1690. if ($this->db->num_rows($result)) { // si aucune ligne dans la base
  1691. $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
  1692. $sql2 .= " SET label='".$this->db->escape($this->multilangs[$key]["label"])."',";
  1693. $sql2 .= " description='".$this->db->escape($this->multilangs[$key]["description"])."'";
  1694. $sql2 .= " WHERE fk_category=".((int) $this->id)." AND lang='".$this->db->escape($key)."'";
  1695. } else {
  1696. $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
  1697. $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->multilangs[$key]["label"])."'";
  1698. $sql2 .= ",'".$this->db->escape($this->multilangs[$key]["description"])."')";
  1699. }
  1700. // on ne sauvegarde pas des champs vides
  1701. if ($this->multilangs[$key]["label"] || $this->multilangs[$key]["description"] || $this->multilangs[$key]["note"]) {
  1702. dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
  1703. }
  1704. if (!$this->db->query($sql2)) {
  1705. $this->error = $this->db->lasterror();
  1706. return -1;
  1707. }
  1708. }
  1709. }
  1710. // Call trigger
  1711. $result = $this->call_trigger('CATEGORY_SET_MULTILANGS', $user);
  1712. if ($result < 0) {
  1713. $this->error = $this->db->lasterror();
  1714. return -1;
  1715. }
  1716. // End call triggers
  1717. return 1;
  1718. }
  1719. /**
  1720. * Load array this->multilangs
  1721. *
  1722. * @return int Return integer <0 if KO, >0 if OK
  1723. */
  1724. public function getMultiLangs()
  1725. {
  1726. global $langs;
  1727. $current_lang = $langs->getDefaultLang();
  1728. $sql = "SELECT lang, label, description";
  1729. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
  1730. $sql .= " WHERE fk_category=".((int) $this->id);
  1731. $result = $this->db->query($sql);
  1732. if ($result) {
  1733. while ($obj = $this->db->fetch_object($result)) {
  1734. //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
  1735. if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
  1736. $this->label = $obj->label;
  1737. $this->description = $obj->description;
  1738. }
  1739. $this->multilangs[$obj->lang]["label"] = $obj->label;
  1740. $this->multilangs[$obj->lang]["description"] = $obj->description;
  1741. }
  1742. return 1;
  1743. } else {
  1744. $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
  1745. return -1;
  1746. }
  1747. }
  1748. /**
  1749. * Return label of contact status
  1750. *
  1751. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
  1752. * @return string Label of contact status
  1753. */
  1754. public function getLibStatut($mode)
  1755. {
  1756. return '';
  1757. }
  1758. /**
  1759. * Initialise an instance with random values.
  1760. * Used to build previews or test instances.
  1761. * id must be 0 if object instance is a specimen.
  1762. *
  1763. * @return void
  1764. */
  1765. public function initAsSpecimen()
  1766. {
  1767. dol_syslog(get_class($this)."::initAsSpecimen");
  1768. // Initialise parametres
  1769. $this->id = 0;
  1770. $this->fk_parent = 0;
  1771. $this->label = 'SPECIMEN';
  1772. $this->specimen = 1;
  1773. $this->description = 'This is a description';
  1774. $this->socid = 1;
  1775. $this->type = self::TYPE_PRODUCT;
  1776. }
  1777. /**
  1778. * Function used to replace a thirdparty id with another one.
  1779. *
  1780. * @param DoliDB $dbs Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
  1781. * @param int $origin_id Old thirdparty id
  1782. * @param int $dest_id New thirdparty id
  1783. * @return bool
  1784. */
  1785. public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
  1786. {
  1787. $tables = array(
  1788. 'categorie_societe'
  1789. );
  1790. return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables, 1);
  1791. }
  1792. /**
  1793. * Return the addtional SQL JOIN query for filtering a list by a category
  1794. *
  1795. * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE)
  1796. * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid")
  1797. * @return string A additional SQL JOIN query
  1798. * @deprecated search on some categories must be done using a WHERE EXISTS or NOT EXISTS and not a LEFT JOIN. @TODO Replace with getWhereQuery($type, $searchCategoryList)
  1799. */
  1800. public static function getFilterJoinQuery($type, $rowIdName)
  1801. {
  1802. if ($type == 'bank_account') {
  1803. $type = 'account';
  1804. }
  1805. return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type;
  1806. }
  1807. /**
  1808. * Return the addtional SQL SELECT query for filtering a list by a category
  1809. *
  1810. * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE)
  1811. * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid")
  1812. * @param Array $searchList A list with the selected categories
  1813. * @return string A additional SQL SELECT query
  1814. * @deprecated search on some categories must be done using a WHERE EXISTS or NOT EXISTS and not a LEFT JOIN
  1815. */
  1816. public static function getFilterSelectQuery($type, $rowIdName, $searchList)
  1817. {
  1818. if ($type == 'bank_account') {
  1819. $type = 'account';
  1820. }
  1821. if ($type == 'customer') {
  1822. $type = 'societe';
  1823. }
  1824. if ($type == 'supplier') {
  1825. $type = 'fournisseur';
  1826. }
  1827. if (empty($searchList) && !is_array($searchList)) {
  1828. return "";
  1829. }
  1830. $searchCategorySqlList = array();
  1831. foreach ($searchList as $searchCategory) {
  1832. if (intval($searchCategory) == -2) {
  1833. $searchCategorySqlList[] = " cp.fk_categorie IS NULL";
  1834. } elseif (intval($searchCategory) > 0) {
  1835. $searchCategorySqlList[] = " ".$rowIdName." IN (SELECT fk_".$type." FROM ".MAIN_DB_PREFIX."categorie_".$type." WHERE fk_categorie = ".((int) $searchCategory).")";
  1836. }
  1837. }
  1838. if (!empty($searchCategorySqlList)) {
  1839. return " AND (".implode(' AND ', $searchCategorySqlList).")";
  1840. } else {
  1841. return "";
  1842. }
  1843. }
  1844. /**
  1845. * Count all categories
  1846. *
  1847. * @return int Number of categories, -1 on error
  1848. */
  1849. public function countNbOfCategories()
  1850. {
  1851. dol_syslog(get_class($this)."::count_all_categories", LOG_DEBUG);
  1852. $sql = "SELECT COUNT(rowid) FROM ".MAIN_DB_PREFIX."categorie";
  1853. $sql .= " WHERE entity IN (".getEntity('category').")";
  1854. $res = $this->db->query($sql);
  1855. if ($res) {
  1856. $obj = $this->db->fetch_object($res);
  1857. return $obj->count;
  1858. } else {
  1859. dol_print_error($this->db);
  1860. return -1;
  1861. }
  1862. }
  1863. }