dolibarr 25.0.0-alpha
modulebuilder.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2009-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
4 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
26require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
27require_once DOL_DOCUMENT_ROOT . '/modulebuilder/class/NamingContract.class.php';
28require_once DOL_DOCUMENT_ROOT . '/modulebuilder/class/AccessPolicyConfig.class.php';
29
44function dolModuleBuilderSqlIdentifier(string $prefix, string $module, string $table, string $key): string
45{
46 // The name of the field is used as is, as it was before, because it may hold uppercase characters
48 $table = dol_strtolower($table);
49
50 $identifier = $prefix.$module.'_'.$table.'_'.$key;
51 if (dol_strlen($identifier) <= 64) {
52 return $identifier;
53 }
54
55 $module = dol_substr($module, 0, 30);
56 $table = dol_substr($table, 0, 20);
57 // 2 = the two '_' separators. The prefix plus the maximum lengths of the module and of the table already
58 // reach 56 characters, so the key gets what is left instead of a fixed length of its own.
59 $key = dol_substr($key, 0, 64 - dol_strlen($prefix) - dol_strlen($module) - dol_strlen($table) - 2);
60
61 return $prefix.$module.'_'.$table.'_'.$key;
62}
63
77function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = '', $addfieldentry = array(), $delfieldentry = '')
78{
79 global $db, $langs;
80
81 if (empty($objectname)) {
82 return -6;
83 }
84 if (empty($readdir)) {
85 $readdir = $destdir;
86 }
87
88 if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) {
89 dol_print_error(null, 'Bad parameter addfieldentry with a property arrayofkeyval defined but that is not an array.');
90 return -7;
91 }
92
93 $error = 0;
94
95 // Check parameters into $addfieldentry (this provided array is filled by modulebuilder/index.php)
96 if (is_array($addfieldentry) && count($addfieldentry) > 0) {
97 if (empty($addfieldentry['name'])) {
98 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Name")), null, 'errors');
99 return -2;
100 }
101 if (empty($addfieldentry['label'])) {
102 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors');
103 return -2;
104 }
105 if (!preg_match('/^(integer|price|sellist|varchar|double|text|html|duration|stars)/', $addfieldentry['type'])
106 && !preg_match('/^(boolean|smallint|real|date|datetime|timestamp|phone|email|url|ip|password)$/', $addfieldentry['type'])) { // Use email for email, mail is kept for compatibility
107 setEventMessages($langs->trans('BadValueForType', $addfieldentry['type']), null, 'errors');
108 return -2;
109 }
110 // Check for type stars(NumberOfStars), NumberOfStars must be an integer between 1 and 10
111 $matches = array();
112 if (preg_match('/^stars\‍((.+)\‍)$/', $addfieldentry['type'], $matches)) {
113 if (!preg_match('/^[0-9]+$/', $matches[1]) || $matches[1] < 1 || $matches[1] > 10) {
114 setEventMessages($langs->trans('BadValueForType', $addfieldentry['type']), null, 'errors');
115 return -2;
116 }
117 }
118 }
119
120 $pathoffiletoeditsrc = $readdir.'/class/'.dol_strtolower($objectname).'.class.php';
121 $pathoffiletoedittarget = $destdir.'/class/'.dol_strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : '');
122 if (!dol_is_file($pathoffiletoeditsrc)) {
123 $langs->load("errors");
124 setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
125 return -3;
126 }
127
128 //$pathoffiletoedittmp = $destdir.'/class/'.dol_strtolower($objectname).'.class.php.tmp';
129 //dol_delete_file($pathoffiletoedittmp, 0, 1, 1);
130
131 try {
132 include_once $pathoffiletoeditsrc;
133 if (class_exists($objectname)) {
134 $object = new $objectname($db);
135 } else {
136 return -4;
137 }
138 '@phan-var-force CommonObject $object';
139
140 // Backup old file
141 dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
142
143 // Edit class files
144 $contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc));
145
146 // Update ->fields (to add or remove entries defined into $addfieldentry)
147 if (count($object->fields)) {
148 if (is_array($addfieldentry) && count($addfieldentry)) {
149 $name = $addfieldentry['name'];
150 unset($addfieldentry['name']);
151
152 $object->fields[$name] = $addfieldentry;
153 }
154 if (!empty($delfieldentry)) {
155 $name = $delfieldentry;
156 unset($object->fields[$name]);
157 }
158 }
159
160 dol_sort_array($object->fields, 'position');
161
162 $i = 0;
163 $texttoinsert = '// BEGIN MODULEBUILDER PROPERTIES'."\n";
164 $texttoinsert .= "\t".'
167'."\n";
168 $texttoinsert .= "\t".'public $fields = array('."\n";
169
170 if (count($object->fields)) {
171 foreach ($object->fields as $key => $val) {
172 $i++;
173 $texttoinsert .= "\t\t".'"'.$key.'" => array(';
174 $texttoinsert .= '"type" => "'.dol_escape_php($val['type']).'",';
175 $texttoinsert .= ' "label" => "'.dol_escape_php($val['label']).'",';
176 if (!empty($val['picto'])) {
177 $texttoinsert .= ' "picto" => "'.dol_escape_php($val['picto']).'",';
178 }
179 $texttoinsert .= ' "enabled" => "'.dol_escape_php($val['enabled'] !== '' ? $val['enabled'] : '1').'",';
180 $texttoinsert .= " 'position' => ".($val['position'] !== '' ? (int) $val['position'] : 50).",";
181 $texttoinsert .= " 'notnull' => ".(empty($val['notnull']) ? 0 : (int) $val['notnull']).",";
182 $texttoinsert .= ' "visible" => "'.dol_escape_php($val['visible'] !== '' ? $val['visible'] : '-1').'",';
183 if (!empty($val['noteditable'])) {
184 $texttoinsert .= ' "noteditable" => "'.dol_escape_php((string) $val['noteditable']).'",';
185 }
186 if (!empty($val['alwayseditable'])) {
187 $texttoinsert .= ' "alwayseditable" => "'.dol_escape_php((string) $val['alwayseditable']).'",';
188 }
189 if (array_key_exists('default', $val) && (!empty($val['default']) || $val['default'] === '0')) {
190 $texttoinsert .= ' "default" => "'.dol_escape_php($val['default']).'",';
191 }
192 if (!empty($val['index'])) {
193 $texttoinsert .= ' "index" => "'.(int) $val['index'].'",';
194 }
195 if (!empty($val['foreignkey'])) {
196 $texttoinsert .= ' "foreignkey" => "'.dol_escape_php($val['foreignkey']).'",';
197 }
198 if (!empty($val['searchall'])) {
199 $texttoinsert .= ' "searchall" => "'.(int) $val['searchall'].'",';
200 }
201 if (!empty($val['isameasure'])) {
202 $texttoinsert .= ' "isameasure" => "'.(int) $val['isameasure'].'",';
203 }
204 if (!empty($val['css'])) {
205 $texttoinsert .= ' "css" => "'.dol_escape_php($val['css']).'",';
206 }
207 if (!empty($val['cssview'])) {
208 $texttoinsert .= ' "cssview" => "'.dol_escape_php($val['cssview']).'",';
209 }
210 if (!empty($val['csslist'])) {
211 $texttoinsert .= ' "csslist" => "'.dol_escape_php($val['csslist']).'",';
212 }
213 if (!empty($val['help'])) {
214 $texttoinsert .= ' "help" => "'.dol_escape_php($val['help']).'",';
215 }
216 if (!empty($val['showoncombobox'])) {
217 $texttoinsert .= ' "showoncombobox" => "'.(int) $val['showoncombobox'].'",';
218 }
219 if (!empty($val['disabled'])) {
220 $texttoinsert .= ' "disabled" => "'.(int) $val['disabled'].'",';
221 }
222 if (!empty($val['autofocusoncreate'])) {
223 $texttoinsert .= ' "autofocusoncreate" => "'.(int) $val['autofocusoncreate'].'",';
224 }
225 if (!empty($val['arrayofkeyval'])) {
226 $texttoinsert .= ' "arrayofkeyval" => array(';
227 $i = 0;
228 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
229 if ($i) {
230 $texttoinsert .= ", ";
231 }
232 $texttoinsert .= '"'.dol_escape_php($key2).'" => "'.dol_escape_php($val2).'"';
233 $i++;
234 }
235 $texttoinsert .= '),';
236 }
237 if (!empty($val['validate'])) {
238 $texttoinsert .= ' "validate" => "'.(int) $val['validate'].'",';
239 }
240 if (!empty($val['comment'])) {
241 $texttoinsert .= ' "comment" => "'.dol_escape_php($val['comment']).'"';
242 }
243
244 $texttoinsert .= "),\n";
245 //print $texttoinsert;
246 }
247 }
248
249 $texttoinsert .= "\t".');'."\n";
250 //print ($texttoinsert);exit;
251
252 if (count($object->fields)) {
253 //$typetotypephp = array('integer' => 'integer', 'duration' => 'integer', 'varchar' => 'string');
254
255 foreach ($object->fields as $key => $val) {
256 $i++;
257 //$typephp = $typetotypephp[$val['type']];
258 $texttoinsert .= "\t".'public $'.$key.";";
259 //if ($key == 'rowid') $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
260 //if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
261 //$texttoinsert.= ($val['notnull']?' NOT NULL':'');
262 //if ($i < count($object->fields)) $texttoinsert. = ";";
263 $texttoinsert .= "\n";
264 }
265 }
266
267 $texttoinsert .= "\t".'// END MODULEBUILDER PROPERTIES';
268
269 //print($texttoinsert);
270
271 $contentclass = preg_replace('/\/\/ BEGIN MODULEBUILDER PROPERTIES.*END MODULEBUILDER PROPERTIES/ims', $texttoinsert, $contentclass);
272 //print $contentclass;
273
274 dol_mkdir(dirname($pathoffiletoedittarget));
275
276 //file_put_contents($pathoffiletoedittmp, $contentclass);
277 $result = file_put_contents(dol_osencode($pathoffiletoedittarget), $contentclass);
278
279 if ($result) {
280 dolChmod($pathoffiletoedittarget, $newmask);
281 } else {
282 $error++;
283 }
284
285 return $error ? -1 : $object;
286 } catch (Exception $e) {
287 print $e->getMessage();
288 return -5;
289 }
290}
291
305function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '', $object = null, $moduletype = 'external')
306{
307 global $db, $langs;
308
309 $error = 0;
310
311 if (empty($objectname)) {
312 return -1;
313 }
314 if (empty($readdir)) {
315 $readdir = $destdir;
316 }
317
318 $pathoffiletoclasssrc = $readdir.'/class/'.dol_strtolower($objectname).'.class.php';
319
320 // Edit .sql file
321 if ($moduletype == 'internal') {
322 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.dol_strtolower($module).'_'.dol_strtolower($objectname).'.sql';
323 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
324 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.dol_strtolower($module).'_'.dol_strtolower($objectname).'-'.dol_strtolower($module).'.sql';
325 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
326 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.dol_strtolower($module).'-'.dol_strtolower($module).'.sql';
327 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
328 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.dol_strtolower($module).'.sql';
329 }
330 }
331 }
332 } else {
333 $pathoffiletoeditsrc = '/sql/llx_'.dol_strtolower($module).'_'.dol_strtolower($objectname).'.sql';
334 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
335 $pathoffiletoeditsrc = '/sql/llx_'.dol_strtolower($module).'_'.dol_strtolower($objectname).'-'.dol_strtolower($module).'.sql';
336 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
337 $pathoffiletoeditsrc = '/sql/llx_'.dol_strtolower($module).'-'.dol_strtolower($module).'.sql';
338 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
339 $pathoffiletoeditsrc = '/sql/llx_'.dol_strtolower($module).'.sql';
340 }
341 }
342 }
343 }
344
345 // Complete path to be full path
346 $pathoffiletoedittarget = $destdir.$pathoffiletoeditsrc.($readdir != $destdir ? '.new' : '');
347 $pathoffiletoeditsrc = $readdir.$pathoffiletoeditsrc;
348
349 if (!dol_is_file($pathoffiletoeditsrc)) {
350 $langs->load("errors");
351 setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
352 return -1;
353 }
354
355 // Load object from myobject.class.php
356 try {
357 if (!is_object($object)) {
358 include_once $pathoffiletoclasssrc;
359 if (class_exists($objectname)) {
360 $object = new $objectname($db);
361 } else {
362 return -1;
363 }
364 }
365 } catch (Exception $e) {
366 print $e->getMessage();
367 }
368
369 // Backup old file
370 dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
371
372 $contentsqlfile = file_get_contents(dol_osencode($pathoffiletoeditsrc));
373
374 $i = 0;
375 $texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n";
376 if (count($object->fields)) {
377 foreach ($object->fields as $key => $val) {
378 $i++;
379
380 $type = $val['type'];
381 $type = preg_replace('/:.*$/', '', $type); // For case type = 'integer:Societe:societe/class/societe.class.php'
382
383 if ($type == 'html') {
384 $type = 'text'; // html modulebuilder type is a text type in database
385 } elseif ($type == 'price') {
386 $type = 'double'; // html modulebuilder type is a text type in database
387 } elseif (in_array($type, array('link', 'sellist', 'duration'))) {
388 $type = 'integer';
389 } elseif ($type == 'chkbxlst') {
390 $type = 'varchar(128)';
391 } elseif ($type == 'mail' || $type == 'email') { // Prefer to use 'email'
392 $type = 'varchar(128)';
393 } elseif (strpos($type, 'stars(') === 0) {
394 $type = 'integer';
395 } elseif ($type == 'phone') {
396 $type = 'varchar(20)';
397 } elseif ($type == 'ip') {
398 $type = 'varchar(32)';
399 } elseif ($type == 'url') {
400 $type = 'varchar(255)';
401 }
402
403 $texttoinsert .= "\t".$key." ".$type;
404 if ($key == 'rowid') {
405 $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY';
406 } elseif ($type == 'timestamp') {
407 $texttoinsert .= ' DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP';
408 }
409 if ($key == 'entity') {
410 $texttoinsert .= ' DEFAULT 1';
411 } else {
412 if (!empty($val['default'])) {
413 if (preg_match('/^null$/i', $val['default'])) {
414 $texttoinsert .= " DEFAULT NULL";
415 } elseif (preg_match('/varchar/', $type)) {
416 $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'";
417 } else {
418 $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : '');
419 }
420 }
421 }
422 $texttoinsert .= ((!empty($val['notnull']) && $val['notnull'] > 0) ? ' NOT NULL' : '');
423 if ($i < count($object->fields)) {
424 $texttoinsert .= ", ";
425 }
426 $texttoinsert .= "\n";
427 }
428 }
429 $texttoinsert .= "\t".'-- END MODULEBUILDER FIELDS';
430
431 $contentsqlfile = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsqlfile);
432
433 $result = file_put_contents($pathoffiletoedittarget, $contentsqlfile);
434 if ($result) {
435 dolChmod($pathoffiletoedittarget, $newmask);
436 } else {
437 $error++;
438 setEventMessages($langs->trans("ErrorFailToCreateFile", $pathoffiletoedittarget), null, 'errors');
439 }
440
441 // Edit .key.sql file
442 $pathoffiletoeditsrc = preg_replace('/\.sql$/', '.key.sql', $pathoffiletoeditsrc);
443 $pathoffiletoedittarget = preg_replace('/\.sql$/', '.key.sql', $pathoffiletoedittarget);
444 $pathoffiletoedittarget = preg_replace('/\.sql.new$/', '.key.sql.new', $pathoffiletoedittarget);
445
446 $contentsqlfile = file_get_contents(dol_osencode($pathoffiletoeditsrc));
447
448 $i = 0;
449 $texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n";
450 if (count($object->fields)) {
451 foreach ($object->fields as $key => $val) {
452 $i++;
453 if (!empty($val['index'])) {
454 $indexname = dolModuleBuilderSqlIdentifier(($key == 'ref' ? "uk_" : "idx_"), $module, $objectname, $key);
455 $texttoinsert .= "ALTER TABLE llx_".dol_strtolower($module).'_'.dol_strtolower($objectname)." ADD ".($key == 'ref' ? "UNIQUE INDEX " : "INDEX ").$indexname." (".$key.($key == 'ref' && array_key_exists('entity', $object->fields) ? ", entity" : "").");";
456 $texttoinsert .= "\n";
457 }
458 if (!empty($val['foreignkey'])) {
459 $tmp = explode('.', $val['foreignkey']);
460 if (!empty($tmp[0]) && !empty($tmp[1])) {
461 $constraintname = dolModuleBuilderSqlIdentifier("llx_", $module, $objectname, $key);
462 $texttoinsert .= "ALTER TABLE llx_".dol_strtolower($module).'_'.dol_strtolower($objectname)." ADD CONSTRAINT ".$constraintname." FOREIGN KEY (".$key.") REFERENCES llx_".preg_replace('/^llx_/', '', $tmp[0])."(".$tmp[1].");";
463 $texttoinsert .= "\n";
464 }
465 }
466 }
467 }
468 $texttoinsert .= '-- END MODULEBUILDER INDEXES';
469
470 $contentsqlfile = preg_replace('/-- BEGIN MODULEBUILDER INDEXES.*END MODULEBUILDER INDEXES/ims', $texttoinsert, $contentsqlfile);
471
472 dol_mkdir(dirname($pathoffiletoedittarget));
473
474 $result2 = file_put_contents($pathoffiletoedittarget, $contentsqlfile);
475 if ($result2) {
476 dolChmod($pathoffiletoedittarget, $newmask);
477 } else {
478 $error++;
479 setEventMessages($langs->trans("ErrorFailToCreateFile", $pathoffiletoedittarget), null, 'errors');
480 }
481
482 return $error ? -1 : 1;
483}
484
492{
493 $objects = array();
494 $listofobject = dol_dir_list($destdir.'/class', 'files', 0, '\.class\.php$');
495 foreach ($listofobject as $fileobj) {
496 if (preg_match('/^api_/', $fileobj['name'])) {
497 continue;
498 }
499 if (preg_match('/^actions_/', $fileobj['name'])) {
500 continue;
501 }
502
503 $tmpcontent = file_get_contents($fileobj['fullname']);
504 $reg = array();
505 if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) {
506 $objectnameloop = $reg[1];
507 $objects[$fileobj['fullname']] = $objectnameloop;
508 }
509 }
510 if (count($objects) > 0) {
511 return $objects;
512 }
513
514 return -1;
515}
516
524function checkExistComment($file, $number)
525{
526 if (!file_exists($file)) {
527 return -1;
528 }
529
530 $content = file_get_contents($file);
531 if ($number === 0) {
532 $ret = 0;
533 if (strpos($content, '/* BEGIN MODULEBUILDER TOPMENU MYOBJECT */') !== false
534 || strpos($content, '/* BEGIN MODULEBUILDER TOPMENU */') !== false) {
535 $ret++;
536 }
537 if (strpos($content, '/* END MODULEBUILDER TOPMENU MYOBJECT */') !== false
538 || strpos($content, '/* END MODULEBUILDER TOPMENU */') !== false) {
539 $ret++;
540 }
541 if (strpos($content, '/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT */') !== false) {
542 $ret++;
543 }
544 if (strpos($content, '/* END MODULEBUILDER LEFTMENU MYOBJECT */') !== false) {
545 $ret++;
546 }
547
548 if ($ret == 4) {
549 return 1;
550 }
551 } elseif ($number === 1) {
552 if (strpos($content, '/* BEGIN MODULEBUILDER PERMISSIONS */') !== false && strpos($content, '/* END MODULEBUILDER PERMISSIONS */') !== false) {
553 return 1;
554 }
555 } elseif ($number == 2) {
556 if (strpos($content, '/* BEGIN MODULEBUILDER DICTIONARIES */') !== false && strpos($content, '/* END MODULEBUILDER DICTIONARIES */') !== false) {
557 return 1;
558 }
559 }
560 return -1;
561}
568function deletePerms($file)
569{
570 require_once DOL_DOCUMENT_ROOT.'/modulebuilder/class/PermissionsBlock.class.php';
571
572 try {
573 $block = PermissionsBlock::fromFile($file);
574 } catch (\RuntimeException $e) {
575 dol_syslog('deletePerms '.$e->getMessage(), LOG_WARNING);
576 return -1;
577 }
578
579 return $block->write('') < 0 ? -1 : 1;
580}
581
598function reWriteAllPermissions($file, $permissions, $key, $right, $objectname, $module, $action)
599{
600 require_once DOL_DOCUMENT_ROOT.'/modulebuilder/class/RightsSyncService.class.php';
601
602 $module = (string) $module;
603 $objectname = (string) $objectname;
604 $permissions = is_array($permissions) ? $permissions : array();
605 $right = is_array($right) ? $right : array();
606
607 // The legacy signature carries the module name only for action -2; the other actions recover
608 // it from the descriptor filename.
609 if ($module === '') {
610 $module = (string) preg_replace('/^mod|\.class\.php$/', '', basename($file));
611 }
612
613 try {
614 switch ((int) $action) {
615 case -2:
616 $cmd = RightsSyncCommand::forObjectCreation($module, $file, $permissions, $objectname);
617 break;
618 case -1:
619 $cmd = RightsSyncCommand::forObjectDeletion($module, $file, $permissions, $objectname);
620 break;
621 case 1:
623 $module,
624 $file,
625 $permissions,
626 (string) ($right[4] ?? ''),
627 (string) ($right[1] ?? ''),
628 (string) ($right[5] ?? '')
629 );
630 break;
631 case 2:
633 $module,
634 $file,
635 $permissions,
636 (int) $key,
637 (string) ($right[4] ?? ''),
638 (string) ($right[1] ?? ''),
639 (string) ($right[5] ?? '')
640 );
641 break;
642 case 0:
643 $cmd = RightsSyncCommand::forRightDeletion($module, $file, $permissions, (int) $key);
644 break;
645 default:
646 dol_syslog('reWriteAllPermissions got an unknown action: '.$action, LOG_WARNING);
647 return -1;
648 }
649 } catch (\InvalidArgumentException $e) {
650 dol_syslog('reWriteAllPermissions '.$e->getMessage(), LOG_WARNING);
651 return -1;
652 }
653
654 $report = (new DescriptorRightsSyncService())->sync($cmd);
655
656 // The historical contract reports a skipped object creation as a failure.
657 if ($report->skipped > 0) {
658 return -1;
659 }
660
661 return $report->toLegacyReturnCode();
662}
663
670function parsePropertyString($string)
671{
672 $string = str_replace("'", '', $string);
673
674 // Uses a regular expression to capture keys and values
675 preg_match_all('/\s*([^\s=>]+)\s*=>\s*([^,]+),?/', $string, $matches, PREG_SET_ORDER);
676 $propertyArray = array();
677
678 foreach ($matches as $match) {
679 $key = trim($match[1]);
680 $value = trim($match[2]);
681
682 if (strpos($value, 'array(') === 0) {
683 $nestedArray = dol_substr($value, 6);
684 $nestedArray = parsePropertyString($nestedArray);
685 $value = $nestedArray;
686 } elseif (strpos($value, '"Id")') !== false) {
687 $value = str_replace(')', '', $value);
688 } else {
689 if (is_numeric($value)) {
690 if (strpos($value, '.') !== false) {
691 $value = (float) $value;
692 } else {
693 $value = (int) $value;
694 }
695 } else {
696 if ($value === 'true') {
697 $value = true;
698 } elseif ($value === 'false') {
699 $value = false;
700 }
701 }
702 }
703 $propertyArray[$key] = $value;
704 }
705
706 return $propertyArray;
707}
708
716function writePropsInAsciiDoc($file, $objectname, $destfile)
717{
718
719 // stock all properties in array
720 $attributesUnique = array('type','label', 'enabled', 'position', 'notnull', 'visible', 'noteditable', 'index', 'default' , 'foreignkey', 'arrayofkeyval', 'alwayseditable','validate', 'searchall','comment', 'isameasure', 'css', 'cssview','csslist', 'help', 'showoncombobox','picto' );
721
722 $start = "public \$fields = array(";
723 $end = ");";
724 $i = 1;
725 $keys = array();
726 $lines = file($file);
727 // Search for start and end lines
728 foreach ($lines as $i => $line) {
729 if (strpos($line, $start) !== false) {
730 // Copy lines until the end on array
731 while (isset($lines[++$i])) {
732 $line = $lines[$i];
733 if (strpos($line, $end) !== false) {
734 break;
735 }
736 $keys[] = $line;
737 }
738 break;
739 }
740 }
741 // write the begin of table with specifics options
742 $table = "== DATA SPECIFICATIONS\n";
743 $table .= "=== Table of fields with properties for object *$objectname* : \n";
744 $table .= "[options='header',grid=rows,frame=topbot,width=100%,caption=Organisation]\n";
745 $table .= "|===\n";
746 $table .= "|code";
747 // write all properties in the header of the table
748 foreach ($attributesUnique as $attUnique) {
749 $table .= "|".$attUnique;
750 }
751 $table .= "\n";
752 $valuesModif = array();
753 foreach ($keys as $string) {
754 $string = trim($string, "'");
755 $string = rtrim($string, ",");
756
757 $array = parsePropertyString($string);
758
759 // Iterate through the array to merge all key to one array
760 $code = '';
761 foreach ($array as $key => $value) {
762 if (is_array($value)) {
763 $code = $key;
764 continue;
765 } else {
766 $array[$code][$key] = $value;
767 unset($array[$key]);
768 }
769 }
770 // check if is array after parsing the string
771 if (!is_array($array)) {
772 return -1;
773 }
774 $field = array_keys($array);
775 if ($field[0] === '') {
776 $field[0] = 'label';
777 }
778 $values = array_values($array)[0];
779
780 // check each field has all properties and add it if missed
781 foreach ($attributesUnique as $attUnique) {
782 if ($attUnique == 'type' && $field[0] === 'label') {
783 $values[$attUnique] = 'varchar(255)';
784 }
785 if (!array_key_exists($attUnique, $values)) {
786 $valuesModif[$attUnique] = '';
787 } else {
788 $valuesModif[$attUnique] = $values[$attUnique];
789 }
790 }
791 $table .= "|*" . $field[0] . "*|";
792 $table .= implode("|", $valuesModif) . "\n";
793 }
794
795 // end table
796 $table .= "|===\n";
797 $table .= "__ end table for object $objectname\n";
798
799 //write in file @phan-suppress-next-line PhanPluginSuspiciousParamPosition
800 $writeInFile = dolReplaceInFile($destfile, array('== DATA SPECIFICATIONS' => $table));
801 if ($writeInFile < 0) {
802 return -1;
803 }
804 return 1;
805}
806
807
815function deletePropsAndPermsFromDoc($file, $objectname)
816{
817 if (dol_is_file($file)) {
818 $start = "== Table of fields and their properties for object *".dol_ucfirst($objectname)."* : ";
819 $end = "__ end table for object ".dol_ucfirst($objectname);
820
821 $str = file_get_contents($file);
822
823 $search = '/' . preg_quote($start, '/') . '(.*?)' . preg_quote($end, '/') . '/s';
824 $new_contents = preg_replace($search, '', $str);
825 file_put_contents($file, $new_contents);
826 dolChmod($file);
827
828 //perms If Exist
829 $perms = "|*".dol_strtolower($objectname)."*|";
830 $search_pattern_perms = '/' . preg_quote($perms, '/') . '.*?\n/';
831 $new_contents = preg_replace($search_pattern_perms, '', $new_contents);
832 file_put_contents($file, $new_contents);
833 dolChmod($file);
834 }
835}
836
837
838
849function getFromFile($file, $start, $end, $excludestart = '', $includese = 0)
850{
851 $keys = array();
852
853 //$lines = file(dol_osencode($file));
854 $fhandle = fopen(dol_osencode($file), 'r');
855 if ($fhandle) {
856 // Search for start and end lines
857 //foreach ($lines as $i => $line) {
858 while ($line = fgets($fhandle)) {
859 if (strpos($line, $start) !== false && (empty($excludestart) || strpos($line, $excludestart) === false)) {
860 if ($includese) {
861 $keys[] = $line;
862 }
863 // Copy lines until we reach the end
864 while (($line = fgets($fhandle)) !== false) {
865 if (strpos($line, $end) !== false) {
866 if ($includese) {
867 $keys[] = $line;
868 }
869 break;
870 }
871 $keys[] = $line;
872 }
873 break;
874 }
875 }
876 }
877 fclose($fhandle);
878
879 $content = implode("", $keys);
880 return $content;
881}
882
889function writePermsInAsciiDoc($file, $destfile)
890{
891 global $langs;
892 //search and get all permissions in string
893 $start = '/* BEGIN MODULEBUILDER PERMISSIONS */';
894 $end = '/* END MODULEBUILDER PERMISSIONS */';
895 $content = getFromFile($file, $start, $end);
896 if (empty($content)) {
897 return -1;
898 }
899 //prepare table
900 $string = "[options='header',grid=rows,width=60%,caption=Organisation]\n";
901 $string .= "|===\n";
902 // header for table
903 $header = array($langs->trans('Objects'),$langs->trans('Permission'));
904 foreach ($header as $h) {
905 $string .= "|".$h;
906 }
907 $string .= "\n";
908 //content table
909 $array = explode(";", $content);
910 $permissions = array_filter($array);
911 // delete occurrences "$r++" and ID
912 $permissions = str_replace('$r++', '1', $permissions);
913
914 $permsN = array();
915 foreach ($permissions as $i => $element) {
916 if ($element == 1) {
917 unset($permissions[$i]);
918 }
919 if (str_contains($element, '$this->numero')) {
920 unset($permissions[$i]);
921 }
922 if (str_contains($element, '$this->rights[$r][5]')) {
923 unset($permissions[$i]);
924 }
925 }
926 // cleaning the string on each element
927 foreach ($permissions as $key => $element) {
928 $element = str_replace(" '", '', $element);
929 $element = trim($element, "'");
930 $permsN[] = dol_substr($element, strpos($element, "=") + 1);
931 }
932 array_pop($permsN);
933
934 // Group permissions by Object and add it to string
935 $final_array = array();
936 $index = 0;
937 while ($index < count($permsN)) {
938 $temp_array = array($permsN[$index], $permsN[$index + 1]);
939 $final_array[] = $temp_array;
940 $index += 2;
941 }
942
943 $result = array();
944 foreach ($final_array as $subarray) {
945 // found object
946 $key = $subarray[1];
947 // add sub array to object
948 $result[$key][] = $subarray;
949 }
950 foreach ($result as $i => $pems) {
951 $string .= "|*".$i."*|";
952 foreach ($pems as $tab) {
953 $string .= $tab[0]." , ";
954 }
955 $string .= "\n";
956 }
957 // end table
958 $string .= "\n|===\n";
959 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
960 $write = dolReplaceInFile($destfile, array('__DATA_PERMISSIONS__' => $string));
961 if ($write < 0) {
962 return -1;
963 }
964 return 1;
965}
966
976function addObjectsToApiFile($srcfile, $file, $objects, $modulename)
977{
978 global $langs, $user;
979
980 if (!file_exists($file)) {
981 return -1;
982 }
983
984 $now = dol_now();
985 $content = file($file); // $content is an array
986
987 $includeClass = "dol_include_once\‍(\'\/\w+\/class\/\w+\.class\.php\'\‍);";
988 $props = 'public\s+\$\w+;';
989 $varcommented = '@var\s+\w+\s+\$\w+\s+{@type\s+\w+}';
990 $constructObj = '\$this->\w+\s+=\s+new\s+\w+\‍(\$this->db\‍);';
991
992 // add properties and declare them in constructor
993 foreach ($content as $lineNumber => &$lineContent) {
994 if (preg_match('/'.$varcommented.'/', $lineContent)) {
995 $lineContent = '';
996 foreach ($objects as $objectname) {
997 $lineContent .= "\t * @var ".$objectname." \$".dol_strtolower($objectname)." {@type ".$objectname."}". PHP_EOL;
998 }
999 //var_dump($lineContent);exit;
1000 } elseif (preg_match('/'.$props.'/', $lineContent)) {
1001 $lineContent = '';
1002 foreach ($objects as $objectname) {
1003 $lineContent .= "\t/*".PHP_EOL."\t * @var mixed TODO: set type".PHP_EOL."\t */".PHP_EOL."\tpublic \$".dol_strtolower($objectname).";". PHP_EOL;
1004 }
1005 } elseif (preg_match('/'.$constructObj.'/', $lineContent)) {
1006 $lineContent = '';
1007 foreach ($objects as $objectname) {
1008 $lineContent .= "\t\t\$this->".dol_strtolower($objectname)." = new ".$objectname."(\$this->db);". PHP_EOL;
1009 }
1010 } elseif (preg_match('/'.$includeClass.'/', $lineContent)) {
1011 $lineContent = '';
1012 foreach ($objects as $objectname) {
1013 $lineContent .= "dol_include_once('/".dol_strtolower($modulename)."/class/".dol_strtolower($objectname).".class.php');". PHP_EOL;
1014 }
1015 }
1016 }
1017
1018 $allContent = implode("", $content);
1019 file_put_contents($file, $allContent);
1020 dolChmod($file);
1021
1022 // Add methods for each object
1023 $allContent = getFromFile($srcfile, '/* BEGIN MODULEBUILDER API MYOBJECT */', '/* END MODULEBUILDER API MYOBJECT */');
1024 foreach ($objects as $objectname) {
1025 if (dol_strtolower($modulename) === dol_strtolower($objectname)) {
1026 dol_syslog('addObjectsToApiFile: skipping object "' . $objectname . '" — name collides with module "' . $modulename . '"', LOG_WARNING);
1027 continue;
1028 }
1029 $nc = new NamingContract($modulename, $objectname);
1030 $extraMap = [
1031 'htdocs/modulebuilder/template' => $nc->moduleNameLower,
1032 '---Replace with your own copyright and developer email---' => dol_print_date($now, '%Y') . ' ' . $user->getFullName($langs) . ($user->email ? ' <' . $user->email . '>' : ''),
1033 ];
1034 $fullMap = array_merge($nc->getSubstitutionMap(), $extraMap);
1035 $contentReplaced = str_replace(array_keys($fullMap), array_values($fullMap), $allContent);
1036
1037 dolReplaceInFile($file, array(
1038 '/* BEGIN MODULEBUILDER API MYOBJECT */' => '/* BEGIN MODULEBUILDER API '.dol_strtoupper($objectname).' */'.$contentReplaced."\t".'/* END MODULEBUILDER API '.dol_strtoupper($objectname).' */'."\n\n\n\t".'/* BEGIN MODULEBUILDER API MYOBJECT */'
1039 ));
1040 }
1041
1042 // Remove the block $allContent found in src file
1043 // TODO Replace with a replacement of all text including into /* BEGIN MODULEBUILDER API MYOBJECT */ and /* END MODULEBUILDER API MYOBJECT */
1044 dolReplaceInFile($file, array($allContent => ''));
1045
1046 return 1;
1047}
1048
1057function removeObjectFromApiFile($file, $objects, $objectname)
1058{
1059 if (!file_exists($file)) {
1060 return -1;
1061 }
1062
1063 $content = file($file); // $content is an array
1064
1065 $includeClass = "dol_include_once\‍(\'\/\w+\/class\/".dol_strtolower($objectname)."\.class\.php\'\‍);";
1066 $props = 'public\s+\$'.dol_strtolower($objectname);
1067 $varcommented = '@var\s+\w+\s+\$'.dol_strtolower($objectname).'\s+{@type\s+\w+}';
1068 $constructObj = '\$this->'.dol_strtolower($objectname).'\s+=\s+new\s+\w+\‍(\$this->db\‍);';
1069
1070 // add properties and declare them in constructor
1071 foreach ($content as $lineNumber => &$lineContent) {
1072 if (preg_match('/'.$varcommented.'/i', $lineContent)) {
1073 $lineContent = '';
1074 } elseif (preg_match('/'.$props.'/i', $lineContent)) {
1075 $lineContent = '';
1076 } elseif (preg_match('/'.$constructObj.'/i', $lineContent)) {
1077 $lineContent = '';
1078 } elseif (preg_match('/'.$includeClass.'/i', $lineContent)) {
1079 $lineContent = '';
1080 }
1081 }
1082
1083 $allContent = implode("", $content);
1084 file_put_contents($file, $allContent);
1085 dolChmod($file);
1086
1087 // for delete methods of object
1088 $begin = '/* BEGIN MODULEBUILDER API '.dol_strtoupper($objectname).' */';
1089 $end = '/* END MODULEBUILDER API '.dol_strtoupper($objectname).' */';
1090 $allContent = getFromFile($file, $begin, $end);
1091 $check = dolReplaceInFile($file, array($allContent => ''));
1092 if ($check) {
1093 dolReplaceInFile($file, array($begin => '', $end => ''));
1094 }
1095
1096 return 1;
1097}
1098
1099
1108function reWriteAllMenus($file, $menus, $menuWantTo, $key, $action)
1109{
1110 $errors = 0;
1111 $counter = 0;
1112 if (!file_exists($file)) {
1113 return -1;
1114 }
1115
1116 if ($action == 0 && !empty($key)) {
1117 // delete menu manually
1118 array_splice($menus, array_search($menus[$key], $menus), 1);
1119 } elseif ($action == 1) {
1120 // add menu manually
1121 array_push($menus, $menuWantTo);
1122 } elseif ($action == 2 && !empty($key) && !empty($menuWantTo)) {
1123 // update right from permissions array
1124 $urlCounter = 0;
1125 // check if the values already exists
1126 foreach ($menus as $index => $menu) {
1127 if ($index !== $key) {
1128 if ($menu['type'] === $menuWantTo['type']) {
1129 if (strcasecmp(str_replace(' ', '', $menu['titre']), str_replace(' ', '', $menuWantTo['titre'])) === 0) {
1130 $counter++;
1131 }
1132 if (strcasecmp(str_replace(' ', '', $menu['url']), str_replace(' ', '', $menuWantTo['url'])) === 0) {
1133 $urlCounter++;
1134 }
1135 }
1136 }
1137 }
1138 if (!$counter && $urlCounter < 2) {
1139 $menus[$key] = $menuWantTo;
1140 } else {
1141 $errors++;
1142 }
1143 } elseif ($action == -1 && !empty($menuWantTo) && is_string($menuWantTo)) {
1144 // delete menus when delete Object
1145 foreach ($menus as $index => $menu) {
1146 if ((strpos(dol_strtolower($menu['fk_menu']), dol_strtolower($menuWantTo)) !== false) || (strpos(dol_strtolower($menu['leftmenu']), dol_strtolower($menuWantTo)) !== false)) {
1147 array_splice($menus, array_search($menu, $menus), 1);
1148 }
1149 }
1150 } else {
1151 $errors++;
1152 }
1153 if (!$errors) {
1154 // delete All LEFT Menus (except for commented template MYOBJECT)
1155 $beginMenu = '/* BEGIN MODULEBUILDER LEFTMENU';
1156 $excludeBeginMenu = '/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT';
1157 $endMenu = '/* END MODULEBUILDER LEFTMENU';
1158 $protection = 0;
1159 while ($protection <= 1000 && $allMenus = getFromFile($file, $beginMenu, $endMenu, $excludeBeginMenu, 1)) {
1160 $protection++;
1161 dolReplaceInFile($file, array($allMenus => ''));
1162 }
1163
1164 // forge the menu code in a string
1165 $str_menu = "";
1166 foreach ($menus as $index => $menu) {
1167 $menu['position'] = "1000 + \$r";
1168 if ($menu['type'] === 'left') {
1169 $start = "\t\t".'/* BEGIN MODULEBUILDER LEFTMENU '.dol_strtoupper(empty($menu['object']) ? $menu['titre'] : $menu['object']).' */';
1170 $end = "\t\t".'/* END MODULEBUILDER LEFTMENU '.dol_strtoupper(empty($menu['object']) ? $menu['titre'] : $menu['object']).' */';
1171
1172 $val_actuel = $menu;
1173 $next_val = empty($menus[$index + 1]) ? null : $menus[$index + 1];
1174 //var_dump(dol_escape_php($menu['perms'], 1)); exit;
1175
1176 $str_menu .= $start."\n";
1177 $str_menu .= "\t\t\$this->menu[\$r++] = array(\n";
1178 $str_menu .= "\t\t\t'fk_menu' => '".dol_escape_php($menu['fk_menu'], 1)."',\n";
1179 $str_menu .= "\t\t\t'type' => '".dol_escape_php($menu['type'], 1)."',\n";
1180 $str_menu .= "\t\t\t'titre' => '".dol_escape_php($menu['titre'], 1)."',\n";
1181 $str_menu .= "\t\t\t'mainmenu' => '".dol_escape_php($menu['mainmenu'], 1)."',\n";
1182 $str_menu .= "\t\t\t'leftmenu' => '".dol_escape_php($menu['leftmenu'], 1)."',\n";
1183 $str_menu .= "\t\t\t'url' => '".dol_escape_php($menu['url'], 1)."',\n";
1184 $str_menu .= "\t\t\t'langs' => '".dol_escape_php($menu['langs'], 1)."',\n";
1185 $str_menu .= "\t\t\t'position' => ".((int) $menu['position']).",\n";
1186 $str_menu .= "\t\t\t'enabled' => '".dol_escape_php((string) $menu['enabled'], 1)."',\n";
1187 $str_menu .= "\t\t\t'perms' => '".dol_escape_php($menu['perms'], 1)."',\n";
1188 $str_menu .= "\t\t\t'target' => '".dol_escape_php($menu['target'], 1)."',\n";
1189 $str_menu .= "\t\t\t'user' => ".((int) $menu['user']).",\n";
1190 $str_menu .= "\t\t\t'object' => '".dol_escape_php($menu['object'], 1)."',\n";
1191 $str_menu .= "\t\t);\n";
1192
1193 if (is_null($next_val) || $val_actuel['leftmenu'] !== $next_val['leftmenu']) {
1194 $str_menu .= $end."\n";
1195 }
1196 }
1197 }
1198
1199 dolReplaceInFile($file, array('/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT */' => $str_menu."\n\t\t/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT */"));
1200 return 1;
1201 }
1202 return -1;
1203}
1204
1213function updateDictionaryInFile($module, $file, $dicts)
1214{
1215 $isEmpty = false;
1216 $dicData = "\t\t\$this->dictionaries = array(\n";
1218 foreach ($dicts as $key => $value) {
1219 if (empty($value)) {
1220 $isEmpty = true;
1221 $dicData = "\t\t\$this->dictionaries = array();";
1222 break;
1223 }
1224
1225 $dicData .= "\t\t\t'$key' => ";
1226
1227 if ($key === 'tabcond') {
1228 $conditions = array_map(
1233 static function ($val) use ($module) {
1234 return is_bool($val) ? "isModEnabled('$module')" : $val;
1235 },
1236 $value
1237 );
1238 $dicData .= "array(" . implode(", ", $conditions) . ")";
1239 } elseif ($key === 'tabhelp') {
1240 $helpItems = array();
1241 foreach ($value as $helpValue) {
1242 $helpItems[] = "array('code' => \$langs->trans('".$helpValue['code']."'), 'field2' => 'field2tooltip')";
1243 }
1244 $dicData .= "array(" . implode(",", $helpItems) . ")";
1245 } else {
1246 if (is_array($value)) {
1247 $dicData .= "array(" . implode(
1248 ",",
1249 array_map(
1254 static function ($val) {
1255 return "'$val'";
1256 },
1257 $value
1258 )
1259 ) . ")";
1260 } else {
1261 $dicData .= "'$value'";
1262 }
1263 }
1264 $dicData .= ",\n";
1265 }
1266 $dicData .= (!$isEmpty ? "\t\t);" : '');
1267
1268 $stringDic = getFromFile($file, '/* BEGIN MODULEBUILDER DICTIONARIES */', '/* END MODULEBUILDER DICTIONARIES */');
1269 $writeInfile = dolReplaceInFile($file, array($stringDic => $dicData."\n"));
1270
1271 return $writeInfile;
1272}
1273
1286function createNewDictionnary($modulename, $file, $namedic, $dictionnaires = null)
1287{
1288 global $db, $langs;
1289
1290 if (empty($namedic)) {
1291 setEventMessages($langs->trans("ErrorEmptyNameDic"), null, 'errors');
1292 return -1;
1293 }
1294 if (!file_exists($file)) {
1295 return -1;
1296 }
1297 $modulename = dol_strtolower($modulename);
1298
1299 if (empty($dictionnaires)) {
1300 $dictionnaires = array('langs' => '', 'tabname' => array(), 'tablib' => array(), 'tabsql' => array(), 'tabsqlsort' => array(), 'tabfield' => array(), 'tabfieldvalue' => array(), 'tabfieldinsert' => array(), 'tabrowid' => array(), 'tabcond' => array(), 'tabhelp' => array());
1301 }
1302
1303 $columns = array(
1304 'rowid' => array('type' => 'integer', 'value' => 11, 'extra' => 'AUTO_INCREMENT'),
1305 'code' => array('type' => 'varchar', 'value' => 255, 'null' => 'NOT NULL'),
1306 'label' => array('type' => 'varchar', 'value' => 255, 'null' => 'NOT NULL'),
1307 'position' => array('type' => 'integer', 'value' => 11, 'null' => 'NULL'),
1308 'use_default' => array('type' => 'varchar', 'value' => 11, 'default' => '1'),
1309 'active' => array('type' => 'integer', 'value' => 3)
1310 );
1311
1312 $primaryKey = 'rowid';
1313 foreach ($columns as $key => $value) {
1314 if ($key === 'rowid') {
1315 $primaryKey = 'rowid';
1316 break;
1317 }
1318 if (!array_key_exists('rowid', $columns)) {
1319 $primaryKey = array_key_first($columns);
1320 break;
1321 }
1322 }
1323
1324 // check if tablename exist in Database and create it if not
1325 $checkTable = $db->DDLDescTable(MAIN_DB_PREFIX.dol_strtolower($namedic));
1326 if ($checkTable && $db->num_rows($checkTable) > 0) {
1327 setEventMessages($langs->trans("ErrorTableExist", $namedic), null, 'errors');
1328 return -1;
1329 } else {
1330 $_results = $db->DDLCreateTable(MAIN_DB_PREFIX.dol_strtolower($namedic), $columns, $primaryKey, "");
1331 if ($_results < 0) {
1332 dol_print_error($db);
1333 $langs->load("errors");
1334 setEventMessages($langs->trans("ErrorTableNotFound", $namedic), null, 'errors');
1335 }
1336 }
1337
1338 // rewrite dictionary if
1339 $dictionnaires['langs'] = $modulename.'@'.$modulename;
1340 $dictionnaires['tabname'][] = dol_strtolower($namedic);
1341 $dictionnaires['tablib'][] = dol_ucfirst(dol_substr($namedic, 2));
1342 $dictionnaires['tabsql'][] = 'SELECT t.rowid as rowid, t.code, t.label, t.active FROM '.MAIN_DB_PREFIX.dol_strtolower($namedic).' as t';
1343 $dictionnaires['tabsqlsort'][] = (array_key_exists('label', $columns) ? 'label ASC' : '');
1344 $dictionnaires['tabfield'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : '');
1345 $dictionnaires['tabfieldvalue'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : '');
1346 $dictionnaires['tabfieldinsert'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : '');
1347 $dictionnaires['tabrowid'][] = $primaryKey;
1348 $dictionnaires['tabcond'][] = isModEnabled('$modulename'); // @phan-suppress-current-line UnknownModuleName
1349 $dictionnaires['tabhelp'][] = (array_key_exists('code', $columns) ? array('code' => $langs->trans('CodeTooltipHelp'), 'field2' => 'field2tooltip') : '');
1350
1351 // Build the dictionary string
1352 $writeInfile = updateDictionaryInFile($modulename, $file, $dictionnaires);
1353 if ($writeInfile > 0) {
1354 setEventMessages($langs->trans("DictionariesCreated", dol_ucfirst(dol_substr($namedic, 2))), null);
1355 }
1356
1357 return -1;
1358}
1359
1367function writeApiUrlsInDoc($file_api, $file_doc)
1368{
1369 $error = 0;
1370 if (!dol_is_file($file_api) || !dol_is_file($file_doc)) {
1371 $error++;
1372 }
1373 $string = getFromFile($file_api, '/*begin methods CRUD*/', '/*end methods CRUD*/');
1374 $extractUrls = explode("\n", $string);
1375
1376 // extract urls from file
1377 $urlValues = array();
1378 foreach ($extractUrls as $key => $line) {
1379 $lineWithoutTabsSpaces = preg_replace('/^[\t\s]+/', '', $line);
1380 if (strpos($lineWithoutTabsSpaces, '* @url') === 0) {
1381 $urlValue = trim(dol_substr($lineWithoutTabsSpaces, dol_strlen('* @url')));
1382 $urlValues[] = $urlValue;
1383 }
1384 }
1385
1386 // get urls by object
1387 $str = $_SERVER['HTTP_HOST'].'/api/index.php/';
1388 $groupedUrls = array();
1389 foreach ($urlValues as $url) {
1390 if (preg_match('/(?:GET|POST|PUT|DELETE) (\w+)s/', $url, $matches)) {
1391 $objectName = $matches[1];
1392 $url = $str.trim(strstr($url, ' '));
1393 $groupedUrls[$objectName][] = $url;
1394 }
1395 }
1396 if (empty($groupedUrls)) {
1397 $error++;
1398 }
1399
1400 // build format asciidoc for urls in table
1401 if (!$error) {
1402 $asciiDocTable = "[options=\"header\"]\n|===\n|Object | URLs\n"; // phpcs:ignore
1403 foreach ($groupedUrls as $objectName => $urls) {
1404 $urlsList = implode(" +\n*", $urls);
1405 $asciiDocTable .= "|$objectName | \n*$urlsList +\n";
1406 }
1407 $asciiDocTable .= "|===\n";
1408 $file_write = dolReplaceInFile($file_doc, array('__API_DOC__' => '__API_DOC__'."\n".$asciiDocTable));
1409 if ($file_write < 0) {
1410 return -1;
1411 }
1412 return 1;
1413 }
1414 return -1;
1415}
1416
1417
1424function countItemsInDirectory($path, $type = 1)
1425{
1426 if (!dol_is_dir($path)) {
1427 return false;
1428 }
1429
1430 $allFilesAndDirs = scandir($path);
1431 $count = 0;
1432
1433 foreach ($allFilesAndDirs as $item) {
1434 if ($item != '.' && $item != '..') {
1435 if ($type == 1 && dol_is_file($path . DIRECTORY_SEPARATOR . $item) && strpos($item, '.back') === false) {
1436 $count++;
1437 } elseif ($type == 2 && dol_is_dir($path . DIRECTORY_SEPARATOR . $item)) {
1438 $count++;
1439 }
1440 }
1441 }
1442 return $count;
1443}
1444
1453{
1454 return array(
1455 'contact' => array('file' => 'myobject_contact.php', 'var' => 'showtabofpagecontact', 'marker' => 'CONTACT', 'label' => 'Contacts'),
1456 'note' => array('file' => 'myobject_note.php', 'var' => 'showtabofpagenote', 'marker' => 'NOTE', 'label' => 'Notes'),
1457 'document' => array('file' => 'myobject_document.php', 'var' => 'showtabofpagedocument', 'marker' => 'DOCUMENT', 'label' => 'Documents'),
1458 'agenda' => array('file' => 'myobject_agenda.php', 'var' => 'showtabofpageagenda', 'marker' => 'AGENDA', 'label' => 'Events'),
1459 );
1460}
1461
1474{
1475 return array(
1476 'sendmail' => array('marker' => 'SENDMAIL', 'label' => 'SendMail', 'default' => 1, 'mode' => 'remove'),
1477 'clone' => array('marker' => 'CLONE', 'label' => 'ToClone', 'default' => 1, 'mode' => 'remove'),
1478 'validate' => array('marker' => 'VALIDATE', 'label' => 'Validate', 'default' => 1, 'mode' => 'remove'),
1479 'setdraft' => array('marker' => 'SETDRAFT', 'label' => 'SetToDraft', 'default' => 1, 'mode' => 'remove'),
1480 'statuschange' => array('marker' => 'STATUSCHANGE', 'label' => 'CancelAndReopen', 'default' => 0, 'mode' => 'activate'),
1481 'delete' => array('marker' => 'DELETE', 'label' => 'Delete', 'default' => 1, 'mode' => 'remove'),
1482 );
1483}
1484
1493{
1494 $defaults = array();
1495 foreach ($map as $key => $meta) {
1496 if (!isset($meta['default']) || !empty($meta['default'])) {
1497 $defaults[] = $key;
1498 }
1499 }
1500 return $defaults;
1501}
1502
1512{
1513 $quotedmarker = preg_quote($marker, '/');
1514 // The trailing \R must not be a \s*: that would also eat the indentation of the next line
1515 return '/\h*\/\/ BEGIN MODULEBUILDER ACTION '.$quotedmarker.'.*?\/\/ END MODULEBUILDER ACTION '.$quotedmarker.'\h*\R(?:\h*\R)?/s';
1516}
1517
1526{
1527 $quotedmarker = preg_quote($marker, '/');
1528 // \R and not \n, to stay aligned with getModuleBuilderCardActionBlockPattern()
1529 return array(
1530 '/\h*\/\* BEGIN COMMENTED '.$quotedmarker.'\h*\R/',
1531 '/\h*END COMMENTED '.$quotedmarker.'\h*\*\/\h*\R/',
1532 );
1533}
1534
1544{
1545 return '/\/\/BEGIN MODULEBUILDER LINES.*?\/\/END MODULEBUILDER LINES\s*/s';
1546}
1547
1556function filterEnabledKeys($requested, $map)
1557{
1558 $valid = array();
1559 if (!is_array($requested) || empty($requested)) {
1560 return $valid;
1561 }
1562 foreach (array_keys($map) as $key) {
1563 if (in_array($key, $requested, true)) {
1564 $valid[] = $key;
1565 }
1566 }
1567 return $valid;
1568}
1569
1578function filterEnabledTabs($requested, $map)
1579{
1580 return filterEnabledKeys($requested, $map);
1581}
1582
1593function dolReplaceInFilePreservingModuleBuilderMarkers($file, $arrayreplacement)
1594{
1595 if (!file_exists($file)) {
1596 return -1;
1597 }
1598 $content = file_get_contents($file);
1599 if ($content === false) {
1600 return -1;
1601 }
1602
1603 // Hide every "/* BEGIN|END MODULEBUILDER ... */" marker behind a sentinel before substituting
1604 $foundmarkers = array();
1605 preg_match_all('/\/\*\s*(?:BEGIN|END) MODULEBUILDER [^*]*\*\//', $content, $foundmarkers);
1606 $sentinels = array();
1607 foreach (array_values(array_unique($foundmarkers[0])) as $index => $marker) {
1608 $key = "\0MODULEBUILDERMARKER".$index."\0";
1609 $sentinels[$key] = $marker;
1610 $content = str_replace($marker, $key, $content);
1611 }
1612
1613 $content = str_replace(array_keys($arrayreplacement), array_values($arrayreplacement), $content);
1614
1615 // Restore the protected markers untouched
1616 if (!empty($sentinels)) {
1617 $content = strtr($content, $sentinels);
1618 }
1619
1620 if (file_put_contents($file, $content) === false) {
1621 return -1;
1622 }
1623 return 1;
1624}
1625
1632{
1633 $pages = array('myobject_card.php', 'myobject_list.php');
1634 foreach (getModuleBuilderObjectTabs() as $tabinfo) {
1635 $pages[] = $tabinfo['file'];
1636 }
1637 return $pages;
1638}
1639
1647{
1648 // The trailing \R must not be a \s*: that would also eat the indentation of the next line
1649 return '/^\h*\/\/ BEGIN MODULEBUILDER ACCESSPOLICY\h*\R(.*?)^\h*\/\/ END MODULEBUILDER ACCESSPOLICY\h*\R/ms';
1650}
1651
1660{
1661 $block = "// Access policy defined with ModuleBuilder, see MyObject::\$accesspolicy\n";
1662 $block .= "try {\n";
1663 $block .= "\t\$permissiontoread = ".$policy->getExpression()->toPhp().";\n";
1664 $block .= "} catch (Throwable \$e) {\n";
1665 $block .= "\tdol_syslog(__FILE__.': access policy evaluation failed, access denied: '.\$e->getMessage(), LOG_ERR);\n";
1666 $block .= "\t\$permissiontoread = false;\n";
1667 $block .= "}\n";
1668 if ($policy->getMessage() !== '') {
1669 // The message is a translation key checked by AccessPolicyConfig: it cannot break out of the quotes
1670 $block .= "if (!\$permissiontoread) {\n";
1671 $block .= "\taccessforbidden('".$policy->getMessage()."');\n";
1672 $block .= "}\n";
1673 }
1674 return $block;
1675}
1676
1684{
1685 $property = "\n";
1686 $property .= "\t/**\n";
1687 $property .= "\t * @var string Access policy of the object pages, serialized by ModuleBuilder (see AccessPolicyConfig)\n";
1688 $property .= "\t */\n";
1689 $property .= "\tpublic \$accesspolicy = ".var_export($policy->toJson(), true).";\n";
1690 return $property;
1691}
1692
1701{
1702 $content = file_exists($file) ? file_get_contents($file) : false;
1703 if ($content === false) {
1704 throw new \InvalidArgumentException('Unable to read the object class '.$file);
1705 }
1706
1707 $matches = array();
1708 $nbpolicies = preg_match_all('/^\h*public \$accesspolicy = \'((?:[^\'\\\\]|\\\\.)*)\';\h*$/m', $content, $matches);
1709 if (empty($nbpolicies)) {
1710 return null;
1711 }
1712 if ($nbpolicies > 1) {
1713 throw new \InvalidArgumentException('The object class '.$file.' stores several access policies');
1714 }
1715 // Reverse var_export(): a single quoted PHP string only escapes the quote and the backslash
1716 return AccessPolicyConfig::fromJson(strtr($matches[1][0], array("\\'" => "'", "\\\\" => "\\")));
1717}
1718
1726function resolveModuleBuilderAccessPolicyBlock(string $file, ?string $replacement): int
1727{
1728 $content = file_exists($file) ? file_get_contents($file) : false;
1729 if ($content === false) {
1730 dol_syslog(__FUNCTION__.": unable to read ".$file, LOG_ERR);
1731 return -1;
1732 }
1733
1735 $nbblocks = preg_match_all($pattern, $content);
1736 if ($nbblocks !== 1) {
1737 dol_syslog(__FUNCTION__.": expected one ACCESSPOLICY block in ".$file.", found ".((int) $nbblocks), LOG_ERR);
1738 return -1;
1739 }
1740
1741 $updated = preg_replace_callback(
1742 $pattern,
1747 static function ($matches) use ($replacement) {
1748 return ($replacement === null) ? $matches[1] : $replacement;
1749 },
1750 $content
1751 );
1752 if ($updated === null || file_put_contents($file, $updated) === false) {
1753 dol_syslog(__FUNCTION__.": unable to write ".$file, LOG_ERR);
1754 return -1;
1755 }
1756 return 1;
1757}
1758
1768{
1769 return resolveModuleBuilderAccessPolicyBlock($file, ($policy === null) ? null : renderModuleBuilderAccessPolicyBlock($policy));
1770}
1771
1781{
1782 return resolveModuleBuilderAccessPolicyBlock($file, ($policy === null) ? null : renderModuleBuilderAccessPolicyProperty($policy));
1783}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Immutable access policy of the pages generated by ModuleBuilder: a rule tree and a deny message.
static fromJson(string $json)
Load a serialized policy, as produced by toJson().
toJson()
Serialize the policy.
Syncs rights straight into the mod<Module>.class.php descriptor file.
Immutable value object holding all case variants of a module/object pair.
static fromFile(string $file)
Read a descriptor and locate its permissions block.
static forObjectDeletion(string $module, string $descriptorFile, array $permissions, string $objectName)
Drop every right attached to an object being deleted.
static forRightDeletion(string $module, string $descriptorFile, array $permissions, int $rightKey)
Remove one right, addressed by its index in the rights array.
static forRightUpdate(string $module, string $descriptorFile, array $permissions, int $rightKey, string $objectName, string $label, string $crud)
Replace one right, addressed by its index in the rights array.
static forRightAddition(string $module, string $descriptorFile, array $permissions, string $objectName, string $label, string $crud)
Append one right to the descriptor.
static forObjectCreation(string $module, string $descriptorFile, array $permissions, string $objectName)
Declare the three CRUD rights of a newly generated object.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_is_dir($folder)
Test if filename is a directory.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask='0', $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_now($mode='gmt')
Return date for now.
dol_ucfirst($string, $encoding="UTF-8")
Convert first character of the first word of a string to upper.
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_escape_php($stringtoescape, $stringforquotes=2)
Returns text escaped for inclusion into a php string, build with double quotes " or '.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
getModuleBuilderDefaultEnabledKeys($map)
Return the keys enabled by default in a ModuleBuilder generation map.
updateDictionaryInFile($module, $file, $dicts)
Updates a dictionary in a module descriptor file.
deletePropsAndPermsFromDoc($file, $objectname)
Delete property and permissions from documentation ascii file if we delete an object.
filterEnabledTabs($requested, $map)
Filter a list of requested tab keys against the known optional tabs map.
applyModuleBuilderAccessPolicyToPage(string $file, ?AccessPolicyConfig $policy)
Apply an access policy to a generated object page.
applyModuleBuilderAccessPolicyToClass(string $file, ?AccessPolicyConfig $policy)
Store an access policy in the generated object class.
getModuleBuilderCardActionUncommentPatterns($marker)
Build the regular expressions removing the comment fence of a card action generated in 'activate' mod...
getModuleBuilderAccessPolicyFromClassFile(string $file)
Load the access policy stored in a generated object class by renderModuleBuilderAccessPolicyProperty(...
createNewDictionnary($modulename, $file, $namedic, $dictionnaires=null)
Create a new dictionary table.
filterEnabledKeys($requested, $map)
Filter a list of requested keys against a known map of generable elements.
countItemsInDirectory($path, $type=1)
count directories or files in modulebuilder folder
getModuleBuilderCardActionBlockPattern($marker)
Build the regular expression matching every block of a card action in the object card template.
writePermsInAsciiDoc($file, $destfile)
Write all permissions of each object in AsciiDoc format.
reWriteAllMenus($file, $menus, $menuWantTo, $key, $action)
parsePropertyString($string)
Converts a formatted properties string into an associative array.
renderModuleBuilderAccessPolicyBlock(AccessPolicyConfig $policy)
Render the block that computes $permissiontoread from an access policy in a generated page.
rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir='', $object=null, $moduletype='external')
Save data into a memory area shared by all users, all sessions on server.
writeApiUrlsInDoc($file_api, $file_doc)
Generate Urls and add them to documentation module.
getFromFile($file, $start, $end, $excludestart='', $includese=0)
Search a string and return all lines needed from file.
dolGetListOfObjectClasses($destdir)
Get list of existing objects from a directory.
deletePerms($file)
Delete all permissions declared in the permissions section of a module descriptor.
getModuleBuilderLinesBlockPattern()
Return the regular expression matching a block of object lines code in the templates,...
writePropsInAsciiDoc($file, $objectname, $destfile)
Write all properties of the object in AsciiDoc format.
renderModuleBuilderAccessPolicyProperty(AccessPolicyConfig $policy)
Render the property of the generated object class that keeps the serialized access policy.
dolModuleBuilderSqlIdentifier(string $prefix, string $module, string $table, string $key)
Build the name of an index or of a foreign key constraint for a table generated by the module builder...
removeObjectFromApiFile($file, $objects, $objectname)
Remove Object variables and methods from API_Module File.
getModuleBuilderObjectCardActions()
Return the map of optional action buttons that can be generated on the card page of a ModuleBuilder o...
getModuleBuilderAccessPolicyPages()
Return the object pages whose read access is driven by the access policy defined in ModuleBuilder.
dolReplaceInFilePreservingModuleBuilderMarkers($file, $arrayreplacement)
Apply substitutions to a module descriptor file while preserving the MODULEBUILDER comment markers.
rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir='', $addfieldentry=array(), $delfieldentry='')
Regenerate files .class.php.
resolveModuleBuilderAccessPolicyBlock(string $file, ?string $replacement)
Resolve the ACCESSPOLICY block of a generated file.
reWriteAllPermissions($file, $permissions, $key, $right, $objectname, $module, $action)
Rewriting all permissions after any actions.
checkExistComment($file, $number)
Function to check if comment BEGIN and END exists in modMyModule class.
getModuleBuilderAccessPolicyBlockPattern()
Return the regular expression matching the ACCESSPOLICY block of a template.
getModuleBuilderObjectTabs()
Return the map of optional tabs that can be generated for a ModuleBuilder object.
addObjectsToApiFile($srcfile, $file, $objects, $modulename)
Add Object in ModuleApi File.