dolibarr 18.0.6
modulebuilder.lib.php
Go to the documentation of this file.
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
38function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = '', $addfieldentry = array(), $delfieldentry = '')
39{
40 global $db, $langs;
41
42 if (empty($objectname)) {
43 return -6;
44 }
45 if (empty($readdir)) {
46 $readdir = $destdir;
47 }
48
49 if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) {
50 dol_print_error('', 'Bad parameter addfieldentry with a property arrayofkeyval defined but that is not an array.');
51 return -7;
52 }
53
54 $error = 0;
55
56 // Check parameters
57 if (is_array($addfieldentry) && count($addfieldentry) > 0) {
58 if (empty($addfieldentry['name'])) {
59 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Name")), null, 'errors');
60 return -2;
61 }
62 if (empty($addfieldentry['label'])) {
63 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors');
64 return -2;
65 }
66 if (!preg_match('/^(integer|price|sellist|varchar|double|text|html|duration)/', $addfieldentry['type'])
67 && !preg_match('/^(boolean|smallint|real|date|datetime|timestamp|phone|mail|url|ip|password)$/', $addfieldentry['type'])) {
68 setEventMessages($langs->trans('BadValueForType', $addfieldentry['type']), null, 'errors');
69 return -2;
70 }
71 }
72
73 $pathoffiletoeditsrc = $readdir.'/class/'.strtolower($objectname).'.class.php';
74 $pathoffiletoedittarget = $destdir.'/class/'.strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : '');
75 if (!dol_is_file($pathoffiletoeditsrc)) {
76 $langs->load("errors");
77 setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
78 return -3;
79 }
80
81 //$pathoffiletoedittmp=$destdir.'/class/'.strtolower($objectname).'.class.php.tmp';
82 //dol_delete_file($pathoffiletoedittmp, 0, 1, 1);
83
84 try {
85 include_once $pathoffiletoeditsrc;
86 if (class_exists($objectname)) {
87 $object = new $objectname($db);
88 } else {
89 return -4;
90 }
91
92 // Backup old file
93 dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
94
95 // Edit class files
96 $contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
97
98 // Update ->fields (to add or remove entries defined into $addfieldentry)
99 if (count($object->fields)) {
100 if (is_array($addfieldentry) && count($addfieldentry)) {
101 $name = $addfieldentry['name'];
102 unset($addfieldentry['name']);
103
104 $object->fields[$name] = $addfieldentry;
105 }
106 if (!empty($delfieldentry)) {
107 $name = $delfieldentry;
108 unset($object->fields[$name]);
109 }
110 }
111
112 dol_sort_array($object->fields, 'position');
113
114 $i = 0;
115 $texttoinsert = '// BEGIN MODULEBUILDER PROPERTIES'."\n";
116 $texttoinsert .= "\t".'
118'."\n";
119 $texttoinsert .= "\t".'public $fields=array('."\n";
120
121 if (count($object->fields)) {
122 foreach ($object->fields as $key => $val) {
123 $i++;
124 $texttoinsert .= "\t\t'".$key."' => array('type'=>'".$val['type']."',";
125 $texttoinsert .= " 'label'=>'".$val['label']."',";
126 if (!empty($val['picto'])) {
127 $texttoinsert .= " 'picto'=>'".$val['picto']."',";
128 }
129 $texttoinsert .= " 'enabled'=>'".($val['enabled'] !== '' ? $val['enabled'] : 1)."',";
130 $texttoinsert .= " 'position'=>".($val['position'] !== '' ? $val['position'] : 50).",";
131 $texttoinsert .= " 'notnull'=>".(empty($val['notnull']) ? 0 : $val['notnull']).",";
132 $texttoinsert .= " 'visible'=>".($val['visible'] !== '' ? $val['visible'] : -1).",";
133 if (!empty($val['noteditable'])) {
134 $texttoinsert .= " 'noteditable'=>'".$val['noteditable']."',";
135 }
136 if (!empty($val['alwayseditable'])) {
137 $texttoinsert .= " 'alwayseditable'=>'".$val['alwayseditable']."',";
138 }
139 if (!empty($val['default']) || (isset($val['default']) && $val['default'] === '0')) {
140 $texttoinsert .= " 'default'=>'".$val['default']."',";
141 }
142 if (!empty($val['index'])) {
143 $texttoinsert .= " 'index'=>".$val['index'].",";
144 }
145 if (!empty($val['foreignkey'])) {
146 $texttoinsert .= " 'foreignkey'=>'".$val['foreignkey']."',";
147 }
148 if (!empty($val['searchall'])) {
149 $texttoinsert .= " 'searchall'=>".$val['searchall'].",";
150 }
151 if (!empty($val['isameasure'])) {
152 $texttoinsert .= " 'isameasure'=>'".$val['isameasure']."',";
153 }
154 if (!empty($val['css'])) {
155 $texttoinsert .= " 'css'=>'".$val['css']."',";
156 }
157 if (!empty($val['cssview'])) {
158 $texttoinsert .= " 'cssview'=>'".$val['cssview']."',";
159 }
160 if (!empty($val['csslist'])) {
161 $texttoinsert .= " 'csslist'=>'".$val['csslist']."',";
162 }
163 if (!empty($val['help'])) {
164 $texttoinsert .= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\",";
165 }
166 if (!empty($val['showoncombobox'])) {
167 $texttoinsert .= " 'showoncombobox'=>'".$val['showoncombobox']."',";
168 }
169 if (!empty($val['disabled'])) {
170 $texttoinsert .= " 'disabled'=>'".$val['disabled']."',";
171 }
172 if (!empty($val['autofocusoncreate'])) {
173 $texttoinsert .= " 'autofocusoncreate'=>'".$val['autofocusoncreate']."',";
174 }
175 if (!empty($val['arrayofkeyval'])) {
176 $texttoinsert .= " 'arrayofkeyval'=>array(";
177 $i = 0;
178 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
179 if ($i) {
180 $texttoinsert .= ", ";
181 }
182 $texttoinsert .= "'".$key2."'=>'".$val2."'";
183 $i++;
184 }
185 $texttoinsert .= "),";
186 }
187 if (!empty($val['validate'])) {
188 $texttoinsert .= " 'validate'=>'".$val['validate']."',";
189 }
190 if (!empty($val['comment'])) {
191 $texttoinsert .= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\"";
192 }
193
194 $texttoinsert .= "),\n";
195 //print $texttoinsert;
196 }
197 }
198
199 $texttoinsert .= "\t".');'."\n";
200 //print ($texttoinsert);exit;
201
202 if (count($object->fields)) {
203 //$typetotypephp=array('integer'=>'integer', 'duration'=>'integer', 'varchar'=>'string');
204
205 foreach ($object->fields as $key => $val) {
206 $i++;
207 //$typephp=$typetotypephp[$val['type']];
208 $texttoinsert .= "\t".'public $'.$key.";";
209 //if ($key == 'rowid') $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
210 //if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
211 //$texttoinsert.= ($val['notnull']?' NOT NULL':'');
212 //if ($i < count($object->fields)) $texttoinsert.=";";
213 $texttoinsert .= "\n";
214 }
215 }
216
217 $texttoinsert .= "\t".'// END MODULEBUILDER PROPERTIES';
218
219 //print($texttoinsert);
220
221 $contentclass = preg_replace('/\/\/ BEGIN MODULEBUILDER PROPERTIES.*END MODULEBUILDER PROPERTIES/ims', $texttoinsert, $contentclass);
222 //print $contentclass;
223
224 dol_mkdir(dirname($pathoffiletoedittarget));
225
226 //file_put_contents($pathoffiletoedittmp, $contentclass);
227 $result = file_put_contents(dol_osencode($pathoffiletoedittarget), $contentclass);
228
229 if ($result) {
230 dolChmod($pathoffiletoedittarget, $newmask);
231 } else {
232 $error++;
233 }
234
235 return $error ? -1 : $object;
236 } catch (Exception $e) {
237 print $e->getMessage();
238 return -5;
239 }
240}
241
255function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '', $object = null, $moduletype = 'external')
256{
257 global $db, $langs;
258
259 $error = 0;
260
261 if (empty($objectname)) {
262 return -1;
263 }
264 if (empty($readdir)) {
265 $readdir = $destdir;
266 }
267
268 $pathoffiletoclasssrc = $readdir.'/class/'.strtolower($objectname).'.class.php';
269
270 // Edit .sql file
271 if ($moduletype == 'internal') {
272 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql';
273 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
274 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'_'.strtolower($objectname).'-'.strtolower($module).'.sql';
275 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
276 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'-'.strtolower($module).'.sql';
277 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
278 $pathoffiletoeditsrc = '/../install/mysql/tables/llx_'.strtolower($module).'.sql';
279 }
280 }
281 }
282 } else {
283 $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql';
284 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
285 $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'-'.strtolower($module).'.sql';
286 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
287 $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'-'.strtolower($module).'.sql';
288 if (! dol_is_file($readdir.$pathoffiletoeditsrc)) {
289 $pathoffiletoeditsrc = '/sql/llx_'.strtolower($module).'.sql';
290 }
291 }
292 }
293 }
294
295 // Complete path to be full path
296 $pathoffiletoedittarget = $destdir.$pathoffiletoeditsrc.($readdir != $destdir ? '.new' : '');
297 $pathoffiletoeditsrc = $readdir.$pathoffiletoeditsrc;
298
299 if (!dol_is_file($pathoffiletoeditsrc)) {
300 $langs->load("errors");
301 setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
302 return -1;
303 }
304
305 // Load object from myobject.class.php
306 try {
307 if (!is_object($object)) {
308 include_once $pathoffiletoclasssrc;
309 if (class_exists($objectname)) {
310 $object = new $objectname($db);
311 } else {
312 return -1;
313 }
314 }
315 } catch (Exception $e) {
316 print $e->getMessage();
317 }
318
319 // Backup old file
320 dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
321
322 $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
323
324 $i = 0;
325 $texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n";
326 if (count($object->fields)) {
327 foreach ($object->fields as $key => $val) {
328 $i++;
329
330 $type = $val['type'];
331 $type = preg_replace('/:.*$/', '', $type); // For case type = 'integer:Societe:societe/class/societe.class.php'
332
333 if ($type == 'html') {
334 $type = 'text'; // html modulebuilder type is a text type in database
335 } elseif ($type == 'price') {
336 $type = 'double'; // html modulebuilder type is a text type in database
337 } elseif (in_array($type, array('link', 'sellist', 'duration'))) {
338 $type = 'integer';
339 }
340 $texttoinsert .= "\t".$key." ".$type;
341 if ($key == 'rowid') {
342 $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY';
343 } elseif ($type == 'timestamp') {
344 $texttoinsert .= ' DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP';
345 }
346 if ($key == 'entity') {
347 $texttoinsert .= ' DEFAULT 1';
348 } else {
349 if (!empty($val['default'])) {
350 if (preg_match('/^null$/i', $val['default'])) {
351 $texttoinsert .= " DEFAULT NULL";
352 } elseif (preg_match('/varchar/', $type)) {
353 $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'";
354 } else {
355 $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : '');
356 }
357 }
358 }
359 $texttoinsert .= ((!empty($val['notnull']) && $val['notnull'] > 0) ? ' NOT NULL' : '');
360 if ($i < count($object->fields)) {
361 $texttoinsert .= ", ";
362 }
363 $texttoinsert .= "\n";
364 }
365 }
366 $texttoinsert .= "\t".'-- END MODULEBUILDER FIELDS';
367
368 $contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql);
369
370 $result = file_put_contents($pathoffiletoedittarget, $contentsql);
371 if ($result) {
372 dolChmod($pathoffiletoedittarget, $newmask);
373 } else {
374 $error++;
375 setEventMessages($langs->trans("ErrorFailToCreateFile", $pathoffiletoedittarget), null, 'errors');
376 }
377
378 // Edit .key.sql file
379 $pathoffiletoeditsrc = preg_replace('/\.sql$/', '.key.sql', $pathoffiletoeditsrc);
380 $pathoffiletoedittarget = preg_replace('/\.sql$/', '.key.sql', $pathoffiletoedittarget);
381 $pathoffiletoedittarget = preg_replace('/\.sql.new$/', '.key.sql.new', $pathoffiletoedittarget);
382
383 $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
384
385 $i = 0;
386 $texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n";
387 if (count($object->fields)) {
388 foreach ($object->fields as $key => $val) {
389 $i++;
390 if (!empty($val['index'])) {
391 $texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD INDEX idx_".strtolower($module).'_'.strtolower($objectname)."_".$key." (".$key.");";
392 $texttoinsert .= "\n";
393 }
394 if (!empty($val['foreignkey'])) {
395 $tmp = explode('.', $val['foreignkey']);
396 if (!empty($tmp[0]) && !empty($tmp[1])) {
397 $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].");";
398 $texttoinsert .= "\n";
399 }
400 }
401 }
402 }
403 $texttoinsert .= '-- END MODULEBUILDER INDEXES';
404
405 $contentsql = preg_replace('/-- BEGIN MODULEBUILDER INDEXES.*END MODULEBUILDER INDEXES/ims', $texttoinsert, $contentsql);
406
407 dol_mkdir(dirname($pathoffiletoedittarget));
408
409 $result2 = file_put_contents($pathoffiletoedittarget, $contentsql);
410 if ($result2) {
411 dolChmod($pathoffiletoedittarget, $newmask);
412 } else {
413 $error++;
414 setEventMessages($langs->trans("ErrorFailToCreateFile", $pathoffiletoedittarget), null, 'errors');
415 }
416
417 return $error ? -1 : 1;
418}
419
427{
428 $objects = array();
429 $listofobject = dol_dir_list($destdir.'/class', 'files', 0, '\.class\.php$');
430 foreach ($listofobject as $fileobj) {
431 if (preg_match('/^api_/', $fileobj['name'])) {
432 continue;
433 }
434 if (preg_match('/^actions_/', $fileobj['name'])) {
435 continue;
436 }
437
438 $tmpcontent = file_get_contents($fileobj['fullname']);
439 $reg = array();
440 if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) {
441 $objectnameloop = $reg[1];
442 $objects[$fileobj['fullname']] = $objectnameloop;
443 }
444 }
445 if (count($objects)>0) {
446 return $objects;
447 }
448
449 return -1;
450}
451
458function deletePerms($file)
459{
460 $start = "/* BEGIN MODULEBUILDER PERMISSIONS */";
461 $end = "/* END MODULEBUILDER PERMISSIONS */";
462 $i = 1;
463 $array = array();
464 $lines = file($file);
465 // Search for start and end lines
466 foreach ($lines as $i => $line) {
467 if (strpos($line, $start) !== false) {
468 $start_line = $i + 1;
469
470 // Copy lines until the end on array
471 while (($line = $lines[++$i]) !== false) {
472 if (strpos($line, $end) !== false) {
473 $end_line = $i + 1;
474 break;
475 }
476 $array[] = $line;
477 }
478 break;
479 }
480 }
481 $allContent = implode("", $array);
482 dolReplaceInFile($file, array($allContent => ''));
483}
484
491function compareFirstValue($a, $b)
492{
493 return strcmp($a[0], $b[0]);
494}
506function reWriteAllPermissions($file, $permissions, $key, $right, $objectname, $module, $action)
507{
508 $error = 0;
509 $rights = array();
510 if ($action == 0) {
511 // delete right from permissions array
512 array_splice($permissions, array_search($permissions[$key], $permissions), 1);
513 } elseif ($action == 1) {
514 array_push($permissions, $right);
515 } elseif ($action == 2 && !empty($right)) {
516 // update right from permissions array
517 array_splice($permissions, array_search($permissions[$key], $permissions), 1, $right);
518 } elseif ($action == -1 && !empty($objectname)) {
519 // when delete object
520 $key = null;
521 $right = null;
522 foreach ($permissions as $perms) {
523 if ($perms[4] === strtolower($objectname)) {
524 array_splice($permissions, array_search($perms, $permissions), 1);
525 }
526 }
527 } elseif ($action == -2 && !empty($objectname) && !empty($module)) {
528 $key= null;
529 $right = null;
530 $objectOfRights = array();
531 //check if object already declared in rights file
532 foreach ($permissions as $right) {
533 $objectOfRights[]= $right[4];
534 }
535 if (in_array(strtolower($objectname), $objectOfRights)) {
536 $error++;
537 } else {
538 $permsToadd = array();
539 $perms = array(
540 'read' => 'Read '.$objectname.' object of '.ucfirst($module),
541 'write' => 'Create/Update '.$objectname.' object of '.ucfirst($module),
542 'delete' => 'Delete '.$objectname.' object of '.ucfirst($module)
543 );
544 $i = 0;
545 foreach ($perms as $index => $value) {
546 $permsToadd[$i][0] = '';
547 $permsToadd[$i][1] = $value;
548 $permsToadd[$i][4] = strtolower($objectname);
549 $permsToadd[$i][5] = $index;
550 array_push($permissions, $permsToadd[$i]);
551 $i++;
552 }
553 }
554 } else {
555 $error++;
556 }
557 if (!$error) {
558 // prepare permissions array
559 $count_perms = count($permissions);
560 for ($i = 0;$i<$count_perms;$i++) {
561 $permissions[$i][0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', \$r + 1)";
562 $permissions[$i][1] = "\$this->rights[\$r][1] = '".$permissions[$i][1]."'";
563 $permissions[$i][4] = "\$this->rights[\$r][4] = '".$permissions[$i][4]."'";
564 $permissions[$i][5] = "\$this->rights[\$r][5] = '".$permissions[$i][5]."';\n\t\t";
565 }
566 // for group permissions by object
567 $perms_grouped = array();
568 foreach ($permissions as $perms) {
569 $object = $perms[4];
570 if (!isset($perms_grouped[$object])) {
571 $perms_grouped[$object] = [];
572 }
573 $perms_grouped[$object][] = $perms;
574 }
575 //$perms_grouped = array_values($perms_grouped);
576 $permissions = $perms_grouped;
577
578
579 // parcourir les objets
580 $o=0;
581 foreach ($permissions as &$object) {
582 // récupérer la permission de l'objet
583 $p = 1;
584 foreach ($object as &$obj) {
585 if (str_contains($obj[5], 'read')) {
586 $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + 0 + 1)";
587 } elseif (str_contains($obj[5], 'write')) {
588 $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + 1 + 1)";
589 } elseif (str_contains($obj[5], 'delete')) {
590 $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + 2 + 1)";
591 } else {
592 $obj[0] = "\$this->rights[\$r][0] = \$this->numero . sprintf('%02d', (".$o." * 10) + ".$p." + 1)";
593 $p++;
594 }
595 }
596 usort($object, 'compareFirstValue');
597 $o++;
598 }
599
600 //convert to string
601 foreach ($permissions as $perms) {
602 foreach ($perms as $per) {
603 $rights[] = implode(";\n\t\t", $per);
604 $rights[] = "\$r++;\n\t\t";
605 }
606 }
607 $rights_str = implode("", $rights);
608 // delete all permission from file
609 deletePerms($file);
610 // rewrite all permission again
611 dolReplaceInFile($file, array('/* BEGIN MODULEBUILDER PERMISSIONS */' => '/* BEGIN MODULEBUILDER PERMISSIONS */'."\n\t\t".$rights_str));
612 return 1;
613 } else {
614 return -1;
615 }
616}
617
625function writePropsInAsciiDoc($file, $objectname, $destfile)
626{
627
628 // stock all properties in array
629 $attributesUnique = array ('label', 'type', 'arrayofkeyval', 'notnull', 'default', 'index', 'foreignkey', 'position', 'enabled', 'visible', 'noteditable', 'alwayseditable', 'searchall', 'isameasure', 'css','cssview','csslist', 'help', 'showoncombobox', 'validate','comment','picto' );
630
631 $start = "public \$fields=array(";
632 $end = ");";
633 $i = 1;
634 $keys = array();
635 $lines = file($file);
636 // Search for start and end lines
637 foreach ($lines as $i => $line) {
638 if (strpos($line, $start) !== false) {
639 // Copy lines until the end on array
640 while (($line = $lines[++$i]) !== false) {
641 if (strpos($line, $end) !== false) {
642 break;
643 }
644 $keys[] = $line;
645 }
646 break;
647 }
648 }
649 // write the begin of table with specifics options
650 $table = "== DATA SPECIFICATIONS\n";
651 $table .= "=== Table of fields with properties for object *$objectname* : \n";
652 $table .= "[options='header',grid=rows,frame=topbot,width=100%,caption=Organisation]\n";
653 $table .= "|===\n";
654 $table .= "|code";
655 // write all properties in the header of the table
656 foreach ($attributesUnique as $attUnique) {
657 $table .= "|".$attUnique;
658 }
659 $table .="\n";
660 foreach ($keys as $string) {
661 $string = trim($string, "'");
662 $string = rtrim($string, ",");
663 $array = eval("return [$string];");
664
665 // check if is array after cleaning string
666 if (!is_array($array)) {
667 return -1;
668 }
669
670 $field = array_keys($array);
671 $values = array_values($array)[0];
672
673 // check each field has all properties and add it if missed
674 foreach ($attributesUnique as $attUnique) {
675 if (!array_key_exists($attUnique, $values)) {
676 $values[$attUnique] = '';
677 }
678 }
679
680 $table .= "|*" . $field[0] . "*|";
681 $table .= implode("|", $values) . "\n";
682 }
683 // end table
684 $table .= "|===\n";
685 $table .= "__ end table for object $objectname\n";
686 //write in file
687 $writeInFile = dolReplaceInFile($destfile, array('== DATA SPECIFICATIONS' => $table));
688 if ($writeInFile<0) {
689 return -1;
690 }
691 return 1;
692}
693
700function deletePropsFromDoc($file, $objectname)
701{
702
703 $start = "== Table of fields and their properties for object *".ucfirst($objectname)."* : ";
704 $end = "__ end table for object ".ucfirst($objectname);
705 $str = file_get_contents($file);
706 $search = '/' . preg_quote($start, '/') . '(.*?)' . preg_quote($end, '/') . '/s';
707 $new_contents = preg_replace($search, '', $str);
708 file_put_contents($file, $new_contents);
709}
710
718function getFromFile($file, $start, $end)
719{
720 $i = 1;
721 $keys = array();
722 $lines = file($file);
723 // Search for start and end lines
724 foreach ($lines as $i => $line) {
725 if (strpos($line, $start) !== false) {
726 // Copy lines until the end on array
727 while (($line = $lines[++$i]) !== false) {
728 if (strpos($line, $end) !== false) {
729 break;
730 }
731 $keys[] = $line;
732 }
733 break;
734 }
735 }
736 $content = implode("", $keys);
737 return $content;
738}
739
746function writePermsInAsciiDoc($file, $destfile)
747{
748 global $langs;
749 //search and get all permssion in stirng
750 $start = '/* BEGIN MODULEBUILDER PERMISSIONS */';
751 $end = '/* END MODULEBUILDER PERMISSIONS */';
752 $content = getFromFile($file, $start, $end);
753 if (empty($content)) {
754 return -1;
755 }
756 //prepare table
757 $string = "[options='header',grid=rows,width=60%,caption=Organisation]\n";
758 $string .= "|===\n";
759 // header for table
760 $header = array($langs->trans('Objects'),$langs->trans('Permission'));
761 foreach ($header as $h) {
762 $string .= "|".$h;
763 }
764 $string .= "\n";
765 //content table
766 $array = explode(";", $content);
767 $permissions = array_filter($array);
768 // delete occurrences "$r++" and ID
769 $permissions = str_replace('$r++', 1, $permissions);
770
771 $permsN = array();
772 foreach ($permissions as $i => $element) {
773 if ($element == 1) {
774 unset($permissions[$i]);
775 }
776 if (str_contains($element, '$this->numero')) {
777 unset($permissions[$i]);
778 }
779 if (str_contains($element, '$this->rights[$r][5]')) {
780 unset($permissions[$i]);
781 }
782 }
783 // cleaning the string on each element
784 foreach ($permissions as $key => $element) {
785 $element = str_replace(" '", '', $element);
786 $element = trim($element, "'");
787 $permsN[] = substr($element, strpos($element, "=")+1);
788 }
789 array_pop($permsN);
790
791 // Group permissions by Object and add it to string
792 $final_array = [];
793 $index = 0;
794 while ($index < count($permsN)) {
795 $temp_array = [$permsN[$index], $permsN[$index + 1]];
796 $final_array[] = $temp_array;
797 $index += 2;
798 }
799
800 $result = array();
801 foreach ($final_array as $subarray) {
802 // found object
803 $key = $subarray[1];
804 // add sub array to object
805 $result[$key][] = $subarray;
806 }
807 foreach ($result as $i => $pems) {
808 $string .= "|*".$i."*|";
809 foreach ($pems as $tab) {
810 $string .= $tab[0]." , ";
811 }
812 $string .= "\n";
813 }
814 // end table
815 $string .= "\n|===\n";
816 $write = dolReplaceInFile($destfile, array('__DATA_PERMISSIONS__'=> $string));
817 if ($write<0) {
818 return -1;
819 }
820 return 1;
821}
822
830function addObjectsToApiFile($file, $objects, $modulename)
831{
832 if (!file_exists($file)) {
833 return -1;
834 }
835 $content = file($file);
836 $includeClass = "dol_include_once('/mymodule/class/myobject.class.php');";
837 $props = "public \$myobject;";
838 $varcomented = "@var MyObject \$myobject {@type MyObject}";
839 $constructObj = "\$this->myobject = new MyObject(\$this->db);";
840
841 // add properties and declare them in consturctor
842 foreach ($content as $lineNumber => &$lineContent) {
843 if (strpos($lineContent, $varcomented) !== false) {
844 $lineContent = '';
845 foreach ($objects as $object) {
846 $lineContent .= "\t * @var ".$object." \$".strtolower($object)." {@type ".$object."}". PHP_EOL;
847 }
848 //var_dump($lineContent);exit;
849 }
850 if (strpos($lineContent, $props) !== false) {
851 $lineContent = '';
852 foreach ($objects as $object) {
853 $lineContent .= "\tpublic \$".strtolower($object).";". PHP_EOL;
854 }
855 }
856 if (strpos($lineContent, $constructObj) !== false) {
857 $lineContent = '';
858 foreach ($objects as $object) {
859 $lineContent .= "\t\t\$this->".strtolower($object)." = new ".$object."(\$this->db);". PHP_EOL;
860 }
861 }
862 if (strpos($lineContent, $includeClass) !== false) {
863 $lineContent = '';
864 foreach ($objects as $object) {
865 $lineContent .= "dol_include_once('/".strtolower($modulename)."/class/".strtolower($object).".class.php');". PHP_EOL;
866 }
867 }
868 }
869 $allContent = implode("", $content);
870 file_put_contents($file, $allContent);
871
872 //add methods for each object
873 $allContent = getFromFile($file, '/*begin methods CRUD*/', '/*end methods CRUD*/');
874 foreach ($objects as $object) {
875 $contentReplaced =str_replace(["myobject","MyObject"], [strtolower($object),$object], $allContent);
876 dolReplaceInFile($file, array('/*end methods CRUD*/' => '/*CRUD FOR '.strtoupper($object).'*/'."\n".$contentReplaced."\n\t".'/*END CRUD FOR '.strtoupper($object).'*/'."\n\t".'/*end methods CRUD*/'));
877 }
878 dolReplaceInFile($file, array($allContent => '','MyModule' => ucfirst($modulename)));
879 return 1;
880}
881
889function removeObjectFromApiFile($file, $objectname, $modulename)
890{
891 $begin = '/*CRUD FOR '.strtoupper($objectname).'*/';
892 $end = '/*END CRUD FOR '.strtoupper($objectname).'*/';
893 $includeClass = "dol_include_once('/".strtolower($modulename)."/class/".strtolower($objectname).".class.php');";
894 $varcomentedDel = "\t * @var ".$objectname." \$".strtolower($objectname)." {@type ".$objectname."}";
895 $propsDel = "\tpublic \$".strtolower($objectname).";";
896 $constructObjDel = "\t\t\$this->".strtolower($objectname)." = new ".$objectname."(\$this->db);";
897
898 if (!file_exists($file)) {
899 return -1;
900 }
901 $content = file($file);
902 // for delete property and the initialization from the construct
903 foreach ($content as $lineNumber => &$lineContent) {
904 if (strpos($lineContent, $includeClass) !== false) {
905 $lineContent = '';
906 }
907 if (strpos($lineContent, $varcomentedDel) !== false) {
908 $lineContent = '';
909 }
910 if (strpos($lineContent, $propsDel) !== false) {
911 $lineContent = '';
912 }
913 if (strpos($lineContent, $constructObjDel) !== false) {
914 $lineContent = '';
915 }
916 }
917 $allContent = implode("", $content);
918 file_put_contents($file, $allContent);
919 // for delete methods of object
920 $allContent = getFromFile($file, $begin, $end);
921 $check = dolReplaceInFile($file, array($allContent => ''));
922 if ($check) {
923 dolReplaceInFile($file, array($begin => '', $end => ''));
924 }
925 return 1;
926}
927
928
937function reWriteAllMenus($file, $menus, $menuWantTo, $key, $action)
938{
939 $errors =0;
940 $counter = 0;
941 if (!file_exists($file)) {
942 return -1;
943 }
944 if ($action == 0 && !empty($key)) {
945 // delete menu manuelly
946 array_splice($menus, array_search($menus[$key], $menus), 1);
947 } elseif ($action == 1) {
948 // add menu manualy
949 array_push($menus, $menuWantTo);
950 } elseif ($action == 2 && !empty($key) && !empty($menuWantTo)) {
951 // update right from permissions array
952
953 // check if the values already exists
954 foreach ($menus as $index => $menu) {
955 if ($index !== $key) {
956 if ($menu['type'] === $menuWantTo['type']) {
957 if (strcasecmp(str_replace(' ', '', $menu['titre']), str_replace(' ', '', $menuWantTo['titre'])) === 0) {
958 $counter++;
959 }
960 if (strcasecmp(str_replace(' ', '', $menu['url']), str_replace(' ', '', $menuWantTo['url'])) === 0) {
961 $counter++;
962 }
963 }
964 }
965 }
966 if (!$counter) {
967 $menus[$key] = $menuWantTo;
968 } else {
969 $errors++;
970 }
971 } elseif ($action == -1 && !empty($menuWantTo)) {
972 // delete menus when delete Object
973 foreach ($menus as $index => $menu) {
974 if ((strpos(strtolower($menu['fk_menu']), strtolower($menuWantTo)) !== false) || (strpos(strtolower($menu['leftmenu']), strtolower($menuWantTo)) !== false)) {
975 array_splice($menus, array_search($menu, $menus), 1);
976 }
977 }
978 } else {
979 $errors++;
980 }
981 if (!$errors) {
982 // delete All LEFT Menus
983 $beginMenu = '/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT */';
984 $endMenu = '/* END MODULEBUILDER LEFTMENU MYOBJECT */';
985 $allMenus = getFromFile($file, $beginMenu, $endMenu);
986 dolReplaceInFile($file, array($allMenus => ''));
987
988 //prepare each menu and stock them in string
989 $str_menu = "";
990 foreach ($menus as $index =>$menu) {
991 $menu['position'] = "1000 + \$r";
992 if ($menu['type'] === 'left') {
993 $start = "\t\t".'/* LEFTMENU '.strtoupper($menu['titre']).' */';
994 $end = "\t\t".'/* END LEFTMENU '.strtoupper($menu['titre']).' */';
995 $val_actuel = $menu;
996 $next_val = $menus[$index + 1];
997 $str_menu .= $start."\n";
998 $str_menu.= "\t\t\$this->menu[\$r++]=array(\n";
999 $str_menu.= "\t\t\t 'fk_menu' =>'".$menu['fk_menu']."',\n";
1000 $str_menu.= "\t\t\t 'type' =>'".$menu['type']."',\n";
1001 $str_menu.= "\t\t\t 'titre' =>'".$menu['titre']."',\n";
1002 $str_menu.= "\t\t\t 'mainmenu' =>'".$menu['mainmenu']."',\n";
1003 $str_menu.= "\t\t\t 'leftmenu' =>'".$menu['leftmenu']."',\n";
1004 $str_menu.= "\t\t\t 'url' =>'".$menu['url']."',\n";
1005 $str_menu.= "\t\t\t 'langs' =>'".$menu['langs']."',\n";
1006 $str_menu.= "\t\t\t 'position' =>".$menu['position'].",\n";
1007 $str_menu.= "\t\t\t 'enabled' =>'".$menu['enabled']."',\n";
1008 $str_menu.= "\t\t\t 'perms' =>'".$menu['perms']."',\n";
1009 $str_menu.= "\t\t\t 'target' =>'".$menu['target']."',\n";
1010 $str_menu.= "\t\t\t 'user' =>".$menu['user'].",\n";
1011 $str_menu.= "\t\t);\n";
1012
1013 if ($val_actuel['leftmenu'] !== $next_val['leftmenu']) {
1014 $str_menu .= $end."\n";
1015 }
1016 }
1017 }
1018
1019 dolReplaceInFile($file, array($beginMenu => $beginMenu."\n".$str_menu."\n"));
1020 return 1;
1021 }return -1;
1022}
dol_is_file($pathoffile)
Return if path is a file.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_dir_list($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:62
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
deletePropsFromDoc($file, $objectname)
Delete property from documentation if we delete object.
writePermsInAsciiDoc($file, $destfile)
Write all permissions of each object in AsciiDoc format.
reWriteAllMenus($file, $menus, $menuWantTo, $key, $action)
rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir='', $object=null, $moduletype='external')
Save data into a memory area shared by all users, all sessions on server.
addObjectsToApiFile($file, $objects, $modulename)
Add Object in ModuleApi File.
dolGetListOfObjectClasses($destdir)
Get list of existing objects from directory.
deletePerms($file)
Delete all permissions.
writePropsInAsciiDoc($file, $objectname, $destfile)
Write all properties of the object in AsciiDoc format.
compareFirstValue($a, $b)
Compare two value.
removeObjectFromApiFile($file, $objectname, $modulename)
Remove Object variables and methods from API_Module File.
rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir='', $addfieldentry=array(), $delfieldentry='')
Regenerate files .class.php.
getFromFile($file, $start, $end)
Search a string and return all lines needed from file.
reWriteAllPermissions($file, $permissions, $key, $right, $objectname, $module, $action)
Rewriting all permissions after any actions.