categorie.class.php 62 KB

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