dolibarr 22.0.5
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_AUTOMATIC_TRIGGER = 1;
61 const STATUS_MANUAL_TRIGGER = 2;
62 const STATUS_CANCELED = 9;
63
64 const TYPE_BLOCKING = 0;
65 const TYPE_NO_BLOCKING = 1;
66
67
96 // BEGIN MODULEBUILDER PROPERTIES
100 public $fields = array(
101 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
102 '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"),
103 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'searchall' => 1, 'css' => 'minwidth300', 'cssview' => 'wordbreak', 'csslist' => 'tdoverflowmax150', 'showoncombobox' => 2, 'validate' => 1, 'autofocusoncreate' => 1),
104 'type' => array('type' => 'select', 'label' => 'Type', 'enabled' => 1, 'position' => 40, 'notnull' => 1, 'default' => '0', 'visible' => 1, 'index' => 1, 'arrayofkeyval' => array('0' => 'Blocking', '1' => 'NoBlocking'), 'help' => 'WebhookTargetTypeHelp', 'validate' => 1),
105 '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,),
106 'url' => array('type' => 'url', 'label' => 'Url', 'enabled' => 1, 'position' => 55, 'notnull' => 1, 'visible' => 1,),
107 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 3, 'validate' => 1,),
108 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 61, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1,),
109 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 62, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1,),
110 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2,),
111 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2,),
112 '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',),
113 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
114 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
115 'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'position' => 2000, 'notnull' => 1, 'default' => '1', 'visible' => 1, 'index' => 1, 'arrayofkeyval' => array('0' => 'Disabled', '1' => 'AutomaticTrigger', '2' => 'ManualTrigger'), 'validate' => 1,),
116 );
120 public $rowid;
124 public $ref;
128 public $label;
132 public $type;
136 public $description;
140 public $note_public;
144 public $note_private;
148 public $fk_user_creat;
152 public $fk_user_modif;
156 public $import_key;
160 public $status;
164 public $url;
168 public $trigger_codes;
169
170 // END MODULEBUILDER PROPERTIES
171
172
173 // If this object has a subtable with lines
174
175 // /**
176 // * @var string Name of subtable line
177 // */
178 // public $table_element_line = 'webhook_targetline';
179
180 // /**
181 // * @var string Field with ID of parent key if this object has a parent
182 // */
183 // public $fk_element = 'fk_target';
184
185 // /**
186 // * @var string Name of subtable class that manage subtable lines
187 // */
188 // public $class_element_line = 'Targetline';
189
190 // /**
191 // * @var array List of child tables. To test if we can delete object.
192 // */
193 // protected $childtables = array();
194
195 // /**
196 // * @var array List of child tables. To know object to delete on cascade.
197 // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
198 // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
199 // */
200 // protected $childtablesoncascade = array('webhook_targetdet');
201
202 // /**
203 // * @var TargetLine[] Array of subtable lines
204 // */
205 // public $lines = array();
206
207
208
214 public function __construct(DoliDB $db)
215 {
216 global $langs;
217
218 $this->db = $db;
219
220 $this->ismultientitymanaged = 0;
221 $this->isextrafieldmanaged = 0;
222
223 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
224 $this->fields['rowid']['visible'] = 0;
225 }
226 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
227 $this->fields['entity']['enabled'] = 0;
228 }
229
230 // Unset fields that are disabled
231 foreach ($this->fields as $key => $val) {
232 if (isset($val['enabled']) && empty($val['enabled'])) {
233 unset($this->fields[$key]);
234 }
235 }
236
237 // Translate some data of arrayofkeyval
238 if (is_object($langs)) {
239 foreach ($this->fields as $key => $val) {
240 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
241 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
242 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
243 }
244 }
245 }
246 }
247 }
248
254 public function initListOfTriggers()
255 {
256 $entitytoicon = array(
257 'societe' => 'company',
258 'facture' => 'bill',
259 'commande' => 'order',
260 'order_supplier' => 'supplier_order',
261 'proposal_supplier' => 'supplier_proposal',
262 'invoice_supplier' => 'supplier_invoice',
263 'facturerec' => 'bill',
264 'ficheinter' => 'intervention',
265 'shipping' => 'shipment',
266 'contrat' => 'contract',
267 'recruitment' => 'recruitmentjobposition',
268 );
269 // Define the array $arrayofkeyval for $this->fields["trigger_codes"]
270 // @phan-suppress-next-line PhanTypeMismatchProperty
271 if (!empty($this->fields["trigger_codes"]['arrayofkeyval']) && is_array($this->fields["trigger_codes"]['arrayofkeyval']) && !empty($this->fields["trigger_codes"]["multiinput"])) {
272 $sql = "SELECT c.code, c.label, c.elementtype FROM ".MAIN_DB_PREFIX."c_action_trigger as c ORDER BY c.rang ASC";
273 $resql = $this->db->query($sql);
274 if ($resql) {
275 $num = $this->db->num_rows($resql);
276 $i = 0;
277 $arraytrigger = array();
278 while ($i < $num) {
279 $obj = $this->db->fetch_object($resql);
280 $elementtype = (!empty($entitytoicon[$obj->elementtype]) ? $entitytoicon[$obj->elementtype] : $obj->elementtype);
281 $arraytrigger[$obj->code] = img_object("", $elementtype).' '.$obj->label.' ('.$obj->code.')';
282 $i++;
283 }
284 $this->fields["trigger_codes"]['arrayofkeyval'] = $arraytrigger;
285 } else {
286 $this->errors[] = 'Error '.$this->db->lasterror();
287 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
288 }
289 }
290
291 return 1;
292 }
293
299 public function isTriggerCodeManualTarget($triggercode)
300 {
301 $res = 0;
302 $error = 0;
303 $sql = "SELECT COUNT(wt.rowid) as nbtarget";
304 $sql .= " FROM ".MAIN_DB_PREFIX."webhook_target as wt";
305 $sql .= " WHERE wt.status = ".((int) $this::STATUS_MANUAL_TRIGGER);
306 $sql .= " AND wt.trigger_codes LIKE '%".$this->db->escape($triggercode)."%'";
307 $resql = $this->db->query($sql);
308 if ($resql) {
309 $num = $this->db->num_rows($resql);
310 if ($num > 0) {
311 $obj = $this->db->fetch_object($resql);
312 $res = $obj->nbtarget;
313 }
314 } else {
315 $this->errors[] = 'Error '.$this->db->lasterror();
316 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
317 $error++;
318 }
319 if ($error) {
320 $res = $error * -1;
321 }
322 return $res;
323 }
324
332 public function create(User $user, $notrigger = 0)
333 {
334 $resultcreate = $this->createCommon($user, $notrigger);
335 $this->ref = (string) $this->id;
336
337 if ($resultcreate <= 0) {
338 return $resultcreate;
339 }
340
341 return $this->id;
342 }
343
351 public function createFromClone(User $user, $fromid)
352 {
353 global $langs, $extrafields;
354 $error = 0;
355
356 dol_syslog(__METHOD__, LOG_DEBUG);
357
358 $object = new self($this->db);
359
360 $this->db->begin();
361
362 // Load source object
363 $result = $object->fetchCommon($fromid);
364 if ($result > 0 && !empty($object->table_element_line)) {
365 $object->fetchLines();
366 }
367
368 // get lines so they will be clone
369 //foreach($this->lines as $line)
370 // $line->fetch_optionals();
371
372 // Reset some properties
373 unset($object->id);
374 unset($object->fk_user_creat);
375 unset($object->import_key);
376
377 // Clear fields
378 if (property_exists($object, 'ref')) {
379 // @phan-suppress-next-line PhanTypeInvalidDimOffset
380 $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
381 }
382 if (property_exists($object, 'label')) {
383 // @phan-suppress-next-line PhanTypeInvalidDimOffset
384 $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
385 }
386 if (property_exists($object, 'status')) {
387 $object->status = self::STATUS_DRAFT;
388 }
389 if (property_exists($object, 'date_creation')) {
390 $object->date_creation = dol_now();
391 }
392 if (property_exists($object, 'date_modification')) {
393 $object->date_modification = null;
394 }
395 // ...
396 // Clear extrafields that are unique
397 if (is_array($object->array_options) && count($object->array_options) > 0) {
398 $extrafields->fetch_name_optionals_label($this->table_element);
399 foreach ($object->array_options as $key => $option) {
400 $shortkey = preg_replace('/options_/', '', $key);
401 if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
402 //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
403 unset($object->array_options[$key]);
404 }
405 }
406 }
407
408 // Create clone
409 $object->context['createfromclone'] = 'createfromclone';
410 $result = $object->createCommon($user);
411 if ($result < 0) {
412 $error++;
414 }
415
416 // if (!$error) {
417 // // copy internal contacts
418 // if ($this->copy_linked_contact($object, 'internal') < 0) {
419 // $error++;
420 // }
421 // }
422
423 // if (!$error) {
424 // // copy external contacts if same company
425 // if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
426 // if ($this->copy_linked_contact($object, 'external') < 0) {
427 // $error++;
428 // }
429 // }
430 // }
431
432 unset($object->context['createfromclone']);
433
434 // End
435 if (!$error) {
436 $this->db->commit();
437 return $object;
438 } else {
439 $this->db->rollback();
440 return -1;
441 }
442 }
443
451 public function fetch($id, $ref = null)
452 {
453 $result = $this->fetchCommon($id, $ref);
454 if (empty($this->ref)) {
455 $this->ref = (string) $this->id;
456 }
457
458 return $result;
459 }
460
466 public function fetchLines()
467 {
468 $this->lines = array();
469
470 $result = $this->fetchLinesCommon();
471 return $result;
472 }
473
474
487 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
488 {
489 dol_syslog(__METHOD__, LOG_DEBUG);
490
491 $records = array();
492
493 $sql = "SELECT ";
494 $sql .= $this->getFieldList('t');
495 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
496 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
497 $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
498 } else {
499 $sql .= " WHERE 1 = 1";
500 }
501
502 $errormessage = '';
503 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
504 if ($errormessage) {
505 $this->errors[] = $errormessage;
506 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
507 return -1;
508 }
509
510 if (!empty($sortfield)) {
511 $sql .= $this->db->order($sortfield, $sortorder);
512 }
513 if (!empty($limit)) {
514 $sql .= $this->db->plimit($limit, $offset);
515 }
516
517 $resql = $this->db->query($sql);
518 if ($resql) {
519 $num = $this->db->num_rows($resql);
520 $i = 0;
521 while ($i < ($limit ? min($limit, $num) : $num)) {
522 $obj = $this->db->fetch_object($resql);
523
524 $record = new self($this->db);
525 $record->setVarsFromFetchObj($obj);
526
527 $records[$record->id] = $record;
528
529 $i++;
530 }
531 $this->db->free($resql);
532
533 return $records;
534 } else {
535 $this->errors[] = 'Error '.$this->db->lasterror();
536 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
537
538 return -1;
539 }
540 }
541
549 public function update(User $user, $notrigger = 0)
550 {
551 return $this->updateCommon($user, $notrigger);
552 }
553
561 public function delete(User $user, $notrigger = 0)
562 {
563 return $this->deleteCommon($user, $notrigger);
564 //return $this->deleteCommon($user, $notrigger, 1);
565 }
566
575 public function deleteLine(User $user, $idline, $notrigger = 0)
576 {
577 if ($this->status < 0) {
578 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
579 return -2;
580 }
581
582 return $this->deleteLineCommon($user, $idline, $notrigger);
583 }
584
585
593 public function validate($user, $notrigger = 0)
594 {
595 global $conf;
596
597 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
598
599 $error = 0;
600
601 // Protection
602 if ($this->status == self::STATUS_AUTOMATIC_TRIGGER) {
603 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
604 return 0;
605 }
606
607 $now = dol_now();
608
609 $this->db->begin();
610
611 // Define new ref
612 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
613 $num = $this->getNextNumRef();
614 } else {
615 $num = $this->ref;
616 }
617 $this->newref = $num;
618
619 if (!empty($num)) {
620 // Validate
621 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
622 $sql .= " SET ref = '".$this->db->escape($num)."',";
623 $sql .= " status = ".((int) self::STATUS_AUTOMATIC_TRIGGER);
624 if (!empty($this->fields['date_validation'])) {
625 $sql .= ", date_validation = '".$this->db->idate($now)."'";
626 }
627 if (!empty($this->fields['fk_user_valid'])) { // @phan-suppress-current-line PhanTypeMismatchProperty
628 $sql .= ", fk_user_valid = ".((int) $user->id);
629 }
630 $sql .= " WHERE rowid = ".((int) $this->id);
631
632 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
633 $resql = $this->db->query($sql);
634 if (!$resql) {
635 dol_print_error($this->db);
636 $this->error = $this->db->lasterror();
637 $error++;
638 }
639
640 if (!$error && !$notrigger) {
641 // Call trigger
642 $result = $this->call_trigger('TARGET_VALIDATE', $user);
643 if ($result < 0) {
644 $error++;
645 }
646 // End call triggers
647 }
648 }
649
650 if (!$error) {
651 $this->oldref = $this->ref;
652
653 // Rename directory if dir was a temporary ref
654 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
655 // Now we rename also files into index
656 $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)."'";
657 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'target/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
658 $resql = $this->db->query($sql);
659 if (!$resql) {
660 $error++;
661 $this->error = $this->db->lasterror();
662 }
663 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'target/".$this->db->escape($this->newref)."'";
664 $sql .= " WHERE filepath = 'target/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
665 $resql = $this->db->query($sql);
666 if (!$resql) {
667 $error++;
668 $this->error = $this->db->lasterror();
669 }
670
671 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
672 $oldref = dol_sanitizeFileName($this->ref);
673 $newref = dol_sanitizeFileName($num);
674 $dirsource = $conf->webhook->dir_output.'/target/'.$oldref;
675 $dirdest = $conf->webhook->dir_output.'/target/'.$newref;
676 if (!$error && file_exists($dirsource)) {
677 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
678
679 if (@rename($dirsource, $dirdest)) {
680 dol_syslog("Rename ok");
681 // Rename docs starting with $oldref with $newref
682 $listoffiles = dol_dir_list($conf->webhook->dir_output.'/target/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
683 foreach ($listoffiles as $fileentry) {
684 $dirsource = $fileentry['name'];
685 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
686 $dirsource = $fileentry['path'].'/'.$dirsource;
687 $dirdest = $fileentry['path'].'/'.$dirdest;
688 @rename($dirsource, $dirdest);
689 }
690 }
691 }
692 }
693 }
694
695 // Set new ref and current status
696 if (!$error) {
697 $this->ref = $num;
698 $this->status = self::STATUS_AUTOMATIC_TRIGGER;
699 }
700
701 if (!$error) {
702 $this->db->commit();
703 return 1;
704 } else {
705 $this->db->rollback();
706 return -1;
707 }
708 }
709
710
718 public function setDraft($user, $notrigger = 0)
719 {
720 // Protection
721 if ($this->status <= self::STATUS_DRAFT) {
722 return 0;
723 }
724
725 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'TARGET_UNVALIDATE');
726 }
727
735 public function cancel($user, $notrigger = 0)
736 {
737 // Protection
738 if ($this->status != self::STATUS_AUTOMATIC_TRIGGER) {
739 return 0;
740 }
741
742 return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'TARGET_CANCEL');
743 }
744
752 public function reopen($user, $notrigger = 0)
753 {
754 // Protection
755 if ($this->status != self::STATUS_CANCELED) {
756 return 0;
757 }
758
759 return $this->setStatusCommon($user, self::STATUS_AUTOMATIC_TRIGGER, $notrigger, 'TARGET_REOPEN');
760 }
761
772 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
773 {
774 global $conf, $langs, $hookmanager;
775
776 if (!empty($conf->dol_no_mouse_hover)) {
777 $notooltip = 1; // Force disable tooltips
778 }
779
780 $result = '';
781
782 $label = img_picto('', $this->picto).' <u>'.$langs->trans("Target").'</u>';
783 if (isset($this->status)) {
784 $label .= ' '.$this->getLibStatut(5);
785 }
786 $label .= '<br>';
787 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
788
789 $url = dol_buildpath('/webhook/target_card.php', 1).'?id='.$this->id;
790
791 if ($option != 'nolink') {
792 // Add param to save lastsearch_values or not
793 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
794 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
795 $add_save_lastsearch_values = 1;
796 }
797 if ($url && $add_save_lastsearch_values) {
798 $url .= '&save_lastsearch_values=1';
799 }
800 }
801
802 $linkclose = '';
803 if (empty($notooltip)) {
804 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
805 $label = $langs->trans("ShowTarget");
806 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
807 }
808 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
809 $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
810 } else {
811 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
812 }
813
814 if ($option == 'nolink' || empty($url)) {
815 $linkstart = '<span';
816 } else {
817 $linkstart = '<a href="'.$url.'"';
818 }
819 $linkstart .= $linkclose.'>';
820 if ($option == 'nolink' || empty($url)) {
821 $linkend = '</span>';
822 } else {
823 $linkend = '</a>';
824 }
825
826 $result .= $linkstart;
827
828 if (empty($this->showphoto_on_popup)) {
829 if ($withpicto) {
830 $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);
831 }
832 } else {
833 if ($withpicto) {
834 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
835
836 list($class, $module) = explode('@', $this->picto);
837 $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
838 $filearray = dol_dir_list($upload_dir, "files");
839 $filename = $filearray[0]['name'];
840 if (!empty($filename)) {
841 $pospoint = strpos($filearray[0]['name'], '.');
842
843 $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
844 if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
845 $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>';
846 } else {
847 $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>';
848 }
849
850 $result .= '</div>';
851 } else {
852 $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);
853 }
854 }
855 }
856
857 if ($withpicto != 2) {
858 $result .= $this->ref;
859 }
860
861 $result .= $linkend;
862 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
863
864 global $action, $hookmanager;
865 $hookmanager->initHooks(array('targetdao'));
866 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
867 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
868 if ($reshook > 0) {
869 $result = $hookmanager->resPrint;
870 } else {
871 $result .= $hookmanager->resPrint;
872 }
873
874 return $result;
875 }
876
883 public function getLabelStatus($mode = 0)
884 {
885 return $this->LibStatut($this->status, $mode);
886 }
887
894 public function getLibStatut($mode = 0)
895 {
896 return $this->LibStatut($this->status, $mode);
897 }
898
899 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
907 public function LibStatut($status, $mode = 0)
908 {
909 // phpcs:enable
910 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
911 global $langs;
912
913 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Disabled');
914 $this->labelStatus[self::STATUS_AUTOMATIC_TRIGGER] = $langs->transnoentitiesnoconv('AutomaticTrigger');
915 $this->labelStatus[self::STATUS_MANUAL_TRIGGER] = $langs->transnoentitiesnoconv('ManualTrigger');
916 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
917 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Disabled');
918 $this->labelStatusShort[self::STATUS_AUTOMATIC_TRIGGER] = $langs->transnoentitiesnoconv('AutomaticTrigger');
919 $this->labelStatusShort[self::STATUS_MANUAL_TRIGGER] = $langs->transnoentitiesnoconv('ManualTrigger');
920 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
921 }
922
923 $statusType = 'status'.$status;
924 if ($status == self::STATUS_AUTOMATIC_TRIGGER) {
925 $statusType = 'status4';
926 }
927 if ($status == self::STATUS_MANUAL_TRIGGER) {
928 $statusType = 'status3';
929 }
930 if ($status == self::STATUS_CANCELED) {
931 $statusType = 'status6';
932 }
933
934 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
935 }
936
943 public function info($id)
944 {
945 $sql = "SELECT rowid, date_creation as datec, tms as datem,";
946 $sql .= " fk_user_creat, fk_user_modif";
947 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
948 $sql .= " WHERE t.rowid = ".((int) $id);
949
950 $result = $this->db->query($sql);
951 if ($result) {
952 if ($this->db->num_rows($result)) {
953 $obj = $this->db->fetch_object($result);
954
955 $this->id = $obj->rowid;
956
957 $this->user_creation_id = $obj->fk_user_creat;
958 $this->user_modification_id = $obj->fk_user_modif;
959 $this->date_creation = $this->db->jdate($obj->datec);
960 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
961 }
962
963 $this->db->free($result);
964 } else {
965 dol_print_error($this->db);
966 }
967 }
968
975 public function initAsSpecimen()
976 {
977 $this->url = "https://thisisunurl";
978 $this->trigger_codes = "ThisIsATestCode";
979
980 return $this->initAsSpecimenCommon();
981 }
982
988 public function getNextNumRef()
989 {
990 global $langs, $conf;
991
992 $mybool = false;
993
994 $classname = getDolGlobalString('WEBHOOK_TARGET_ADDON', 'mod_target_standard');
995 $file = $classname.".php";
996
997 // Include file with class
998 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
999 foreach ($dirmodels as $reldir) {
1000 $dir = dol_buildpath($reldir."core/modules/webhook/");
1001
1002 // Load file with numbering class (if found)
1003 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1004 }
1005
1006 if (!$mybool) {
1007 dol_print_error(null, "Failed to include file ".$file);
1008 return '';
1009 }
1010
1011 if (class_exists($classname)) {
1012 $obj = new $classname();
1013 '@phan-var-force CommonNumRefGenerator $obj';
1014 $numref = $obj->getNextValue($this);
1015
1016 if ($numref != '' && $numref != '-1') {
1017 return $numref;
1018 } else {
1019 $this->error = $obj->error;
1020 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1021 return "";
1022 }
1023 } else {
1024 print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1025 return "";
1026 }
1027 }
1028
1040 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1041 {
1042 $result = 0;
1043 $includedocgeneration = 0;
1044
1045 if (!dol_strlen($modele)) {
1046 $modele = 'standard_target';
1047
1048 if (!empty($this->model_pdf)) {
1049 $modele = $this->model_pdf;
1050 } elseif (getDolGlobalString('TARGET_ADDON_PDF')) {
1051 $modele = getDolGlobalString('TARGET_ADDON_PDF');
1052 }
1053 }
1054
1055 $modelpath = "core/modules/webhook/doc/";
1056
1057 if ($includedocgeneration && !empty($modele)) {
1058 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1059 }
1060
1061 return $result;
1062 }
1063
1071 public function doScheduledJob()
1072 {
1073 //global $conf, $langs;
1074
1075 //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1076
1077 $error = 0;
1078 $this->output = '';
1079 $this->error = '';
1080
1081 dol_syslog(__METHOD__, LOG_DEBUG);
1082
1083 //$now = dol_now();
1084
1085 $this->db->begin();
1086
1087 // ...
1088
1089 $this->db->commit();
1090
1091 return $error;
1092 }
1093}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
$object ref
Definition info.php:90
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.
isTriggerCodeManualTarget($triggercode)
Test if a TriggerCode is inside a Target with status to Manual.
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 in emory the list of all objects 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.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
dol_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_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79