DolibarrModules.class.php 77 KB

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