categorie.class.php 63 KB

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