target.class.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) ---Put here your own copyright and developer email---
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file class/target.class.php
  20. * \ingroup webhook
  21. * \brief This file is a CRUD class file for Target (Create/Read/Update/Delete)
  22. */
  23. // Put here all includes required by your class file
  24. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  25. //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  26. //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  27. /**
  28. * Class for Target
  29. */
  30. class Target extends CommonObject
  31. {
  32. /**
  33. * @var string ID of module.
  34. */
  35. public $module = 'webhook';
  36. /**
  37. * @var string ID to identify managed object.
  38. */
  39. public $element = 'target';
  40. /**
  41. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  42. */
  43. public $table_element = 'webhook_target';
  44. /**
  45. * @var int Does this object support multicompany module ?
  46. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  47. */
  48. public $ismultientitymanaged = 0;
  49. /**
  50. * @var int Does object support extrafields ? 0=No, 1=Yes
  51. */
  52. public $isextrafieldmanaged = 0;
  53. /**
  54. * @var string String with name of icon for target. Must be the part after the 'object_' into object_target.png
  55. */
  56. public $picto = 'webhook';
  57. const STATUS_DRAFT = 0;
  58. const STATUS_VALIDATED = 1;
  59. const STATUS_CANCELED = 9;
  60. /**
  61. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  62. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  63. * 'label' the translation key.
  64. * 'picto' is code of a picto to show before value in forms
  65. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM' or 'isModEnabled("multicurrency")' ...)
  66. * 'position' is the sort order of field.
  67. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  68. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  69. * 'noteditable' says if field is not editable (1 or 0)
  70. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  71. * 'index' if we want an index in database.
  72. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  73. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  74. * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
  75. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
  76. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  77. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  78. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  79. * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
  80. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  81. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  82. * 'validate' is 1 if need to validate with $this->validateField()
  83. * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
  84. *
  85. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  86. */
  87. // BEGIN MODULEBUILDER PROPERTIES
  88. /**
  89. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  90. */
  91. public $fields=array(
  92. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
  93. '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"),
  94. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'help'=>"Help text", 'showoncombobox'=>'2', 'validate'=>'1',),
  95. 'url' => array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1,),
  96. 'trigger_codes' => array('type'=>'text', 'label'=>'TriggerCodes', 'enabled'=>'1', 'position'=>55, 'notnull'=>1, 'visible'=>1, 'help'=>"TriggerCodeInfo",),
  97. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3, 'validate'=>'1',),
  98. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak', 'validate'=>'1',),
  99. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak', 'validate'=>'1',),
  100. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
  101. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
  102. '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',),
  103. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
  104. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
  105. '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',),
  106. );
  107. public $rowid;
  108. public $ref;
  109. public $label;
  110. public $description;
  111. public $note_public;
  112. public $note_private;
  113. public $date_creation;
  114. public $tms;
  115. public $fk_user_creat;
  116. public $fk_user_modif;
  117. public $import_key;
  118. public $status;
  119. public $url;
  120. public $trigger_codes;
  121. // END MODULEBUILDER PROPERTIES
  122. // If this object has a subtable with lines
  123. // /**
  124. // * @var string Name of subtable line
  125. // */
  126. // public $table_element_line = 'webhook_targetline';
  127. // /**
  128. // * @var string Field with ID of parent key if this object has a parent
  129. // */
  130. // public $fk_element = 'fk_target';
  131. // /**
  132. // * @var string Name of subtable class that manage subtable lines
  133. // */
  134. // public $class_element_line = 'Targetline';
  135. // /**
  136. // * @var array List of child tables. To test if we can delete object.
  137. // */
  138. // protected $childtables = array();
  139. // /**
  140. // * @var array List of child tables. To know object to delete on cascade.
  141. // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  142. // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  143. // */
  144. // protected $childtablesoncascade = array('webhook_targetdet');
  145. // /**
  146. // * @var TargetLine[] Array of subtable lines
  147. // */
  148. // public $lines = array();
  149. /**
  150. * Constructor
  151. *
  152. * @param DoliDb $db Database handler
  153. */
  154. public function __construct(DoliDB $db)
  155. {
  156. global $conf, $langs;
  157. $this->db = $db;
  158. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  159. $this->fields['rowid']['visible'] = 0;
  160. }
  161. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  162. $this->fields['entity']['enabled'] = 0;
  163. }
  164. // Example to show how to set values of fields definition dynamically
  165. /*if ($user->rights->webhook->target->read) {
  166. $this->fields['myfield']['visible'] = 1;
  167. $this->fields['myfield']['noteditable'] = 0;
  168. }*/
  169. // Unset fields that are disabled
  170. foreach ($this->fields as $key => $val) {
  171. if (isset($val['enabled']) && empty($val['enabled'])) {
  172. unset($this->fields[$key]);
  173. }
  174. }
  175. // Translate some data of arrayofkeyval
  176. if (is_object($langs)) {
  177. foreach ($this->fields as $key => $val) {
  178. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  179. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  180. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  181. }
  182. }
  183. }
  184. }
  185. }
  186. /**
  187. * Create object into database
  188. *
  189. * @param User $user User that creates
  190. * @param bool $notrigger false=launch triggers after, true=disable triggers
  191. * @return int <0 if KO, ID of created object if OK
  192. */
  193. public function create(User $user, $notrigger = false)
  194. {
  195. $resultcreate = $this->createCommon($user, $notrigger);
  196. $this->ref = $this->id;
  197. if ($resultcreate <= 0) {
  198. return $resultcreate;
  199. }
  200. return $this->id;
  201. }
  202. /**
  203. * Clone an object into another one
  204. *
  205. * @param User $user User that creates
  206. * @param int $fromid Id of object to clone
  207. * @return mixed New object created, <0 if KO
  208. */
  209. public function createFromClone(User $user, $fromid)
  210. {
  211. global $langs, $extrafields;
  212. $error = 0;
  213. dol_syslog(__METHOD__, LOG_DEBUG);
  214. $object = new self($this->db);
  215. $this->db->begin();
  216. // Load source object
  217. $result = $object->fetchCommon($fromid);
  218. if ($result > 0 && !empty($object->table_element_line)) {
  219. $object->fetchLines();
  220. }
  221. // get lines so they will be clone
  222. //foreach($this->lines as $line)
  223. // $line->fetch_optionals();
  224. // Reset some properties
  225. unset($object->id);
  226. unset($object->fk_user_creat);
  227. unset($object->import_key);
  228. // Clear fields
  229. if (property_exists($object, 'ref')) {
  230. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  231. }
  232. if (property_exists($object, 'label')) {
  233. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  234. }
  235. if (property_exists($object, 'status')) {
  236. $object->status = self::STATUS_DRAFT;
  237. }
  238. if (property_exists($object, 'date_creation')) {
  239. $object->date_creation = dol_now();
  240. }
  241. if (property_exists($object, 'date_modification')) {
  242. $object->date_modification = null;
  243. }
  244. // ...
  245. // Clear extrafields that are unique
  246. if (is_array($object->array_options) && count($object->array_options) > 0) {
  247. $extrafields->fetch_name_optionals_label($this->table_element);
  248. foreach ($object->array_options as $key => $option) {
  249. $shortkey = preg_replace('/options_/', '', $key);
  250. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  251. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  252. unset($object->array_options[$key]);
  253. }
  254. }
  255. }
  256. // Create clone
  257. $object->context['createfromclone'] = 'createfromclone';
  258. $result = $object->createCommon($user);
  259. if ($result < 0) {
  260. $error++;
  261. $this->error = $object->error;
  262. $this->errors = $object->errors;
  263. }
  264. if (!$error) {
  265. // copy internal contacts
  266. if ($this->copy_linked_contact($object, 'internal') < 0) {
  267. $error++;
  268. }
  269. }
  270. if (!$error) {
  271. // copy external contacts if same company
  272. if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  273. if ($this->copy_linked_contact($object, 'external') < 0) {
  274. $error++;
  275. }
  276. }
  277. }
  278. unset($object->context['createfromclone']);
  279. // End
  280. if (!$error) {
  281. $this->db->commit();
  282. return $object;
  283. } else {
  284. $this->db->rollback();
  285. return -1;
  286. }
  287. }
  288. /**
  289. * Load object in memory from the database
  290. *
  291. * @param int $id Id object
  292. * @param string $ref Ref
  293. * @return int <0 if KO, 0 if not found, >0 if OK
  294. */
  295. public function fetch($id, $ref = null)
  296. {
  297. $result = $this->fetchCommon($id, $ref);
  298. if (empty($this->ref)) {
  299. $this->ref = $this->id;
  300. }
  301. return $result;
  302. }
  303. /**
  304. * Load object lines in memory from the database
  305. *
  306. * @return int <0 if KO, 0 if not found, >0 if OK
  307. */
  308. public function fetchLines()
  309. {
  310. $this->lines = array();
  311. $result = $this->fetchLinesCommon();
  312. return $result;
  313. }
  314. /**
  315. * Load list of objects in memory from the database.
  316. *
  317. * @param string $sortorder Sort Order
  318. * @param string $sortfield Sort field
  319. * @param int $limit limit
  320. * @param int $offset Offset
  321. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  322. * @param string $filtermode Filter mode (AND or OR)
  323. * @return array|int int <0 if KO, array of pages if OK
  324. */
  325. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  326. {
  327. global $conf;
  328. dol_syslog(__METHOD__, LOG_DEBUG);
  329. $records = array();
  330. $sql = "SELECT ";
  331. $sql .= $this->getFieldList('t');
  332. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  333. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  334. $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
  335. } else {
  336. $sql .= " WHERE 1 = 1";
  337. }
  338. // Manage filter
  339. $sqlwhere = array();
  340. if (count($filter) > 0) {
  341. foreach ($filter as $key => $value) {
  342. if ($key == 't.rowid') {
  343. $sqlwhere[] = $key." = ".((int) $value);
  344. } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  345. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  346. } elseif ($key == 'customsql') {
  347. $sqlwhere[] = $value;
  348. } elseif (strpos($value, '%') === false) {
  349. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  350. } else {
  351. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  352. }
  353. }
  354. }
  355. if (count($sqlwhere) > 0) {
  356. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  357. }
  358. if (!empty($sortfield)) {
  359. $sql .= $this->db->order($sortfield, $sortorder);
  360. }
  361. if (!empty($limit)) {
  362. $sql .= $this->db->plimit($limit, $offset);
  363. }
  364. $resql = $this->db->query($sql);
  365. if ($resql) {
  366. $num = $this->db->num_rows($resql);
  367. $i = 0;
  368. while ($i < ($limit ? min($limit, $num) : $num)) {
  369. $obj = $this->db->fetch_object($resql);
  370. $record = new self($this->db);
  371. $record->setVarsFromFetchObj($obj);
  372. $records[$record->id] = $record;
  373. $i++;
  374. }
  375. $this->db->free($resql);
  376. return $records;
  377. } else {
  378. $this->errors[] = 'Error '.$this->db->lasterror();
  379. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  380. return -1;
  381. }
  382. }
  383. /**
  384. * Update object into database
  385. *
  386. * @param User $user User that modifies
  387. * @param bool $notrigger false=launch triggers after, true=disable triggers
  388. * @return int <0 if KO, >0 if OK
  389. */
  390. public function update(User $user, $notrigger = false)
  391. {
  392. return $this->updateCommon($user, $notrigger);
  393. }
  394. /**
  395. * Delete object in database
  396. *
  397. * @param User $user User that deletes
  398. * @param bool $notrigger false=launch triggers after, true=disable triggers
  399. * @return int <0 if KO, >0 if OK
  400. */
  401. public function delete(User $user, $notrigger = false)
  402. {
  403. return $this->deleteCommon($user, $notrigger);
  404. //return $this->deleteCommon($user, $notrigger, 1);
  405. }
  406. /**
  407. * Delete a line of object in database
  408. *
  409. * @param User $user User that delete
  410. * @param int $idline Id of line to delete
  411. * @param bool $notrigger false=launch triggers after, true=disable triggers
  412. * @return int >0 if OK, <0 if KO
  413. */
  414. public function deleteLine(User $user, $idline, $notrigger = false)
  415. {
  416. if ($this->status < 0) {
  417. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  418. return -2;
  419. }
  420. return $this->deleteLineCommon($user, $idline, $notrigger);
  421. }
  422. /**
  423. * Validate object
  424. *
  425. * @param User $user User making status change
  426. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  427. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  428. */
  429. public function validate($user, $notrigger = 0)
  430. {
  431. global $conf, $langs;
  432. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  433. $error = 0;
  434. // Protection
  435. if ($this->status == self::STATUS_VALIDATED) {
  436. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  437. return 0;
  438. }
  439. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->target->write))
  440. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->target->target_advance->validate))))
  441. {
  442. $this->error='NotEnoughPermissions';
  443. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  444. return -1;
  445. }*/
  446. $now = dol_now();
  447. $this->db->begin();
  448. // Define new ref
  449. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  450. $num = $this->getNextNumRef();
  451. } else {
  452. $num = $this->ref;
  453. }
  454. $this->newref = $num;
  455. if (!empty($num)) {
  456. // Validate
  457. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  458. $sql .= " SET ref = '".$this->db->escape($num)."',";
  459. $sql .= " status = ".self::STATUS_VALIDATED;
  460. if (!empty($this->fields['date_validation'])) {
  461. $sql .= ", date_validation = '".$this->db->idate($now)."'";
  462. }
  463. if (!empty($this->fields['fk_user_valid'])) {
  464. $sql .= ", fk_user_valid = ".((int) $user->id);
  465. }
  466. $sql .= " WHERE rowid = ".((int) $this->id);
  467. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  468. $resql = $this->db->query($sql);
  469. if (!$resql) {
  470. dol_print_error($this->db);
  471. $this->error = $this->db->lasterror();
  472. $error++;
  473. }
  474. if (!$error && !$notrigger) {
  475. // Call trigger
  476. $result = $this->call_trigger('TARGET_VALIDATE', $user);
  477. if ($result < 0) {
  478. $error++;
  479. }
  480. // End call triggers
  481. }
  482. }
  483. if (!$error) {
  484. $this->oldref = $this->ref;
  485. // Rename directory if dir was a temporary ref
  486. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  487. // Now we rename also files into index
  488. $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)."'";
  489. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'target/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  490. $resql = $this->db->query($sql);
  491. if (!$resql) {
  492. $error++; $this->error = $this->db->lasterror();
  493. }
  494. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  495. $oldref = dol_sanitizeFileName($this->ref);
  496. $newref = dol_sanitizeFileName($num);
  497. $dirsource = $conf->webhook->dir_output.'/target/'.$oldref;
  498. $dirdest = $conf->webhook->dir_output.'/target/'.$newref;
  499. if (!$error && file_exists($dirsource)) {
  500. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  501. if (@rename($dirsource, $dirdest)) {
  502. dol_syslog("Rename ok");
  503. // Rename docs starting with $oldref with $newref
  504. $listoffiles = dol_dir_list($conf->webhook->dir_output.'/target/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  505. foreach ($listoffiles as $fileentry) {
  506. $dirsource = $fileentry['name'];
  507. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  508. $dirsource = $fileentry['path'].'/'.$dirsource;
  509. $dirdest = $fileentry['path'].'/'.$dirdest;
  510. @rename($dirsource, $dirdest);
  511. }
  512. }
  513. }
  514. }
  515. }
  516. // Set new ref and current status
  517. if (!$error) {
  518. $this->ref = $num;
  519. $this->status = self::STATUS_VALIDATED;
  520. }
  521. if (!$error) {
  522. $this->db->commit();
  523. return 1;
  524. } else {
  525. $this->db->rollback();
  526. return -1;
  527. }
  528. }
  529. /**
  530. * Set draft status
  531. *
  532. * @param User $user Object user that modify
  533. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  534. * @return int <0 if KO, >0 if OK
  535. */
  536. public function setDraft($user, $notrigger = 0)
  537. {
  538. // Protection
  539. if ($this->status <= self::STATUS_DRAFT) {
  540. return 0;
  541. }
  542. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->write))
  543. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->webhook_advance->validate))))
  544. {
  545. $this->error='Permission denied';
  546. return -1;
  547. }*/
  548. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'TARGET_UNVALIDATE');
  549. }
  550. /**
  551. * Set cancel status
  552. *
  553. * @param User $user Object user that modify
  554. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  555. * @return int <0 if KO, 0=Nothing done, >0 if OK
  556. */
  557. public function cancel($user, $notrigger = 0)
  558. {
  559. // Protection
  560. if ($this->status != self::STATUS_VALIDATED) {
  561. return 0;
  562. }
  563. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->write))
  564. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->webhook_advance->validate))))
  565. {
  566. $this->error='Permission denied';
  567. return -1;
  568. }*/
  569. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'TARGET_CANCEL');
  570. }
  571. /**
  572. * Set back to validated status
  573. *
  574. * @param User $user Object user that modify
  575. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  576. * @return int <0 if KO, 0=Nothing done, >0 if OK
  577. */
  578. public function reopen($user, $notrigger = 0)
  579. {
  580. // Protection
  581. if ($this->status != self::STATUS_CANCELED) {
  582. return 0;
  583. }
  584. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->write))
  585. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->webhook->webhook_advance->validate))))
  586. {
  587. $this->error='Permission denied';
  588. return -1;
  589. }*/
  590. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'TARGET_REOPEN');
  591. }
  592. /**
  593. * Return a link to the object card (with optionaly the picto)
  594. *
  595. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  596. * @param string $option On what the link point to ('nolink', ...)
  597. * @param int $notooltip 1=Disable tooltip
  598. * @param string $morecss Add more css on link
  599. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  600. * @return string String with URL
  601. */
  602. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  603. {
  604. global $conf, $langs, $hookmanager;
  605. if (!empty($conf->dol_no_mouse_hover)) {
  606. $notooltip = 1; // Force disable tooltips
  607. }
  608. $result = '';
  609. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Target").'</u>';
  610. if (isset($this->status)) {
  611. $label .= ' '.$this->getLibStatut(5);
  612. }
  613. $label .= '<br>';
  614. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  615. $url = dol_buildpath('/webhook/target_card.php', 1).'?id='.$this->id;
  616. if ($option != 'nolink') {
  617. // Add param to save lastsearch_values or not
  618. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  619. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  620. $add_save_lastsearch_values = 1;
  621. }
  622. if ($url && $add_save_lastsearch_values) {
  623. $url .= '&save_lastsearch_values=1';
  624. }
  625. }
  626. $linkclose = '';
  627. if (empty($notooltip)) {
  628. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  629. $label = $langs->trans("ShowTarget");
  630. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  631. }
  632. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  633. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  634. } else {
  635. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  636. }
  637. if ($option == 'nolink' || empty($url)) {
  638. $linkstart = '<span';
  639. } else {
  640. $linkstart = '<a href="'.$url.'"';
  641. }
  642. $linkstart .= $linkclose.'>';
  643. if ($option == 'nolink' || empty($url)) {
  644. $linkend = '</span>';
  645. } else {
  646. $linkend = '</a>';
  647. }
  648. $result .= $linkstart;
  649. if (empty($this->showphoto_on_popup)) {
  650. if ($withpicto) {
  651. $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);
  652. }
  653. } else {
  654. if ($withpicto) {
  655. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  656. list($class, $module) = explode('@', $this->picto);
  657. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  658. $filearray = dol_dir_list($upload_dir, "files");
  659. $filename = $filearray[0]['name'];
  660. if (!empty($filename)) {
  661. $pospoint = strpos($filearray[0]['name'], '.');
  662. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  663. if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
  664. $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>';
  665. } else {
  666. $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>';
  667. }
  668. $result .= '</div>';
  669. } else {
  670. $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);
  671. }
  672. }
  673. }
  674. if ($withpicto != 2) {
  675. $result .= $this->ref;
  676. }
  677. $result .= $linkend;
  678. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  679. global $action, $hookmanager;
  680. $hookmanager->initHooks(array('targetdao'));
  681. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  682. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  683. if ($reshook > 0) {
  684. $result = $hookmanager->resPrint;
  685. } else {
  686. $result .= $hookmanager->resPrint;
  687. }
  688. return $result;
  689. }
  690. /**
  691. * Return the label of the status
  692. *
  693. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  694. * @return string Label of status
  695. */
  696. public function getLabelStatus($mode = 0)
  697. {
  698. return $this->LibStatut($this->status, $mode);
  699. }
  700. /**
  701. * Return the label of the status
  702. *
  703. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  704. * @return string Label of status
  705. */
  706. public function getLibStatut($mode = 0)
  707. {
  708. return $this->LibStatut($this->status, $mode);
  709. }
  710. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  711. /**
  712. * Return the status
  713. *
  714. * @param int $status Id status
  715. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  716. * @return string Label of status
  717. */
  718. public function LibStatut($status, $mode = 0)
  719. {
  720. // phpcs:enable
  721. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  722. global $langs;
  723. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  724. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  725. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  726. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  727. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  728. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  729. }
  730. $statusType = 'status'.$status;
  731. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  732. if ($status == self::STATUS_CANCELED) {
  733. $statusType = 'status6';
  734. }
  735. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  736. }
  737. /**
  738. * Load the info information in the object
  739. *
  740. * @param int $id Id of object
  741. * @return void
  742. */
  743. public function info($id)
  744. {
  745. $sql = "SELECT rowid, date_creation as datec, tms as datem,";
  746. $sql .= " fk_user_creat, fk_user_modif";
  747. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  748. $sql .= " WHERE t.rowid = ".((int) $id);
  749. $result = $this->db->query($sql);
  750. if ($result) {
  751. if ($this->db->num_rows($result)) {
  752. $obj = $this->db->fetch_object($result);
  753. $this->id = $obj->rowid;
  754. $this->user_creation_id = $obj->fk_user_creat;
  755. $this->user_modification_id = $obj->fk_user_modif;
  756. $this->date_creation = $this->db->jdate($obj->datec);
  757. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  758. }
  759. $this->db->free($result);
  760. } else {
  761. dol_print_error($this->db);
  762. }
  763. }
  764. /**
  765. * Initialise object with example values
  766. * Id must be 0 if object instance is a specimen
  767. *
  768. * @return void
  769. */
  770. public function initAsSpecimen()
  771. {
  772. $this->url = "https://thisisunurl";
  773. $this->trigger_codes = "ThisIsATestCode";
  774. $this->initAsSpecimenCommon();
  775. }
  776. /**
  777. * Create an array of lines
  778. *
  779. * @return array|int array of lines if OK, <0 if KO
  780. */
  781. public function getLinesArray()
  782. {
  783. $this->lines = array();
  784. $objectline = new TargetLine($this->db);
  785. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_target = '.((int) $this->id)));
  786. if (is_numeric($result)) {
  787. $this->error = $objectline->error;
  788. $this->errors = $objectline->errors;
  789. return $result;
  790. } else {
  791. $this->lines = $result;
  792. return $this->lines;
  793. }
  794. }
  795. /**
  796. * Returns the reference to the following non used object depending on the active numbering module.
  797. *
  798. * @return string Object free reference
  799. */
  800. public function getNextNumRef()
  801. {
  802. global $langs, $conf;
  803. if (empty($conf->global->WEBHOOK_TARGET_ADDON)) {
  804. $conf->global->WEBHOOK_TARGET_ADDON = 'mod_target_standard';
  805. }
  806. if (!empty($conf->global->WEBHOOK_TARGET_ADDON)) {
  807. $mybool = false;
  808. $file = $conf->global->WEBHOOK_TARGET_ADDON.".php";
  809. $classname = $conf->global->WEBHOOK_TARGET_ADDON;
  810. // Include file with class
  811. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  812. foreach ($dirmodels as $reldir) {
  813. $dir = dol_buildpath($reldir."core/modules/webhook/");
  814. // Load file with numbering class (if found)
  815. $mybool |= @include_once $dir.$file;
  816. }
  817. if ($mybool === false) {
  818. dol_print_error('', "Failed to include file ".$file);
  819. return '';
  820. }
  821. if (class_exists($classname)) {
  822. $obj = new $classname();
  823. $numref = $obj->getNextValue($this);
  824. if ($numref != '' && $numref != '-1') {
  825. return $numref;
  826. } else {
  827. $this->error = $obj->error;
  828. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  829. return "";
  830. }
  831. } else {
  832. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  833. return "";
  834. }
  835. } else {
  836. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  837. return "";
  838. }
  839. }
  840. /**
  841. * Create a document onto disk according to template module.
  842. *
  843. * @param string $modele Force template to use ('' to not force)
  844. * @param Translate $outputlangs objet lang a utiliser pour traduction
  845. * @param int $hidedetails Hide details of lines
  846. * @param int $hidedesc Hide description
  847. * @param int $hideref Hide ref
  848. * @param null|array $moreparams Array to provide more information
  849. * @return int 0 if KO, 1 if OK
  850. */
  851. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  852. {
  853. global $conf, $langs;
  854. $result = 0;
  855. $includedocgeneration = 0;
  856. if (!dol_strlen($modele)) {
  857. $modele = 'standard_target';
  858. if (!empty($this->model_pdf)) {
  859. $modele = $this->model_pdf;
  860. } elseif (!empty($conf->global->TARGET_ADDON_PDF)) {
  861. $modele = $conf->global->TARGET_ADDON_PDF;
  862. }
  863. }
  864. $modelpath = "core/modules/webhook/doc/";
  865. if ($includedocgeneration && !empty($modele)) {
  866. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  867. }
  868. return $result;
  869. }
  870. /**
  871. * Action executed by scheduler
  872. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  873. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  874. *
  875. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  876. */
  877. public function doScheduledJob()
  878. {
  879. global $conf, $langs;
  880. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  881. $error = 0;
  882. $this->output = '';
  883. $this->error = '';
  884. dol_syslog(__METHOD__, LOG_DEBUG);
  885. $now = dol_now();
  886. $this->db->begin();
  887. // ...
  888. $this->db->commit();
  889. return $error;
  890. }
  891. }
  892. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  893. /**
  894. * Class TargetLine. You can also remove this and generate a CRUD class for lines objects.
  895. */
  896. class TargetLine extends CommonObjectLine
  897. {
  898. // To complete with content of an object TargetLine
  899. // We should have a field rowid, fk_target and position
  900. /**
  901. * @var int Does object support extrafields ? 0=No, 1=Yes
  902. */
  903. public $isextrafieldmanaged = 0;
  904. /**
  905. * Constructor
  906. *
  907. * @param DoliDb $db Database handler
  908. */
  909. public function __construct(DoliDB $db)
  910. {
  911. $this->db = $db;
  912. }
  913. }