dolibarr 23.0.3
cronjob.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2007-2022 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
4 * Copyright (C) 2023-2024 William Mead <william.mead@manchenumerique.fr>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
27// Put here all includes required by your class file
28require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
29require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
30
31
35class Cronjob extends CommonObject
36{
40 public $element = 'cronjob';
41
45 public $table_element = 'cronjob';
46
50 public $picto = 'cron';
51
55 public $jobtype;
56
60 public $datec = '';
61
65 public $label;
66
70 public $command;
74 public $classesname;
78 public $objectname;
82 public $methodename;
86 public $params;
90 public $md5params;
94 public $module_name;
98 public $priority;
99
103 public $datelastrun = '';
104
108 public $datenextrun = '';
109
113 public $dateend = '';
114
118 public $datestart = '';
119
123 public $datelastresult = '';
124
128 public $lastresult;
129
133 public $lastoutput;
134
138 public $unitfrequency;
139
143 public $frequency;
144
148 public $status;
149
153 public $processing;
154
158 public $pid;
159
163 public $email_alert;
164
168 public $fk_user_author;
169
173 public $fk_user_mod;
174
178 public $nbrun;
179
183 public $maxrun;
184
188 public $libname;
189
193 public $test;
194
198 public $autodelete;
199
203 public $lines;
204
205
206 const STATUS_DISABLED = 0;
207 const STATUS_ENABLED = 1;
208 const STATUS_ARCHIVED = 2;
209 const MAXIMUM_LENGTH_FOR_LASTOUTPUT_FIELD = 65535;
210
211
255 // BEGIN MODULEBUILDER PROPERTIES
260 public $fields = array(
261 "rowid" => array("type" => "integer", "label" => "Ref", "enabled" => "1", 'position' => 10, 'notnull' => 1, "visible" => "1",),
262 "label" => array("type" => "varchar(255)", "label" => "Label", "enabled" => "1", 'position' => 30, 'notnull' => 1, "visible" => "1", "alwayseditable" => "1", "css" => "minwidth300", "cssview" => "wordbreak", "csslist" => "tdoverflowmax150",),
263 "params" => array("type" => "text", "label" => "Params", "enabled" => "1", 'position' => 55, 'notnull' => 0, "visible" => "0",),
264 "md5params" => array("type" => "varchar(32)", "label" => "Md5params", "enabled" => "1", 'position' => 60, 'notnull' => 0, "visible" => "0",),
265 "module_name" => array("type" => "varchar(255)", "label" => "Module", "enabled" => "1", 'position' => 65, 'notnull' => 0, "visible" => "1",),
266 "jobtype" => array("type" => "varchar(10)", "label" => "Type", "enabled" => "1", 'position' => 68, 'notnull' => 1, "visible" => "1",),
267 //"command" => array("type" => "varchar(255)", "label" => "Command", "enabled" => "1", 'position' => 35, 'notnull' => 0, "visible" => "-1",),
268 //"classesname" => array("type" => "varchar(255)", "label" => "Classesname", "enabled" => "1", 'position' => 40, 'notnull' => 0, "visible" => "-1",),
269 //"objectname" => array("type" => "varchar(255)", "label" => "Objectname", "enabled" => "1", 'position' => 45, 'notnull' => 0, "visible" => "-1",),
270 //"methodename" => array("type" => "varchar(255)", "label" => "Methodename", "enabled" => "1", 'position' => 50, 'notnull' => 0, "visible" => "-1",),
271 "priority" => array("type" => "integer", "label" => "Priority", "enabled" => "1", 'position' => 70, 'notnull' => 0, "visible" => "0",),
272 "datelastrun" => array("type" => "datetime", "label" => "Datelastrun", "enabled" => "1", 'position' => 75, 'notnull' => 0, "visible" => "-1",),
273 "datenextrun" => array("type" => "datetime", "label" => "Datenextrun", "enabled" => "1", 'position' => 80, 'notnull' => 0, "visible" => "1",),
274 //"datestart" => array("type" => "datetime", "label" => "Datestart", "enabled" => "1", 'position' => 85, 'notnull' => 0, "visible" => "0",),
275 //"dateend" => array("type" => "datetime", "label" => "Dateend", "enabled" => "1", 'position' => 90, 'notnull' => 0, "visible" => "0",),
276 "datelastresult" => array("type" => "datetime", "label" => "Datelastresult", "enabled" => "1", 'position' => 95, 'notnull' => 0, "visible" => "0",),
277 "lastresult" => array("type" => "text", "label" => "Lastresult", "enabled" => "1", 'position' => 100, 'notnull' => 0, "visible" => "1",),
278 "lastoutput" => array("type" => "text", "label" => "Lastoutput", "enabled" => "1", 'position' => 105, 'notnull' => 0, "visible" => "-1",),
279 //"frequency" => array("type" => "integer", "label" => "Frequency", "enabled" => "1", 'position' => 115, 'notnull' => 1, "visible" => "1",),
280 //"unitfrequency" => array("type" => "varchar(255)", "label" => "Unitfrequency", "enabled" => "1", 'position' => 116, 'notnull' => 1, "visible" => "1",),
281 "nbrun" => array("type" => "integer", "label" => "Nbrun", "enabled" => "1", 'position' => 120, 'notnull' => 0, "visible" => "1",),
282 "fk_user_author" => array("type" => "integer", "label" => "UserCreation", "picto" => "user", "enabled" => "1", 'position' => 130, 'notnull' => 0, "visible" => "-1", "css" => "maxwidth500 widthcentpercentminusxx",),
283 "fk_user_mod" => array("type" => "integer", "label" => "UserModification", "picto" => "user", "enabled" => "1", 'position' => 135, 'notnull' => 0, "visible" => "-1", "css" => "maxwidth500 widthcentpercentminusxx",),
284 "note" => array("type" => "text", "label" => "Note", "enabled" => "1", 'position' => 140, 'notnull' => 0, "visible" => "0",),
285 "libname" => array("type" => "varchar(255)", "label" => "Libname", "enabled" => "1", 'position' => 145, 'notnull' => 0, "visible" => "0",),
286 "maxrun" => array("type" => "integer", "label" => "Maxrun", "enabled" => "1", 'position' => 155, 'notnull' => 1, "visible" => "0",),
287 "autodelete" => array("type" => "integer", "label" => "Autodelete", "enabled" => "1", 'position' => 160, 'notnull' => 0, "visible" => "0",),
288 "fk_mailing" => array("type" => "integer", "label" => "Fkmailing", "enabled" => "1", 'position' => 165, 'notnull' => 0, "visible" => "0", "css" => "maxwidth500 widthcentpercentminusxx",),
289 "test" => array("type" => "varchar(255)", "label" => "Test", "enabled" => "1", 'position' => 170, 'notnull' => 0, "visible" => "0",),
290 "processing" => array("type" => "integer", "label" => "Processing", "enabled" => "1", 'position' => 175, 'notnull' => 1, "visible" => "0",),
291 "email_alert" => array("type" => "varchar(128)", "label" => "Emailalert", "enabled" => "1", 'position' => 180, 'notnull' => 0, "visible" => "0",),
292 "pid" => array("type" => "integer", "label" => "Pid", "enabled" => "1", 'position' => 185, 'notnull' => 0, "visible" => "0",),
293 "tms" => array("type" => "timestamp", "label" => "DateModification", "enabled" => "1", 'position' => 300, 'notnull' => 1, "visible" => "-1",),
294 "datec" => array("type" => "datetime", "label" => "DateCreation", "enabled" => "1", 'position' => 301, 'notnull' => 0, "visible" => "-1",),
295 "status" => array("type" => "integer", "label" => "Status", "enabled" => "1", 'position' => 500, 'notnull' => 1, "visible" => "1",),
296 );
297 // END MODULEBUILDER PROPERTIES
298
299
305 public function __construct(DoliDB $db)
306 {
307 $this->db = $db;
308 }
309
310
318 public function create(User $user, int $notrigger = 0)
319 {
320 global $conf, $langs;
321 $error = 0;
322
323 $now = dol_now();
324
325 // Clean parameters
326 if (isset($this->label)) {
327 $this->label = trim($this->label);
328 }
329 if (isset($this->jobtype)) {
330 $this->jobtype = trim($this->jobtype);
331 }
332 if (isset($this->command)) {
333 $this->command = trim($this->command);
334 }
335 if (isset($this->classesname)) {
336 $this->classesname = trim($this->classesname);
337 }
338 if (isset($this->objectname)) {
339 $this->objectname = trim($this->objectname);
340 }
341 if (isset($this->methodename)) {
342 $this->methodename = trim($this->methodename);
343 }
344 if (isset($this->params)) {
345 $this->params = trim($this->params);
346 }
347 if (isset($this->md5params)) {
348 $this->md5params = trim($this->md5params);
349 }
350 if (isset($this->module_name)) {
351 $this->module_name = trim($this->module_name);
352 }
353 if (isset($this->lastoutput)) {
354 $this->lastoutput = trim($this->lastoutput);
355 }
356 if (isset($this->lastresult)) {
357 $this->lastresult = trim($this->lastresult);
358 }
359 if (isset($this->unitfrequency)) {
360 $this->unitfrequency = trim($this->unitfrequency);
361 }
362 if (isset($this->frequency)) {
363 $this->frequency = (int) $this->frequency;
364 }
365 if (isset($this->status)) {
366 $this->status = (int) $this->status;
367 }
368 if (isset($this->note_private)) {
369 $this->note_private = trim($this->note_private);
370 }
371 if (isset($this->nbrun)) {
372 $this->nbrun = (int) $this->nbrun;
373 }
374 if (isset($this->maxrun)) {
375 $this->maxrun = (int) $this->maxrun;
376 }
377 if (isset($this->libname)) {
378 $this->libname = trim($this->libname);
379 }
380 if (isset($this->test)) {
381 $this->test = trim($this->test);
382 }
383
384 // Check parameters
385 // Put here code to add a control on parameters values
386 if (dol_strlen($this->datenextrun) == 0) {
387 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronDtNextLaunch'));
388 $error++;
389 }
390 if (empty($this->label)) {
391 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLabel'));
392 $error++;
393 }
394 if ((dol_strlen($this->datestart) != 0) && (dol_strlen($this->dateend) != 0) && ($this->dateend < $this->datestart)) {
395 $this->errors[] = $langs->trans('CronErrEndDateStartDt');
396 $error++;
397 }
398 if (empty($this->unitfrequency)) {
399 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronFrequency'));
400 $error++;
401 }
402 if (($this->jobtype == 'command') && (empty($this->command))) {
403 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronCommand'));
404 $error++;
405 }
406 if (($this->jobtype == 'method') && (empty($this->classesname))) {
407 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronClass'));
408 $error++;
409 }
410 if (($this->jobtype == 'method' || $this->jobtype == 'function') && (empty($this->methodename))) {
411 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronMethod'));
412 $error++;
413 }
414 if (($this->jobtype == 'method') && (empty($this->objectname))) {
415 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronObject'));
416 $error++;
417 }
418 if (($this->jobtype == 'function') && (empty($this->libname))) {
419 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLib'));
420 $error++;
421 }
422
423 // Insert request
424 $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob(";
425 $sql .= "entity,";
426 $sql .= "datec,";
427 $sql .= "jobtype,";
428 $sql .= "label,";
429 $sql .= "command,";
430 $sql .= "classesname,";
431 $sql .= "objectname,";
432 $sql .= "methodename,";
433 $sql .= "params,";
434 $sql .= "md5params,";
435 $sql .= "module_name,";
436 $sql .= "priority,";
437 $sql .= "datelastrun,";
438 $sql .= "datenextrun,";
439 $sql .= "dateend,";
440 $sql .= "datestart,";
441 $sql .= "lastresult,";
442 $sql .= "datelastresult,";
443 $sql .= "lastoutput,";
444 $sql .= "unitfrequency,";
445 $sql .= "frequency,";
446 $sql .= "status,";
447 $sql .= "fk_user_author,";
448 $sql .= "fk_user_mod,";
449 $sql .= "note,";
450 $sql .= "nbrun,";
451 $sql .= "maxrun,";
452 $sql .= "libname,";
453 $sql .= "test";
454 $sql .= ") VALUES (";
455 $sql .= " ".(!isset($this->entity) ? (int) $conf->entity : (int) $this->entity).",";
456 $sql .= " '".$this->db->idate($now)."',";
457 $sql .= " ".(!isset($this->jobtype) ? 'NULL' : "'".$this->db->escape($this->jobtype)."'").",";
458 $sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").",";
459 $sql .= " ".(!isset($this->command) ? 'NULL' : "'".$this->db->escape($this->command)."'").",";
460 $sql .= " ".(!isset($this->classesname) ? 'NULL' : "'".$this->db->escape($this->classesname)."'").",";
461 $sql .= " ".(!isset($this->objectname) ? 'NULL' : "'".$this->db->escape($this->objectname)."'").",";
462 $sql .= " ".(!isset($this->methodename) ? 'NULL' : "'".$this->db->escape($this->methodename)."'").",";
463 $sql .= " ".(!isset($this->params) ? 'NULL' : "'".$this->db->escape($this->params)."'").",";
464 $sql .= " ".(!isset($this->md5params) ? 'NULL' : "'".$this->db->escape($this->md5params)."'").",";
465 $sql .= " ".(!isset($this->module_name) ? 'NULL' : "'".$this->db->escape($this->module_name)."'").",";
466 $sql .= " ".(is_numeric($this->priority) ? (int) $this->priority : 50).",";
467 $sql .= " ".(!isset($this->datelastrun) || dol_strlen($this->datelastrun) == 0 ? 'NULL' : "'".$this->db->idate($this->datelastrun)."'").",";
468 $sql .= " ".(!isset($this->datenextrun) || dol_strlen($this->datenextrun) == 0 ? 'NULL' : "'".$this->db->idate($this->datenextrun)."'").",";
469 $sql .= " ".(!isset($this->dateend) || dol_strlen($this->dateend) == 0 ? 'NULL' : "'".$this->db->idate($this->dateend)."'").",";
470 $sql .= " ".(!isset($this->datestart) || dol_strlen($this->datestart) == 0 ? 'NULL' : "'".$this->db->idate($this->datestart)."'").",";
471 $sql .= " ".(!isset($this->lastresult) ? 'NULL' : "'".$this->db->escape($this->lastresult)."'").",";
472 $sql .= " ".(!isset($this->datelastresult) || dol_strlen($this->datelastresult) == 0 ? 'NULL' : "'".$this->db->idate($this->datelastresult)."'").",";
473 $sql .= " ".(!isset($this->lastoutput) ? 'NULL' : "'".$this->db->escape($this->lastoutput)."'").",";
474 $sql .= " ".(!isset($this->unitfrequency) ? 'NULL' : "'".$this->db->escape($this->unitfrequency)."'").",";
475 $sql .= " ".(!isset($this->frequency) ? '0' : ((int) $this->frequency)).",";
476 $sql .= " ".(!isset($this->status) ? '0' : ((int) $this->status)).",";
477 $sql .= " ".($user->id ? (int) $user->id : "NULL").",";
478 $sql .= " ".($user->id ? (int) $user->id : "NULL").",";
479 $sql .= " ".(!isset($this->note_private) ? 'NULL' : "'".$this->db->escape($this->note_private)."'").",";
480 $sql .= " ".(!isset($this->nbrun) ? '0' : ((int) $this->nbrun)).",";
481 $sql .= " ".(empty($this->maxrun) ? '0' : ((int) $this->maxrun)).",";
482 $sql .= " ".(!isset($this->libname) ? 'NULL' : "'".$this->db->escape($this->libname)."'").",";
483 $sql .= " ".(!isset($this->test) ? 'NULL' : "'".$this->db->escape($this->test)."'");
484 $sql .= ")";
485
486 $this->db->begin();
487
488 dol_syslog(get_class($this)."::create", LOG_DEBUG);
489 $resql = $this->db->query($sql);
490 if (!$resql) {
491 $error++;
492 $this->errors[] = "Error ".$this->db->lasterror();
493 }
494
495 if (!$error) {
496 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."cronjob");
497 }
498
499 // Commit or rollback
500 if ($error) {
501 $this->db->rollback();
502 return -1 * $error;
503 } else {
504 $this->db->commit();
505 return $this->id;
506 }
507 }
508
509
519 public function fetch(int $id, string $objectname = '', string $methodname = '', string $label = '')
520 {
521 $sql = "SELECT";
522 $sql .= " t.rowid,";
523 $sql .= " t.entity,";
524 $sql .= " t.tms,";
525 $sql .= " t.datec,";
526 $sql .= " t.jobtype,";
527 $sql .= " t.label,";
528 $sql .= " t.command,";
529 $sql .= " t.classesname,";
530 $sql .= " t.objectname,";
531 $sql .= " t.methodename,";
532 $sql .= " t.params,";
533 $sql .= " t.md5params,";
534 $sql .= " t.module_name,";
535 $sql .= " t.priority,";
536 $sql .= " t.datelastrun,";
537 $sql .= " t.datenextrun,";
538 $sql .= " t.dateend,";
539 $sql .= " t.datestart,";
540 $sql .= " t.lastresult,";
541 $sql .= " t.datelastresult,";
542 $sql .= " t.lastoutput,";
543 $sql .= " t.unitfrequency,";
544 $sql .= " t.frequency,";
545 $sql .= " t.status,";
546 $sql .= " t.processing,";
547 $sql .= " t.pid,";
548 $sql .= " t.email_alert,";
549 $sql .= " t.fk_user_author,";
550 $sql .= " t.fk_user_mod,";
551 $sql .= " t.note as note_private,";
552 $sql .= " t.nbrun,";
553 $sql .= " t.maxrun,";
554 $sql .= " t.libname,";
555 $sql .= " t.test";
556 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t";
557 if ($id > 0) {
558 $sql .= " WHERE t.rowid = ".((int) $id);
559 } elseif ($label) {
560 $sql .= " WHERE t.entity IN(0, ".getEntity('cron').")";
561 $sql .= " AND t.label = '".$this->db->escape($label)."'";
562 } else {
563 $sql .= " WHERE t.entity IN(0, ".getEntity('cron').")";
564 $sql .= " AND t.objectname = '".$this->db->escape($objectname)."'";
565 $sql .= " AND t.methodename = '".$this->db->escape($methodname)."'";
566 }
567
568 $resql = $this->db->query($sql);
569 if ($resql) {
570 if ($this->db->num_rows($resql)) {
571 $obj = $this->db->fetch_object($resql);
572
573 $this->id = $obj->rowid;
574 $this->ref = $obj->rowid;
575 $this->entity = $obj->entity;
576 $this->tms = $this->db->jdate($obj->tms);
577 $this->date_modification = $this->db->jdate($obj->tms);
578 $this->datec = $this->db->jdate($obj->datec);
579 $this->label = $obj->label;
580 $this->jobtype = $obj->jobtype;
581 $this->command = $obj->command;
582 $this->classesname = $obj->classesname;
583 $this->objectname = $obj->objectname;
584 $this->methodename = $obj->methodename;
585 $this->params = $obj->params;
586 $this->md5params = $obj->md5params;
587 $this->module_name = $obj->module_name;
588 $this->priority = $obj->priority;
589 $this->datelastrun = $this->db->jdate($obj->datelastrun);
590 $this->datenextrun = $this->db->jdate($obj->datenextrun);
591 $this->dateend = $this->db->jdate($obj->dateend);
592 $this->datestart = $this->db->jdate($obj->datestart);
593 $this->lastresult = (string) $obj->lastresult;
594 $this->lastoutput = $obj->lastoutput;
595 $this->datelastresult = $this->db->jdate($obj->datelastresult);
596 $this->unitfrequency = $obj->unitfrequency;
597 $this->frequency = $obj->frequency;
598 $this->status = $obj->status;
599 $this->processing = $obj->processing;
600 $this->pid = $obj->pid;
601 $this->email_alert = $obj->email_alert;
602 $this->fk_user_author = $obj->fk_user_author;
603 $this->fk_user_mod = $obj->fk_user_mod;
604 $this->note_private = $obj->note_private;
605 $this->nbrun = $obj->nbrun;
606 $this->maxrun = $obj->maxrun;
607 $this->libname = $obj->libname;
608 $this->test = $obj->test;
609 }
610 $this->db->free($resql);
611
612 return 1;
613 } else {
614 $this->error = "Error ".$this->db->lasterror();
615 return -1;
616 }
617 }
618
631 public function fetchAll(string $sortorder = 'DESC', string $sortfield = 't.rowid', int $limit = 0, int $offset = 0, int $status = 1, $filter = '', int $processing = -1)
632 {
633 $this->lines = array();
634
635 $sql = "SELECT";
636 $sql .= " t.rowid,";
637 $sql .= " t.entity,";
638 $sql .= " t.tms,";
639 $sql .= " t.datec,";
640 $sql .= " t.jobtype,";
641 $sql .= " t.label,";
642 $sql .= " t.command,";
643 $sql .= " t.classesname,";
644 $sql .= " t.objectname,";
645 $sql .= " t.methodename,";
646 $sql .= " t.params,";
647 $sql .= " t.md5params,";
648 $sql .= " t.module_name,";
649 $sql .= " t.priority,";
650 $sql .= " t.datelastrun,";
651 $sql .= " t.datenextrun,";
652 $sql .= " t.dateend,";
653 $sql .= " t.datestart,";
654 $sql .= " t.lastresult,";
655 $sql .= " t.datelastresult,";
656 $sql .= " t.lastoutput,";
657 $sql .= " t.unitfrequency,";
658 $sql .= " t.frequency,";
659 $sql .= " t.status,";
660 $sql .= " t.processing,";
661 $sql .= " t.pid,";
662 $sql .= " t.email_alert,";
663 $sql .= " t.fk_user_author,";
664 $sql .= " t.fk_user_mod,";
665 $sql .= " t.note as note_private,";
666 $sql .= " t.nbrun,";
667 $sql .= " t.maxrun,";
668 $sql .= " t.libname,";
669 $sql .= " t.test";
670 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t";
671 $sql .= " WHERE 1 = 1";
672 if ($processing >= 0) {
673 $sql .= " AND t.processing = ".(empty($processing) ? '0' : '1');
674 }
675 if ($status >= 0 && $status < 2) {
676 $sql .= " AND t.status = ".(empty($status) ? '0' : '1');
677 } elseif ($status == 2) {
678 $sql .= " AND t.status = 2";
679 }
680
681 // Manage filter
682 if (is_array($filter)) {
683 if (count($filter) > 0) {
684 foreach ($filter as $key => $value) {
685 if ($key == 't.rowid') {
686 $sql .= " AND ".$this->db->sanitize($key)." = ".((int) $value);
687 } else {
688 $sql .= " AND ".$this->db->sanitize($key)." LIKE '%".$this->db->escape($this->db->escapeforlike($value))."%'";
689 }
690 }
691 }
692
693 $filter = '';
694 }
695
696 // Manage filter
697 $errormessage = '';
698 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
699 if ($errormessage) {
700 $this->errors[] = $errormessage;
701 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
702 return -1;
703 }
704
705 $sql .= $this->db->order($sortfield, $sortorder);
706 if (!empty($limit) && !empty($offset)) {
707 $sql .= $this->db->plimit($limit + 1, $offset);
708 }
709
710 dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
711 $resql = $this->db->query($sql);
712 if ($resql) {
713 $num = $this->db->num_rows($resql);
714 $i = 0;
715
716 if ($num) {
717 while ($i < $num) {
718 $obj = $this->db->fetch_object($resql);
719 $cronjob_obj = new Cronjob($this->db);
720
721 $cronjob_obj->id = $obj->rowid;
722 $cronjob_obj->ref = $obj->rowid;
723 $cronjob_obj->entity = $obj->entity;
724 $cronjob_obj->tms = $this->db->jdate($obj->tms);
725 $cronjob_obj->datec = $this->db->jdate($obj->datec);
726 $cronjob_obj->label = $obj->label;
727 $cronjob_obj->jobtype = $obj->jobtype;
728 $cronjob_obj->command = $obj->command;
729 $cronjob_obj->classesname = $obj->classesname;
730 $cronjob_obj->objectname = $obj->objectname;
731 $cronjob_obj->methodename = $obj->methodename;
732 $cronjob_obj->params = $obj->params;
733 $cronjob_obj->md5params = $obj->md5params;
734 $cronjob_obj->module_name = $obj->module_name;
735 $cronjob_obj->priority = $obj->priority;
736 $cronjob_obj->datelastrun = $this->db->jdate($obj->datelastrun);
737 $cronjob_obj->datenextrun = $this->db->jdate($obj->datenextrun);
738 $cronjob_obj->dateend = $this->db->jdate($obj->dateend);
739 $cronjob_obj->datestart = $this->db->jdate($obj->datestart);
740 $cronjob_obj->lastresult = $obj->lastresult;
741 $cronjob_obj->lastoutput = $obj->lastoutput;
742 $cronjob_obj->datelastresult = $this->db->jdate($obj->datelastresult);
743 $cronjob_obj->unitfrequency = $obj->unitfrequency;
744 $cronjob_obj->frequency = $obj->frequency;
745 $cronjob_obj->status = $obj->status;
746 $cronjob_obj->processing = $obj->processing;
747 $cronjob_obj->pid = $obj->pid;
748 $cronjob_obj->email_alert = $obj->email_alert;
749 $cronjob_obj->fk_user_author = $obj->fk_user_author;
750 $cronjob_obj->fk_user_mod = $obj->fk_user_mod;
751 $cronjob_obj->note_private = $obj->note_private;
752 $cronjob_obj->nbrun = $obj->nbrun;
753 $cronjob_obj->maxrun = $obj->maxrun;
754 $cronjob_obj->libname = $obj->libname;
755 $cronjob_obj->test = $obj->test;
756
757 $this->lines[] = $cronjob_obj;
758
759 $i++;
760 }
761 }
762 $this->db->free($resql);
763
764 return 1;
765 } else {
766 $this->error = "Error ".$this->db->lasterror();
767 return -1;
768 }
769 }
770
771
779 public function update($user = null, int $notrigger = 0)
780 {
781 global $conf, $langs;
782
783 $langs->load('cron');
784
785 $error = 0;
786
787 // Clean parameters
788 if (isset($this->label)) {
789 $this->label = trim($this->label);
790 }
791 if (isset($this->jobtype)) {
792 $this->jobtype = trim($this->jobtype);
793 }
794 if (isset($this->command)) {
795 $this->command = trim($this->command);
796 }
797 if (isset($this->classesname)) {
798 $this->classesname = trim($this->classesname);
799 }
800 if (isset($this->objectname)) {
801 $this->objectname = trim($this->objectname);
802 }
803 if (isset($this->methodename)) {
804 $this->methodename = trim($this->methodename);
805 }
806 if (isset($this->params)) {
807 $this->params = trim($this->params);
808 }
809 if (isset($this->md5params)) {
810 $this->md5params = trim($this->md5params);
811 }
812 if (isset($this->module_name)) {
813 $this->module_name = trim($this->module_name);
814 }
815 if (isset($this->priority)) {
816 $this->priority = trim($this->priority);
817 }
818 if (isset($this->lastoutput)) {
819 $this->lastoutput = trim($this->lastoutput);
820 }
821 if (isset($this->lastresult)) {
822 $this->lastresult = trim($this->lastresult);
823 }
824 if (isset($this->unitfrequency)) {
825 $this->unitfrequency = trim($this->unitfrequency);
826 }
827 if (isset($this->frequency)) {
828 $this->frequency = (int) $this->frequency;
829 }
830 if (isset($this->status)) {
831 $this->status = (int) $this->status;
832 }
833 if (isset($this->note_private)) {
834 $this->note_private = trim($this->note_private);
835 }
836 if (isset($this->nbrun)) {
837 $this->nbrun = (is_numeric($this->nbrun)) ? (int) trim((string) $this->nbrun) : 0;
838 }
839 if (isset($this->libname)) {
840 $this->libname = trim($this->libname);
841 }
842 if (isset($this->test)) {
843 $this->test = trim($this->test);
844 }
845
846 if (empty($this->maxrun)) {
847 $this->maxrun = 0;
848 }
849 if (empty($this->processing)) {
850 $this->processing = 0;
851 }
852 if (empty($this->pid)) {
853 $this->pid = null;
854 }
855 if (empty($this->email_alert)) {
856 $this->email_alert = '';
857 }
858 if (empty($this->datenextrun)) {
859 $this->datenextrun = dol_now();
860 }
861
862 // Check parameters
863 // Put here code to add a control on parameters values
864 if (dol_strlen($this->datenextrun) == 0 && $this->status == self::STATUS_ENABLED) {
865 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronDtNextLaunch'));
866 $error++;
867 }
868 if ((dol_strlen($this->datestart) != 0) && (dol_strlen($this->dateend) != 0) && ($this->dateend < $this->datestart)) {
869 $this->errors[] = $langs->trans('CronErrEndDateStartDt');
870 $error++;
871 }
872 if (empty($this->label)) {
873 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLabel'));
874 $error++;
875 }
876 if (empty($this->unitfrequency)) {
877 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronFrequency'));
878 $error++;
879 }
880 if (($this->jobtype == 'command') && (empty($this->command))) {
881 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronCommand'));
882 $error++;
883 }
884 if (($this->jobtype == 'method') && (empty($this->classesname))) {
885 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronClass'));
886 $error++;
887 }
888 if (($this->jobtype == 'method' || $this->jobtype == 'function') && (empty($this->methodename))) {
889 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronMethod'));
890 $error++;
891 }
892 if (($this->jobtype == 'method') && (empty($this->objectname))) {
893 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronObject'));
894 $error++;
895 }
896
897 if (($this->jobtype == 'function') && (empty($this->libname))) {
898 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLib'));
899 $error++;
900 }
901
902
903 // Update request
904 $sql = "UPDATE ".MAIN_DB_PREFIX."cronjob SET";
905 $sql .= " entity=".(isset($this->entity) ? ((int) $this->entity) : $conf->entity).",";
906 $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
907 $sql .= " jobtype=".(isset($this->jobtype) ? "'".$this->db->escape($this->jobtype)."'" : "null").",";
908 $sql .= " command=".(isset($this->command) ? "'".$this->db->escape($this->command)."'" : "null").",";
909 $sql .= " classesname=".(isset($this->classesname) ? "'".$this->db->escape($this->classesname)."'" : "null").",";
910 $sql .= " objectname=".(isset($this->objectname) ? "'".$this->db->escape($this->objectname)."'" : "null").",";
911 $sql .= " methodename=".(isset($this->methodename) ? "'".$this->db->escape($this->methodename)."'" : "null").",";
912 $sql .= " params=".(isset($this->params) ? "'".$this->db->escape($this->params)."'" : "null").",";
913 $sql .= " md5params=".(isset($this->md5params) ? "'".$this->db->escape($this->md5params)."'" : "null").",";
914 $sql .= " module_name=".(isset($this->module_name) ? "'".$this->db->escape($this->module_name)."'" : "null").",";
915 $sql .= " priority=".(isset($this->priority) ? ((int) $this->priority) : "null").",";
916 $sql .= " datelastrun=".(dol_strlen($this->datelastrun) != 0 ? "'".$this->db->idate($this->datelastrun)."'" : 'null').",";
917 $sql .= " datenextrun=".(dol_strlen($this->datenextrun) != 0 ? "'".$this->db->idate($this->datenextrun)."'" : 'null').",";
918 $sql .= " dateend=".(dol_strlen($this->dateend) != 0 ? "'".$this->db->idate($this->dateend)."'" : 'null').",";
919 $sql .= " datestart=".(dol_strlen($this->datestart) != 0 ? "'".$this->db->idate($this->datestart)."'" : 'null').",";
920 $sql .= " datelastresult=".(dol_strlen($this->datelastresult) != 0 ? "'".$this->db->idate($this->datelastresult)."'" : 'null').",";
921 $sql .= " lastresult=".(isset($this->lastresult) ? "'".$this->db->escape($this->lastresult)."'" : "null").",";
922 $sql .= " lastoutput=".(isset($this->lastoutput) ? "'".$this->db->escape($this->lastoutput)."'" : "null").",";
923 $sql .= " unitfrequency=".(isset($this->unitfrequency) ? "'".$this->db->escape($this->unitfrequency)."'" : "null").",";
924 $sql .= " frequency=".(isset($this->frequency) ? ((int) $this->frequency) : "null").",";
925 $sql .= " status=".(isset($this->status) ? ((int) $this->status) : "null").",";
926 $sql .= " processing=".((isset($this->processing) && $this->processing > 0) ? $this->processing : "0").",";
927 $sql .= " pid=".(isset($this->pid) ? ((int) $this->pid) : "null").",";
928 $sql .= " email_alert = ".(isset($this->email_alert) ? "'".$this->db->escape($this->email_alert)."'" : "null").",";
929 $sql .= " fk_user_mod = ".((int) $user->id).",";
930 $sql .= " note=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
931 $sql .= " nbrun=".((isset($this->nbrun) && $this->nbrun > 0) ? $this->nbrun : "null").",";
932 $sql .= " maxrun=".((isset($this->maxrun) && $this->maxrun > 0) ? $this->maxrun : "0").",";
933 $sql .= " libname=".(isset($this->libname) ? "'".$this->db->escape($this->libname)."'" : "null").",";
934 $sql .= " test=".(isset($this->test) ? "'".$this->db->escape($this->test)."'" : "null");
935 $sql .= " WHERE rowid=".((int) $this->id);
936
937 $this->db->begin();
938
939 dol_syslog(get_class($this)."::update", LOG_DEBUG);
940 $resql = $this->db->query($sql);
941 if (!$resql) {
942 $error++;
943 $this->errors[] = "Error ".$this->db->lasterror();
944 }
945
946 // Commit or rollback
947 if ($error) {
948 foreach ($this->errors as $errmsg) {
949 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
950 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
951 }
952 $this->db->rollback();
953 return -1 * $error;
954 } else {
955 $this->db->commit();
956 return 1;
957 }
958 }
959
960
968 public function delete(User $user, int $notrigger = 0)
969 {
970 $error = 0;
971
972 $this->db->begin();
973
974 $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
975 $sql .= " WHERE rowid=".((int) $this->id);
976
977 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
978 $resql = $this->db->query($sql);
979 if (!$resql) {
980 $error++;
981 $this->errors[] = "Error ".$this->db->lasterror();
982 }
983
984 // Commit or rollback
985 if ($error) {
986 foreach ($this->errors as $errmsg) {
987 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
988 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
989 }
990 $this->db->rollback();
991 return -1 * $error;
992 } else {
993 $this->db->commit();
994 return 1;
995 }
996 }
997
998
999
1007 public function createFromClone(User $user, int $fromid)
1008 {
1009 global $langs;
1010
1011 $error = 0;
1012
1013 $object = new Cronjob($this->db);
1014
1015 $this->db->begin();
1016
1017 // Load source object
1018 $object->fetch($fromid);
1019 $object->id = 0;
1020
1021 // Clear fields
1022 $object->status = self::STATUS_DISABLED;
1023 $object->label = $langs->trans("CopyOf").' '.$langs->trans($object->label);
1024 $object->datelastrun = null;
1025 $object->lastresult = '';
1026 $object->datelastresult = null;
1027 $object->datenextrun = dol_now();
1028 $object->lastoutput = '';
1029 $object->nbrun = 0;
1030
1031 // Create clone
1032 $object->context['createfromclone'] = 'createfromclone';
1033 $result = $object->create($user);
1034
1035 // Other options
1036 if ($result < 0) {
1037 $this->error = $object->error;
1038 $this->errors = $object->errors;
1039 $error++;
1040 }
1041
1042 unset($object->context['createfromclone']);
1043
1044 // End
1045 if (!$error) {
1046 $this->db->commit();
1047 return $object->id;
1048 } else {
1049 $this->db->rollback();
1050 return -1;
1051 }
1052 }
1053
1054
1061 public function initAsSpecimen()
1062 {
1063 $this->id = 0;
1064 $this->ref = '';
1065 $this->entity = 0;
1066 $this->date_modification = dol_now();
1067 $this->datec = '';
1068 $this->label = '';
1069 $this->jobtype = '';
1070 $this->command = '';
1071 $this->classesname = '';
1072 $this->objectname = '';
1073 $this->methodename = '';
1074 $this->params = '';
1075 $this->md5params = '';
1076 $this->module_name = '';
1077 $this->priority = '';
1078 $this->datelastrun = '';
1079 $this->datenextrun = '';
1080 $this->dateend = '';
1081 $this->datestart = '';
1082 $this->datelastresult = '';
1083 $this->lastoutput = '';
1084 $this->lastresult = '';
1085 $this->unitfrequency = '86400';
1086 $this->frequency = 0;
1087 $this->status = 0;
1088 $this->processing = 0;
1089 $this->pid = null;
1090 $this->email_alert = '';
1091 $this->fk_user_author = 0;
1092 $this->fk_user_mod = 0;
1093 $this->note_private = '';
1094 $this->nbrun = 0;
1095 $this->maxrun = 100;
1096 $this->libname = '';
1097
1098 return 1;
1099 }
1100
1101
1108 public function getTooltipContentArray($params)
1109 {
1110 global $langs;
1111
1112 $langs->load('cron');
1113 $datas = [];
1114
1115 $datas['picto'] = img_picto('', 'object_'.$this->picto).' <u>'.$langs->trans("CronTask").'</u>';
1116 if (isset($this->status)) {
1117 $datas['picto'] .= ' '.$this->getLibStatut(5);
1118 }
1119 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.dol_escape_htmltag($this->ref);
1120 $datas['label'] = '<br><b>'.$langs->trans('Title').':</b> '.$langs->trans($this->label);
1121 if ($this->label != $langs->trans($this->label)) {
1122 $datas['label'] .= ' <span class="opacitymedium">('.$this->label.')</span>';
1123 }
1124 if (!empty($this->params)) {
1125 $datas['params'] = '<br><b>'.$langs->trans('Parameters').':</b> '.dol_escape_htmltag($this->params);
1126 }
1127 $datas['space'] = '<br>';
1128
1129 if (!empty($this->datestart) && $this->datestart >= dol_now()) {
1130 $datas['crondtstart'] = '<br><b>'.$langs->trans('CronDtStart').':</b> '.dol_print_date($this->datestart, 'dayhour', 'tzuserrel');
1131 }
1132 if (!empty($this->dateend)) {
1133 $datas['crondtend'] = '<br><b>'.$langs->trans('CronDtEnd').':</b> '.dol_print_date($this->dateend, 'dayhour', 'tzuserrel');
1134 }
1135 if (!empty($this->datelastrun)) {
1136 $datas['cronlastlaunch'] = '<br><b>'.$langs->trans('CronDtLastLaunch').':</b> '.dol_print_date($this->datelastrun, 'dayhour', 'tzuserrel');
1137 }
1138 if (!empty($this->datenextrun)) {
1139 $datas['crondtnextlaunch'] = '<br><b>'.$langs->trans('CronDtNextLaunch').':</b> '.dol_print_date($this->datenextrun, 'dayhour', 'tzuserrel');
1140 }
1141
1142 return $datas;
1143 }
1144
1155 public function getNomUrl($withpicto = 0, string $option = '', int $notooltip = 0, string $morecss = '', int $save_lastsearch_value = -1)
1156 {
1157 global $conf, $langs;
1158
1159 if (!empty($conf->dol_no_mouse_hover)) {
1160 $notooltip = 1; // Force disable tooltips
1161 }
1162
1163 $result = '';
1164
1165 $params = [
1166 'id' => $this->id,
1167 'objecttype' => $this->element,
1168 ];
1169 $classfortooltip = 'classfortooltip';
1170 $dataparams = '';
1171 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1172 $classfortooltip = 'classforajaxtooltip';
1173 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1174 $label = '';
1175 } else {
1176 $label = implode($this->getTooltipContentArray($params));
1177 }
1178
1179 $url = DOL_URL_ROOT.'/cron/card.php?id='.$this->id;
1180
1181 if ($option != 'nolink') {
1182 // Add param to save lastsearch_values or not
1183 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1184 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1185 $add_save_lastsearch_values = 1;
1186 }
1187 if ($add_save_lastsearch_values) {
1188 $url .= '&save_lastsearch_values=1';
1189 }
1190 }
1191
1192 $linkclose = '';
1193 if (empty($notooltip)) {
1194 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1195 $label = $langs->trans("ShowCronJob");
1196 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1197 }
1198 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1199 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1200 } else {
1201 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1202 }
1203
1204 $linkstart = '<a href="'.$url.'"';
1205 $linkstart .= $linkclose.'>';
1206 $linkend = '</a>';
1207
1208 $result .= $linkstart;
1209 if ($withpicto) {
1210 $result .= img_object(($notooltip ? '' : $label), ($this->picto ?: 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1211 }
1212 if ($withpicto != 2) {
1213 $result .= $this->ref;
1214 }
1215 $result .= $linkend;
1216 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1217
1218 return $result;
1219 }
1220
1221
1228 public function info(int $id)
1229 {
1230 $sql = "SELECT";
1231 $sql .= " f.rowid, f.datec, f.tms, f.fk_user_mod, f.fk_user_author";
1232 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as f";
1233 $sql .= " WHERE f.rowid = ".((int) $id);
1234
1235 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1236 $resql = $this->db->query($sql);
1237 if ($resql) {
1238 if ($this->db->num_rows($resql)) {
1239 $obj = $this->db->fetch_object($resql);
1240
1241 $this->id = $obj->rowid;
1242
1243 $this->user_modification_id = $obj->fk_user_mod;
1244 $this->user_creation_id = $obj->fk_user_author;
1245 $this->date_creation = $this->db->jdate($obj->datec);
1246 $this->date_modification = $this->db->jdate($obj->tms);
1247 }
1248 $this->db->free($resql);
1249
1250 return 1;
1251 } else {
1252 $this->error = "Error ".$this->db->lasterror();
1253 return -1;
1254 }
1255 }
1256
1257
1258 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1267 public function run_jobs(string $userlogin)
1268 {
1269 // phpcs:enable
1270 global $langs, $conf, $hookmanager;
1271
1272 $hookmanager->initHooks(array('cron'));
1273
1274 $now = dol_now();
1275 $error = 0;
1276
1277 $langs->load('cron');
1278
1279 if (empty($userlogin)) {
1280 $this->error = "User login is mandatory";
1281 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1282 return -1;
1283 }
1284
1285 // Force the environment of running to the environment declared for job, so jobs launched from command line will run into correct environment
1286 // When job is ran from GUI, the environment should already be same, except if job has entity 0 (visible into all environments)
1287 if ($conf->entity != $this->entity && $this->entity > 0) {
1288 dol_syslog("We try to run a job in entity ".$this->entity." when we are in entity ".$conf->entity, LOG_WARNING);
1289 }
1290 $savcurrententity = $conf->entity;
1291 $conf->setEntityValues($this->db, $this->entity);
1292 dol_syslog(get_class($this)."::run_jobs entity for running job is ".$conf->entity);
1293
1294 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1295 $user = new User($this->db);
1296 $result = $user->fetch(0, $userlogin);
1297 if ($result < 0) {
1298 $this->error = "User Error:".$user->error;
1299 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1300 $conf->setEntityValues($this->db, $savcurrententity);
1301 return -1;
1302 } else {
1303 if (empty($user->id)) {
1304 $this->error = "User login: ".$userlogin." does not exist";
1305 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1306 $conf->setEntityValues($this->db, $savcurrententity);
1307 return -1;
1308 }
1309 }
1310
1311 dol_syslog(get_class($this)."::run_jobs jobtype=".$this->jobtype." userlogin=".$userlogin, LOG_DEBUG);
1312
1313 // Increase limit of time. Works only if we are not in safe mode
1314 $ExecTimeLimit = getDolGlobalInt('MAIN_CRON_EXEC_TIME_LIMIT', 600);
1315 if (!empty($ExecTimeLimit)) {
1316 $err = error_reporting();
1317 error_reporting(0); // Disable all errors
1318 //error_reporting(E_ALL);
1319 @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
1320 error_reporting($err);
1321 }
1322 $MemoryLimit = getDolGlobalString('MAIN_CRON_MEMORY_LIMIT');
1323 if (!empty($MemoryLimit)) {
1324 @ini_set('memory_limit', $MemoryLimit);
1325 }
1326
1327 // Update last run date start (to track running jobs)
1328 $this->datelastrun = $now;
1329 $this->datelastresult = null;
1330 $this->lastoutput = '';
1331 $this->lastresult = '';
1332 $this->processing = 1; // To know job was started
1333 $this->pid = function_exists('getmypid') ? getmypid() : null; // Avoid dol_getmypid to get null if the function is not available
1334 $this->nbrun += 1;
1335 $result = $this->update($user); // This include begin/commit
1336 if ($result < 0) {
1337 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1338 $conf->setEntityValues($this->db, $savcurrententity);
1339 return -1;
1340 }
1341
1342 // Run a method
1343 if ($this->jobtype == 'method') {
1344 // Deny to launch a method from a deactivated module
1345 if (!empty($this->entity) && !empty($this->module_name) && !isModEnabled(strtolower($this->module_name))) {
1346 $this->error = $langs->transnoentitiesnoconv('CronModuleNotEnabledInThisEntity', $this->methodename, $this->objectname);
1347 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1348 $this->lastoutput = $this->error;
1349 $this->lastresult = '-1';
1350 $error++;
1351 }
1352
1353 // load classes
1354 if (!$error) {
1355 $ret = dol_include_once($this->classesname);
1356 if ($ret === false || (!class_exists($this->objectname))) {
1357 if ($ret === false) {
1358 $this->error = $langs->transnoentitiesnoconv('CronCannotLoadClass', $this->classesname, $this->objectname);
1359 } else {
1360 $this->error = $langs->transnoentitiesnoconv('CronCannotLoadObject', $this->classesname, $this->objectname);
1361 }
1362 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1363 $this->lastoutput = $this->error;
1364 $this->lastresult = '-1';
1365 $error++;
1366 }
1367 }
1368
1369 // test if method exists
1370 if (!$error) {
1371 if (!method_exists($this->objectname, $this->methodename)) {
1372 $this->error = $langs->transnoentitiesnoconv('CronMethodDoesNotExists', $this->objectname, $this->methodename);
1373 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1374 $this->lastoutput = $this->error;
1375 $this->lastresult = '-1';
1376 $error++;
1377 }
1378 if (in_array(strtolower(trim($this->methodename)), array('executecli'))) {
1379 $this->error = $langs->transnoentitiesnoconv('CronMethodNotAllowed', $this->methodename, $this->objectname);
1380 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1381 $this->lastoutput = $this->error;
1382 $this->lastresult = '-1';
1383 $error++;
1384 }
1385 }
1386
1387 // Load langs
1388 if (!$error) {
1389 $result = $langs->load($this->module_name);
1390 $result = $langs->load($this->module_name.'@'.$this->module_name, 0, 0, '', 0, 1);
1391
1392 if ($result < 0) { // If technical error
1393 dol_syslog(get_class($this)."::run_jobs Cannot load module lang file - ".$langs->error, LOG_ERR);
1394 $this->error = $langs->error;
1395 $this->lastoutput = $this->error;
1396 $this->lastresult = '-1';
1397 $error++;
1398 }
1399 }
1400
1401 if (!$error) {
1402 dol_syslog(get_class($this)."::run_jobs START ".$this->objectname."->".$this->methodename."(".$this->params."); (Note: Log for cron jobs may be into a different log file)", LOG_DEBUG);
1403
1404 // Create Object for the called module
1405 $nameofclass = (string) $this->objectname;
1406 $object = new $nameofclass($this->db);
1407 if ($this->entity > 0) {
1408 $object->entity = $this->entity; // We work on a dedicated entity
1409 }
1410
1411 $params_arr = array();
1412 if (!empty($this->params) || $this->params === '0') {
1413 $params_arr = array_map('trim', explode(",", $this->params));
1414 }
1415
1416 if (!is_array($params_arr)) {
1417 $result = call_user_func(array($object, $this->methodename), $this->params);
1418 } else {
1419 $result = call_user_func_array(array($object, $this->methodename), $params_arr);
1420 }
1421 $errmsg = '';
1422 if ($result === false || (!is_bool($result) && $result != 0)) {
1423 $langs->load("errors");
1424
1425 if (!is_array($object->errors) || !in_array($object->error, $object->errors)) {
1426 $errmsg .= $object->error;
1427 }
1428 if (is_array($object->errors) && count($object->errors)) {
1429 $errmsg .= (($errmsg ? ', ' : '').implode(', ', $object->errors));
1430 }
1431 if (empty($errmsg)) {
1432 $errmsg = $langs->trans('ErrorUnknown');
1433 }
1434
1435 dol_syslog(get_class($this)."::run_jobs END result=".$result." error=".$errmsg, LOG_ERR);
1436
1437 $this->error = $errmsg;
1438 $this->lastoutput = dol_substr((empty($object->output) ? "" : $object->output."\n").$errmsg, 0, $this::MAXIMUM_LENGTH_FOR_LASTOUTPUT_FIELD, 'UTF-8', 1);
1439 $this->lastresult = is_numeric($result) ? var_export($result, true) : '-1';
1440 $error++;
1441 } else {
1442 dol_syslog(get_class($this)."::run_jobs END");
1443 $this->lastoutput = dol_substr((empty($object->output) ? "" : $object->output."\n"), 0, $this::MAXIMUM_LENGTH_FOR_LASTOUTPUT_FIELD, 'UTF-8', 1);
1444 $this->lastresult = var_export($result, true);
1445 }
1446 }
1447 }
1448
1449 if ($this->jobtype == 'function') {
1450 //load lib
1451 $libpath = '/'.strtolower($this->module_name).'/lib/'.$this->libname;
1452 $ret = dol_include_once($libpath);
1453 if ($ret === false) {
1454 $this->error = $langs->trans('CronCannotLoadLib').': '.$libpath;
1455 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1456 $conf->setEntityValues($this->db, $savcurrententity);
1457 return -1;
1458 }
1459
1460 // Load langs
1461 $result = $langs->load($this->module_name);
1462 $result = $langs->load($this->module_name.'@'.$this->module_name); // If this->module_name was an existing language file, this will make nothing
1463 if ($result < 0) { // If technical error
1464 dol_syslog(get_class($this)."::run_jobs Cannot load module langs".$langs->error, LOG_ERR);
1465 $conf->setEntityValues($this->db, $savcurrententity);
1466 return -1;
1467 }
1468
1469 dol_syslog(get_class($this)."::run_jobs ".$this->libname."::".$this->methodename."(".$this->params.");", LOG_DEBUG);
1470 $params_arr = explode(", ", $this->params);
1471 if (!is_array($params_arr)) {
1472 $result = call_user_func($this->methodename, $this->params);
1473 } else {
1474 $result = call_user_func_array($this->methodename, $params_arr);
1475 }
1476
1477 if ($result === false || (!is_bool($result) && $result != 0)) {
1478 $langs->load("errors");
1479 dol_syslog(get_class($this)."::run_jobs result=".$result, LOG_ERR);
1480 $this->error = $langs->trans('ErrorUnknown');
1481 $this->lastoutput = $this->error;
1482 $this->lastresult = is_numeric($result) ? var_export($result, true) : '-1';
1483 $error++;
1484 } else {
1485 $this->lastoutput = var_export($result, true);
1486 $this->lastresult = var_export($result, true); // Return code
1487 }
1488 }
1489
1490 // Run a command line
1491 if ($this->jobtype == 'command') {
1492 global $dolibarr_cron_allow_cli;
1493
1494 if (empty($dolibarr_cron_allow_cli)) {
1495 $langs->load("errors");
1496 $this->error = $langs->trans("FailedToExecutCommandJob");
1497 $this->lastoutput = '';
1498 $this->lastresult = $langs->trans("ErrorParameterMustBeEnabledToAllwoThisFeature", 'dolibarr_cron_allow_cli');
1499 } else {
1500 $outputdir = $conf->cron->dir_temp;
1501 if (empty($outputdir)) {
1502 $outputdir = $conf->cronjob->dir_temp;
1503 }
1504
1505 if (!empty($outputdir)) {
1506 dol_mkdir($outputdir);
1507 $outputfile = $outputdir.'/cronjob.'.$userlogin.'.out'; // File used with popen method
1508
1509 // Execute a CLI
1510 include_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
1511 $utils = new Utils($this->db);
1512 $arrayresult = $utils->executeCLI($this->command, $outputfile);
1513
1514 $this->error = $arrayresult['error'];
1515 $this->lastoutput = $arrayresult['output'];
1516 $this->lastresult = (string) $arrayresult['result'];
1517 }
1518 }
1519 }
1520
1521 dol_syslog(get_class($this)."::run_jobs now we update job to track it is finished (with success or error)");
1522
1523 $this->datelastresult = dol_now();
1524 $this->processing = 0;
1525 $this->pid = null;
1526 $result = $this->update($user); // This include begin/commit
1527 if ($result < 0) {
1528 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1529 $conf->setEntityValues($this->db, $savcurrententity);
1530 return -1;
1531 }
1532
1533 $conf->setEntityValues($this->db, $savcurrententity);
1534
1535 if ($error && !empty($this->email_alert)) {
1536 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1537 $subject = $langs->transnoentitiesnoconv("ErrorInBatch", $this->label);
1538 $msg = $langs->transnoentitiesnoconv("ErrorInBatch", $this->label);
1539 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
1540 $cmailfile = new CMailFile($subject, $this->email_alert, $from, $msg);
1541 $result = $cmailfile->sendfile(); // Do not test result
1542 }
1543
1544 return $error ? -1 : 1;
1545 }
1546
1547
1548 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1556 public function reprogram_jobs(string $userlogin, int $now)
1557 {
1558 // phpcs:enable
1559 dol_syslog(get_class($this)."::reprogram_jobs userlogin:$userlogin", LOG_DEBUG);
1560
1561 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1562 $user = new User($this->db);
1563 $result = $user->fetch(0, $userlogin);
1564 if ($result < 0) {
1565 $this->error = "User Error : ".$user->error;
1566 dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1567 return -1;
1568 } else {
1569 if (empty($user->id)) {
1570 $this->error = " User user login:".$userlogin." do not exists";
1571 dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1572 return -1;
1573 }
1574 }
1575
1576 dol_syslog(get_class($this)."::reprogram_jobs datenextrun=".$this->datenextrun." ".dol_print_date($this->datenextrun, 'dayhourrfc')." frequency=".$this->frequency." unitfrequency=".$this->unitfrequency, LOG_DEBUG);
1577
1578 if (empty($this->datenextrun)) {
1579 if (empty($this->datestart)) {
1580 if (!is_numeric($this->frequency) || (int) $this->unitfrequency == 2678400) {
1581 $this->datenextrun = dol_time_plus_duree($now, $this->frequency, 'm');
1582 } else {
1583 $this->datenextrun = $now + ($this->frequency * (int) $this->unitfrequency);
1584 }
1585 } else {
1586 if (!is_numeric($this->frequency) || (int) $this->unitfrequency == 2678400) {
1587 $this->datenextrun = dol_time_plus_duree($this->datestart, $this->frequency, 'm');
1588 } else {
1589 $this->datenextrun = $this->datestart + ($this->frequency * (int) $this->unitfrequency);
1590 }
1591 }
1592 }
1593
1594 if ($this->datenextrun < $now && $this->frequency > 0 && !empty($this->unitfrequency)) {
1595 // Loop until date is after future
1596 while ($this->datenextrun < $now) {
1597 if (!is_numeric($this->unitfrequency) || (int) $this->unitfrequency == 2678400 || (int) $this->unitfrequency <= 0) {
1598 $this->datenextrun = dol_time_plus_duree($this->datenextrun, $this->frequency, 'm');
1599 } else {
1600 $this->datenextrun += ($this->frequency * (int) $this->unitfrequency);
1601 }
1602 }
1603 } else {
1604 dol_syslog(get_class($this)."::reprogram_jobs datenextrun is already in future, we do not change it");
1605 }
1606
1607
1608 // Archive job
1609 if ($this->autodelete == 2) {
1610 if (($this->maxrun > 0 && ($this->nbrun >= $this->maxrun))
1611 || ($this->dateend && ($this->datenextrun > $this->dateend))) {
1612 $this->status = self::STATUS_ARCHIVED;
1613 dol_syslog(get_class($this)."::reprogram_jobs Job will be set to archived", LOG_ERR);
1614 }
1615 }
1616
1617 $result = $this->update($user);
1618 if ($result < 0) {
1619 dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1620 return -1;
1621 }
1622
1623 return 1;
1624 }
1625
1632 public function getLibStatut(int $mode = 0)
1633 {
1634 return $this->LibStatut($this->status, $mode, $this->processing, $this->lastresult);
1635 }
1636
1637 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1647 public function LibStatut(int $status, int $mode = 0, int $processing = 0, string $lastResult = '')
1648 {
1649 // phpcs:enable
1650 $this->labelStatus = array(); // Force reset o array because label depends on other fields
1651 $this->labelStatusShort = array();
1652
1653 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1654 global $langs;
1655 $langs->load('users');
1656
1657 $moreText = '';
1658 if ($processing) {
1659 $moreText = ' ('.$langs->trans("Running").')';
1660 } elseif ($lastResult) {
1661 $moreText .= ' ('.$langs->trans("Error").')';
1662 }
1663
1664 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled').$moreText;
1665 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Scheduled').$moreText;
1666 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
1667 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Scheduled');
1668 }
1669
1670 $statusType = 'status4';
1671 if ($status == self::STATUS_ENABLED && $processing) {
1672 $statusType = 'status1';
1673 }
1674 if ($status == self::STATUS_DISABLED) {
1675 $statusType = 'status5';
1676 }
1677 if ($status == self::STATUS_ENABLED && $this->lastresult) {
1678 $statusType = 'status8';
1679 }
1680
1681 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1682 }
1683}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Cron Job class.
fetchAll(string $sortorder='DESC', string $sortfield='t.rowid', int $limit=0, int $offset=0, int $status=1, $filter='', int $processing=-1)
Load list of cron jobs in a memory array from the database.
createFromClone(User $user, int $fromid)
Load an object from its id and create a new one in database.
reprogram_jobs(string $userlogin, int $now)
Reprogram a job.
run_jobs(string $userlogin)
Run a job.
LibStatut(int $status, int $mode=0, int $processing=0, string $lastResult='')
Return label of a giver status.
create(User $user, int $notrigger=0)
Create object into database.
getLibStatut(int $mode=0)
Return label of status of user (active, inactive)
__construct(DoliDB $db)
Constructor.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
fetch(int $id, string $objectname='', string $methodname='', string $label='')
Load object in memory from the database.
getNomUrl($withpicto=0, string $option='', int $notooltip=0, string $morecss='', int $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
$fields
'type' field format: 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortf...
info(int $id)
Load object information.
getTooltipContentArray($params)
getTooltipContentArray
update($user=null, int $notrigger=0)
Update object into database.
Class to manage Dolibarr database access.
Class to manage Dolibarr users.
Class to manage utility methods.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
dol_now($mode='gmt')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...