myobject.class.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2023 Frédéric France <frederic.france@netlogic.fr>
  4. * Copyright (C) ---Put here your own copyright and developer email---
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/modulebuilder/template/class/myobject.class.php
  21. * \ingroup mymodule
  22. * \brief This file is a CRUD class file for MyObject (Create/Read/Update/Delete)
  23. */
  24. // Put here all includes required by your class file
  25. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  26. //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  27. //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  28. /**
  29. * Class for MyObject
  30. */
  31. class MyObject extends CommonObject
  32. {
  33. /**
  34. * @var string ID of module.
  35. */
  36. public $module = 'mymodule';
  37. /**
  38. * @var string ID to identify managed object.
  39. */
  40. public $element = 'myobject';
  41. /**
  42. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  43. */
  44. public $table_element = 'mymodule_myobject';
  45. /**
  46. * @var int Does this object support multicompany module ?
  47. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  48. */
  49. public $ismultientitymanaged = 0;
  50. /**
  51. * @var int Does object support extrafields ? 0=No, 1=Yes
  52. */
  53. public $isextrafieldmanaged = 1;
  54. /**
  55. * @var string String with name of icon for myobject. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'myobject@mymodule' if picto is file 'img/object_myobject.png'.
  56. */
  57. public $picto = 'fa-file';
  58. const STATUS_DRAFT = 0;
  59. const STATUS_VALIDATED = 1;
  60. const STATUS_CANCELED = 9;
  61. /**
  62. * 'type' field format:
  63. * 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',
  64. * 'select' (list of values are in 'options'),
  65. * 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:SortField]]]]]]',
  66. * 'chkbxlst:...',
  67. * 'varchar(x)',
  68. * 'text', 'text:none', 'html',
  69. * 'double(24,8)', 'real', 'price',
  70. * 'date', 'datetime', 'timestamp', 'duration',
  71. * 'boolean', 'checkbox', 'radio', 'array',
  72. * 'mail', 'phone', 'url', 'password', 'ip'
  73. * Note: Filter must be a Dolibarr Universal Filter syntax string. Example: "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.status:!=:0) or (t.nature:is:NULL)"
  74. * 'label' the translation key.
  75. * 'picto' is code of a picto to show before value in forms
  76. * 'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalInt("MY_SETUP_PARAM")' or 'isModEnabled("multicurrency")' ...)
  77. * 'position' is the sort order of field.
  78. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  79. * '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)
  80. * 'noteditable' says if field is not editable (1 or 0)
  81. * 'alwayseditable' says if field can be modified also when status is not draft ('1' or '0')
  82. * '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.
  83. * 'index' if we want an index in database.
  84. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  85. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  86. * '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)
  87. * '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'
  88. * 'help' and 'helplist' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  89. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  90. * '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.
  91. * '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'
  92. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  93. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  94. * 'validate' is 1 if need to validate with $this->validateField()
  95. * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
  96. *
  97. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  98. */
  99. // BEGIN MODULEBUILDER PROPERTIES
  100. /**
  101. * @var array Array with all fields into database and their property. Do not use it as a static var. It may be modified by constructor.
  102. */
  103. public $fields = array(
  104. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
  105. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>10),
  106. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'noteditable'=>0, 'default'=>'', 'notnull'=> 1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20, 'searchall'=>1, 'comment'=>'Reference of object', 'validate'=>1),
  107. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'help'=>'Help text', 'showoncombobox'=>2, 'validate'=>1, 'alwayseditable'=>1),
  108. 'amount' => array('type'=>'price', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for amount', 'validate'=>1),
  109. 'qty' => array('type'=>'real', 'label'=>'Qty', 'enabled'=>1, 'visible'=>1, 'default'=>'0', 'position'=>45, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for quantity', 'css'=>'maxwidth75imp', 'validate'=>1),
  110. 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))', 'picto'=>'company', 'label'=>'ThirdParty', 'visible'=> 1, 'enabled'=>'isModEnabled("societe")', 'position'=>50, 'notnull'=>-1, 'index'=>1, 'help'=>'OrganizationEventLinkToThirdParty', 'validate'=>1, 'css'=>'maxwidth500 widthcentpercentminusxx', 'csslist'=>'tdoverflowmax150'),
  111. 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'picto'=>'project', 'enabled'=>'isModEnabled("project")', 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1, 'validate'=>1, 'css'=>'maxwidth500 widthcentpercentminusxx', 'csslist'=>'tdoverflowmax150'),
  112. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>60, 'validate'=>1),
  113. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'validate'=>1, 'cssview'=>'wordbreak'),
  114. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'validate'=>1, 'cssview'=>'wordbreak'),
  115. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>500),
  116. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 0, 'position'=>501),
  117. //'date_validation ' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
  118. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>510, 'foreignkey'=>'user.rowid', 'csslist'=>'tdoverflowmax150'),
  119. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511, 'csslist'=>'tdoverflowmax150'),
  120. //'fk_user_valid' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
  121. 'last_main_doc' => array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>0, 'notnull'=>0, 'position'=>600),
  122. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
  123. 'model_pdf' => array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'notnull'=>-1, 'position'=>1010),
  124. 'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=> 1, 'default'=>0, 'index'=>1, 'position'=>2000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 9=>'Canceled'), 'validate'=>1),
  125. );
  126. /**
  127. * @var int ID
  128. */
  129. public $rowid;
  130. /**
  131. * @var string Ref
  132. */
  133. public $ref;
  134. /**
  135. * @var int Entity
  136. */
  137. public $entity;
  138. /**
  139. * @var string label
  140. */
  141. public $label;
  142. /**
  143. * @var string amount
  144. */
  145. public $amount;
  146. /**
  147. * @var int Thirdparty ID
  148. */
  149. public $socid; // both socid and fk_soc are used
  150. public $fk_soc; // both socid and fk_soc are used
  151. /**
  152. * @var int Status
  153. */
  154. public $status;
  155. /**
  156. * @var integer|string date_creation
  157. */
  158. public $date_creation;
  159. /**
  160. * @var integer tms
  161. */
  162. public $tms;
  163. /**
  164. * @var int ID
  165. */
  166. public $fk_user_creat;
  167. /**
  168. * @var int ID
  169. */
  170. public $fk_user_modif;
  171. /**
  172. * @var string public $last_main_doc
  173. */
  174. public $last_main_doc;
  175. /**
  176. * @var string import_key
  177. */
  178. public $import_key;
  179. // END MODULEBUILDER PROPERTIES
  180. // If this object has a subtable with lines
  181. // /**
  182. // * @var string Name of subtable line
  183. // */
  184. // public $table_element_line = 'mymodule_myobjectline';
  185. // /**
  186. // * @var string Field with ID of parent key if this object has a parent
  187. // */
  188. // public $fk_element = 'fk_myobject';
  189. // /**
  190. // * @var string Name of subtable class that manage subtable lines
  191. // */
  192. // public $class_element_line = 'MyObjectline';
  193. // /**
  194. // * @var array List of child tables. To test if we can delete object.
  195. // */
  196. // protected $childtables = array('mychildtable' => array('name'=>'MyObject', 'fk_element'=>'fk_myobject'));
  197. // /**
  198. // * @var array List of child tables. To know object to delete on cascade.
  199. // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  200. // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  201. // */
  202. // protected $childtablesoncascade = array('mymodule_myobjectdet');
  203. // /**
  204. // * @var MyObjectLine[] Array of subtable lines
  205. // */
  206. // public $lines = array();
  207. /**
  208. * Constructor
  209. *
  210. * @param DoliDb $db Database handler
  211. */
  212. public function __construct(DoliDB $db)
  213. {
  214. global $conf, $langs;
  215. $this->db = $db;
  216. if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
  217. $this->fields['rowid']['visible'] = 0;
  218. }
  219. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  220. $this->fields['entity']['enabled'] = 0;
  221. }
  222. // Example to show how to set values of fields definition dynamically
  223. /*if ($user->hasRight('mymodule', 'myobject', 'read')) {
  224. $this->fields['myfield']['visible'] = 1;
  225. $this->fields['myfield']['noteditable'] = 0;
  226. }*/
  227. // Unset fields that are disabled
  228. foreach ($this->fields as $key => $val) {
  229. if (isset($val['enabled']) && empty($val['enabled'])) {
  230. unset($this->fields[$key]);
  231. }
  232. }
  233. // Translate some data of arrayofkeyval
  234. if (is_object($langs)) {
  235. foreach ($this->fields as $key => $val) {
  236. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  237. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  238. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  239. }
  240. }
  241. }
  242. }
  243. }
  244. /**
  245. * Create object into database
  246. *
  247. * @param User $user User that creates
  248. * @param bool $notrigger false=launch triggers after, true=disable triggers
  249. * @return int Return integer <0 if KO, Id of created object if OK
  250. */
  251. public function create(User $user, $notrigger = false)
  252. {
  253. $resultcreate = $this->createCommon($user, $notrigger);
  254. //$resultvalidate = $this->validate($user, $notrigger);
  255. return $resultcreate;
  256. }
  257. /**
  258. * Clone an object into another one
  259. *
  260. * @param User $user User that creates
  261. * @param int $fromid Id of object to clone
  262. * @return mixed New object created, <0 if KO
  263. */
  264. public function createFromClone(User $user, $fromid)
  265. {
  266. global $langs, $extrafields;
  267. $error = 0;
  268. dol_syslog(__METHOD__, LOG_DEBUG);
  269. $object = new self($this->db);
  270. $this->db->begin();
  271. // Load source object
  272. $result = $object->fetchCommon($fromid);
  273. if ($result > 0 && !empty($object->table_element_line)) {
  274. $object->fetchLines();
  275. }
  276. // get lines so they will be clone
  277. //foreach($this->lines as $line)
  278. // $line->fetch_optionals();
  279. // Reset some properties
  280. unset($object->id);
  281. unset($object->fk_user_creat);
  282. unset($object->import_key);
  283. // Clear fields
  284. if (property_exists($object, 'ref')) {
  285. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  286. }
  287. if (property_exists($object, 'label')) {
  288. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  289. }
  290. if (property_exists($object, 'status')) {
  291. $object->status = self::STATUS_DRAFT;
  292. }
  293. if (property_exists($object, 'date_creation')) {
  294. $object->date_creation = dol_now();
  295. }
  296. if (property_exists($object, 'date_modification')) {
  297. $object->date_modification = null;
  298. }
  299. // ...
  300. // Clear extrafields that are unique
  301. if (is_array($object->array_options) && count($object->array_options) > 0) {
  302. $extrafields->fetch_name_optionals_label($this->table_element);
  303. foreach ($object->array_options as $key => $option) {
  304. $shortkey = preg_replace('/options_/', '', $key);
  305. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  306. //var_dump($key);
  307. //var_dump($clonedObj->array_options[$key]); exit;
  308. unset($object->array_options[$key]);
  309. }
  310. }
  311. }
  312. // Create clone
  313. $object->context['createfromclone'] = 'createfromclone';
  314. $result = $object->createCommon($user);
  315. if ($result < 0) {
  316. $error++;
  317. $this->setErrorsFromObject($object);
  318. }
  319. if (!$error) {
  320. // copy internal contacts
  321. if ($this->copy_linked_contact($object, 'internal') < 0) {
  322. $error++;
  323. }
  324. }
  325. if (!$error) {
  326. // copy external contacts if same company
  327. if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  328. if ($this->copy_linked_contact($object, 'external') < 0) {
  329. $error++;
  330. }
  331. }
  332. }
  333. unset($object->context['createfromclone']);
  334. // End
  335. if (!$error) {
  336. $this->db->commit();
  337. return $object;
  338. } else {
  339. $this->db->rollback();
  340. return -1;
  341. }
  342. }
  343. /**
  344. * Load object in memory from the database
  345. *
  346. * @param int $id Id object
  347. * @param string $ref Ref
  348. * @param int $noextrafields 0=Default to load extrafields, 1=No extrafields
  349. * @param int $nolines 0=Default to load extrafields, 1=No extrafields
  350. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  351. */
  352. public function fetch($id, $ref = null, $noextrafields = 0, $nolines = 0)
  353. {
  354. $result = $this->fetchCommon($id, $ref, '', $noextrafields);
  355. if ($result > 0 && !empty($this->table_element_line) && empty($nolines)) {
  356. $this->fetchLines($noextrafields);
  357. }
  358. return $result;
  359. }
  360. /**
  361. * Load object lines in memory from the database
  362. *
  363. * @param int $noextrafields 0=Default to load extrafields, 1=No extrafields
  364. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  365. */
  366. public function fetchLines($noextrafields = 0)
  367. {
  368. $this->lines = array();
  369. $result = $this->fetchLinesCommon('', $noextrafields);
  370. return $result;
  371. }
  372. /**
  373. * Load list of objects in memory from the database. Using a fetchAll is a bad practice, instead try to forge you optimized and limited SQL request.
  374. *
  375. * @param string $sortorder Sort Order
  376. * @param string $sortfield Sort field
  377. * @param int $limit limit
  378. * @param int $offset Offset
  379. * @param array $filter Filter array. Example array('mystringfield'=>'value', 'myintfield'=>4, 'customsql'=>...)
  380. * @param string $filtermode Filter mode (AND or OR)
  381. * @return array|int int <0 if KO, array of pages if OK
  382. */
  383. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  384. {
  385. dol_syslog(__METHOD__, LOG_DEBUG);
  386. $records = array();
  387. $sql = "SELECT ";
  388. $sql .= $this->getFieldList('t');
  389. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  390. if (isset($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) {
  391. $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON tf.fk_object = t.rowid";
  392. }
  393. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  394. $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
  395. } else {
  396. $sql .= " WHERE 1 = 1";
  397. }
  398. // Manage filter
  399. $sqlwhere = array();
  400. if (count($filter) > 0) {
  401. foreach ($filter as $key => $value) {
  402. $columnName = preg_replace('/^t\./', '', $key);
  403. if ($key === 'customsql') {
  404. // Never use 'customsql' with a value from user input since it is injected as is. The value must be hard coded.
  405. $sqlwhere[] = $value;
  406. continue;
  407. } elseif (isset($this->fields[$columnName])) {
  408. $type = $this->fields[$columnName]['type'];
  409. if (preg_match('/^integer/', $type)) {
  410. if (is_int($value)) {
  411. // single value
  412. $sqlwhere[] = $key . " = " . intval($value);
  413. } elseif (is_array($value)) {
  414. if (empty($value)) {
  415. continue;
  416. }
  417. $sqlwhere[] = $key . ' IN (' . $this->db->sanitize(implode(',', array_map('intval', $value))) . ')';
  418. }
  419. continue;
  420. } elseif (in_array($type, array('date', 'datetime', 'timestamp'))) {
  421. $sqlwhere[] = $key . " = '" . $this->db->idate($value) . "'";
  422. continue;
  423. }
  424. }
  425. // when the $key doesn't fall into the previously handled categories, we do as if the column were a varchar/text
  426. if (is_array($value) && count($value)) {
  427. $value = implode(',', array_map(function ($v) {
  428. return "'" . $this->db->sanitize($this->db->escape($v)) . "'";
  429. }, $value));
  430. $sqlwhere[] = $key . ' IN (' . $this->db->sanitize($value, true) . ')';
  431. } elseif (is_scalar($value)) {
  432. if (strpos($value, '%') === false) {
  433. $sqlwhere[] = $key . " = '" . $this->db->sanitize($this->db->escape($value)) . "'";
  434. } else {
  435. $sqlwhere[] = $key . " LIKE '%" . $this->db->escapeforlike($this->db->escape($value)) . "%'";
  436. }
  437. }
  438. }
  439. }
  440. if (count($sqlwhere) > 0) {
  441. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  442. }
  443. if (!empty($sortfield)) {
  444. $sql .= $this->db->order($sortfield, $sortorder);
  445. }
  446. if (!empty($limit)) {
  447. $sql .= $this->db->plimit($limit, $offset);
  448. }
  449. $resql = $this->db->query($sql);
  450. if ($resql) {
  451. $num = $this->db->num_rows($resql);
  452. $i = 0;
  453. while ($i < ($limit ? min($limit, $num) : $num)) {
  454. $obj = $this->db->fetch_object($resql);
  455. $record = new self($this->db);
  456. $record->setVarsFromFetchObj($obj);
  457. $records[$record->id] = $record;
  458. $i++;
  459. }
  460. $this->db->free($resql);
  461. return $records;
  462. } else {
  463. $this->errors[] = 'Error '.$this->db->lasterror();
  464. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  465. return -1;
  466. }
  467. }
  468. /**
  469. * Update object into database
  470. *
  471. * @param User $user User that modifies
  472. * @param bool $notrigger false=launch triggers after, true=disable triggers
  473. * @return int Return integer <0 if KO, >0 if OK
  474. */
  475. public function update(User $user, $notrigger = false)
  476. {
  477. return $this->updateCommon($user, $notrigger);
  478. }
  479. /**
  480. * Delete object in database
  481. *
  482. * @param User $user User that deletes
  483. * @param bool $notrigger false=launch triggers, true=disable triggers
  484. * @return int Return integer <0 if KO, >0 if OK
  485. */
  486. public function delete(User $user, $notrigger = false)
  487. {
  488. return $this->deleteCommon($user, $notrigger);
  489. //return $this->deleteCommon($user, $notrigger, 1);
  490. }
  491. /**
  492. * Delete a line of object in database
  493. *
  494. * @param User $user User that delete
  495. * @param int $idline Id of line to delete
  496. * @param bool $notrigger false=launch triggers after, true=disable triggers
  497. * @return int >0 if OK, <0 if KO
  498. */
  499. public function deleteLine(User $user, $idline, $notrigger = false)
  500. {
  501. if ($this->status < 0) {
  502. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  503. return -2;
  504. }
  505. return $this->deleteLineCommon($user, $idline, $notrigger);
  506. }
  507. /**
  508. * Validate object
  509. *
  510. * @param User $user User making status change
  511. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  512. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  513. */
  514. public function validate($user, $notrigger = 0)
  515. {
  516. global $conf, $langs;
  517. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  518. $error = 0;
  519. // Protection
  520. if ($this->status == self::STATUS_VALIDATED) {
  521. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  522. return 0;
  523. }
  524. /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','write'))
  525. || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->myobject->myobject_advance->validate))))
  526. {
  527. $this->error='NotEnoughPermissions';
  528. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  529. return -1;
  530. }*/
  531. $now = dol_now();
  532. $this->db->begin();
  533. // Define new ref
  534. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  535. $num = $this->getNextNumRef();
  536. } else {
  537. $num = $this->ref;
  538. }
  539. $this->newref = $num;
  540. if (!empty($num)) {
  541. // Validate
  542. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  543. $sql .= " SET ref = '".$this->db->escape($num)."',";
  544. $sql .= " status = ".self::STATUS_VALIDATED;
  545. if (!empty($this->fields['date_validation'])) {
  546. $sql .= ", date_validation = '".$this->db->idate($now)."'";
  547. }
  548. if (!empty($this->fields['fk_user_valid'])) {
  549. $sql .= ", fk_user_valid = ".((int) $user->id);
  550. }
  551. $sql .= " WHERE rowid = ".((int) $this->id);
  552. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  553. $resql = $this->db->query($sql);
  554. if (!$resql) {
  555. dol_print_error($this->db);
  556. $this->error = $this->db->lasterror();
  557. $error++;
  558. }
  559. if (!$error && !$notrigger) {
  560. // Call trigger
  561. $result = $this->call_trigger('MYOBJECT_VALIDATE', $user);
  562. if ($result < 0) {
  563. $error++;
  564. }
  565. // End call triggers
  566. }
  567. }
  568. if (!$error) {
  569. $this->oldref = $this->ref;
  570. // Rename directory if dir was a temporary ref
  571. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  572. // Now we rename also files into index
  573. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'myobject/".$this->db->escape($this->newref)."'";
  574. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  575. $resql = $this->db->query($sql);
  576. if (!$resql) {
  577. $error++;
  578. $this->error = $this->db->lasterror();
  579. }
  580. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'myobject/".$this->db->escape($this->newref)."'";
  581. $sql .= " WHERE filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  582. $resql = $this->db->query($sql);
  583. if (!$resql) {
  584. $error++;
  585. $this->error = $this->db->lasterror();
  586. }
  587. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  588. $oldref = dol_sanitizeFileName($this->ref);
  589. $newref = dol_sanitizeFileName($num);
  590. $dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref;
  591. $dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref;
  592. if (!$error && file_exists($dirsource)) {
  593. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  594. if (@rename($dirsource, $dirdest)) {
  595. dol_syslog("Rename ok");
  596. // Rename docs starting with $oldref with $newref
  597. $listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  598. foreach ($listoffiles as $fileentry) {
  599. $dirsource = $fileentry['name'];
  600. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  601. $dirsource = $fileentry['path'].'/'.$dirsource;
  602. $dirdest = $fileentry['path'].'/'.$dirdest;
  603. @rename($dirsource, $dirdest);
  604. }
  605. }
  606. }
  607. }
  608. }
  609. // Set new ref and current status
  610. if (!$error) {
  611. $this->ref = $num;
  612. $this->status = self::STATUS_VALIDATED;
  613. }
  614. if (!$error) {
  615. $this->db->commit();
  616. return 1;
  617. } else {
  618. $this->db->rollback();
  619. return -1;
  620. }
  621. }
  622. /**
  623. * Set draft status
  624. *
  625. * @param User $user Object user that modify
  626. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  627. * @return int Return integer <0 if KO, >0 if OK
  628. */
  629. public function setDraft($user, $notrigger = 0)
  630. {
  631. // Protection
  632. if ($this->status <= self::STATUS_DRAFT) {
  633. return 0;
  634. }
  635. /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','write'))
  636. || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','mymodule_advance','validate'))))
  637. {
  638. $this->error='Permission denied';
  639. return -1;
  640. }*/
  641. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MYMODULE_MYOBJECT_UNVALIDATE');
  642. }
  643. /**
  644. * Set cancel status
  645. *
  646. * @param User $user Object user that modify
  647. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  648. * @return int <0 if KO, 0=Nothing done, >0 if OK
  649. */
  650. public function cancel($user, $notrigger = 0)
  651. {
  652. // Protection
  653. if ($this->status != self::STATUS_VALIDATED) {
  654. return 0;
  655. }
  656. /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','write'))
  657. || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','mymodule_advance','validate'))))
  658. {
  659. $this->error='Permission denied';
  660. return -1;
  661. }*/
  662. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MYMODULE_MYOBJECT_CANCEL');
  663. }
  664. /**
  665. * Set back to validated status
  666. *
  667. * @param User $user Object user that modify
  668. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  669. * @return int <0 if KO, 0=Nothing done, >0 if OK
  670. */
  671. public function reopen($user, $notrigger = 0)
  672. {
  673. // Protection
  674. if ($this->status == self::STATUS_VALIDATED) {
  675. return 0;
  676. }
  677. /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','write'))
  678. || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','mymodule_advance','validate'))))
  679. {
  680. $this->error='Permission denied';
  681. return -1;
  682. }*/
  683. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MYMODULE_MYOBJECT_REOPEN');
  684. }
  685. /**
  686. * getTooltipContentArray
  687. *
  688. * @param array $params Params to construct tooltip data
  689. * @since v18
  690. * @return array
  691. */
  692. public function getTooltipContentArray($params)
  693. {
  694. global $langs;
  695. $datas = [];
  696. if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  697. return ['optimize' => $langs->trans("ShowMyObject")];
  698. }
  699. $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("MyObject").'</u>';
  700. if (isset($this->status)) {
  701. $datas['picto'] .= ' '.$this->getLibStatut(5);
  702. }
  703. if (property_exists($this, 'ref')) {
  704. $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  705. }
  706. if (property_exists($this, 'label')) {
  707. $datas['ref'] = '<br>'.$langs->trans('Label').':</b> '.$this->label;
  708. }
  709. return $datas;
  710. }
  711. /**
  712. * Return a link to the object card (with optionaly the picto)
  713. *
  714. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  715. * @param string $option On what the link point to ('nolink', ...)
  716. * @param int $notooltip 1=Disable tooltip
  717. * @param string $morecss Add more css on link
  718. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  719. * @return string String with URL
  720. */
  721. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  722. {
  723. global $conf, $langs, $hookmanager;
  724. if (!empty($conf->dol_no_mouse_hover)) {
  725. $notooltip = 1; // Force disable tooltips
  726. }
  727. $result = '';
  728. $params = [
  729. 'id' => $this->id,
  730. 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
  731. 'option' => $option,
  732. ];
  733. $classfortooltip = 'classfortooltip';
  734. $dataparams = '';
  735. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  736. $classfortooltip = 'classforajaxtooltip';
  737. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  738. $label = '';
  739. } else {
  740. $label = implode($this->getTooltipContentArray($params));
  741. }
  742. $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id;
  743. if ($option !== 'nolink') {
  744. // Add param to save lastsearch_values or not
  745. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  746. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  747. $add_save_lastsearch_values = 1;
  748. }
  749. if ($url && $add_save_lastsearch_values) {
  750. $url .= '&save_lastsearch_values=1';
  751. }
  752. }
  753. $linkclose = '';
  754. if (empty($notooltip)) {
  755. if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  756. $label = $langs->trans("ShowMyObject");
  757. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  758. }
  759. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  760. $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
  761. } else {
  762. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  763. }
  764. if ($option == 'nolink' || empty($url)) {
  765. $linkstart = '<span';
  766. } else {
  767. $linkstart = '<a href="'.$url.'"';
  768. }
  769. $linkstart .= $linkclose.'>';
  770. if ($option == 'nolink' || empty($url)) {
  771. $linkend = '</span>';
  772. } else {
  773. $linkend = '</a>';
  774. }
  775. $result .= $linkstart;
  776. if (empty($this->showphoto_on_popup)) {
  777. if ($withpicto) {
  778. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
  779. }
  780. } else {
  781. if ($withpicto) {
  782. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  783. list($class, $module) = explode('@', $this->picto);
  784. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  785. $filearray = dol_dir_list($upload_dir, "files");
  786. $filename = $filearray[0]['name'];
  787. if (!empty($filename)) {
  788. $pospoint = strpos($filearray[0]['name'], '.');
  789. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  790. if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
  791. $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>';
  792. } else {
  793. $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>';
  794. }
  795. $result .= '</div>';
  796. } else {
  797. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
  798. }
  799. }
  800. }
  801. if ($withpicto != 2) {
  802. $result .= $this->ref;
  803. }
  804. $result .= $linkend;
  805. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  806. global $action, $hookmanager;
  807. $hookmanager->initHooks(array($this->element.'dao'));
  808. $parameters = array('id' => $this->id, 'getnomurl' => &$result);
  809. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  810. if ($reshook > 0) {
  811. $result = $hookmanager->resPrint;
  812. } else {
  813. $result .= $hookmanager->resPrint;
  814. }
  815. return $result;
  816. }
  817. /**
  818. * Return a thumb for kanban views
  819. *
  820. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  821. * @param array $arraydata Array of data
  822. * @return string HTML Code for Kanban thumb.
  823. */
  824. public function getKanbanView($option = '', $arraydata = null)
  825. {
  826. global $conf, $langs;
  827. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  828. $return = '<div class="box-flex-item box-flex-grow-zero">';
  829. $return .= '<div class="info-box info-box-sm">';
  830. $return .= '<span class="info-box-icon bg-infobox-action">';
  831. $return .= img_picto('', $this->picto);
  832. $return .= '</span>';
  833. $return .= '<div class="info-box-content">';
  834. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  835. if ($selected >= 0) {
  836. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  837. }
  838. if (property_exists($this, 'label')) {
  839. $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">'.$this->label.'</div>';
  840. }
  841. if (property_exists($this, 'thirdparty') && is_object($this->thirdparty)) {
  842. $return .= '<br><div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
  843. }
  844. if (property_exists($this, 'amount')) {
  845. $return .= '<br>';
  846. $return .= '<span class="info-box-label amount">'.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).'</span>';
  847. }
  848. if (method_exists($this, 'getLibStatut')) {
  849. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
  850. }
  851. $return .= '</div>';
  852. $return .= '</div>';
  853. $return .= '</div>';
  854. return $return;
  855. }
  856. /**
  857. * Return the label of the status
  858. *
  859. * @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
  860. * @return string Label of status
  861. */
  862. public function getLabelStatus($mode = 0)
  863. {
  864. return $this->LibStatut($this->status, $mode);
  865. }
  866. /**
  867. * Return the label of the status
  868. *
  869. * @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
  870. * @return string Label of status
  871. */
  872. public function getLibStatut($mode = 0)
  873. {
  874. return $this->LibStatut($this->status, $mode);
  875. }
  876. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  877. /**
  878. * Return the label of a given status
  879. *
  880. * @param int $status Id status
  881. * @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
  882. * @return string Label of status
  883. */
  884. public function LibStatut($status, $mode = 0)
  885. {
  886. // phpcs:enable
  887. if (is_null($status)) {
  888. return '';
  889. }
  890. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  891. global $langs;
  892. //$langs->load("mymodule@mymodule");
  893. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  894. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  895. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  896. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  897. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  898. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  899. }
  900. $statusType = 'status'.$status;
  901. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  902. if ($status == self::STATUS_CANCELED) {
  903. $statusType = 'status6';
  904. }
  905. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  906. }
  907. /**
  908. * Load the info information in the object
  909. *
  910. * @param int $id Id of object
  911. * @return void
  912. */
  913. public function info($id)
  914. {
  915. $sql = "SELECT rowid,";
  916. $sql .= " date_creation as datec, tms as datem";
  917. if (!empty($this->fields['date_validation'])) {
  918. $sql .= ", date_validation as datev";
  919. }
  920. if (!empty($this->fields['fk_user_creat'])) {
  921. $sql .= ", fk_user_creat";
  922. }
  923. if (!empty($this->fields['fk_user_modif'])) {
  924. $sql .= ", fk_user_modif";
  925. }
  926. if (!empty($this->fields['fk_user_valid'])) {
  927. $sql .= ", fk_user_valid";
  928. }
  929. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  930. $sql .= " WHERE t.rowid = ".((int) $id);
  931. $result = $this->db->query($sql);
  932. if ($result) {
  933. if ($this->db->num_rows($result)) {
  934. $obj = $this->db->fetch_object($result);
  935. $this->id = $obj->rowid;
  936. if (!empty($this->fields['fk_user_creat'])) {
  937. $this->user_creation_id = $obj->fk_user_creat;
  938. }
  939. if (!empty($this->fields['fk_user_modif'])) {
  940. $this->user_modification_id = $obj->fk_user_modif;
  941. }
  942. if (!empty($this->fields['fk_user_valid'])) {
  943. $this->user_validation_id = $obj->fk_user_valid;
  944. }
  945. $this->date_creation = $this->db->jdate($obj->datec);
  946. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  947. if (!empty($obj->datev)) {
  948. $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
  949. }
  950. }
  951. $this->db->free($result);
  952. } else {
  953. dol_print_error($this->db);
  954. }
  955. }
  956. /**
  957. * Initialise object with example values
  958. * Id must be 0 if object instance is a specimen
  959. *
  960. * @return void
  961. */
  962. public function initAsSpecimen()
  963. {
  964. // Set here init that are not commonf fields
  965. // $this->property1 = ...
  966. // $this->property2 = ...
  967. $this->initAsSpecimenCommon();
  968. }
  969. /**
  970. * Create an array of lines
  971. *
  972. * @return array|int array of lines if OK, <0 if KO
  973. */
  974. public function getLinesArray()
  975. {
  976. $this->lines = array();
  977. $objectline = new MyObjectLine($this->db);
  978. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.((int) $this->id)));
  979. if (is_numeric($result)) {
  980. $this->setErrorsFromObject($objectline);
  981. return $result;
  982. } else {
  983. $this->lines = $result;
  984. return $this->lines;
  985. }
  986. }
  987. /**
  988. * Returns the reference to the following non used object depending on the active numbering module.
  989. *
  990. * @return string Object free reference
  991. */
  992. public function getNextNumRef()
  993. {
  994. global $langs, $conf;
  995. $langs->load("mymodule@mymodule");
  996. if (!getDolGlobalString('MYMODULE_MYOBJECT_ADDON')) {
  997. $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
  998. }
  999. if (getDolGlobalString('MYMODULE_MYOBJECT_ADDON')) {
  1000. $mybool = false;
  1001. $file = getDolGlobalString('MYMODULE_MYOBJECT_ADDON').".php";
  1002. $classname = getDolGlobalString('MYMODULE_MYOBJECT_ADDON');
  1003. // Include file with class
  1004. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  1005. foreach ($dirmodels as $reldir) {
  1006. $dir = dol_buildpath($reldir."core/modules/mymodule/");
  1007. // Load file with numbering class (if found)
  1008. $mybool |= @include_once $dir.$file;
  1009. }
  1010. if ($mybool === false) {
  1011. dol_print_error('', "Failed to include file ".$file);
  1012. return '';
  1013. }
  1014. if (class_exists($classname)) {
  1015. $obj = new $classname();
  1016. $numref = $obj->getNextValue($this);
  1017. if ($numref != '' && $numref != '-1') {
  1018. return $numref;
  1019. } else {
  1020. $this->error = $obj->error;
  1021. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  1022. return "";
  1023. }
  1024. } else {
  1025. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  1026. return "";
  1027. }
  1028. } else {
  1029. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  1030. return "";
  1031. }
  1032. }
  1033. /**
  1034. * Create a document onto disk according to template module.
  1035. *
  1036. * @param string $modele Force template to use ('' to not force)
  1037. * @param Translate $outputlangs objet lang a utiliser pour traduction
  1038. * @param int $hidedetails Hide details of lines
  1039. * @param int $hidedesc Hide description
  1040. * @param int $hideref Hide ref
  1041. * @param null|array $moreparams Array to provide more information
  1042. * @return int 0 if KO, 1 if OK
  1043. */
  1044. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  1045. {
  1046. global $conf, $langs;
  1047. $result = 0;
  1048. $includedocgeneration = 0;
  1049. $langs->load("mymodule@mymodule");
  1050. if (!dol_strlen($modele)) {
  1051. $modele = 'standard_myobject';
  1052. if (!empty($this->model_pdf)) {
  1053. $modele = $this->model_pdf;
  1054. } elseif (getDolGlobalString('MYOBJECT_ADDON_PDF')) {
  1055. $modele = getDolGlobalString('MYOBJECT_ADDON_PDF');
  1056. }
  1057. }
  1058. $modelpath = "core/modules/mymodule/doc/";
  1059. if ($includedocgeneration && !empty($modele)) {
  1060. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1061. }
  1062. return $result;
  1063. }
  1064. /**
  1065. * Action executed by scheduler
  1066. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  1067. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  1068. *
  1069. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  1070. */
  1071. public function doScheduledJob()
  1072. {
  1073. //global $conf, $langs;
  1074. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlogfile.log';
  1075. $error = 0;
  1076. $this->output = '';
  1077. $this->error = '';
  1078. dol_syslog(__METHOD__." start", LOG_INFO);
  1079. $now = dol_now();
  1080. $this->db->begin();
  1081. // ...
  1082. $this->db->commit();
  1083. dol_syslog(__METHOD__." end", LOG_INFO);
  1084. return $error;
  1085. }
  1086. }
  1087. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  1088. /**
  1089. * Class MyObjectLine. You can also remove this and generate a CRUD class for lines objects.
  1090. */
  1091. class MyObjectLine extends CommonObjectLine
  1092. {
  1093. // To complete with content of an object MyObjectLine
  1094. // We should have a field rowid, fk_myobject and position
  1095. /**
  1096. * @var int Does object support extrafields ? 0=No, 1=Yes
  1097. */
  1098. public $isextrafieldmanaged = 0;
  1099. /**
  1100. * Constructor
  1101. *
  1102. * @param DoliDb $db Database handler
  1103. */
  1104. public function __construct(DoliDB $db)
  1105. {
  1106. $this->db = $db;
  1107. }
  1108. }