categorie.class.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058
  1. <?php
  2. /* Copyright (C) 2005 Matthieu Valleton <mv@seeschloss.org>
  3. * Copyright (C) 2005 Davoleau Brice <brice.davoleau@gmail.com>
  4. * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  5. * Copyright (C) 2006-2012 Regis Houssin <regis.houssin@inodbox.com>
  6. * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  7. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  8. * Copyright (C) 2013-2016 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2013-2018 Philippe Grand <philippe.grand@atoo-net.com>
  10. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  12. * Copyright (C) 2016 Charlie Benke <charlie@patas-monkey.com>
  13. * Copyright (C) 2018-2022 Frédéric France <frederic.france@netlogic.fr>
  14. * Copyright (C) 2023 Benjamin Falière <benjamin.faliere@altairis.fr>
  15. *
  16. * This program is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 3 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  28. */
  29. /**
  30. * \file htdocs/categories/class/categorie.class.php
  31. * \ingroup categorie
  32. * \brief File of class to manage categories
  33. */
  34. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/knowledgemanagement/class/knowledgerecord.class.php';
  40. /**
  41. * Class to manage categories
  42. */
  43. class Categorie extends CommonObject
  44. {
  45. // Categories types (we use string because we want to accept any modules/types in a future)
  46. const TYPE_PRODUCT = 'product';
  47. const TYPE_SUPPLIER = 'supplier';
  48. const TYPE_CUSTOMER = 'customer';
  49. const TYPE_MEMBER = 'member';
  50. const TYPE_CONTACT = 'contact';
  51. const TYPE_USER = 'user';
  52. const TYPE_PROJECT = 'project';
  53. const TYPE_ACCOUNT = 'bank_account';
  54. const TYPE_BANK_LINE = 'bank_line';
  55. const TYPE_WAREHOUSE = 'warehouse';
  56. const TYPE_ACTIONCOMM = 'actioncomm';
  57. const TYPE_WEBSITE_PAGE = 'website_page';
  58. const TYPE_TICKET = 'ticket';
  59. const TYPE_KNOWLEDGEMANAGEMENT = 'knowledgemanagement';
  60. /**
  61. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  62. */
  63. public $picto = 'category';
  64. /**
  65. * @var array Table of mapping between type string and ID used for field 'type' in table llx_categories
  66. */
  67. protected $MAP_ID = array(
  68. 'product' => 0,
  69. 'supplier' => 1,
  70. 'customer' => 2,
  71. 'member' => 3,
  72. 'contact' => 4,
  73. 'bank_account' => 5,
  74. 'project' => 6,
  75. 'user' => 7,
  76. 'bank_line' => 8,
  77. 'warehouse' => 9,
  78. 'actioncomm' => 10,
  79. 'website_page' => 11,
  80. 'ticket' => 12,
  81. 'knowledgemanagement' => 13
  82. );
  83. /**
  84. * @var array Code mapping from ID
  85. *
  86. * @note This array should be removed in future, once previous constants are moved to the string value. Deprecated
  87. */
  88. public static $MAP_ID_TO_CODE = array(
  89. 0 => 'product',
  90. 1 => 'supplier',
  91. 2 => 'customer',
  92. 3 => 'member',
  93. 4 => 'contact',
  94. 5 => 'bank_account',
  95. 6 => 'project',
  96. 7 => 'user',
  97. 8 => 'bank_line',
  98. 9 => 'warehouse',
  99. 10 => 'actioncomm',
  100. 11 => 'website_page',
  101. 12 => 'ticket',
  102. 13 => 'knowledgemanagement'
  103. );
  104. /**
  105. * @var array Foreign keys mapping from type string when value does not match
  106. *
  107. * @todo Move to const array when PHP 5.6 will be our minimum target
  108. */
  109. public $MAP_CAT_FK = array(
  110. 'customer' => 'soc',
  111. 'supplier' => 'soc',
  112. 'contact' => 'socpeople',
  113. 'bank_account' => 'account',
  114. );
  115. /**
  116. * @var array Category tables mapping from type string (llx_categorie_...) when value does not match
  117. *
  118. * @note Move to const array when PHP 5.6 will be our minimum target
  119. */
  120. public $MAP_CAT_TABLE = array(
  121. 'customer' => 'societe',
  122. 'supplier' => 'fournisseur',
  123. 'bank_account'=> 'account',
  124. );
  125. /**
  126. * @var array Object class mapping from type string
  127. *
  128. * @note Move to const array when PHP 5.6 will be our minimum target
  129. */
  130. public $MAP_OBJ_CLASS = array(
  131. 'product' => 'Product',
  132. 'customer' => 'Societe',
  133. 'supplier' => 'Fournisseur',
  134. 'member' => 'Adherent',
  135. 'contact' => 'Contact',
  136. 'user' => 'User',
  137. 'account' => 'Account', // old for bank account
  138. 'bank_account' => 'Account',
  139. 'project' => 'Project',
  140. 'warehouse'=> 'Entrepot',
  141. 'actioncomm' => 'ActionComm',
  142. 'website_page' => 'WebsitePage',
  143. 'ticket' => 'Ticket',
  144. 'knowledgemanagement' => 'KnowledgeRecord'
  145. );
  146. /**
  147. * @var array Title Area mapping from type string
  148. *
  149. * @note Move to const array when PHP 5.6 will be our minimum target
  150. */
  151. public static $MAP_TYPE_TITLE_AREA = array(
  152. 'product' => 'ProductsCategoriesArea',
  153. 'customer' => 'CustomersCategoriesArea',
  154. 'supplier' => 'SuppliersCategoriesArea',
  155. 'member' => 'MembersCategoriesArea',
  156. 'contact' => 'ContactsCategoriesArea',
  157. 'user' => 'UsersCategoriesArea',
  158. 'account' => 'AccountsCategoriesArea', // old for bank account
  159. 'bank_account' => 'AccountsCategoriesArea',
  160. 'project' => 'ProjectsCategoriesArea',
  161. 'warehouse'=> 'StocksCategoriesArea',
  162. 'actioncomm' => 'ActioncommCategoriesArea',
  163. 'website_page' => 'WebsitePageCategoriesArea'
  164. );
  165. /**
  166. * @var array Object table mapping from type string (table llx_...) when value of key does not match table name.
  167. * This array may be completed by external modules with hook "constructCategory"
  168. */
  169. public $MAP_OBJ_TABLE = array(
  170. 'customer' => 'societe',
  171. 'supplier' => 'societe',
  172. 'member' => 'adherent',
  173. 'contact' => 'socpeople',
  174. 'account' => 'bank_account', // old for bank account
  175. 'project' => 'projet',
  176. 'warehouse'=> 'entrepot',
  177. 'knowledgemanagement' => 'knowledgemanagement_knowledgerecord'
  178. );
  179. /**
  180. * @var string ID to identify managed object
  181. */
  182. public $element = 'category';
  183. /**
  184. * @var string Name of table without prefix where object is stored
  185. */
  186. public $table_element = 'categorie';
  187. /**
  188. * @var int ID
  189. */
  190. public $fk_parent;
  191. /**
  192. * @var string Category label
  193. */
  194. public $label;
  195. /**
  196. * @var string description
  197. */
  198. public $description;
  199. /**
  200. * @var string Color
  201. */
  202. public $color;
  203. /**
  204. * @var int Visible
  205. */
  206. public $visible;
  207. /**
  208. * @var int Id of thirdparty when CATEGORY_ASSIGNED_TO_A_CUSTOMER is set
  209. */
  210. public $socid;
  211. /**
  212. * @var string Category type
  213. *
  214. * @see Categorie::TYPE_PRODUCT
  215. * @see Categorie::TYPE_SUPPLIER
  216. * @see Categorie::TYPE_CUSTOMER
  217. * @see Categorie::TYPE_MEMBER
  218. * @see Categorie::TYPE_CONTACT
  219. * @see Categorie::TYPE_USER
  220. * @see Categorie::TYPE_PROJECT
  221. * @see Categorie::TYPE_ACCOUNT
  222. * @see Categorie::TYPE_BANK_LINE
  223. * @see Categorie::TYPE_WAREHOUSE
  224. * @see Categorie::TYPE_ACTIONCOMM
  225. * @see Categorie::TYPE_WEBSITE_PAGE
  226. * @see Categorie::TYPE_TICKET
  227. */
  228. public $type;
  229. /**
  230. * @var array Categories table in memory
  231. */
  232. public $cats = array();
  233. /**
  234. * @var array Mother of table
  235. */
  236. public $motherof = array();
  237. /**
  238. * @var array Childs
  239. */
  240. public $childs = array();
  241. /**
  242. * Constructor
  243. *
  244. * @param DoliDB $db Database handler
  245. */
  246. public function __construct($db)
  247. {
  248. global $hookmanager;
  249. $this->db = $db;
  250. if (is_object($hookmanager)) {
  251. $hookmanager->initHooks(array('category'));
  252. $parameters = array();
  253. $reshook = $hookmanager->executeHooks('constructCategory', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  254. if ($reshook >= 0 && !empty($hookmanager->resArray)) {
  255. foreach ($hookmanager->resArray as $mapList) {
  256. $mapId = $mapList['id'];
  257. $mapCode = $mapList['code'];
  258. self::$MAP_ID_TO_CODE[$mapId] = $mapCode;
  259. $this->MAP_ID[$mapCode] = $mapId;
  260. $this->MAP_CAT_FK[$mapCode] = $mapList['cat_fk'];
  261. $this->MAP_CAT_TABLE[$mapCode] = $mapList['cat_table'];
  262. $this->MAP_OBJ_CLASS[$mapCode] = $mapList['obj_class'];
  263. $this->MAP_OBJ_TABLE[$mapCode] = $mapList['obj_table'];
  264. }
  265. }
  266. }
  267. }
  268. /**
  269. * Get map list
  270. *
  271. * @return array
  272. */
  273. public function getMapList()
  274. {
  275. $mapList = array();
  276. foreach ($this->MAP_ID as $mapCode => $mapId) {
  277. $mapList[] = array(
  278. 'id' => $mapId,
  279. 'code' => $mapCode,
  280. 'cat_fk' => (empty($this->MAP_CAT_FK[$mapCode]) ? $mapCode : $this->MAP_CAT_FK[$mapCode]),
  281. 'cat_table' => (empty($this->MAP_CAT_TABLE[$mapCode]) ? $mapCode : $this->MAP_CAT_TABLE[$mapCode]),
  282. 'obj_class' => (empty($this->MAP_OBJ_CLASS[$mapCode]) ? $mapCode : $this->MAP_OBJ_CLASS[$mapCode]),
  283. 'obj_table' => (empty($this->MAP_OBJ_TABLE[$mapCode]) ? $mapCode : $this->MAP_OBJ_TABLE[$mapCode])
  284. );
  285. }
  286. return $mapList;
  287. }
  288. /**
  289. * Load category into memory from database
  290. *
  291. * @param int $id Id of category
  292. * @param string $label Label of category
  293. * @param string $type Type of category ('product', '...') or (0, 1, ...)
  294. * @param string $ref_ext External reference of object
  295. * @return int <0 if KO, >0 if OK
  296. */
  297. public function fetch($id, $label = '', $type = null, $ref_ext = '')
  298. {
  299. global $conf;
  300. // Check parameters
  301. if (empty($id) && empty($label) && empty($ref_ext)) {
  302. $this->error = "No category to search for";
  303. return -1;
  304. }
  305. if (!is_null($type) && !is_numeric($type)) {
  306. $type = $this->MAP_ID[$type];
  307. }
  308. $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext";
  309. $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif";
  310. $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
  311. if ($id) {
  312. $sql .= " WHERE rowid = ".((int) $id);
  313. } elseif (!empty($ref_ext)) {
  314. $sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'";
  315. } else {
  316. $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")";
  317. if (!is_null($type)) {
  318. $sql .= " AND type = ".((int) $type);
  319. }
  320. }
  321. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  322. $resql = $this->db->query($sql);
  323. if ($resql) {
  324. if ($this->db->num_rows($resql) > 0) {
  325. $res = $this->db->fetch_array($resql);
  326. $this->id = $res['rowid'];
  327. //$this->ref = $res['rowid'];
  328. $this->fk_parent = (int) $res['fk_parent'];
  329. $this->label = $res['label'];
  330. $this->description = $res['description'];
  331. $this->color = $res['color'];
  332. $this->socid = (int) $res['fk_soc'];
  333. $this->visible = (int) $res['visible'];
  334. $this->type = (int) $res['type'];
  335. $this->ref_ext = $res['ref_ext'];
  336. $this->entity = (int) $res['entity'];
  337. $this->date_creation = $this->db->jdate($res['date_creation']);
  338. $this->date_modification = $this->db->jdate($res['tms']);
  339. $this->user_creation_id = (int) $res['fk_user_creat'];
  340. $this->user_modification_id = (int) $res['fk_user_modif'];
  341. $this->user_creation = (int) $res['fk_user_creat'];
  342. $this->user_modification = (int) $res['fk_user_modif'];
  343. // Retrieve all extrafield
  344. // fetch optionals attributes and labels
  345. $this->fetch_optionals();
  346. $this->db->free($resql);
  347. // multilangs
  348. if (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. * @return array|int -1 if KO, array of instance of object if OK
  751. * @see containsObject()
  752. */
  753. public function getObjectsInCateg($type, $onlyids = 0, $limit = 0, $offset = 0, $sortfield = '', $sortorder = 'ASC')
  754. {
  755. global $user;
  756. $objs = array();
  757. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  758. $obj = new $classnameforobj($this->db);
  759. $sql = "SELECT c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]);
  760. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as c";
  761. $sql .= ", ".MAIN_DB_PREFIX.(empty($this->MAP_OBJ_TABLE[$type]) ? $type : $this->MAP_OBJ_TABLE[$type])." as o";
  762. $sql .= " WHERE o.entity IN (".getEntity($obj->element).")";
  763. $sql .= " AND c.fk_categorie = ".((int) $this->id);
  764. $sql .= " AND c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = o.rowid";
  765. // Protection for external users
  766. if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) {
  767. $sql .= " AND o.rowid = ".((int) $user->socid);
  768. }
  769. $sql .= $this->db->order($sortfield, $sortorder);
  770. if ($limit > 0 || $offset > 0) {
  771. $sql .= $this->db->plimit($limit + 1, $offset);
  772. }
  773. dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
  774. $resql = $this->db->query($sql);
  775. if ($resql) {
  776. while ($rec = $this->db->fetch_array($resql)) {
  777. if ($onlyids) {
  778. $objs[] = $rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])];
  779. } else {
  780. $classnameforobj = $this->MAP_OBJ_CLASS[$type];
  781. $obj = new $classnameforobj($this->db);
  782. $obj->fetch($rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]);
  783. $objs[] = $obj;
  784. }
  785. }
  786. return $objs;
  787. } else {
  788. $this->error = $this->db->error().' sql='.$sql;
  789. return -1;
  790. }
  791. }
  792. /**
  793. * Check for the presence of an object in a category
  794. *
  795. * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member')
  796. * @param int $object_id Id of the object to search
  797. * @return int Number of occurrences
  798. * @see getObjectsInCateg()
  799. */
  800. public function containsObject($type, $object_id)
  801. {
  802. $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]);
  803. $sql .= " WHERE fk_categorie = ".((int) $this->id)." AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".((int) $object_id);
  804. dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
  805. $resql = $this->db->query($sql);
  806. if ($resql) {
  807. return $this->db->fetch_object($resql)->nb;
  808. } else {
  809. $this->error = $this->db->error().' sql='.$sql;
  810. return -1;
  811. }
  812. }
  813. /**
  814. * List categories of an element id
  815. *
  816. * @param int $id Id of element
  817. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact')
  818. * @param string $sortfield Sort field
  819. * @param string $sortorder Sort order
  820. * @param int $limit Limit for list
  821. * @param int $page Page number
  822. * @return array|int Array of categories, 0 if no cat, -1 on error
  823. */
  824. public function getListForItem($id, $type = 'customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  825. {
  826. global $conf;
  827. $categories = array();
  828. $type = sanitizeVal($type, 'aZ09');
  829. $sub_type = $type;
  830. $subcol_name = "fk_".$type;
  831. if ($type == "customer") {
  832. $sub_type = "societe";
  833. $subcol_name = "fk_soc";
  834. }
  835. if ($type == "supplier") {
  836. $sub_type = "fournisseur";
  837. $subcol_name = "fk_soc";
  838. }
  839. if ($type == "contact") {
  840. $subcol_name = "fk_socpeople";
  841. }
  842. $idoftype = array_search($type, self::$MAP_ID_TO_CODE);
  843. $sql = "SELECT s.rowid";
  844. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s, ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub";
  845. $sql .= ' WHERE s.entity IN ('.getEntity('category').')';
  846. $sql .= ' AND s.type='.((int) $idoftype);
  847. $sql .= ' AND s.rowid = sub.fk_categorie';
  848. $sql .= " AND sub.".$subcol_name." = ".((int) $id);
  849. $sql .= $this->db->order($sortfield, $sortorder);
  850. $offset = 0;
  851. $nbtotalofrecords = '';
  852. if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
  853. $result = $this->db->query($sql);
  854. $nbtotalofrecords = $this->db->num_rows($result);
  855. if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
  856. $page = 0;
  857. $offset = 0;
  858. }
  859. }
  860. if ($limit) {
  861. if ($page < 0) {
  862. $page = 0;
  863. }
  864. $offset = $limit * $page;
  865. $sql .= $this->db->plimit($limit + 1, $offset);
  866. }
  867. $result = $this->db->query($sql);
  868. if ($result) {
  869. $i = 0;
  870. $num = $this->db->num_rows($result);
  871. $min = min($num, ($limit <= 0 ? $num : $limit));
  872. while ($i < $min) {
  873. $obj = $this->db->fetch_object($result);
  874. $category_static = new Categorie($this->db);
  875. if ($category_static->fetch($obj->rowid)) {
  876. $categories[$i]['id'] = $category_static->id;
  877. $categories[$i]['fk_parent'] = $category_static->fk_parent;
  878. $categories[$i]['label'] = $category_static->label;
  879. $categories[$i]['description'] = $category_static->description;
  880. $categories[$i]['color'] = $category_static->color;
  881. $categories[$i]['socid'] = $category_static->socid;
  882. $categories[$i]['ref_ext'] = $category_static->ref_ext;
  883. $categories[$i]['visible'] = $category_static->visible;
  884. $categories[$i]['type'] = $category_static->type;
  885. $categories[$i]['entity'] = $category_static->entity;
  886. $categories[$i]['array_options'] = $category_static->array_options;
  887. // multilangs
  888. if (getDolGlobalInt('MAIN_MULTILANGS') && isset($category_static->multilangs)) {
  889. $categories[$i]['multilangs'] = $category_static->multilangs;
  890. }
  891. }
  892. $i++;
  893. }
  894. } else {
  895. $this->error = $this->db->lasterror();
  896. return -1;
  897. }
  898. if (!count($categories)) {
  899. return 0;
  900. }
  901. return $categories;
  902. }
  903. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  904. /**
  905. * Return direct childs id of a category into an array
  906. *
  907. * @return array|int <0 KO, array ok
  908. */
  909. public function get_filles()
  910. {
  911. // phpcs:enable
  912. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
  913. $sql .= " WHERE fk_parent = ".((int) $this->id);
  914. $sql .= " AND entity IN (".getEntity('category').")";
  915. $res = $this->db->query($sql);
  916. if ($res) {
  917. $cats = array();
  918. while ($rec = $this->db->fetch_array($res)) {
  919. $cat = new Categorie($this->db);
  920. $cat->fetch($rec['rowid']);
  921. $cats[] = $cat;
  922. }
  923. return $cats;
  924. } else {
  925. dol_print_error($this->db);
  926. return -1;
  927. }
  928. }
  929. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  930. /**
  931. * Load the array this->motherof that is array(id_son=>id_parent, ...)
  932. *
  933. * @return int <0 if KO, >0 if OK
  934. */
  935. protected function load_motherof()
  936. {
  937. // phpcs:enable
  938. $this->motherof = array();
  939. // Load array[child]=parent
  940. $sql = "SELECT fk_parent as id_parent, rowid as id_son";
  941. $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
  942. $sql .= " WHERE fk_parent != 0";
  943. $sql .= " AND entity IN (".getEntity('category').")";
  944. dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
  945. $resql = $this->db->query($sql);
  946. if ($resql) {
  947. while ($obj = $this->db->fetch_object($resql)) {
  948. $this->motherof[$obj->id_son] = $obj->id_parent;
  949. }
  950. return 1;
  951. } else {
  952. dol_print_error($this->db);
  953. return -1;
  954. }
  955. }
  956. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  957. /**
  958. * Rebuilding the category tree as an array
  959. * Return an array of table('id','id_mere',...) trie selon arbre et avec:
  960. * id = id de la categorie
  961. * id_mere = id de la categorie mere
  962. * id_children = tableau des id enfant
  963. * label = nom de la categorie
  964. * fulllabel = nom avec chemin complet de la categorie
  965. * fullpath = chemin complet compose des id
  966. *
  967. * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member', ...)
  968. * @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.
  969. * $markafterid can be an :
  970. * - int (id of category)
  971. * - string (categories ids separated by comma)
  972. * - array (list of categories ids)
  973. * @param int $include [=0] Removed or 1=Keep only
  974. * @return array|int Array of categories. this->cats and this->motherof are set, -1 on error
  975. */
  976. public function get_full_arbo($type, $markafterid = 0, $include = 0)
  977. {
  978. // phpcs:enable
  979. global $conf, $langs;
  980. if (!is_numeric($type)) {
  981. $type = $this->MAP_ID[$type];
  982. }
  983. if (is_null($type)) {
  984. $this->error = 'BadValueForParameterType';
  985. return -1;
  986. }
  987. if (is_string($markafterid)) {
  988. $markafterid = explode(',', $markafterid);
  989. } elseif (is_numeric($markafterid)) {
  990. if ($markafterid > 0) {
  991. $markafterid = array($markafterid);
  992. } else {
  993. $markafterid = array();
  994. }
  995. } elseif (!is_array($markafterid)) {
  996. $markafterid = array();
  997. }
  998. $this->cats = array();
  999. // Init this->motherof that is array(id_son=>id_parent, ...)
  1000. $this->load_motherof();
  1001. $current_lang = $langs->getDefaultLang();
  1002. // Init $this->cats array
  1003. $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
  1004. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1005. $sql .= ", t.label as label_trans, t.description as description_trans";
  1006. }
  1007. $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
  1008. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1009. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'";
  1010. }
  1011. $sql .= " WHERE c.entity IN (".getEntity('category').")";
  1012. $sql .= " AND c.type = ".(int) $type;
  1013. dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
  1014. $resql = $this->db->query($sql);
  1015. if ($resql) {
  1016. $i = 0;
  1017. while ($obj = $this->db->fetch_object($resql)) {
  1018. $this->cats[$obj->rowid]['rowid'] = $obj->rowid;
  1019. $this->cats[$obj->rowid]['id'] = $obj->rowid;
  1020. $this->cats[$obj->rowid]['fk_parent'] = $obj->fk_parent;
  1021. $this->cats[$obj->rowid]['label'] = !empty($obj->label_trans) ? $obj->label_trans : $obj->label;
  1022. $this->cats[$obj->rowid]['description'] = !empty($obj->description_trans) ? $obj->description_trans : $obj->description;
  1023. $this->cats[$obj->rowid]['color'] = $obj->color;
  1024. $this->cats[$obj->rowid]['visible'] = $obj->visible;
  1025. $this->cats[$obj->rowid]['ref_ext'] = $obj->ref_ext;
  1026. $this->cats[$obj->rowid]['picto'] = 'category';
  1027. $i++;
  1028. }
  1029. } else {
  1030. dol_print_error($this->db);
  1031. return -1;
  1032. }
  1033. // We add the fullpath property to each elements of first level (no parent exists)
  1034. dol_syslog(get_class($this)."::get_full_arbo call to buildPathFromId", LOG_DEBUG);
  1035. foreach ($this->cats as $key => $val) {
  1036. //print 'key='.$key.'<br>'."\n";
  1037. $this->buildPathFromId($key, 0); // Process a branch from the root category key (this category has no parent)
  1038. }
  1039. // Include or exclude leaf including $markafterid from tree
  1040. if (count($markafterid) > 0) {
  1041. $keyfiltercatid = '('.implode('|', $markafterid).')';
  1042. //print "Look to discard category ".$markafterid."\n";
  1043. $keyfilter1 = '^'.$keyfiltercatid.'$';
  1044. $keyfilter2 = '_'.$keyfiltercatid.'$';
  1045. $keyfilter3 = '^'.$keyfiltercatid.'_';
  1046. $keyfilter4 = '_'.$keyfiltercatid.'_';
  1047. foreach ($this->cats as $key => $val) {
  1048. $test = (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
  1049. || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath']));
  1050. if (($test && !$include) || (!$test && $include)) {
  1051. unset($this->cats[$key]);
  1052. }
  1053. }
  1054. }
  1055. dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
  1056. $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
  1057. //$this->debug_cats();
  1058. return $this->cats;
  1059. }
  1060. /**
  1061. * For category id_categ and its childs available in this->cats, define property fullpath and fulllabel.
  1062. * It is called by get_full_arbo()
  1063. * This function is a memory scan only from $this->cats and $this->motherof, no database access must be done here.
  1064. *
  1065. * @param int $id_categ id_categ entry to update
  1066. * @param int $protection Deep counter to avoid infinite loop
  1067. * @return void
  1068. * @see get_full_arbo()
  1069. */
  1070. private function buildPathFromId($id_categ, $protection = 1000)
  1071. {
  1072. //dol_syslog(get_class($this)."::buildPathFromId id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
  1073. if (!empty($this->cats[$id_categ]['fullpath'])) {
  1074. // Already defined
  1075. dol_syslog(get_class($this)."::buildPathFromId fullpath and fulllabel already defined", LOG_WARNING);
  1076. return;
  1077. }
  1078. // First build full array $motherof
  1079. //$this->load_motherof(); // Disabled because already done by caller of buildPathFromId
  1080. // $this->cats[$id_categ] is supposed to be already an array. We just want to complete it with property fullpath and fulllabel
  1081. // Define fullpath and fulllabel
  1082. $this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
  1083. $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
  1084. $i = 0; $cursor_categ = $id_categ;
  1085. //print 'Work for id_categ='.$id_categ.'<br>'."\n";
  1086. while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) {
  1087. //print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
  1088. $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
  1089. $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'];
  1090. //print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
  1091. $i++;
  1092. $cursor_categ = $this->motherof[$cursor_categ];
  1093. }
  1094. //print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'<br>'."\n";
  1095. // We count number of _ to have level
  1096. $nbunderscore = substr_count($this->cats[$id_categ]['fullpath'], '_');
  1097. $this->cats[$id_categ]['level'] = ($nbunderscore ? $nbunderscore : null);
  1098. return;
  1099. }
  1100. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1101. /**
  1102. * Display content of $this->cats
  1103. *
  1104. * @return void
  1105. */
  1106. public function debug_cats()
  1107. {
  1108. // phpcs:enable
  1109. // Display $this->cats
  1110. foreach ($this->cats as $key => $val) {
  1111. print 'id: '.$this->cats[$key]['id'];
  1112. print ' label: '.$this->cats[$key]['label'];
  1113. print ' mother: '.$this->cats[$key]['fk_parent'];
  1114. //print ' children: '.(is_array($this->cats[$key]['id_children'])?join(',',$this->cats[$key]['id_children']):'');
  1115. print ' fullpath: '.$this->cats[$key]['fullpath'];
  1116. print ' fulllabel: '.$this->cats[$key]['fulllabel'];
  1117. print "<br>\n";
  1118. }
  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. * Return name and link of category (with picto)
  1443. * Use ->id, ->ref, ->label, ->color
  1444. *
  1445. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1446. * @param string $option Sur quoi pointe le lien ('', 'xyz')
  1447. * @param int $maxlength Max length of text
  1448. * @param string $moreparam More param on URL link
  1449. * @return string Chaine avec URL
  1450. */
  1451. public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $moreparam = '')
  1452. {
  1453. global $langs, $hookmanager;
  1454. $result = '';
  1455. $label = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
  1456. // Check contrast with background and correct text color
  1457. $forced_color = 'categtextwhite';
  1458. if ($this->color) {
  1459. if (colorIsLight($this->color)) {
  1460. $forced_color = 'categtextblack';
  1461. }
  1462. }
  1463. $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.$moreparam.'&backtopage='.urlencode($_SERVER['PHP_SELF'].($moreparam ? '?'.$moreparam : '')).'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip '.$forced_color.'">';
  1464. $linkend = '</a>';
  1465. $picto = 'category';
  1466. if ($withpicto) {
  1467. $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
  1468. }
  1469. if ($withpicto && $withpicto != 2) {
  1470. $result .= ' ';
  1471. }
  1472. if ($withpicto != 2) {
  1473. $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend;
  1474. }
  1475. global $action;
  1476. $hookmanager->initHooks(array($this->element . 'dao'));
  1477. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1478. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1479. if ($reshook > 0) {
  1480. $result = $hookmanager->resPrint;
  1481. } else {
  1482. $result .= $hookmanager->resPrint;
  1483. }
  1484. return $result;
  1485. }
  1486. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1487. /**
  1488. * Deplace fichier uploade sous le nom $file dans le repertoire sdir
  1489. *
  1490. * @param string $sdir Final destination directory
  1491. * @param array $file Uploaded file name
  1492. * @return void
  1493. */
  1494. public function add_photo($sdir, $file)
  1495. {
  1496. // phpcs:enable
  1497. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1498. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
  1499. $dir .= "photos/";
  1500. if (!file_exists($dir)) {
  1501. dol_mkdir($dir);
  1502. }
  1503. if (file_exists($dir)) {
  1504. if (is_array($file['name']) && count($file['name']) > 0) {
  1505. $nbfile = count($file['name']);
  1506. for ($i = 0; $i <= $nbfile; $i++) {
  1507. $originImage = $dir.$file['name'][$i];
  1508. // Cree fichier en taille origine
  1509. dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
  1510. if (file_exists($originImage)) {
  1511. // Create thumbs
  1512. $this->addThumbs($originImage);
  1513. }
  1514. }
  1515. } else {
  1516. $originImage = $dir.$file['name'];
  1517. // Cree fichier en taille origine
  1518. dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
  1519. if (file_exists($originImage)) {
  1520. // Create thumbs
  1521. $this->addThumbs($originImage);
  1522. }
  1523. }
  1524. }
  1525. }
  1526. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1527. /**
  1528. * Return tableau de toutes les photos de la categorie
  1529. *
  1530. * @param string $dir Repertoire a scanner
  1531. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  1532. * @return array Tableau de photos
  1533. */
  1534. public function liste_photos($dir, $nbmax = 0)
  1535. {
  1536. // phpcs:enable
  1537. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1538. $nbphoto = 0;
  1539. $tabobj = array();
  1540. $dirthumb = $dir.'thumbs/';
  1541. if (file_exists($dir)) {
  1542. $handle = opendir($dir);
  1543. if (is_resource($handle)) {
  1544. while (($file = readdir($handle)) !== false) {
  1545. if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) {
  1546. $nbphoto++;
  1547. $photo = $file;
  1548. // On determine nom du fichier vignette
  1549. $photo_vignette = '';
  1550. if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) {
  1551. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
  1552. }
  1553. // Objet
  1554. $obj = array();
  1555. $obj['photo'] = $photo;
  1556. if ($photo_vignette && is_file($dirthumb.$photo_vignette)) {
  1557. $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
  1558. } else {
  1559. $obj['photo_vignette'] = "";
  1560. }
  1561. $tabobj[$nbphoto - 1] = $obj;
  1562. // On continue ou on arrete de boucler
  1563. if ($nbmax && $nbphoto >= $nbmax) {
  1564. break;
  1565. }
  1566. }
  1567. }
  1568. closedir($handle);
  1569. }
  1570. }
  1571. return $tabobj;
  1572. }
  1573. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1574. /**
  1575. * Efface la photo de la categorie et sa vignette
  1576. *
  1577. * @param string $file Path to file
  1578. * @return void
  1579. */
  1580. public function delete_photo($file)
  1581. {
  1582. // phpcs:enable
  1583. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1584. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  1585. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
  1586. $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
  1587. // On efface l'image d'origine
  1588. dol_delete_file($file, 1);
  1589. // Si elle existe, on efface la vignette
  1590. if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs)) {
  1591. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
  1592. if (file_exists($dirthumb.$photo_vignette)) {
  1593. dol_delete_file($dirthumb.$photo_vignette, 1);
  1594. }
  1595. }
  1596. }
  1597. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1598. /**
  1599. * Load size of image file
  1600. *
  1601. * @param string $file Path to file
  1602. * @return void
  1603. */
  1604. public function get_image_size($file)
  1605. {
  1606. // phpcs:enable
  1607. $infoImg = getimagesize($file); // Recuperation des infos de l'image
  1608. $this->imgWidth = $infoImg[0]; // Largeur de l'image
  1609. $this->imgHeight = $infoImg[1]; // Hauteur de l'image
  1610. }
  1611. /**
  1612. * Update ou cree les traductions des infos produits
  1613. *
  1614. * @param User $user Object user
  1615. *
  1616. * @return int <0 if KO, >0 if OK
  1617. */
  1618. public function setMultiLangs($user)
  1619. {
  1620. global $langs;
  1621. $langs_available = $langs->get_available_languages();
  1622. $current_lang = $langs->getDefaultLang();
  1623. foreach ($langs_available as $key => $value) {
  1624. $sql = "SELECT rowid";
  1625. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
  1626. $sql .= " WHERE fk_category=".((int) $this->id);
  1627. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1628. $result = $this->db->query($sql);
  1629. if ($key == $current_lang) {
  1630. if ($this->db->num_rows($result)) { // si aucune ligne dans la base
  1631. $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
  1632. $sql2 .= " SET label = '".$this->db->escape($this->label)."',";
  1633. $sql2 .= " description = '".$this->db->escape($this->description)."'";
  1634. $sql2 .= " WHERE fk_category = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1635. } else {
  1636. $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
  1637. $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->label)."'";
  1638. $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["description"])."')";
  1639. }
  1640. dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
  1641. if (!$this->db->query($sql2)) {
  1642. $this->error = $this->db->lasterror();
  1643. return -1;
  1644. }
  1645. } elseif (isset($this->multilangs["$key"])) {
  1646. if ($this->db->num_rows($result)) { // si aucune ligne dans la base
  1647. $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
  1648. $sql2 .= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1649. $sql2 .= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1650. $sql2 .= " WHERE fk_category=".((int) $this->id)." AND lang='".$this->db->escape($key)."'";
  1651. } else {
  1652. $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
  1653. $sql2 .= " VALUES(".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($this->multilangs["$key"]["label"])."'";
  1654. $sql2 .= ",'".$this->db->escape($this->multilangs["$key"]["description"])."')";
  1655. }
  1656. // on ne sauvegarde pas des champs vides
  1657. if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) {
  1658. dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
  1659. }
  1660. if (!$this->db->query($sql2)) {
  1661. $this->error = $this->db->lasterror();
  1662. return -1;
  1663. }
  1664. }
  1665. }
  1666. // Call trigger
  1667. $result = $this->call_trigger('CATEGORY_SET_MULTILANGS', $user);
  1668. if ($result < 0) {
  1669. $this->error = $this->db->lasterror();
  1670. return -1;
  1671. }
  1672. // End call triggers
  1673. return 1;
  1674. }
  1675. /**
  1676. * Load array this->multilangs
  1677. *
  1678. * @return int <0 if KO, >0 if OK
  1679. */
  1680. public function getMultiLangs()
  1681. {
  1682. global $langs;
  1683. $current_lang = $langs->getDefaultLang();
  1684. $sql = "SELECT lang, label, description";
  1685. $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
  1686. $sql .= " WHERE fk_category=".((int) $this->id);
  1687. $result = $this->db->query($sql);
  1688. if ($result) {
  1689. while ($obj = $this->db->fetch_object($result)) {
  1690. //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
  1691. if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
  1692. $this->label = $obj->label;
  1693. $this->description = $obj->description;
  1694. }
  1695. $this->multilangs["$obj->lang"]["label"] = $obj->label;
  1696. $this->multilangs["$obj->lang"]["description"] = $obj->description;
  1697. }
  1698. return 1;
  1699. } else {
  1700. $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
  1701. return -1;
  1702. }
  1703. }
  1704. /**
  1705. * Return label of contact status
  1706. *
  1707. * @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
  1708. * @return string Label of contact status
  1709. */
  1710. public function getLibStatut($mode)
  1711. {
  1712. return '';
  1713. }
  1714. /**
  1715. * Initialise an instance with random values.
  1716. * Used to build previews or test instances.
  1717. * id must be 0 if object instance is a specimen.
  1718. *
  1719. * @return void
  1720. */
  1721. public function initAsSpecimen()
  1722. {
  1723. dol_syslog(get_class($this)."::initAsSpecimen");
  1724. // Initialise parametres
  1725. $this->id = 0;
  1726. $this->fk_parent = 0;
  1727. $this->label = 'SPECIMEN';
  1728. $this->specimen = 1;
  1729. $this->description = 'This is a description';
  1730. $this->socid = 1;
  1731. $this->type = self::TYPE_PRODUCT;
  1732. }
  1733. /**
  1734. * Function used to replace a thirdparty id with another one.
  1735. *
  1736. * @param DoliDB $db Database handler
  1737. * @param int $origin_id Old thirdparty id
  1738. * @param int $dest_id New thirdparty id
  1739. * @return bool
  1740. */
  1741. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1742. {
  1743. $tables = array(
  1744. 'categorie_societe'
  1745. );
  1746. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables, 1);
  1747. }
  1748. /**
  1749. * Return the addtional SQL JOIN query for filtering a list by a category
  1750. *
  1751. * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE)
  1752. * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid")
  1753. * @return string A additional SQL JOIN query
  1754. * @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)
  1755. */
  1756. public static function getFilterJoinQuery($type, $rowIdName)
  1757. {
  1758. if ($type == 'bank_account') {
  1759. $type = 'account';
  1760. }
  1761. return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type;
  1762. }
  1763. /**
  1764. * Return the addtional SQL SELECT query for filtering a list by a category
  1765. *
  1766. * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE)
  1767. * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid")
  1768. * @param Array $searchList A list with the selected categories
  1769. * @return string A additional SQL SELECT query
  1770. * @deprecated search on some categories must be done using a WHERE EXISTS or NOT EXISTS and not a LEFT JOIN
  1771. */
  1772. public static function getFilterSelectQuery($type, $rowIdName, $searchList)
  1773. {
  1774. if ($type == 'bank_account') {
  1775. $type = 'account';
  1776. }
  1777. if ($type == 'customer') {
  1778. $type = 'societe';
  1779. }
  1780. if ($type == 'supplier') {
  1781. $type = 'fournisseur';
  1782. }
  1783. if (empty($searchList) && !is_array($searchList)) {
  1784. return "";
  1785. }
  1786. $searchCategorySqlList = array();
  1787. foreach ($searchList as $searchCategory) {
  1788. if (intval($searchCategory) == -2) {
  1789. $searchCategorySqlList[] = " cp.fk_categorie IS NULL";
  1790. } elseif (intval($searchCategory) > 0) {
  1791. $searchCategorySqlList[] = " ".$rowIdName." IN (SELECT fk_".$type." FROM ".MAIN_DB_PREFIX."categorie_".$type." WHERE fk_categorie = ".((int) $searchCategory).")";
  1792. }
  1793. }
  1794. if (!empty($searchCategorySqlList)) {
  1795. return " AND (".implode(' AND ', $searchCategorySqlList).")";
  1796. } else {
  1797. return "";
  1798. }
  1799. }
  1800. /**
  1801. * Count all categories
  1802. *
  1803. * @return int Number of categories, -1 on error
  1804. */
  1805. public function countNbOfCategories()
  1806. {
  1807. dol_syslog(get_class($this)."::count_all_categories", LOG_DEBUG);
  1808. $sql = "SELECT COUNT(rowid) FROM ".MAIN_DB_PREFIX."categorie";
  1809. $sql .= " WHERE entity IN (".getEntity('category').")";
  1810. $res = $this->db->query($sql);
  1811. if ($res) {
  1812. $obj = $this->db->fetch_object($res);
  1813. return $obj->count;
  1814. } else {
  1815. dol_print_error($this->db);
  1816. return -1;
  1817. }
  1818. }
  1819. }