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

Cronjob::LibStatut()   D

Complexity

Conditions 24

Size

Total Lines 38
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 24
eloc 22
c 0
b 0
f 0
nop 3
dl 0
loc 38
rs 4.1666

How to fix   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) 2007-2012 Laurent Destailleur  <[email protected]>
3
 * Copyright (C) 2013      Florian Henry        <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
/**
20
 *  \file       cron/class/cronjob.class.php
21
 *  \ingroup    cron
22
 */
23
24
// Put here all includes required by your class file
25
require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
26
27
28
/**
29
 *	Cron Job class
30
 */
31
class Cronjob extends CommonObject
32
{
33
	/**
34
	 * @var string ID to identify managed object
35
	 */
36
	public $element='cronjob';
37
38
	/**
39
	 * @var string Name of table without prefix where object is stored
40
	 */
41
	public $table_element='cronjob';
42
43
    /**
44
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
45
	 */
46
	public $picto = 'cron';
47
48
    /**
49
	 * @var int Entity
50
	 */
51
	public $entity;
52
53
    public $jobtype;
54
	public $tms='';
55
	public $datec='';
56
57
	/**
58
     * @var string Cron Job label
59
     */
60
    public $label;
61
62
	public $command;
63
	public $classesname;
64
	public $objectname;
65
	public $methodename;
66
	public $params;
67
	public $md5params;
68
	public $module_name;
69
	public $priority;
70
	/**
71
	 * @var string|int     Date for last job execution
72
	 */
73
	public $datelastrun='';
74
	/**
75
	 * @var string|int     Date for next job execution
76
	 */
77
	public $datenextrun='';
78
	public $dateend='';
79
	public $datestart='';
80
	public $datelastresult='';
81
	public $lastresult;
82
	public $lastoutput;
83
	public $unitfrequency;
84
	public $frequency;
85
86
	/**
87
	 * @var int Status
88
	 */
89
	public $status;
90
91
	public $processing;
92
93
	/**
94
     * @var int ID
95
     */
96
	public $fk_user_author;
97
98
	/**
99
     * @var int ID
100
     */
101
	public $fk_user_mod;
102
103
	public $nbrun;
104
	public $libname;
105
	public $test;					// A test condition to know if job is visible/qualified
106
107
	const STATUS_DISABLED = 0;
108
	const STATUS_ENABLED = 1;
109
	const STATUS_ARCHIVED = 2;
110
111
112
    /**
113
     *  Constructor
114
     *
115
     *  @param	DoliDb		$db      Database handler
116
     */
117
    public function __construct($db)
118
    {
119
        $this->db = $db;
120
    }
121
122
123
    /**
124
     *  Create object into database
125
     *
126
     *  @param	User	$user        User that creates
127
     *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
128
     *  @return int      		   	 <0 if KO, Id of created object if OK
129
     */
130
    public function create($user, $notrigger = 0)
131
    {
132
    	global $conf, $langs;
133
		$error=0;
134
135
		$now=dol_now();
136
137
		// Clean parameters
138
139
		if (isset($this->label)) $this->label=trim($this->label);
140
		if (isset($this->jobtype)) $this->jobtype=trim($this->jobtype);
141
		if (isset($this->command)) $this->command=trim($this->command);
142
		if (isset($this->classesname)) $this->classesname=trim($this->classesname);
143
		if (isset($this->objectname)) $this->objectname=trim($this->objectname);
144
		if (isset($this->methodename)) $this->methodename=trim($this->methodename);
145
		if (isset($this->params)) $this->params=trim($this->params);
146
		if (isset($this->md5params)) $this->md5params=trim($this->md5params);
147
		if (isset($this->module_name)) $this->module_name=trim($this->module_name);
148
		if (isset($this->priority)) $this->priority=trim($this->priority);
149
		if (isset($this->lastoutput)) $this->lastoutput=trim($this->lastoutput);
150
		if (isset($this->lastresult)) $this->lastresult=trim($this->lastresult);
151
		if (isset($this->unitfrequency)) $this->unitfrequency=trim($this->unitfrequency);
152
		if (isset($this->frequency)) $this->frequency=trim($this->frequency);
153
		if (isset($this->status)) $this->status=trim($this->status);
154
		if (isset($this->note)) $this->note=trim($this->note);
155
		if (isset($this->nbrun)) $this->nbrun=trim($this->nbrun);
156
		if (isset($this->libname)) $this->libname = trim($this->libname);
157
		if (isset($this->test)) $this->test = trim($this->test);
158
159
		// Check parameters
160
		// Put here code to add a control on parameters values
161
		if (dol_strlen($this->datestart)==0) {
162
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronDtStart'));
163
			$error++;
164
		}
165
		if (empty($this->label)) {
166
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLabel'));
167
			$error++;
168
		}
169
		if ((dol_strlen($this->datestart)!=0) && (dol_strlen($this->dateend)!=0) && ($this->dateend<$this->datestart)) {
170
			$this->errors[]=$langs->trans('CronErrEndDateStartDt');
171
			$error++;
172
		}
173
		if (empty($this->unitfrequency)) {
174
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronFrequency'));
175
			$error++;
176
		}
177
		if (($this->jobtype=='command') && (empty($this->command))) {
178
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronCommand'));
179
			$error++;
180
		}
181
		if (($this->jobtype=='method') && (empty($this->classesname))) {
182
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronClass'));
183
			$error++;
184
		}
185
		if (($this->jobtype=='method' || $this->jobtype == 'function') && (empty($this->methodename))) {
186
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronMethod'));
187
			$error++;
188
		}
189
		if (($this->jobtype=='method') && (empty($this->objectname))) {
190
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronObject'));
191
			$error++;
192
		}
193
		if (($this->jobtype=='function') && (empty($this->libname))) {
194
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLib'));
195
			$error++;
196
		}
197
198
        // Insert request
199
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob(";
200
		$sql.= "entity,";
201
		$sql.= "datec,";
202
		$sql.= "jobtype,";
203
		$sql.= "label,";
204
		$sql.= "command,";
205
		$sql.= "classesname,";
206
		$sql.= "objectname,";
207
		$sql.= "methodename,";
208
		$sql.= "params,";
209
		$sql.= "md5params,";
210
		$sql.= "module_name,";
211
		$sql.= "priority,";
212
		$sql.= "datelastrun,";
213
		$sql.= "datenextrun,";
214
		$sql.= "dateend,";
215
		$sql.= "datestart,";
216
		$sql.= "lastresult,";
217
		$sql.= "datelastresult,";
218
		$sql.= "lastoutput,";
219
		$sql.= "unitfrequency,";
220
		$sql.= "frequency,";
221
		$sql.= "status,";
222
		$sql.= "fk_user_author,";
223
		$sql.= "fk_user_mod,";
224
		$sql.= "note,";
225
		$sql.= "nbrun,";
226
		$sql.= "maxrun,";
227
		$sql.= "libname,";
228
		$sql.= "test";
229
		$sql.= ") VALUES (";
230
		$sql.= " ".(! isset($this->entity)?$conf->entity:$this->db->escape($this->entity)).",";
231
		$sql.= " '".$this->db->idate($now)."',";
232
		$sql.= " ".(! isset($this->jobtype)?'NULL':"'".$this->db->escape($this->jobtype)."'").",";
233
		$sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").",";
234
		$sql.= " ".(! isset($this->command)?'NULL':"'".$this->db->escape($this->command)."'").",";
235
		$sql.= " ".(! isset($this->classesname)?'NULL':"'".$this->db->escape($this->classesname)."'").",";
236
		$sql.= " ".(! isset($this->objectname)?'NULL':"'".$this->db->escape($this->objectname)."'").",";
237
		$sql.= " ".(! isset($this->methodename)?'NULL':"'".$this->db->escape($this->methodename)."'").",";
238
		$sql.= " ".(! isset($this->params)?'NULL':"'".$this->db->escape($this->params)."'").",";
239
		$sql.= " ".(! isset($this->md5params)?'NULL':"'".$this->db->escape($this->md5params)."'").",";
240
		$sql.= " ".(! isset($this->module_name)?'NULL':"'".$this->db->escape($this->module_name)."'").",";
241
		$sql.= " ".(! isset($this->priority)?'0':$this->priority).",";
242
		$sql.= " ".(! isset($this->datelastrun) || dol_strlen($this->datelastrun)==0?'NULL':"'".$this->db->idate($this->datelastrun)."'").",";
243
		$sql.= " ".(! isset($this->datenextrun) || dol_strlen($this->datenextrun)==0?'NULL':"'".$this->db->idate($this->datenextrun)."'").",";
244
		$sql.= " ".(! isset($this->dateend) || dol_strlen($this->dateend)==0?'NULL':"'".$this->db->idate($this->dateend)."'").",";
245
		$sql.= " ".(! isset($this->datestart) || dol_strlen($this->datestart)==0?'NULL':"'".$this->db->idate($this->datestart)."'").",";
246
		$sql.= " ".(! isset($this->lastresult)?'NULL':"'".$this->db->escape($this->lastresult)."'").",";
247
		$sql.= " ".(! isset($this->datelastresult) || dol_strlen($this->datelastresult)==0?'NULL':"'".$this->db->idate($this->datelastresult)."'").",";
248
		$sql.= " ".(! isset($this->lastoutput)?'NULL':"'".$this->db->escape($this->lastoutput)."'").",";
249
		$sql.= " ".(! isset($this->unitfrequency)?'NULL':"'".$this->db->escape($this->unitfrequency)."'").",";
250
		$sql.= " ".(! isset($this->frequency)?'0':$this->frequency).",";
251
		$sql.= " ".(! isset($this->status)?'0':$this->status).",";
252
		$sql.= " ".$user->id.",";
253
		$sql.= " ".$user->id.",";
254
		$sql.= " ".(! isset($this->note)?'NULL':"'".$this->db->escape($this->note)."'").",";
255
		$sql.= " ".(! isset($this->nbrun)?'0':$this->db->escape($this->nbrun)).",";
256
		$sql.= " ".(empty($this->maxrun)?'0':$this->db->escape($this->maxrun)).",";
257
		$sql.= " ".(! isset($this->libname)?'NULL':"'".$this->db->escape($this->libname)."'").",";
258
		$sql.= " ".(! isset($this->test)?'NULL':"'".$this->db->escape($this->test)."'")."";
259
		$sql.= ")";
260
261
		$this->db->begin();
262
263
	   	dol_syslog(get_class($this)."::create", LOG_DEBUG);
264
        $resql=$this->db->query($sql);
265
    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
266
267
		if (! $error)
268
        {
269
            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."cronjob");
270
271
			//if (! $notrigger)
272
			//{
273
	            // Uncomment this and change MYOBJECT to your own tag if you
274
	            // want this action calls a trigger.
275
276
	            //// Call triggers
277
	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
278
	            //$interface=new Interfaces($this->db);
279
	            //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
280
	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
281
	            //// End call triggers
282
			//}
283
        }
284
285
        // Commit or rollback
286
        if ($error)
287
		{
288
			foreach($this->errors as $errmsg)
289
			{
290
	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
291
	            $this->error.=($this->error?', '.$errmsg:$errmsg);
292
			}
293
			$this->db->rollback();
294
			return -1*$error;
295
		}
296
		else
297
		{
298
			$this->db->commit();
299
            return $this->id;
300
		}
301
    }
302
303
304
    /**
305
     *  Load object in memory from the database
306
     *
307
     *  @param	int		$id    Id object
308
     *  @return int          	<0 if KO, >0 if OK
309
     */
310
    public function fetch($id)
311
    {
312
        $sql = "SELECT";
313
        $sql.= " t.rowid,";
314
        $sql.= " t.entity,";
315
		$sql.= " t.tms,";
316
		$sql.= " t.datec,";
317
		$sql.= " t.jobtype,";
318
		$sql.= " t.label,";
319
		$sql.= " t.command,";
320
		$sql.= " t.classesname,";
321
		$sql.= " t.objectname,";
322
		$sql.= " t.methodename,";
323
		$sql.= " t.params,";
324
		$sql.= " t.md5params,";
325
		$sql.= " t.module_name,";
326
		$sql.= " t.priority,";
327
		$sql.= " t.datelastrun,";
328
		$sql.= " t.datenextrun,";
329
		$sql.= " t.dateend,";
330
		$sql.= " t.datestart,";
331
		$sql.= " t.lastresult,";
332
		$sql.= " t.datelastresult,";
333
		$sql.= " t.lastoutput,";
334
		$sql.= " t.unitfrequency,";
335
		$sql.= " t.frequency,";
336
		$sql.= " t.status,";
337
		$sql.= " t.processing,";
338
		$sql.= " t.fk_user_author,";
339
		$sql.= " t.fk_user_mod,";
340
		$sql.= " t.note,";
341
		$sql.= " t.nbrun,";
342
		$sql.= " t.maxrun,";
343
		$sql.= " t.libname,";
344
		$sql.= " t.test";
345
        $sql.= " FROM ".MAIN_DB_PREFIX."cronjob as t";
346
        $sql.= " WHERE t.rowid = ".$id;
347
348
    	dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
349
        $resql=$this->db->query($sql);
350
        if ($resql)
351
        {
352
            if ($this->db->num_rows($resql))
353
            {
354
                $obj = $this->db->fetch_object($resql);
355
356
                $this->id    = $obj->rowid;
357
                $this->ref = $obj->rowid;
358
				$this->entity = $obj->entity;
359
				$this->tms = $this->db->jdate($obj->tms);
360
				$this->datec = $this->db->jdate($obj->datec);
361
				$this->label = $obj->label;
362
				$this->jobtype = $obj->jobtype;
363
				$this->command = $obj->command;
364
				$this->classesname = $obj->classesname;
365
				$this->objectname = $obj->objectname;
366
				$this->methodename = $obj->methodename;
367
				$this->params = $obj->params;
368
				$this->md5params = $obj->md5params;
369
				$this->module_name = $obj->module_name;
370
				$this->priority = $obj->priority;
371
				$this->datelastrun = $this->db->jdate($obj->datelastrun);
372
				$this->datenextrun = $this->db->jdate($obj->datenextrun);
373
				$this->dateend = $this->db->jdate($obj->dateend);
374
				$this->datestart = $this->db->jdate($obj->datestart);
375
				$this->lastresult = $obj->lastresult;
376
				$this->lastoutput = $obj->lastoutput;
377
				$this->datelastresult = $this->db->jdate($obj->datelastresult);
378
				$this->unitfrequency = $obj->unitfrequency;
379
				$this->frequency = $obj->frequency;
380
				$this->status = $obj->status;
381
				$this->processing = $obj->processing;
382
				$this->fk_user_author = $obj->fk_user_author;
383
				$this->fk_user_mod = $obj->fk_user_mod;
384
				$this->note = $obj->note;
385
				$this->nbrun = $obj->nbrun;
386
				$this->maxrun = $obj->maxrun;
387
				$this->libname = $obj->libname;
388
				$this->test = $obj->test;
389
            }
390
            $this->db->free($resql);
391
392
            return 1;
393
        }
394
        else
395
        {
396
      	    $this->error="Error ".$this->db->lasterror();
397
            return -1;
398
        }
399
    }
400
401
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
402
    /**
403
     *  Load object in memory from the database
404
     *
405
	 *  @param	string		$sortorder      sort order
406
	 *  @param	string		$sortfield      sort field
407
	 *  @param	int			$limit		    limit page
408
	 *  @param	int			$offset    	    page
409
	 *  @param	int			$status    	    display active or not
410
	 *  @param	array		$filter    	    filter output
411
	 *  @param  int         $processing     Processing or not
412
     *  @return int          			    <0 if KO, >0 if OK
413
     */
414
    public function fetch_all($sortorder = 'DESC', $sortfield = 't.rowid', $limit = 0, $offset = 0, $status = 1, $filter = '', $processing = -1)
415
    {
416
        // phpcs:enable
417
        global $langs;
418
419
    	$this->lines=array();
420
421
    	$sql = "SELECT";
422
    	$sql.= " t.rowid,";
423
    	$sql.= " t.entity,";
424
    	$sql.= " t.tms,";
425
    	$sql.= " t.datec,";
426
    	$sql.= " t.jobtype,";
427
    	$sql.= " t.label,";
428
    	$sql.= " t.command,";
429
    	$sql.= " t.classesname,";
430
    	$sql.= " t.objectname,";
431
    	$sql.= " t.methodename,";
432
    	$sql.= " t.params,";
433
    	$sql.= " t.md5params,";
434
    	$sql.= " t.module_name,";
435
    	$sql.= " t.priority,";
436
    	$sql.= " t.datelastrun,";
437
    	$sql.= " t.datenextrun,";
438
    	$sql.= " t.dateend,";
439
    	$sql.= " t.datestart,";
440
    	$sql.= " t.lastresult,";
441
    	$sql.= " t.datelastresult,";
442
    	$sql.= " t.lastoutput,";
443
    	$sql.= " t.unitfrequency,";
444
    	$sql.= " t.frequency,";
445
    	$sql.= " t.status,";
446
    	$sql.= " t.processing,";
447
    	$sql.= " t.fk_user_author,";
448
    	$sql.= " t.fk_user_mod,";
449
    	$sql.= " t.note,";
450
    	$sql.= " t.nbrun,";
451
    	$sql.= " t.libname,";
452
    	$sql.= " t.test";
453
    	$sql.= " FROM ".MAIN_DB_PREFIX."cronjob as t";
454
    	$sql.= " WHERE 1 = 1";
455
    	if ($processing >= 0) $sql.= " AND t.processing = ".(empty($processing)?'0':'1');
456
    	if ($status >= 0 && $status < 2) $sql.= " AND t.status = ".(empty($status)?'0':'1');
457
    	elseif ($status == 2) $sql.= " AND t.status = 2";
458
    	//Manage filter
459
    	if (is_array($filter) && count($filter)>0) {
460
    		foreach($filter as $key => $value)
461
    		{
462
    		    if ($key == 't.rowid') $sql.= ' AND '.$key.' = '.$this->db->escape($value);
463
   				else $sql.= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\'';
464
    		}
465
    	}
466
467
    	$sql.= $this->db->order($sortfield, $sortorder);
468
    	if (!empty($limit) && !empty($offset)) {
469
    		$sql.= $this->db->plimit($limit + 1, $offset);
470
    	}
471
472
    	$sqlwhere = array();
473
474
    	if (count($sqlwhere)>0) {
475
    		$sql.= " WHERE ".implode(' AND ', $sqlwhere);
476
    	}
477
478
    	dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
479
    	$resql=$this->db->query($sql);
480
    	if ($resql)
481
    	{
482
    		$num=$this->db->num_rows($resql);
483
    		$i=0;
484
485
    		if ($num)
486
    		{
487
	    		while ($i < $num)
488
	    		{
489
	    			$line = new Cronjobline();
490
491
	    			$obj = $this->db->fetch_object($resql);
492
493
	    			$line->id    = $obj->rowid;
494
	    			$line->ref = $obj->rowid;
495
	    			$line->entity = $obj->entity;
496
	    			$line->tms = $this->db->jdate($obj->tms);
497
	    			$line->datec = $this->db->jdate($obj->datec);
498
	    			$line->label = $obj->label;
499
	    			$line->jobtype = $obj->jobtype;
500
	    			$line->command = $obj->command;
501
	    			$line->classesname = $obj->classesname;
502
	    			$line->objectname = $obj->objectname;
503
	    			$line->methodename = $obj->methodename;
504
	    			$line->params = $obj->params;
505
	    			$line->md5params = $obj->md5params;
506
	    			$line->module_name = $obj->module_name;
507
	    			$line->priority = $obj->priority;
508
	    			$line->datelastrun = $this->db->jdate($obj->datelastrun);
509
	    			$line->datenextrun = $this->db->jdate($obj->datenextrun);
510
	    			$line->dateend = $this->db->jdate($obj->dateend);
511
	    			$line->datestart = $this->db->jdate($obj->datestart);
512
	    			$line->lastresult = $obj->lastresult;
513
	    			$line->datelastresult = $this->db->jdate($obj->datelastresult);
514
	    			$line->lastoutput = $obj->lastoutput;
515
	    			$line->unitfrequency = $obj->unitfrequency;
516
	    			$line->frequency = $obj->frequency;
517
	    			$line->status = $obj->status;
518
	    			$line->processing = $obj->processing;
519
	    			$line->fk_user_author = $obj->fk_user_author;
520
	    			$line->fk_user_mod = $obj->fk_user_mod;
521
	    			$line->note = $obj->note;
522
	    			$line->nbrun = $obj->nbrun;
523
	    			$line->libname = $obj->libname;
524
	    			$line->test = $obj->test;
525
	    			$this->lines[]=$line;
526
527
	    			$i++;
528
	    		}
529
    		}
530
    		$this->db->free($resql);
531
532
    		return 1;
533
    	}
534
    	else
535
    	{
536
    		$this->error="Error ".$this->db->lasterror();
537
    		return -1;
538
    	}
539
    }
540
541
542
    /**
543
     *  Update object into database
544
     *
545
     *  @param	User	$user        User that modifies
546
     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
547
     *  @return int     		   	 <0 if KO, >0 if OK
548
     */
549
    public function update($user = null, $notrigger = 0)
550
    {
551
    	global $conf, $langs;
552
553
    	$langs->load('cron');
554
555
		$error=0;
556
557
		// Clean parameters
558
		if (isset($this->label)) $this->label=trim($this->label);
559
		if (isset($this->jobtype)) $this->jobtype=trim($this->jobtype);
560
		if (isset($this->command)) $this->command=trim($this->command);
561
		if (isset($this->classesname)) $this->classesname=trim($this->classesname);
562
		if (isset($this->objectname)) $this->objectname=trim($this->objectname);
563
		if (isset($this->methodename)) $this->methodename=trim($this->methodename);
564
		if (isset($this->params)) $this->params=trim($this->params);
565
		if (isset($this->md5params)) $this->md5params=trim($this->md5params);
566
		if (isset($this->module_name)) $this->module_name=trim($this->module_name);
567
		if (isset($this->priority)) $this->priority=trim($this->priority);
568
		if (isset($this->lastoutput)) $this->lastoutput=trim($this->lastoutput);
569
		if (isset($this->lastresult)) $this->lastresult=trim($this->lastresult);
570
		if (isset($this->unitfrequency)) $this->unitfrequency=trim($this->unitfrequency);
571
		if (isset($this->frequency)) $this->frequency=trim($this->frequency);
572
		if (isset($this->status)) $this->status=trim($this->status);
573
		if (isset($this->note)) $this->note=trim($this->note);
574
		if (isset($this->nbrun)) $this->nbrun=trim($this->nbrun);
575
        if (isset($this->libname)) $this->libname = trim($this->libname);
576
        if (isset($this->test)) $this->test = trim($this->test);
577
578
		if (empty($this->maxrun)) $this->maxrun=0;
579
        if (empty($this->processing)) $this->processing=0;
580
581
		// Check parameters
582
		// Put here code to add a control on parameters values
583
		if (dol_strlen($this->datestart)==0) {
584
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronDtStart'));
585
			$error++;
586
		}
587
		if ((dol_strlen($this->datestart)!=0) && (dol_strlen($this->dateend)!=0) && ($this->dateend<$this->datestart)) {
588
			$this->errors[]=$langs->trans('CronErrEndDateStartDt');
589
			$error++;
590
		}
591
		if (empty($this->label)) {
592
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLabel'));
593
			$error++;
594
		}
595
		if (empty($this->unitfrequency)) {
596
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronFrequency'));
597
			$error++;
598
		}
599
		if (($this->jobtype=='command') && (empty($this->command))) {
600
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronCommand'));
601
			$error++;
602
		}
603
		if (($this->jobtype=='method') && (empty($this->classesname))) {
604
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronClass'));
605
			$error++;
606
		}
607
		if (($this->jobtype=='method' || $this->jobtype == 'function') && (empty($this->methodename))) {
608
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronMethod'));
609
			$error++;
610
		}
611
		if (($this->jobtype=='method') && (empty($this->objectname))) {
612
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronObject'));
613
			$error++;
614
		}
615
616
		if (($this->jobtype=='function') && (empty($this->libname))) {
617
			$this->errors[]=$langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLib'));
618
			$error++;
619
		}
620
621
622
        // Update request
623
        $sql = "UPDATE ".MAIN_DB_PREFIX."cronjob SET";
624
        $sql.= " entity=".(isset($this->entity)?$this->db->escape($this->entity):$conf->entity).",";
625
		$sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
626
		$sql.= " jobtype=".(isset($this->jobtype)?"'".$this->db->escape($this->jobtype)."'":"null").",";
627
		$sql.= " command=".(isset($this->command)?"'".$this->db->escape($this->command)."'":"null").",";
628
		$sql.= " classesname=".(isset($this->classesname)?"'".$this->db->escape($this->classesname)."'":"null").",";
629
		$sql.= " objectname=".(isset($this->objectname)?"'".$this->db->escape($this->objectname)."'":"null").",";
630
		$sql.= " methodename=".(isset($this->methodename)?"'".$this->db->escape($this->methodename)."'":"null").",";
631
		$sql.= " params=".(isset($this->params)?"'".$this->db->escape($this->params)."'":"null").",";
632
		$sql.= " md5params=".(isset($this->md5params)?"'".$this->db->escape($this->md5params)."'":"null").",";
633
		$sql.= " module_name=".(isset($this->module_name)?"'".$this->db->escape($this->module_name)."'":"null").",";
634
		$sql.= " priority=".(isset($this->priority)?$this->priority:"null").",";
635
		$sql.= " datelastrun=".(dol_strlen($this->datelastrun)!=0 ? "'".$this->db->idate($this->datelastrun)."'" : 'null').",";
636
		$sql.= " datenextrun=".(dol_strlen($this->datenextrun)!=0 ? "'".$this->db->idate($this->datenextrun)."'" : 'null').",";
637
		$sql.= " dateend=".(dol_strlen($this->dateend)!=0 ? "'".$this->db->idate($this->dateend)."'" : 'null').",";
638
		$sql.= " datestart=".(dol_strlen($this->datestart)!=0 ? "'".$this->db->idate($this->datestart)."'" : 'null').",";
639
		$sql.= " datelastresult=".(dol_strlen($this->datelastresult)!=0 ? "'".$this->db->idate($this->datelastresult)."'" : 'null').",";
640
		$sql.= " lastresult=".(isset($this->lastresult)?"'".$this->db->escape($this->lastresult)."'":"null").",";
641
		$sql.= " lastoutput=".(isset($this->lastoutput)?"'".$this->db->escape($this->lastoutput)."'":"null").",";
642
		$sql.= " unitfrequency=".(isset($this->unitfrequency)?$this->unitfrequency:"null").",";
643
		$sql.= " frequency=".(isset($this->frequency)?$this->frequency:"null").",";
644
		$sql.= " status=".(isset($this->status)?$this->status:"null").",";
645
		$sql.= " processing=".((isset($this->processing) && $this->processing > 0)?$this->processing:"0").",";
646
		$sql.= " fk_user_mod=".$user->id.",";
647
		$sql.= " note=".(isset($this->note)?"'".$this->db->escape($this->note)."'":"null").",";
648
		$sql.= " nbrun=".((isset($this->nbrun) && $this->nbrun >0)?$this->nbrun:"null").",";
649
		$sql.= " maxrun=".((isset($this->maxrun) && $this->maxrun > 0)?$this->maxrun:"0").",";
650
		$sql.= " libname=".(isset($this->libname)?"'".$this->db->escape($this->libname)."'":"null").",";
651
		$sql.= " test=".(isset($this->test)?"'".$this->db->escape($this->test)."'":"null");
652
		$sql.= " WHERE rowid=".$this->id;
653
654
        $this->db->begin();
655
656
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
657
        $resql = $this->db->query($sql);
658
    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
659
660
		//if (! $error && ! $notrigger)
661
		//{
662
	            // Uncomment this and change MYOBJECT to your own tag if you
663
	            // want this action calls a trigger.
664
665
	            //// Call triggers
666
	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
667
	            //$interface=new Interfaces($this->db);
668
	            //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
669
	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
670
	            //// End call triggers
671
		//}
672
673
        // Commit or rollback
674
		if ($error)
675
		{
676
			foreach($this->errors as $errmsg)
677
			{
678
	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
679
	            $this->error.=($this->error?', '.$errmsg:$errmsg);
680
			}
681
			$this->db->rollback();
682
			return -1*$error;
683
		}
684
		else
685
		{
686
			$this->db->commit();
687
			return 1;
688
		}
689
    }
690
691
692
 	/**
693
	 *  Delete object in database
694
	 *
695
     *	@param  User	$user        User that deletes
696
     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
697
	 *  @return	int					 <0 if KO, >0 if OK
698
	 */
699
    public function delete($user, $notrigger = 0)
700
	{
701
		$error=0;
702
703
		$this->db->begin();
704
705
    	$sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
706
    	$sql.= " WHERE rowid=".$this->id;
707
708
    	dol_syslog(get_class($this)."::delete", LOG_DEBUG);
709
    	$resql = $this->db->query($sql);
710
        if (! $resql) {
711
            $error++;
712
            $this->errors[]="Error ".$this->db->lasterror();
713
        }
714
715
        // Commit or rollback
716
		if ($error)
717
		{
718
			foreach($this->errors as $errmsg)
719
			{
720
	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
721
	            $this->error.=($this->error?', '.$errmsg:$errmsg);
722
			}
723
			$this->db->rollback();
724
			return -1*$error;
725
		}
726
		else
727
		{
728
			$this->db->commit();
729
			return 1;
730
		}
731
	}
732
733
734
735
	/**
736
	 *	Load an object from its id and create a new one in database
737
	 *
738
	 *  @param	User	$user		User making the clone
739
	 *	@param	int		$fromid     Id of object to clone
740
	 * 	@return	int					New id of clone
741
	 */
742
	public function createFromClone(User $user, $fromid)
743
	{
744
		$error=0;
745
746
		$object=new Cronjob($this->db);
747
748
		$this->db->begin();
749
750
		// Load source object
751
		$object->fetch($fromid);
752
		$object->id=0;
753
		$object->statut=0;
754
755
		// Clear fields
756
		// ...
757
758
		// Create clone
759
		$object->context['createfromclone'] = 'createfromclone';
760
		$result=$object->create($user);
761
762
		// Other options
763
		if ($result < 0)
764
		{
765
			$this->error=$object->error;
766
			$error++;
767
		}
768
769
		//if (! $error)
770
		//{
771
772
		//}
773
774
		unset($object->context['createfromclone']);
775
776
		// End
777
		if (! $error)
778
		{
779
			$this->db->commit();
780
			return $object->id;
781
		}
782
		else
783
		{
784
			$this->db->rollback();
785
			return -1;
786
		}
787
	}
788
789
790
	/**
791
	 *	Initialise object with example values
792
	 *	Id must be 0 if object instance is a specimen
793
	 *
794
	 *	@return	void
795
	 */
796
	public function initAsSpecimen()
797
	{
798
		$this->id=0;
799
		$this->ref=0;
800
		$this->entity=0;
801
		$this->tms='';
802
		$this->datec='';
803
		$this->label='';
804
		$this->jobtype='';
805
		$this->command='';
806
		$this->classesname='';
807
		$this->objectname='';
808
		$this->methodename='';
809
		$this->params='';
810
		$this->md5params='';
811
		$this->module_name='';
812
		$this->priority='';
813
		$this->datelastrun='';
814
		$this->datenextrun='';
815
		$this->dateend='';
816
		$this->datestart='';
817
		$this->datelastresult='';
818
		$this->lastoutput='';
819
		$this->lastresult='';
820
		$this->unitfrequency='';
821
		$this->frequency='';
822
		$this->status=0;
823
		$this->processing=0;
824
		$this->fk_user_author='';
1 ignored issue
show
Documentation Bug introduced by
The property $fk_user_author was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
825
		$this->fk_user_mod='';
1 ignored issue
show
Documentation Bug introduced by
The property $fk_user_mod was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
826
		$this->note='';
1 ignored issue
show
Deprecated Code introduced by
The property CommonObject::$note has been deprecated. ( Ignorable by Annotation )

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

826
		/** @scrutinizer ignore-deprecated */ $this->note='';
Loading history...
827
		$this->nbrun='';
828
		$this->maxrun=100;
829
        $this->libname = '';
830
	}
831
832
833
	/**
834
	 *  Return a link to the object card (with optionaly the picto)
835
	 *
836
	 *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
837
	 *	@param	string	$option						On what the link point to ('nolink', ...)
838
	 *  @param	int  	$notooltip					1=Disable tooltip
839
	 *  @param  string  $morecss            		Add more css on link
840
	 *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
841
	 *	@return	string								String with URL
842
	 */
843
	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
844
	{
845
		global $db, $conf, $langs;
846
		global $dolibarr_main_authentication, $dolibarr_main_demo;
847
		global $menumanager;
848
849
		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
850
851
		$result = '';
852
853
		$label = '<u>' . $langs->trans("CronJob") . '</u>';
854
		$label.= '<br>';
855
		$label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
856
857
		$url = DOL_URL_ROOT.'/cron/card.php?id='.$this->id;
858
859
		if ($option != 'nolink')
860
		{
861
			// Add param to save lastsearch_values or not
862
			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
863
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
864
			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
865
		}
866
867
		$linkclose='';
868
		if (empty($notooltip))
869
		{
870
			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
871
			{
872
				$label=$langs->trans("ShowCronJob");
873
				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
874
			}
875
			$linkclose.=' title="'.dol_escape_htmltag($label, 1).'"';
876
			$linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
877
		}
878
		else $linkclose = ($morecss?' class="'.$morecss.'"':'');
879
880
		$linkstart = '<a href="'.$url.'"';
881
		$linkstart.=$linkclose.'>';
882
		$linkend='</a>';
883
884
		$result .= $linkstart;
885
		if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
886
		if ($withpicto != 2) $result.= $this->ref;
887
		$result .= $linkend;
888
		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
889
890
		return $result;
891
	}
892
893
894
	/**
895
	 *	Load object information
896
	 *
897
	 *	@return	int
898
	 */
899
	public function info()
900
	{
901
		$sql = "SELECT";
902
		$sql.= " f.rowid, f.datec, f.tms, f.fk_user_mod, f.fk_user_author";
903
		$sql.= " FROM ".MAIN_DB_PREFIX."cronjob as f";
904
		$sql.= " WHERE f.rowid = ".$this->id;
905
906
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
907
		$resql=$this->db->query($sql);
908
		if ($resql)
909
		{
910
			if ($this->db->num_rows($resql))
911
			{
912
				$obj = $this->db->fetch_object($resql);
913
				$this->id = $obj->rowid;
914
				$this->date_creation = $this->db->jdate($obj->datec);
915
				$this->date_modification = $this->db->jdate($obj->tms);
916
				$this->user_modification = $obj->fk_user_mod;
917
				$this->user_creation = $obj->fk_user_author;
918
			}
919
			$this->db->free($resql);
920
921
			return 1;
922
		}
923
		else
924
		{
925
			$this->error="Error ".$this->db->lasterror();
926
			return -1;
927
		}
928
	}
929
930
931
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
932
	/**
933
	 * Run a job.
934
	 * Once job is finished, status and nb of run is updated.
935
	 * This function does not plan the next run. This is done by function ->reprogram_jobs
936
	 *
937
	 * @param   string		$userlogin    	User login
938
	 * @return	int					 		<0 if KO, >0 if OK
939
	 */
940
	public function run_jobs($userlogin)
941
	{
942
        // phpcs:enable
943
		global $langs, $conf, $hookmanager;
944
945
		$hookmanager->initHooks(array('cron'));
946
947
		$now=dol_now();
948
		$error = 0;
949
		$retval = '';
950
951
		$langs->load('cron');
952
953
		if (empty($userlogin))
954
		{
955
			$this->error="User login is mandatory";
956
			dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
957
			return -1;
958
		}
959
960
		// Force the environment of running to the environment declared for job, so jobs launched from command line will run into correct environment
961
		// When job is ran from GUI, the environment should already be same, except if job has entity 0 (visible into all environments)
962
		if ($conf->entity != $this->entity && $this->entity > 0)
963
		{
964
			dol_syslog("We try to run a job in entity ".$this->entity." when we are in entity ".$conf->entity, LOG_WARNING);
965
		}
966
		$savcurrententity = $conf->entity;
967
		$conf->entity = $this->entity;
968
		dol_syslog(get_class($this)."::run_jobs entity for running job is ".$conf->entity);
969
970
		require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
971
		$user=new User($this->db);
972
		$result=$user->fetch('', $userlogin);
973
		if ($result<0)
974
		{
975
			$this->error="User Error:".$user->error;
976
			dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
977
			$conf->entity = $savcurrententity;
978
			return -1;
979
		}
980
		else
981
		{
982
			if (empty($user->id))
983
			{
984
				$this->error=" User user login:".$userlogin." do not exists";
985
				dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
986
				$conf->entity = $savcurrententity;
987
				return -1;
988
			}
989
		}
990
991
		dol_syslog(get_class($this)."::run_jobs jobtype=".$this->jobtype." userlogin=".$userlogin, LOG_DEBUG);
992
993
		// Increase limit of time. Works only if we are not in safe mode
994
		$ExecTimeLimit=600;
995
		if (!empty($ExecTimeLimit))
1 ignored issue
show
introduced by
The condition empty($ExecTimeLimit) is always false.
Loading history...
996
		{
997
			$err=error_reporting();
998
			error_reporting(0);     // Disable all errors
999
			//error_reporting(E_ALL);
1000
			@set_time_limit($ExecTimeLimit);   // Need more than 240 on Windows 7/64
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). 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

1000
			/** @scrutinizer ignore-unhandled */ @set_time_limit($ExecTimeLimit);   // Need more than 240 on Windows 7/64

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...
1001
			error_reporting($err);
1002
		}
1003
		if (!empty($MemoryLimit))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $MemoryLimit seems to never exist and therefore empty should always be true.
Loading history...
1004
		{
1005
			@ini_set('memory_limit', $MemoryLimit);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for ini_set(). 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

1005
			/** @scrutinizer ignore-unhandled */ @ini_set('memory_limit', $MemoryLimit);

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...
1006
		}
1007
1008
		// Update last run date start (to track running jobs)
1009
		$this->datelastrun=$now;
1010
		$this->datelastresult=null;
1011
		$this->lastoutput='';
1012
		$this->lastresult='';
1013
		$this->processing = 1;                // To know job was started
1014
		$this->nbrun=$this->nbrun + 1;
1015
		$result = $this->update($user);       // This include begin/commit
1016
		if ($result<0) {
1017
			dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1018
			$conf->entity = $savcurrententity;
1019
			return -1;
1020
		}
1021
1022
		// Run a method
1023
		if ($this->jobtype=='method')
1024
		{
1025
			// load classes
1026
			if (! $error)
1027
			{
1028
				$ret=dol_include_once($this->classesname);
1029
				if ($ret===false || (! class_exists($this->objectname)))
1030
				{
1031
					if ($ret===false) $this->error=$langs->trans('CronCannotLoadClass', $this->classesname, $this->objectname);
1032
					else $this->error=$langs->trans('CronCannotLoadObject', $this->classesname, $this->objectname);
1033
					dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1034
					$this->lastoutput = $this->error;
1035
					$this->lastresult = -1;
1036
					$retval = $this->lastresult;
1037
					$error++;
1038
				}
1039
			}
1040
1041
			// test if method exists
1042
			if (! $error)
1043
			{
1044
			    if (! method_exists($this->objectname, $this->methodename))
1045
			    {
1046
			        $this->error=$langs->trans('CronMethodDoesNotExists', $this->objectname, $this->methodename);
1047
    				dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1048
    				$this->lastoutput = $this->error;
1049
    				$this->lastresult = -1;
1050
    				$retval = $this->lastresult;
1051
    				$error++;
1052
			    }
1053
			}
1054
1055
			// Load langs
1056
			if (! $error)
1057
			{
1058
				$result=$langs->load($this->module_name);
1059
				$result=$langs->load($this->module_name.'@'.$this->module_name);	// If this->module_name was an existing language file, this will make nothing
1060
				if ($result < 0)	// If technical error
1061
				{
1062
					dol_syslog(get_class($this)."::run_jobs Cannot load module lang file - ".$langs->error, LOG_ERR);
1063
					$this->error = $langs->error;
1064
					$this->lastoutput = $this->error;
1065
					$this->lastresult = -1;
1066
	                $retval = $this->lastresult;
1067
	                $error++;
1068
				}
1069
			}
1070
1071
			if (! $error)
1072
			{
1073
				dol_syslog(get_class($this)."::run_jobs START ".$this->objectname."->".$this->methodename."(".$this->params.");", LOG_DEBUG);
1074
1075
				// Create Object for the called module
1076
				$object = new $this->objectname($this->db);
1077
				if ($this->entity > 0) $object->entity = $this->entity;		// We work on a dedicated entity
1078
1079
				$params_arr = array_map('trim', explode(",", $this->params));
1080
1081
				if (!is_array($params_arr))
1 ignored issue
show
introduced by
The condition is_array($params_arr) is always true.
Loading history...
1082
				{
1083
					$result = call_user_func(array($object, $this->methodename), $this->params);
1084
				}
1085
				else
1086
				{
1087
					$result = call_user_func_array(array($object, $this->methodename), $params_arr);
1088
				}
1089
1090
				if ($result === false || (! is_bool($result) && $result != 0))
1091
				{
1092
				    $langs->load("errors");
1093
1094
				    $errmsg='';
1095
				    if (! is_array($object->errors) || ! in_array($object->error, $object->errors)) $errmsg.=$object->error;
1096
				    if (is_array($object->errors) && count($object->errors)) $errmsg.=($errmsg?', '.$errmsg:'').join(', ', $object->errors);
1097
				    if (empty($errmsg)) $errmsg=$langs->trans('ErrorUnknown');
1098
1099
				    dol_syslog(get_class($this)."::run_jobs END result=".$result." error=".$errmsg, LOG_ERR);
1100
1101
				    $this->error = $errmsg;
1102
				    $this->lastoutput = ($object->output?$object->output."\n":"").$errmsg;
1103
					$this->lastresult = is_numeric($result)?$result:-1;
1104
		            $retval = $this->lastresult;
1105
		            $error++;
1106
				}
1107
				else
1108
				{
1109
					dol_syslog(get_class($this)."::run_jobs END");
1110
				    $this->lastoutput=$object->output;
1111
					$this->lastresult=var_export($result, true);
1112
					$retval = $this->lastresult;
1113
				}
1114
			}
1115
		}
1116
1117
		if ($this->jobtype == 'function') {
1118
			//load lib
1119
			$libpath = '/' . strtolower($this->module_name) . '/lib/' . $this->libname;
1120
			$ret = dol_include_once($libpath);
1121
			if ($ret === false)
1122
			{
1123
				$this->error = $langs->trans('CronCannotLoadLib') . ': ' . $libpath;
1124
				dol_syslog(get_class($this) . "::run_jobs " . $this->error, LOG_ERR);
1125
				$conf->entity = $savcurrententity;
1126
				return -1;
1127
			}
1128
1129
			// Load langs
1130
			$result=$langs->load($this->module_name);
1131
			$result=$langs->load($this->module_name.'@'.$this->module_name);	// If this->module_name was an existing language file, this will make nothing
1132
			if ($result < 0)	// If technical error
1133
			{
1134
				dol_syslog(get_class($this) . "::run_jobs Cannot load module langs" . $langs->error, LOG_ERR);
1135
				$conf->entity = $savcurrententity;
1136
				return -1;
1137
			}
1138
1139
			dol_syslog(get_class($this) . "::run_jobs " . $this->libname . "::" . $this->methodename."(" . $this->params . ");", LOG_DEBUG);
1140
			$params_arr = explode(", ", $this->params);
1141
			if (!is_array($params_arr))
1 ignored issue
show
introduced by
The condition is_array($params_arr) is always true.
Loading history...
1142
			{
1143
				$result = call_user_func($this->methodename, $this->params);
1144
			}
1145
			else
1146
			{
1147
				$result = call_user_func_array($this->methodename, $params_arr);
1148
			}
1149
1150
			if ($result === false || (! is_bool($result) && $result != 0))
1151
			{
1152
			    $langs->load("errors");
1153
			    dol_syslog(get_class($this)."::run_jobs result=".$result, LOG_ERR);
1154
			    $this->error = $langs->trans('ErrorUnknown');
1155
			    $this->lastoutput = $this->error;
1156
			    $this->lastresult = is_numeric($result)?$result:-1;
1157
			    $retval = $this->lastresult;
1158
			    $error++;
1159
			}
1160
			else
1161
			{
1162
                $this->lastoutput=var_export($result, true);
1163
                $this->lastresult=var_export($result, true);	// Return code
1164
                $retval = $this->lastresult;
1165
			}
1166
		}
1167
1168
		// Run a command line
1169
		if ($this->jobtype=='command')
1170
		{
1171
			$outputdir = $conf->cron->dir_temp;
1172
			if (empty($outputdir)) $outputdir = $conf->cronjob->dir_temp;
1173
1174
			if (! empty($outputdir))
1175
			{
1176
				dol_mkdir($outputdir);
1177
				$outputfile=$outputdir.'/cronjob.'.$userlogin.'.out';	// File used with popen method
1178
1179
				// Execute a CLI
1180
				include_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
1181
				$utils = new Utils($this->db);
1182
				$arrayresult = $utils->executeCLI($this->command, $outputfile);
1183
1184
				$retval = $arrayresult['result'];
1185
				$this->error      = $arrayresult['error'];
1186
				$this->lastoutput = $arrayresult['output'];
1187
				$this->lastresult = $arrayresult['result'];
1188
			}
1189
		}
1190
1191
		dol_syslog(get_class($this)."::run_jobs now we update job to track it is finished (with success or error)");
1192
1193
		$this->datelastresult=dol_now();
1194
		$this->processing=0;
1195
		$result = $this->update($user);       // This include begin/commit
1196
		if ($result < 0)
1197
		{
1198
			dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1199
			$conf->entity = $savcurrententity;
1200
			return -1;
1201
		}
1202
1203
		$conf->entity = $savcurrententity;
1204
		return $error?-1:1;
1205
	}
1206
1207
1208
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1209
	/**
1210
	 * Reprogram a job
1211
	 *
1212
	 * @param  string		$userlogin      User login
1213
	 * @param  integer      $now            Date returned by dol_now()
1214
	 * @return int					        <0 if KO, >0 if OK
1215
	 */
1216
	public function reprogram_jobs($userlogin, $now)
1217
	{
1218
        // phpcs:enable
1219
		dol_syslog(get_class($this)."::reprogram_jobs userlogin:$userlogin", LOG_DEBUG);
1220
1221
		require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1222
		$user=new User($this->db);
1223
		$result=$user->fetch('', $userlogin);
1224
		if ($result<0)
1225
		{
1226
			$this->error="User Error : ".$user->error;
1227
			dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1228
			return -1;
1229
		}
1230
		else
1231
		{
1232
			if (empty($user->id))
1233
			{
1234
				$this->error=" User user login:".$userlogin." do not exists";
1235
				dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1236
				return -1;
1237
			}
1238
		}
1239
1240
		dol_syslog(get_class($this)."::reprogram_jobs datenextrun=".$this->datenextrun." ".dol_print_date($this->datenextrun, 'dayhourrfc')." frequency=".$this->frequency." unitfrequency=".$this->unitfrequency, LOG_DEBUG);
1241
1242
		if (empty($this->datenextrun))
1243
		{
1244
			if (empty($this->datestart)) $this->datenextrun = $now + ($this->frequency * $this->unitfrequency);
1245
			else $this->datenextrun = $this->datestart + ($this->frequency * $this->unitfrequency);
1246
		}
1247
1248
		if ($this->datenextrun < $now && $this->frequency > 0 && $this->unitfrequency > 0)
1249
		{
1250
		    // Loop until date is after future
1251
		    while ($this->datenextrun < $now)
1252
		    {
1253
		        $this->datenextrun += ($this->frequency * $this->unitfrequency);
1254
1255
		        // TODO For exact frequency (every month, every year, ...), use instead a dol_time_plus_duree($time, $duration_value, $duration_unit)
1256
		    }
1257
		}
1258
		else
1259
		{
1260
			//$this->datenextrun=$this->datenextrun + ($this->frequency * $this->unitfrequency);
1261
		    dol_syslog(get_class($this)."::reprogram_jobs datenextrun is already in future, we do not change it");
1262
		}
1263
1264
1265
		// Archive job
1266
		if ($this->autodelete == 2)
0 ignored issues
show
Bug Best Practice introduced by
The property autodelete does not exist on Cronjob. Did you maybe forget to declare it?
Loading history...
1267
		{
1268
		    if (($this->maxrun > 0 && ($this->nbrun >= $this->maxrun))
1269
		        || ($this->dateend && ($this->datenextrun > $this->dateend)))
1270
		    {
1271
		        $this->status = 2;
1272
		        dol_syslog(get_class($this)."::reprogram_jobs Job will be set to archived", LOG_ERR);
1273
		    }
1274
		}
1275
1276
		$result = $this->update($user);
1277
		if ($result<0)
1278
		{
1279
			dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1280
			return -1;
1281
		}
1282
1283
		return 1;
1284
	}
1285
1286
	/**
1287
	 *  Return label of status of user (active, inactive)
1288
	 *
1289
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1290
	 *  @return	string 			       Label of status
1291
	 */
1292
	public function getLibStatut($mode = 0)
1293
	{
1294
	    return $this->LibStatut($this->status, $mode, $this->processing);
1295
	}
1296
1297
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1298
	/**
1299
	 *  Renvoi le libelle d'un statut donne
1300
	 *
1301
	 *  @param	int		$status        	Id statut
1302
	 *  @param  int		$mode          	0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1303
	 *	@param	int		$processing		0=Not running, 1=Running
1304
	 *  @return string 			       	Label of status
1305
	 */
1306
    public function LibStatut($status, $mode = 0, $processing = 0)
1307
	{
1308
        // phpcs:enable
1309
        global $langs;
1310
	    $langs->load('users');
1311
1312
	    $moretext = '';
1313
	    if ($processing) $moretext=' ('.$langs->trans("Running").')';
1314
1315
	    if ($mode == 0)
1316
	    {
1317
	    	if ($status == 1) return $langs->trans('Enabled').$moretext;
1318
	    	elseif ($status == 0) return $langs->trans('Disabled').$moretext;
1319
	    }
1320
	    elseif ($mode == 1)
1321
	    {
1322
	    	if ($status == 1) return $langs->trans('Enabled').$moretext;
1323
	    	elseif ($status == 0) return $langs->trans('Disabled').$moretext;
1324
	    }
1325
	    elseif ($mode == 2)
1326
	    {
1327
	    	if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut'.($processing?'1':'4'), 'class="pictostatus"').' '.$langs->trans('Enabled').$moretext;
1328
	    	elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5', 'class="pictostatus"').' '.$langs->trans('Disabled').$moretext;
1329
	    }
1330
	    elseif ($mode == 3)
1331
	    {
1332
	    	if ($status == 1) return img_picto($langs->trans('Enabled').$moretext, 'statut'.($processing?'1':'4'), 'class="pictostatus"');
1333
	    	elseif ($status == 0) return img_picto($langs->trans('Disabled').$moretext, 'statut5', 'class="pictostatus"');
1334
	    }
1335
	    elseif ($mode == 4)
1336
	    {
1337
	    	if ($status == 1) return img_picto($langs->trans('Enabled').$moretext, 'statut'.($processing?'1':'4'), 'class="pictostatus"').' '.$langs->trans('Enabled').$moretext;
1338
	    	elseif ($status == 0) return img_picto($langs->trans('Disabled').$moretext, 'statut5', 'class="pictostatus"').' '.$langs->trans('Disabled').$moretext;
1339
	    }
1340
        elseif ($mode == 5)
1341
        {
1342
            if ($status == 1) return $langs->trans('Enabled').$moretext.' '.img_picto($langs->trans('Enabled').$moretext, 'statut'.($processing?'1':'4'), 'class="pictostatus"');
1343
            elseif ($status == 0) return $langs->trans('Disabled').$moretext.' '.img_picto($langs->trans('Disabled').$moretext, 'statut5', 'class="pictostatus"');
1344
        }
1345
    }
1346
}
1347
1348
1349
/**
1350
 *	Crob Job line class
1351
 */
1352
class Cronjobline
1353
{
1354
1355
	/**
1356
	 * @var int ID
1357
	 */
1358
	public $id;
1359
1360
	/**
1361
	 * @var string Ref
1362
	 */
1363
	public $ref;
1364
1365
	public $tms='';
1366
	public $datec='';
1367
1368
	/**
1369
     * @var string Cron Job Line label
1370
     */
1371
    public $label;
1372
1373
	public $jobtype;
1374
	public $command;
1375
	public $classesname;
1376
	public $objectname;
1377
	public $methodename;
1378
	public $params;
1379
	public $md5params;
1380
	public $module_name;
1381
	public $priority;
1382
	public $datelastrun='';
1383
	public $datenextrun='';
1384
	public $dateend='';
1385
	public $datestart='';
1386
	public $lastresult='';
1387
	public $lastoutput;
1388
	public $unitfrequency;
1389
	public $frequency;
1390
1391
	/**
1392
	 * @var int Status
1393
	 */
1394
	public $status;
1395
1396
	/**
1397
     * @var int ID
1398
     */
1399
	public $fk_user_author;
1400
1401
	/**
1402
     * @var int ID
1403
     */
1404
	public $fk_user_mod;
1405
1406
	public $note;
1407
	public $nbrun;
1408
	public $libname;
1409
1410
	/**
1411
	 *  Constructor
1412
	 *
1413
	 */
1414
	public function __construct()
1415
	{
1416
		return 1;
1417
	}
1418
}
1419