categorie.class.php 61 KB

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