myobject.class.php 40 KB

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