DolibarrModules.class.php 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532
  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. // Search if cron entry already present
  1288. $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."cronjob";
  1289. //$sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."'";
  1290. $sql .= " WHERE label = '".$this->db->escape($label)."'";
  1291. /*if ($class) {
  1292. $sql .= " AND classesname = '".$this->db->escape($class)."'";
  1293. }
  1294. if ($objectname) {
  1295. $sql .= " AND objectname = '".$this->db->escape($objectname)."'";
  1296. }
  1297. if ($method) {
  1298. $sql .= " AND methodename = '".$this->db->escape($method)."'";
  1299. }
  1300. if ($command) {
  1301. $sql .= " AND command = '".$this->db->escape($command)."'";
  1302. }
  1303. if ($parameters) {
  1304. $sql .= " AND params = '".$this->db->escape($parameters)."'";
  1305. }*/
  1306. $sql .= " AND entity = ".((int) $entity); // Must be exact entity
  1307. $now = dol_now();
  1308. $result = $this->db->query($sql);
  1309. if ($result) {
  1310. $obj = $this->db->fetch_object($result);
  1311. if ($obj->nb == 0) {
  1312. $this->db->begin();
  1313. if (!$err) {
  1314. $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob (module_name, datec, datestart, dateend, label, jobtype, classesname, objectname, methodename, command, params, note,";
  1315. if (is_int($frequency)) {
  1316. $sql .= ' frequency,';
  1317. }
  1318. if (is_int($unitfrequency)) {
  1319. $sql .= ' unitfrequency,';
  1320. }
  1321. if (is_int($priority)) {
  1322. $sql .= ' priority,';
  1323. }
  1324. if (is_int($status)) {
  1325. $sql .= ' status,';
  1326. }
  1327. $sql .= " entity, test)";
  1328. $sql .= " VALUES (";
  1329. $sql .= "'".$this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class)."', ";
  1330. $sql .= "'".$this->db->idate($now)."', ";
  1331. $sql .= ($datestart ? "'".$this->db->idate($datestart)."'" : "'".$this->db->idate($now)."'").", ";
  1332. $sql .= ($dateend ? "'".$this->db->idate($dateend)."'" : "NULL").", ";
  1333. $sql .= "'".$this->db->escape($label)."', ";
  1334. $sql .= "'".$this->db->escape($jobtype)."', ";
  1335. $sql .= ($class ? "'".$this->db->escape($class)."'" : "null").",";
  1336. $sql .= ($objectname ? "'".$this->db->escape($objectname)."'" : "null").",";
  1337. $sql .= ($method ? "'".$this->db->escape($method)."'" : "null").",";
  1338. $sql .= ($command ? "'".$this->db->escape($command)."'" : "null").",";
  1339. $sql .= ($parameters ? "'".$this->db->escape($parameters)."'" : "null").",";
  1340. $sql .= ($comment ? "'".$this->db->escape($comment)."'" : "null").",";
  1341. if (is_int($frequency)) {
  1342. $sql .= "'".$this->db->escape($frequency)."', ";
  1343. }
  1344. if (is_int($unitfrequency)) {
  1345. $sql .= "'".$this->db->escape($unitfrequency)."', ";
  1346. }
  1347. if (is_int($priority)) {
  1348. $sql .= "'".$this->db->escape($priority)."', ";
  1349. }
  1350. if (is_int($status)) {
  1351. $sql .= ((int) $status).", ";
  1352. }
  1353. $sql .= $entity.",";
  1354. $sql .= "'".$this->db->escape($test)."'";
  1355. $sql .= ")";
  1356. $resql = $this->db->query($sql);
  1357. if (!$resql) {
  1358. $err++;
  1359. }
  1360. }
  1361. if (!$err) {
  1362. $this->db->commit();
  1363. } else {
  1364. $this->error = $this->db->lasterror();
  1365. $this->db->rollback();
  1366. }
  1367. }
  1368. // else box already registered into database
  1369. } else {
  1370. $this->error = $this->db->lasterror();
  1371. $err++;
  1372. }
  1373. }
  1374. }
  1375. return $err;
  1376. }
  1377. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1378. /**
  1379. * Removes boxes
  1380. *
  1381. * @return int Error count (0 if OK)
  1382. */
  1383. public function delete_cronjobs()
  1384. {
  1385. // phpcs:enable
  1386. global $conf;
  1387. $err = 0;
  1388. if (is_array($this->cronjobs)) {
  1389. $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
  1390. $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class)."'";
  1391. $sql .= " AND entity = ".$conf->entity;
  1392. $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.
  1393. // 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.
  1394. dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG);
  1395. $resql = $this->db->query($sql);
  1396. if (!$resql) {
  1397. $this->error = $this->db->lasterror();
  1398. $err++;
  1399. }
  1400. }
  1401. return $err;
  1402. }
  1403. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1404. /**
  1405. * Removes tabs
  1406. *
  1407. * @return int Error count (0 if OK)
  1408. */
  1409. public function delete_tabs()
  1410. {
  1411. // phpcs:enable
  1412. global $conf;
  1413. $err = 0;
  1414. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  1415. $sql .= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'";
  1416. $sql .= " AND entity = ".$conf->entity;
  1417. dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG);
  1418. if (!$this->db->query($sql)) {
  1419. $this->error = $this->db->lasterror();
  1420. $err++;
  1421. }
  1422. return $err;
  1423. }
  1424. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1425. /**
  1426. * Adds tabs
  1427. *
  1428. * @return int Error count (0 if ok)
  1429. */
  1430. public function insert_tabs()
  1431. {
  1432. // phpcs:enable
  1433. global $conf;
  1434. $err = 0;
  1435. if (!empty($this->tabs)) {
  1436. dol_syslog(get_class($this)."::insert_tabs", LOG_DEBUG);
  1437. $i = 0;
  1438. foreach ($this->tabs as $key => $value) {
  1439. if (is_array($value) && count($value) == 0) {
  1440. continue; // Discard empty arrays
  1441. }
  1442. $entity = $conf->entity;
  1443. $newvalue = $value;
  1444. if (is_array($value)) {
  1445. $newvalue = $value['data'];
  1446. if (isset($value['entity'])) {
  1447. $entity = $value['entity'];
  1448. }
  1449. }
  1450. if ($newvalue) {
  1451. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
  1452. $sql .= "name";
  1453. $sql .= ", type";
  1454. $sql .= ", value";
  1455. $sql .= ", note";
  1456. $sql .= ", visible";
  1457. $sql .= ", entity";
  1458. $sql .= ")";
  1459. $sql .= " VALUES (";
  1460. $sql .= $this->db->encrypt($this->const_name."_TABS_".$i);
  1461. $sql .= ", 'chaine'";
  1462. $sql .= ", ".$this->db->encrypt($newvalue);
  1463. $sql .= ", null";
  1464. $sql .= ", '0'";
  1465. $sql .= ", ".((int) $entity);
  1466. $sql .= ")";
  1467. $resql = $this->db->query($sql);
  1468. if (!$resql) {
  1469. dol_syslog($this->db->lasterror(), LOG_ERR);
  1470. if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1471. $this->error = $this->db->lasterror();
  1472. $this->errors[] = $this->db->lasterror();
  1473. $err++;
  1474. break;
  1475. }
  1476. }
  1477. }
  1478. $i++;
  1479. }
  1480. }
  1481. return $err;
  1482. }
  1483. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1484. /**
  1485. * Adds constants
  1486. *
  1487. * @return int Error count (0 if OK)
  1488. */
  1489. public function insert_const()
  1490. {
  1491. // phpcs:enable
  1492. global $conf;
  1493. $err = 0;
  1494. if (empty($this->const)) {
  1495. return 0;
  1496. }
  1497. dol_syslog(get_class($this)."::insert_const", LOG_DEBUG);
  1498. foreach ($this->const as $key => $value) {
  1499. $name = $this->const[$key][0];
  1500. $type = $this->const[$key][1];
  1501. $val = $this->const[$key][2];
  1502. $note = isset($this->const[$key][3]) ? $this->const[$key][3] : '';
  1503. $visible = isset($this->const[$key][4]) ? $this->const[$key][4] : 0;
  1504. $entity = (!empty($this->const[$key][5]) && $this->const[$key][5] != 'current') ? 0 : $conf->entity;
  1505. // Clean
  1506. if (empty($visible)) {
  1507. $visible = '0';
  1508. }
  1509. if (empty($val) && $val != '0') {
  1510. $val = '';
  1511. }
  1512. $sql = "SELECT count(*) as nb";
  1513. $sql .= " FROM ".MAIN_DB_PREFIX."const";
  1514. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
  1515. $sql .= " AND entity = ".((int) $entity);
  1516. $result = $this->db->query($sql);
  1517. if ($result) {
  1518. $row = $this->db->fetch_row($result);
  1519. if ($row[0] == 0) { // If not found
  1520. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)";
  1521. $sql .= " VALUES (";
  1522. $sql .= $this->db->encrypt($name);
  1523. $sql .= ",'".$this->db->escape($type)."'";
  1524. $sql .= ",".(($val != '') ? $this->db->encrypt($val) : "''");
  1525. $sql .= ",".($note ? "'".$this->db->escape($note)."'" : "null");
  1526. $sql .= ",'".$this->db->escape($visible)."'";
  1527. $sql .= ",".$entity;
  1528. $sql .= ")";
  1529. if (!$this->db->query($sql)) {
  1530. $err++;
  1531. }
  1532. } else {
  1533. dol_syslog(get_class($this)."::insert_const constant '".$name."' already exists", LOG_DEBUG);
  1534. }
  1535. } else {
  1536. $err++;
  1537. }
  1538. }
  1539. return $err;
  1540. }
  1541. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1542. /**
  1543. * Removes constants tagged 'deleteonunactive'
  1544. *
  1545. * @return int Return integer <0 if KO, 0 if OK
  1546. */
  1547. public function delete_const()
  1548. {
  1549. // phpcs:enable
  1550. global $conf;
  1551. $err = 0;
  1552. if (empty($this->const)) {
  1553. return 0;
  1554. }
  1555. foreach ($this->const as $key => $value) {
  1556. $name = $this->const[$key][0];
  1557. $deleteonunactive = (!empty($this->const[$key][6])) ? 1 : 0;
  1558. if ($deleteonunactive) {
  1559. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  1560. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
  1561. $sql .= " AND entity in (0, ".$conf->entity.")";
  1562. dol_syslog(get_class($this)."::delete_const", LOG_DEBUG);
  1563. if (!$this->db->query($sql)) {
  1564. $this->error = $this->db->lasterror();
  1565. $err++;
  1566. }
  1567. }
  1568. }
  1569. return $err;
  1570. }
  1571. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1572. /**
  1573. * Adds access rights
  1574. *
  1575. * @param int $reinitadminperms If 1, we also grant them to all admin users
  1576. * @param int $force_entity Force current entity
  1577. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1578. * @return int Error count (0 if OK)
  1579. */
  1580. public function insert_permissions($reinitadminperms = 0, $force_entity = null, $notrigger = 0)
  1581. {
  1582. // phpcs:enable
  1583. global $conf, $user;
  1584. $err = 0;
  1585. $entity = (!empty($force_entity) ? $force_entity : $conf->entity);
  1586. dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG);
  1587. // Test if module is activated
  1588. $sql_del = "SELECT ".$this->db->decrypt('value')." as value";
  1589. $sql_del .= " FROM ".MAIN_DB_PREFIX."const";
  1590. $sql_del .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
  1591. $sql_del .= " AND entity IN (0,".$entity.")";
  1592. $resql = $this->db->query($sql_del);
  1593. if ($resql) {
  1594. $obj = $this->db->fetch_object($resql);
  1595. if ($obj !== null && !empty($obj->value) && !empty($this->rights)) {
  1596. include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  1597. // If the module is active
  1598. foreach ($this->rights as $key => $value) {
  1599. $r_id = $this->rights[$key][0]; // permission id in llx_rights_def (not unique because primary key is couple id-entity)
  1600. $r_desc = $this->rights[$key][1];
  1601. $r_type = isset($this->rights[$key][2]) ? $this->rights[$key][2] : '';
  1602. $r_def = empty($this->rights[$key][3]) ? 0 : $this->rights[$key][3];
  1603. $r_perms = $this->rights[$key][4];
  1604. $r_subperms = isset($this->rights[$key][5]) ? $this->rights[$key][5] : '';
  1605. $r_modul = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
  1606. if (empty($r_type)) {
  1607. $r_type = 'w';
  1608. }
  1609. // Search if perm already present
  1610. $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def";
  1611. $sql .= " WHERE id = ".((int) $r_id)." AND entity = ".((int) $entity);
  1612. $resqlselect = $this->db->query($sql);
  1613. if ($resqlselect) {
  1614. $objcount = $this->db->fetch_object($resqlselect);
  1615. if ($objcount && $objcount->nb == 0) {
  1616. if (dol_strlen($r_perms)) {
  1617. if (dol_strlen($r_subperms)) {
  1618. $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def";
  1619. $sql .= " (id, entity, libelle, module, type, bydefault, perms, subperms)";
  1620. $sql .= " VALUES ";
  1621. $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)."')";
  1622. } else {
  1623. $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def";
  1624. $sql .= " (id, entity, libelle, module, type, bydefault, perms)";
  1625. $sql .= " VALUES ";
  1626. $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)."')";
  1627. }
  1628. } else {
  1629. $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def ";
  1630. $sql .= " (id, entity, libelle, module, type, bydefault)";
  1631. $sql .= " VALUES ";
  1632. $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$this->db->escape($r_modul)."','".$this->db->escape($r_type)."',".$r_def.")";
  1633. }
  1634. $resqlinsert = $this->db->query($sql, 1);
  1635. if (!$resqlinsert) {
  1636. if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") {
  1637. $this->error = $this->db->lasterror();
  1638. $err++;
  1639. break;
  1640. } else {
  1641. dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO);
  1642. }
  1643. }
  1644. $this->db->free($resqlinsert);
  1645. }
  1646. $this->db->free($resqlselect);
  1647. }
  1648. // If we want to init permissions on admin users
  1649. if ($reinitadminperms) {
  1650. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1";
  1651. dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG);
  1652. $resqlseladmin = $this->db->query($sql, 1);
  1653. if ($resqlseladmin) {
  1654. $num = $this->db->num_rows($resqlseladmin);
  1655. $i = 0;
  1656. while ($i < $num) {
  1657. $obj2 = $this->db->fetch_object($resqlseladmin);
  1658. dol_syslog(get_class($this)."::insert_permissions Add permission id ".$r_id." to user id=".$obj2->rowid);
  1659. $tmpuser = new User($this->db);
  1660. $result = $tmpuser->fetch($obj2->rowid);
  1661. if ($result > 0) {
  1662. $tmpuser->addrights($r_id, '', '', 0, 1);
  1663. } else {
  1664. dol_syslog(get_class($this)."::insert_permissions Failed to add the permission to user because fetch return an error", LOG_ERR);
  1665. }
  1666. $i++;
  1667. }
  1668. } else {
  1669. dol_print_error($this->db);
  1670. }
  1671. }
  1672. }
  1673. if ($reinitadminperms && !empty($user->admin)) { // Reload permission for current user if defined
  1674. // We reload permissions
  1675. $user->clearrights();
  1676. $user->getrights();
  1677. }
  1678. }
  1679. $this->db->free($resql);
  1680. } else {
  1681. $this->error = $this->db->lasterror();
  1682. $err++;
  1683. }
  1684. return $err;
  1685. }
  1686. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1687. /**
  1688. * Removes access rights
  1689. *
  1690. * @return int Error count (0 if OK)
  1691. */
  1692. public function delete_permissions()
  1693. {
  1694. // phpcs:enable
  1695. global $conf;
  1696. $err = 0;
  1697. $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def";
  1698. $sql .= " WHERE module = '".$this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class)."'";
  1699. $sql .= " AND entity = ".$conf->entity;
  1700. dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG);
  1701. if (!$this->db->query($sql)) {
  1702. $this->error = $this->db->lasterror();
  1703. $err++;
  1704. }
  1705. return $err;
  1706. }
  1707. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1708. /**
  1709. * Adds menu entries
  1710. *
  1711. * @return int Error count (0 if OK)
  1712. */
  1713. public function insert_menus()
  1714. {
  1715. // phpcs:enable
  1716. global $conf, $user;
  1717. if (!is_array($this->menu) || empty($this->menu)) {
  1718. return 0;
  1719. }
  1720. include_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php';
  1721. dol_syslog(get_class($this)."::insert_menus", LOG_DEBUG);
  1722. $err = 0;
  1723. // Common module
  1724. $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
  1725. $this->db->begin();
  1726. foreach ($this->menu as $key => $value) {
  1727. $menu = new Menubase($this->db);
  1728. $menu->menu_handler = 'all';
  1729. //$menu->module=strtolower($this->name); TODO When right_class will be same than module name
  1730. $menu->module = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
  1731. if (!$this->menu[$key]['fk_menu']) {
  1732. $menu->fk_menu = 0;
  1733. } else {
  1734. $foundparent = 0;
  1735. $fk_parent = $this->menu[$key]['fk_menu'];
  1736. $reg = array();
  1737. if (preg_match('/^r=/', $fk_parent)) { // old deprecated method
  1738. $fk_parent = str_replace('r=', '', $fk_parent);
  1739. if (isset($this->menu[$fk_parent]['rowid'])) {
  1740. $menu->fk_menu = $this->menu[$fk_parent]['rowid'];
  1741. $foundparent = 1;
  1742. }
  1743. } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
  1744. $menu->fk_menu = -1;
  1745. $menu->fk_mainmenu = $reg[1];
  1746. $menu->fk_leftmenu = $reg[2];
  1747. $foundparent = 1;
  1748. } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
  1749. $menu->fk_menu = -1;
  1750. $menu->fk_mainmenu = $reg[1];
  1751. $menu->fk_leftmenu = '';
  1752. $foundparent = 1;
  1753. }
  1754. if (!$foundparent) {
  1755. $this->error = "ErrorBadDefinitionOfMenuArrayInModuleDescriptor";
  1756. dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR);
  1757. $err++;
  1758. }
  1759. }
  1760. $menu->type = $this->menu[$key]['type'];
  1761. $menu->mainmenu = isset($this->menu[$key]['mainmenu']) ? $this->menu[$key]['mainmenu'] : (isset($menu->fk_mainmenu) ? $menu->fk_mainmenu : '');
  1762. $menu->leftmenu = isset($this->menu[$key]['leftmenu']) ? $this->menu[$key]['leftmenu'] : '';
  1763. $menu->title = $this->menu[$key]['titre'];
  1764. $menu->prefix = isset($this->menu[$key]['prefix']) ? $this->menu[$key]['prefix'] : '';
  1765. $menu->url = $this->menu[$key]['url'];
  1766. $menu->langs = isset($this->menu[$key]['langs']) ? $this->menu[$key]['langs'] : '';
  1767. $menu->position = $this->menu[$key]['position'];
  1768. $menu->perms = $this->menu[$key]['perms'];
  1769. $menu->target = isset($this->menu[$key]['target']) ? $this->menu[$key]['target'] : '';
  1770. $menu->user = $this->menu[$key]['user'];
  1771. $menu->enabled = isset($this->menu[$key]['enabled']) ? $this->menu[$key]['enabled'] : 0;
  1772. $menu->position = $this->menu[$key]['position'];
  1773. $menu->entity = $entity;
  1774. if (!$err) {
  1775. $result = $menu->create($user); // Save menu entry into table llx_menu
  1776. if ($result > 0) {
  1777. $this->menu[$key]['rowid'] = $result;
  1778. } else {
  1779. $this->error = $menu->error;
  1780. dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR);
  1781. $err++;
  1782. break;
  1783. }
  1784. }
  1785. }
  1786. if (!$err) {
  1787. $this->db->commit();
  1788. } else {
  1789. dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR);
  1790. $this->db->rollback();
  1791. }
  1792. return $err;
  1793. }
  1794. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1795. /**
  1796. * Removes menu entries
  1797. *
  1798. * @return int Error count (0 if OK)
  1799. */
  1800. public function delete_menus()
  1801. {
  1802. // phpcs:enable
  1803. global $conf;
  1804. $err = 0;
  1805. //$module=strtolower($this->name); TODO When right_class will be same than module name
  1806. $module = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
  1807. $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu";
  1808. $sql .= " WHERE module = '".$this->db->escape($module)."'";
  1809. $sql .= " AND entity IN (0, ".$conf->entity.")";
  1810. dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG);
  1811. $resql = $this->db->query($sql);
  1812. if (!$resql) {
  1813. $this->error = $this->db->lasterror();
  1814. $err++;
  1815. }
  1816. return $err;
  1817. }
  1818. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1819. /**
  1820. * Creates directories
  1821. *
  1822. * @return int Error count (0 if OK)
  1823. */
  1824. public function create_dirs()
  1825. {
  1826. // phpcs:enable
  1827. global $langs, $conf;
  1828. $err = 0;
  1829. $name = '';
  1830. if (isset($this->dirs) && is_array($this->dirs)) {
  1831. foreach ($this->dirs as $key => $value) {
  1832. $addtodatabase = 0;
  1833. if (!is_array($value)) {
  1834. $dir = $value; // Default simple mode
  1835. } else {
  1836. $constname = $this->const_name."_DIR_";
  1837. $dir = $this->dirs[$key][1];
  1838. $addtodatabase = empty($this->dirs[$key][2]) ? '' : $this->dirs[$key][2]; // Create constante in llx_const
  1839. $subname = empty($this->dirs[$key][3]) ? '' : strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output)
  1840. $forcename = empty($this->dirs[$key][4]) ? '' : strtoupper($this->dirs[$key][4]); // Change the module name if different
  1841. if (!empty($forcename)) {
  1842. $constname = 'MAIN_MODULE_'.$forcename."_DIR_";
  1843. }
  1844. if (!empty($subname)) {
  1845. $constname = $constname.$subname."_";
  1846. }
  1847. $name = $constname.strtoupper($this->dirs[$key][0]);
  1848. }
  1849. // Define directory full path ($dir must start with "/")
  1850. if (!getDolGlobalString('MAIN_MODULE_MULTICOMPANY') || $conf->entity == 1) {
  1851. $fulldir = DOL_DATA_ROOT.$dir;
  1852. } else {
  1853. $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir;
  1854. }
  1855. // Create dir if it does not exists
  1856. if (!empty($fulldir) && !file_exists($fulldir)) {
  1857. if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) {
  1858. $this->error = $langs->trans("ErrorCanNotCreateDir", $fulldir);
  1859. dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR);
  1860. $err++;
  1861. }
  1862. }
  1863. // Define the constant in database if requested (not the default mode)
  1864. if (!empty($addtodatabase) && !empty($name)) {
  1865. $result = $this->insert_dirs($name, $dir);
  1866. if ($result) {
  1867. $err++;
  1868. }
  1869. }
  1870. }
  1871. }
  1872. return $err;
  1873. }
  1874. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1875. /**
  1876. * Adds directories definitions
  1877. *
  1878. * @param string $name Name
  1879. * @param string $dir Directory
  1880. *
  1881. * @return int Error count (0 if OK)
  1882. */
  1883. public function insert_dirs($name, $dir)
  1884. {
  1885. // phpcs:enable
  1886. global $conf;
  1887. $err = 0;
  1888. $sql = "SELECT count(*)";
  1889. $sql .= " FROM ".MAIN_DB_PREFIX."const";
  1890. $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
  1891. $sql .= " AND entity = ".$conf->entity;
  1892. dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
  1893. $result = $this->db->query($sql);
  1894. if ($result) {
  1895. $row = $this->db->fetch_row($result);
  1896. if ($row[0] == 0) {
  1897. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, type, value, note, visible, entity)";
  1898. $sql .= " VALUES (".$this->db->encrypt($name).", 'chaine', ".$this->db->encrypt($dir).", '".$this->db->escape("Directory for module ".$this->name)."', '0', ".((int) $conf->entity).")";
  1899. dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
  1900. $this->db->query($sql);
  1901. }
  1902. } else {
  1903. $this->error = $this->db->lasterror();
  1904. $err++;
  1905. }
  1906. return $err;
  1907. }
  1908. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1909. /**
  1910. * Removes directories
  1911. *
  1912. * @return int Error count (0 if OK)
  1913. */
  1914. public function delete_dirs()
  1915. {
  1916. // phpcs:enable
  1917. global $conf;
  1918. $err = 0;
  1919. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  1920. $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'";
  1921. $sql .= " AND entity = ".$conf->entity;
  1922. dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG);
  1923. if (!$this->db->query($sql)) {
  1924. $this->error = $this->db->lasterror();
  1925. $err++;
  1926. }
  1927. return $err;
  1928. }
  1929. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1930. /**
  1931. * Adds generic parts
  1932. *
  1933. * @return int Error count (0 if OK)
  1934. */
  1935. public function insert_module_parts()
  1936. {
  1937. // phpcs:enable
  1938. global $conf;
  1939. $error = 0;
  1940. if (is_array($this->module_parts)) {
  1941. if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
  1942. $this->module_parts['icon'] = $this->picto;
  1943. }
  1944. foreach ($this->module_parts as $key => $value) {
  1945. if (is_array($value) && count($value) == 0) {
  1946. continue; // Discard empty arrays
  1947. }
  1948. $entity = $conf->entity; // Reset the current entity
  1949. $newvalue = $value;
  1950. // Serialize array parameters
  1951. if (is_array($value)) {
  1952. // Can defined other parameters
  1953. // Example when $key='hooks', then $value is an array('data'=>array('hookcontext1','hookcontext2'), 'entity'=>X)
  1954. if (isset($value['data']) && is_array($value['data'])) {
  1955. $newvalue = json_encode($value['data']);
  1956. if (isset($value['entity'])) {
  1957. $entity = $value['entity'];
  1958. }
  1959. } elseif (isset($value['data']) && !is_array($value['data'])) {
  1960. $newvalue = $value['data'];
  1961. if (isset($value['entity'])) {
  1962. $entity = $value['entity'];
  1963. }
  1964. } else { // when hook is declared with syntax 'hook'=>array('hookcontext1','hookcontext2',...)
  1965. $newvalue = json_encode($value);
  1966. }
  1967. }
  1968. if (!empty($newvalue)) {
  1969. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
  1970. $sql .= "name";
  1971. $sql .= ", type";
  1972. $sql .= ", value";
  1973. $sql .= ", note";
  1974. $sql .= ", visible";
  1975. $sql .= ", entity";
  1976. $sql .= ")";
  1977. $sql .= " VALUES (";
  1978. $sql .= " ".$this->db->encrypt($this->const_name."_".strtoupper($key), 1);
  1979. $sql .= ", 'chaine'";
  1980. $sql .= ", ".$this->db->encrypt($newvalue, 1);
  1981. $sql .= ", null";
  1982. $sql .= ", '0'";
  1983. $sql .= ", ".((int) $entity);
  1984. $sql .= ")";
  1985. dol_syslog(get_class($this)."::insert_module_parts for key=".$this->const_name."_".strtoupper($key), LOG_DEBUG);
  1986. $resql = $this->db->query($sql, 1);
  1987. if (!$resql) {
  1988. if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1989. $error++;
  1990. $this->error = $this->db->lasterror();
  1991. } else {
  1992. dol_syslog(get_class($this)."::insert_module_parts for ".$this->const_name."_".strtoupper($key)." Record already exists.", LOG_WARNING);
  1993. }
  1994. }
  1995. }
  1996. }
  1997. }
  1998. return $error;
  1999. }
  2000. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2001. /**
  2002. * Removes generic parts
  2003. *
  2004. * @return int Error count (0 if OK)
  2005. */
  2006. public function delete_module_parts()
  2007. {
  2008. // phpcs:enable
  2009. global $conf;
  2010. $err = 0;
  2011. if (is_array($this->module_parts)) {
  2012. dol_syslog(get_class($this)."::delete_module_parts", LOG_DEBUG);
  2013. if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
  2014. $this->module_parts['icon'] = $this->picto;
  2015. }
  2016. foreach ($this->module_parts as $key => $value) {
  2017. // If entity is defined
  2018. if (is_array($value) && isset($value['entity'])) {
  2019. $entity = $value['entity'];
  2020. } else {
  2021. $entity = $conf->entity;
  2022. }
  2023. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  2024. $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'";
  2025. $sql .= " AND entity = ".((int) $entity);
  2026. if (!$this->db->query($sql)) {
  2027. $this->error = $this->db->lasterror();
  2028. $err++;
  2029. }
  2030. }
  2031. }
  2032. return $err;
  2033. }
  2034. /**
  2035. * Function called when module is enabled.
  2036. * The init function adds tabs, constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
  2037. * It also creates data directories
  2038. *
  2039. * @param string $options Options when enabling module ('', 'newboxdefonly', 'noboxes', 'menuonly')
  2040. * 'noboxes' = Do not insert boxes 'newboxdefonly' = For boxes, insert def of boxes only and not boxes activation
  2041. * @return int 1 if OK, 0 if KO
  2042. */
  2043. public function init($options = '')
  2044. {
  2045. return $this->_init(array(), $options);
  2046. }
  2047. /**
  2048. * Function called when module is disabled.
  2049. * The remove function removes tabs, constants, boxes, permissions and menus from Dolibarr database.
  2050. * Data directories are not deleted
  2051. *
  2052. * @param string $options Options when enabling module ('', 'noboxes')
  2053. * @return int 1 if OK, 0 if KO
  2054. */
  2055. public function remove($options = '')
  2056. {
  2057. return $this->_remove(array(), $options);
  2058. }
  2059. /**
  2060. * Return Kanban view of a module
  2061. *
  2062. * @param string $codeenabledisable HTML code for button to enable/disable module
  2063. * @param string $codetoconfig HTML code to go to config page
  2064. * @return string HTML code of Kanban view
  2065. */
  2066. public function getKanbanView($codeenabledisable = '', $codetoconfig = '')
  2067. {
  2068. global $conf, $langs;
  2069. // Define imginfo
  2070. $imginfo = "info";
  2071. if ($this->isCoreOrExternalModule() == 'external') {
  2072. $imginfo = "info_black";
  2073. }
  2074. $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($this)));
  2075. $version = $this->getVersion(0);
  2076. $versiontrans = '';
  2077. if (preg_match('/development/i', $version)) {
  2078. $versiontrans .= 'warning';
  2079. }
  2080. if (preg_match('/experimental/i', $version)) {
  2081. $versiontrans .= 'warning';
  2082. }
  2083. if (preg_match('/deprecated/i', $version)) {
  2084. $versiontrans .= 'warning';
  2085. }
  2086. $return = '
  2087. <div class="box-flex-item info-box-module'
  2088. .(getDolGlobalString($const_name) ? '' : ' --disabled')
  2089. .($this->isCoreOrExternalModule() == 'external' ? ' --external' : '')
  2090. .($this->needUpdate ? ' --need-update' : '')
  2091. .'">
  2092. <div class="info-box info-box-sm info-box-module">
  2093. <div class="info-box-icon'.(!getDolGlobalString($const_name) ? '' : ' info-box-icon-module-enabled'.($versiontrans ? ' info-box-icon-module-warning' : '')).'">';
  2094. $alttext = '';
  2095. //if (is_array($objMod->need_dolibarr_version)) $alttext.=($alttext?' - ':'').'Dolibarr >= '.join('.',$objMod->need_dolibarr_version);
  2096. //if (is_array($objMod->phpmin)) $alttext.=($alttext?' - ':'').'PHP >= '.join('.',$objMod->phpmin);
  2097. if (!empty($this->picto)) {
  2098. if (preg_match('/^\//i', $this->picto)) {
  2099. $return .= img_picto($alttext, $this->picto, 'class="inline-block valignmiddle"', 1);
  2100. } else {
  2101. $return .= img_object($alttext, $this->picto, 'class="inline-block valignmiddle"');
  2102. }
  2103. } else {
  2104. $return .= img_object($alttext, 'generic', 'class="inline-block valignmiddle"');
  2105. }
  2106. if ($this->isCoreOrExternalModule() == 'external' || preg_match('/development|experimental|deprecated/i', $version)) {
  2107. $versionTitle = $langs->trans("Version").' '.$this->getVersion(1);
  2108. if ($this->needUpdate) {
  2109. $versionTitle.= '<br>'.$langs->trans('ModuleUpdateAvailable').' : '.$this->lastVersion;
  2110. }
  2111. $return .= '<span class="info-box-icon-version'.($versiontrans ? ' '.$versiontrans : '').' classfortooltip" title="'.dol_escape_js($versionTitle).'" >';
  2112. $return .= $this->getVersion(1);
  2113. $return .= '</span>';
  2114. }
  2115. $return .= '</div>
  2116. <div class="info-box-content info-box-text-module'.(!getDolGlobalString($const_name) ? '' : ' info-box-module-enabled'.($versiontrans ? ' info-box-content-warning' : '')).'">
  2117. <span class="info-box-title">'.$this->getName().'</span>
  2118. <span class="info-box-desc twolinesmax opacitymedium" title="'.dol_escape_htmltag($this->getDesc()).'">'.nl2br($this->getDesc()).'</span>';
  2119. $return .= '<div class="valignmiddle inline-block info-box-more">';
  2120. //if ($versiontrans) print img_warning($langs->trans("Version").' '.$this->getVersion(1)).' ';
  2121. $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>';
  2122. $return .= '</div><br>';
  2123. $return .= '<div class="valignmiddle inline-block info-box-actions">';
  2124. $return .= '<div class="valignmiddle inline-block info-box-setup">';
  2125. $return .= $codetoconfig;
  2126. $return .= '</div>';
  2127. $return .= '<div class="valignmiddle inline-block marginleftonly marginrightonly">';
  2128. $return .= $codeenabledisable;
  2129. $return .= '</div>';
  2130. $return .= '</div>';
  2131. $return .= '
  2132. </div><!-- /.info-box-content -->
  2133. </div><!-- /.info-box -->
  2134. </div>';
  2135. return $return;
  2136. }
  2137. /**
  2138. * Check for module update
  2139. * TODO : store results for $this->url_last_version and $this->needUpdate
  2140. * Add a cron task to monitor for updates
  2141. *
  2142. * @return int Return integer <0 if Error, 0 == no update needed, >0 if need update
  2143. */
  2144. public function checkForUpdate()
  2145. {
  2146. require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  2147. if (!empty($this->url_last_version)) {
  2148. $lastVersion = getURLContent($this->url_last_version, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
  2149. if (isset($lastVersion['content']) && strlen($lastVersion['content']) < 30) {
  2150. // 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 _ . -
  2151. $this->lastVersion = preg_replace("/[^a-zA-Z0-9_\.\-]+/", "", $lastVersion['content']);
  2152. if (version_compare($this->lastVersion, $this->version) > 0) {
  2153. $this->needUpdate = true;
  2154. return 1;
  2155. } else {
  2156. $this->needUpdate = false;
  2157. return 0;
  2158. }
  2159. } else {
  2160. return -1;
  2161. }
  2162. }
  2163. return 0;
  2164. }
  2165. }