categorie.class.php 60 KB

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