Passed
Push — master ( d03ea5...4fd4ae )
by Patrick
02:40
created

Mib::update_oid_create()   F

Complexity

Conditions 14
Paths 1152

Size

Total Lines 61
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 40
c 0
b 0
f 0
nc 1152
nop 0
dl 0
loc 61
rs 2.1

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
3
namespace Trapdirector;
4
5
use Trapdirector\Logging;
6
use Trapdirector\Database;
7
use PDO;
8
use Exception;
9
use Icinga\Module\TrapDirector\Config\TrapModuleConfig;
10
11
class Mib
12
{
13
    
14
    protected $logging; //< logging class
15
    protected $trapsDB; //< Database class
16
    
17
    public $snmptranslate;
18
    public $snmptranslateDirs;
19
    
20
    private $dbOidAll; //< All oid in database;
21
    private $dbOidIndex; //< Index of oid in dbOidAll
22
    private $objectsAll; //< output lines of snmptranslate list
23
    private $trapObjectsIndex; //< array of traps objects (as OID)
24
    
25
    private $oidDesc=array(); //< $oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL
26
27
    // Timing vars for update
28
    private $timing=array();
29
    
30
    /**
31
     * Setup Mib Class
32
     * @param Logging $logClass : where to log
33
     * @param Database $dbClass : Database
34
     */
35
    function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
36
    {
37
        $this->logging=$logClass;
38
        $this->trapsDB=$dbClass;
39
        $this->snmptranslate=$snmptrans;
40
        $this->snmptranslateDirs=$snmptransdir;
41
42
    }
43
    
44
    /**
45
     * Update object in DB with object in dbOidIndex if name/mib/type has changed.
46
     * @return number : 0=unchanged, 1 = changed, 2=created
47
     */
48
    private function update_oid_update()
49
    {
50
        
51
        $db_conn=$this->trapsDB->db_connect_trap();
52
        
53
        if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
54
        { // newly created.
55
            return 0;
56
        }
57
        $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
58
        $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
59
        if ( $this->oidDesc['name'] != $dbOid['name'] ||
60
            $this->oidDesc['mib'] != $dbOid['mib'] ||
61
            $this->oidDesc['type'] !=$dbOid['type']
62
            )
63
        { // Do update
64
            $sql='UPDATE '.$this->trapsDB->dbPrefix.'mib_cache SET '.
65
                'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
66
                ', syntax = :syntax, type_enum = :type_enum, description = :description '.
67
                ' WHERE id= :id';
68
            $sqlQuery=$db_conn->prepare($sql);
69
            
70
            $sqlParam=array(
71
                ':name' => $this->oidDesc['name'],
72
                ':type' => $this->oidDesc['type'],
73
                ':mib' => $this->oidDesc['mib'],
74
                ':tc' =>  $this->oidDesc['textconv']??'null',
75
                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
76
                ':syntax' => $this->oidDesc['syntax']==null??'null',
77
                ':type_enum' => $this->oidDesc['type_enum']??'null',
78
                ':description' => $this->oidDesc['description']??'null',
79
                ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
80
            );
81
            
82
            if ($sqlQuery->execute($sqlParam) === false) {
83
                $this->logging->log('Error in query : ' . $sql,ERROR,'');
84
            }
85
            $this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
86
            return 1;
87
        }
88
        else
89
        {
90
            $this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
91
            return 0;
92
        }
93
    }
94
95
    /**
96
     * Create object in DB with object in dbOidIndex
97
     * @return number : 0=unchanged, 1 = changed, 2=created
98
     */
99
    private function update_oid_create()
100
    {
101
        // Insert data
102
        
103
        $db_conn=$this->trapsDB->db_connect_trap();
104
        $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache '.
105
            '(oid, name, type , mib, textual_convention, display_hint '.
106
            ', syntax, type_enum , description ) ' .
107
            'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
108
            ', :syntax, :type_enum, :description )';
109
        
110
        if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
111
        
112
        $sqlQuery=$db_conn->prepare($sql);
113
        
114
        $sqlParam=array(
115
            ':oid' => $this->oidDesc['oid'],
116
            ':name' => $this->oidDesc['name'],
117
            ':type' => $this->oidDesc['type'],
118
            ':mib' => $this->oidDesc['mib'],
119
            ':tc' =>  ($this->oidDesc['textconv']==null)?'null':$this->oidDesc['textconv'] ,
120
            ':display_hint' => ($this->oidDesc['dispHint']==null)?'null':$this->oidDesc['dispHint'] ,
121
            ':syntax' => ($this->oidDesc['syntax']==null)?'null':$this->oidDesc['syntax'],
122
            ':type_enum' => ($this->oidDesc['type_enum']==null)?'null':$this->oidDesc['type_enum'],
123
            ':description' => ($this->oidDesc['description']==null)?'null':$this->oidDesc['description']
124
        );
125
        
126
        if ($sqlQuery->execute($sqlParam) === false) {
127
            $this->logging->log('Error in query : ' . $sql,1,'');
128
        }
129
        
130
        switch ($this->trapsDB->trapDBType)
131
        {
132
            case 'pgsql':
133
                // Get last id to insert oid/values in secondary table
134
                if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
135
                    $this->logging->log('Error getting id - pgsql - ',1,'');
136
                }
137
                if (! isset($inserted_id_ret['id'])) {
138
                    $this->logging->log('Error getting id - pgsql - empty.',1,'');
139
                }
140
                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
141
                break;
142
            case 'mysql':
143
                // Get last id to insert oid/values in secondary table
144
                $sql='SELECT LAST_INSERT_ID();';
145
                if (($ret_code=$db_conn->query($sql)) === false) {
146
                    $this->logging->log('Erreur getting id - mysql - ',1,'');
147
                }
148
                
149
                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
150
                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
151
                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
152
                break;
153
            default:
154
                $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
155
        }
156
        
157
        // Set as newly created.
158
        $this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
159
        return 2;
160
    }
161
    
162
    /**
163
     * Update or add an OID to database uses $this->dbOidIndex for mem cache
164
     * and $this->oidDesc doe data
165
     * @return number : 0=unchanged, 1 = changed, 2=created
166
     */
167
    public function update_oid()
168
    {
169
        $db_conn=$this->trapsDB->db_connect_trap();
170
        // Quote description.
171
        $this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
172
        
173
        if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
174
        { // oid exists in db, so update
175
            return $this->update_oid_update();
176
        }
177
        // create new OID.
178
        return $this->update_oid_create();
179
180
    }
181
    
182
/**
183
 * get all objects for a trap.
184
 * @param integer $trapId
185
 * @return array : array of cached objects
186
 */    
187
    private function cache_db_objects($trapId)
188
    {
189
        $dbObjects=array(); // cache of objects for trap in db
190
        $db_conn=$this->trapsDB->db_connect_trap();
191
        // Get all objects
192
        $sql='SELECT * FROM '.$this->trapsDB->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
193
        $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
194
        if (($ret_code=$db_conn->query($sql)) === false) {
195
            $this->logging->log('No result in query : ' . $sql,1,'');
196
        }
197
        $dbObjectsRaw=$ret_code->fetchAll();
198
        
199
        foreach ($dbObjectsRaw as $val)
200
        {
201
            $dbObjects[$val['object_id']]=1;
202
        }
203
        return $dbObjects;
204
    }
205
206
/**
207
 * Get object details & mib , returns snmptranslate output
208
 * @param string $object : object name
209
 * @param string $trapmib : mib of trap
210
 * @return NULL|array : null if not found, or output of snmptranslate
211
 */
212
    private function get_object_details($object,$trapmib)
213
    {
214
        $match=$snmptrans=array();
215
        $retVal=0;
216
        $this->oidDesc['mib']=$trapmib;
217
        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
218
            ' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
219
        if ($retVal!=0)
220
        {
221
            // Maybe not trap mib, search with IR
222
            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
223
                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
224
            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
225
            { // Not found -> continue with warning
226
                $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
227
                return null;
228
            }
229
            $this->oidDesc['mib']=$match[1];
230
            
231
            // Do the snmptranslate again.
232
            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
233
                ' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
234
            if ($retVal!=0) {
235
                $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
236
                return null;
237
            }
238
            
239
        }
240
        return $snmptrans;
241
    }
242
243
/**
244
 * Parse snmptranslate output and set  $this->oidDesc with elements 
245
 * @param array $snmptrans : multi line output of snmptrans
246
 */
247
    private function parse_object($snmptrans)
248
    {
249
        $tmpdesc=''; // For multiline description
250
        $indesc=false; // true if currently inside multiline description
251
        $match=array();
252
        
253
        foreach ($snmptrans as $line)
254
        {
255
            if ($indesc===true)
256
            {
257
                $line=preg_replace('/[\t ]+/',' ',$line);
258
                if (preg_match('/(.*)"$/', $line,$match))
259
                {
260
                    $this->oidDesc['description'] = $tmpdesc . $match[1];
261
                    $indesc=false;
262
                }
263
                $tmpdesc.=$line;
264
                continue;
265
            }
266
            if (preg_match('/^\.[0-9\.]+$/', $line))
267
            {
268
                $this->oidDesc['oid']=$line;
269
                continue;
270
            }
271
            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
272
            {
273
                $this->oidDesc['syntax']=$match[1];
274
                $this->oidDesc['type_enum']=$match[2];
275
                continue;
276
            }
277
            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
278
            {
279
                $this->oidDesc['syntax']=$match[1];
280
                continue;
281
            }
282
            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
283
            {
284
                $this->oidDesc['dispHint']=$match[1];
285
                continue;
286
            }
287
            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
288
            {
289
                $this->oidDesc['description']=$match[1];
290
                continue;
291
            }
292
            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
293
            {
294
                $tmpdesc=$match[1];
295
                $indesc=true;
296
                continue;
297
            }
298
            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
299
            {
300
                $this->oidDesc['textconv']=$match[1];
301
                continue;
302
            }
303
        }
304
    }
305
306
    /**
307
     * create or update (with check_existing = true) objects of trap
308
     * @param string $trapOID : trap oid
309
     * @param string $trapmib : mib of trap
310
     * @param array $objects : array of objects name (without MIB)
311
     * @param bool $check_existing : check instead of create
312
     */
313
    public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
314
    {              
315
        $trapId = $this->dbOidIndex[$trapOID]['id']; // Get id of trap
316
        
317
        if ($check_existing === true)
318
        {
319
            $dbObjects=$this->cache_db_objects($trapId);
320
        }
321
        
322
        foreach ($objects as $object)
323
        {
324
            
325
            $this->reset_oidDesc();
326
            
327
            $snmptrans=$this->get_object_details($object, $trapmib); // Get object mib & details
1 ignored issue
show
Bug introduced by
Are you sure the assignment to $snmptrans is correct as $this->get_object_details($object, $trapmib) targeting Trapdirector\Mib::get_object_details() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
328
            if ($snmptrans === null) continue; // object not found
329
            
330
            $this->parse_object($snmptrans);
331
332
            $this->oidDesc['name'] = $object;
333
            
334
            $this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'],DEBUG );
335
336
            // Update
337
            $this->update_oid();
338
            
339
            if (isset($dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]))
340
            {   // if link exists, continue
341
                $dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]=2;
342
                continue;
343
            }
344
            if ($check_existing === true)
345
            {
346
                // TODO : check link trap - objects exists, mark them.
347
            }
348
            // Associate in object table
349
            $db_conn=$this->trapsDB->db_connect_trap();
350
            $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache_trap_object (trap_id,object_id) '.
351
                'values (:trap_id, :object_id)';
352
            $sqlQuery=$db_conn->prepare($sql);
353
            $sqlParam=array(
354
                ':trap_id' => $trapId,
355
                ':object_id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'],
356
            );
357
            
358
            if ($sqlQuery->execute($sqlParam) === false) {
359
                $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
360
            }
361
        }
362
        if ($check_existing === true)
363
        {
364
            // TODO : remove link trap - objects that wasn't marked.
365
        }
366
        
367
    }
368
369
    private function reset_oidDesc()
370
    {
371
        $this->oidDesc['oid']=null;
372
        $this->oidDesc['name']=null;
373
        $this->oidDesc['type']=null;
374
        $this->oidDesc['mib']=null;
375
        $this->oidDesc['textconv']=null;
376
        $this->oidDesc['dispHint'] =null;
377
        $this->oidDesc['syntax']=null;
378
        $this->oidDesc['type_enum']=null;
379
        $this->oidDesc['description']=null;
380
    }
381
    
382
    /**
383
     * Fills $this->objectsAll with all mibs from snmptranslate
384
     * @return integer : number of elements 
385
     */
386
    private function load_mibs_snmptranslate()
387
    {
388
        $retVal=0;
389
        // Get all mib objects from all mibs
390
        $snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
391
        $this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
392
        unset($this->objectsAll);
393
        exec($snmpCommand,$this->objectsAll,$retVal);
394
        if ($retVal!=0)
395
        {
396
            $this->logging->log('error executing snmptranslate',ERROR,'');
397
        }
398
        // Count elements to show progress
399
        $numElements=count($this->objectsAll);
400
        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
401
        return $numElements;
402
    }
403
404
    /**
405
     * load all mib objects db in dbOidAll (raw) and index in dbOidIndex
406
     */
407
    private function load_mibs_from_db()
408
    {
409
        // Get all mibs from databse to have a memory index
410
        
411
        $db_conn=$this->trapsDB->db_connect_trap();
412
        
413
        $sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
414
        $this->logging->log('SQL query : '.$sql,DEBUG );
415
        if (($ret_code=$db_conn->query($sql)) === false) {
416
            $this->logging->log('No result in query : ' . $sql,ERROR,'');
417
        }
418
        $this->dbOidAll=$ret_code->fetchAll();
419
        $this->dbOidIndex=array();
420
        // Create the index for db;
421
        foreach($this->dbOidAll as $key=>$val)
422
        {
423
            $this->dbOidIndex[$val['oid']]['key']=$key;
424
            $this->dbOidIndex[$val['oid']]['id']=$val['id'];
425
        }
426
    }
427
428
    /**
429
     * Reset all update timers & count to zero
430
     */
431
    private function reset_update_timers()
432
    {
433
        $this->timing['base_parse_time']=0;
434
        $this->timing['base_check_time']=0;
435
        $this->timing['type0_check_time']=0;
436
        $this->timing['nottrap_time']=0;
437
        $this->timing['update_time']=0;
438
        $this->timing['objects_time']=0;
439
        $this->timing['base_parse_num']=0;
440
        $this->timing['base_check_num']=0;
441
        $this->timing['type0_check_num']=0;
442
        $this->timing['nottrap_num']=0;
443
        $this->timing['update_num']=0;
444
        $this->timing['objects_num']=0;
445
        $this->timing['num_traps']=0;
446
    }
447
448
    /**
449
     * Detect if $this->objectsAll[$curElement] is a trap 
450
     * @param integer $curElement
451
     * @param bool $onlyTraps : set to false to get all and not only traps.
452
     * @return boolean : false if it's a trap , true if not
453
     */
454
    private function detect_trap($curElement,$onlyTraps)
455
    {
456
        // Get oid or pass if not found
457
        if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
458
        {
459
            $this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
460
            $this->timing['base_parse_num'] ++;
461
            return true;
462
        }
463
        $this->oidDesc['oid']=$this->objectsAll[$curElement];
464
        
465
        // get next line
466
        $curElement++;
467
        $match=$snmptrans=array();
468
        if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
469
            $this->objectsAll[$curElement],$match))
470
        {
471
            $this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
472
            $this->timing['base_check_num']++;
473
            return true;
474
        }
475
        
476
        $this->oidDesc['name']=$match[1]; // Name
477
        $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
478
        
479
        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
480
        {
481
            // Check if next is suboid -> in that case is cannot be a trap
482
            if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
483
            {
484
                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
485
                $this->timing['type0_check_num']++;
486
                return true;
487
            }
488
            unset($snmptrans);
489
            $retVal=0;
490
            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
491
                ' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
492
            if ($retVal!=0)
493
            {
494
                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
495
                $this->timing['type0_check_num']++;
496
                return true;
497
            }
498
            //echo "\n v1 trap found : $this->oidDesc['oid'] \n";
499
            // Force as trap.
500
            $this->oidDesc['type']=21;
501
        }
502
        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
503
        {
504
            $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
505
            $this->timing['nottrap_num']++;
506
            return true;
507
        }
508
        return false;
509
    }
510
   
511
    /**
512
     * get_trap_mib_description
513
     * @return array|null : array of snmptranslate output or null on error
514
    **/
515
    private function get_trap_mib_description()
516
    {
517
        $retVal=0;
518
        $match=$snmptrans=array();
519
        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
520
            ' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
521
        if ($retVal!=0)
522
        {
523
            $this->logging->log('error executing snmptranslate',ERROR);
524
            return $snmptrans;
525
        }
526
        
527
        if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
528
        {
529
            $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
530
            return $snmptrans;
531
        }
532
        $this->oidDesc['mib']=$match[1];
533
        
534
        $numLine=1;
535
        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
536
        if (isset($snmptrans[$numLine]))
537
        {
538
            $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
539
            
540
            while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
541
            {
542
                $this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
543
                $numLine++;
544
            }
545
            if (isset($snmptrans[$numLine])) {
546
                $this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
547
                $this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
548
            }
549
            
550
        }
551
        return $snmptrans;
552
    }
553
554
    /**
555
     * Get trap objects
556
     * @param array $snmptrans : output of snmptranslate for TrapModuleConfig
557
     * @return array|null : array of objects or null if not found
558
    **/
559
    private function get_trap_objects($snmptrans)
560
    {
561
        $objectName=null;
562
        $match=array();
563
        foreach ($snmptrans as $line)
564
        {
565
            if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
566
            {
567
                $objectName=$match[1];
568
            }
569
        }
570
        if ($objectName == null)
571
        {
572
            $this->logging->log('No objects for ' . $this->oidDesc['oid'],DEBUG);
573
            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
574
            return null;
575
        }
576
        
577
        $trapObjects=array();
578
        while (preg_match('/ *([^ ,]+) *,* */',$objectName,$match))
579
        {
580
            array_push($trapObjects,$match[1]);
581
            $objectName=preg_replace('/'.$match[0].'/','',$objectName);
582
        }
583
        return $trapObjects;
584
    }
585
    
586
    /**
587
     * Cache mib in database
588
     * @param boolean $display_progress : Display progress on standard output
589
     * @param boolean $check_change : Force check of trap params & objects
590
     * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
591
     * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
592
     */
593
    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
0 ignored issues
show
Unused Code introduced by
The parameter $startOID is not used and could be removed. ( Ignorable by Annotation )

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

593
    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,/** @scrutinizer ignore-unused */ $startOID='.1')

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
594
    {
595
        // Global Timing
596
        $timeTaken = microtime(true);
597
        
598
        $numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
599
        
600
        $this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
601
        
602
        $step=$basestep=$numElements/10; // output display of % done
603
        $num_step=0;
604
        $timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
605
        
606
        // Create index for trap objects
607
        $this->trapObjectsIndex=array();
608
        
609
        // detailed timing (time_* vars)
610
        $this->reset_update_timers();
611
        
612
        for ($curElement=0;$curElement < $numElements;$curElement++)
613
        {
614
            $this->timing['base_time']= microtime(true);
615
            if ($display_progress)
616
            {
617
                if ((microtime(true)-$timeFiveSec) > 2)
618
                { // echo a . every 2 sec
619
                    echo '.';
620
                    $timeFiveSec = microtime(true);
621
                }
622
                if ($curElement>$step)
623
                { // display progress
624
                    $num_step++;
625
                    $step+=$basestep;   
626
                    echo "\n" . ($num_step*10). '% : ';
627
                }
628
            }
629
            
630
            $this->reset_oidDesc();
631
            if ($this->detect_trap($curElement,$onlyTraps)===true)
632
            {
633
                continue;
634
            }
635
            
636
            $this->timing['num_traps']++;
637
            
638
            $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
639
            if ($display_progress) echo '#'; // echo a # when trap found
640
641
            // get trap objects & source MIB
642
            
643
            $snmptrans=$this->get_trap_mib_description(); // get MIB & description
644
645
646
            $update=$this->update_oid(); // Do update of trap.
647
            
648
            $this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
649
            $this->timing['update_num']++;
650
            
651
            $this->timing['base_time']= microtime(true); // Reset to check object time
652
            
653
            if (($update==0) && ($check_change===false))
654
            { // Trapd didn't change & force check disabled
655
                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
656
                if ($display_progress) echo "C";
657
                continue;
658
            }
659
            
660
            $trapObjects=$this->get_trap_objects($snmptrans); // Get trap objects from snmptranslate output            
661
            if ($trapObjects == null)
662
            {
663
                continue;
664
            }
665
           
666
            $this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
667
            
668
            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
669
            $this->timing['objects_num']++;
670
        }
671
        
672
        if ($display_progress)
673
        {
674
            echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
675
            echo "\nParsing : " . number_format($this->timing['base_parse_time']+$this->timing['base_check_time'],1) ." sec / " . ($this->timing['base_parse_num']+ $this->timing['base_check_num'])  . " occurences\n";
676
            echo "Detecting traps : " . number_format($this->timing['type0_check_time']+$this->timing['nottrap_time'],1) . " sec / " . ($this->timing['type0_check_num']+$this->timing['nottrap_num']) ." occurences\n";
677
            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
678
            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
679
            
680
            $timeTaken=microtime(true) - $timeTaken;
681
            echo "Global time : ".round($timeTaken)." seconds\n";
682
        }
683
    }
684
    
685
    
686
}