dolibarr 20.0.2
target.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) ---Put here your own copyright and developer email---
4 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Put here all includes required by your class file
28require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
29//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
30//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
31
35class Target extends CommonObject
36{
40 public $module = 'webhook';
41
45 public $element = 'target';
46
50 public $table_element = 'webhook_target';
51
55 public $picto = 'webhook';
56
57
58 const STATUS_DRAFT = 0;
59 const STATUS_VALIDATED = 1;
60 const STATUS_CANCELED = 9;
61
62
91 // BEGIN MODULEBUILDER PROPERTIES
95 public $fields = array(
96 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
97 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 20, 'notnull' => 1, 'visible' => 4, 'noteditable' => 1, 'index' => 1, 'searchall' => 1, 'validate' => 1, 'comment' => "Reference of object"),
98 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'position' => 30, 'notnull' => 0, 'visible' => 1, 'searchall' => 1, 'css' => 'minwidth300', 'cssview' => 'wordbreak', 'csslist'=>'tdoverflowmax150', 'showoncombobox' => 2, 'validate' => 1,),
99 'trigger_codes' => array('type' => 'text', 'label' => 'TriggerCodes', 'enabled' => 1, 'position' => 50, 'notnull' => 1, 'visible' => 1, 'help' => "TriggerCodeInfo", 'tdcss'=>'titlefieldmiddle', 'csslist'=>'tdoverflowmax200', 'css' => 'minwidth400', 'arrayofkeyval' => array('defined_in_constructor' => 'defined_from_c_action_trigger'), 'multiinput' => 1,),
100 'url' => array('type' => 'url', 'label' => 'Url', 'enabled' => 1, 'position' => 55, 'notnull' => 1, 'visible' => 1,),
101 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 3, 'validate' => 1,),
102 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 61, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1,),
103 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 62, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1,),
104 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2,),
105 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2,),
106 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'position' => 510, 'notnull' => 1, 'visible' => -2, 'foreignkey' => 'user.rowid',),
107 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
108 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
109 'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'position' => 2000, 'notnull' => 1, 'default' => '1', 'visible' => 1, 'index' => 1, 'arrayofkeyval' => array('0' => 'Disabled', '1' => 'Enabled'), 'validate' => 1,),
110 );
111 public $rowid;
112 public $ref;
113 public $label;
114 public $description;
115 public $note_public;
116 public $note_private;
117 public $date_creation;
118 public $fk_user_creat;
119 public $fk_user_modif;
120 public $import_key;
121 public $status;
122 public $url;
126 public $trigger_codes;
127 // END MODULEBUILDER PROPERTIES
128
129
130 // If this object has a subtable with lines
131
132 // /**
133 // * @var string Name of subtable line
134 // */
135 // public $table_element_line = 'webhook_targetline';
136
137 // /**
138 // * @var string Field with ID of parent key if this object has a parent
139 // */
140 // public $fk_element = 'fk_target';
141
142 // /**
143 // * @var string Name of subtable class that manage subtable lines
144 // */
145 // public $class_element_line = 'Targetline';
146
147 // /**
148 // * @var array List of child tables. To test if we can delete object.
149 // */
150 // protected $childtables = array();
151
152 // /**
153 // * @var array List of child tables. To know object to delete on cascade.
154 // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
155 // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
156 // */
157 // protected $childtablesoncascade = array('webhook_targetdet');
158
159 // /**
160 // * @var TargetLine[] Array of subtable lines
161 // */
162 // public $lines = array();
163
164
165
171 public function __construct(DoliDB $db)
172 {
173 global $langs;
174
175 $this->db = $db;
176
177 $this->ismultientitymanaged = 0;
178 $this->isextrafieldmanaged = 0;
179
180 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
181 $this->fields['rowid']['visible'] = 0;
182 }
183 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
184 $this->fields['entity']['enabled'] = 0;
185 }
186
187 // Unset fields that are disabled
188 foreach ($this->fields as $key => $val) {
189 if (isset($val['enabled']) && empty($val['enabled'])) {
190 unset($this->fields[$key]);
191 }
192 }
193
194 // Translate some data of arrayofkeyval
195 if (is_object($langs)) {
196 foreach ($this->fields as $key => $val) {
197 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
198 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
199 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
200 }
201 }
202 }
203 }
204 }
205
211 public function initListOfTriggers()
212 {
213 // Define the array $arrayofkeyval for $this->fields["trigger_codes"]
214 if (!empty($this->fields["trigger_codes"]['arrayofkeyval']) && is_array($this->fields["trigger_codes"]['arrayofkeyval']) && !empty($this->fields["trigger_codes"]["multiinput"])) {
215 $sql = "SELECT c.code, c.label FROM ".MAIN_DB_PREFIX."c_action_trigger as c ORDER BY c.rang DESC";
216 $resql = $this->db->query($sql);
217 if ($resql) {
218 $num = $this->db->num_rows($resql);
219 $i = 0;
220 $arraytrigger = array();
221 while ($i < $num) {
222 $obj = $this->db->fetch_object($resql);
223 $arraytrigger[$obj->code] = $obj->label.' ('.$obj->code.')';
224 $i++;
225 }
226 $this->fields["trigger_codes"]['arrayofkeyval'] = $arraytrigger;
227 } else {
228 $this->errors[] = 'Error '.$this->db->lasterror();
229 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
230 }
231 }
232
233 return 1;
234 }
235
243 public function create(User $user, $notrigger = 0)
244 {
245 $resultcreate = $this->createCommon($user, $notrigger);
246 $this->ref = (string) $this->id;
247
248 if ($resultcreate <= 0) {
249 return $resultcreate;
250 }
251
252 return $this->id;
253 }
254
262 public function createFromClone(User $user, $fromid)
263 {
264 global $langs, $extrafields;
265 $error = 0;
266
267 dol_syslog(__METHOD__, LOG_DEBUG);
268
269 $object = new self($this->db);
270
271 $this->db->begin();
272
273 // Load source object
274 $result = $object->fetchCommon($fromid);
275 if ($result > 0 && !empty($object->table_element_line)) {
276 $object->fetchLines();
277 }
278
279 // get lines so they will be clone
280 //foreach($this->lines as $line)
281 // $line->fetch_optionals();
282
283 // Reset some properties
284 unset($object->id);
285 unset($object->fk_user_creat);
286 unset($object->import_key);
287
288 // Clear fields
289 if (property_exists($object, 'ref')) {
290 $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
291 }
292 if (property_exists($object, 'label')) {
293 $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
294 }
295 if (property_exists($object, 'status')) {
296 $object->status = self::STATUS_DRAFT;
297 }
298 if (property_exists($object, 'date_creation')) {
299 $object->date_creation = dol_now();
300 }
301 if (property_exists($object, 'date_modification')) {
302 $object->date_modification = null;
303 }
304 // ...
305 // Clear extrafields that are unique
306 if (is_array($object->array_options) && count($object->array_options) > 0) {
307 $extrafields->fetch_name_optionals_label($this->table_element);
308 foreach ($object->array_options as $key => $option) {
309 $shortkey = preg_replace('/options_/', '', $key);
310 if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
311 //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
312 unset($object->array_options[$key]);
313 }
314 }
315 }
316
317 // Create clone
318 $object->context['createfromclone'] = 'createfromclone';
319 $result = $object->createCommon($user);
320 if ($result < 0) {
321 $error++;
323 }
324
325 // if (!$error) {
326 // // copy internal contacts
327 // if ($this->copy_linked_contact($object, 'internal') < 0) {
328 // $error++;
329 // }
330 // }
331
332 // if (!$error) {
333 // // copy external contacts if same company
334 // if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
335 // if ($this->copy_linked_contact($object, 'external') < 0) {
336 // $error++;
337 // }
338 // }
339 // }
340
341 unset($object->context['createfromclone']);
342
343 // End
344 if (!$error) {
345 $this->db->commit();
346 return $object;
347 } else {
348 $this->db->rollback();
349 return -1;
350 }
351 }
352
360 public function fetch($id, $ref = null)
361 {
362 $result = $this->fetchCommon($id, $ref);
363 if (empty($this->ref)) {
364 $this->ref = (string) $this->id;
365 }
366
367 return $result;
368 }
369
375 public function fetchLines()
376 {
377 $this->lines = array();
378
379 $result = $this->fetchLinesCommon();
380 return $result;
381 }
382
383
396 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
397 {
398 dol_syslog(__METHOD__, LOG_DEBUG);
399
400 $records = array();
401
402 $sql = "SELECT ";
403 $sql .= $this->getFieldList('t');
404 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
405 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
406 $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
407 } else {
408 $sql .= " WHERE 1 = 1";
409 }
410
411 $errormessage = '';
412 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
413 if ($errormessage) {
414 $this->errors[] = $errormessage;
415 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
416 return -1;
417 }
418
419 if (!empty($sortfield)) {
420 $sql .= $this->db->order($sortfield, $sortorder);
421 }
422 if (!empty($limit)) {
423 $sql .= $this->db->plimit($limit, $offset);
424 }
425
426 $resql = $this->db->query($sql);
427 if ($resql) {
428 $num = $this->db->num_rows($resql);
429 $i = 0;
430 while ($i < ($limit ? min($limit, $num) : $num)) {
431 $obj = $this->db->fetch_object($resql);
432
433 $record = new self($this->db);
434 $record->setVarsFromFetchObj($obj);
435
436 $records[$record->id] = $record;
437
438 $i++;
439 }
440 $this->db->free($resql);
441
442 return $records;
443 } else {
444 $this->errors[] = 'Error '.$this->db->lasterror();
445 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
446
447 return -1;
448 }
449 }
450
458 public function update(User $user, $notrigger = 0)
459 {
460 // Clean trigger_codes
461 $this->trigger_codes = preg_replace('/[\r\n\s]/', '', $this->trigger_codes);
462
463 return $this->updateCommon($user, $notrigger);
464 }
465
473 public function delete(User $user, $notrigger = 0)
474 {
475 return $this->deleteCommon($user, $notrigger);
476 //return $this->deleteCommon($user, $notrigger, 1);
477 }
478
487 public function deleteLine(User $user, $idline, $notrigger = 0)
488 {
489 if ($this->status < 0) {
490 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
491 return -2;
492 }
493
494 return $this->deleteLineCommon($user, $idline, $notrigger);
495 }
496
497
505 public function validate($user, $notrigger = 0)
506 {
507 global $conf;
508
509 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
510
511 $error = 0;
512
513 // Protection
514 if ($this->status == self::STATUS_VALIDATED) {
515 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
516 return 0;
517 }
518
519 $now = dol_now();
520
521 $this->db->begin();
522
523 // Define new ref
524 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
525 $num = $this->getNextNumRef();
526 } else {
527 $num = $this->ref;
528 }
529 $this->newref = $num;
530
531 if (!empty($num)) {
532 // Validate
533 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
534 $sql .= " SET ref = '".$this->db->escape($num)."',";
535 $sql .= " status = ".self::STATUS_VALIDATED;
536 if (!empty($this->fields['date_validation'])) {
537 $sql .= ", date_validation = '".$this->db->idate($now)."'";
538 }
539 if (!empty($this->fields['fk_user_valid'])) {
540 $sql .= ", fk_user_valid = ".((int) $user->id);
541 }
542 $sql .= " WHERE rowid = ".((int) $this->id);
543
544 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
545 $resql = $this->db->query($sql);
546 if (!$resql) {
547 dol_print_error($this->db);
548 $this->error = $this->db->lasterror();
549 $error++;
550 }
551
552 if (!$error && !$notrigger) {
553 // Call trigger
554 $result = $this->call_trigger('TARGET_VALIDATE', $user);
555 if ($result < 0) {
556 $error++;
557 }
558 // End call triggers
559 }
560 }
561
562 if (!$error) {
563 $this->oldref = $this->ref;
564
565 // Rename directory if dir was a temporary ref
566 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
567 // Now we rename also files into index
568 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'target/".$this->db->escape($this->newref)."'";
569 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'target/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
570 $resql = $this->db->query($sql);
571 if (!$resql) {
572 $error++;
573 $this->error = $this->db->lasterror();
574 }
575 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'target/".$this->db->escape($this->newref)."'";
576 $sql .= " WHERE filepath = 'target/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
577 $resql = $this->db->query($sql);
578 if (!$resql) {
579 $error++;
580 $this->error = $this->db->lasterror();
581 }
582
583 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
584 $oldref = dol_sanitizeFileName($this->ref);
585 $newref = dol_sanitizeFileName($num);
586 $dirsource = $conf->webhook->dir_output.'/target/'.$oldref;
587 $dirdest = $conf->webhook->dir_output.'/target/'.$newref;
588 if (!$error && file_exists($dirsource)) {
589 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
590
591 if (@rename($dirsource, $dirdest)) {
592 dol_syslog("Rename ok");
593 // Rename docs starting with $oldref with $newref
594 $listoffiles = dol_dir_list($conf->webhook->dir_output.'/target/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
595 foreach ($listoffiles as $fileentry) {
596 $dirsource = $fileentry['name'];
597 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
598 $dirsource = $fileentry['path'].'/'.$dirsource;
599 $dirdest = $fileentry['path'].'/'.$dirdest;
600 @rename($dirsource, $dirdest);
601 }
602 }
603 }
604 }
605 }
606
607 // Set new ref and current status
608 if (!$error) {
609 $this->ref = $num;
610 $this->status = self::STATUS_VALIDATED;
611 }
612
613 if (!$error) {
614 $this->db->commit();
615 return 1;
616 } else {
617 $this->db->rollback();
618 return -1;
619 }
620 }
621
622
630 public function setDraft($user, $notrigger = 0)
631 {
632 // Protection
633 if ($this->status <= self::STATUS_DRAFT) {
634 return 0;
635 }
636
637 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'TARGET_UNVALIDATE');
638 }
639
647 public function cancel($user, $notrigger = 0)
648 {
649 // Protection
650 if ($this->status != self::STATUS_VALIDATED) {
651 return 0;
652 }
653
654 return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'TARGET_CANCEL');
655 }
656
664 public function reopen($user, $notrigger = 0)
665 {
666 // Protection
667 if ($this->status != self::STATUS_CANCELED) {
668 return 0;
669 }
670
671 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'TARGET_REOPEN');
672 }
673
684 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
685 {
686 global $conf, $langs, $hookmanager;
687
688 if (!empty($conf->dol_no_mouse_hover)) {
689 $notooltip = 1; // Force disable tooltips
690 }
691
692 $result = '';
693
694 $label = img_picto('', $this->picto).' <u>'.$langs->trans("Target").'</u>';
695 if (isset($this->status)) {
696 $label .= ' '.$this->getLibStatut(5);
697 }
698 $label .= '<br>';
699 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
700
701 $url = dol_buildpath('/webhook/target_card.php', 1).'?id='.$this->id;
702
703 if ($option != 'nolink') {
704 // Add param to save lastsearch_values or not
705 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
706 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
707 $add_save_lastsearch_values = 1;
708 }
709 if ($url && $add_save_lastsearch_values) {
710 $url .= '&save_lastsearch_values=1';
711 }
712 }
713
714 $linkclose = '';
715 if (empty($notooltip)) {
716 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
717 $label = $langs->trans("ShowTarget");
718 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
719 }
720 $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
721 $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
722 } else {
723 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
724 }
725
726 if ($option == 'nolink' || empty($url)) {
727 $linkstart = '<span';
728 } else {
729 $linkstart = '<a href="'.$url.'"';
730 }
731 $linkstart .= $linkclose.'>';
732 if ($option == 'nolink' || empty($url)) {
733 $linkend = '</span>';
734 } else {
735 $linkend = '</a>';
736 }
737
738 $result .= $linkstart;
739
740 if (empty($this->showphoto_on_popup)) {
741 if ($withpicto) {
742 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
743 }
744 } else {
745 if ($withpicto) {
746 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
747
748 list($class, $module) = explode('@', $this->picto);
749 $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
750 $filearray = dol_dir_list($upload_dir, "files");
751 $filename = $filearray[0]['name'];
752 if (!empty($filename)) {
753 $pospoint = strpos($filearray[0]['name'], '.');
754
755 $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
756 if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
757 $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
758 } else {
759 $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
760 }
761
762 $result .= '</div>';
763 } else {
764 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
765 }
766 }
767 }
768
769 if ($withpicto != 2) {
770 $result .= $this->ref;
771 }
772
773 $result .= $linkend;
774 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
775
776 global $action, $hookmanager;
777 $hookmanager->initHooks(array('targetdao'));
778 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
779 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
780 if ($reshook > 0) {
781 $result = $hookmanager->resPrint;
782 } else {
783 $result .= $hookmanager->resPrint;
784 }
785
786 return $result;
787 }
788
795 public function getLabelStatus($mode = 0)
796 {
797 return $this->LibStatut($this->status, $mode);
798 }
799
806 public function getLibStatut($mode = 0)
807 {
808 return $this->LibStatut($this->status, $mode);
809 }
810
811 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
819 public function LibStatut($status, $mode = 0)
820 {
821 // phpcs:enable
822 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
823 global $langs;
824
825 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
826 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
827 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
828 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
829 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
830 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
831 }
832
833 $statusType = 'status'.$status;
834 if ($status == self::STATUS_VALIDATED) {
835 $statusType = 'status4';
836 }
837 if ($status == self::STATUS_CANCELED) {
838 $statusType = 'status6';
839 }
840
841 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
842 }
843
850 public function info($id)
851 {
852 $sql = "SELECT rowid, date_creation as datec, tms as datem,";
853 $sql .= " fk_user_creat, fk_user_modif";
854 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
855 $sql .= " WHERE t.rowid = ".((int) $id);
856
857 $result = $this->db->query($sql);
858 if ($result) {
859 if ($this->db->num_rows($result)) {
860 $obj = $this->db->fetch_object($result);
861
862 $this->id = $obj->rowid;
863
864 $this->user_creation_id = $obj->fk_user_creat;
865 $this->user_modification_id = $obj->fk_user_modif;
866 $this->date_creation = $this->db->jdate($obj->datec);
867 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
868 }
869
870 $this->db->free($result);
871 } else {
872 dol_print_error($this->db);
873 }
874 }
875
882 public function initAsSpecimen()
883 {
884 $this->url = "https://thisisunurl";
885 $this->trigger_codes = "ThisIsATestCode";
886
887 return $this->initAsSpecimenCommon();
888 }
889
895 public function getNextNumRef()
896 {
897 global $langs, $conf;
898
899 $mybool = false;
900
901 $classname = getDolGlobalString('WEBHOOK_TARGET_ADDON', 'mod_target_standard');
902 $file = $classname.".php";
903
904 // Include file with class
905 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
906 foreach ($dirmodels as $reldir) {
907 $dir = dol_buildpath($reldir."core/modules/webhook/");
908
909 // Load file with numbering class (if found)
910 $mybool = ((bool) @include_once $dir.$file) || $mybool;
911 }
912
913 if ($mybool === false) {
914 dol_print_error(null, "Failed to include file ".$file);
915 return '';
916 }
917
918 if (class_exists($classname)) {
919 $obj = new $classname();
920 $numref = $obj->getNextValue($this);
921
922 if ($numref != '' && $numref != '-1') {
923 return $numref;
924 } else {
925 $this->error = $obj->error;
926 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
927 return "";
928 }
929 } else {
930 print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
931 return "";
932 }
933 }
934
946 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
947 {
948 $result = 0;
949 $includedocgeneration = 0;
950
951 if (!dol_strlen($modele)) {
952 $modele = 'standard_target';
953
954 if (!empty($this->model_pdf)) {
955 $modele = $this->model_pdf;
956 } elseif (getDolGlobalString('TARGET_ADDON_PDF')) {
957 $modele = getDolGlobalString('TARGET_ADDON_PDF');
958 }
959 }
960
961 $modelpath = "core/modules/webhook/doc/";
962
963 if ($includedocgeneration && !empty($modele)) {
964 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
965 }
966
967 return $result;
968 }
969
977 public function doScheduledJob()
978 {
979 //global $conf, $langs;
980
981 //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
982
983 $error = 0;
984 $this->output = '';
985 $this->error = '';
986
987 dol_syslog(__METHOD__, LOG_DEBUG);
988
989 //$now = dol_now();
990
991 $this->db->begin();
992
993 // ...
994
995 $this->db->commit();
996
997 return $error;
998 }
999}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:637
$object ref
Definition info.php:79
Parent class of all other business classes (invoices, contracts, proposals, orders,...
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setErrorsFromObject($object)
setErrorsFromObject
createCommon(User $user, $notrigger=0)
Create object in the database.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
updateCommon(User $user, $notrigger=0)
Update object into database.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
Class for Target.
deleteLine(User $user, $idline, $notrigger=0)
Delete a line of object in database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
initListOfTriggers()
Init the list of available triggers;.
getLabelStatus($mode=0)
Return the label of the status.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
fetchLines()
Load object lines in memory from the database.
info($id)
Load the info information in the object.
fetch($id, $ref=null)
Load object in memory from the database.
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
__construct(DoliDB $db)
Constructor.
getLibStatut($mode=0)
Return the label of the status.
reopen($user, $notrigger=0)
Set back to validated status.
createFromClone(User $user, $fromid)
Clone an object into another one.
LibStatut($status, $mode=0)
Return the status.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
create(User $user, $notrigger=0)
Create object into database.
getNextNumRef()
Returns the reference to the following non used object depending on the active numbering module.
cancel($user, $notrigger=0)
Set cancel status.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND')
Load list of objects in memory from the database.
validate($user, $notrigger=0)
Validate object.
setDraft($user, $notrigger=0)
Set draft status.
update(User $user, $notrigger=0)
Update object into database.
Class to manage Dolibarr users.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.