Completed
Branch develop (eec106)
by
unknown
20:48
created

Interfaces::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2005-2009 Laurent Destailleur  <[email protected]>
3
 * Copyright (C) 2006      Rodolphe Quiedeville <[email protected]>
4
 * Copyright (C) 2010      Regis Houssin        <[email protected]>
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 <http://www.gnu.org/licenses/>.
18
 */
19
20
/**
21
 *   \file		    htdocs/core/class/interfaces.class.php
22
 *   \ingroup		core
23
 *   \brief			Fichier de la classe de gestion des triggers
24
 */
25
26
require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php';
27
28
29
/**
30
 *   Class to manage triggers
31
 */
32
class Interfaces
33
{
34
    var $db;
35
	var $dir;				// Directory with all core and external triggers files
36
    var $errors	= array();	// Array for errors
37
38
    /**
39
     *	Constructor
40
     *
41
     *  @param		DoliDB		$db      Database handler
42
     */
43
    function __construct($db)
44
    {
45
        $this->db = $db;
46
    }
47
48
    /**
49
     *   Function called when a Dolibarr business event occurs
50
     *   This function call all qualified triggers.
51
     *
52
     *   @param		string		$action     Trigger event code
53
     *   @param     object		$object     Objet concerned. Some context information may also be provided into array property object->context.
54
     *   @param     User		$user       Objet user
55
     *   @param     Lang		$langs      Objet lang
56
     *   @param     Conf		$conf       Objet conf
57
     *   @return    int         			Nb of triggers ran if no error, -Nb of triggers with errors otherwise.
58
     */
59
    function run_triggers($action,$object,$user,$langs,$conf)
60
    {
61
        // Check parameters
62
        if (! is_object($object) || ! is_object($conf))	// Error
63
        {
64
        	$this->error='function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf);
65
            dol_syslog(get_class($this).'::run_triggers '.$this->error, LOG_ERR);
66
        	$this->errors[]=$this->error;
67
            return -1;
68
        }
69
        if (! is_object($langs))	// Warning
70
        {
71
            dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
72
        }
73
        if (! is_object($user))	    // Warning
74
        {
75
            dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
76
            global $db;
77
            $user = new User($db);
78
        }
79
80
        $nbfile = $nbtotal = $nbok = $nbko = 0;
81
82
        $files = array();
83
        $modules = array();
84
        $orders = array();
85
		$i=0;
86
87
		$dirtriggers=array_merge(array('/core/triggers'),$conf->modules_parts['triggers']);
88
        foreach($dirtriggers as $reldir)
89
        {
90
            $dir=dol_buildpath($reldir,0);
91
            $newdir=dol_osencode($dir);
92
            //print "xx".$dir;exit;
93
94
            // Check if directory exists (we do not use dol_is_dir to avoir loading files.lib.php at each call)
95
            if (! is_dir($newdir)) continue;
96
97
            $handle=opendir($newdir);
98
            if (is_resource($handle))
99
            {
100
                while (($file = readdir($handle))!==false)
101
                {
102
                    if (is_readable($newdir."/".$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php$/i',$file,$reg))
103
                    {
104
						$part1=$reg[1];
105
						$part2=$reg[2];
106
						$part3=$reg[3];
107
108
                        $nbfile++;
109
110
                        // Check if trigger file is disabled by name
111
                        if (preg_match('/NORUN$/i',$file)) continue;
112
                        // Check if trigger file is for a particular module
113
                        $qualified=true;
114
                        if (strtolower($reg[2]) != 'all')
115
                        {
116
                            $module=preg_replace('/^mod/i','',$reg[2]);
117
                            $constparam='MAIN_MODULE_'.strtoupper($module);
118
                            if (empty($conf->global->$constparam)) $qualified=false;
119
                        }
120
121
                        if (! $qualified)
122
                        {
123
                            dol_syslog(get_class($this)."::run_triggers action=".$action." Triggers for file '".$file."' need module to be enabled", LOG_DEBUG);
124
                            continue;
125
                        }
126
127
                        $modName = "Interface".ucfirst($reg[3]);
128
                        //print "file=$file - modName=$modName\n";
129
                        if (in_array($modName,$modules))    // $modules = list of modName already loaded
130
                        {
131
                            $langs->load("errors");
132
                            dol_syslog(get_class($this)."::run_triggers action=".$action." ".$langs->trans("ErrorDuplicateTrigger", $newdir."/".$file, $fullpathfiles[$modName]), LOG_WARNING);
0 ignored issues
show
Bug introduced by
The variable $fullpathfiles does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
133
                            continue;
134
                        }
135
136
                        try {
137
                            //print 'Todo for '.$modName." : ".$newdir.'/'.$file."\n";
138
                            include_once $newdir.'/'.$file;
139
                            //print 'Done for '.$modName."\n";
140
                        }
141
                        catch(Exception $e)
142
                        {
143
                            dol_syslog('ko for '.$modName." ".$e->getMessage()."\n", LOG_ERR);
144
                        }
145
146
                        $modules[$i] = $modName;
147
                        $files[$i] = $file;
148
                        $fullpathfiles[$modName] = $newdir.'/'.$file;
149
                        $orders[$i] = $part1.'_'.$part2.'_'.$part3;   // Set sort criteria value
150
151
                        $i++;
152
                    }
153
                }
154
            }
155
        }
156
157
        asort($orders);
158
159
        // Loop on each trigger
160
        foreach ($orders as $key => $value)
161
        {
162
            $modName = $modules[$key];
163
            if (empty($modName)) continue;
164
165
            $objMod = new $modName($this->db);
166
            if ($objMod)
167
            {
168
            	$result=0;
169
170
				if (method_exists($objMod, 'runTrigger'))	// New method to implement
171
				{
172
	                dol_syslog(get_class($this)."::run_triggers action=".$action." Launch runTrigger for file '".$files[$key]."'", LOG_INFO);
173
	                $result=$objMod->runTrigger($action,$object,$user,$langs,$conf);
174
				}
175
				elseif (method_exists($objMod, 'run_trigger'))	// Deprecated method
176
				{
177
	                dol_syslog(get_class($this)."::run_triggers action=".$action." Launch run_trigger for file '".$files[$key]."'", LOG_INFO);
178
					$result=$objMod->run_trigger($action,$object,$user,$langs,$conf);
179
				}
180
				else
181
				{
182
	                dol_syslog(get_class($this)."::run_triggers action=".$action." A trigger was declared for class ".get_class($objMod)." but method runTrigger was not found", LOG_ERR);
183
				}
184
185
                if ($result > 0)
186
                {
187
                    // Action OK
188
                    $nbtotal++;
189
                    $nbok++;
190
                }
191
                if ($result == 0)
192
                {
193
                    // Aucune action faite
194
                    $nbtotal++;
195
                }
196
                if ($result < 0)
197
                {
198
                    // Action KO
199
                    //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($objMod->errors), LOG_ERR);
200
                    $nbtotal++;
201
                    $nbko++;
202
                    if (! empty($objMod->errors)) $this->errors=array_merge($this->errors,$objMod->errors);
203
                    else if (! empty($objMod->error))  $this->errors[]=$objMod->error;
204
                    //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($this->errors), LOG_ERR);
205
                }
206
            }
207
            else
208
			{
209
                dol_syslog(get_class($this)."::run_triggers action=".$action." Failed to instantiate trigger for file '".$files[$key]."'", LOG_ERR);
210
            }
211
        }
212
213
        if ($nbko)
214
        {
215
            dol_syslog(get_class($this)."::run_triggers action=".$action." Files found: ".$nbfile.", Files launched: ".$nbtotal.", Done: ".$nbok.", Failed: ".$nbko." - Nb of error string returned in this->errors = ".count($this->errors), LOG_ERR);
216
            return -$nbko;
217
        }
218
        else
219
        {
220
            //dol_syslog(get_class($this)."::run_triggers Files found: ".$nbfile.", Files launched: ".$nbtotal.", Done: ".$nbok.", Failed: ".$nbko, LOG_DEBUG);
221
            return $nbok;
222
        }
223
    }
224
225
    /**
226
     *  Return list of triggers. Function used by admin page htdoc/admin/triggers.
227
     *  List is sorted by trigger filename so by priority to run.
228
     *
229
     *	@param	array		$forcedirtriggers		null=All default directories. This parameter is used by modulebuilder module only.
230
     * 	@return	array								Array list of triggers
231
     */
232
    function getTriggersList($forcedirtriggers=null)
233
    {
234
        global $conf, $langs;
235
236
        $files = array();
237
        $fullpath = array();
238
        $relpath = array();
239
        $iscoreorexternal = array();
240
        $modules = array();
241
        $orders = array();
242
        $i = 0;
243
244
        $dirtriggers=array_merge(array('/core/triggers/'),$conf->modules_parts['triggers']);
245
        if (is_array($forcedirtriggers))
246
        {
247
        	$dirtriggers=$forcedirtriggers;
248
        }
249
250
        foreach($dirtriggers as $reldir)
251
        {
252
            $dir=dol_buildpath($reldir,0);
253
            $newdir=dol_osencode($dir);
254
255
            // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php at each call)
256
            if (! is_dir($newdir)) continue;
257
258
            $handle=opendir($newdir);
259
            if (is_resource($handle))
260
            {
261
                while (($file = readdir($handle))!==false)
262
                {
263
                    if (is_readable($newdir.'/'.$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/',$file,$reg))
264
                    {
265
                        if (preg_match('/\.back$/',$file)) continue;
266
267
						$part1=$reg[1];
268
						$part2=$reg[2];
269
						$part3=$reg[3];
270
271
                        $modName = 'Interface'.ucfirst($reg[3]);
272
                        //print "file=$file"; print "modName=$modName"; exit;
273
                        if (in_array($modName,$modules))
274
                        {
275
                            $langs->load("errors");
276
                            print '<div class="error">'.$langs->trans("Error").' : '.$langs->trans("ErrorDuplicateTrigger",$modName,"/htdocs/core/triggers/").'</div>';
277
                        }
278
                        else
279
                        {
280
                            include_once $newdir.'/'.$file;
281
                        }
282
283
                        $files[$i] = $file;
284
                        $fullpath[$i] = $dir.'/'.$file;
285
                        $relpath[$i] = preg_replace('/^\//','',$reldir).'/'.$file;
286
                        $iscoreorexternal[$i] = ($reldir == '/core/triggers/'?'internal':'external');
287
                        $modules[$i] = $modName;
288
                        $orders[$i] = $part1.'_'.$part2.'_'.$part3;   // Set sort criteria value
289
290
                        $i++;
291
                    }
292
                }
293
                closedir($handle);
294
            }
295
        }
296
297
        asort($orders);
298
299
        $triggers = array();
300
        $j = 0;
301
302
        // Loop on each trigger
303
        foreach ($orders as $key => $value)
304
        {
305
            $modName = $modules[$key];
306
            if (empty($modName)) continue;
307
308
            if (! class_exists($modName))
309
            {
310
				print 'Error: A trigger file was found but its class "'.$modName.'" was not found.'."<br>\n";
311
            	continue;
312
            }
313
314
            $objMod = new $modName($this->db);
315
316
            // Define disabledbyname and disabledbymodule
317
            $disabledbyname=0;
318
            $disabledbymodule=1;
319
            $module='';
320
321
            // Check if trigger file is disabled by name
322
            if (preg_match('/NORUN$/i',$files[$key])) $disabledbyname=1;
323
            // Check if trigger file is for a particular module
324
            if (preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/i',$files[$key],$reg))
325
            {
326
                $module=preg_replace('/^mod/i','',$reg[2]);
327
                $constparam='MAIN_MODULE_'.strtoupper($module);
328
                if (strtolower($reg[2]) == 'all') $disabledbymodule=0;
329
                else if (empty($conf->global->$constparam)) $disabledbymodule=2;
330
            }
331
332
			// We set info of modules
333
            $triggers[$j]['picto'] = $objMod->picto?img_object('',$objMod->picto):img_object('','generic');
334
            $triggers[$j]['file'] = $files[$key];
335
            $triggers[$j]['fullpath'] = $fullpath[$key];
336
            $triggers[$j]['relpath'] = $relpath[$key];
337
            $triggers[$j]['iscoreorexternal'] = $iscoreorexternal[$key];
338
            $triggers[$j]['version'] = $objMod->getVersion();
339
            $triggers[$j]['status'] = img_picto($langs->trans("Active"),'tick');
340
            if ($disabledbyname > 0 || $disabledbymodule > 1) $triggers[$j]['status'] = '';
341
342
            $text ='<b>'.$langs->trans("Description").':</b><br>';
343
            $text.=$objMod->getDesc().'<br>';
344
            $text.='<br><b>'.$langs->trans("Status").':</b><br>';
345
            if ($disabledbyname == 1)
346
            {
347
                $text.=$langs->trans("TriggerDisabledByName").'<br>';
348
                if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
349
            }
350
            else
351
            {
352
                if ($disabledbymodule == 0) $text.=$langs->trans("TriggerAlwaysActive").'<br>';
353
                if ($disabledbymodule == 1) $text.=$langs->trans("TriggerActiveAsModuleActive",$module).'<br>';
354
                if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
355
            }
356
357
            $triggers[$j]['info'] = $text;
358
            $j++;
359
        }
360
        return $triggers;
361
    }
362
363
}
364