DolibarrModules.class.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  1. <?php
  2. /* Copyright (C) 2003-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  6. * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  7. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  10. * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/core/modules/DolibarrModules.class.php
  27. * \brief File of parent class of module descriptor class files
  28. */
  29. /**
  30. * Class DolibarrModules
  31. *
  32. * Parent class for module descriptor class files
  33. */
  34. class DolibarrModules // Can not be abstract, because we need to instantiate it into unActivateModule to be able to disable a module whose files were removed.
  35. {
  36. /**
  37. * @var DoliDb Database handler
  38. */
  39. public $db;
  40. /**
  41. * @var int Module unique ID
  42. * @see https://wiki.dolibarr.org/index.php/List_of_modules_id
  43. */
  44. public $numero;
  45. /**
  46. * @var string Publisher name
  47. * @since 4.0.0
  48. */
  49. public $editor_name;
  50. /**
  51. * @var string URL of module at publisher site
  52. * @since 4.0.0
  53. */
  54. public $editor_url;
  55. /**
  56. * @var string Family
  57. * @see $familyinfo
  58. *
  59. * Native values: 'crm', 'financial', 'hr', 'projects', 'products', 'ecm', 'technic', 'other'.
  60. * Use familyinfo to declare a custom value.
  61. */
  62. public $family;
  63. /**
  64. * @var array Custom family informations
  65. * @see $family
  66. *
  67. * e.g.:
  68. * array(
  69. * 'myownfamily' => array(
  70. * 'position' => '001',
  71. * 'label' => $langs->trans("MyOwnFamily")
  72. * )
  73. * );
  74. */
  75. public $familyinfo;
  76. /**
  77. * @var string Module position on 2 digits
  78. */
  79. public $module_position = '50';
  80. /**
  81. * @var string Module name
  82. *
  83. * Only used if Module[ID]Name translation string is not found.
  84. *
  85. * You can use the following code to automatically derive it from your module's class name:
  86. * preg_replace('/^mod/i', '', get_class($this))
  87. */
  88. public $name;
  89. /**
  90. * @var string[] Paths to create when module is activated
  91. *
  92. * e.g.: array('/mymodule/temp')
  93. */
  94. public $dirs = array();
  95. /**
  96. * @var array Module boxes
  97. */
  98. public $boxes = array();
  99. /**
  100. * @var array Module constants
  101. */
  102. public $const = array();
  103. /**
  104. * @var array Module cron jobs entries
  105. */
  106. public $cronjobs = array();
  107. /**
  108. * @var array Module access rights
  109. */
  110. public $rights;
  111. /**
  112. * @var string Module access rights family
  113. */
  114. public $rights_class;
  115. /**
  116. * @var array|int Module menu entries (1 means the menu entries are not declared into module descriptor but are hardcoded into menu manager)
  117. */
  118. public $menu = array();
  119. /**
  120. * @var array Module parts
  121. * array(
  122. * // Set this to 1 if module has its own trigger directory (/mymodule/core/triggers)
  123. * 'triggers' => 0,
  124. * // Set this to 1 if module has its own login method directory (/mymodule/core/login)
  125. * 'login' => 0,
  126. * // Set this to 1 if module has its own substitution function file (/mymodule/core/substitutions)
  127. * 'substitutions' => 0,
  128. * // Set this to 1 if module has its own menus handler directory (/mymodule/core/menus)
  129. * 'menus' => 0,
  130. * // Set this to 1 if module has its own theme directory (/mymodule/theme)
  131. * 'theme' => 0,
  132. * // Set this to 1 if module overwrite template dir (/mymodule/core/tpl)
  133. * 'tpl' => 0,
  134. * // Set this to 1 if module has its own barcode directory (/mymodule/core/modules/barcode)
  135. * 'barcode' => 0,
  136. * // Set this to 1 if module has its own models directory (/mymodule/core/modules/xxx)
  137. * 'models' => 0,
  138. * // Set this to relative path of css file if module has its own css file
  139. * 'css' => '/mymodule/css/mymodule.css.php',
  140. * // Set this to relative path of js file if module must load a js on all pages
  141. * 'js' => '/mymodule/js/mymodule.js',
  142. * // Set here all hooks context managed by module
  143. * 'hooks' => array('hookcontext1','hookcontext2')
  144. * )
  145. */
  146. public $module_parts = array();
  147. /**
  148. * @var string Module documents ?
  149. * @deprecated Seems unused anywhere
  150. */
  151. public $docs;
  152. /**
  153. * @var string ?
  154. * @deprecated Seems unused anywhere
  155. */
  156. public $dbversion = "-";
  157. /**
  158. * @var string Error message
  159. */
  160. public $error;
  161. /**
  162. * @var string Module version
  163. * @see http://semver.org
  164. *
  165. * The following keywords can also be used:
  166. * 'development'
  167. * 'experimental'
  168. * 'dolibarr': only for core modules that share its version
  169. * 'dolibarr_deprecated': only for deprecated core modules
  170. */
  171. public $version;
  172. /**
  173. * Module last version
  174. * @var string $lastVersion
  175. */
  176. public $lastVersion = '';
  177. /**
  178. * true indicate this module need update
  179. * @var bool $needUpdate
  180. */
  181. public $needUpdate = false;
  182. /**
  183. * @var string Module description (short text)
  184. *
  185. * Only used if Module[ID]Desc translation string is not found.
  186. */
  187. public $description;
  188. /**
  189. * @var string Module description (long text)
  190. * @since 4.0.0
  191. *
  192. * HTML content supported.
  193. */
  194. public $descriptionlong;
  195. // For exports
  196. /**
  197. * @var string Module export code
  198. */
  199. public $export_code;
  200. /**
  201. * @var string Module export label
  202. */
  203. public $export_label;
  204. public $export_permission;
  205. public $export_fields_array;
  206. public $export_TypeFields_array; // Array of key=>type where type can be 'Numeric', 'Date', 'Text', 'Boolean', 'Status', 'List:xxx:login:rowid'
  207. public $export_entities_array;
  208. public $export_special_array; // special or computed field
  209. public $export_dependencies_array;
  210. public $export_sql_start;
  211. public $export_sql_end;
  212. public $export_sql_order;
  213. // For import
  214. /**
  215. * @var string Module import code
  216. */
  217. public $import_code;
  218. /**
  219. * @var string Module import label
  220. */
  221. public $import_label;
  222. /**
  223. * @var string Module constant name
  224. */
  225. public $const_name;
  226. /**
  227. * @var bool Module can't be disabled
  228. */
  229. public $always_enabled;
  230. /**
  231. * @var int Module is enabled globally (Multicompany support)
  232. */
  233. public $core_enabled;
  234. /**
  235. * @var string Name of image file used for this module
  236. *
  237. * If file is in theme/yourtheme/img directory under name object_pictoname.png use 'pictoname'
  238. * If file is in module/img directory under name object_pictoname.png use 'pictoname@module'
  239. */
  240. public $picto;
  241. /**
  242. * @var string[] List of config pages
  243. *
  244. * Name of php pages stored into module/admin directory, used to setup module.
  245. * e.g.: "admin.php@module"
  246. */
  247. public $config_page_url;
  248. /**
  249. * @var string[] List of module class names that must be enabled if this module is enabled. e.g.: array('modAnotherModule', 'FR'=>'modYetAnotherModule')
  250. * @see $requiredby
  251. */
  252. public $depends;
  253. /**
  254. * @var string[] List of module class names to disable if the module is disabled.
  255. * @see $depends
  256. */
  257. public $requiredby;
  258. /**
  259. * @var string[] List of module class names as string this module is in conflict with.
  260. * @see $depends
  261. */
  262. public $conflictwith;
  263. /**
  264. * @var string[] Module language files
  265. */
  266. public $langfiles;
  267. /**
  268. * @var array<string,string> Array of warnings to show when we activate the module
  269. *
  270. * array('always'='text') or array('FR'='text')
  271. */
  272. public $warnings_activation;
  273. /**
  274. * @var array<string,string> Array of warnings to show when we activate an external module
  275. *
  276. * array('always'='text') or array('FR'='text')
  277. */
  278. public $warnings_activation_ext;
  279. /**
  280. * @var array Minimum version of PHP required by module.
  281. * e.g.: PHP ≥ 5.6 = array(5, 6)
  282. */
  283. public $phpmin;
  284. /**
  285. * @var array Minimum version of Dolibarr required by module.
  286. * e.g.: Dolibarr ≥ 3.6 = array(3, 6)
  287. */
  288. public $need_dolibarr_version;
  289. /**
  290. * @var bool Whether to hide the module.
  291. */
  292. public $hidden = false;
  293. /**
  294. * Constructor. Define names, constants, directories, boxes, permissions
  295. *
  296. * @param DoliDB $db Database handler
  297. */
  298. public function __construct($db)
  299. {
  300. $this->db = $db;
  301. }
  302. // We should but can't set this as abstract because this will make dolibarr hang
  303. // after migration due to old module not implementing. We must wait PHP is able to make
  304. // a try catch on Fatal error to manage this correctly.
  305. // We need constructor into function unActivateModule into admin.lib.php
  306. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  307. /**
  308. * Enables a module.
  309. * Inserts all informations into database.
  310. *
  311. * @param array $array_sql SQL requests to be executed when enabling module
  312. * @param string $options String with options when disabling module:
  313. * - 'noboxes' = Do all actions but do not insert boxes
  314. * - 'newboxdefonly' = Do all actions but for boxes, insert def of boxes only and not boxes activation
  315. * @return int 1 if OK, 0 if KO
  316. */
  317. protected function _init($array_sql, $options = '')
  318. {
  319. // phpcs:enable
  320. global $conf;
  321. $err = 0;
  322. $this->db->begin();
  323. // Insert activation module constant
  324. if (!$err) {
  325. $err += $this->_active();
  326. }
  327. // Insert new pages for tabs (into llx_const)
  328. if (!$err) {
  329. $err += $this->insert_tabs();
  330. }
  331. // Insert activation of module's parts
  332. if (!$err) {
  333. $err += $this->insert_module_parts();
  334. }
  335. // Insert constant defined by modules (into llx_const)
  336. if (!$err && !preg_match('/newboxdefonly/', $options)) {
  337. $err += $this->insert_const(); // Test on newboxdefonly to avoid to erase value during upgrade
  338. }
  339. // Insert boxes def (into llx_boxes_def) and boxes setup (into llx_boxes)
  340. if (!$err && !preg_match('/noboxes/', $options)) {
  341. $err += $this->insert_boxes($options);
  342. }
  343. // Insert cron job entries (entry in llx_cronjobs)
  344. if (!$err) {
  345. $err += $this->insert_cronjobs();
  346. }
  347. // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user.
  348. if (!$err) {
  349. $err += $this->insert_permissions(1, null, 1);
  350. }
  351. // Insert specific menus entries into database
  352. if (!$err) {
  353. $err += $this->insert_menus();
  354. }
  355. // Create module's directories
  356. if (!$err) {
  357. $err += $this->create_dirs();
  358. }
  359. // Execute addons requests
  360. $num = count($array_sql);
  361. for ($i = 0; $i < $num; $i++) {
  362. if (!$err) {
  363. $val = $array_sql[$i];
  364. $sql = $val;
  365. $ignoreerror = 0;
  366. if (is_array($val)) {
  367. $sql = $val['sql'];
  368. $ignoreerror = $val['ignoreerror'];
  369. }
  370. // Add current entity id
  371. $sql = str_replace('__ENTITY__', $conf->entity, $sql);
  372. dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror."", LOG_DEBUG);
  373. $result = $this->db->query($sql, $ignoreerror);
  374. if (!$result) {
  375. if (!$ignoreerror) {
  376. $this->error = $this->db->lasterror();
  377. $err++;
  378. } else {
  379. dol_syslog(get_class($this)."::_init Warning ".$this->db->lasterror(), LOG_WARNING);
  380. }
  381. }
  382. }
  383. }
  384. // Return code
  385. if (!$err) {
  386. $this->db->commit();
  387. return 1;
  388. } else {
  389. $this->db->rollback();
  390. return 0;
  391. }
  392. }
  393. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  394. /**
  395. * Disable function. Deletes the module constants and boxes from the database.
  396. *
  397. * @param string[] $array_sql SQL requests to be executed when module is disabled
  398. * @param string $options Options when disabling module:
  399. *
  400. * @return int 1 if OK, 0 if KO
  401. */
  402. protected function _remove($array_sql, $options = '')
  403. {
  404. // phpcs:enable
  405. $err = 0;
  406. $this->db->begin();
  407. // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const)
  408. if (!$err) {
  409. $err += $this->_unactive();
  410. }
  411. // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const)
  412. if (!$err) {
  413. $err += $this->delete_tabs();
  414. }
  415. // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const)
  416. if (!$err) {
  417. $err += $this->delete_module_parts();
  418. }
  419. // Remove constants defined by modules
  420. if (!$err) {
  421. $err += $this->delete_const();
  422. }
  423. // Remove list of module's available boxes (entry in llx_boxes)
  424. if (!$err && !preg_match('/(newboxdefonly|noboxes)/', $options)) {
  425. $err += $this->delete_boxes(); // We don't have to delete if option ask to keep boxes safe or ask to add new box def only
  426. }
  427. // Remove list of module's cron job entries (entry in llx_cronjobs)
  428. if (!$err) {
  429. $err += $this->delete_cronjobs();
  430. }
  431. // Remove module's permissions from list of available permissions (entries in llx_rights_def)
  432. if (!$err) {
  433. $err += $this->delete_permissions();
  434. }
  435. // Remove module's menus (entries in llx_menu)
  436. if (!$err) {
  437. $err += $this->delete_menus();
  438. }
  439. // Remove module's directories
  440. if (!$err) {
  441. $err += $this->delete_dirs();
  442. }
  443. // Run complementary sql requests
  444. $num = count($array_sql);
  445. for ($i = 0; $i < $num; $i++) {
  446. if (!$err) {
  447. dol_syslog(get_class($this)."::_remove", LOG_DEBUG);
  448. $result = $this->db->query($array_sql[$i]);
  449. if (!$result) {
  450. $this->error = $this->db->error();
  451. $err++;
  452. }
  453. }
  454. }
  455. // Return code
  456. if (!$err) {
  457. $this->db->commit();
  458. return 1;
  459. } else {
  460. $this->db->rollback();
  461. return 0;
  462. }
  463. }
  464. /**
  465. * Gives the translated module name if translation exists in admin.lang or into language files of module.
  466. * Otherwise return the module key name.
  467. *
  468. * @return string Translated module name
  469. */
  470. public function getName()
  471. {
  472. global $langs;
  473. $langs->load("admin");
  474. if ($langs->transnoentitiesnoconv("Module".$this->numero."Name") != ("Module".$this->numero."Name")) {
  475. // If module name translation exists
  476. return $langs->transnoentitiesnoconv("Module".$this->numero."Name");
  477. } else {
  478. // If module name translation using it's unique id does not exist, we try to use its name to find translation
  479. if (is_array($this->langfiles)) {
  480. foreach ($this->langfiles as $val) {
  481. if ($val) {
  482. $langs->load($val);
  483. }
  484. }
  485. }
  486. if ($langs->trans("Module".$this->name."Name") != ("Module".$this->name."Name")) {
  487. // If module name translation exists
  488. return $langs->transnoentitiesnoconv("Module".$this->name."Name");
  489. }
  490. // Last chance with simple label
  491. return $langs->transnoentitiesnoconv($this->name);
  492. }
  493. }
  494. /**
  495. * Gives the translated module description if translation exists in admin.lang or the default module description
  496. *
  497. * @return string Translated module description
  498. */
  499. public function getDesc()
  500. {
  501. global $langs;
  502. $langs->load("admin");
  503. if ($langs->transnoentitiesnoconv("Module".$this->numero."Desc") != ("Module".$this->numero."Desc")) {
  504. // If module description translation exists
  505. return $langs->transnoentitiesnoconv("Module".$this->numero."Desc");
  506. } else {
  507. // If module description translation does not exist using its unique id, we can use its name to find translation
  508. if (is_array($this->langfiles)) {
  509. foreach ($this->langfiles as $val) {
  510. if ($val) {
  511. $langs->load($val);
  512. }
  513. }
  514. }
  515. if ($langs->transnoentitiesnoconv("Module".$this->name."Desc") != ("Module".$this->name."Desc")) {
  516. // If module name translation exists
  517. return $langs->trans("Module".$this->name."Desc");
  518. }
  519. // Last chance with simple label
  520. return $langs->trans($this->description);
  521. }
  522. }
  523. /**
  524. * Gives the long description of a module. First check README-la_LA.md then README.md
  525. * If no markdown files found, it returns translated value of the key ->descriptionlong.
  526. *
  527. * @return string Long description of a module from README.md of from property.
  528. */
  529. public function getDescLong()
  530. {
  531. global $langs;
  532. $langs->load("admin");
  533. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  534. include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  535. $content='';
  536. $pathoffile = $this->getDescLongReadmeFound();
  537. if ($pathoffile) { // Mostly for external modules
  538. $content = file_get_contents($pathoffile);
  539. if ((float) DOL_VERSION >= 6.0) {
  540. @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
  541. $content = dolMd2Html(
  542. $content,
  543. 'parsedown',
  544. array(
  545. 'doc/' => dol_buildpath(strtolower($this->name).'/doc/', 1),
  546. 'img/' => dol_buildpath(strtolower($this->name).'/img/', 1),
  547. 'images/' => dol_buildpath(strtolower($this->name).'/images/', 1),
  548. )
  549. );
  550. } else {
  551. $content = nl2br($content);
  552. }
  553. } else {
  554. // Mostly for internal modules
  555. if (!empty($this->descriptionlong)) {
  556. if (is_array($this->langfiles)) {
  557. foreach ($this->langfiles as $val) {
  558. if ($val) {
  559. $langs->load($val);
  560. }
  561. }
  562. }
  563. $content = $langs->transnoentitiesnoconv($this->descriptionlong);
  564. }
  565. }
  566. return $content;
  567. }
  568. /**
  569. * Return path of file if a README file was found.
  570. *
  571. * @return string Path of file if a README file was found.
  572. */
  573. public function getDescLongReadmeFound()
  574. {
  575. global $langs;
  576. $filefound = false;
  577. // Define path to file README.md.
  578. // First check README-la_LA.md then README-la.md then README.md
  579. $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0);
  580. if (dol_is_file($pathoffile)) {
  581. $filefound = true;
  582. }
  583. if (!$filefound) {
  584. $tmp = explode('_', $langs->defaultlang);
  585. $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$tmp[0].'.md', 0);
  586. if (dol_is_file($pathoffile)) {
  587. $filefound = true;
  588. }
  589. }
  590. if (!$filefound) {
  591. $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0);
  592. if (dol_is_file($pathoffile)) {
  593. $filefound = true;
  594. }
  595. }
  596. return ($filefound ? $pathoffile : '');
  597. }
  598. /**
  599. * Gives the changelog. First check ChangeLog-la_LA.md then ChangeLog.md
  600. *
  601. * @return string Content of ChangeLog
  602. */
  603. public function getChangeLog()
  604. {
  605. global $langs;
  606. $langs->load("admin");
  607. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  608. include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  609. $filefound = false;
  610. // Define path to file README.md.
  611. // First check ChangeLog-la_LA.md then ChangeLog.md
  612. $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog-'.$langs->defaultlang.'.md', 0);
  613. if (dol_is_file($pathoffile)) {
  614. $filefound = true;
  615. }
  616. if (!$filefound) {
  617. $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0);
  618. if (dol_is_file($pathoffile)) {
  619. $filefound = true;
  620. }
  621. }
  622. if ($filefound) { // Mostly for external modules
  623. $content = file_get_contents($pathoffile);
  624. if ((float) DOL_VERSION >= 6.0) {
  625. @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
  626. $content = dolMd2Html($content, 'parsedown', array('doc/'=>dol_buildpath(strtolower($this->name).'/doc/', 1)));
  627. } else {
  628. $content = nl2br($content);
  629. }
  630. }
  631. return $content;
  632. }
  633. /**
  634. * Gives the publisher name
  635. *
  636. * @return string Publisher name
  637. */
  638. public function getPublisher()
  639. {
  640. return $this->editor_name;
  641. }
  642. /**
  643. * Gives the publisher url
  644. *
  645. * @return string Publisher url
  646. */
  647. public function getPublisherUrl()
  648. {
  649. return $this->editor_url;
  650. }
  651. /**
  652. * Gives module version (translated if param $translated is on)
  653. * For 'experimental' modules, gives 'experimental' translation
  654. * For 'dolibarr' modules, gives Dolibarr version
  655. *
  656. * @param int $translated 1=Special version keys are translated, 0=Special version keys are not translated
  657. * @return string Module version
  658. */
  659. public function getVersion($translated = 1)
  660. {
  661. global $langs;
  662. $langs->load("admin");
  663. $ret = '';
  664. $newversion = preg_replace('/_deprecated/', '', $this->version);
  665. if ($newversion == 'experimental') {
  666. $ret = ($translated ? $langs->transnoentitiesnoconv("VersionExperimental") : $newversion);
  667. } elseif ($newversion == 'development') {
  668. $ret = ($translated ? $langs->transnoentitiesnoconv("VersionDevelopment") : $newversion);
  669. } elseif ($newversion == 'dolibarr') {
  670. $ret = DOL_VERSION;
  671. } elseif ($newversion) {
  672. $ret = $newversion;
  673. } else {
  674. $ret = ($translated ? $langs->transnoentitiesnoconv("VersionUnknown") : 'unknown');
  675. }
  676. if (preg_match('/_deprecated/', $this->version)) {
  677. $ret .= ($translated ? ' ('.$langs->transnoentitiesnoconv("Deprecated").')' : $this->version);
  678. }
  679. return $ret;
  680. }
  681. /**
  682. * Gives the module position
  683. *
  684. * @return int Module position (an external module should never return a value lower than 100000. 1-100000 are reserved for core)
  685. */
  686. public function getModulePosition()
  687. {
  688. if (in_array($this->version, array('dolibarr', 'experimental', 'development'))) { // core module
  689. return $this->module_position;
  690. } else { // external module
  691. if ($this->module_position >= 100000) {
  692. return $this->module_position;
  693. } else {
  694. return $this->module_position + 100000;
  695. }
  696. }
  697. }
  698. /**
  699. * Tells if module is core or external
  700. *
  701. * @return string 'core', 'external' or 'unknown'
  702. */
  703. public function isCoreOrExternalModule()
  704. {
  705. if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') {
  706. return 'core';
  707. }
  708. if (!empty($this->version) && !in_array($this->version, array('experimental', 'development'))) {
  709. return 'external';
  710. }
  711. if (!empty($this->editor_name) || !empty($this->editor_url)) {
  712. return 'external';
  713. }
  714. if ($this->numero >= 100000) {
  715. return 'external';
  716. }
  717. return 'unknown';
  718. }
  719. /**
  720. * Gives module related language files list
  721. *
  722. * @return string[] Language files list
  723. */
  724. public function getLangFilesArray()
  725. {
  726. return $this->langfiles;
  727. }
  728. /**
  729. * Gives translated label of an export dataset
  730. *
  731. * @param int $r Dataset index
  732. *
  733. * @return string Translated databaset label
  734. */
  735. public function getExportDatasetLabel($r)
  736. {
  737. global $langs;
  738. $langstring = "ExportDataset_".$this->export_code[$r];
  739. if ($langs->trans($langstring) == $langstring) {
  740. // Translation not found
  741. return $langs->trans($this->export_label[$r]);
  742. } else {
  743. // Translation found
  744. return $langs->trans($langstring);
  745. }
  746. }
  747. /**
  748. * Gives translated label of an import dataset
  749. *
  750. * @param int $r Dataset index
  751. *
  752. * @return string Translated dataset label
  753. */
  754. public function getImportDatasetLabel($r)
  755. {
  756. global $langs;
  757. $langstring = "ImportDataset_".$this->import_code[$r];
  758. //print "x".$langstring;
  759. if ($langs->trans($langstring) == $langstring) {
  760. // Translation not found
  761. return $langs->transnoentitiesnoconv($this->import_label[$r]);
  762. } else {
  763. // Translation found
  764. return $langs->transnoentitiesnoconv($langstring);
  765. }
  766. }
  767. /**
  768. * Gives the last date of activation
  769. *
  770. * @return int|string Date of last activation or '' if module was never activated
  771. */
  772. public function getLastActivationDate()
  773. {
  774. global $conf;
  775. $err = 0;
  776. $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const";
  777. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
  778. $sql .= " AND entity IN (0, ".$conf->entity.")";
  779. dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
  780. $resql = $this->db->query($sql);
  781. if (!$resql) {
  782. $err++;
  783. } else {
  784. $obj = $this->db->fetch_object($resql);
  785. if ($obj) {
  786. return $this->db->jdate($obj->tms);
  787. }
  788. }
  789. return '';
  790. }
  791. /**
  792. * Gives the last author of activation
  793. *
  794. * @return array Array array('authorid'=>Id of last activation user, 'lastactivationdate'=>Date of last activation)
  795. */
  796. public function getLastActivationInfo()
  797. {
  798. global $conf;
  799. $err = 0;
  800. $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const";
  801. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
  802. $sql .= " AND entity IN (0, ".$conf->entity.")";
  803. dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
  804. $resql = $this->db->query($sql);
  805. if (!$resql) {
  806. $err++;
  807. } else {
  808. $obj = $this->db->fetch_object($resql);
  809. $tmp = array();
  810. if ($obj->note) {
  811. $tmp = json_decode($obj->note, true);
  812. }
  813. if ($obj) {
  814. return array('authorid'=>$tmp['authorid'], 'ip'=>$tmp['ip'], 'lastactivationdate'=>$this->db->jdate($obj->tms));
  815. }
  816. }
  817. return array();
  818. }
  819. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  820. /**
  821. * Insert constants for module activation
  822. *
  823. * @return int Error count (0 if OK)
  824. */
  825. protected function _active()
  826. {
  827. // phpcs:enable
  828. global $conf, $user;
  829. $err = 0;
  830. // Common module
  831. $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
  832. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  833. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
  834. $sql .= " AND entity IN (0, ".$entity.")";
  835. dol_syslog(get_class($this)."::_active delete activation constant", LOG_DEBUG);
  836. $resql = $this->db->query($sql);
  837. if (!$resql) {
  838. $err++;
  839. }
  840. $note = json_encode(array('authorid'=>(is_object($user) ? $user->id : 0), 'ip'=>(empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR'])));
  841. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES";
  842. $sql .= " (".$this->db->encrypt($this->const_name, 1);
  843. $sql .= ", ".$this->db->encrypt('1', 1);
  844. $sql .= ", 0, ".$entity;
  845. $sql .= ", '".$this->db->escape($note)."')";
  846. dol_syslog(get_class($this)."::_active insert activation constant", LOG_DEBUG);
  847. $resql = $this->db->query($sql);
  848. if (!$resql) {
  849. $err++;
  850. }
  851. return $err;
  852. }
  853. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  854. /**
  855. * Module deactivation
  856. *
  857. * @return int Error count (0 if OK)
  858. */
  859. protected function _unactive()
  860. {
  861. // phpcs:enable
  862. global $conf;
  863. $err = 0;
  864. // Common module
  865. $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
  866. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  867. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
  868. $sql .= " AND entity IN (0, ".$entity.")";
  869. dol_syslog(get_class($this)."::_unactive", LOG_DEBUG);
  870. $this->db->query($sql);
  871. return $err;
  872. }
  873. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps,PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  874. /**
  875. * Create tables and keys required by module.
  876. * Files module.sql and module.key.sql with create table and create keys
  877. * commands must be stored in directory reldir='/module/sql/'
  878. * This function is called by this->init
  879. *
  880. * @param string $reldir Relative directory where to scan files
  881. * @return int <=0 if KO, >0 if OK
  882. */
  883. protected function _load_tables($reldir)
  884. {
  885. // phpcs:enable
  886. global $conf;
  887. $error = 0;
  888. $dirfound = 0;
  889. if (empty($reldir)) {
  890. return 1;
  891. }
  892. include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
  893. $ok = 1;
  894. foreach ($conf->file->dol_document_root as $dirroot) {
  895. if ($ok) {
  896. $dir = $dirroot.$reldir;
  897. $ok = 0;
  898. $handle = @opendir($dir); // Dir may not exists
  899. if (is_resource($handle)) {
  900. $dirfound++;
  901. // Run llx_mytable.sql files, then llx_mytable_*.sql
  902. $files = array();
  903. while (($file = readdir($handle)) !== false) {
  904. $files[] = $file;
  905. }
  906. sort($files);
  907. foreach ($files as $file) {
  908. if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_' && substr($file, 0, 4) != 'data') {
  909. $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1);
  910. if ($result <= 0) {
  911. $error++;
  912. }
  913. }
  914. }
  915. rewinddir($handle);
  916. // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql
  917. $files = array();
  918. while (($file = readdir($handle)) !== false) {
  919. $files[] = $file;
  920. }
  921. sort($files);
  922. foreach ($files as $file) {
  923. if (preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_' && substr($file, 0, 4) != 'data') {
  924. $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1);
  925. if ($result <= 0) {
  926. $error++;
  927. }
  928. }
  929. }
  930. rewinddir($handle);
  931. // Run data_xxx.sql files (Must be done after llx_mytable.key.sql)
  932. $files = array();
  933. while (($file = readdir($handle)) !== false) {
  934. $files[] = $file;
  935. }
  936. sort($files);
  937. foreach ($files as $file) {
  938. if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'data') {
  939. $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1);
  940. if ($result <= 0) {
  941. $error++;
  942. }
  943. }
  944. }
  945. rewinddir($handle);
  946. // Run update_xxx.sql files
  947. $files = array();
  948. while (($file = readdir($handle)) !== false) {
  949. $files[] = $file;
  950. }
  951. sort($files);
  952. foreach ($files as $file) {
  953. if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 6) == 'update') {
  954. $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1);
  955. if ($result <= 0) {
  956. $error++;
  957. }
  958. }
  959. }
  960. closedir($handle);
  961. }
  962. if ($error == 0) {
  963. $ok = 1;
  964. }
  965. }
  966. }
  967. if (!$dirfound) {
  968. dol_syslog("A module ask to load sql files into ".$reldir." but this directory was not found.", LOG_WARNING);
  969. }
  970. return $ok;
  971. }
  972. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  973. /**
  974. * Adds boxes
  975. *
  976. * @param string $option Options when disabling module ('newboxdefonly'=insert only boxes definition)
  977. *
  978. * @return int Error count (0 if OK)
  979. */
  980. public function insert_boxes($option = '')
  981. {
  982. // phpcs:enable
  983. include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
  984. global $conf;
  985. $err = 0;
  986. if (is_array($this->boxes)) {
  987. dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
  988. $pos_name = InfoBox::getListOfPagesForBoxes();
  989. foreach ($this->boxes as $key => $value) {
  990. $file = isset($this->boxes[$key]['file']) ? $this->boxes[$key]['file'] : '';
  991. $note = isset($this->boxes[$key]['note']) ? $this->boxes[$key]['note'] : '';
  992. $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton']) ? $this->boxes[$key]['enabledbydefaulton'] : 'Home';
  993. if (empty($file)) {
  994. $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
  995. }
  996. if (empty($note)) {
  997. $note = isset($this->boxes[$key][2]) ? $this->boxes[$key][2] : ''; // For backward compatibility
  998. }
  999. // Search if boxes def already present
  1000. $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def";
  1001. $sql .= " WHERE file = '".$this->db->escape($file)."'";
  1002. $sql .= " AND entity = ".$conf->entity;
  1003. if ($note) {
  1004. $sql .= " AND note ='".$this->db->escape($note)."'";
  1005. }
  1006. $result = $this->db->query($sql);
  1007. if ($result) {
  1008. $obj = $this->db->fetch_object($result);
  1009. if ($obj->nb == 0) {
  1010. $this->db->begin();
  1011. if (!$err) {
  1012. $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)";
  1013. $sql .= " VALUES ('".$this->db->escape($file)."', ";
  1014. $sql .= $conf->entity.", ";
  1015. $sql .= $note ? "'".$this->db->escape($note)."'" : "null";
  1016. $sql .= ")";
  1017. dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
  1018. $resql = $this->db->query($sql);
  1019. if (!$resql) {
  1020. $err++;
  1021. }
  1022. }
  1023. if (!$err && !preg_match('/newboxdefonly/', $option)) {
  1024. $lastid = $this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def", "rowid");
  1025. foreach ($pos_name as $key2 => $val2) {
  1026. //print 'key2='.$key2.'-val2='.$val2."<br>\n";
  1027. if ($enabledbydefaulton && $val2 != $enabledbydefaulton) {
  1028. continue; // Not enabled by default onto this page.
  1029. }
  1030. $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id,position,box_order,fk_user,entity)";
  1031. $sql .= " VALUES (".$lastid.", ".$key2.", '0', 0, ".$conf->entity.")";
  1032. dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2."", LOG_DEBUG);
  1033. $resql = $this->db->query($sql);
  1034. if (!$resql) {
  1035. $err++;
  1036. }
  1037. }
  1038. }
  1039. if (!$err) {
  1040. $this->db->commit();
  1041. } else {
  1042. $this->error = $this->db->lasterror();
  1043. $this->db->rollback();
  1044. }
  1045. }
  1046. // else box already registered into database
  1047. } else {
  1048. $this->error = $this->db->lasterror();
  1049. $err++;
  1050. }
  1051. }
  1052. }
  1053. return $err;
  1054. }
  1055. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1056. /**
  1057. * Removes boxes
  1058. *
  1059. * @return int Error count (0 if OK)
  1060. */
  1061. public function delete_boxes()
  1062. {
  1063. // phpcs:enable
  1064. global $conf;
  1065. $err = 0;
  1066. if (is_array($this->boxes)) {
  1067. foreach ($this->boxes as $key => $value) {
  1068. //$titre = $this->boxes[$key][0];
  1069. if (empty($this->boxes[$key]['file'])) {
  1070. $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
  1071. } else {
  1072. $file = $this->boxes[$key]['file'];
  1073. }
  1074. //$note = $this->boxes[$key][2];
  1075. // TODO If the box is also included by another module and the other module is still on, we should not remove it.
  1076. // For the moment, we manage this with hard coded exception
  1077. //print "Remove box ".$file.'<br>';
  1078. if ($file == 'box_graph_product_distribution.php') {
  1079. if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) {
  1080. dol_syslog("We discard deleting module ".$file." because another module still active requires it.");
  1081. continue;
  1082. }
  1083. }
  1084. if ($this->db->type == 'sqlite3') {
  1085. // sqlite doesn't support "USING" syntax.
  1086. // TODO: remove this dependency.
  1087. $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes ";
  1088. $sql .= "WHERE ".MAIN_DB_PREFIX."boxes.box_id IN (";
  1089. $sql .= "SELECT ".MAIN_DB_PREFIX."boxes_def.rowid ";
  1090. $sql .= "FROM ".MAIN_DB_PREFIX."boxes_def ";
  1091. $sql .= "WHERE ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."') ";
  1092. $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
  1093. } else {
  1094. $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes";
  1095. $sql .= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def";
  1096. $sql .= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid";
  1097. $sql .= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'";
  1098. $sql .= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
  1099. }
  1100. dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
  1101. $resql = $this->db->query($sql);
  1102. if (!$resql) {
  1103. $this->error = $this->db->lasterror();
  1104. $err++;
  1105. }
  1106. $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def";
  1107. $sql .= " WHERE file = '".$this->db->escape($file)."'";
  1108. $sql .= " AND entity = ".$conf->entity; // Do not use getEntity here, we want to delete only in current company
  1109. dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
  1110. $resql = $this->db->query($sql);
  1111. if (!$resql) {
  1112. $this->error = $this->db->lasterror();
  1113. $err++;
  1114. }
  1115. }
  1116. }
  1117. return $err;
  1118. }
  1119. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1120. /**
  1121. * Adds cronjobs
  1122. *
  1123. * @return int Error count (0 if OK)
  1124. */
  1125. public function insert_cronjobs()
  1126. {
  1127. // phpcs:enable
  1128. include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
  1129. global $conf;
  1130. $err = 0;
  1131. if (is_array($this->cronjobs)) {
  1132. dol_syslog(get_class($this)."::insert_cronjobs", LOG_DEBUG);
  1133. foreach ($this->cronjobs as $key => $value) {
  1134. $entity = isset($this->cronjobs[$key]['entity']) ? $this->cronjobs[$key]['entity'] : $conf->entity;
  1135. $label = isset($this->cronjobs[$key]['label']) ? $this->cronjobs[$key]['label'] : '';
  1136. $jobtype = isset($this->cronjobs[$key]['jobtype']) ? $this->cronjobs[$key]['jobtype'] : '';
  1137. $class = isset($this->cronjobs[$key]['class']) ? $this->cronjobs[$key]['class'] : '';
  1138. $objectname = isset($this->cronjobs[$key]['objectname']) ? $this->cronjobs[$key]['objectname'] : '';
  1139. $method = isset($this->cronjobs[$key]['method']) ? $this->cronjobs[$key]['method'] : '';
  1140. $command = isset($this->cronjobs[$key]['command']) ? $this->cronjobs[$key]['command'] : '';
  1141. $parameters = isset($this->cronjobs[$key]['parameters']) ? $this->cronjobs[$key]['parameters'] : '';
  1142. $comment = isset($this->cronjobs[$key]['comment']) ? $this->cronjobs[$key]['comment'] : '';
  1143. $frequency = isset($this->cronjobs[$key]['frequency']) ? $this->cronjobs[$key]['frequency'] : '';
  1144. $unitfrequency = isset($this->cronjobs[$key]['unitfrequency']) ? $this->cronjobs[$key]['unitfrequency'] : '';
  1145. $priority = isset($this->cronjobs[$key]['priority']) ? $this->cronjobs[$key]['priority'] : '';
  1146. $datestart = isset($this->cronjobs[$key]['datestart']) ? $this->cronjobs[$key]['datestart'] : '';
  1147. $dateend = isset($this->cronjobs[$key]['dateend']) ? $this->cronjobs[$key]['dateend'] : '';
  1148. $status = isset($this->cronjobs[$key]['status']) ? $this->cronjobs[$key]['status'] : '';
  1149. $test = isset($this->cronjobs[$key]['test']) ? $this->cronjobs[$key]['test'] : ''; // Line must be enabled or not (so visible or not)
  1150. // Search if cron entry already present
  1151. $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."cronjob";
  1152. $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."'";
  1153. if ($class) {
  1154. $sql .= " AND classesname = '".$this->db->escape($class)."'";
  1155. }
  1156. if ($objectname) {
  1157. $sql .= " AND objectname = '".$this->db->escape($objectname)."'";
  1158. }
  1159. if ($method) {
  1160. $sql .= " AND methodename = '".$this->db->escape($method)."'";
  1161. }
  1162. if ($command) {
  1163. $sql .= " AND command = '".$this->db->escape($command)."'";
  1164. }
  1165. $sql .= " AND entity = ".((int) $entity); // Must be exact entity
  1166. $now = dol_now();
  1167. $result = $this->db->query($sql);
  1168. if ($result) {
  1169. $obj = $this->db->fetch_object($result);
  1170. if ($obj->nb == 0) {
  1171. $this->db->begin();
  1172. if (!$err) {
  1173. $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob (module_name, datec, datestart, dateend, label, jobtype, classesname, objectname, methodename, command, params, note,";
  1174. if (is_int($frequency)) {
  1175. $sql .= ' frequency,';
  1176. }
  1177. if (is_int($unitfrequency)) {
  1178. $sql .= ' unitfrequency,';
  1179. }
  1180. if (is_int($priority)) {
  1181. $sql .= ' priority,';
  1182. }
  1183. if (is_int($status)) {
  1184. $sql .= ' status,';
  1185. }
  1186. $sql .= " entity, test)";
  1187. $sql .= " VALUES (";
  1188. $sql .= "'".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."', ";
  1189. $sql .= "'".$this->db->idate($now)."', ";
  1190. $sql .= ($datestart ? "'".$this->db->idate($datestart)."'" : "'".$this->db->idate($now)."'").", ";
  1191. $sql .= ($dateend ? "'".$this->db->idate($dateend)."'" : "NULL").", ";
  1192. $sql .= "'".$this->db->escape($label)."', ";
  1193. $sql .= "'".$this->db->escape($jobtype)."', ";
  1194. $sql .= ($class ? "'".$this->db->escape($class)."'" : "null").",";
  1195. $sql .= ($objectname ? "'".$this->db->escape($objectname)."'" : "null").",";
  1196. $sql .= ($method ? "'".$this->db->escape($method)."'" : "null").",";
  1197. $sql .= ($command ? "'".$this->db->escape($command)."'" : "null").",";
  1198. $sql .= ($parameters ? "'".$this->db->escape($parameters)."'" : "null").",";
  1199. $sql .= ($comment ? "'".$this->db->escape($comment)."'" : "null").",";
  1200. if (is_int($frequency)) {
  1201. $sql .= "'".$this->db->escape($frequency)."', ";
  1202. }
  1203. if (is_int($unitfrequency)) {
  1204. $sql .= "'".$this->db->escape($unitfrequency)."', ";
  1205. }
  1206. if (is_int($priority)) {
  1207. $sql .= "'".$this->db->escape($priority)."', ";
  1208. }
  1209. if (is_int($status)) {
  1210. $sql .= "'".$this->db->escape($status)."', ";
  1211. }
  1212. $sql .= $entity.",";
  1213. $sql .= "'".$this->db->escape($test)."'";
  1214. $sql .= ")";
  1215. $resql = $this->db->query($sql);
  1216. if (!$resql) {
  1217. $err++;
  1218. }
  1219. }
  1220. if (!$err) {
  1221. $this->db->commit();
  1222. } else {
  1223. $this->error = $this->db->lasterror();
  1224. $this->db->rollback();
  1225. }
  1226. }
  1227. // else box already registered into database
  1228. } else {
  1229. $this->error = $this->db->lasterror();
  1230. $err++;
  1231. }
  1232. }
  1233. }
  1234. return $err;
  1235. }
  1236. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1237. /**
  1238. * Removes boxes
  1239. *
  1240. * @return int Error count (0 if OK)
  1241. */
  1242. public function delete_cronjobs()
  1243. {
  1244. // phpcs:enable
  1245. global $conf;
  1246. $err = 0;
  1247. if (is_array($this->cronjobs)) {
  1248. $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
  1249. $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."'";
  1250. $sql .= " AND entity = ".$conf->entity;
  1251. $sql .= " AND test = '1'"; // We delete on lines that are not set with a complete test that is '$conf->module->enabled' so when module is disabled, the cron is also removed.
  1252. // For crons declared with a '$conf->module->enabled', there is no need to delete the line, so we don't loose setup if we reenable module.
  1253. dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG);
  1254. $resql = $this->db->query($sql);
  1255. if (!$resql) {
  1256. $this->error = $this->db->lasterror();
  1257. $err++;
  1258. }
  1259. }
  1260. return $err;
  1261. }
  1262. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1263. /**
  1264. * Removes tabs
  1265. *
  1266. * @return int Error count (0 if OK)
  1267. */
  1268. public function delete_tabs()
  1269. {
  1270. // phpcs:enable
  1271. global $conf;
  1272. $err = 0;
  1273. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  1274. $sql .= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'";
  1275. $sql .= " AND entity = ".$conf->entity;
  1276. dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG);
  1277. if (!$this->db->query($sql)) {
  1278. $this->error = $this->db->lasterror();
  1279. $err++;
  1280. }
  1281. return $err;
  1282. }
  1283. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1284. /**
  1285. * Adds tabs
  1286. *
  1287. * @return int Error count (0 if ok)
  1288. */
  1289. public function insert_tabs()
  1290. {
  1291. // phpcs:enable
  1292. global $conf;
  1293. $err = 0;
  1294. if (!empty($this->tabs)) {
  1295. dol_syslog(get_class($this)."::insert_tabs", LOG_DEBUG);
  1296. $i = 0;
  1297. foreach ($this->tabs as $key => $value) {
  1298. if (is_array($value) && count($value) == 0) {
  1299. continue; // Discard empty arrays
  1300. }
  1301. $entity = $conf->entity;
  1302. $newvalue = $value;
  1303. if (is_array($value)) {
  1304. $newvalue = $value['data'];
  1305. if (isset($value['entity'])) {
  1306. $entity = $value['entity'];
  1307. }
  1308. }
  1309. if ($newvalue) {
  1310. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
  1311. $sql .= "name";
  1312. $sql .= ", type";
  1313. $sql .= ", value";
  1314. $sql .= ", note";
  1315. $sql .= ", visible";
  1316. $sql .= ", entity";
  1317. $sql .= ")";
  1318. $sql .= " VALUES (";
  1319. $sql .= $this->db->encrypt($this->const_name."_TABS_".$i, 1);
  1320. $sql .= ", 'chaine'";
  1321. $sql .= ", ".$this->db->encrypt($newvalue, 1);
  1322. $sql .= ", null";
  1323. $sql .= ", '0'";
  1324. $sql .= ", ".$entity;
  1325. $sql .= ")";
  1326. $resql = $this->db->query($sql);
  1327. if (!$resql) {
  1328. dol_syslog($this->db->lasterror(), LOG_ERR);
  1329. if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1330. $this->error = $this->db->lasterror();
  1331. $this->errors[] = $this->db->lasterror();
  1332. $err++;
  1333. break;
  1334. }
  1335. }
  1336. }
  1337. $i++;
  1338. }
  1339. }
  1340. return $err;
  1341. }
  1342. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1343. /**
  1344. * Adds constants
  1345. *
  1346. * @return int Error count (0 if OK)
  1347. */
  1348. public function insert_const()
  1349. {
  1350. // phpcs:enable
  1351. global $conf;
  1352. $err = 0;
  1353. if (empty($this->const)) {
  1354. return 0;
  1355. }
  1356. dol_syslog(get_class($this)."::insert_const", LOG_DEBUG);
  1357. foreach ($this->const as $key => $value) {
  1358. $name = $this->const[$key][0];
  1359. $type = $this->const[$key][1];
  1360. $val = $this->const[$key][2];
  1361. $note = isset($this->const[$key][3]) ? $this->const[$key][3] : '';
  1362. $visible = isset($this->const[$key][4]) ? $this->const[$key][4] : 0;
  1363. $entity = (!empty($this->const[$key][5]) && $this->const[$key][5] != 'current') ? 0 : $conf->entity;
  1364. // Clean
  1365. if (empty($visible)) {
  1366. $visible = '0';
  1367. }
  1368. if (empty($val) && $val != '0') {
  1369. $val = '';
  1370. }
  1371. $sql = "SELECT count(*)";
  1372. $sql .= " FROM ".MAIN_DB_PREFIX."const";
  1373. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
  1374. $sql .= " AND entity = ".((int) $entity);
  1375. $result = $this->db->query($sql);
  1376. if ($result) {
  1377. $row = $this->db->fetch_row($result);
  1378. if ($row[0] == 0) { // If not found
  1379. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)";
  1380. $sql .= " VALUES (";
  1381. $sql .= $this->db->encrypt($name, 1);
  1382. $sql .= ",'".$this->db->escape($type)."'";
  1383. $sql .= ",".(($val != '') ? $this->db->encrypt($val, 1) : "''");
  1384. $sql .= ",".($note ? "'".$this->db->escape($note)."'" : "null");
  1385. $sql .= ",'".$this->db->escape($visible)."'";
  1386. $sql .= ",".$entity;
  1387. $sql .= ")";
  1388. if (!$this->db->query($sql)) {
  1389. $err++;
  1390. }
  1391. } else {
  1392. dol_syslog(get_class($this)."::insert_const constant '".$name."' already exists", LOG_WARNING);
  1393. }
  1394. } else {
  1395. $err++;
  1396. }
  1397. }
  1398. return $err;
  1399. }
  1400. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1401. /**
  1402. * Removes constants tagged 'deleteonunactive'
  1403. *
  1404. * @return int <0 if KO, 0 if OK
  1405. */
  1406. public function delete_const()
  1407. {
  1408. // phpcs:enable
  1409. global $conf;
  1410. $err = 0;
  1411. if (empty($this->const)) {
  1412. return 0;
  1413. }
  1414. foreach ($this->const as $key => $value) {
  1415. $name = $this->const[$key][0];
  1416. $deleteonunactive = (!empty($this->const[$key][6])) ? 1 : 0;
  1417. if ($deleteonunactive) {
  1418. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  1419. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
  1420. $sql .= " AND entity in (0, ".$conf->entity.")";
  1421. dol_syslog(get_class($this)."::delete_const", LOG_DEBUG);
  1422. if (!$this->db->query($sql)) {
  1423. $this->error = $this->db->lasterror();
  1424. $err++;
  1425. }
  1426. }
  1427. }
  1428. return $err;
  1429. }
  1430. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1431. /**
  1432. * Adds access rights
  1433. *
  1434. * @param int $reinitadminperms If 1, we also grant them to all admin users
  1435. * @param int $force_entity Force current entity
  1436. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1437. * @return int Error count (0 if OK)
  1438. */
  1439. public function insert_permissions($reinitadminperms = 0, $force_entity = null, $notrigger = 0)
  1440. {
  1441. // phpcs:enable
  1442. global $conf, $user;
  1443. $err = 0;
  1444. $entity = (!empty($force_entity) ? $force_entity : $conf->entity);
  1445. dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG);
  1446. // Test if module is activated
  1447. $sql_del = "SELECT ".$this->db->decrypt('value')." as value";
  1448. $sql_del .= " FROM ".MAIN_DB_PREFIX."const";
  1449. $sql_del .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
  1450. $sql_del .= " AND entity IN (0,".$entity.")";
  1451. $resql = $this->db->query($sql_del);
  1452. if ($resql) {
  1453. $obj = $this->db->fetch_object($resql);
  1454. if ($obj !== null && !empty($obj->value) && !empty($this->rights)) {
  1455. // If the module is active
  1456. foreach ($this->rights as $key => $value) {
  1457. $r_id = $this->rights[$key][0];
  1458. $r_desc = $this->rights[$key][1];
  1459. $r_type = isset($this->rights[$key][2]) ? $this->rights[$key][2] : '';
  1460. $r_def = empty($this->rights[$key][3]) ? 0 : $this->rights[$key][3];
  1461. $r_perms = $this->rights[$key][4];
  1462. $r_subperms = isset($this->rights[$key][5]) ? $this->rights[$key][5] : '';
  1463. $r_modul = empty($this->rights_class) ?strtolower($this->name) : $this->rights_class;
  1464. if (empty($r_type)) {
  1465. $r_type = 'w';
  1466. }
  1467. // Search if perm already present
  1468. $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def";
  1469. $sql .= " WHERE id = ".((int) $r_id)." AND entity = ".((int) $entity);
  1470. $resqlselect = $this->db->query($sql);
  1471. if ($resqlselect) {
  1472. $objcount = $this->db->fetch_object($resqlselect);
  1473. if ($objcount && $objcount->nb == 0) {
  1474. if (dol_strlen($r_perms)) {
  1475. if (dol_strlen($r_subperms)) {
  1476. $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def";
  1477. $sql .= " (id, entity, libelle, module, type, bydefault, perms, subperms)";
  1478. $sql .= " VALUES ";
  1479. $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$this->db->escape($r_modul)."','".$this->db->escape($r_type)."',".$r_def.",'".$this->db->escape($r_perms)."','".$this->db->escape($r_subperms)."')";
  1480. } else {
  1481. $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def";
  1482. $sql .= " (id, entity, libelle, module, type, bydefault, perms)";
  1483. $sql .= " VALUES ";
  1484. $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$this->db->escape($r_modul)."','".$this->db->escape($r_type)."',".$r_def.",'".$this->db->escape($r_perms)."')";
  1485. }
  1486. } else {
  1487. $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def ";
  1488. $sql .= " (id, entity, libelle, module, type, bydefault)";
  1489. $sql .= " VALUES ";
  1490. $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$this->db->escape($r_modul)."','".$this->db->escape($r_type)."',".$r_def.")";
  1491. }
  1492. $resqlinsert = $this->db->query($sql, 1);
  1493. if (!$resqlinsert) {
  1494. if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") {
  1495. $this->error = $this->db->lasterror();
  1496. $err++;
  1497. break;
  1498. } else {
  1499. dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO);
  1500. }
  1501. }
  1502. $this->db->free($resqlinsert);
  1503. }
  1504. $this->db->free($resqlselect);
  1505. }
  1506. // If we want to init permissions on admin users
  1507. if ($reinitadminperms) {
  1508. if (!class_exists('User')) {
  1509. include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  1510. }
  1511. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1";
  1512. dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG);
  1513. $resqlseladmin = $this->db->query($sql, 1);
  1514. if ($resqlseladmin) {
  1515. $num = $this->db->num_rows($resqlseladmin);
  1516. $i = 0;
  1517. while ($i < $num) {
  1518. $obj2 = $this->db->fetch_object($resqlseladmin);
  1519. dol_syslog(get_class($this)."::insert_permissions Add permission to user id=".$obj2->rowid);
  1520. $tmpuser = new User($this->db);
  1521. $result = $tmpuser->fetch($obj2->rowid);
  1522. if ($result > 0) {
  1523. $tmpuser->addrights($r_id, '', '', 0, 1);
  1524. } else {
  1525. dol_syslog(get_class($this)."::insert_permissions Failed to add the permission to user because fetch return an error", LOG_ERR);
  1526. }
  1527. $i++;
  1528. }
  1529. } else {
  1530. dol_print_error($this->db);
  1531. }
  1532. }
  1533. }
  1534. if ($reinitadminperms && !empty($user->admin)) { // Reload permission for current user if defined
  1535. // We reload permissions
  1536. $user->clearrights();
  1537. $user->getrights();
  1538. }
  1539. }
  1540. $this->db->free($resql);
  1541. } else {
  1542. $this->error = $this->db->lasterror();
  1543. $err++;
  1544. }
  1545. return $err;
  1546. }
  1547. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1548. /**
  1549. * Removes access rights
  1550. *
  1551. * @return int Error count (0 if OK)
  1552. */
  1553. public function delete_permissions()
  1554. {
  1555. // phpcs:enable
  1556. global $conf;
  1557. $err = 0;
  1558. $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def";
  1559. $sql .= " WHERE module = '".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."'";
  1560. $sql .= " AND entity = ".$conf->entity;
  1561. dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG);
  1562. if (!$this->db->query($sql)) {
  1563. $this->error = $this->db->lasterror();
  1564. $err++;
  1565. }
  1566. return $err;
  1567. }
  1568. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1569. /**
  1570. * Adds menu entries
  1571. *
  1572. * @return int Error count (0 if OK)
  1573. */
  1574. public function insert_menus()
  1575. {
  1576. // phpcs:enable
  1577. global $user;
  1578. if (!is_array($this->menu) || empty($this->menu)) {
  1579. return 0;
  1580. }
  1581. include_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php';
  1582. dol_syslog(get_class($this)."::insert_menus", LOG_DEBUG);
  1583. $err = 0;
  1584. $this->db->begin();
  1585. foreach ($this->menu as $key => $value) {
  1586. $menu = new Menubase($this->db);
  1587. $menu->menu_handler = 'all';
  1588. //$menu->module=strtolower($this->name); TODO When right_class will be same than module name
  1589. $menu->module = empty($this->rights_class) ?strtolower($this->name) : $this->rights_class;
  1590. if (!$this->menu[$key]['fk_menu']) {
  1591. $menu->fk_menu = 0;
  1592. } else {
  1593. $foundparent = 0;
  1594. $fk_parent = $this->menu[$key]['fk_menu'];
  1595. if (preg_match('/^r=/', $fk_parent)) { // old deprecated method
  1596. $fk_parent = str_replace('r=', '', $fk_parent);
  1597. if (isset($this->menu[$fk_parent]['rowid'])) {
  1598. $menu->fk_menu = $this->menu[$fk_parent]['rowid'];
  1599. $foundparent = 1;
  1600. }
  1601. } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
  1602. $menu->fk_menu = -1;
  1603. $menu->fk_mainmenu = $reg[1];
  1604. $menu->fk_leftmenu = $reg[2];
  1605. $foundparent = 1;
  1606. } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
  1607. $menu->fk_menu = -1;
  1608. $menu->fk_mainmenu = $reg[1];
  1609. $menu->fk_leftmenu = '';
  1610. $foundparent = 1;
  1611. }
  1612. if (!$foundparent) {
  1613. $this->error = "ErrorBadDefinitionOfMenuArrayInModuleDescriptor";
  1614. dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR);
  1615. $err++;
  1616. }
  1617. }
  1618. $menu->type = $this->menu[$key]['type'];
  1619. $menu->mainmenu = isset($this->menu[$key]['mainmenu']) ? $this->menu[$key]['mainmenu'] : (isset($menu->fk_mainmenu) ? $menu->fk_mainmenu : '');
  1620. $menu->leftmenu = isset($this->menu[$key]['leftmenu']) ? $this->menu[$key]['leftmenu'] : '';
  1621. $menu->title = $this->menu[$key]['titre'];
  1622. $menu->prefix = isset($this->menu[$key]['prefix']) ? $this->menu[$key]['prefix'] : '';
  1623. $menu->url = $this->menu[$key]['url'];
  1624. $menu->langs = isset($this->menu[$key]['langs']) ? $this->menu[$key]['langs'] : '';
  1625. $menu->position = $this->menu[$key]['position'];
  1626. $menu->perms = $this->menu[$key]['perms'];
  1627. $menu->target = isset($this->menu[$key]['target']) ? $this->menu[$key]['target'] : '';
  1628. $menu->user = $this->menu[$key]['user'];
  1629. $menu->enabled = isset($this->menu[$key]['enabled']) ? $this->menu[$key]['enabled'] : 0;
  1630. $menu->position = $this->menu[$key]['position'];
  1631. if (!$err) {
  1632. $result = $menu->create($user); // Save menu entry into table llx_menu
  1633. if ($result > 0) {
  1634. $this->menu[$key]['rowid'] = $result;
  1635. } else {
  1636. $this->error = $menu->error;
  1637. dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR);
  1638. $err++;
  1639. break;
  1640. }
  1641. }
  1642. }
  1643. if (!$err) {
  1644. $this->db->commit();
  1645. } else {
  1646. dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR);
  1647. $this->db->rollback();
  1648. }
  1649. return $err;
  1650. }
  1651. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1652. /**
  1653. * Removes menu entries
  1654. *
  1655. * @return int Error count (0 if OK)
  1656. */
  1657. public function delete_menus()
  1658. {
  1659. // phpcs:enable
  1660. global $conf;
  1661. $err = 0;
  1662. //$module=strtolower($this->name); TODO When right_class will be same than module name
  1663. $module = empty($this->rights_class) ?strtolower($this->name) : $this->rights_class;
  1664. $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu";
  1665. $sql .= " WHERE module = '".$this->db->escape($module)."'";
  1666. $sql .= " AND entity = ".$conf->entity;
  1667. dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG);
  1668. $resql = $this->db->query($sql);
  1669. if (!$resql) {
  1670. $this->error = $this->db->lasterror();
  1671. $err++;
  1672. }
  1673. return $err;
  1674. }
  1675. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1676. /**
  1677. * Creates directories
  1678. *
  1679. * @return int Error count (0 if OK)
  1680. */
  1681. public function create_dirs()
  1682. {
  1683. // phpcs:enable
  1684. global $langs, $conf;
  1685. $err = 0;
  1686. if (isset($this->dirs) && is_array($this->dirs)) {
  1687. foreach ($this->dirs as $key => $value) {
  1688. $addtodatabase = 0;
  1689. if (!is_array($value)) {
  1690. $dir = $value; // Default simple mode
  1691. } else {
  1692. $constname = $this->const_name."_DIR_";
  1693. $dir = $this->dirs[$key][1];
  1694. $addtodatabase = empty($this->dirs[$key][2]) ? '' : $this->dirs[$key][2]; // Create constante in llx_const
  1695. $subname = empty($this->dirs[$key][3]) ? '' : strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output)
  1696. $forcename = empty($this->dirs[$key][4]) ? '' : strtoupper($this->dirs[$key][4]); // Change the module name if different
  1697. if (!empty($forcename)) {
  1698. $constname = 'MAIN_MODULE_'.$forcename."_DIR_";
  1699. }
  1700. if (!empty($subname)) {
  1701. $constname = $constname.$subname."_";
  1702. }
  1703. $name = $constname.strtoupper($this->dirs[$key][0]);
  1704. }
  1705. // Define directory full path ($dir must start with "/")
  1706. if (empty($conf->global->MAIN_MODULE_MULTICOMPANY) || $conf->entity == 1) {
  1707. $fulldir = DOL_DATA_ROOT.$dir;
  1708. } else {
  1709. $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir;
  1710. }
  1711. // Create dir if it does not exists
  1712. if (!empty($fulldir) && !file_exists($fulldir)) {
  1713. if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) {
  1714. $this->error = $langs->trans("ErrorCanNotCreateDir", $fulldir);
  1715. dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR);
  1716. $err++;
  1717. }
  1718. }
  1719. // Define the constant in database if requested (not the default mode)
  1720. if (!empty($addtodatabase)) {
  1721. $result = $this->insert_dirs($name, $dir);
  1722. if ($result) {
  1723. $err++;
  1724. }
  1725. }
  1726. }
  1727. }
  1728. return $err;
  1729. }
  1730. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1731. /**
  1732. * Adds directories definitions
  1733. *
  1734. * @param string $name Name
  1735. * @param string $dir Directory
  1736. *
  1737. * @return int Error count (0 if OK)
  1738. */
  1739. public function insert_dirs($name, $dir)
  1740. {
  1741. // phpcs:enable
  1742. global $conf;
  1743. $err = 0;
  1744. $sql = "SELECT count(*)";
  1745. $sql .= " FROM ".MAIN_DB_PREFIX."const";
  1746. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
  1747. $sql .= " AND entity = ".$conf->entity;
  1748. dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
  1749. $result = $this->db->query($sql);
  1750. if ($result) {
  1751. $row = $this->db->fetch_row($result);
  1752. if ($row[0] == 0) {
  1753. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)";
  1754. $sql .= " VALUES (".$this->db->encrypt($name, 1).",'chaine',".$this->db->encrypt($dir, 1).",'Directory for module ".$this->name."','0',".$conf->entity.")";
  1755. dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
  1756. $this->db->query($sql);
  1757. }
  1758. } else {
  1759. $this->error = $this->db->lasterror();
  1760. $err++;
  1761. }
  1762. return $err;
  1763. }
  1764. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1765. /**
  1766. * Removes directories
  1767. *
  1768. * @return int Error count (0 if OK)
  1769. */
  1770. public function delete_dirs()
  1771. {
  1772. // phpcs:enable
  1773. global $conf;
  1774. $err = 0;
  1775. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  1776. $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'";
  1777. $sql .= " AND entity = ".$conf->entity;
  1778. dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG);
  1779. if (!$this->db->query($sql)) {
  1780. $this->error = $this->db->lasterror();
  1781. $err++;
  1782. }
  1783. return $err;
  1784. }
  1785. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1786. /**
  1787. * Adds generic parts
  1788. *
  1789. * @return int Error count (0 if OK)
  1790. */
  1791. public function insert_module_parts()
  1792. {
  1793. // phpcs:enable
  1794. global $conf;
  1795. $error = 0;
  1796. if (is_array($this->module_parts) && !empty($this->module_parts)) {
  1797. foreach ($this->module_parts as $key => $value) {
  1798. if (is_array($value) && count($value) == 0) {
  1799. continue; // Discard empty arrays
  1800. }
  1801. $entity = $conf->entity; // Reset the current entity
  1802. $newvalue = $value;
  1803. // Serialize array parameters
  1804. if (is_array($value)) {
  1805. // Can defined other parameters
  1806. // Example when $key='hooks', then $value is an array('data'=>array('hookcontext1','hookcontext2'), 'entity'=>X)
  1807. if (isset($value['data']) && is_array($value['data'])) {
  1808. $newvalue = json_encode($value['data']);
  1809. if (isset($value['entity'])) {
  1810. $entity = $value['entity'];
  1811. }
  1812. } elseif (isset($value['data']) && !is_array($value['data'])) {
  1813. $newvalue = $value['data'];
  1814. if (isset($value['entity'])) {
  1815. $entity = $value['entity'];
  1816. }
  1817. } else // when hook is declared with syntax 'hook'=>array('hookcontext1','hookcontext2',...)
  1818. {
  1819. $newvalue = json_encode($value);
  1820. }
  1821. }
  1822. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
  1823. $sql .= "name";
  1824. $sql .= ", type";
  1825. $sql .= ", value";
  1826. $sql .= ", note";
  1827. $sql .= ", visible";
  1828. $sql .= ", entity";
  1829. $sql .= ")";
  1830. $sql .= " VALUES (";
  1831. $sql .= $this->db->encrypt($this->const_name."_".strtoupper($key), 1);
  1832. $sql .= ", 'chaine'";
  1833. $sql .= ", ".$this->db->encrypt($newvalue, 1);
  1834. $sql .= ", null";
  1835. $sql .= ", '0'";
  1836. $sql .= ", ".$entity;
  1837. $sql .= ")";
  1838. dol_syslog(get_class($this)."::insert_module_parts for key=".$this->const_name."_".strtoupper($key), LOG_DEBUG);
  1839. $resql = $this->db->query($sql, 1);
  1840. if (!$resql) {
  1841. if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1842. $error++;
  1843. $this->error = $this->db->lasterror();
  1844. } else {
  1845. dol_syslog(get_class($this)."::insert_module_parts for ".$this->const_name."_".strtoupper($key)." Record already exists.", LOG_WARNING);
  1846. }
  1847. }
  1848. }
  1849. }
  1850. return $error;
  1851. }
  1852. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1853. /**
  1854. * Removes generic parts
  1855. *
  1856. * @return int Error count (0 if OK)
  1857. */
  1858. public function delete_module_parts()
  1859. {
  1860. // phpcs:enable
  1861. global $conf;
  1862. $err = 0;
  1863. $entity = $conf->entity;
  1864. if (is_array($this->module_parts) && !empty($this->module_parts)) {
  1865. foreach ($this->module_parts as $key => $value) {
  1866. // If entity is defined
  1867. if (is_array($value) && isset($value['entity'])) {
  1868. $entity = $value['entity'];
  1869. }
  1870. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  1871. $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'";
  1872. $sql .= " AND entity = ".((int) $entity);
  1873. dol_syslog(get_class($this)."::delete_const_".$key."", LOG_DEBUG);
  1874. if (!$this->db->query($sql)) {
  1875. $this->error = $this->db->lasterror();
  1876. $err++;
  1877. }
  1878. }
  1879. }
  1880. return $err;
  1881. }
  1882. /**
  1883. * Function called when module is enabled.
  1884. * The init function adds tabs, constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
  1885. * It also creates data directories
  1886. *
  1887. * @param string $options Options when enabling module ('', 'newboxdefonly', 'noboxes', 'menuonly')
  1888. * 'noboxes' = Do not insert boxes 'newboxdefonly' = For boxes, insert def of boxes only and not boxes activation
  1889. * @return int 1 if OK, 0 if KO
  1890. */
  1891. public function init($options = '')
  1892. {
  1893. return $this->_init(array(), $options);
  1894. }
  1895. /**
  1896. * Function called when module is disabled.
  1897. * The remove function removes tabs, constants, boxes, permissions and menus from Dolibarr database.
  1898. * Data directories are not deleted
  1899. *
  1900. * @param string $options Options when enabling module ('', 'noboxes')
  1901. * @return int 1 if OK, 0 if KO
  1902. */
  1903. public function remove($options = '')
  1904. {
  1905. return $this->_remove(array(), $options);
  1906. }
  1907. /**
  1908. * Return Kanban view of a module
  1909. *
  1910. * @param string $codeenabledisable HTML code for button to enable/disable module
  1911. * @param string $codetoconfig HTML code to go to config page
  1912. * @return string HTML code of Kanban view
  1913. */
  1914. public function getKanbanView($codeenabledisable = '', $codetoconfig = '')
  1915. {
  1916. global $conf, $langs;
  1917. // Define imginfo
  1918. $imginfo = "info";
  1919. if ($this->isCoreOrExternalModule() == 'external') {
  1920. $imginfo = "info_black";
  1921. }
  1922. $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($this)));
  1923. $version = $this->getVersion(0);
  1924. $versiontrans = '';
  1925. if (preg_match('/development/i', $version)) {
  1926. $versiontrans .= 'warning';
  1927. }
  1928. if (preg_match('/experimental/i', $version)) {
  1929. $versiontrans .= 'warning';
  1930. }
  1931. if (preg_match('/deprecated/i', $version)) {
  1932. $versiontrans .= 'warning';
  1933. }
  1934. print '
  1935. <div class="box-flex-item info-box-module'
  1936. .(empty($conf->global->$const_name) ? ' --disabled' : '')
  1937. .($this->isCoreOrExternalModule() == 'external' ? ' --external' : '')
  1938. .($this->needUpdate ? ' --need-update' : '')
  1939. .'">
  1940. <div class="info-box info-box-sm info-box-module">
  1941. <div class="info-box-icon'.(empty($conf->global->$const_name) ? '' : ' info-box-icon-module-enabled'.($versiontrans ? ' info-box-icon-module-warning' : '')).'">';
  1942. $alttext = '';
  1943. //if (is_array($objMod->need_dolibarr_version)) $alttext.=($alttext?' - ':'').'Dolibarr >= '.join('.',$objMod->need_dolibarr_version);
  1944. //if (is_array($objMod->phpmin)) $alttext.=($alttext?' - ':'').'PHP >= '.join('.',$objMod->phpmin);
  1945. if (!empty($this->picto)) {
  1946. if (preg_match('/^\//i', $this->picto)) {
  1947. print img_picto($alttext, $this->picto, 'class="inline-block valignmiddle"', 1);
  1948. } else {
  1949. print img_object($alttext, $this->picto, 'class="inline-block valignmiddle"');
  1950. }
  1951. } else {
  1952. print img_object($alttext, 'generic', 'class="inline-block valignmiddle"');
  1953. }
  1954. if ($this->isCoreOrExternalModule() == 'external' || preg_match('/development|experimental|deprecated/i', $version)) {
  1955. $versionTitle = $langs->trans("Version").' '.$this->getVersion(1);
  1956. if ($this->needUpdate) {
  1957. $versionTitle.= '<br>'.$langs->trans('ModuleUpdateAvailable').' : '.$this->lastVersion;
  1958. }
  1959. print '<span class="info-box-icon-version'.($versiontrans ? ' '.$versiontrans : '').' classfortooltip" title="'.dol_escape_js($versionTitle).'" >';
  1960. print $this->getVersion(1);
  1961. print '</span>';
  1962. }
  1963. print '</div>
  1964. <div class="info-box-content info-box-text-module'.(empty($conf->global->$const_name) ? '' : ' info-box-module-enabled'.($versiontrans ? ' info-box-content-warning' : '')).'">
  1965. <span class="info-box-title">'.$this->getName().'</span>
  1966. <span class="info-box-desc twolinesmax opacitymedium" title="'.dol_escape_htmltag($this->getDesc()).'">'.nl2br($this->getDesc()).'</span>';
  1967. print '<div class="valignmiddle inline-block info-box-more">';
  1968. //if ($versiontrans) print img_warning($langs->trans("Version").' '.$this->getVersion(1)).' ';
  1969. print '<a class="valignmiddle inline-block" href="javascript:document_preview(\''.DOL_URL_ROOT.'/admin/modulehelp.php?id='.$this->numero.'\',\'text/html\',\''.dol_escape_js($langs->trans("Module")).'\')">'.img_picto(($this->isCoreOrExternalModule() == 'external' ? $langs->trans("ExternalModule").' - ' : '').$langs->trans("ClickToShowDescription"), $imginfo).'</a>';
  1970. print '</div><br>';
  1971. print '<div class="valignmiddle inline-block info-box-actions">';
  1972. print '<div class="valignmiddle inline-block info-box-setup">';
  1973. print $codetoconfig;
  1974. print '</div>';
  1975. print '<div class="valignmiddle inline-block marginleftonly marginrightonly">';
  1976. print $codeenabledisable;
  1977. print '</div>';
  1978. print '</div>';
  1979. print '
  1980. </div><!-- /.info-box-content -->
  1981. </div><!-- /.info-box -->
  1982. </div>';
  1983. }
  1984. /**
  1985. * Check for module update
  1986. * TODO : store results for $this->url_last_version and $this->needUpdate
  1987. * Add a cron task to monitor for updates
  1988. *
  1989. * @return int <0 if Error, 0 == no update needed, >0 if need update
  1990. */
  1991. public function checkForUpdate()
  1992. {
  1993. require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  1994. if (!empty($this->url_last_version)) {
  1995. $lastVersion = getURLContent($this->url_last_version, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
  1996. if (isset($lastVersion['content']) && strlen($lastVersion['content']) < 30) {
  1997. // Security warning : be careful with remote data content, the module editor could be hacked (or evil) so limit to a-z A-Z 0-9 _ . -
  1998. $this->lastVersion = preg_replace("/[^a-zA-Z0-9_\.\-]+/", "", $lastVersion['content']);
  1999. if (version_compare($this->lastVersion, $this->version) > 0) {
  2000. $this->needUpdate = true;
  2001. return 1;
  2002. } else {
  2003. $this->needUpdate = false;
  2004. return 0;
  2005. }
  2006. } else {
  2007. return -1;
  2008. }
  2009. }
  2010. return 0;
  2011. }
  2012. }