categorie.class.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090
  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. * 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] = isset($mapList['cat_fk']) ? $mapList['cat_fk'] : null;
  261. $this->MAP_CAT_TABLE[$mapCode] = isset($mapList['cat_table']) ? $mapList['cat_table'] : null;
  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 (getDolGlobalInt('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. * @see del_type()
  621. */
  622. public function add_type($obj, $type = '')
  623. {
  624. // phpcs:enable
  625. global $user, $langs, $conf;
  626. $error = 0;
  627. if ($this->id == -1) {
  628. return -2;
  629. }
  630. if (empty($type)) {
  631. $type = $obj->element;
  632. }
  633. dol_syslog(get_class($this).'::add_type', LOG_DEBUG);
  634. $this->db->begin();
  635. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  636. $sql .= " (fk_categorie, fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]).")";
  637. $sql .= " VALUES (".((int) $this->id).", ".((int) $obj->id).")";
  638. if ($this->db->query($sql)) {
  639. if (!empty($conf->global->CATEGORIE_RECURSIV_ADD)) {
  640. $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie';
  641. $sql .= " WHERE rowid = ".((int) $this->id);
  642. dol_syslog(get_class($this)."::add_type", LOG_DEBUG);
  643. $resql = $this->db->query($sql);
  644. if ($resql) {
  645. if ($this->db->num_rows($resql) > 0) {
  646. $objparent = $this->db->fetch_object($resql);
  647. if (!empty($objparent->fk_parent)) {
  648. $cat = new Categorie($this->db);
  649. $cat->id = $objparent->fk_parent;
  650. if (!$cat->containsObject($type, $obj->id)) {
  651. $result = $cat->add_type($obj, $type);
  652. if ($result < 0) {
  653. $this->error = $cat->error;
  654. $error++;
  655. }
  656. }
  657. }
  658. }
  659. } else {
  660. $error++;
  661. $this->error = $this->db->lasterror();
  662. }
  663. if ($error) {
  664. $this->db->rollback();
  665. return -1;
  666. }
  667. }
  668. // Call trigger
  669. $this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
  670. $result = $this->call_trigger('CATEGORY_LINK', $user);
  671. if ($result < 0) {
  672. $error++;
  673. }
  674. // End call triggers
  675. if (!$error) {
  676. $this->db->commit();
  677. return 1;
  678. } else {
  679. $this->db->rollback();
  680. return -2;
  681. }
  682. } else {
  683. $this->db->rollback();
  684. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  685. $this->error = $this->db->lasterrno();
  686. return -3;
  687. } else {
  688. $this->error = $this->db->lasterror();
  689. }
  690. return -1;
  691. }
  692. }
  693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  694. /**
  695. * Delete object from category
  696. *
  697. * @param CommonObject $obj Object
  698. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member')
  699. * @return int 1 if OK, -1 if KO
  700. * @see add_type()
  701. */
  702. public function del_type($obj, $type)
  703. {
  704. // phpcs:enable
  705. global $user, $langs, $conf;
  706. $error = 0;
  707. // For backward compatibility
  708. if ($type == 'societe') {
  709. $type = 'customer';
  710. dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
  711. } elseif ($type == 'fournisseur') {
  712. $type = 'supplier';
  713. dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
  714. }
  715. $this->db->begin();
  716. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  717. $sql .= " WHERE fk_categorie = ".((int) $this->id);
  718. $sql .= " AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $obj->id);
  719. dol_syslog(get_class($this).'::del_type', LOG_DEBUG);
  720. if ($this->db->query($sql)) {
  721. // Call trigger
  722. $this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
  723. $result = $this->call_trigger('CATEGORY_UNLINK', $user);
  724. if ($result < 0) {
  725. $error++;
  726. }
  727. // End call triggers
  728. if (!$error) {
  729. $this->db->commit();
  730. return 1;
  731. } else {
  732. $this->db->rollback();
  733. return -2;
  734. }
  735. } else {
  736. $this->db->rollback();
  737. $this->error = $this->db->lasterror();
  738. return -1;
  739. }
  740. }
  741. /**
  742. * Return list of fetched instance of elements having this category
  743. *
  744. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member', 'knowledge_management', ...)
  745. * @param int $onlyids Return only ids of objects (consume less memory)
  746. * @param int $limit Limit
  747. * @param int $offset Offset
  748. * @param string $sortfield Sort fields
  749. * @param string $sortorder Sort order ('ASC' or 'DESC');
  750. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customsql'=>...)
  751. * @param string $filtermode Filter mode (AND or OR)
  752. * @return array|int -1 if KO, array of instance of object if OK
  753. * @see containsObject()
  754. */
  755. public function getObjectsInCateg($type, $onlyids = 0, $limit = 0, $offset = 0, $sortfield = '', $sortorder = 'ASC', $filter = array(), $filtermode = 'AND')
  756. {
  757. global $user;
  758. $objs = array();
  759. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  760. $obj = new $classnameforobj($this->db);
  761. $sql = "SELECT c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]);
  762. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as c";
  763. $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." as o";
  764. $sql .= " WHERE o.entity IN (".getEntity($obj->element).")";
  765. $sql .= " AND c.fk_categorie = ".((int) $this->id);
  766. // Compatibility with actioncomm table which has id instead of rowid
  767. if ($this->MAP_OBJ_TABLE[$type] == "actioncomm" || $type == "actioncomm") {
  768. $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.id";
  769. } else {
  770. $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.rowid";
  771. }
  772. // Protection for external users
  773. if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) {
  774. $sql .= " AND o.rowid = ".((int) $user->socid);
  775. }
  776. // Manage filter
  777. $sqlwhere = array();
  778. if (count($filter) > 0) {
  779. foreach ($filter as $key => $value) {
  780. if ($key == 'o.rowid') {
  781. $sqlwhere[] = $key." = ".((int) $value);
  782. } elseif ($key == 'customsql') {
  783. $sqlwhere[] = $value;
  784. }
  785. }
  786. }
  787. if (count($sqlwhere) > 0) {
  788. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  789. }
  790. $sql .= $this->db->order($sortfield, $sortorder);
  791. if ($limit > 0 || $offset > 0) {
  792. $sql .= $this->db->plimit($limit + 1, $offset);
  793. }
  794. dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
  795. $resql = $this->db->query($sql);
  796. if ($resql) {
  797. while ($rec = $this->db->fetch_array($resql)) {
  798. if ($onlyids) {
  799. $objs[] = $rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])];
  800. } else {
  801. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  802. $obj = new $classnameforobj($this->db);
  803. $obj->fetch($rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]);
  804. $objs[] = $obj;
  805. }
  806. }
  807. return $objs;
  808. } else {
  809. $this->error = $this->db->error().' sql='.$sql;
  810. return -1;
  811. }
  812. }
  813. /**
  814. * Check for the presence of an object in a category
  815. *
  816. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member')
  817. * @param int $object_id Id of the object to search
  818. * @return int Number of occurrences
  819. * @see getObjectsInCateg()
  820. */
  821. public function containsObject($type, $object_id)
  822. {
  823. $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  824. $sql .= " WHERE fk_categorie = ".((int) $this->id)." AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $object_id);
  825. dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
  826. $resql = $this->db->query($sql);
  827. if ($resql) {
  828. return $this->db->fetch_object($resql)->nb;
  829. } else {
  830. $this->error = $this->db->error().' sql='.$sql;
  831. return -1;
  832. }
  833. }
  834. /**
  835. * List categories of an element id
  836. *
  837. * @param int $id Id of element
  838. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact')
  839. * @param string $sortfield Sort field
  840. * @param string $sortorder Sort order
  841. * @param int $limit Limit for list
  842. * @param int $page Page number
  843. * @return array|int Array of categories, 0 if no cat, -1 on error
  844. */
  845. public function getListForItem($id, $type = 'customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  846. {
  847. global $conf;
  848. $categories = array();
  849. $type = sanitizeVal($type, 'aZ09');
  850. $sub_type = $type;
  851. $subcol_name = "fk_".$type;
  852. if ($type == "customer") {
  853. $sub_type = "societe";
  854. $subcol_name = "fk_soc";
  855. }
  856. if ($type == "supplier") {
  857. $sub_type = "fournisseur";
  858. $subcol_name = "fk_soc";
  859. }
  860. if ($type == "contact") {
  861. $subcol_name = "fk_socpeople";
  862. }
  863. $idoftype = array_search($type, self::$MAP_ID_TO_CODE);
  864. $sql = "SELECT s.rowid";
  865. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s, ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub";
  866. $sql .= ' WHERE s.entity IN ('.getEntity('category').')';
  867. $sql .= ' AND s.type='.((int) $idoftype);
  868. $sql .= ' AND s.rowid = sub.fk_categorie';
  869. $sql .= " AND sub.".$subcol_name." = ".((int) $id);
  870. $sql .= $this->db->order($sortfield, $sortorder);
  871. $offset = 0;
  872. $nbtotalofrecords = '';
  873. if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
  874. $result = $this->db->query($sql);
  875. $nbtotalofrecords = $this->db->num_rows($result);
  876. if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
  877. $page = 0;
  878. $offset = 0;
  879. }
  880. }
  881. if ($limit) {
  882. if ($page < 0) {
  883. $page = 0;
  884. }
  885. $offset = $limit * $page;
  886. $sql .= $this->db->plimit($limit + 1, $offset);
  887. }
  888. $result = $this->db->query($sql);
  889. if ($result) {
  890. $i = 0;
  891. $num = $this->db->num_rows($result);
  892. $min = min($num, ($limit <= 0 ? $num : $limit));
  893. while ($i < $min) {
  894. $obj = $this->db->fetch_object($result);
  895. $category_static = new Categorie($this->db);
  896. if ($category_static->fetch($obj->rowid)) {
  897. $categories[$i]['id'] = $category_static->id;
  898. $categories[$i]['fk_parent'] = $category_static->fk_parent;
  899. $categories[$i]['label'] = $category_static->label;
  900. $categories[$i]['description'] = $category_static->description;
  901. $categories[$i]['color'] = $category_static->color;
  902. $categories[$i]['socid'] = $category_static->socid;
  903. $categories[$i]['ref_ext'] = $category_static->ref_ext;
  904. $categories[$i]['visible'] = $category_static->visible;
  905. $categories[$i]['type'] = $category_static->type;
  906. $categories[$i]['entity'] = $category_static->entity;
  907. $categories[$i]['array_options'] = $category_static->array_options;
  908. // multilangs
  909. if (getDolGlobalInt('MAIN_MULTILANGS') && isset($category_static->multilangs)) {
  910. $categories[$i]['multilangs'] = $category_static->multilangs;
  911. }
  912. }
  913. $i++;
  914. }
  915. } else {
  916. $this->error = $this->db->lasterror();
  917. return -1;
  918. }
  919. if (!count($categories)) {
  920. return 0;
  921. }
  922. return $categories;
  923. }
  924. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  925. /**
  926. * Return direct childs id of a category into an array
  927. *
  928. * @return array|int <0 KO, array ok
  929. */
  930. public function get_filles()
  931. {
  932. // phpcs:enable
  933. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  934. $sql .= " WHERE fk_parent = ".((int) $this->id);
  935. $sql .= " AND entity IN (".getEntity('category').")";
  936. $res = $this->db->query($sql);
  937. if ($res) {
  938. $cats = array();
  939. while ($rec = $this->db->fetch_array($res)) {
  940. $cat = new Categorie($this->db);
  941. $cat->fetch($rec['rowid']);
  942. $cats[] = $cat;
  943. }
  944. return $cats;
  945. } else {
  946. dol_print_error($this->db);
  947. return -1;
  948. }
  949. }
  950. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  951. /**
  952. * Load the array this->motherof that is array(id_son=>id_parent, ...)
  953. *
  954. * @return int <0 if KO, >0 if OK
  955. */
  956. protected function load_motherof()
  957. {
  958. // phpcs:enable
  959. $this->motherof = array();
  960. // Load array[child]=parent
  961. $sql = "SELECT fk_parent as id_parent, rowid as id_son";
  962. $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
  963. $sql .= " WHERE fk_parent != 0";
  964. $sql .= " AND entity IN (".getEntity('category').")";
  965. dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
  966. $resql = $this->db->query($sql);
  967. if ($resql) {
  968. while ($obj = $this->db->fetch_object($resql)) {
  969. $this->motherof[$obj->id_son] = $obj->id_parent;
  970. }
  971. return 1;
  972. } else {
  973. dol_print_error($this->db);
  974. return -1;
  975. }
  976. }
  977. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  978. /**
  979. * Rebuilding the category tree as an array
  980. * Return an array of table('id','id_mere',...) trie selon arbre et avec:
  981. * id = id de la categorie
  982. * id_mere = id de la categorie mere
  983. * id_children = tableau des id enfant
  984. * label = nom de la categorie
  985. * fulllabel = nom avec chemin complet de la categorie
  986. * fullpath = chemin complet compose des id
  987. *
  988. * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member', ...)
  989. * @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.
  990. * $markafterid can be an :
  991. * - int (id of category)
  992. * - string (categories ids separated by comma)
  993. * - array (list of categories ids)
  994. * @param int $include [=0] Removed or 1=Keep only
  995. * @return array|int Array of categories. this->cats and this->motherof are set, -1 on error
  996. */
  997. public function get_full_arbo($type, $markafterid = 0, $include = 0)
  998. {
  999. // phpcs:enable
  1000. global $conf, $langs;
  1001. if (!is_numeric($type)) {
  1002. $type = $this->MAP_ID[$type];
  1003. }
  1004. if (is_null($type)) {
  1005. $this->error = 'BadValueForParameterType';
  1006. return -1;
  1007. }
  1008. if (is_string($markafterid)) {
  1009. $markafterid = explode(',', $markafterid);
  1010. } elseif (is_numeric($markafterid)) {
  1011. if ($markafterid > 0) {
  1012. $markafterid = array($markafterid);
  1013. } else {
  1014. $markafterid = array();
  1015. }
  1016. } elseif (!is_array($markafterid)) {
  1017. $markafterid = array();
  1018. }
  1019. $this->cats = array();
  1020. // Init this->motherof that is array(id_son=>id_parent, ...)
  1021. $this->load_motherof();
  1022. $current_lang = $langs->getDefaultLang();
  1023. // Init $this->cats array
  1024. $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
  1025. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1026. $sql .= ", t.label as label_trans, t.description as description_trans";
  1027. }
  1028. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
  1029. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1030. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'";
  1031. }
  1032. $sql .= " WHERE c.entity IN (".getEntity('category').")";
  1033. $sql .= " AND c.type = ".(int) $type;
  1034. dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
  1035. $resql = $this->db->query($sql);
  1036. if ($resql) {
  1037. $i = 0;
  1038. while ($obj = $this->db->fetch_object($resql)) {
  1039. $this->cats[$obj->rowid]['rowid'] = $obj->rowid;
  1040. $this->cats[$obj->rowid]['id'] = $obj->rowid;
  1041. $this->cats[$obj->rowid]['fk_parent'] = $obj->fk_parent;
  1042. $this->cats[$obj->rowid]['label'] = !empty($obj->label_trans) ? $obj->label_trans : $obj->label;
  1043. $this->cats[$obj->rowid]['description'] = !empty($obj->description_trans) ? $obj->description_trans : $obj->description;
  1044. $this->cats[$obj->rowid]['color'] = $obj->color;
  1045. $this->cats[$obj->rowid]['visible'] = $obj->visible;
  1046. $this->cats[$obj->rowid]['ref_ext'] = $obj->ref_ext;
  1047. $this->cats[$obj->rowid]['picto'] = 'category';
  1048. $i++;
  1049. }
  1050. } else {
  1051. dol_print_error($this->db);
  1052. return -1;
  1053. }
  1054. // We add the fullpath property to each elements of first level (no parent exists)
  1055. dol_syslog(get_class($this)."::get_full_arbo call to buildPathFromId", LOG_DEBUG);
  1056. foreach ($this->cats as $key => $val) {
  1057. //print 'key='.$key.'<br>'."\n";
  1058. $this->buildPathFromId($key, 0); // Process a branch from the root category key (this category has no parent)
  1059. }
  1060. // Include or exclude leaf including $markafterid from tree
  1061. if (count($markafterid) > 0) {
  1062. $keyfiltercatid = '('.implode('|', $markafterid).')';
  1063. //print "Look to discard category ".$markafterid."\n";
  1064. $keyfilter1 = '^'.$keyfiltercatid.'$';
  1065. $keyfilter2 = '_'.$keyfiltercatid.'$';
  1066. $keyfilter3 = '^'.$keyfiltercatid.'_';
  1067. $keyfilter4 = '_'.$keyfiltercatid.'_';
  1068. foreach ($this->cats as $key => $val) {
  1069. $test = (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
  1070. || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath']));
  1071. if (($test && !$include) || (!$test && $include)) {
  1072. unset($this->cats[$key]);
  1073. }
  1074. }
  1075. }
  1076. dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
  1077. $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
  1078. return $this->cats;
  1079. }
  1080. /**
  1081. * For category id_categ and its childs available in this->cats, define property fullpath and fulllabel.
  1082. * It is called by get_full_arbo()
  1083. * This function is a memory scan only from $this->cats and $this->motherof, no database access must be done here.
  1084. *
  1085. * @param int $id_categ id_categ entry to update
  1086. * @param int $protection Deep counter to avoid infinite loop
  1087. * @return int <0 if KO, >0 if OK
  1088. * @see get_full_arbo()
  1089. */
  1090. private function buildPathFromId($id_categ, $protection = 1000)
  1091. {
  1092. //dol_syslog(get_class($this)."::buildPathFromId id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
  1093. if (!empty($this->cats[$id_categ]['fullpath'])) {
  1094. // Already defined
  1095. dol_syslog(get_class($this)."::buildPathFromId fullpath and fulllabel already defined", LOG_WARNING);
  1096. return -1;
  1097. }
  1098. // First build full array $motherof
  1099. //$this->load_motherof(); // Disabled because already done by caller of buildPathFromId
  1100. // $this->cats[$id_categ] is supposed to be already an array. We just want to complete it with property fullpath and fulllabel
  1101. // Define fullpath and fulllabel
  1102. $this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
  1103. $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
  1104. $i = 0; $cursor_categ = $id_categ;
  1105. //print 'Work for id_categ='.$id_categ.'<br>'."\n";
  1106. while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) {
  1107. //print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
  1108. $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
  1109. $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'];
  1110. //print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
  1111. $i++;
  1112. $cursor_categ = $this->motherof[$cursor_categ];
  1113. }
  1114. //print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'<br>'."\n";
  1115. // We count number of _ to have level
  1116. $nbunderscore = substr_count($this->cats[$id_categ]['fullpath'], '_');
  1117. $this->cats[$id_categ]['level'] = ($nbunderscore ? $nbunderscore : null);
  1118. return 1;
  1119. }
  1120. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1121. /**
  1122. * Returns all categories
  1123. *
  1124. * @param int $type Type of category (0, 1, ...)
  1125. * @param boolean $parent Just parent categories if true
  1126. * @return array|int Table of Object Category, -1 on error
  1127. */
  1128. public function get_all_categories($type = null, $parent = false)
  1129. {
  1130. // phpcs:enable
  1131. if (!is_numeric($type)) {
  1132. $type = $this->MAP_ID[$type];
  1133. }
  1134. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  1135. $sql .= " WHERE entity IN (".getEntity('category').")";
  1136. if (!is_null($type)) {
  1137. $sql .= " AND type = ".(int) $type;
  1138. }
  1139. if ($parent) {
  1140. $sql .= " AND fk_parent = 0";
  1141. }
  1142. $res = $this->db->query($sql);
  1143. if ($res) {
  1144. $cats = array();
  1145. while ($rec = $this->db->fetch_array($res)) {
  1146. $cat = new Categorie($this->db);
  1147. $cat->fetch($rec['rowid']);
  1148. $cats[$rec['rowid']] = $cat;
  1149. }
  1150. return $cats;
  1151. } else {
  1152. dol_print_error($this->db);
  1153. return -1;
  1154. }
  1155. }
  1156. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1157. /**
  1158. * Returns the top level categories (which are not child)
  1159. *
  1160. * @param int $type Type of category (0, 1, ...)
  1161. * @return array
  1162. */
  1163. public function get_main_categories($type = null)
  1164. {
  1165. // phpcs:enable
  1166. return $this->get_all_categories($type, true);
  1167. }
  1168. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1169. /**
  1170. * Check if no category with same label already exists for this cat's parent or root and for this cat's type
  1171. *
  1172. * @return integer 1 if already exist, 0 otherwise, -1 if error
  1173. */
  1174. public function already_exists()
  1175. {
  1176. // phpcs:enable
  1177. $type = $this->type;
  1178. if (!is_numeric($type)) {
  1179. $type = $this->MAP_ID[$type];
  1180. }
  1181. /* We have to select any rowid from llx_categorie which category's mother and label
  1182. * are equals to those of the calling category
  1183. */
  1184. $sql = "SELECT c.rowid";
  1185. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c ";
  1186. $sql .= " WHERE c.entity IN (".getEntity('category').")";
  1187. $sql .= " AND c.type = ".((int) $type);
  1188. $sql .= " AND c.fk_parent = ".((int) $this->fk_parent);
  1189. $sql .= " AND c.label = '".$this->db->escape($this->label)."'";
  1190. dol_syslog(get_class($this)."::already_exists", LOG_DEBUG);
  1191. $resql = $this->db->query($sql);
  1192. if ($resql) {
  1193. if ($this->db->num_rows($resql) > 0) { // Checking for empty resql
  1194. $obj = $this->db->fetch_array($resql);
  1195. /* If object called create, obj cannot have is id.
  1196. * If object called update, he mustn't have the same label as an other category for this mother.
  1197. * So if the result have the same id, update is not for label, and if result have an other one,
  1198. * update may be for label.
  1199. */
  1200. if ($obj[0] > 0 && $obj[0] != $this->id) {
  1201. 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);
  1202. return 1;
  1203. }
  1204. }
  1205. 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);
  1206. return 0;
  1207. } else {
  1208. $this->error = $this->db->error();
  1209. return -1;
  1210. }
  1211. }
  1212. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1213. /**
  1214. * Returns the path of the category, with the names of the categories
  1215. * separated by $sep (" >> " by default)
  1216. *
  1217. * @param string $sep Separator
  1218. * @param string $url Url ('', 'none' or 'urltouse')
  1219. * @param int $nocolor 0
  1220. * @param string $addpicto Add picto into link
  1221. * @return array
  1222. */
  1223. public function print_all_ways($sep = '&gt;&gt;', $url = '', $nocolor = 0, $addpicto = 0)
  1224. {
  1225. // phpcs:enable
  1226. $ways = array();
  1227. $allways = $this->get_all_ways(); // Load array of categories
  1228. foreach ($allways as $way) {
  1229. $w = array();
  1230. $i = 0;
  1231. $forced_color = '';
  1232. foreach ($way as $cat) {
  1233. $i++;
  1234. if (empty($nocolor)) {
  1235. $forced_color = 'colortoreplace';
  1236. if ($i == count($way)) { // Last category in hierarchy
  1237. // Check contrast with background and correct text color
  1238. $forced_color = 'categtextwhite';
  1239. if ($cat->color) {
  1240. if (colorIsLight($cat->color)) {
  1241. $forced_color = 'categtextblack';
  1242. }
  1243. }
  1244. }
  1245. }
  1246. if ($url == '') {
  1247. $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$cat->id.'&type='.$cat->type.'" class="'.$forced_color.'">';
  1248. $linkend = '</a>';
  1249. $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
  1250. } elseif ($url == 'none') {
  1251. $link = '<span class="'.$forced_color.'">';
  1252. $linkend = '</span>';
  1253. $w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
  1254. } else {
  1255. $w[] = '<a class="'.$forced_color.'" href="'.DOL_URL_ROOT.'/'.$url.'?catid='.$cat->id.'">'.($addpicto ? img_object('', 'category') : '').$cat->label.'</a>';
  1256. }
  1257. }
  1258. $newcategwithpath = preg_replace('/colortoreplace/', $forced_color, implode('<span class="inline-block valignmiddle paddingleft paddingright '.$forced_color.'">'.$sep.'</span>', $w));
  1259. $ways[] = $newcategwithpath;
  1260. }
  1261. return $ways;
  1262. }
  1263. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1264. /**
  1265. * Returns an array containing the list of parent categories
  1266. *
  1267. * @return int|array <0 KO, array OK
  1268. */
  1269. public function get_meres()
  1270. {
  1271. // phpcs:enable
  1272. $parents = array();
  1273. $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie";
  1274. $sql .= " WHERE rowid = ".((int) $this->id);
  1275. $res = $this->db->query($sql);
  1276. if ($res) {
  1277. while ($rec = $this->db->fetch_array($res)) {
  1278. if ($rec['fk_parent'] > 0) {
  1279. $cat = new Categorie($this->db);
  1280. $cat->fetch($rec['fk_parent']);
  1281. $parents[] = $cat;
  1282. }
  1283. }
  1284. return $parents;
  1285. } else {
  1286. dol_print_error($this->db);
  1287. return -1;
  1288. }
  1289. }
  1290. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1291. /**
  1292. * Returns in a table all possible paths to get to the category
  1293. * starting with the major categories represented by Tables of categories
  1294. *
  1295. * @return array
  1296. */
  1297. public function get_all_ways()
  1298. {
  1299. // phpcs:enable
  1300. $ways = array();
  1301. $parents = $this->get_meres();
  1302. if (is_array($parents)) {
  1303. foreach ($parents as $parent) {
  1304. $allways = $parent->get_all_ways();
  1305. foreach ($allways as $way) {
  1306. $w = $way;
  1307. $w[] = $this;
  1308. $ways[] = $w;
  1309. }
  1310. }
  1311. }
  1312. if (count($ways) == 0) {
  1313. $ways[0][0] = $this;
  1314. }
  1315. return $ways;
  1316. }
  1317. /**
  1318. * Return list of categories (object instances or labels) linked to element of id $id and type $type
  1319. * Should be named getListOfCategForObject
  1320. *
  1321. * @param int $id Id of element
  1322. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') or (0, 1, 2, ...)
  1323. * @param string $mode 'id'=Get array of category ids, 'object'=Get array of fetched category instances, 'label'=Get array of category
  1324. * labels, 'id'= Get array of category IDs
  1325. * @return Categorie[]|int Array of category objects or < 0 if KO
  1326. */
  1327. public function containing($id, $type, $mode = 'object')
  1328. {
  1329. $cats = array();
  1330. if (is_numeric($type)) {
  1331. $type = Categorie::$MAP_ID_TO_CODE[$type];
  1332. }
  1333. if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this with standard category code after migration of llx_bank_categ into llx_categorie
  1334. // Load bank categories
  1335. $sql = "SELECT c.label, c.rowid";
  1336. $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c";
  1337. $sql .= " WHERE a.lineid=".((int) $id)." AND a.fk_categ = c.rowid";
  1338. $sql .= " AND c.entity IN (".getEntity('category').")";
  1339. $sql .= " ORDER BY c.label";
  1340. $res = $this->db->query($sql);
  1341. if ($res) {
  1342. while ($obj = $this->db->fetch_object($res)) {
  1343. if ($mode == 'id') {
  1344. $cats[] = $obj->rowid;
  1345. } elseif ($mode == 'label') {
  1346. $cats[] = $obj->label;
  1347. } else {
  1348. $cat = new Categorie($this->db);
  1349. $cat->id = $obj->rowid;
  1350. $cat->label = $obj->label;
  1351. $cats[] = $cat;
  1352. }
  1353. }
  1354. } else {
  1355. dol_print_error($this->db);
  1356. return -1;
  1357. }
  1358. } else {
  1359. $sql = "SELECT ct.fk_categorie, c.label, c.rowid";
  1360. $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";
  1361. $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".(int) $id;
  1362. // This seems useless because the table already contains id of category of 1 unique type. So commented.
  1363. // So now it works also with external added categories.
  1364. //$sql .= " AND c.type = ".((int) $this->MAP_ID[$type]);
  1365. $sql .= " AND c.entity IN (".getEntity('category').")";
  1366. $res = $this->db->query($sql);
  1367. if ($res) {
  1368. while ($obj = $this->db->fetch_object($res)) {
  1369. if ($mode == 'id') {
  1370. $cats[] = $obj->rowid;
  1371. } elseif ($mode == 'label') {
  1372. $cats[] = $obj->label;
  1373. } else {
  1374. $cat = new Categorie($this->db);
  1375. $cat->fetch($obj->fk_categorie);
  1376. $cats[] = $cat;
  1377. }
  1378. }
  1379. } else {
  1380. dol_print_error($this->db);
  1381. return -1;
  1382. }
  1383. }
  1384. return $cats;
  1385. }
  1386. /**
  1387. * Returns categories whose id or name match
  1388. * add wildcards in the name unless $exact = true
  1389. *
  1390. * @param int $id Id
  1391. * @param string $nom Name
  1392. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  1393. * @param boolean $exact Exact string search (true/false)
  1394. * @param boolean $case Case sensitive (true/false)
  1395. * @return Categorie[]|int Array of Categorie, -1 if error
  1396. */
  1397. public function rechercher($id, $nom, $type, $exact = false, $case = false)
  1398. {
  1399. // Deprecation warning
  1400. if (is_numeric($type)) {
  1401. dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING);
  1402. }
  1403. $cats = array();
  1404. // For backward compatibility
  1405. if (is_numeric($type)) {
  1406. // We want to reverse lookup
  1407. $map_type = array_flip($this->MAP_ID);
  1408. $type = $map_type[$type];
  1409. dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING);
  1410. }
  1411. // Generation requete recherche
  1412. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  1413. $sql .= " WHERE type = ".((int) $this->MAP_ID[$type]);
  1414. $sql .= " AND entity IN (".getEntity('category').")";
  1415. if ($nom) {
  1416. if (!$exact) {
  1417. $nom = '%'.$this->db->escape(str_replace('*', '%', $nom)).'%';
  1418. }
  1419. if (!$case) {
  1420. $sql .= " AND label LIKE '".$this->db->escape($nom)."'";
  1421. } else {
  1422. $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
  1423. }
  1424. }
  1425. if ($id) {
  1426. $sql .= " AND rowid = ".((int) $id);
  1427. }
  1428. $res = $this->db->query($sql);
  1429. if ($res) {
  1430. while ($rec = $this->db->fetch_array($res)) {
  1431. $cat = new Categorie($this->db);
  1432. $cat->fetch($rec['rowid']);
  1433. $cats[] = $cat;
  1434. }
  1435. return $cats;
  1436. } else {
  1437. $this->error = $this->db->error().' sql='.$sql;
  1438. return -1;
  1439. }
  1440. }
  1441. /**
  1442. * getTooltipContentArray
  1443. * @param array $params params to construct tooltip data
  1444. * @since v18
  1445. * @return array
  1446. */
  1447. public function getTooltipContentArray($params)
  1448. {
  1449. global $langs;
  1450. $langs->load('categories');
  1451. $datas = [];
  1452. $datas['label'] = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
  1453. return $datas;
  1454. }
  1455. /**
  1456. * Return name and link of category (with picto)
  1457. * Use ->id, ->ref, ->label, ->color
  1458. *
  1459. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1460. * @param string $option Sur quoi pointe le lien ('', 'xyz')
  1461. * @param int $maxlength Max length of text
  1462. * @param string $moreparam More param on URL link
  1463. * @return string Chaine avec URL
  1464. */
  1465. public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $moreparam = '')
  1466. {
  1467. global $langs, $hookmanager;
  1468. $result = '';
  1469. $params = [
  1470. 'id' => $this->id,
  1471. 'objecttype' => $this->element,
  1472. 'option' => $option,
  1473. ];
  1474. $classfortooltip = 'classfortooltip';
  1475. $dataparams = '';
  1476. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  1477. $classfortooltip = 'classforajaxtooltip';
  1478. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  1479. $label = '';
  1480. } else {
  1481. $label = implode($this->getTooltipContentArray($params));
  1482. }
  1483. // Check contrast with background and correct text color
  1484. $forced_color = 'categtextwhite';
  1485. if ($this->color) {
  1486. if (colorIsLight($this->color)) {
  1487. $forced_color = 'categtextblack';
  1488. }
  1489. }
  1490. $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : ''));
  1491. $link .= '"'.$dataparams;
  1492. $link .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  1493. $link .= ' class="'.$classfortooltip.' '.$forced_color.'">';
  1494. $linkend = '</a>';
  1495. $picto = 'category';
  1496. if ($withpicto) {
  1497. $result .= ($link.img_object($label, $picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
  1498. }
  1499. if ($withpicto && $withpicto != 2) {
  1500. $result .= ' ';
  1501. }
  1502. if ($withpicto != 2) {
  1503. $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend;
  1504. }
  1505. global $action;
  1506. $hookmanager->initHooks(array($this->element . 'dao'));
  1507. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1508. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1509. if ($reshook > 0) {
  1510. $result = $hookmanager->resPrint;
  1511. } else {
  1512. $result .= $hookmanager->resPrint;
  1513. }
  1514. return $result;
  1515. }
  1516. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1517. /**
  1518. * Deplace fichier uploade sous le nom $file dans le repertoire sdir
  1519. *
  1520. * @param string $sdir Final destination directory
  1521. * @param array $file Uploaded file name
  1522. * @return void
  1523. */
  1524. public function add_photo($sdir, $file)
  1525. {
  1526. // phpcs:enable
  1527. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1528. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
  1529. $dir .= "photos/";
  1530. if (!file_exists($dir)) {
  1531. dol_mkdir($dir);
  1532. }
  1533. if (file_exists($dir)) {
  1534. if (is_array($file['name']) && count($file['name']) > 0) {
  1535. $nbfile = count($file['name']);
  1536. for ($i = 0; $i <= $nbfile; $i++) {
  1537. $originImage = $dir.$file['name'][$i];
  1538. // Cree fichier en taille origine
  1539. dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
  1540. if (file_exists($originImage)) {
  1541. // Create thumbs
  1542. $this->addThumbs($originImage);
  1543. }
  1544. }
  1545. } else {
  1546. $originImage = $dir.$file['name'];
  1547. // Cree fichier en taille origine
  1548. dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
  1549. if (file_exists($originImage)) {
  1550. // Create thumbs
  1551. $this->addThumbs($originImage);
  1552. }
  1553. }
  1554. }
  1555. }
  1556. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1557. /**
  1558. * Return tableau de toutes les photos de la categorie
  1559. *
  1560. * @param string $dir Repertoire a scanner
  1561. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  1562. * @return array Tableau de photos
  1563. */
  1564. public function liste_photos($dir, $nbmax = 0)
  1565. {
  1566. // phpcs:enable
  1567. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1568. $nbphoto = 0;
  1569. $tabobj = array();
  1570. $dirthumb = $dir.'thumbs/';
  1571. if (file_exists($dir)) {
  1572. $handle = opendir($dir);
  1573. if (is_resource($handle)) {
  1574. while (($file = readdir($handle)) !== false) {
  1575. if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) {
  1576. $nbphoto++;
  1577. $photo = $file;
  1578. // On determine nom du fichier vignette
  1579. $photo_vignette = '';
  1580. if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) {
  1581. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
  1582. }
  1583. // Objet
  1584. $obj = array();
  1585. $obj['photo'] = $photo;
  1586. if ($photo_vignette && is_file($dirthumb.$photo_vignette)) {
  1587. $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
  1588. } else {
  1589. $obj['photo_vignette'] = "";
  1590. }
  1591. $tabobj[$nbphoto - 1] = $obj;
  1592. // On continue ou on arrete de boucler
  1593. if ($nbmax && $nbphoto >= $nbmax) {
  1594. break;
  1595. }
  1596. }
  1597. }
  1598. closedir($handle);
  1599. }
  1600. }
  1601. return $tabobj;
  1602. }
  1603. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1604. /**
  1605. * Efface la photo de la categorie et sa vignette
  1606. *
  1607. * @param string $file Path to file
  1608. * @return void
  1609. */
  1610. public function delete_photo($file)
  1611. {
  1612. // phpcs:enable
  1613. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1614. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  1615. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
  1616. $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
  1617. // On efface l'image d'origine
  1618. dol_delete_file($file, 1);
  1619. // Si elle existe, on efface la vignette
  1620. if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs)) {
  1621. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
  1622. if (file_exists($dirthumb.$photo_vignette)) {
  1623. dol_delete_file($dirthumb.$photo_vignette, 1);
  1624. }
  1625. }
  1626. }
  1627. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1628. /**
  1629. * Load size of image file
  1630. *
  1631. * @param string $file Path to file
  1632. * @return void
  1633. */
  1634. public function get_image_size($file)
  1635. {
  1636. // phpcs:enable
  1637. $infoImg = getimagesize($file); // Recuperation des infos de l'image
  1638. $this->imgWidth = $infoImg[0]; // Largeur de l'image
  1639. $this->imgHeight = $infoImg[1]; // Hauteur de l'image
  1640. }
  1641. /**
  1642. * Update ou cree les traductions des infos produits
  1643. *
  1644. * @param User $user Object user
  1645. *
  1646. * @return int <0 if KO, >0 if OK
  1647. */
  1648. public function setMultiLangs($user)
  1649. {
  1650. global $langs;
  1651. $langs_available = $langs->get_available_languages();
  1652. $current_lang = $langs->getDefaultLang();
  1653. foreach ($langs_available as $key => $value) {
  1654. $sql = "SELECT rowid";
  1655. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
  1656. $sql .= " WHERE fk_category=".((int) $this->id);
  1657. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1658. $result = $this->db->query($sql);
  1659. if ($key == $current_lang) {
  1660. if ($this->db->num_rows($result)) { // si aucune ligne dans la base
  1661. $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
  1662. $sql2 .= " SET label = '".$this->db->escape($this->label)."',";
  1663. $sql2 .= " description = '".$this->db->escape($this->description)."'";
  1664. $sql2 .= " WHERE fk_category = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1665. } else {
  1666. $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
  1667. $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->label)."'";
  1668. $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["description"])."')";
  1669. }
  1670. dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
  1671. if (!$this->db->query($sql2)) {
  1672. $this->error = $this->db->lasterror();
  1673. return -1;
  1674. }
  1675. } elseif (isset($this->multilangs["$key"])) {
  1676. if ($this->db->num_rows($result)) { // si aucune ligne dans la base
  1677. $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
  1678. $sql2 .= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1679. $sql2 .= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1680. $sql2 .= " WHERE fk_category=".((int) $this->id)." AND lang='".$this->db->escape($key)."'";
  1681. } else {
  1682. $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
  1683. $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->multilangs["$key"]["label"])."'";
  1684. $sql2 .= ",'".$this->db->escape($this->multilangs["$key"]["description"])."')";
  1685. }
  1686. // on ne sauvegarde pas des champs vides
  1687. if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) {
  1688. dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
  1689. }
  1690. if (!$this->db->query($sql2)) {
  1691. $this->error = $this->db->lasterror();
  1692. return -1;
  1693. }
  1694. }
  1695. }
  1696. // Call trigger
  1697. $result = $this->call_trigger('CATEGORY_SET_MULTILANGS', $user);
  1698. if ($result < 0) {
  1699. $this->error = $this->db->lasterror();
  1700. return -1;
  1701. }
  1702. // End call triggers
  1703. return 1;
  1704. }
  1705. /**
  1706. * Load array this->multilangs
  1707. *
  1708. * @return int <0 if KO, >0 if OK
  1709. */
  1710. public function getMultiLangs()
  1711. {
  1712. global $langs;
  1713. $current_lang = $langs->getDefaultLang();
  1714. $sql = "SELECT lang, label, description";
  1715. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
  1716. $sql .= " WHERE fk_category=".((int) $this->id);
  1717. $result = $this->db->query($sql);
  1718. if ($result) {
  1719. while ($obj = $this->db->fetch_object($result)) {
  1720. //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
  1721. if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
  1722. $this->label = $obj->label;
  1723. $this->description = $obj->description;
  1724. }
  1725. $this->multilangs["$obj->lang"]["label"] = $obj->label;
  1726. $this->multilangs["$obj->lang"]["description"] = $obj->description;
  1727. }
  1728. return 1;
  1729. } else {
  1730. $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
  1731. return -1;
  1732. }
  1733. }
  1734. /**
  1735. * Return label of contact status
  1736. *
  1737. * @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
  1738. * @return string Label of contact status
  1739. */
  1740. public function getLibStatut($mode)
  1741. {
  1742. return '';
  1743. }
  1744. /**
  1745. * Initialise an instance with random values.
  1746. * Used to build previews or test instances.
  1747. * id must be 0 if object instance is a specimen.
  1748. *
  1749. * @return void
  1750. */
  1751. public function initAsSpecimen()
  1752. {
  1753. dol_syslog(get_class($this)."::initAsSpecimen");
  1754. // Initialise parametres
  1755. $this->id = 0;
  1756. $this->fk_parent = 0;
  1757. $this->label = 'SPECIMEN';
  1758. $this->specimen = 1;
  1759. $this->description = 'This is a description';
  1760. $this->socid = 1;
  1761. $this->type = self::TYPE_PRODUCT;
  1762. }
  1763. /**
  1764. * Function used to replace a thirdparty id with another one.
  1765. *
  1766. * @param DoliDB $dbs Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
  1767. * @param int $origin_id Old thirdparty id
  1768. * @param int $dest_id New thirdparty id
  1769. * @return bool
  1770. */
  1771. public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
  1772. {
  1773. $tables = array(
  1774. 'categorie_societe'
  1775. );
  1776. return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables, 1);
  1777. }
  1778. /**
  1779. * Return the addtional SQL JOIN query for filtering a list by a category
  1780. *
  1781. * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE)
  1782. * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid")
  1783. * @return string A additional SQL JOIN query
  1784. * @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)
  1785. */
  1786. public static function getFilterJoinQuery($type, $rowIdName)
  1787. {
  1788. if ($type == 'bank_account') {
  1789. $type = 'account';
  1790. }
  1791. return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type;
  1792. }
  1793. /**
  1794. * Return the addtional SQL SELECT query for filtering a list by a category
  1795. *
  1796. * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE)
  1797. * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid")
  1798. * @param Array $searchList A list with the selected categories
  1799. * @return string A additional SQL SELECT query
  1800. * @deprecated search on some categories must be done using a WHERE EXISTS or NOT EXISTS and not a LEFT JOIN
  1801. */
  1802. public static function getFilterSelectQuery($type, $rowIdName, $searchList)
  1803. {
  1804. if ($type == 'bank_account') {
  1805. $type = 'account';
  1806. }
  1807. if ($type == 'customer') {
  1808. $type = 'societe';
  1809. }
  1810. if ($type == 'supplier') {
  1811. $type = 'fournisseur';
  1812. }
  1813. if (empty($searchList) && !is_array($searchList)) {
  1814. return "";
  1815. }
  1816. $searchCategorySqlList = array();
  1817. foreach ($searchList as $searchCategory) {
  1818. if (intval($searchCategory) == -2) {
  1819. $searchCategorySqlList[] = " cp.fk_categorie IS NULL";
  1820. } elseif (intval($searchCategory) > 0) {
  1821. $searchCategorySqlList[] = " ".$rowIdName." IN (SELECT fk_".$type." FROM ".MAIN_DB_PREFIX."categorie_".$type." WHERE fk_categorie = ".((int) $searchCategory).")";
  1822. }
  1823. }
  1824. if (!empty($searchCategorySqlList)) {
  1825. return " AND (".implode(' AND ', $searchCategorySqlList).")";
  1826. } else {
  1827. return "";
  1828. }
  1829. }
  1830. /**
  1831. * Count all categories
  1832. *
  1833. * @return int Number of categories, -1 on error
  1834. */
  1835. public function countNbOfCategories()
  1836. {
  1837. dol_syslog(get_class($this)."::count_all_categories", LOG_DEBUG);
  1838. $sql = "SELECT COUNT(rowid) FROM ".MAIN_DB_PREFIX."categorie";
  1839. $sql .= " WHERE entity IN (".getEntity('category').")";
  1840. $res = $this->db->query($sql);
  1841. if ($res) {
  1842. $obj = $this->db->fetch_object($res);
  1843. return $obj->count;
  1844. } else {
  1845. dol_print_error($this->db);
  1846. return -1;
  1847. }
  1848. }
  1849. }