modulebuilder.lib.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. <?php
  2. /* Copyright (C) 2009-2010 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. * or see https://www.gnu.org/
  17. */
  18. /**
  19. * \file htdocs/core/lib/modulebuilder.lib.php
  20. * \brief Set of function for modulebuilder management
  21. */
  22. /**
  23. * Regenerate files .class.php
  24. *
  25. * @param string $destdir Directory
  26. * @param string $module Module name
  27. * @param string $objectname Name of object
  28. * @param string $newmask New mask
  29. * @param string $readdir Directory source (use $destdir when not defined)
  30. * @param string $addfieldentry Array of 1 field entry to add array('key'=>,'type'=>,''label'=>,'visible'=>,'enabled'=>,'position'=>,'notnull'=>','index'=>,'searchall'=>,'comment'=>,'help'=>,'isameasure')
  31. * @param string $delfieldentry Id of field to remove
  32. * @return int|object Return integer <=0 if KO, Object if OK
  33. * @see rebuildObjectSql()
  34. */
  35. function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = '', $addfieldentry = array(), $delfieldentry = '')
  36. {
  37. global $db, $langs;
  38. if (empty($objectname)) {
  39. return -6;
  40. }
  41. if (empty($readdir)) {
  42. $readdir = $destdir;
  43. }
  44. if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) {
  45. dol_print_error('', 'Bad parameter addfieldentry with a property arrayofkeyval defined but that is not an array.');
  46. return -7;
  47. }
  48. $error = 0;
  49. // Check parameters
  50. if (is_array($addfieldentry) && count($addfieldentry) > 0) {
  51. if (empty($addfieldentry['name'])) {
  52. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Name")), null, 'errors');
  53. return -2;
  54. }
  55. if (empty($addfieldentry['label'])) {
  56. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors');
  57. return -2;
  58. }
  59. if (!preg_match('/^(integer|price|sellist|varchar|double|text|html|duration)/', $addfieldentry['type'])
  60. && !preg_match('/^(boolean|smallint|real|date|datetime|timestamp|phone|mail|url|ip|password)$/', $addfieldentry['type'])) {
  61. setEventMessages($langs->trans('BadValueForType', $addfieldentry['type']), null, 'errors');
  62. return -2;
  63. }
  64. }
  65. $pathoffiletoeditsrc = $readdir.'/class/'.strtolower($objectname).'.class.php';
  66. $pathoffiletoedittarget = $destdir.'/class/'.strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : '');
  67. if (!dol_is_file($pathoffiletoeditsrc)) {
  68. $langs->load("errors");
  69. setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
  70. return -3;
  71. }
  72. //$pathoffiletoedittmp=$destdir.'/class/'.strtolower($objectname).'.class.php.tmp';
  73. //dol_delete_file($pathoffiletoedittmp, 0, 1, 1);
  74. try {
  75. include_once $pathoffiletoeditsrc;
  76. if (class_exists($objectname)) {
  77. $object = new $objectname($db);
  78. } else {
  79. return -4;
  80. }
  81. // Backup old file
  82. dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
  83. // Edit class files
  84. $contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
  85. // Update ->fields (to add or remove entries defined into $addfieldentry)
  86. if (count($object->fields)) {
  87. if (is_array($addfieldentry) && count($addfieldentry)) {
  88. $name = $addfieldentry['name'];
  89. unset($addfieldentry['name']);
  90. $object->fields[$name] = $addfieldentry;
  91. }
  92. if (!empty($delfieldentry)) {
  93. $name = $delfieldentry;
  94. unset($object->fields[$name]);
  95. }
  96. }
  97. dol_sort_array($object->fields, 'position');
  98. $i = 0;
  99. $texttoinsert = '// BEGIN MODULEBUILDER PROPERTIES'."\n";
  100. $texttoinsert .= "\t".'/**'."\n";
  101. $texttoinsert .= "\t".' * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.'."\n";
  102. $texttoinsert .= "\t".' */'."\n";
  103. $texttoinsert .= "\t".'public $fields=array('."\n";
  104. if (count($object->fields)) {
  105. foreach ($object->fields as $key => $val) {
  106. $i++;
  107. $texttoinsert .= "\t\t".'"'.$key.'" => array(';
  108. $texttoinsert .= '"type"=>"'.dol_escape_php($val['type']).'",';
  109. $texttoinsert .= ' "label"=>"'.dol_escape_php($val['label']).'",';
  110. if (!empty($val['picto'])) {
  111. $texttoinsert .= ' "picto"=>"'.dol_escape_php($val['picto']).'",';
  112. }
  113. $texttoinsert .= ' "enabled"=>"'.($val['enabled'] !== '' ? dol_escape_php($val['enabled']) : 1).'",';
  114. $texttoinsert .= " 'position'=>".($val['position'] !== '' ? (int) $val['position'] : 50).",";
  115. $texttoinsert .= " 'notnull'=>".(empty($val['notnull']) ? 0 : (int) $val['notnull']).",";
  116. $texttoinsert .= ' "visible"=>"'.($val['visible'] !== '' ? dol_escape_js($val['visible']) : -1).'",';
  117. if (!empty($val['noteditable'])) {
  118. $texttoinsert .= ' "noteditable"=>"'.dol_escape_php($val['noteditable']).'",';
  119. }
  120. if (!empty($val['alwayseditable'])) {
  121. $texttoinsert .= ' "alwayseditable"=>"'.dol_escape_php($val['alwayseditable']).'",';
  122. }
  123. if (!empty($val['default']) || (isset($val['default']) && $val['default'] === '0')) {
  124. $texttoinsert .= ' "default"=>"'.dol_escape_php($val['default']).'",';
  125. }
  126. if (!empty($val['index'])) {
  127. $texttoinsert .= ' "index"=>"'.(int) $val['index'].'",';
  128. }
  129. if (!empty($val['foreignkey'])) {
  130. $texttoinsert .= ' "foreignkey"=>"'.(int) $val['foreignkey'].'",';
  131. }
  132. if (!empty($val['searchall'])) {
  133. $texttoinsert .= ' "searchall"=>"'.(int) $val['searchall'].'",';
  134. }
  135. if (!empty($val['isameasure'])) {
  136. $texttoinsert .= ' "isameasure"=>"'.(int) $val['isameasure'].'",';
  137. }
  138. if (!empty($val['css'])) {
  139. $texttoinsert .= ' "css"=>"'.dol_escape_php($val['css']).'",';
  140. }
  141. if (!empty($val['cssview'])) {
  142. $texttoinsert .= ' "cssview"=>"'.dol_escape_php($val['cssview']).'",';
  143. }
  144. if (!empty($val['csslist'])) {
  145. $texttoinsert .= ' "csslist"=>"'.dol_escape_php($val['csslist']).'",';
  146. }
  147. if (!empty($val['help'])) {
  148. $texttoinsert .= ' "help"=>"'.dol_escape_php($val['help']).'",';
  149. }
  150. if (!empty($val['showoncombobox'])) {
  151. $texttoinsert .= ' "showoncombobox"=>"'.(int) $val['showoncombobox'].'",';
  152. }
  153. if (!empty($val['disabled'])) {
  154. $texttoinsert .= ' "disabled"=>"'.(int) $val['disabled'].'",';
  155. }
  156. if (!empty($val['autofocusoncreate'])) {
  157. $texttoinsert .= ' "autofocusoncreate"=>"'.(int) $val['autofocusoncreate'].'",';
  158. }
  159. if (!empty($val['arrayofkeyval'])) {
  160. $texttoinsert .= ' "arrayofkeyval"=>array(';
  161. $i = 0;
  162. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  163. if ($i) {
  164. $texttoinsert .= ", ";
  165. }
  166. $texttoinsert .= '"'.dol_escape_php($key2).'" => "'.dol_escape_php($val2).'"';
  167. $i++;
  168. }
  169. $texttoinsert .= '),';
  170. }
  171. if (!empty($val['validate'])) {
  172. $texttoinsert .= ' "validate"=>"'.(int) $val['validate'].'",';
  173. }
  174. if (!empty($val['comment'])) {
  175. $texttoinsert .= ' "comment"=>"'.dol_escape_php($val['comment']).'"';
  176. }
  177. $texttoinsert .= "),\n";
  178. //print $texttoinsert;
  179. }
  180. }
  181. $texttoinsert .= "\t".');'."\n";
  182. //print ($texttoinsert);exit;
  183. if (count($object->fields)) {
  184. //$typetotypephp=array('integer'=>'integer', 'duration'=>'integer', 'varchar'=>'string');
  185. foreach ($object->fields as $key => $val) {
  186. $i++;
  187. //$typephp=$typetotypephp[$val['type']];
  188. $texttoinsert .= "\t".'public $'.$key.";";
  189. //if ($key == 'rowid') $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
  190. //if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
  191. //$texttoinsert.= ($val['notnull']?' NOT NULL':'');
  192. //if ($i < count($object->fields)) $texttoinsert.=";";
  193. $texttoinsert .= "\n";
  194. }
  195. }
  196. $texttoinsert .= "\t".'// END MODULEBUILDER PROPERTIES';
  197. //print($texttoinsert);
  198. $contentclass = preg_replace('/\/\/ BEGIN MODULEBUILDER PROPERTIES.*END MODULEBUILDER PROPERTIES/ims', $texttoinsert, $contentclass);
  199. //print $contentclass;
  200. dol_mkdir(dirname($pathoffiletoedittarget));
  201. //file_put_contents($pathoffiletoedittmp, $contentclass);
  202. $result = file_put_contents(dol_osencode($pathoffiletoedittarget), $contentclass);
  203. if ($result) {
  204. dolChmod($pathoffiletoedittarget, $newmask);
  205. } else {
  206. $error++;
  207. }
  208. return $error ? -1 : $object;
  209. } catch (Exception $e) {
  210. print $e->getMessage();
  211. return -5;
  212. }
  213. }
  214. /**
  215. * Save data into a memory area shared by all users, all sessions on server
  216. *
  217. * @param string $destdir Directory
  218. * @param string $module Module name
  219. * @param string $objectname Name of object
  220. * @param string $newmask New mask
  221. * @param string $readdir Directory source (use $destdir when not defined)
  222. * @param Object $object If object was already loaded/known, it is pass to avoid another include and new.
  223. * @param string $moduletype 'external' or 'internal'
  224. * @return int Return integer <=0 if KO, >0 if OK
  225. * @see rebuildObjectClass()
  226. */
  227. function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '', $object = null, $moduletype = 'external')
  228. {
  229. global $db, $langs;
  230. $error = 0;
  231. if (empty($objectname)) {
  232. return -1;
  233. }
  234. if (empty($readdir)) {
  235. $readdir = $destdir;
  236. }
  237. $pathoffiletoclasssrc = $readdir.'/class/'.strtolower($objectname).'.class.php';
  238. // Edit .sql file
  239. if ($moduletype == 'internal') {
  240. $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql';
  241. if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
  242. $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'_'.strtolower($objectname).'-'.strtolower($module).'.sql';
  243. if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
  244. $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'-'.strtolower($module).'.sql';
  245. if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
  246. $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'.sql';
  247. }
  248. }
  249. }
  250. } else {
  251. $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql';
  252. if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
  253. $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'-'.strtolower($module).'.sql';
  254. if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
  255. $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'-'.strtolower($module).'.sql';
  256. if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
  257. $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'.sql';
  258. }
  259. }
  260. }
  261. }
  262. // Complete path to be full path
  263. $pathoffiletoedittarget = $destdir.$pathoffiletoeditsrc.($readdir != $destdir ? '.new' : '');
  264. $pathoffiletoeditsrc = $readdir.$pathoffiletoeditsrc;
  265. if (!dol_is_file($pathoffiletoeditsrc)) {
  266. $langs->load("errors");
  267. setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
  268. return -1;
  269. }
  270. // Load object from myobject.class.php
  271. try {
  272. if (!is_object($object)) {
  273. include_once $pathoffiletoclasssrc;
  274. if (class_exists($objectname)) {
  275. $object = new $objectname($db);
  276. } else {
  277. return -1;
  278. }
  279. }
  280. } catch (Exception $e) {
  281. print $e->getMessage();
  282. }
  283. // Backup old file
  284. dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
  285. $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
  286. $i = 0;
  287. $texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n";
  288. if (count($object->fields)) {
  289. foreach ($object->fields as $key => $val) {
  290. $i++;
  291. $type = $val['type'];
  292. $type = preg_replace('/:.*$/', '', $type); // For case type = 'integer:Societe:societe/class/societe.class.php'
  293. if ($type == 'html') {
  294. $type = 'text'; // html modulebuilder type is a text type in database
  295. } elseif ($type == 'price') {
  296. $type = 'double'; // html modulebuilder type is a text type in database
  297. } elseif (in_array($type, array('link', 'sellist', 'duration'))) {
  298. $type = 'integer';
  299. } elseif ($type == 'mail') {
  300. $type = 'varchar(128)';
  301. } elseif ($type == 'phone') {
  302. $type = 'varchar(20)';
  303. } elseif ($type == 'ip') {
  304. $type = 'varchar(32)';
  305. }
  306. $texttoinsert .= "\t".$key." ".$type;
  307. if ($key == 'rowid') {
  308. $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY';
  309. } elseif ($type == 'timestamp') {
  310. $texttoinsert .= ' DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP';
  311. }
  312. if ($key == 'entity') {
  313. $texttoinsert .= ' DEFAULT 1';
  314. } else {
  315. if (!empty($val['default'])) {
  316. if (preg_match('/^null$/i', $val['default'])) {
  317. $texttoinsert .= " DEFAULT NULL";
  318. } elseif (preg_match('/varchar/', $type)) {
  319. $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'";
  320. } else {
  321. $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : '');
  322. }
  323. }
  324. }
  325. $texttoinsert .= ((!empty($val['notnull']) && $val['notnull'] > 0) ? ' NOT NULL' : '');
  326. if ($i < count($object->fields)) {
  327. $texttoinsert .= ", ";
  328. }
  329. $texttoinsert .= "\n";
  330. }
  331. }
  332. $texttoinsert .= "\t".'-- END MODULEBUILDER FIELDS';
  333. $contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql);
  334. $result = file_put_contents($pathoffiletoedittarget, $contentsql);
  335. if ($result) {
  336. dolChmod($pathoffiletoedittarget, $newmask);
  337. } else {
  338. $error++;
  339. setEventMessages($langs->trans("ErrorFailToCreateFile", $pathoffiletoedittarget), null, 'errors');
  340. }
  341. // Edit .key.sql file
  342. $pathoffiletoeditsrc = preg_replace('/\.sql$/', '.key.sql', $pathoffiletoeditsrc);
  343. $pathoffiletoedittarget = preg_replace('/\.sql$/', '.key.sql', $pathoffiletoedittarget);
  344. $pathoffiletoedittarget = preg_replace('/\.sql.new$/', '.key.sql.new', $pathoffiletoedittarget);
  345. $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
  346. $i = 0;
  347. $texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n";
  348. if (count($object->fields)) {
  349. foreach ($object->fields as $key => $val) {
  350. $i++;
  351. if (!empty($val['index'])) {
  352. $texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD INDEX idx_".strtolower($module).'_'.strtolower($objectname)."_".$key." (".$key.");";
  353. $texttoinsert .= "\n";
  354. }
  355. if (!empty($val['foreignkey'])) {
  356. $tmp = explode('.', $val['foreignkey']);
  357. if (!empty($tmp[0]) && !empty($tmp[1])) {
  358. $texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD CONSTRAINT llx_".strtolower($module).'_'.strtolower($objectname)."_".$key." FOREIGN KEY (".$key.") REFERENCES llx_".preg_replace('/^llx_/', '', $tmp[0])."(".$tmp[1].");";
  359. $texttoinsert .= "\n";
  360. }
  361. }
  362. }
  363. }
  364. $texttoinsert .= '-- END MODULEBUILDER INDEXES';
  365. $contentsql = preg_replace('/-- BEGIN MODULEBUILDER INDEXES.*END MODULEBUILDER INDEXES/ims', $texttoinsert, $contentsql);
  366. dol_mkdir(dirname($pathoffiletoedittarget));
  367. $result2 = file_put_contents($pathoffiletoedittarget, $contentsql);
  368. if ($result2) {
  369. dolChmod($pathoffiletoedittarget, $newmask);
  370. } else {
  371. $error++;
  372. setEventMessages($langs->trans("ErrorFailToCreateFile", $pathoffiletoedittarget), null, 'errors');
  373. }
  374. return $error ? -1 : 1;
  375. }
  376. /**
  377. * Get list of existing objects from directory
  378. *
  379. * @param string $destdir Directory
  380. * @return array|int Return integer <=0 if KO, array if OK
  381. */
  382. function dolGetListOfObjectClasses($destdir)
  383. {
  384. $objects = array();
  385. $listofobject = dol_dir_list($destdir.'/class', 'files', 0, '\.class\.php$');
  386. foreach ($listofobject as $fileobj) {
  387. if (preg_match('/^api_/', $fileobj['name'])) {
  388. continue;
  389. }
  390. if (preg_match('/^actions_/', $fileobj['name'])) {
  391. continue;
  392. }
  393. $tmpcontent = file_get_contents($fileobj['fullname']);
  394. $reg = array();
  395. if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) {
  396. $objectnameloop = $reg[1];
  397. $objects[$fileobj['fullname']] = $objectnameloop;
  398. }
  399. }
  400. if (count($objects)>0) {
  401. return $objects;
  402. }
  403. return -1;
  404. }
  405. /**
  406. * function for check if comment begin an end exist in modMyModule class
  407. * @param string $file filename or path
  408. * @param int $number 0 = For Menus,1 = For permissions, 2 = For Dictionaries
  409. * @return int 1 if OK , -1 if KO
  410. */
  411. function checkExistComment($file, $number)
  412. {
  413. if (!file_exists($file)) {
  414. return -1;
  415. }
  416. $content = file_get_contents($file);
  417. if ($number === 0) {
  418. if (strpos($content, '/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT */') !== false && strpos($content, '/* END MODULEBUILDER LEFTMENU MYOBJECT */') !== false) {
  419. return 1;
  420. }
  421. } elseif ($number === 1) {
  422. if (strpos($content, '/* BEGIN MODULEBUILDER PERMISSIONS */') !== false && strpos($content, '/* END MODULEBUILDER PERMISSIONS */') !== false) {
  423. return 1;
  424. }
  425. } elseif ($number == 2) {
  426. if (strpos($content, '/* BEGIN MODULEBUILDER DICTIONARIES */') !== false && strpos($content, '/* END MODULEBUILDER DICTIONARIES */') !== false) {
  427. return 1;
  428. }
  429. }
  430. return -1;
  431. }
  432. /**
  433. * Delete all permissions
  434. *
  435. * @param string $file file with path
  436. * @return void
  437. */
  438. function deletePerms($file)
  439. {
  440. $start = "/* BEGIN MODULEBUILDER PERMISSIONS */";
  441. $end = "/* END MODULEBUILDER PERMISSIONS */";
  442. $i = 1;
  443. $array = array();
  444. $lines = file($file);
  445. // Search for start and end lines
  446. foreach ($lines as $i => $line) {
  447. if (strpos($line, $start) !== false) {
  448. $start_line = $i + 1;
  449. // Copy lines until the end on array
  450. while (($line = $lines[++$i]) !== false) {
  451. if (strpos($line, $end) !== false) {
  452. $end_line = $i + 1;
  453. break;
  454. }
  455. $array[] = $line;
  456. }
  457. break;
  458. }
  459. }
  460. $allContent = implode("", $array);
  461. dolReplaceInFile($file, array($allContent => ''));
  462. }
  463. /**
  464. * Compare two value
  465. * @param int|string $a value 1
  466. * @param int|string $b value 2
  467. * @return int less 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
  468. */
  469. function compareFirstValue($a, $b)
  470. {
  471. return strcmp($a[0], $b[0]);
  472. }
  473. /**
  474. * Rewriting all permissions after any actions
  475. * @param string $file filename or path
  476. * @param array $permissions permissions existing in file
  477. * @param int|null $key key for permission needed
  478. * @param array|null $right $right to update or add
  479. * @param string|null $objectname name of object
  480. * @param string|null $module name of module
  481. * @param int $action 0 for delete, 1 for add, 2 for update, -1 when delete object completly, -2 for generate rights after add
  482. * @return int 1 if OK,-1 if KO
  483. */
  484. function reWriteAllPermissions($file, $permissions, $key, $right, $objectname, $module, $action)
  485. {
  486. $error = 0;
  487. $rights = array();
  488. if ($action == 0) {
  489. // delete right from permissions array
  490. array_splice($permissions, array_search($permissions[$key], $permissions), 1);
  491. } elseif ($action == 1) {
  492. array_push($permissions, $right);
  493. } elseif ($action == 2 && !empty($right)) {
  494. // update right from permissions array
  495. array_splice($permissions, array_search($permissions[$key], $permissions), 1, $right);
  496. } elseif ($action == -1 && !empty($objectname)) {
  497. // when delete object
  498. $key = null;
  499. $right = null;
  500. foreach ($permissions as $perms) {
  501. if ($perms[4] === strtolower($objectname)) {
  502. array_splice($permissions, array_search($perms, $permissions), 1);
  503. }
  504. }
  505. } elseif ($action == -2 && !empty($objectname) && !empty($module)) {
  506. $key= null;
  507. $right = null;
  508. $objectOfRights = array();
  509. //check if object already declared in rights file
  510. foreach ($permissions as $right) {
  511. $objectOfRights[]= $right[4];
  512. }
  513. if (in_array(strtolower($objectname), $objectOfRights)) {
  514. $error++;
  515. } else {
  516. $permsToadd = array();
  517. $perms = array(
  518. 'read' => 'Read '.$objectname.' object of '.ucfirst($module),
  519. 'write' => 'Create/Update '.$objectname.' object of '.ucfirst($module),
  520. 'delete' => 'Delete '.$objectname.' object of '.ucfirst($module)
  521. );
  522. $i = 0;
  523. foreach ($perms as $index => $value) {
  524. $permsToadd[$i][0] = '';
  525. $permsToadd[$i][1] = $value;
  526. $permsToadd[$i][4] = strtolower($objectname);
  527. $permsToadd[$i][5] = $index;
  528. array_push($permissions, $permsToadd[$i]);
  529. $i++;
  530. }
  531. }
  532. } else {
  533. $error++;
  534. }
  535. if (!$error) {
  536. // prepare permissions array
  537. $count_perms = count($permissions);
  538. for ($i = 0;$i<$count_perms;$i++) {
  539. $permissions[$i][0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', \$r + 1)";
  540. $permissions[$i][1] = "\$this->rights[\$r][1] = '".$permissions[$i][1]."'";
  541. $permissions[$i][4] = "\$this->rights[\$r][4] = '".$permissions[$i][4]."'";
  542. $permissions[$i][5] = "\$this->rights[\$r][5] = '".$permissions[$i][5]."';\n\t\t";
  543. }
  544. // for group permissions by object
  545. $perms_grouped = array();
  546. foreach ($permissions as $perms) {
  547. $object = $perms[4];
  548. if (!isset($perms_grouped[$object])) {
  549. $perms_grouped[$object] = [];
  550. }
  551. $perms_grouped[$object][] = $perms;
  552. }
  553. //$perms_grouped = array_values($perms_grouped);
  554. $permissions = $perms_grouped;
  555. // parcourir les objets
  556. $o=0;
  557. foreach ($permissions as &$object) {
  558. // récupérer la permission de l'objet
  559. $p = 1;
  560. foreach ($object as &$obj) {
  561. if (str_contains($obj[5], 'read')) {
  562. $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + 0 + 1)";
  563. } elseif (str_contains($obj[5], 'write')) {
  564. $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + 1 + 1)";
  565. } elseif (str_contains($obj[5], 'delete')) {
  566. $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + 2 + 1)";
  567. } else {
  568. $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + ".$p." + 1)";
  569. $p++;
  570. }
  571. }
  572. usort($object, 'compareFirstValue');
  573. $o++;
  574. }
  575. //convert to string
  576. foreach ($permissions as $perms) {
  577. foreach ($perms as $per) {
  578. $rights[] = implode(";\n\t\t", $per);
  579. $rights[] = "\$r++;\n\t\t";
  580. }
  581. }
  582. $rights_str = implode("", $rights);
  583. // delete all permission from file
  584. deletePerms($file);
  585. // rewrite all permission again
  586. dolReplaceInFile($file, array('/* BEGIN MODULEBUILDER PERMISSIONS */' => '/* BEGIN MODULEBUILDER PERMISSIONS */'."\n\t\t".$rights_str));
  587. return 1;
  588. } else {
  589. return -1;
  590. }
  591. }
  592. /**
  593. * Converts a formatted properties string into an associative array.
  594. *
  595. * @param string $string The formatted properties string.
  596. * @return array The resulting associative array.
  597. */
  598. function parsePropertyString($string)
  599. {
  600. $string = str_replace("'", '', $string);
  601. // Uses a regular expression to capture keys and values
  602. preg_match_all('/\s*([^\s=>]+)\s*=>\s*([^,]+),?/', $string, $matches, PREG_SET_ORDER);
  603. $propertyArray = [];
  604. foreach ($matches as $match) {
  605. $key = trim($match[1]);
  606. $value = trim($match[2]);
  607. if (strpos($value, 'array(') === 0) {
  608. $nestedArray = substr($value, 6);
  609. $nestedArray = parsePropertyString($nestedArray);
  610. $value = $nestedArray;
  611. } elseif (strpos($value, '"Id")') !== false) {
  612. $value = str_replace(')', '', $value);
  613. } else {
  614. if (is_numeric($value)) {
  615. if (strpos($value, '.') !== false) {
  616. $value = (float) $value;
  617. } else {
  618. $value = (int) $value;
  619. }
  620. } else {
  621. if ($value === 'true') {
  622. $value = true;
  623. } elseif ($value === 'false') {
  624. $value = false;
  625. }
  626. }
  627. }
  628. $propertyArray[$key] = $value;
  629. }
  630. return $propertyArray;
  631. }
  632. /**
  633. * Write all properties of the object in AsciiDoc format
  634. * @param string $file path of the class
  635. * @param string $objectname name of the objectClass
  636. * @param string $destfile file where write table of properties
  637. * @return int 1 if OK, -1 if KO
  638. */
  639. function writePropsInAsciiDoc($file, $objectname, $destfile)
  640. {
  641. // stock all properties in array
  642. $attributesUnique = array('type','label', 'enabled', 'position', 'notnull', 'visible', 'noteditable', 'index', 'default' , 'foreignkey', 'arrayofkeyval', 'alwayseditable','validate', 'searchall','comment', 'isameasure', 'css', 'cssview','csslist', 'help', 'showoncombobox','picto' );
  643. $start = "public \$fields=array(";
  644. $end = ");";
  645. $i = 1;
  646. $keys = array();
  647. $lines = file($file);
  648. // Search for start and end lines
  649. foreach ($lines as $i => $line) {
  650. if (strpos($line, $start) !== false) {
  651. // Copy lines until the end on array
  652. while (($line = $lines[++$i]) !== false) {
  653. if (strpos($line, $end) !== false) {
  654. break;
  655. }
  656. $keys[] = $line;
  657. }
  658. break;
  659. }
  660. }
  661. // write the begin of table with specifics options
  662. $table = "== DATA SPECIFICATIONS\n";
  663. $table .= "=== Table of fields with properties for object *$objectname* : \n";
  664. $table .= "[options='header',grid=rows,frame=topbot,width=100%,caption=Organisation]\n";
  665. $table .= "|===\n";
  666. $table .= "|code";
  667. // write all properties in the header of the table
  668. foreach ($attributesUnique as $attUnique) {
  669. $table .= "|".$attUnique;
  670. }
  671. $table .="\n";
  672. $valuesModif = array();
  673. foreach ($keys as $string) {
  674. $string = trim($string, "'");
  675. $string = rtrim($string, ",");
  676. $array = parsePropertyString($string);
  677. // Iterate through the array to merge all key to one array
  678. $code = '';
  679. foreach ($array as $key => $value) {
  680. if (is_array($value)) {
  681. $code = $key;
  682. continue;
  683. } else {
  684. $array[$code][$key] = $value;
  685. unset($array[$key]);
  686. }
  687. }
  688. // check if is array after parsing the string
  689. if (!is_array($array)) {
  690. return -1;
  691. }
  692. $field = array_keys($array);
  693. if ($field[0] === '') {
  694. $field[0] = 'label';
  695. }
  696. $values = array_values($array)[0];
  697. // check each field has all properties and add it if missed
  698. foreach ($attributesUnique as $attUnique) {
  699. if ($attUnique == 'type' && $field[0] === 'label') {
  700. $values[$attUnique] = 'varchar(255)';
  701. }
  702. if (!array_key_exists($attUnique, $values)) {
  703. $valuesModif[$attUnique] = '';
  704. } else {
  705. $valuesModif[$attUnique] = $values[$attUnique];
  706. }
  707. }
  708. $table .= "|*" . $field[0] . "*|";
  709. $table .= implode("|", $valuesModif) . "\n";
  710. }
  711. // end table
  712. $table .= "|===\n";
  713. $table .= "__ end table for object $objectname\n";
  714. //write in file
  715. $writeInFile = dolReplaceInFile($destfile, array('== DATA SPECIFICATIONS' => $table));
  716. if ($writeInFile<0) {
  717. return -1;
  718. }
  719. return 1;
  720. }
  721. /**
  722. * Delete property and permissions from documentation ascii file if we delete an object
  723. *
  724. * @param string $file file or path
  725. * @param string $objectname name of object wants to deleted
  726. * @return void
  727. */
  728. function deletePropsAndPermsFromDoc($file, $objectname)
  729. {
  730. if (dol_is_file($file)) {
  731. $start = "== Table of fields and their properties for object *".ucfirst($objectname)."* : ";
  732. $end = "__ end table for object ".ucfirst($objectname);
  733. $str = file_get_contents($file);
  734. $search = '/' . preg_quote($start, '/') . '(.*?)' . preg_quote($end, '/') . '/s';
  735. $new_contents = preg_replace($search, '', $str);
  736. file_put_contents($file, $new_contents);
  737. //perms If Exist
  738. $perms = "|*".strtolower($objectname)."*|";
  739. $search_pattern_perms = '/' . preg_quote($perms, '/') . '.*?\n/';
  740. $new_contents = preg_replace($search_pattern_perms, '', $new_contents);
  741. file_put_contents($file, $new_contents);
  742. }
  743. }
  744. /**
  745. * Search a string and return all lines needed from file
  746. * @param string $file file for searching
  747. * @param string $start start line if exist
  748. * @param string $end end line if exist
  749. * @return string return the content needed
  750. */
  751. function getFromFile($file, $start, $end)
  752. {
  753. $i = 1;
  754. $keys = array();
  755. $lines = file($file);
  756. // Search for start and end lines
  757. foreach ($lines as $i => $line) {
  758. if (strpos($line, $start) !== false) {
  759. // Copy lines until the end on array
  760. while (($line = $lines[++$i]) !== false) {
  761. if (strpos($line, $end) !== false) {
  762. break;
  763. }
  764. $keys[] = $line;
  765. }
  766. break;
  767. }
  768. }
  769. $content = implode("", $keys);
  770. return $content;
  771. }
  772. /**
  773. * Write all permissions of each object in AsciiDoc format
  774. * @param string $file path of the class
  775. * @param string $destfile file where write table of permissions
  776. * @return int 1 if OK, -1 if KO
  777. */
  778. function writePermsInAsciiDoc($file, $destfile)
  779. {
  780. global $langs;
  781. //search and get all permssion in stirng
  782. $start = '/* BEGIN MODULEBUILDER PERMISSIONS */';
  783. $end = '/* END MODULEBUILDER PERMISSIONS */';
  784. $content = getFromFile($file, $start, $end);
  785. if (empty($content)) {
  786. return -1;
  787. }
  788. //prepare table
  789. $string = "[options='header',grid=rows,width=60%,caption=Organisation]\n";
  790. $string .= "|===\n";
  791. // header for table
  792. $header = array($langs->trans('Objects'),$langs->trans('Permission'));
  793. foreach ($header as $h) {
  794. $string .= "|".$h;
  795. }
  796. $string .= "\n";
  797. //content table
  798. $array = explode(";", $content);
  799. $permissions = array_filter($array);
  800. // delete occurrences "$r++" and ID
  801. $permissions = str_replace('$r++', 1, $permissions);
  802. $permsN = array();
  803. foreach ($permissions as $i => $element) {
  804. if ($element == 1) {
  805. unset($permissions[$i]);
  806. }
  807. if (str_contains($element, '$this->numero')) {
  808. unset($permissions[$i]);
  809. }
  810. if (str_contains($element, '$this->rights[$r][5]')) {
  811. unset($permissions[$i]);
  812. }
  813. }
  814. // cleaning the string on each element
  815. foreach ($permissions as $key => $element) {
  816. $element = str_replace(" '", '', $element);
  817. $element = trim($element, "'");
  818. $permsN[] = substr($element, strpos($element, "=")+1);
  819. }
  820. array_pop($permsN);
  821. // Group permissions by Object and add it to string
  822. $final_array = [];
  823. $index = 0;
  824. while ($index < count($permsN)) {
  825. $temp_array = [$permsN[$index], $permsN[$index + 1]];
  826. $final_array[] = $temp_array;
  827. $index += 2;
  828. }
  829. $result = array();
  830. foreach ($final_array as $subarray) {
  831. // found object
  832. $key = $subarray[1];
  833. // add sub array to object
  834. $result[$key][] = $subarray;
  835. }
  836. foreach ($result as $i => $pems) {
  837. $string .= "|*".$i."*|";
  838. foreach ($pems as $tab) {
  839. $string .= $tab[0]." , ";
  840. }
  841. $string .= "\n";
  842. }
  843. // end table
  844. $string .= "\n|===\n";
  845. $write = dolReplaceInFile($destfile, array('__DATA_PERMISSIONS__'=> $string));
  846. if ($write<0) {
  847. return -1;
  848. }
  849. return 1;
  850. }
  851. /**
  852. * Add Object in ModuleApi File
  853. * @param string $file path of file
  854. * @param array $objects array of objects in the module
  855. * @param string $modulename name of module
  856. * @return int 1 if OK, -1 if KO
  857. */
  858. function addObjectsToApiFile($file, $objects, $modulename)
  859. {
  860. if (!file_exists($file)) {
  861. return -1;
  862. }
  863. $content = file($file);
  864. $includeClass = "dol_include_once('/mymodule/class/myobject.class.php');";
  865. $props = "public \$myobject;";
  866. $varcomented = "@var MyObject \$myobject {@type MyObject}";
  867. $constructObj = "\$this->myobject = new MyObject(\$this->db);";
  868. // add properties and declare them in consturctor
  869. foreach ($content as $lineNumber => &$lineContent) {
  870. if (strpos($lineContent, $varcomented) !== false) {
  871. $lineContent = '';
  872. foreach ($objects as $object) {
  873. $lineContent .= "\t * @var ".$object." \$".strtolower($object)." {@type ".$object."}". PHP_EOL;
  874. }
  875. //var_dump($lineContent);exit;
  876. }
  877. if (strpos($lineContent, $props) !== false) {
  878. $lineContent = '';
  879. foreach ($objects as $object) {
  880. $lineContent .= "\tpublic \$".strtolower($object).";". PHP_EOL;
  881. }
  882. }
  883. if (strpos($lineContent, $constructObj) !== false) {
  884. $lineContent = '';
  885. foreach ($objects as $object) {
  886. $lineContent .= "\t\t\$this->".strtolower($object)." = new ".$object."(\$this->db);". PHP_EOL;
  887. }
  888. }
  889. if (strpos($lineContent, $includeClass) !== false) {
  890. $lineContent = '';
  891. foreach ($objects as $object) {
  892. $lineContent .= "dol_include_once('/".strtolower($modulename)."/class/".strtolower($object).".class.php');". PHP_EOL;
  893. }
  894. }
  895. }
  896. $allContent = implode("", $content);
  897. file_put_contents($file, $allContent);
  898. //add methods for each object
  899. $allContent = getFromFile($file, '/*begin methods CRUD*/', '/*end methods CRUD*/');
  900. foreach ($objects as $object) {
  901. $contentReplaced =str_replace(["myobject","MyObject"], [strtolower($object),$object], $allContent);
  902. dolReplaceInFile($file, array('/*end methods CRUD*/' => '/*CRUD FOR '.strtoupper($object).'*/'."\n".$contentReplaced."\n\t".'/*END CRUD FOR '.strtoupper($object).'*/'."\n\t".'/*end methods CRUD*/'));
  903. }
  904. dolReplaceInFile($file, array($allContent => '','MyModule' => ucfirst($modulename)));
  905. return 1;
  906. }
  907. /**
  908. * Remove Object variables and methods from API_Module File
  909. * @param string $file file api module
  910. * @param string $objectname name of object whant to remove
  911. * @param string $modulename name of module
  912. * @return int 1 if OK, -1 if KO
  913. */
  914. function removeObjectFromApiFile($file, $objectname, $modulename)
  915. {
  916. $begin = '/*CRUD FOR '.strtoupper($objectname).'*/';
  917. $end = '/*END CRUD FOR '.strtoupper($objectname).'*/';
  918. $includeClass = "dol_include_once('/".strtolower($modulename)."/class/".strtolower($objectname).".class.php');";
  919. $varcomentedDel = "\t * @var ".$objectname." \$".strtolower($objectname)." {@type ".$objectname."}";
  920. $propsDel = "\tpublic \$".strtolower($objectname).";";
  921. $constructObjDel = "\t\t\$this->".strtolower($objectname)." = new ".$objectname."(\$this->db);";
  922. if (!file_exists($file)) {
  923. return -1;
  924. }
  925. $content = file($file);
  926. // for delete property and the initialization from the construct
  927. foreach ($content as $lineNumber => &$lineContent) {
  928. if (strpos($lineContent, $includeClass) !== false) {
  929. $lineContent = '';
  930. }
  931. if (strpos($lineContent, $varcomentedDel) !== false) {
  932. $lineContent = '';
  933. }
  934. if (strpos($lineContent, $propsDel) !== false) {
  935. $lineContent = '';
  936. }
  937. if (strpos($lineContent, $constructObjDel) !== false) {
  938. $lineContent = '';
  939. }
  940. }
  941. $allContent = implode("", $content);
  942. file_put_contents($file, $allContent);
  943. // for delete methods of object
  944. $allContent = getFromFile($file, $begin, $end);
  945. $check = dolReplaceInFile($file, array($allContent => ''));
  946. if ($check) {
  947. dolReplaceInFile($file, array($begin => '', $end => ''));
  948. }
  949. return 1;
  950. }
  951. /**
  952. * @param string $file path of filename
  953. * @param mixed $menus all menus for module
  954. * @param mixed|null $menuWantTo menu get for do actions
  955. * @param int|null $key key for the concerned menu
  956. * @param int $action for specify what action (0 = delete, 1 = add, 2 = update, -1 = when delete object)
  957. * @return int 1 if OK, -1 if KO
  958. */
  959. function reWriteAllMenus($file, $menus, $menuWantTo, $key, $action)
  960. {
  961. $errors =0;
  962. $counter = 0;
  963. if (!file_exists($file)) {
  964. return -1;
  965. }
  966. if ($action == 0 && !empty($key)) {
  967. // delete menu manuelly
  968. array_splice($menus, array_search($menus[$key], $menus), 1);
  969. } elseif ($action == 1) {
  970. // add menu manualy
  971. array_push($menus, $menuWantTo);
  972. } elseif ($action == 2 && !empty($key) && !empty($menuWantTo)) {
  973. // update right from permissions array
  974. $urlCounter=0;
  975. // check if the values already exists
  976. foreach ($menus as $index => $menu) {
  977. if ($index !== $key) {
  978. if ($menu['type'] === $menuWantTo['type']) {
  979. if (strcasecmp(str_replace(' ', '', $menu['titre']), str_replace(' ', '', $menuWantTo['titre'])) === 0) {
  980. $counter++;
  981. }
  982. if (strcasecmp(str_replace(' ', '', $menu['url']), str_replace(' ', '', $menuWantTo['url'])) === 0) {
  983. $urlCounter++;
  984. }
  985. }
  986. }
  987. }
  988. if (!$counter && $urlCounter < 2) {
  989. $menus[$key] = $menuWantTo;
  990. } else {
  991. $errors++;
  992. }
  993. } elseif ($action == -1 && !empty($menuWantTo)) {
  994. // delete menus when delete Object
  995. foreach ($menus as $index => $menu) {
  996. if ((strpos(strtolower($menu['fk_menu']), strtolower($menuWantTo)) !== false) || (strpos(strtolower($menu['leftmenu']), strtolower($menuWantTo)) !== false)) {
  997. array_splice($menus, array_search($menu, $menus), 1);
  998. }
  999. }
  1000. } else {
  1001. $errors++;
  1002. }
  1003. if (!$errors) {
  1004. // delete All LEFT Menus
  1005. $beginMenu = '/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT */';
  1006. $endMenu = '/* END MODULEBUILDER LEFTMENU MYOBJECT */';
  1007. $allMenus = getFromFile($file, $beginMenu, $endMenu);
  1008. dolReplaceInFile($file, array($allMenus => ''));
  1009. //prepare each menu and stock them in string
  1010. $str_menu = "";
  1011. foreach ($menus as $index => $menu) {
  1012. $menu['position'] = "1000 + \$r";
  1013. if ($menu['type'] === 'left') {
  1014. $start = "\t\t".'/* LEFTMENU '.strtoupper($menu['titre']).' */';
  1015. $end = "\t\t".'/* END LEFTMENU '.strtoupper($menu['titre']).' */';
  1016. $val_actuel = $menu;
  1017. $next_val = empty($menus[$index + 1]) ? null : $menus[$index + 1];
  1018. //var_dump(dol_escape_php($menu['perms'], 1)); exit;
  1019. $str_menu .= $start."\n";
  1020. $str_menu.= "\t\t\$this->menu[\$r++]=array(\n";
  1021. $str_menu.= "\t\t\t 'fk_menu' => '".dol_escape_php($menu['fk_menu'], 1)."',\n";
  1022. $str_menu.= "\t\t\t 'type' => '".dol_escape_php($menu['type'], 1)."',\n";
  1023. $str_menu.= "\t\t\t 'titre' => '".dol_escape_php($menu['titre'], 1)."',\n";
  1024. $str_menu.= "\t\t\t 'mainmenu' => '".dol_escape_php($menu['mainmenu'], 1)."',\n";
  1025. $str_menu.= "\t\t\t 'leftmenu' => '".dol_escape_php($menu['leftmenu'], 1)."',\n";
  1026. $str_menu.= "\t\t\t 'url' => '".dol_escape_php($menu['url'], 1)."',\n";
  1027. $str_menu.= "\t\t\t 'langs' => '".dol_escape_php($menu['langs'], 1)."',\n";
  1028. $str_menu.= "\t\t\t 'position' => ".((int) $menu['position']).",\n";
  1029. $str_menu.= "\t\t\t 'enabled' => '".dol_escape_php($menu['enabled'], 1)."',\n";
  1030. $str_menu.= "\t\t\t 'perms' => '".dol_escape_php($menu['perms'], 1)."',\n";
  1031. $str_menu.= "\t\t\t 'target' => '".dol_escape_php($menu['target'], 1)."',\n";
  1032. $str_menu.= "\t\t\t 'user' => ".((int) $menu['user']).",\n";
  1033. $str_menu.= "\t\t);\n";
  1034. if (is_null($next_val) || $val_actuel['leftmenu'] !== $next_val['leftmenu']) {
  1035. $str_menu .= $end."\n";
  1036. }
  1037. }
  1038. }
  1039. dolReplaceInFile($file, array($beginMenu => $beginMenu."\n".$str_menu."\n"));
  1040. return 1;
  1041. }
  1042. return -1;
  1043. }
  1044. /**
  1045. * Updates a dictionary in a module descriptor file.
  1046. *
  1047. * @param string $module The name of the module.
  1048. * @param string $file The path to the module descriptor file.
  1049. * @param array $dicts The dictionary data to be updated.
  1050. * @return int Returns the number of replacements made in the file.
  1051. */
  1052. function updateDictionaryInFile($module, $file, $dicts)
  1053. {
  1054. $isEmpty = false;
  1055. $dicData = "\t\t\$this->dictionaries=array(\n";
  1056. $module = strtolower($module);
  1057. foreach ($dicts as $key => $value) {
  1058. if (empty($value)) {
  1059. $isEmpty = true;
  1060. $dicData = "\t\t\$this->dictionaries=array();";
  1061. break;
  1062. }
  1063. $dicData .= "\t\t\t'$key'=>";
  1064. if ($key === 'tabcond') {
  1065. $conditions = array_map(function ($val) use ($module) {
  1066. return ($val === true || $val === false) ? "isModEnabled('$module')" : $val;
  1067. }, $value);
  1068. $dicData .= "array(" . implode(",", $conditions) . ")";
  1069. } elseif ($key === 'tabhelp') {
  1070. $helpItems = array();
  1071. foreach ($value as $helpValue) {
  1072. $helpItems[] = "array('code'=>\$langs->trans('".$helpValue['code']."'), 'field2' => 'field2tooltip')";
  1073. }
  1074. $dicData .= "array(" . implode(",", $helpItems) . ")";
  1075. } else {
  1076. if (is_array($value)) {
  1077. $dicData .= "array(" . implode(",", array_map(function ($val) {
  1078. return "'$val'";
  1079. }, $value)) . ")";
  1080. } else {
  1081. $dicData .= "'$value'";
  1082. }
  1083. }
  1084. $dicData .= ",\n";
  1085. }
  1086. $dicData .= (!$isEmpty ? "\t\t);" : '');
  1087. $stringDic = getFromFile($file, '/* BEGIN MODULEBUILDER DICTIONARIES */', '/* END MODULEBUILDER DICTIONARIES */');
  1088. $writeInfile = dolReplaceInFile($file, array($stringDic => $dicData."\n"));
  1089. return $writeInfile;
  1090. }
  1091. /**
  1092. * Creates a new dictionary table.
  1093. *
  1094. * for creating a new dictionary table in Dolibarr. It generates the necessary SQL code to define the table structure,
  1095. * including columns such as 'rowid', 'code', 'label', 'position', 'use_default', 'active', etc. The table name is constructed based on the provided $namedic parameter.
  1096. *
  1097. * @param string $modulename The lowercase name of the module for which the dictionary table is being created.
  1098. * @param string $file The file path to the Dolibarr module builder file where the dictionaries are defined.
  1099. * @param string $namedic The name of the dictionary, which will also be used as the base for the table name.
  1100. * @param array|null $dictionnaires An optional array containing pre-existing dictionary data, including 'tabname', 'tablib', 'tabsql', etc.
  1101. * @return void
  1102. */
  1103. function createNewDictionnary($modulename, $file, $namedic, $dictionnaires = null)
  1104. {
  1105. global $db, $langs;
  1106. if (empty($namedic)) {
  1107. setEventMessages($langs->trans("ErrorEmptyNameDic"), null, 'errors');
  1108. return;
  1109. }
  1110. if (!file_exists($file)) {
  1111. return -1;
  1112. }
  1113. $modulename = strtolower($modulename);
  1114. if (empty($dictionnaires)) {
  1115. $dictionnaires = array('langs' => '', 'tabname' => array(), 'tablib' => array(), 'tabsql' => array(), 'tabsqlsort' => array(), 'tabfield' => array(), 'tabfieldvalue' => array(), 'tabfieldinsert' => array(), 'tabrowid' => array(), 'tabcond' => array(), 'tabhelp' => array());
  1116. }
  1117. $columns = array(
  1118. 'rowid' => array('type' => 'integer(11)'),
  1119. 'code' => array('type' => 'varchar(255) NOT NULL'),
  1120. 'label' => array('type' => 'varchar(255) NOT NULL'),
  1121. 'position' => array('type' => 'integer(11) NULL'),
  1122. 'use_default' => array('type' => 'varchar(255) DEFAULT 1'),
  1123. 'active' => array('type' => 'integer')
  1124. );
  1125. $primaryKey = 'rowid';
  1126. foreach ($columns as $key => $value) {
  1127. if ($key === 'rowid') {
  1128. $primaryKey = 'rowid';
  1129. break;
  1130. }
  1131. if (!array_key_exists('rowid', $columns)) {
  1132. $primaryKey = array_key_first($columns);
  1133. break;
  1134. }
  1135. }
  1136. // check if tablename exist in Database and create it if not
  1137. $query = "SHOW TABLES LIKE '" . MAIN_DB_PREFIX.strtolower($namedic) . "'";
  1138. $checkTable = $db->query($query);
  1139. if ($checkTable && $db->num_rows($checkTable) > 0) {
  1140. setEventMessages($langs->trans("ErrorTableExist", $namedic), null, 'errors');
  1141. return;
  1142. } else {
  1143. $_results = $db->DDLCreateTable(MAIN_DB_PREFIX.strtolower($namedic), $columns, $primaryKey, "InnoDB");
  1144. if ($_results < 0) {
  1145. dol_print_error($db);
  1146. $langs->load("errors");
  1147. setEventMessages($langs->trans("ErrorTableNotFound", $namedic), null, 'errors');
  1148. }
  1149. }
  1150. // rewrite dictionnary if
  1151. $dictionnaires['langs'] = $modulename.'@'.$modulename;
  1152. $dictionnaires['tabname'][] = strtolower($namedic);
  1153. $dictionnaires['tablib'][] = ucfirst(substr($namedic, 2));
  1154. $dictionnaires['tabsql'][] = 'SELECT t.rowid as rowid, t.code, t.label, t.active FROM '.MAIN_DB_PREFIX.strtolower($namedic).' as t';
  1155. $dictionnaires['tabsqlsort'][] = (array_key_exists('label', $columns) ? 'label ASC' : '');
  1156. $dictionnaires['tabfield'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : '');
  1157. $dictionnaires['tabfieldvalue'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : '');
  1158. $dictionnaires['tabfieldinsert'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : '');
  1159. $dictionnaires['tabrowid'][] = $primaryKey;
  1160. $dictionnaires['tabcond'][] = isModEnabled('$modulename');
  1161. $dictionnaires['tabhelp'][] = (array_key_exists('code', $columns) ? array('code'=>$langs->trans('CodeTooltipHelp'), 'field2' => 'field2tooltip') : '');
  1162. // Build the dictionary string
  1163. $writeInfile = updateDictionaryInFile($modulename, $file, $dictionnaires);
  1164. if ($writeInfile > 0) {
  1165. setEventMessages($langs->trans("DictionariesCreated", ucfirst(substr($namedic, 2))), null);
  1166. }
  1167. }
  1168. /**
  1169. * Generate Urls and add them to documentaion module
  1170. *
  1171. * @param string $file_api filename or path of api
  1172. * @param string $file_doc filename or path of documentation
  1173. * @return int -1 if KO, 1 if OK, 0 if nothing change
  1174. */
  1175. function writeApiUrlsInDoc($file_api, $file_doc)
  1176. {
  1177. $error = 0;
  1178. if (!dol_is_file($file_api) || !dol_is_file($file_doc)) {
  1179. $error++;
  1180. }
  1181. $string = getFromFile($file_api, '/*begin methods CRUD*/', '/*end methods CRUD*/');
  1182. $extractUrls = explode("\n", $string);
  1183. // extract urls from file
  1184. $urlValues = [];
  1185. foreach ($extractUrls as $key => $line) {
  1186. $lineWithoutTabsSpaces = preg_replace('/^[\t\s]+/', '', $line);
  1187. if (strpos($lineWithoutTabsSpaces, '* @url') === 0) {
  1188. $urlValue = trim(substr($lineWithoutTabsSpaces, strlen('* @url')));
  1189. $urlValues[] = $urlValue;
  1190. }
  1191. }
  1192. // get urls by object
  1193. $str = $_SERVER['HTTP_HOST'].'/api/index.php/';
  1194. $groupedUrls = [];
  1195. foreach ($urlValues as $url) {
  1196. if (preg_match('/(?:GET|POST|PUT|DELETE) (\w+)s/', $url, $matches)) {
  1197. $objectName = $matches[1];
  1198. $url = $str.trim(strstr($url, ' '));
  1199. $groupedUrls[$objectName][] = $url;
  1200. }
  1201. }
  1202. if (empty($groupedUrls)) {
  1203. $error++;
  1204. }
  1205. // buil format asciidoc for urls in table
  1206. if (!$error) {
  1207. $asciiDocTable = "[options=\"header\"]\n|===\n|Objet | URLs\n";
  1208. foreach ($groupedUrls as $objectName => $urls) {
  1209. $urlsList = implode(" +\n*", $urls);
  1210. $asciiDocTable .= "|$objectName | \n*$urlsList +\n";
  1211. }
  1212. $asciiDocTable .= "|===\n";
  1213. $file_write = dolReplaceInFile($file_doc, array('__API_DOC__' => '__API_DOC__'."\n".$asciiDocTable));
  1214. if ($file_write < 0) {
  1215. return -1;
  1216. }
  1217. return 1;
  1218. }
  1219. return -1;
  1220. }
  1221. /**
  1222. * count directories or files in modulebuilder folder
  1223. * @param string $path path of directory
  1224. * @param int $type type of file 1= file,2=directory
  1225. * @return int|bool
  1226. */
  1227. function countItemsInDirectory($path, $type = 1)
  1228. {
  1229. if (!is_dir($path)) {
  1230. return false;
  1231. }
  1232. $allFilesAndDirs = scandir($path);
  1233. $count = 0;
  1234. foreach ($allFilesAndDirs as $item) {
  1235. if ($item != '.' && $item != '..') {
  1236. if ($type == 1 && is_file($path . DIRECTORY_SEPARATOR . $item) && strpos($item, '.back') === false) {
  1237. $count++;
  1238. } elseif ($type == 2 && is_dir($path . DIRECTORY_SEPARATOR . $item)) {
  1239. $count++;
  1240. }
  1241. }
  1242. }
  1243. return $count;
  1244. }