DolibarrModules.class.php 72 KB

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