dolibarr 25.0.0-alpha
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-2026 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2026 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 $this->lastoutput = dol_substr($this->lastoutput, 0, self::MAXIMUM_LENGTH_FOR_LASTOUTPUT_FIELD, 'UTF-8', 1);
356 }
357 if (isset($this->lastresult)) {
358 $this->lastresult = trim($this->lastresult);
359 }
360 if (isset($this->unitfrequency)) {
361 $this->unitfrequency = trim($this->unitfrequency);
362 }
363 if (isset($this->frequency)) {
364 $this->frequency = (int) $this->frequency;
365 }
366 if (isset($this->status)) {
367 $this->status = (int) $this->status;
368 }
369 if (isset($this->note_private)) {
370 $this->note_private = trim($this->note_private);
371 }
372 if (isset($this->nbrun)) {
373 $this->nbrun = (int) $this->nbrun;
374 }
375 if (isset($this->maxrun)) {
376 $this->maxrun = (int) $this->maxrun;
377 }
378 if (isset($this->libname)) {
379 $this->libname = trim($this->libname);
380 }
381 if (isset($this->test)) {
382 $this->test = trim($this->test);
383 }
384
385 // Check parameters
386 // Put here code to add a control on parameters values
387 if (dol_strlen($this->datenextrun) == 0) {
388 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronDtNextLaunch'));
389 $error++;
390 }
391 if (empty($this->label)) {
392 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLabel'));
393 $error++;
394 }
395 if ((dol_strlen($this->datestart) != 0) && (dol_strlen($this->dateend) != 0) && ($this->dateend < $this->datestart)) {
396 $this->errors[] = $langs->trans('CronErrEndDateStartDt');
397 $error++;
398 }
399 if (empty($this->unitfrequency)) {
400 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronFrequency'));
401 $error++;
402 }
403 if (($this->jobtype == 'command') && (empty($this->command))) {
404 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronCommand'));
405 $error++;
406 }
407 if (($this->jobtype == 'method') && (empty($this->classesname))) {
408 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronClass'));
409 $error++;
410 }
411 if (($this->jobtype == 'method' || $this->jobtype == 'function') && (empty($this->methodename))) {
412 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronMethod'));
413 $error++;
414 }
415 if (($this->jobtype == 'method') && (empty($this->objectname))) {
416 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronObject'));
417 $error++;
418 }
419 if (($this->jobtype == 'function') && (empty($this->libname))) {
420 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLib'));
421 $error++;
422 }
423
424 // Insert request
425 $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob(";
426 $sql .= "entity,";
427 $sql .= "datec,";
428 $sql .= "jobtype,";
429 $sql .= "label,";
430 $sql .= "command,";
431 $sql .= "classesname,";
432 $sql .= "objectname,";
433 $sql .= "methodename,";
434 $sql .= "params,";
435 $sql .= "md5params,";
436 $sql .= "module_name,";
437 $sql .= "priority,";
438 $sql .= "datelastrun,";
439 $sql .= "datenextrun,";
440 $sql .= "dateend,";
441 $sql .= "datestart,";
442 $sql .= "lastresult,";
443 $sql .= "datelastresult,";
444 $sql .= "lastoutput,";
445 $sql .= "unitfrequency,";
446 $sql .= "frequency,";
447 $sql .= "status,";
448 $sql .= "fk_user_author,";
449 $sql .= "fk_user_mod,";
450 $sql .= "note,";
451 $sql .= "nbrun,";
452 $sql .= "maxrun,";
453 $sql .= "libname,";
454 $sql .= "test";
455 $sql .= ") VALUES (";
456 $sql .= " ".(!isset($this->entity) ? (int) $conf->entity : (int) $this->entity).",";
457 $sql .= " '".$this->db->idate($now)."',";
458 $sql .= " ".(!isset($this->jobtype) ? 'NULL' : "'".$this->db->escape($this->jobtype)."'").",";
459 $sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").",";
460 $sql .= " ".(!isset($this->command) ? 'NULL' : "'".$this->db->escape($this->command)."'").",";
461 $sql .= " ".(!isset($this->classesname) ? 'NULL' : "'".$this->db->escape($this->classesname)."'").",";
462 $sql .= " ".(!isset($this->objectname) ? 'NULL' : "'".$this->db->escape($this->objectname)."'").",";
463 $sql .= " ".(!isset($this->methodename) ? 'NULL' : "'".$this->db->escape($this->methodename)."'").",";
464 $sql .= " ".(!isset($this->params) ? 'NULL' : "'".$this->db->escape($this->params)."'").",";
465 $sql .= " ".(!isset($this->md5params) ? 'NULL' : "'".$this->db->escape($this->md5params)."'").",";
466 $sql .= " ".(!isset($this->module_name) ? 'NULL' : "'".$this->db->escape($this->module_name)."'").",";
467 $sql .= " ".(is_numeric($this->priority) ? (int) $this->priority : 50).",";
468 $sql .= " ".(!isset($this->datelastrun) || dol_strlen($this->datelastrun) == 0 ? 'NULL' : "'".$this->db->idate($this->datelastrun)."'").",";
469 $sql .= " ".(!isset($this->datenextrun) || dol_strlen($this->datenextrun) == 0 ? 'NULL' : "'".$this->db->idate($this->datenextrun)."'").",";
470 $sql .= " ".(!isset($this->dateend) || dol_strlen($this->dateend) == 0 ? 'NULL' : "'".$this->db->idate($this->dateend)."'").",";
471 $sql .= " ".(!isset($this->datestart) || dol_strlen($this->datestart) == 0 ? 'NULL' : "'".$this->db->idate($this->datestart)."'").",";
472 $sql .= " ".(!isset($this->lastresult) ? 'NULL' : "'".$this->db->escape($this->lastresult)."'").",";
473 $sql .= " ".(!isset($this->datelastresult) || dol_strlen($this->datelastresult) == 0 ? 'NULL' : "'".$this->db->idate($this->datelastresult)."'").",";
474 $sql .= " ".(!isset($this->lastoutput) ? 'NULL' : "'".$this->db->escape($this->lastoutput)."'").",";
475 $sql .= " ".(!isset($this->unitfrequency) ? 'NULL' : "'".$this->db->escape($this->unitfrequency)."'").",";
476 $sql .= " ".(!isset($this->frequency) ? '0' : ((int) $this->frequency)).",";
477 $sql .= " ".(!isset($this->status) ? '0' : ((int) $this->status)).",";
478 $sql .= " ".($user->id ? (int) $user->id : "NULL").",";
479 $sql .= " ".($user->id ? (int) $user->id : "NULL").",";
480 $sql .= " ".(!isset($this->note_private) ? 'NULL' : "'".$this->db->escape($this->note_private)."'").",";
481 $sql .= " ".(!isset($this->nbrun) ? '0' : ((int) $this->nbrun)).",";
482 $sql .= " ".(empty($this->maxrun) ? '0' : ((int) $this->maxrun)).",";
483 $sql .= " ".(!isset($this->libname) ? 'NULL' : "'".$this->db->escape($this->libname)."'").",";
484 $sql .= " ".(!isset($this->test) ? 'NULL' : "'".$this->db->escape($this->test)."'");
485 $sql .= ")";
486
487 $this->db->begin();
488
489 dol_syslog(get_class($this)."::create", LOG_DEBUG);
490 $resql = $this->db->query($sql);
491 if (!$resql) {
492 $error++;
493 $this->errors[] = "Error ".$this->db->lasterror();
494 }
495
496 if (!$error) {
497 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."cronjob");
498 }
499
500 if (!$error && !$notrigger) {
501 // Call trigger
502 $result = $this->call_trigger('CRONJOB_CREATE', $user);
503 if ($result < 0) {
504 $error++;
505 }
506 // End call triggers
507 }
508
509 // Commit or rollback
510 if ($error) {
511 $this->db->rollback();
512 return -1 * $error;
513 } else {
514 $this->db->commit();
515 return $this->id;
516 }
517 }
518
519
529 public function fetch(int $id, string $objectname = '', string $methodname = '', string $label = '')
530 {
531 $sql = "SELECT";
532 $sql .= " t.rowid,";
533 $sql .= " t.entity,";
534 $sql .= " t.tms,";
535 $sql .= " t.datec,";
536 $sql .= " t.jobtype,";
537 $sql .= " t.label,";
538 $sql .= " t.command,";
539 $sql .= " t.classesname,";
540 $sql .= " t.objectname,";
541 $sql .= " t.methodename,";
542 $sql .= " t.params,";
543 $sql .= " t.md5params,";
544 $sql .= " t.module_name,";
545 $sql .= " t.priority,";
546 $sql .= " t.datelastrun,";
547 $sql .= " t.datenextrun,";
548 $sql .= " t.dateend,";
549 $sql .= " t.datestart,";
550 $sql .= " t.lastresult,";
551 $sql .= " t.datelastresult,";
552 $sql .= " t.lastoutput,";
553 $sql .= " t.unitfrequency,";
554 $sql .= " t.frequency,";
555 $sql .= " t.status,";
556 $sql .= " t.processing,";
557 $sql .= " t.pid,";
558 $sql .= " t.email_alert,";
559 $sql .= " t.fk_user_author,";
560 $sql .= " t.fk_user_mod,";
561 $sql .= " t.note as note_private,";
562 $sql .= " t.nbrun,";
563 $sql .= " t.maxrun,";
564 $sql .= " t.libname,";
565 $sql .= " t.test";
566 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t";
567 if ($id > 0) {
568 $sql .= " WHERE t.rowid = ".((int) $id);
569 } elseif ($label) {
570 $sql .= " WHERE t.entity IN(0, ".getEntity('cron').")";
571 $sql .= " AND t.label = '".$this->db->escape($label)."'";
572 } else {
573 $sql .= " WHERE t.entity IN(0, ".getEntity('cron').")";
574 $sql .= " AND t.objectname = '".$this->db->escape($objectname)."'";
575 $sql .= " AND t.methodename = '".$this->db->escape($methodname)."'";
576 }
577
578 $resql = $this->db->query($sql);
579 if ($resql) {
580 if ($this->db->num_rows($resql)) {
581 $obj = $this->db->fetch_object($resql);
582
583 $this->id = $obj->rowid;
584 $this->ref = $obj->rowid;
585 $this->entity = $obj->entity;
586 $this->tms = $this->db->jdate($obj->tms);
587 $this->date_modification = $this->db->jdate($obj->tms);
588 $this->datec = $this->db->jdate($obj->datec);
589 $this->label = $obj->label;
590 $this->jobtype = $obj->jobtype;
591 $this->command = $obj->command;
592 $this->classesname = $obj->classesname;
593 $this->objectname = $obj->objectname;
594 $this->methodename = $obj->methodename;
595 $this->params = $obj->params;
596 $this->md5params = $obj->md5params;
597 $this->module_name = $obj->module_name;
598 $this->priority = $obj->priority;
599 $this->datelastrun = $this->db->jdate($obj->datelastrun);
600 $this->datenextrun = $this->db->jdate($obj->datenextrun);
601 $this->dateend = $this->db->jdate($obj->dateend);
602 $this->datestart = $this->db->jdate($obj->datestart);
603 $this->lastresult = (string) $obj->lastresult;
604 $this->lastoutput = $obj->lastoutput;
605 $this->datelastresult = $this->db->jdate($obj->datelastresult);
606 $this->unitfrequency = $obj->unitfrequency;
607 $this->frequency = $obj->frequency;
608 $this->status = $obj->status;
609 $this->processing = $obj->processing;
610 $this->pid = $obj->pid;
611 $this->email_alert = $obj->email_alert;
612 $this->fk_user_author = $obj->fk_user_author;
613 $this->fk_user_mod = $obj->fk_user_mod;
614 $this->note_private = $obj->note_private;
615 $this->nbrun = $obj->nbrun;
616 $this->maxrun = $obj->maxrun;
617 $this->libname = $obj->libname;
618 $this->test = $obj->test;
619
620 $this->db->free($resql);
621 return 1;
622 }
623 $this->db->free($resql);
624
625 return 0;
626 } else {
627 $this->error = "Error ".$this->db->lasterror();
628 return -1;
629 }
630 }
631
644 public function fetchAll(string $sortorder = 'DESC', string $sortfield = 't.rowid', int $limit = 0, int $offset = 0, int $status = 1, $filter = '', int $processing = -1)
645 {
646 $this->lines = array();
647
648 $sql = "SELECT";
649 $sql .= " t.rowid,";
650 $sql .= " t.entity,";
651 $sql .= " t.tms,";
652 $sql .= " t.datec,";
653 $sql .= " t.jobtype,";
654 $sql .= " t.label,";
655 $sql .= " t.command,";
656 $sql .= " t.classesname,";
657 $sql .= " t.objectname,";
658 $sql .= " t.methodename,";
659 $sql .= " t.params,";
660 $sql .= " t.md5params,";
661 $sql .= " t.module_name,";
662 $sql .= " t.priority,";
663 $sql .= " t.datelastrun,";
664 $sql .= " t.datenextrun,";
665 $sql .= " t.dateend,";
666 $sql .= " t.datestart,";
667 $sql .= " t.lastresult,";
668 $sql .= " t.datelastresult,";
669 $sql .= " t.lastoutput,";
670 $sql .= " t.unitfrequency,";
671 $sql .= " t.frequency,";
672 $sql .= " t.status,";
673 $sql .= " t.processing,";
674 $sql .= " t.pid,";
675 $sql .= " t.email_alert,";
676 $sql .= " t.fk_user_author,";
677 $sql .= " t.fk_user_mod,";
678 $sql .= " t.note as note_private,";
679 $sql .= " t.nbrun,";
680 $sql .= " t.maxrun,";
681 $sql .= " t.libname,";
682 $sql .= " t.test";
683 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t";
684 $sql .= " WHERE 1 = 1";
685 if ($processing >= 0) {
686 $sql .= " AND t.processing = ".(empty($processing) ? '0' : '1');
687 }
688 if ($status >= 0 && $status < 2) {
689 $sql .= " AND t.status = ".(empty($status) ? '0' : '1');
690 } elseif ($status == 2) {
691 $sql .= " AND t.status = 2";
692 }
693
694 // Manage filter
695 if (is_array($filter)) {
696 if (count($filter) > 0) {
697 foreach ($filter as $key => $value) {
698 if ($key == 't.rowid') {
699 $sql .= " AND ".$this->db->sanitize($key)." = ".((int) $value);
700 } else {
701 $sql .= " AND ".$this->db->sanitize($key)." LIKE '%".$this->db->escape($this->db->escapeforlike($value))."%'";
702 }
703 }
704 }
705
706 $filter = '';
707 }
708
709 // Manage filter
710 $errormessage = '';
711 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
712 if ($errormessage) {
713 $this->errors[] = $errormessage;
714 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
715 return -1;
716 }
717
718 $sql .= $this->db->order($sortfield, $sortorder);
719 if (!empty($limit) && !empty($offset)) {
720 $sql .= $this->db->plimit($limit + 1, $offset);
721 }
722
723 dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
724 $resql = $this->db->query($sql);
725 if ($resql) {
726 $num = $this->db->num_rows($resql);
727 $i = 0;
728
729 if ($num) {
730 while ($i < $num) {
731 $obj = $this->db->fetch_object($resql);
732 $cronjob_obj = new Cronjob($this->db);
733
734 $cronjob_obj->id = $obj->rowid;
735 $cronjob_obj->ref = $obj->rowid;
736 $cronjob_obj->entity = $obj->entity;
737 $cronjob_obj->tms = $this->db->jdate($obj->tms);
738 $cronjob_obj->datec = $this->db->jdate($obj->datec);
739 $cronjob_obj->label = $obj->label;
740 $cronjob_obj->jobtype = $obj->jobtype;
741 $cronjob_obj->command = $obj->command;
742 $cronjob_obj->classesname = $obj->classesname;
743 $cronjob_obj->objectname = $obj->objectname;
744 $cronjob_obj->methodename = $obj->methodename;
745 $cronjob_obj->params = $obj->params;
746 $cronjob_obj->md5params = $obj->md5params;
747 $cronjob_obj->module_name = $obj->module_name;
748 $cronjob_obj->priority = $obj->priority;
749 $cronjob_obj->datelastrun = $this->db->jdate($obj->datelastrun);
750 $cronjob_obj->datenextrun = $this->db->jdate($obj->datenextrun);
751 $cronjob_obj->dateend = $this->db->jdate($obj->dateend);
752 $cronjob_obj->datestart = $this->db->jdate($obj->datestart);
753 $cronjob_obj->lastresult = $obj->lastresult;
754 $cronjob_obj->lastoutput = $obj->lastoutput;
755 $cronjob_obj->datelastresult = $this->db->jdate($obj->datelastresult);
756 $cronjob_obj->unitfrequency = $obj->unitfrequency;
757 $cronjob_obj->frequency = $obj->frequency;
758 $cronjob_obj->status = $obj->status;
759 $cronjob_obj->processing = $obj->processing;
760 $cronjob_obj->pid = $obj->pid;
761 $cronjob_obj->email_alert = $obj->email_alert;
762 $cronjob_obj->fk_user_author = $obj->fk_user_author;
763 $cronjob_obj->fk_user_mod = $obj->fk_user_mod;
764 $cronjob_obj->note_private = $obj->note_private;
765 $cronjob_obj->nbrun = $obj->nbrun;
766 $cronjob_obj->maxrun = $obj->maxrun;
767 $cronjob_obj->libname = $obj->libname;
768 $cronjob_obj->test = $obj->test;
769
770 $this->lines[] = $cronjob_obj;
771
772 $i++;
773 }
774 }
775 $this->db->free($resql);
776
777 return 1;
778 } else {
779 $this->error = "Error ".$this->db->lasterror();
780 return -1;
781 }
782 }
783
784
792 public function update($user = null, int $notrigger = 0)
793 {
794 global $conf, $langs;
795
796 $langs->load('cron');
797
798 $error = 0;
799
800 // Clean parameters
801 if (isset($this->label)) {
802 $this->label = trim($this->label);
803 }
804 if (isset($this->jobtype)) {
805 $this->jobtype = trim($this->jobtype);
806 }
807 if (isset($this->command)) {
808 $this->command = trim($this->command);
809 }
810 if (isset($this->classesname)) {
811 $this->classesname = trim($this->classesname);
812 }
813 if (isset($this->objectname)) {
814 $this->objectname = trim($this->objectname);
815 }
816 if (isset($this->methodename)) {
817 $this->methodename = trim($this->methodename);
818 }
819 if (isset($this->params)) {
820 $this->params = trim($this->params);
821 }
822 if (isset($this->md5params)) {
823 $this->md5params = trim($this->md5params);
824 }
825 if (isset($this->module_name)) {
826 $this->module_name = trim($this->module_name);
827 }
828 if (isset($this->priority)) {
829 $this->priority = trim($this->priority);
830 }
831 if (isset($this->lastoutput)) {
832 $this->lastoutput = trim($this->lastoutput);
833 $this->lastoutput = dol_substr($this->lastoutput, 0, self::MAXIMUM_LENGTH_FOR_LASTOUTPUT_FIELD, 'UTF-8', 1);
834 }
835 if (isset($this->lastresult)) {
836 $this->lastresult = trim($this->lastresult);
837 }
838 if (isset($this->unitfrequency)) {
839 $this->unitfrequency = trim($this->unitfrequency);
840 }
841 if (isset($this->frequency)) {
842 $this->frequency = (int) $this->frequency;
843 }
844 if (isset($this->status)) {
845 $this->status = (int) $this->status;
846 }
847 if (isset($this->note_private)) {
848 $this->note_private = trim($this->note_private);
849 }
850 if (isset($this->nbrun)) {
851 $this->nbrun = (is_numeric($this->nbrun)) ? (int) trim((string) $this->nbrun) : 0;
852 }
853 if (isset($this->libname)) {
854 $this->libname = trim($this->libname);
855 }
856 if (isset($this->test)) {
857 $this->test = trim($this->test);
858 }
859
860 if (empty($this->maxrun)) {
861 $this->maxrun = 0;
862 }
863 if (empty($this->processing)) {
864 $this->processing = 0;
865 }
866 if (empty($this->pid)) {
867 $this->pid = null;
868 }
869 if (empty($this->email_alert)) {
870 $this->email_alert = '';
871 }
872 if (empty($this->datenextrun)) {
873 $this->datenextrun = dol_now();
874 }
875
876 // Check parameters
877 // Put here code to add a control on parameters values
878 if (dol_strlen($this->datenextrun) == 0 && $this->status == self::STATUS_ENABLED) {
879 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronDtNextLaunch'));
880 $error++;
881 }
882 if ((dol_strlen($this->datestart) != 0) && (dol_strlen($this->dateend) != 0) && ($this->dateend < $this->datestart)) {
883 $this->errors[] = $langs->trans('CronErrEndDateStartDt');
884 $error++;
885 }
886 if (empty($this->label)) {
887 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLabel'));
888 $error++;
889 }
890 if (empty($this->unitfrequency)) {
891 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronFrequency'));
892 $error++;
893 }
894 if (($this->jobtype == 'command') && (empty($this->command))) {
895 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronCommand'));
896 $error++;
897 }
898 if (($this->jobtype == 'method') && (empty($this->classesname))) {
899 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronClass'));
900 $error++;
901 }
902 if (($this->jobtype == 'method' || $this->jobtype == 'function') && (empty($this->methodename))) {
903 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronMethod'));
904 $error++;
905 }
906 if (($this->jobtype == 'method') && (empty($this->objectname))) {
907 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronObject'));
908 $error++;
909 }
910
911 if (($this->jobtype == 'function') && (empty($this->libname))) {
912 $this->errors[] = $langs->trans('CronFieldMandatory', $langs->transnoentitiesnoconv('CronLib'));
913 $error++;
914 }
915
916
917 // Update request
918 $sql = "UPDATE ".MAIN_DB_PREFIX."cronjob SET";
919 $sql .= " entity=".(isset($this->entity) ? ((int) $this->entity) : ((int) $conf->entity)).",";
920 $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
921 $sql .= " jobtype=".(isset($this->jobtype) ? "'".$this->db->escape($this->jobtype)."'" : "null").",";
922 $sql .= " command=".(isset($this->command) ? "'".$this->db->escape($this->command)."'" : "null").",";
923 $sql .= " classesname=".(isset($this->classesname) ? "'".$this->db->escape($this->classesname)."'" : "null").",";
924 $sql .= " objectname=".(isset($this->objectname) ? "'".$this->db->escape($this->objectname)."'" : "null").",";
925 $sql .= " methodename=".(isset($this->methodename) ? "'".$this->db->escape($this->methodename)."'" : "null").",";
926 $sql .= " params=".(isset($this->params) ? "'".$this->db->escape($this->params)."'" : "null").",";
927 $sql .= " md5params=".(isset($this->md5params) ? "'".$this->db->escape($this->md5params)."'" : "null").",";
928 $sql .= " module_name=".(isset($this->module_name) ? "'".$this->db->escape($this->module_name)."'" : "null").",";
929 $sql .= " priority=".(isset($this->priority) ? ((int) $this->priority) : "null").",";
930 $sql .= " datelastrun=".(dol_strlen($this->datelastrun) != 0 ? "'".$this->db->idate($this->datelastrun)."'" : 'null').",";
931 $sql .= " datenextrun=".(dol_strlen($this->datenextrun) != 0 ? "'".$this->db->idate($this->datenextrun)."'" : 'null').",";
932 $sql .= " dateend=".(dol_strlen($this->dateend) != 0 ? "'".$this->db->idate($this->dateend)."'" : 'null').",";
933 $sql .= " datestart=".(dol_strlen($this->datestart) != 0 ? "'".$this->db->idate($this->datestart)."'" : 'null').",";
934 $sql .= " datelastresult=".(dol_strlen($this->datelastresult) != 0 ? "'".$this->db->idate($this->datelastresult)."'" : 'null').",";
935 $sql .= " lastresult=".(isset($this->lastresult) ? "'".$this->db->escape($this->lastresult)."'" : "null").",";
936 $sql .= " lastoutput=".(isset($this->lastoutput) ? "'".$this->db->escape($this->lastoutput)."'" : "null").",";
937 $sql .= " unitfrequency=".(isset($this->unitfrequency) ? "'".$this->db->escape($this->unitfrequency)."'" : "null").",";
938 $sql .= " frequency=".(isset($this->frequency) ? ((int) $this->frequency) : "null").",";
939 $sql .= " status=".(isset($this->status) ? ((int) $this->status) : "null").",";
940 $sql .= " processing=".((isset($this->processing) && $this->processing > 0) ? ((int) $this->processing) : "0").",";
941 $sql .= " pid=".(isset($this->pid) ? ((int) $this->pid) : "null").",";
942 $sql .= " email_alert = ".(isset($this->email_alert) ? "'".$this->db->escape($this->email_alert)."'" : "null").",";
943 $sql .= " fk_user_mod = ".((int) $user->id).",";
944 $sql .= " note=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
945 $sql .= " nbrun=".((isset($this->nbrun) && $this->nbrun > 0) ? ((int) $this->nbrun) : "null").",";
946 $sql .= " maxrun=".((isset($this->maxrun) && $this->maxrun > 0) ? ((int) $this->maxrun) : "0").",";
947 $sql .= " libname=".(isset($this->libname) ? "'".$this->db->escape($this->libname)."'" : "null").",";
948 $sql .= " test=".(isset($this->test) ? "'".$this->db->escape($this->test)."'" : "null");
949 $sql .= " WHERE rowid=".((int) $this->id);
950
951 $this->db->begin();
952
953 dol_syslog(get_class($this)."::update", LOG_DEBUG);
954 $resql = $this->db->query($sql);
955 if (!$resql) {
956 $error++;
957 $this->errors[] = "Error ".$this->db->lasterror();
958 }
959
960 if (!$error && $user && !$notrigger) {
961 // Call trigger
962 $result = $this->call_trigger('CRONJOB_MODIFY', $user);
963 if ($result < 0) {
964 $error++;
965 }
966 // End call triggers
967 }
968
969 // Commit or rollback
970 if ($error) {
971 foreach ($this->errors as $errmsg) {
972 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
973 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
974 }
975 $this->db->rollback();
976 return -1 * $error;
977 } else {
978 $this->db->commit();
979 return 1;
980 }
981 }
982
983
991 public function delete(User $user, int $notrigger = 0)
992 {
993 $error = 0;
994
995 $this->db->begin();
996
997 $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
998 $sql .= " WHERE rowid=".((int) $this->id);
999
1000 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1001 $resql = $this->db->query($sql);
1002 if (!$resql) {
1003 $error++;
1004 $this->errors[] = "Error ".$this->db->lasterror();
1005 }
1006
1007 if (!$error && !$notrigger) {
1008 // Call trigger
1009 $result = $this->call_trigger('CRONJOB_DELETE', $user);
1010 if ($result < 0) {
1011 $error++;
1012 }
1013 // End call triggers
1014 }
1015
1016 // Commit or rollback
1017 if ($error) {
1018 foreach ($this->errors as $errmsg) {
1019 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1020 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1021 }
1022 $this->db->rollback();
1023 return -1 * $error;
1024 } else {
1025 $this->db->commit();
1026 return 1;
1027 }
1028 }
1029
1030
1031
1039 public function createFromClone(User $user, int $fromid)
1040 {
1041 global $langs;
1042
1043 $error = 0;
1044
1045 $object = new Cronjob($this->db);
1046
1047 $this->db->begin();
1048
1049 // Load source object
1050 $object->fetch($fromid);
1051 $object->id = 0;
1052
1053 // Clear fields
1054 $object->status = self::STATUS_DISABLED;
1055 $object->label = $langs->trans("CopyOf").' '.$langs->trans($object->label);
1056 $object->datelastrun = null;
1057 $object->lastresult = '';
1058 $object->datelastresult = null;
1059 $object->datenextrun = dol_now();
1060 $object->lastoutput = '';
1061 $object->nbrun = 0;
1062
1063 // Create clone
1064 $object->context['createfromclone'] = 'createfromclone';
1065 $result = $object->create($user);
1066
1067 // Other options
1068 if ($result < 0) {
1069 $this->error = $object->error;
1070 $this->errors = $object->errors;
1071 $error++;
1072 }
1073
1074 unset($object->context['createfromclone']);
1075
1076 // End
1077 if (!$error) {
1078 $this->db->commit();
1079 return $object->id;
1080 } else {
1081 $this->db->rollback();
1082 return -1;
1083 }
1084 }
1085
1086
1093 public function initAsSpecimen()
1094 {
1095 $this->id = 0;
1096 $this->ref = '';
1097 $this->entity = 0;
1098 $this->date_modification = dol_now();
1099 $this->datec = '';
1100 $this->label = '';
1101 $this->jobtype = '';
1102 $this->command = '';
1103 $this->classesname = '';
1104 $this->objectname = '';
1105 $this->methodename = '';
1106 $this->params = '';
1107 $this->md5params = '';
1108 $this->module_name = '';
1109 $this->priority = '';
1110 $this->datelastrun = '';
1111 $this->datenextrun = '';
1112 $this->dateend = '';
1113 $this->datestart = '';
1114 $this->datelastresult = '';
1115 $this->lastoutput = '';
1116 $this->lastresult = '';
1117 $this->unitfrequency = '86400';
1118 $this->frequency = 0;
1119 $this->status = 0;
1120 $this->processing = 0;
1121 $this->pid = null;
1122 $this->email_alert = '';
1123 $this->fk_user_author = 0;
1124 $this->fk_user_mod = 0;
1125 $this->note_private = '';
1126 $this->nbrun = 0;
1127 $this->maxrun = 100;
1128 $this->libname = '';
1129
1130 return 1;
1131 }
1132
1133
1140 public function getTooltipContentArray($params)
1141 {
1142 global $langs;
1143
1144 $langs->load('cron');
1145 $datas = [];
1146
1147 $datas['picto'] = img_picto('', 'object_'.$this->picto).' <u>'.$langs->trans("CronTask").'</u>';
1148 if (isset($this->status)) {
1149 $datas['picto'] .= ' '.$this->getLibStatut(5);
1150 }
1151 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.dol_escape_htmltag($this->ref);
1152 $datas['label'] = '<br><b>'.$langs->trans('Title').':</b> '.$langs->trans($this->label);
1153 if ($this->label != $langs->trans($this->label)) {
1154 $datas['label'] .= ' <span class="opacitymedium">('.$this->label.')</span>';
1155 }
1156 if (!empty($this->params)) {
1157 $datas['params'] = '<br><b>'.$langs->trans('Parameters').':</b> '.dol_escape_htmltag($this->params);
1158 }
1159 $datas['space'] = '<br>';
1160
1161 if (!empty($this->datestart) && $this->datestart >= dol_now()) {
1162 $datas['crondtstart'] = '<br><b>'.$langs->trans('CronDtStart').':</b> '.dol_print_date($this->datestart, 'dayhour', 'tzuserrel');
1163 }
1164 if (!empty($this->dateend)) {
1165 $datas['crondtend'] = '<br><b>'.$langs->trans('CronDtEnd').':</b> '.dol_print_date($this->dateend, 'dayhour', 'tzuserrel');
1166 }
1167 if (!empty($this->datelastrun)) {
1168 $datas['cronlastlaunch'] = '<br><b>'.$langs->trans('CronDtLastLaunch').':</b> '.dol_print_date($this->datelastrun, 'dayhour', 'tzuserrel');
1169 }
1170 if (!empty($this->datenextrun)) {
1171 $datas['crondtnextlaunch'] = '<br><b>'.$langs->trans('CronDtNextLaunch').':</b> '.dol_print_date($this->datenextrun, 'dayhour', 'tzuserrel');
1172 }
1173
1174 return $datas;
1175 }
1176
1187 public function getNomUrl($withpicto = 0, string $option = '', int $notooltip = 0, string $morecss = '', int $save_lastsearch_value = -1)
1188 {
1189 global $conf, $langs;
1190
1191 if (!empty($conf->dol_no_mouse_hover)) {
1192 $notooltip = 1; // Force disable tooltips
1193 }
1194
1195 $result = '';
1196
1197 $params = [
1198 'id' => $this->id,
1199 'objecttype' => $this->element,
1200 ];
1201 $classfortooltip = 'classfortooltip';
1202 $dataparams = '';
1203 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1204 $classfortooltip = 'classforajaxtooltip';
1205 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1206 $label = '';
1207 } else {
1208 $label = implode($this->getTooltipContentArray($params));
1209 }
1210
1211 $url = DOL_URL_ROOT.'/cron/card.php?id='.$this->id;
1212
1213 if ($option != 'nolink') {
1214 // Add param to save lastsearch_values or not
1215 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1216 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1217 $add_save_lastsearch_values = 1;
1218 }
1219 if ($add_save_lastsearch_values) {
1220 $url .= '&save_lastsearch_values=1';
1221 }
1222 }
1223
1224 $linkclose = '';
1225 if (empty($notooltip)) {
1226 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1227 $label = $langs->trans("ShowCronJob");
1228 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1229 }
1230 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1231 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1232 } else {
1233 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1234 }
1235
1236 $linkstart = '<a href="'.$url.'"';
1237 $linkstart .= $linkclose.'>';
1238 $linkend = '</a>';
1239
1240 $result .= $linkstart;
1241 if ($withpicto) {
1242 $result .= img_object(($notooltip ? '' : $label), ($this->picto ?: 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1243 }
1244 if ($withpicto != 2) {
1245 $result .= $this->ref;
1246 }
1247 $result .= $linkend;
1248 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1249
1250 return $result;
1251 }
1252
1253
1260 public function info(int $id)
1261 {
1262 $sql = "SELECT";
1263 $sql .= " f.rowid, f.datec, f.tms, f.fk_user_mod, f.fk_user_author";
1264 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as f";
1265 $sql .= " WHERE f.rowid = ".((int) $id);
1266
1267 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1268 $resql = $this->db->query($sql);
1269 if ($resql) {
1270 if ($this->db->num_rows($resql)) {
1271 $obj = $this->db->fetch_object($resql);
1272
1273 $this->id = $obj->rowid;
1274
1275 $this->user_modification_id = $obj->fk_user_mod;
1276 $this->user_creation_id = $obj->fk_user_author;
1277 $this->date_creation = $this->db->jdate($obj->datec);
1278 $this->date_modification = $this->db->jdate($obj->tms);
1279 }
1280 $this->db->free($resql);
1281
1282 return 1;
1283 } else {
1284 $this->error = "Error ".$this->db->lasterror();
1285 return -1;
1286 }
1287 }
1288
1289
1290 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1299 public function run_jobs(string $userlogin)
1300 {
1301 // phpcs:enable
1302 global $langs, $conf, $hookmanager;
1303
1304 $hookmanager->initHooks(array('cron'));
1305
1306 $now = dol_now();
1307 $error = 0;
1308
1309 $langs->load('cron');
1310
1311 if (empty($userlogin)) {
1312 $this->error = "User login is mandatory";
1313 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1314 return -1;
1315 }
1316
1317 // Force the environment of running to the environment declared for job, so jobs launched from command line will run into correct environment
1318 // When job is ran from GUI, the environment should already be same, except if job has entity 0 (visible into all environments)
1319 if ($conf->entity != $this->entity && $this->entity > 0) {
1320 dol_syslog("We try to run a job in entity ".$this->entity." when we are in entity ".$conf->entity, LOG_WARNING);
1321 }
1322 $savcurrententity = $conf->entity;
1323 $conf->setEntityValues($this->db, $this->entity);
1324 dol_syslog(get_class($this)."::run_jobs entity for running job is ".$conf->entity);
1325
1326 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1327 $user = new User($this->db);
1328 $result = $user->fetch(0, $userlogin);
1329 if ($result < 0) {
1330 $this->error = "User Error:".$user->error;
1331 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1332 $conf->setEntityValues($this->db, $savcurrententity);
1333 return -1;
1334 } else {
1335 if (empty($user->id)) {
1336 $this->error = "User login: ".$userlogin." does not exist";
1337 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1338 $conf->setEntityValues($this->db, $savcurrententity);
1339 return -1;
1340 }
1341 }
1342
1343 dol_syslog(get_class($this)."::run_jobs jobtype=".$this->jobtype." userlogin=".$userlogin, LOG_DEBUG);
1344
1345 // Increase limit of time. Works only if we are not in safe mode
1346 $ExecTimeLimit = getDolGlobalInt('MAIN_CRON_EXEC_TIME_LIMIT', 600);
1347 if (!empty($ExecTimeLimit)) {
1348 $err = error_reporting();
1349 error_reporting(0); // Disable all errors
1350 //error_reporting(E_ALL);
1351 @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
1352 error_reporting($err);
1353 }
1354 $MemoryLimit = getDolGlobalString('MAIN_CRON_MEMORY_LIMIT');
1355 if (!empty($MemoryLimit)) {
1356 @ini_set('memory_limit', $MemoryLimit);
1357 }
1358
1359 // Update last run date start (to track running jobs)
1360 $this->datelastrun = $now;
1361 $this->datelastresult = null;
1362 $this->lastoutput = '';
1363 $this->lastresult = '';
1364 $this->processing = 1; // To know job was started
1365 $this->pid = function_exists('getmypid') ? getmypid() : null; // Avoid dol_getmypid to get null if the function is not available
1366 $this->nbrun += 1;
1367 $result = $this->update($user); // This include begin/commit
1368 if ($result < 0) {
1369 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1370 $conf->setEntityValues($this->db, $savcurrententity);
1371 return -1;
1372 }
1373
1374 // Safety net: If the job execution ends unexpectedly (fatal error, timeout, explicit exit, ...),
1375 // the row may remain stuck with processing=1 and will never be selected again by runners
1376 // (they fetch jobs with processing=0 by default). We register a shutdown handler to unlock it.
1377 $cronjobid = (int) $this->id;
1378 $cronjobpid = (int) $this->pid;
1379 $dbs = $this->db;
1380 register_shutdown_function(static function () use ($cronjobid, $cronjobpid, $dbs) {
1381 // The job may have closed the connection before ending, and a shutdown handler runs after that.
1382 // Querying a closed mysqli connection raises an Error, not an Exception, so it would escape the
1383 // try/catch below and turn into a fatal error at every run (#39801).
1384 if (empty($cronjobid) || empty($dbs) || empty($dbs->connected)) {
1385 return;
1386 }
1387
1388 try {
1389 // Ensure we are not trapped into a transaction left open by the job.
1390 $dbs->rollback('cron register_shutdown_function');
1391 } catch (Throwable $e) {
1392 // Ignore
1393 }
1394
1395 // If job is already closed, do nothing.
1396 $sql = "SELECT processing, pid, datelastresult FROM ".MAIN_DB_PREFIX."cronjob WHERE rowid = ".((int) $cronjobid);
1397 $resql = $dbs->query($sql);
1398 if (!$resql) {
1399 return;
1400 }
1401 $obj = $dbs->fetch_object($resql);
1402 $dbs->free($resql);
1403
1404 if (!$obj || (int) $obj->processing !== 1 || !empty($obj->datelastresult)) {
1405 return;
1406 }
1407
1408 // Protect against unlocking a job started by another PID (concurrent runner).
1409 if (!empty($obj->pid) && (int) $obj->pid !== (int) $cronjobpid) {
1410 return;
1411 }
1412
1413 $now = dol_now();
1414 $lastoutput = 'Cron job aborted unexpectedly (shutdown).';
1415
1416 $lastError = error_get_last();
1417 if (is_array($lastError) && !empty($lastError['message'])) {
1418 $lastoutput .= ' Last error: '.dol_trunc($lastError['message'], 2000, 'right', 'UTF-8', 1);
1419 }
1420
1421 $sql = "UPDATE ".MAIN_DB_PREFIX."cronjob";
1422 $sql .= " SET processing = 0, pid = NULL, datelastresult = '".$dbs->idate($now)."', lastresult = '-1', lastoutput = '".$dbs->escape($lastoutput)."'";
1423 $sql .= " WHERE rowid = ".((int) $cronjobid)." AND processing = 1 AND datelastresult IS NULL";
1424 $dbs->query($sql);
1425 });
1426
1427 // Run a method
1428 if ($this->jobtype == 'method') {
1429 // Deny to launch a method from a deactivated module
1430 if (!empty($this->entity) && !empty($this->module_name) && !isModEnabled(strtolower($this->module_name))) {
1431 $this->error = $langs->transnoentitiesnoconv('CronModuleNotEnabledInThisEntity', $this->methodename, $this->objectname);
1432 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1433 $this->lastoutput = $this->error;
1434 $this->lastresult = '-1';
1435 $error++;
1436 }
1437
1438 // load classes
1439 if (!$error) {
1440 $ret = dol_include_once($this->classesname);
1441 if ($ret === false || (!class_exists($this->objectname))) {
1442 if ($ret === false) {
1443 $this->error = $langs->transnoentitiesnoconv('CronCannotLoadClass', $this->classesname, $this->objectname);
1444 } else {
1445 $this->error = $langs->transnoentitiesnoconv('CronCannotLoadObject', $this->classesname, $this->objectname);
1446 }
1447 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1448 $this->lastoutput = $this->error;
1449 $this->lastresult = '-1';
1450 $error++;
1451 }
1452 }
1453
1454 // test if method exists
1455 if (!$error) {
1456 if (!method_exists($this->objectname, $this->methodename)) {
1457 $this->error = $langs->transnoentitiesnoconv('CronMethodDoesNotExists', $this->objectname, $this->methodename);
1458 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1459 $this->lastoutput = $this->error;
1460 $this->lastresult = '-1';
1461 $error++;
1462 }
1463 if (in_array(strtolower(trim($this->methodename)), array('executecli'))) {
1464 $this->error = $langs->transnoentitiesnoconv('CronMethodNotAllowed', $this->methodename, $this->objectname);
1465 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1466 $this->lastoutput = $this->error;
1467 $this->lastresult = '-1';
1468 $error++;
1469 }
1470 }
1471
1472 // Load langs (module_name is optional for a 'method' job, e.g. one targeting a core
1473 // class such as Utils, so only attempt this when one was actually set - Translate::load()
1474 // rejects an empty domain and prints a hard error otherwise)
1475 if (!$error && !empty($this->module_name)) {
1476 $result = $langs->load($this->module_name);
1477 $result = $langs->load($this->module_name.'@'.$this->module_name, 0, 0, '', 0, 1);
1478
1479 if ($result < 0) { // If technical error
1480 dol_syslog(get_class($this)."::run_jobs Cannot load module lang file - ".$langs->error, LOG_ERR);
1481 $this->error = $langs->error;
1482 $this->lastoutput = $this->error;
1483 $this->lastresult = '-1';
1484 $error++;
1485 }
1486 }
1487
1488 if (!$error) {
1489 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);
1490
1491 // Create Object for the called module
1492 $nameofclass = (string) $this->objectname;
1493 $object = new $nameofclass($this->db);
1494 if ($this->entity > 0) {
1495 $object->entity = $this->entity; // We work on a dedicated entity
1496 }
1497
1498 $params_arr = array();
1499 if (!empty($this->params) || $this->params === '0') {
1500 $params_arr = array_map('trim', explode(",", $this->params));
1501 }
1502
1503 if (!is_array($params_arr)) {
1504 $result = call_user_func(array($object, $this->methodename), $this->params);
1505 } else {
1506 $result = call_user_func_array(array($object, $this->methodename), $params_arr);
1507 }
1508 $errmsg = '';
1509 if ($result === false || (!is_bool($result) && $result != 0)) {
1510 $langs->load("errors");
1511
1512 if (!is_array($object->errors) || !in_array($object->error, $object->errors)) {
1513 $errmsg .= $object->error;
1514 }
1515 if (is_array($object->errors) && count($object->errors)) {
1516 $errmsg .= (($errmsg ? ', ' : '').implode(', ', $object->errors));
1517 }
1518 if (empty($errmsg)) {
1519 $errmsg = $langs->trans('ErrorUnknown');
1520 }
1521
1522 dol_syslog(get_class($this)."::run_jobs END result=".$result." error=".$errmsg, LOG_ERR);
1523
1524 $this->error = $errmsg;
1525 $this->lastoutput = dol_substr((empty($object->output) ? "" : $object->output."\n").$errmsg, 0, $this::MAXIMUM_LENGTH_FOR_LASTOUTPUT_FIELD, 'UTF-8', 1);
1526 $this->lastresult = is_numeric($result) ? var_export($result, true) : '-1';
1527 $error++;
1528 } else {
1529 dol_syslog(get_class($this)."::run_jobs END");
1530 $this->lastoutput = dol_substr((empty($object->output) ? "" : $object->output."\n"), 0, $this::MAXIMUM_LENGTH_FOR_LASTOUTPUT_FIELD, 'UTF-8', 1);
1531 $this->lastresult = var_export($result, true);
1532 }
1533 }
1534 }
1535
1536 if ($this->jobtype == 'function') {
1537 //load lib
1538 $libpath = '/'.strtolower($this->module_name).'/lib/'.$this->libname;
1539 $ret = dol_include_once($libpath);
1540 if ($ret === false) {
1541 $this->error = $langs->trans('CronCannotLoadLib').': '.$libpath;
1542 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1543 $this->lastoutput = $this->error;
1544 $this->lastresult = '-1';
1545 $error++;
1546 }
1547
1548 // Load langs
1549 if (!$error) {
1550 $result = $langs->load($this->module_name);
1551 $result = $langs->load($this->module_name.'@'.$this->module_name); // If this->module_name was an existing language file, this will make nothing
1552 if ($result < 0) { // If technical error
1553 dol_syslog(get_class($this)."::run_jobs Cannot load module langs".$langs->error, LOG_ERR);
1554 $this->error = $langs->error;
1555 $this->lastoutput = $this->error;
1556 $this->lastresult = '-1';
1557 $error++;
1558 }
1559 }
1560
1561 if (!$error) {
1562 dol_syslog(get_class($this)."::run_jobs ".$this->libname."::".$this->methodename."(".$this->params.");", LOG_DEBUG);
1563
1564 $params_arr = array();
1565 if (!empty($this->params) || $this->params === '0') {
1566 $params_arr = array_map('trim', explode(",", $this->params));
1567 }
1568
1569 $result = call_user_func_array($this->methodename, $params_arr);
1570
1571 if ($result === false || (!is_bool($result) && $result != 0)) {
1572 $langs->load("errors");
1573 dol_syslog(get_class($this)."::run_jobs result=".$result, LOG_ERR);
1574 $this->error = $langs->trans('ErrorUnknown');
1575 $this->lastoutput = $this->error;
1576 $this->lastresult = is_numeric($result) ? var_export($result, true) : '-1';
1577 $error++;
1578 } else {
1579 $this->lastoutput = var_export($result, true);
1580 $this->lastresult = var_export($result, true); // Return code
1581 }
1582 }
1583 }
1584
1585 // Run a command line
1586 if ($this->jobtype == 'command') {
1587 global $dolibarr_cron_allow_cli;
1588
1589 if (empty($dolibarr_cron_allow_cli)) {
1590 $langs->load("errors");
1591 $this->error = $langs->trans("FailedToExecutCommandJob");
1592 $this->lastoutput = '';
1593 $this->lastresult = $langs->trans("ErrorParameterMustBeEnabledToAllwoThisFeature", 'dolibarr_cron_allow_cli');
1594 $error++;
1595 } else {
1596 $outputdir = $conf->cron->dir_temp;
1597 if (empty($outputdir)) {
1598 $outputdir = $conf->cronjob->dir_temp;
1599 }
1600 dol_mkdir($outputdir);
1601
1602 if (!empty($outputdir)) {
1603 $outputfile = $outputdir.'/cronjob.'.$userlogin.'.out'; // File used with popen method
1604
1605 // Execute a CLI
1606 include_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
1607 $utils = new Utils($this->db);
1608 $arrayresult = $utils->executeCLI($this->command, $outputfile);
1609
1610 $this->error = $arrayresult['error'];
1611 $this->lastoutput = $arrayresult['output'];
1612 $this->lastresult = (string) $arrayresult['result'];
1613 } else {
1614 $langs->load("errors");
1615 $this->error = $langs->trans("ErrorNoTmpDir", (string) $outputdir);
1616 $this->lastoutput = '';
1617 $this->lastresult = '-1';
1618 $error++;
1619 }
1620 }
1621 }
1622
1623 dol_syslog(get_class($this)."::run_jobs now we update job to track it is finished (with success or error)");
1624
1625 $this->datelastresult = dol_now();
1626 $this->processing = 0;
1627 $this->pid = null;
1628 $result = $this->update($user); // This include begin/commit
1629 if ($result < 0) {
1630 dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
1631 $conf->setEntityValues($this->db, $savcurrententity);
1632 return -1;
1633 }
1634
1635 $conf->setEntityValues($this->db, $savcurrententity);
1636
1637 if ($error && !empty($this->email_alert)) {
1638 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1639 $subject = $langs->transnoentitiesnoconv("ErrorInBatch", $this->label);
1640 $msg = $langs->transnoentitiesnoconv("ErrorInBatch", $this->label);
1641 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
1642 $cmailfile = new CMailFile($subject, $this->email_alert, $from, $msg);
1643 $result = $cmailfile->sendfile(); // Do not test result
1644 }
1645
1646 return $error ? -1 : 1;
1647 }
1648
1649
1650 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1658 public function reprogram_jobs(string $userlogin, int $now)
1659 {
1660 // phpcs:enable
1661 dol_syslog(get_class($this)."::reprogram_jobs userlogin:$userlogin", LOG_DEBUG);
1662
1663 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1664 $user = new User($this->db);
1665 $result = $user->fetch(0, $userlogin);
1666 if ($result < 0) {
1667 $this->error = "User Error : ".$user->error;
1668 dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1669 return -1;
1670 } else {
1671 if (empty($user->id)) {
1672 $this->error = " User user login:".$userlogin." do not exists";
1673 dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1674 return -1;
1675 }
1676 }
1677
1678 dol_syslog(get_class($this)."::reprogram_jobs datenextrun=".$this->datenextrun." ".dol_print_date($this->datenextrun, 'dayhourrfc')." frequency=".$this->frequency." unitfrequency=".$this->unitfrequency, LOG_DEBUG);
1679
1680 if (empty($this->datenextrun)) {
1681 if (empty($this->datestart)) {
1682 if (!is_numeric($this->frequency) || (int) $this->unitfrequency == 2678400) {
1683 $this->datenextrun = dol_time_plus_duree($now, $this->frequency, 'm');
1684 } else {
1685 $this->datenextrun = $now + ((int) $this->frequency * (int) $this->unitfrequency);
1686 }
1687 } else {
1688 if (!is_numeric($this->frequency) || (int) $this->unitfrequency == 2678400) {
1689 $this->datenextrun = dol_time_plus_duree($this->datestart, $this->frequency, 'm');
1690 } else {
1691 $this->datenextrun = $this->datestart + ((int) $this->frequency * (int) $this->unitfrequency);
1692 }
1693 }
1694 }
1695
1696 if ($this->datenextrun < $now && $this->frequency > 0 && !empty($this->unitfrequency)) {
1697 // Loop until date is after future
1698 while ($this->datenextrun < $now) {
1699 if (!is_numeric($this->unitfrequency) || (int) $this->unitfrequency == 2678400 || (int) $this->unitfrequency <= 0) {
1700 $this->datenextrun = dol_time_plus_duree($this->datenextrun, $this->frequency, 'm');
1701 } else {
1702 $this->datenextrun += ((int) $this->frequency * (int) $this->unitfrequency);
1703 }
1704 }
1705 } else {
1706 dol_syslog(get_class($this)."::reprogram_jobs datenextrun is already in future, we do not change it");
1707 }
1708
1709
1710 // Archive job
1711 if ($this->autodelete == 2) {
1712 if (($this->maxrun > 0 && ($this->nbrun >= $this->maxrun))
1713 || ($this->dateend && ($this->datenextrun > $this->dateend))) {
1714 $this->status = self::STATUS_ARCHIVED;
1715 dol_syslog(get_class($this)."::reprogram_jobs Job will be set to archived", LOG_ERR);
1716 }
1717 }
1718
1719 $result = $this->update($user);
1720 if ($result < 0) {
1721 dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
1722 return -1;
1723 }
1724
1725 return 1;
1726 }
1727
1734 public function getLibStatut(int $mode = 0)
1735 {
1736 return $this->LibStatut($this->status, $mode, $this->processing, $this->lastresult);
1737 }
1738
1739 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1749 public function LibStatut(int $status, int $mode = 0, int $processing = 0, string $lastResult = '')
1750 {
1751 // phpcs:enable
1752 $this->labelStatus = array(); // Force reset o array because label depends on other fields
1753 $this->labelStatusShort = array();
1754
1755 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1756 global $langs;
1757 $langs->load('users');
1758
1759 $moreText = '';
1760 if ($processing) {
1761 $moreText = ' ('.$langs->trans("Running").')';
1762 } elseif ($lastResult) {
1763 $moreText .= ' ('.$langs->trans("Error").')';
1764 }
1765
1766 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled').$moreText;
1767 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Scheduled').$moreText;
1768 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
1769 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Scheduled');
1770 }
1771
1772 $statusType = 'status4';
1773 if ($status == self::STATUS_ENABLED && $processing) {
1774 $statusType = 'status1';
1775 }
1776 if ($status == self::STATUS_DISABLED) {
1777 $statusType = 'status5';
1778 }
1779 if ($status == self::STATUS_ENABLED && $this->lastresult) {
1780 $statusType = 'status8';
1781 }
1782
1783 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1784 }
1785}
$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,...
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:169
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:126
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_now($mode='gmt')
Return date for now.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
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)
Definition html.lib.php:181