Passed
Branch develop (a7390e)
by
unknown
25:38
created

modulebuilder.lib.php ➔ rebuildObjectSql()   F

Complexity

Conditions 32
Paths 1545

Size

Total Lines 133

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 32
nc 1545
nop 6
dl 0
loc 133
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2009-2010 Laurent Destailleur  <[email protected]>
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 <http://www.gnu.org/licenses/>.
16
 * or see http://www.gnu.org/
17
 */
18
19
/**
20
 *  \file		htdocs/core/lib/memory.lib.php
21
 *  \brief		Set of function for memory/cache management
22
 */
23
24
25
26
27
/**
28
 * 	Regenerate files .class.php
29
 *
30
 *  @param	string      $destdir		Directory
31
 * 	@param	string		$module			Module name
32
 *  @param	string      $objectname		Name of object
33
 * 	@param	string		$newmask		New mask
34
 *  @param	string      $readdir		Directory source (use $destdir when not defined)
35
 *  @param	string		$addfieldentry	Array of the field entry to add array('key'=>,'type'=>,''label'=>,'visible'=>,'enabled'=>,'position'=>,'notnull'=>','index'=>,'searchall'=>,'comment'=>,'help'=>,'isameasure')
36
 *  @param	string		$delfieldentry	Id of field to remove
37
 * 	@return	int|object					<=0 if KO, Object if OK
38
 *  @see rebuildObjectSql()
39
 */
40
function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = '', $addfieldentry = array(), $delfieldentry = '')
41
{
42
    global $db, $langs;
43
44
    if (empty($objectname)) return -1;
45
    if (empty($readdir)) $readdir=$destdir;
46
47
    if (! empty($addfieldentry['arrayofkeyval']) && ! is_array($addfieldentry['arrayofkeyval']))
48
    {
49
    	dol_print_error('', 'Bad parameter addfieldentry with a property arrayofkeyval defined but that is not an array.');
50
    	return -1;
51
    }
52
53
    // Check parameters
54
    if (count($addfieldentry) > 0)
55
    {
56
        if (empty($addfieldentry['name']))
57
    	{
58
    		setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Name")), null, 'errors');
59
    		return -2;
60
    	}
61
        if (empty($addfieldentry['label']))
62
    	{
63
    		setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors');
64
    		return -2;
65
    	}
66
67
    	if (! preg_match('/^(price|boolean|sellist|integer|date|timestamp|varchar|double|text|html)/', $addfieldentry['type']))
68
69
    	{
70
    		setEventMessages($langs->trans('BadFormatForType', $objectname), null, 'errors');
71
    		return -2;
72
    	}
73
    }
74
75
    $pathoffiletoeditsrc=$readdir.'/class/'.strtolower($objectname).'.class.php';
76
    $pathoffiletoedittarget=$destdir.'/class/'.strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : '');
77
    if (! dol_is_file($pathoffiletoeditsrc))
78
    {
79
    	$langs->load("errors");
80
        setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
81
        return -3;
82
    }
83
84
    //$pathoffiletoedittmp=$destdir.'/class/'.strtolower($objectname).'.class.php.tmp';
85
    //dol_delete_file($pathoffiletoedittmp, 0, 1, 1);
86
87
    try
88
    {
89
        include_once $pathoffiletoeditsrc;
90
        if (class_exists($objectname)) $object=new $objectname($db);
91
        else return -4;
92
93
        // Backup old file
94
        dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
95
96
        // Edit class files
97
        $contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
98
99
	    // Update ->fields (add or remove entries)
100
        if (count($object->fields))
101
        {
102
        	if (is_array($addfieldentry) && count($addfieldentry))
103
        	{
104
				$name=$addfieldentry['name'];
105
        		unset($addfieldentry['name']);
106
107
        		$object->fields[$name]=$addfieldentry;
108
        	}
109
        	if (! empty($delfieldentry))
110
        	{
111
        		$name=$delfieldentry;
112
        		unset($object->fields[$name]);
113
        	}
114
        }
115
116
        dol_sort_array($object->fields, 'position');
117
118
        $i=0;
119
        $texttoinsert = '// BEGIN MODULEBUILDER PROPERTIES'."\n";
120
        $texttoinsert.= "\t".'/**'."\n";
121
        $texttoinsert.= "\t".' * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.'."\n";
122
        $texttoinsert.= "\t".' */'."\n";
123
        $texttoinsert.= "\t".'public $fields=array('."\n";
124
125
        if (count($object->fields))
126
        {
127
128
            foreach($object->fields as $key => $val)
129
            {
130
                $i++;
131
                $texttoinsert.= "\t\t'".$key."' => array('type'=>'".$val['type']."', 'label'=>'".$val['label']."',";
132
                $texttoinsert.= " 'enabled'=>".($val['enabled']!=''?$val['enabled']:1).",";
133
                $texttoinsert.= " 'visible'=>".($val['visible']!=''?$val['visible']:-1).",";
134
                $texttoinsert.= " 'position'=>".($val['position']!=''?$val['position']:50).",";
135
                $texttoinsert.= " 'notnull'=>".($val['notnull']!=''?$val['notnull']:-1).",";
136
                if ($val['default'])        $texttoinsert.= " 'default'=>'".$val['default']."',";
137
                if ($val['index'])          $texttoinsert.= " 'index'=>".$val['index'].",";
138
                if ($val['searchall'])      $texttoinsert.= " 'searchall'=>".$val['searchall'].",";
139
                if ($val['isameasure'])     $texttoinsert.= " 'isameasure'=>'".$val['isameasure']."',";
140
                if ($val['foreignkey'])     $texttoinsert.= " 'foreignkey'=>'".$val['foreignkey']."',";
141
                if ($val['help'])           $texttoinsert.= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\",";
142
                if ($val['comment'])        $texttoinsert.= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\",";
143
                if ($val['showoncombobox']) $texttoinsert.= " 'showoncombobox'=>'".$val['showoncombobox']."',";
144
                if ($val['arrayofkeyval'])
145
                {
146
                	$texttoinsert.= " 'arrayofkeyval'=>array(";
147
                	$i=0;
148
                	foreach($val['arrayofkeyval'] as $key2 => $val2)
149
                	{
150
                		if ($i) $texttoinsert.=", ";
151
                		$texttoinsert.="'".$key2."'=>'".$val2."'";
152
                		$i++;
153
                	}
154
                	$texttoinsert.= ")";
155
                }
156
                $texttoinsert.= "),\n";
157
            }
158
        }
159
160
        $texttoinsert.= "\t".');'."\n";
161
		//print ($texttoinsert);exit;
162
163
        if (count($object->fields))
164
        {
165
        	$typetotypephp=array('integer'=>'integer', 'varchar'=>'string');
166
167
        	foreach($object->fields as $key => $val)
168
            {
169
                $i++;
170
                //$typephp=$typetotypephp[$val['type']];
171
                $texttoinsert.= "\t".'public $'.$key.";";
172
                //if ($key == 'rowid')  $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
173
                //if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
174
                //$texttoinsert.= ($val['notnull']?' NOT NULL':'');
175
                //if ($i < count($object->fields)) $texttoinsert.=";";
176
                $texttoinsert.= "\n";
177
            }
178
        }
179
180
        $texttoinsert.= "\t".'// END MODULEBUILDER PROPERTIES';
181
182
        //print($texttoinsert);exit;
183
184
        $contentclass = preg_replace('/\/\/ BEGIN MODULEBUILDER PROPERTIES.*END MODULEBUILDER PROPERTIES/ims', $texttoinsert, $contentclass);
185
186
        dol_mkdir(dirname($pathoffiletoedittarget));
187
188
        //file_put_contents($pathoffiletoedittmp, $contentclass);
189
        file_put_contents(dol_osencode($pathoffiletoedittarget), $contentclass);
190
        @chmod($pathoffiletoedittarget, octdec($newmask));
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

190
        /** @scrutinizer ignore-unhandled */ @chmod($pathoffiletoedittarget, octdec($newmask));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
191
192
        return $object;
193
    }
194
    catch(Exception $e)
195
    {
196
        print $e->getMessage();
197
        return -5;
198
    }
199
}
200
201
/**
202
 * 	Save data into a memory area shared by all users, all sessions on server
203
 *
204
 *  @param	string      $destdir		Directory
205
 * 	@param	string		$module			Module name
206
 *  @param	string      $objectname		Name of object
207
 * 	@param	string		$newmask		New mask
208
 *  @param	string      $readdir		Directory source (use $destdir when not defined)
209
 *  @param	Object		$object			If object was already loaded/known, it is pass to avaoid another include and new.
210
 * 	@return	int							<=0 if KO, >0 if OK
211
 *  @see rebuildObjectClass()
212
 */
213
function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = '', $object = null)
214
{
215
    global $db, $langs;
216
217
    $error = 0;
218
219
    if (empty($objectname)) return -1;
220
    if (empty($readdir)) $readdir=$destdir;
221
222
    $pathoffiletoclasssrc=$readdir.'/class/'.strtolower($objectname).'.class.php';
223
224
    // Edit .sql file
225
    $pathoffiletoeditsrc=$readdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql';
226
    $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql'.($readdir != $destdir ? '.new' : '');
227
	if (! dol_is_file($pathoffiletoeditsrc))
228
    {
229
    	$langs->load("errors");
230
    	setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
231
    	return -1;
232
    }
233
234
    // Load object from myobject.class.php
235
    try
236
    {
237
    	if (! is_object($object))
238
    	{
239
    		include_once $pathoffiletoclasssrc;
240
        	if (class_exists($objectname)) $object=new $objectname($db);
241
        	else return -1;
242
    	}
243
    }
244
    catch(Exception $e)
245
    {
246
        print $e->getMessage();
247
    }
248
249
    // Backup old file
250
    dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
251
252
    $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
253
254
    $i=0;
255
    $texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n";
256
    if (count($object->fields))
257
    {
258
        foreach($object->fields as $key => $val)
259
        {
260
            $i++;
261
262
            $type = $val['type'];
263
            $type = preg_replace('/:.*$/', '', $type);		// For case type = 'integer:Societe:societe/class/societe.class.php'
264
265
            if ($type == 'html') $type = 'text';            // html modulebuilder type is a text type in database
266
            elseif ($type == 'price') $type = 'double';            // html modulebuilder type is a text type in database
267
            elseif ($type == 'link' || $type == 'sellist') $type = 'integer';
268
            $texttoinsert.= "\t".$key." ".$type;
269
            if ($key == 'rowid')  $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
270
            if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
271
            else
272
            {
273
            	if ($val['default'] != '')
274
            	{
275
            		if (preg_match('/^null$/i', $val['default'])) $texttoinsert.= " DEFAULT NULL";
276
            		elseif (preg_match('/varchar/', $type)) $texttoinsert.= " DEFAULT '".$db->escape($val['default'])."'";
277
            		else $texttoinsert.= (($val['default'] > 0)?' DEFAULT '.$val['default']:'');
278
            	}
279
            }
280
            $texttoinsert.= (($val['notnull'] > 0)?' NOT NULL':'');
281
            if ($i < count($object->fields)) $texttoinsert.=", ";
282
            $texttoinsert.= "\n";
283
        }
284
    }
285
    $texttoinsert.= "\t".'-- END MODULEBUILDER FIELDS';
286
287
    $contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql);
288
289
    $result = file_put_contents($pathoffiletoedittarget, $contentsql);
290
    if ($result)
291
    {
292
    	@chmod($pathoffiletoedittarget, octdec($newmask));
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

292
    	/** @scrutinizer ignore-unhandled */ @chmod($pathoffiletoedittarget, octdec($newmask));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
293
    }
294
    else
295
    {
296
    	$error++;
297
    }
298
299
    // Edit .key.sql file
300
    $pathoffiletoeditsrc=$destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.key.sql';
301
    $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.key.sql'.($readdir != $destdir ? '.new' : '');
302
303
    $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
304
305
    $i=0;
306
    $texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n";
307
    if (count($object->fields))
308
    {
309
        foreach($object->fields as $key => $val)
310
        {
311
            $i++;
312
            if (! empty($val['index']))
313
            {
314
                $texttoinsert.= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD INDEX idx_".strtolower($module).'_'.strtolower($objectname)."_".$key." (".$key.");";
315
                $texttoinsert.= "\n";
316
            }
317
            if (! empty($val['foreignkey']))
318
            {
319
            	$tmp=explode('.', $val['foreignkey']);
320
            	if (! empty($tmp[0]) && ! empty($tmp[1]))
321
            	{
322
            		$texttoinsert.= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD CONSTRAINT llx_".strtolower($module).'_'.strtolower($objectname)."_".$key." FOREIGN KEY (".$key.") REFERENCES ".$tmp[0]."(".$tmp[1].");";
323
            		$texttoinsert.= "\n";
324
            	}
325
            }
326
        }
327
    }
328
    $texttoinsert.= '-- END MODULEBUILDER INDEXES';
329
330
    $contentsql = preg_replace('/-- BEGIN MODULEBUILDER INDEXES.*END MODULEBUILDER INDEXES/ims', $texttoinsert, $contentsql);
331
332
    dol_mkdir(dirname($pathoffiletoedittarget));
333
334
    $result2 = file_put_contents($pathoffiletoedittarget, $contentsql);
335
    if ($result)
336
    {
337
    	@chmod($pathoffiletoedittarget, octdec($newmask));
338
    }
339
    else
340
    {
341
    	$error++;
342
    }
343
344
    return $error ? -1 : 1;
345
}
346