categorie.class.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  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 <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. global $conf, $langs, $hookmanager;
  489. $error = 0;
  490. // Clean parameters
  491. $this->label = trim($this->label);
  492. $this->description = trim($this->description);
  493. $this->ref_ext = trim($this->ref_ext);
  494. $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
  495. $this->visible = ($this->visible != "" ? intval($this->visible) : 0);
  496. if ($this->already_exists()) {
  497. $this->error = $langs->trans("ImpossibleUpdateCat");
  498. $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
  499. return -1;
  500. }
  501. $this->db->begin();
  502. $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
  503. $sql .= " SET label = '".$this->db->escape($this->label)."',";
  504. $sql .= " description = '".$this->db->escape($this->description)."',";
  505. $sql .= " ref_ext = '".$this->db->escape($this->ref_ext)."',";
  506. $sql .= " color = '".$this->db->escape($this->color)."'";
  507. if (getDolGlobalString('CATEGORY_ASSIGNED_TO_A_CUSTOMER')) {
  508. $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : 'null');
  509. }
  510. $sql .= ", visible = ".(int) $this->visible;
  511. $sql .= ", fk_parent = ".(int) $this->fk_parent;
  512. $sql .= ", fk_user_modif = ".(int) $user->id;
  513. $sql .= " WHERE rowid = ".((int) $this->id);
  514. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  515. if ($this->db->query($sql)) {
  516. $action = 'update';
  517. // Actions on extra fields
  518. if (!$error) {
  519. $result = $this->insertExtraFields();
  520. if ($result < 0) {
  521. $error++;
  522. }
  523. }
  524. if (!$error) {
  525. // Call trigger
  526. $result = $this->call_trigger('CATEGORY_MODIFY', $user);
  527. if ($result < 0) {
  528. $error++;
  529. }
  530. // End call triggers
  531. }
  532. if (!$error) {
  533. $this->db->commit();
  534. return 1;
  535. } else {
  536. $this->db->rollback();
  537. return -1;
  538. }
  539. } else {
  540. $this->db->rollback();
  541. dol_print_error($this->db);
  542. return -1;
  543. }
  544. }
  545. /**
  546. * Delete a category from database
  547. *
  548. * @param User $user Object user that ask to delete
  549. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  550. * @return int <0 KO >0 OK
  551. */
  552. public function delete($user, $notrigger = 0)
  553. {
  554. global $conf, $langs;
  555. $error = 0;
  556. // Clean parameters
  557. $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
  558. dol_syslog(get_class($this)."::remove");
  559. $this->db->begin();
  560. if (!$error && !$notrigger) {
  561. // Call trigger
  562. $result = $this->call_trigger('CATEGORY_DELETE', $user);
  563. if ($result < 0) {
  564. $error++;
  565. }
  566. // End call triggers
  567. }
  568. /* FIX #1317 : Check for child category and move up 1 level*/
  569. if (!$error) {
  570. $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
  571. $sql .= " SET fk_parent = ".((int) $this->fk_parent);
  572. $sql .= " WHERE fk_parent = ".((int) $this->id);
  573. if (!$this->db->query($sql)) {
  574. $this->error = $this->db->lasterror();
  575. $error++;
  576. }
  577. }
  578. $arraydelete = array(
  579. 'categorie_account' => 'fk_categorie',
  580. 'categorie_actioncomm' => 'fk_categorie',
  581. 'categorie_contact' => 'fk_categorie',
  582. 'categorie_fournisseur' => 'fk_categorie',
  583. 'categorie_knowledgemanagement' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('knowledgemanagement')),
  584. 'categorie_member' => 'fk_categorie',
  585. 'categorie_user' => 'fk_categorie',
  586. 'categorie_product' => 'fk_categorie',
  587. 'categorie_project' => 'fk_categorie',
  588. 'categorie_societe' => 'fk_categorie',
  589. 'categorie_ticket' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('ticket')),
  590. 'categorie_warehouse' => 'fk_categorie',
  591. 'categorie_website_page' => array('field' => 'fk_categorie', 'enabled' => isModEnabled('website')),
  592. 'bank_class' => 'fk_categ',
  593. 'categorie_lang' => 'fk_category',
  594. 'categorie' => 'rowid',
  595. );
  596. foreach ($arraydelete as $key => $value) {
  597. if (is_array($value)) {
  598. if (empty($value['enabled'])) {
  599. continue;
  600. }
  601. $value = $value['field'];
  602. }
  603. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$key;
  604. $sql .= " WHERE ".$value." = ".((int) $this->id);
  605. if (!$this->db->query($sql)) {
  606. $this->errors[] = $this->db->lasterror();
  607. dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR);
  608. $error++;
  609. }
  610. }
  611. // Removed extrafields
  612. if (!$error) {
  613. $result = $this->deleteExtraFields();
  614. if ($result < 0) {
  615. $error++;
  616. dol_syslog(get_class($this)."::delete erreur ".$this->error, LOG_ERR);
  617. }
  618. }
  619. if (!$error) {
  620. $this->db->commit();
  621. return 1;
  622. } else {
  623. $this->db->rollback();
  624. return -1;
  625. }
  626. }
  627. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  628. /**
  629. * Link an object to the category
  630. *
  631. * @param CommonObject $obj Object to link to category
  632. * @param string $type Type of category ('product', ...). Use '' to take $obj->element.
  633. * @return int 1 : OK, -1 : erreur SQL, -2 : id not defined, -3 : Already linked
  634. * @see del_type()
  635. */
  636. public function add_type($obj, $type = '')
  637. {
  638. // phpcs:enable
  639. global $user, $conf;
  640. $error = 0;
  641. if ($this->id == -1) {
  642. return -2;
  643. }
  644. if (empty($type)) {
  645. $type = $obj->element;
  646. }
  647. dol_syslog(get_class($this).'::add_type', LOG_DEBUG);
  648. $this->db->begin();
  649. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  650. $sql .= " (fk_categorie, fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]).")";
  651. $sql .= " VALUES (".((int) $this->id).", ".((int) $obj->id).")";
  652. if ($this->db->query($sql)) {
  653. if (getDolGlobalString('CATEGORIE_RECURSIV_ADD')) {
  654. $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie';
  655. $sql .= " WHERE rowid = ".((int) $this->id);
  656. dol_syslog(get_class($this)."::add_type", LOG_DEBUG);
  657. $resql = $this->db->query($sql);
  658. if ($resql) {
  659. if ($this->db->num_rows($resql) > 0) {
  660. $objparent = $this->db->fetch_object($resql);
  661. if (!empty($objparent->fk_parent)) {
  662. $cat = new Categorie($this->db);
  663. $cat->id = $objparent->fk_parent;
  664. if (!$cat->containsObject($type, $obj->id)) {
  665. $result = $cat->add_type($obj, $type);
  666. if ($result < 0) {
  667. $this->error = $cat->error;
  668. $error++;
  669. }
  670. }
  671. }
  672. }
  673. } else {
  674. $error++;
  675. $this->error = $this->db->lasterror();
  676. }
  677. if ($error) {
  678. $this->db->rollback();
  679. return -1;
  680. }
  681. }
  682. // Call trigger
  683. $this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
  684. $result = $this->call_trigger('CATEGORY_LINK', $user);
  685. if ($result < 0) {
  686. $error++;
  687. }
  688. // End call triggers
  689. if (!$error) {
  690. $this->db->commit();
  691. return 1;
  692. } else {
  693. $this->db->rollback();
  694. return -2;
  695. }
  696. } else {
  697. $this->db->rollback();
  698. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  699. $this->error = $this->db->lasterrno();
  700. return -3;
  701. } else {
  702. $this->error = $this->db->lasterror();
  703. }
  704. return -1;
  705. }
  706. }
  707. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  708. /**
  709. * Delete object from category
  710. *
  711. * @param CommonObject $obj Object
  712. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member')
  713. * @return int 1 if OK, -1 if KO
  714. * @see add_type()
  715. */
  716. public function del_type($obj, $type)
  717. {
  718. // phpcs:enable
  719. global $user, $langs, $conf;
  720. $error = 0;
  721. // For backward compatibility
  722. if ($type == 'societe') {
  723. $type = 'customer';
  724. dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
  725. } elseif ($type == 'fournisseur') {
  726. $type = 'supplier';
  727. dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
  728. }
  729. $this->db->begin();
  730. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  731. $sql .= " WHERE fk_categorie = ".((int) $this->id);
  732. $sql .= " AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $obj->id);
  733. dol_syslog(get_class($this).'::del_type', LOG_DEBUG);
  734. if ($this->db->query($sql)) {
  735. // Call trigger
  736. $this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
  737. $result = $this->call_trigger('CATEGORY_UNLINK', $user);
  738. if ($result < 0) {
  739. $error++;
  740. }
  741. // End call triggers
  742. if (!$error) {
  743. $this->db->commit();
  744. return 1;
  745. } else {
  746. $this->db->rollback();
  747. return -2;
  748. }
  749. } else {
  750. $this->db->rollback();
  751. $this->error = $this->db->lasterror();
  752. return -1;
  753. }
  754. }
  755. /**
  756. * Return list of fetched instance of elements having this category
  757. *
  758. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member', 'knowledge_management', ...)
  759. * @param int $onlyids Return only ids of objects (consume less memory)
  760. * @param int $limit Limit
  761. * @param int $offset Offset
  762. * @param string $sortfield Sort fields
  763. * @param string $sortorder Sort order ('ASC' or 'DESC');
  764. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customsql'=>...)
  765. * @param string $filtermode Filter mode (AND or OR)
  766. * @return array|int -1 if KO, array of instance of object if OK
  767. * @see containsObject()
  768. */
  769. public function getObjectsInCateg($type, $onlyids = 0, $limit = 0, $offset = 0, $sortfield = '', $sortorder = 'ASC', $filter = array(), $filtermode = 'AND')
  770. {
  771. global $user;
  772. $objs = array();
  773. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  774. $obj = new $classnameforobj($this->db);
  775. $sql = "SELECT c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]);
  776. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as c";
  777. $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." as o";
  778. $sql .= " WHERE o.entity IN (".getEntity($obj->element).")";
  779. $sql .= " AND c.fk_categorie = ".((int) $this->id);
  780. // Compatibility with actioncomm table which has id instead of rowid
  781. if ((array_key_exists($type, $this->MAP_OBJ_TABLE) && $this->MAP_OBJ_TABLE[$type] == "actioncomm") || $type == "actioncomm") {
  782. $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.id";
  783. } else {
  784. $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.rowid";
  785. }
  786. // Protection for external users
  787. if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) {
  788. $sql .= " AND o.rowid = ".((int) $user->socid);
  789. }
  790. // Manage filter
  791. $sqlwhere = array();
  792. if (count($filter) > 0) {
  793. foreach ($filter as $key => $value) {
  794. if ($key == 'o.rowid') {
  795. $sqlwhere[] = $key." = ".((int) $value);
  796. } elseif ($key == 'customsql') {
  797. $sqlwhere[] = $value;
  798. }
  799. }
  800. }
  801. if (count($sqlwhere) > 0) {
  802. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  803. }
  804. $sql .= $this->db->order($sortfield, $sortorder);
  805. if ($limit > 0 || $offset > 0) {
  806. $sql .= $this->db->plimit($limit + 1, $offset);
  807. }
  808. dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
  809. $resql = $this->db->query($sql);
  810. if ($resql) {
  811. while ($rec = $this->db->fetch_array($resql)) {
  812. if ($onlyids) {
  813. $objs[] = $rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])];
  814. } else {
  815. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  816. $obj = new $classnameforobj($this->db);
  817. $obj->fetch($rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]);
  818. $objs[] = $obj;
  819. }
  820. }
  821. return $objs;
  822. } else {
  823. $this->error = $this->db->error().' sql='.$sql;
  824. return -1;
  825. }
  826. }
  827. /**
  828. * Check for the presence of an object in a category
  829. *
  830. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member')
  831. * @param int $object_id Id of the object to search
  832. * @return int Number of occurrences
  833. * @see getObjectsInCateg()
  834. */
  835. public function containsObject($type, $object_id)
  836. {
  837. $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  838. $sql .= " WHERE fk_categorie = ".((int) $this->id)." AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $object_id);
  839. dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
  840. $resql = $this->db->query($sql);
  841. if ($resql) {
  842. return $this->db->fetch_object($resql)->nb;
  843. } else {
  844. $this->error = $this->db->error().' sql='.$sql;
  845. return -1;
  846. }
  847. }
  848. /**
  849. * List categories of an element id
  850. *
  851. * @param int $id Id of element
  852. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact')
  853. * @param string $sortfield Sort field
  854. * @param string $sortorder Sort order
  855. * @param int $limit Limit for list
  856. * @param int $page Page number
  857. * @return array|int Array of categories, 0 if no cat, -1 on error
  858. */
  859. public function getListForItem($id, $type = 'customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  860. {
  861. global $conf;
  862. $categories = array();
  863. $type = sanitizeVal($type, 'aZ09');
  864. $sub_type = $type;
  865. $subcol_name = "fk_".$type;
  866. if ($type == "customer") {
  867. $sub_type = "societe";
  868. $subcol_name = "fk_soc";
  869. }
  870. if ($type == "supplier") {
  871. $sub_type = "fournisseur";
  872. $subcol_name = "fk_soc";
  873. }
  874. if ($type == "contact") {
  875. $subcol_name = "fk_socpeople";
  876. }
  877. $idoftype = array_search($type, self::$MAP_ID_TO_CODE);
  878. $sql = "SELECT s.rowid";
  879. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s, ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub";
  880. $sql .= ' WHERE s.entity IN ('.getEntity('category').')';
  881. $sql .= ' AND s.type='.((int) $idoftype);
  882. $sql .= ' AND s.rowid = sub.fk_categorie';
  883. $sql .= " AND sub.".$subcol_name." = ".((int) $id);
  884. $sql .= $this->db->order($sortfield, $sortorder);
  885. $offset = 0;
  886. $nbtotalofrecords = '';
  887. if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
  888. $result = $this->db->query($sql);
  889. $nbtotalofrecords = $this->db->num_rows($result);
  890. if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
  891. $page = 0;
  892. $offset = 0;
  893. }
  894. }
  895. if ($limit) {
  896. if ($page < 0) {
  897. $page = 0;
  898. }
  899. $offset = $limit * $page;
  900. $sql .= $this->db->plimit($limit + 1, $offset);
  901. }
  902. $result = $this->db->query($sql);
  903. if ($result) {
  904. $i = 0;
  905. $num = $this->db->num_rows($result);
  906. $min = min($num, ($limit <= 0 ? $num : $limit));
  907. while ($i < $min) {
  908. $obj = $this->db->fetch_object($result);
  909. $category_static = new Categorie($this->db);
  910. if ($category_static->fetch($obj->rowid)) {
  911. $categories[$i]['id'] = $category_static->id;
  912. $categories[$i]['fk_parent'] = $category_static->fk_parent;
  913. $categories[$i]['label'] = $category_static->label;
  914. $categories[$i]['description'] = $category_static->description;
  915. $categories[$i]['color'] = $category_static->color;
  916. $categories[$i]['socid'] = $category_static->socid;
  917. $categories[$i]['ref_ext'] = $category_static->ref_ext;
  918. $categories[$i]['visible'] = $category_static->visible;
  919. $categories[$i]['type'] = $category_static->type;
  920. $categories[$i]['entity'] = $category_static->entity;
  921. $categories[$i]['array_options'] = $category_static->array_options;
  922. // multilangs
  923. if (getDolGlobalInt('MAIN_MULTILANGS') && isset($category_static->multilangs)) {
  924. $categories[$i]['multilangs'] = $category_static->multilangs;
  925. }
  926. }
  927. $i++;
  928. }
  929. } else {
  930. $this->error = $this->db->lasterror();
  931. return -1;
  932. }
  933. if (!count($categories)) {
  934. return 0;
  935. }
  936. return $categories;
  937. }
  938. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  939. /**
  940. * Return direct childs id of a category into an array
  941. *
  942. * @return array|int <0 KO, array ok
  943. */
  944. public function get_filles()
  945. {
  946. // phpcs:enable
  947. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  948. $sql .= " WHERE fk_parent = ".((int) $this->id);
  949. $sql .= " AND entity IN (".getEntity('category').")";
  950. $res = $this->db->query($sql);
  951. if ($res) {
  952. $cats = array();
  953. while ($rec = $this->db->fetch_array($res)) {
  954. $cat = new Categorie($this->db);
  955. $cat->fetch($rec['rowid']);
  956. $cats[] = $cat;
  957. }
  958. return $cats;
  959. } else {
  960. dol_print_error($this->db);
  961. return -1;
  962. }
  963. }
  964. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  965. /**
  966. * Load the array this->motherof that is array(id_son=>id_parent, ...)
  967. *
  968. * @return int <0 if KO, >0 if OK
  969. */
  970. protected function load_motherof()
  971. {
  972. // phpcs:enable
  973. $this->motherof = array();
  974. // Load array[child]=parent
  975. $sql = "SELECT fk_parent as id_parent, rowid as id_son";
  976. $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
  977. $sql .= " WHERE fk_parent != 0";
  978. $sql .= " AND entity IN (".getEntity('category').")";
  979. dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
  980. $resql = $this->db->query($sql);
  981. if ($resql) {
  982. while ($obj = $this->db->fetch_object($resql)) {
  983. $this->motherof[$obj->id_son] = $obj->id_parent;
  984. }
  985. return 1;
  986. } else {
  987. dol_print_error($this->db);
  988. return -1;
  989. }
  990. }
  991. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  992. /**
  993. * Rebuilding the category tree as an array
  994. * Return an array of table('id','id_mere',...) trie selon arbre et avec:
  995. * id = id de la categorie
  996. * id_mere = id de la categorie mere
  997. * id_children = tableau des id enfant
  998. * label = nom de la categorie
  999. * fulllabel = nom avec chemin complet de la categorie
  1000. * fullpath = chemin complet compose des id
  1001. *
  1002. * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member', ...)
  1003. * @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.
  1004. * $markafterid can be an :
  1005. * - int (id of category)
  1006. * - string (categories ids separated by comma)
  1007. * - array (list of categories ids)
  1008. * @param int $include [=0] Removed or 1=Keep only
  1009. * @return array|int Array of categories. this->cats and this->motherof are set, -1 on error
  1010. */
  1011. public function get_full_arbo($type, $markafterid = 0, $include = 0)
  1012. {
  1013. // phpcs:enable
  1014. global $conf, $langs;
  1015. if (!is_numeric($type)) {
  1016. $type = $this->MAP_ID[$type];
  1017. }
  1018. if (is_null($type)) {
  1019. $this->error = 'BadValueForParameterType';
  1020. return -1;
  1021. }
  1022. if (is_string($markafterid)) {
  1023. $markafterid = explode(',', $markafterid);
  1024. } elseif (is_numeric($markafterid)) {
  1025. if ($markafterid > 0) {
  1026. $markafterid = array($markafterid);
  1027. } else {
  1028. $markafterid = array();
  1029. }
  1030. } elseif (!is_array($markafterid)) {
  1031. $markafterid = array();
  1032. }
  1033. $this->cats = array();
  1034. // Init this->motherof that is array(id_son=>id_parent, ...)
  1035. $this->load_motherof();
  1036. $current_lang = $langs->getDefaultLang();
  1037. // Init $this->cats array
  1038. $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
  1039. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1040. $sql .= ", t.label as label_trans, t.description as description_trans";
  1041. }
  1042. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
  1043. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1044. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'";
  1045. }
  1046. $sql .= " WHERE c.entity IN (".getEntity('category').")";
  1047. $sql .= " AND c.type = ".(int) $type;
  1048. dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
  1049. $resql = $this->db->query($sql);
  1050. if ($resql) {
  1051. $i = 0;
  1052. while ($obj = $this->db->fetch_object($resql)) {
  1053. $this->cats[$obj->rowid]['rowid'] = $obj->rowid;
  1054. $this->cats[$obj->rowid]['id'] = $obj->rowid;
  1055. $this->cats[$obj->rowid]['fk_parent'] = $obj->fk_parent;
  1056. $this->cats[$obj->rowid]['label'] = !empty($obj->label_trans) ? $obj->label_trans : $obj->label;
  1057. $this->cats[$obj->rowid]['description'] = !empty($obj->description_trans) ? $obj->description_trans : $obj->description;
  1058. $this->cats[$obj->rowid]['color'] = $obj->color;
  1059. $this->cats[$obj->rowid]['visible'] = $obj->visible;
  1060. $this->cats[$obj->rowid]['ref_ext'] = $obj->ref_ext;
  1061. $this->cats[$obj->rowid]['picto'] = 'category';
  1062. $i++;
  1063. }
  1064. } else {
  1065. dol_print_error($this->db);
  1066. return -1;
  1067. }
  1068. // We add the fullpath property to each elements of first level (no parent exists)
  1069. dol_syslog(get_class($this)."::get_full_arbo call to buildPathFromId", LOG_DEBUG);
  1070. foreach ($this->cats as $key => $val) {
  1071. //print 'key='.$key.'<br>'."\n";
  1072. $this->buildPathFromId($key, 0); // Process a branch from the root category key (this category has no parent)
  1073. }
  1074. // Include or exclude leaf including $markafterid from tree
  1075. if (count($markafterid) > 0) {
  1076. $keyfiltercatid = '('.implode('|', $markafterid).')';
  1077. //print "Look to discard category ".$markafterid."\n";
  1078. $keyfilter1 = '^'.$keyfiltercatid.'$';
  1079. $keyfilter2 = '_'.$keyfiltercatid.'$';
  1080. $keyfilter3 = '^'.$keyfiltercatid.'_';
  1081. $keyfilter4 = '_'.$keyfiltercatid.'_';
  1082. foreach ($this->cats as $key => $val) {
  1083. $test = (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
  1084. || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath']));
  1085. if (($test && !$include) || (!$test && $include)) {
  1086. unset($this->cats[$key]);
  1087. }
  1088. }
  1089. }
  1090. dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
  1091. $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
  1092. return $this->cats;
  1093. }
  1094. /**
  1095. * For category id_categ and its childs available in this->cats, define property fullpath and fulllabel.
  1096. * It is called by get_full_arbo()
  1097. * This function is a memory scan only from $this->cats and $this->motherof, no database access must be done here.
  1098. *
  1099. * @param int $id_categ id_categ entry to update
  1100. * @param int $protection Deep counter to avoid infinite loop
  1101. * @return int <0 if KO, >0 if OK
  1102. * @see get_full_arbo()
  1103. */
  1104. private function buildPathFromId($id_categ, $protection = 1000)
  1105. {
  1106. //dol_syslog(get_class($this)."::buildPathFromId id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
  1107. if (!empty($this->cats[$id_categ]['fullpath'])) {
  1108. // Already defined
  1109. dol_syslog(get_class($this)."::buildPathFromId fullpath and fulllabel already defined", LOG_WARNING);
  1110. return -1;
  1111. }
  1112. // First build full array $motherof
  1113. //$this->load_motherof(); // Disabled because already done by caller of buildPathFromId
  1114. // $this->cats[$id_categ] is supposed to be already an array. We just want to complete it with property fullpath and fulllabel
  1115. // Define fullpath and fulllabel
  1116. $this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
  1117. $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
  1118. $i = 0; $cursor_categ = $id_categ;
  1119. //print 'Work for id_categ='.$id_categ.'<br>'."\n";
  1120. while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) {
  1121. //print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
  1122. $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
  1123. $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'];
  1124. //print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
  1125. $i++;
  1126. $cursor_categ = $this->motherof[$cursor_categ];
  1127. }
  1128. //print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'<br>'."\n";
  1129. // We count number of _ to have level
  1130. $nbunderscore = substr_count($this->cats[$id_categ]['fullpath'], '_');
  1131. $this->cats[$id_categ]['level'] = ($nbunderscore ? $nbunderscore : null);
  1132. return 1;
  1133. }
  1134. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1135. /**
  1136. * Returns all categories
  1137. *
  1138. * @param int $type Type of category (0, 1, ...)
  1139. * @param boolean $parent Just parent categories if true
  1140. * @return array|int Table of Object Category, -1 on error
  1141. */
  1142. public function get_all_categories($type = null, $parent = false)
  1143. {
  1144. // phpcs:enable
  1145. if (!is_numeric($type)) {
  1146. $type = $this->MAP_ID[$type];
  1147. }
  1148. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  1149. $sql .= " WHERE entity IN (".getEntity('category').")";
  1150. if (!is_null($type)) {
  1151. $sql .= " AND type = ".(int) $type;
  1152. }
  1153. if ($parent) {
  1154. $sql .= " AND fk_parent = 0";
  1155. }
  1156. $res = $this->db->query($sql);
  1157. if ($res) {
  1158. $cats = array();
  1159. while ($rec = $this->db->fetch_array($res)) {
  1160. $cat = new Categorie($this->db);
  1161. $cat->fetch($rec['rowid']);
  1162. $cats[$rec['rowid']] = $cat;
  1163. }
  1164. return $cats;
  1165. } else {
  1166. dol_print_error($this->db);
  1167. return -1;
  1168. }
  1169. }
  1170. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1171. /**
  1172. * Returns the top level categories (which are not child)
  1173. *
  1174. * @param int $type Type of category (0, 1, ...)
  1175. * @return array
  1176. */
  1177. public function get_main_categories($type = null)
  1178. {
  1179. // phpcs:enable
  1180. return $this->get_all_categories($type, true);
  1181. }
  1182. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1183. /**
  1184. * Check if no category with same label already exists for this cat's parent or root and for this cat's type
  1185. *
  1186. * @return integer 1 if already exist, 0 otherwise, -1 if error
  1187. */
  1188. public function already_exists()
  1189. {
  1190. // phpcs:enable
  1191. $type = $this->type;
  1192. if (!is_numeric($type)) {
  1193. $type = $this->MAP_ID[$type];
  1194. }
  1195. /* We have to select any rowid from llx_categorie which category's mother and label
  1196. * are equals to those of the calling category
  1197. */
  1198. $sql = "SELECT c.rowid";
  1199. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c ";
  1200. $sql .= " WHERE c.entity IN (".getEntity('category').")";
  1201. $sql .= " AND c.type = ".((int) $type);
  1202. $sql .= " AND c.fk_parent = ".((int) $this->fk_parent);
  1203. $sql .= " AND c.label = '".$this->db->escape($this->label)."'";
  1204. dol_syslog(get_class($this)."::already_exists", LOG_DEBUG);
  1205. $resql = $this->db->query($sql);
  1206. if ($resql) {
  1207. if ($this->db->num_rows($resql) > 0) { // Checking for empty resql
  1208. $obj = $this->db->fetch_array($resql);
  1209. /* If object called create, obj cannot have is id.
  1210. * If object called update, he mustn't have the same label as an other category for this mother.
  1211. * So if the result have the same id, update is not for label, and if result have an other one,
  1212. * update may be for label.
  1213. */
  1214. if ($obj[0] > 0 && $obj[0] != $this->id) {
  1215. 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);
  1216. return 1;
  1217. }
  1218. }
  1219. 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);
  1220. return 0;
  1221. } else {
  1222. $this->error = $this->db->error();
  1223. return -1;
  1224. }
  1225. }
  1226. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1227. /**
  1228. * Returns the path of the category, with the names of the categories
  1229. * separated by $sep (" >> " by default)
  1230. *
  1231. * @param string $sep Separator
  1232. * @param string $url Url ('', 'none' or 'urltouse')
  1233. * @param int $nocolor 0
  1234. * @param string $addpicto Add picto into link
  1235. * @return array
  1236. */
  1237. public function print_all_ways($sep = '&gt;&gt;', $url = '', $nocolor = 0, $addpicto = 0)
  1238. {
  1239. // phpcs:enable
  1240. $ways = array();
  1241. $allways = $this->get_all_ways(); // Load array of categories
  1242. foreach ($allways as $way) {
  1243. $w = array();
  1244. $i = 0;
  1245. $forced_color = '';
  1246. foreach ($way as $cat) {
  1247. $i++;
  1248. if (empty($nocolor)) {
  1249. $forced_color = 'colortoreplace';
  1250. if ($i == count($way)) { // Last category in hierarchy
  1251. // Check contrast with background and correct text color
  1252. $forced_color = 'categtextwhite';
  1253. if ($cat->color) {
  1254. if (colorIsLight($cat->color)) {
  1255. $forced_color = 'categtextblack';
  1256. }
  1257. }
  1258. }
  1259. }
  1260. if ($url == '') {
  1261. $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$cat->id.'&type='.$cat->type.'" class="'.$forced_color.'">';
  1262. $linkend = '</a>';
  1263. $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
  1264. } elseif ($url == 'none') {
  1265. $link = '<span class="'.$forced_color.'">';
  1266. $linkend = '</span>';
  1267. $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
  1268. } else {
  1269. $w[] = '<a class="'.$forced_color.'" href="'.DOL_URL_ROOT.'/'.$url.'?catid='.$cat->id.'">'.($addpicto ? img_object('', 'category') : '').$cat->label.'</a>';
  1270. }
  1271. }
  1272. $newcategwithpath = preg_replace('/colortoreplace/', $forced_color, implode('<span class="inline-block valignmiddle paddingleft paddingright '.$forced_color.'">'.$sep.'</span>', $w));
  1273. $ways[] = $newcategwithpath;
  1274. }
  1275. return $ways;
  1276. }
  1277. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1278. /**
  1279. * Returns an array containing the list of parent categories
  1280. *
  1281. * @return int|array <0 KO, array OK
  1282. */
  1283. public function get_meres()
  1284. {
  1285. // phpcs:enable
  1286. $parents = array();
  1287. $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie";
  1288. $sql .= " WHERE rowid = ".((int) $this->id);
  1289. $res = $this->db->query($sql);
  1290. if ($res) {
  1291. while ($rec = $this->db->fetch_array($res)) {
  1292. if ($rec['fk_parent'] > 0) {
  1293. $cat = new Categorie($this->db);
  1294. $cat->fetch($rec['fk_parent']);
  1295. $parents[] = $cat;
  1296. }
  1297. }
  1298. return $parents;
  1299. } else {
  1300. dol_print_error($this->db);
  1301. return -1;
  1302. }
  1303. }
  1304. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1305. /**
  1306. * Returns in a table all possible paths to get to the category
  1307. * starting with the major categories represented by Tables of categories
  1308. *
  1309. * @return array
  1310. */
  1311. public function get_all_ways()
  1312. {
  1313. // phpcs:enable
  1314. $ways = array();
  1315. $parents = $this->get_meres();
  1316. if (is_array($parents)) {
  1317. foreach ($parents as $parent) {
  1318. $allways = $parent->get_all_ways();
  1319. foreach ($allways as $way) {
  1320. $w = $way;
  1321. $w[] = $this;
  1322. $ways[] = $w;
  1323. }
  1324. }
  1325. }
  1326. if (count($ways) == 0) {
  1327. $ways[0][0] = $this;
  1328. }
  1329. return $ways;
  1330. }
  1331. /**
  1332. * Return list of categories (object instances or labels) linked to element of id $id and type $type
  1333. * Should be named getListOfCategForObject
  1334. *
  1335. * @param int $id Id of element
  1336. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') or (0, 1, 2, ...)
  1337. * @param string $mode 'id'=Get array of category ids, 'object'=Get array of fetched category instances, 'label'=Get array of category
  1338. * labels, 'id'= Get array of category IDs
  1339. * @return Categorie[]|int Array of category objects or < 0 if KO
  1340. */
  1341. public function containing($id, $type, $mode = 'object')
  1342. {
  1343. $cats = array();
  1344. if (is_numeric($type)) {
  1345. $type = Categorie::$MAP_ID_TO_CODE[$type];
  1346. }
  1347. if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this with standard category code after migration of llx_bank_categ into llx_categorie
  1348. // Load bank categories
  1349. $sql = "SELECT c.label, c.rowid";
  1350. $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c";
  1351. $sql .= " WHERE a.lineid=".((int) $id)." AND a.fk_categ = c.rowid";
  1352. $sql .= " AND c.entity IN (".getEntity('category').")";
  1353. $sql .= " ORDER BY c.label";
  1354. $res = $this->db->query($sql);
  1355. if ($res) {
  1356. while ($obj = $this->db->fetch_object($res)) {
  1357. if ($mode == 'id') {
  1358. $cats[] = $obj->rowid;
  1359. } elseif ($mode == 'label') {
  1360. $cats[] = $obj->label;
  1361. } else {
  1362. $cat = new Categorie($this->db);
  1363. $cat->id = $obj->rowid;
  1364. $cat->label = $obj->label;
  1365. $cats[] = $cat;
  1366. }
  1367. }
  1368. } else {
  1369. dol_print_error($this->db);
  1370. return -1;
  1371. }
  1372. } else {
  1373. $sql = "SELECT ct.fk_categorie, c.label, c.rowid";
  1374. $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";
  1375. $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".(int) $id;
  1376. // This seems useless because the table already contains id of category of 1 unique type. So commented.
  1377. // So now it works also with external added categories.
  1378. //$sql .= " AND c.type = ".((int) $this->MAP_ID[$type]);
  1379. $sql .= " AND c.entity IN (".getEntity('category').")";
  1380. $res = $this->db->query($sql);
  1381. if ($res) {
  1382. while ($obj = $this->db->fetch_object($res)) {
  1383. if ($mode == 'id') {
  1384. $cats[] = $obj->rowid;
  1385. } elseif ($mode == 'label') {
  1386. $cats[] = $obj->label;
  1387. } else {
  1388. $cat = new Categorie($this->db);
  1389. $cat->fetch($obj->fk_categorie);
  1390. $cats[] = $cat;
  1391. }
  1392. }
  1393. } else {
  1394. dol_print_error($this->db);
  1395. return -1;
  1396. }
  1397. }
  1398. return $cats;
  1399. }
  1400. /**
  1401. * Returns categories whose id or name match
  1402. * add wildcards in the name unless $exact = true
  1403. *
  1404. * @param int $id Id
  1405. * @param string $nom Name
  1406. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  1407. * @param boolean $exact Exact string search (true/false)
  1408. * @param boolean $case Case sensitive (true/false)
  1409. * @return Categorie[]|int Array of Categorie, -1 if error
  1410. */
  1411. public function rechercher($id, $nom, $type, $exact = false, $case = false)
  1412. {
  1413. // Deprecation warning
  1414. if (is_numeric($type)) {
  1415. dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING);
  1416. }
  1417. $cats = array();
  1418. // For backward compatibility
  1419. if (is_numeric($type)) {
  1420. // We want to reverse lookup
  1421. $map_type = array_flip($this->MAP_ID);
  1422. $type = $map_type[$type];
  1423. dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING);
  1424. }
  1425. // Generation requete recherche
  1426. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  1427. $sql .= " WHERE type = ".((int) $this->MAP_ID[$type]);
  1428. $sql .= " AND entity IN (".getEntity('category').")";
  1429. if ($nom) {
  1430. if (!$exact) {
  1431. $nom = '%'.$this->db->escape(str_replace('*', '%', $nom)).'%';
  1432. }
  1433. if (!$case) {
  1434. $sql .= " AND label LIKE '".$this->db->escape($nom)."'";
  1435. } else {
  1436. $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
  1437. }
  1438. }
  1439. if ($id) {
  1440. $sql .= " AND rowid = ".((int) $id);
  1441. }
  1442. $res = $this->db->query($sql);
  1443. if ($res) {
  1444. while ($rec = $this->db->fetch_array($res)) {
  1445. $cat = new Categorie($this->db);
  1446. $cat->fetch($rec['rowid']);
  1447. $cats[] = $cat;
  1448. }
  1449. return $cats;
  1450. } else {
  1451. $this->error = $this->db->error().' sql='.$sql;
  1452. return -1;
  1453. }
  1454. }
  1455. /**
  1456. * getTooltipContentArray
  1457. * @param array $params params to construct tooltip data
  1458. * @since v18
  1459. * @return array
  1460. */
  1461. public function getTooltipContentArray($params)
  1462. {
  1463. global $langs;
  1464. $langs->load('categories');
  1465. $datas = [];
  1466. $datas['label'] = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
  1467. return $datas;
  1468. }
  1469. /**
  1470. * Return name and link of category (with picto)
  1471. * Use ->id, ->ref, ->label, ->color
  1472. *
  1473. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1474. * @param string $option Sur quoi pointe le lien ('', 'xyz')
  1475. * @param int $maxlength Max length of text
  1476. * @param string $moreparam More param on URL link
  1477. * @return string Chaine avec URL
  1478. */
  1479. public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $moreparam = '')
  1480. {
  1481. global $langs, $hookmanager;
  1482. $result = '';
  1483. $params = [
  1484. 'id' => $this->id,
  1485. 'objecttype' => $this->element,
  1486. 'option' => $option,
  1487. ];
  1488. $classfortooltip = 'classfortooltip';
  1489. $dataparams = '';
  1490. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  1491. $classfortooltip = 'classforajaxtooltip';
  1492. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  1493. $label = '';
  1494. } else {
  1495. $label = implode($this->getTooltipContentArray($params));
  1496. }
  1497. // Check contrast with background and correct text color
  1498. $forced_color = 'categtextwhite';
  1499. if ($this->color) {
  1500. if (colorIsLight($this->color)) {
  1501. $forced_color = 'categtextblack';
  1502. }
  1503. }
  1504. $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : ''));
  1505. $link .= '"'.$dataparams;
  1506. $link .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  1507. $link .= ' class="'.$classfortooltip.' '.$forced_color.'">';
  1508. $linkend = '</a>';
  1509. $picto = 'category';
  1510. if ($withpicto) {
  1511. $result .= ($link.img_object($label, $picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
  1512. }
  1513. if ($withpicto && $withpicto != 2) {
  1514. $result .= ' ';
  1515. }
  1516. if ($withpicto != 2) {
  1517. $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend;
  1518. }
  1519. global $action;
  1520. $hookmanager->initHooks(array($this->element . 'dao'));
  1521. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1522. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1523. if ($reshook > 0) {
  1524. $result = $hookmanager->resPrint;
  1525. } else {
  1526. $result .= $hookmanager->resPrint;
  1527. }
  1528. return $result;
  1529. }
  1530. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1531. /**
  1532. * Deplace fichier uploade sous le nom $file dans le repertoire sdir
  1533. *
  1534. * @param string $sdir Final destination directory
  1535. * @param array $file Uploaded file name
  1536. * @return void
  1537. */
  1538. public function add_photo($sdir, $file)
  1539. {
  1540. // phpcs:enable
  1541. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1542. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
  1543. $dir .= "photos/";
  1544. if (!file_exists($dir)) {
  1545. dol_mkdir($dir);
  1546. }
  1547. if (file_exists($dir)) {
  1548. if (is_array($file['name']) && count($file['name']) > 0) {
  1549. $nbfile = count($file['name']);
  1550. for ($i = 0; $i <= $nbfile; $i++) {
  1551. $originImage = $dir.$file['name'][$i];
  1552. // Cree fichier en taille origine
  1553. dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
  1554. if (file_exists($originImage)) {
  1555. // Create thumbs
  1556. $this->addThumbs($originImage);
  1557. }
  1558. }
  1559. } else {
  1560. $originImage = $dir.$file['name'];
  1561. // Cree fichier en taille origine
  1562. dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
  1563. if (file_exists($originImage)) {
  1564. // Create thumbs
  1565. $this->addThumbs($originImage);
  1566. }
  1567. }
  1568. }
  1569. }
  1570. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1571. /**
  1572. * Return tableau de toutes les photos de la categorie
  1573. *
  1574. * @param string $dir Repertoire a scanner
  1575. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  1576. * @return array Tableau de photos
  1577. */
  1578. public function liste_photos($dir, $nbmax = 0)
  1579. {
  1580. // phpcs:enable
  1581. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1582. $nbphoto = 0;
  1583. $tabobj = array();
  1584. $dirthumb = $dir.'thumbs/';
  1585. if (file_exists($dir)) {
  1586. $handle = opendir($dir);
  1587. if (is_resource($handle)) {
  1588. while (($file = readdir($handle)) !== false) {
  1589. if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) {
  1590. $nbphoto++;
  1591. $photo = $file;
  1592. // On determine nom du fichier vignette
  1593. $photo_vignette = '';
  1594. if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) {
  1595. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
  1596. }
  1597. // Objet
  1598. $obj = array();
  1599. $obj['photo'] = $photo;
  1600. if ($photo_vignette && is_file($dirthumb.$photo_vignette)) {
  1601. $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
  1602. } else {
  1603. $obj['photo_vignette'] = "";
  1604. }
  1605. $tabobj[$nbphoto - 1] = $obj;
  1606. // On continue ou on arrete de boucler
  1607. if ($nbmax && $nbphoto >= $nbmax) {
  1608. break;
  1609. }
  1610. }
  1611. }
  1612. closedir($handle);
  1613. }
  1614. }
  1615. return $tabobj;
  1616. }
  1617. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1618. /**
  1619. * Efface la photo de la categorie et sa vignette
  1620. *
  1621. * @param string $file Path to file
  1622. * @return void
  1623. */
  1624. public function delete_photo($file)
  1625. {
  1626. // phpcs:enable
  1627. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1628. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  1629. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
  1630. $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
  1631. // On efface l'image d'origine
  1632. dol_delete_file($file, 1);
  1633. // Si elle existe, on efface la vignette
  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 <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 <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. }