myobject.class.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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[: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->hasRights->('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 <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. * @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 (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->myobject->write))
  495. || (getDolGlobalInt('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 (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->write))
  598. || (getDolGlobalInt('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 (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->write))
  619. || (getDolGlobalInt('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 (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->write))
  640. || (getDolGlobalInt('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. * getTooltipContentArray
  649. *
  650. * @param array $params Params to construct tooltip data
  651. * @since v18
  652. * @return array
  653. */
  654. public function getTooltipContentArray($params)
  655. {
  656. global $conf, $langs;
  657. $datas = [];
  658. if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  659. return ['optimize' => $langs->trans("ShowMyObject")];
  660. }
  661. $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("MyObject").'</u>';
  662. if (isset($this->status)) {
  663. $datas['picto'] .= ' '.$this->getLibStatut(5);
  664. }
  665. $datas['ref'] .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  666. return $datas;
  667. }
  668. /**
  669. * Return a link to the object card (with optionaly the picto)
  670. *
  671. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  672. * @param string $option On what the link point to ('nolink', ...)
  673. * @param int $notooltip 1=Disable tooltip
  674. * @param string $morecss Add more css on link
  675. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  676. * @return string String with URL
  677. */
  678. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  679. {
  680. global $conf, $langs, $hookmanager;
  681. if (!empty($conf->dol_no_mouse_hover)) {
  682. $notooltip = 1; // Force disable tooltips
  683. }
  684. $result = '';
  685. $params = [
  686. 'id' => $this->id,
  687. 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
  688. 'option' => $option,
  689. ];
  690. $classfortooltip = 'classfortooltip';
  691. $dataparams = '';
  692. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  693. $classfortooltip = 'classforajaxtooltip';
  694. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  695. $label = '';
  696. } else {
  697. $label = implode($this->getTooltipContentArray($params));
  698. }
  699. $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id;
  700. if ($option != 'nolink') {
  701. // Add param to save lastsearch_values or not
  702. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  703. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  704. $add_save_lastsearch_values = 1;
  705. }
  706. if ($url && $add_save_lastsearch_values) {
  707. $url .= '&save_lastsearch_values=1';
  708. }
  709. }
  710. $linkclose = '';
  711. if (empty($notooltip)) {
  712. if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  713. $label = $langs->trans("ShowMyObject");
  714. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  715. }
  716. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  717. $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
  718. } else {
  719. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  720. }
  721. if ($option == 'nolink' || empty($url)) {
  722. $linkstart = '<span';
  723. } else {
  724. $linkstart = '<a href="'.$url.'"';
  725. }
  726. $linkstart .= $linkclose.'>';
  727. if ($option == 'nolink' || empty($url)) {
  728. $linkend = '</span>';
  729. } else {
  730. $linkend = '</a>';
  731. }
  732. $result .= $linkstart;
  733. if (empty($this->showphoto_on_popup)) {
  734. if ($withpicto) {
  735. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
  736. }
  737. } else {
  738. if ($withpicto) {
  739. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  740. list($class, $module) = explode('@', $this->picto);
  741. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  742. $filearray = dol_dir_list($upload_dir, "files");
  743. $filename = $filearray[0]['name'];
  744. if (!empty($filename)) {
  745. $pospoint = strpos($filearray[0]['name'], '.');
  746. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  747. if (!getDolGlobalInt(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
  748. $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>';
  749. } else {
  750. $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>';
  751. }
  752. $result .= '</div>';
  753. } else {
  754. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
  755. }
  756. }
  757. }
  758. if ($withpicto != 2) {
  759. $result .= $this->ref;
  760. }
  761. $result .= $linkend;
  762. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  763. global $action, $hookmanager;
  764. $hookmanager->initHooks(array($this->element.'dao'));
  765. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  766. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  767. if ($reshook > 0) {
  768. $result = $hookmanager->resPrint;
  769. } else {
  770. $result .= $hookmanager->resPrint;
  771. }
  772. return $result;
  773. }
  774. /**
  775. * Return a thumb for kanban views
  776. *
  777. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  778. * @param array $arraydata Array of data
  779. * @return string HTML Code for Kanban thumb.
  780. */
  781. public function getKanbanView($option = '', $arraydata = null)
  782. {
  783. global $conf, $langs;
  784. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  785. $return = '<div class="box-flex-item box-flex-grow-zero">';
  786. $return .= '<div class="info-box info-box-sm">';
  787. $return .= '<span class="info-box-icon bg-infobox-action">';
  788. $return .= img_picto('', $this->picto);
  789. $return .= '</span>';
  790. $return .= '<div class="info-box-content">';
  791. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  792. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  793. if (property_exists($this, 'label')) {
  794. $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">'.$this->label.'</div>';
  795. }
  796. if (property_exists($this, 'amount')) {
  797. $return .= '<br>';
  798. $return .= '<span class="info-box-label amount">'.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).'</span>';
  799. }
  800. if (method_exists($this, 'getLibStatut')) {
  801. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
  802. }
  803. $return .= '</div>';
  804. $return .= '</div>';
  805. $return .= '</div>';
  806. return $return;
  807. }
  808. /**
  809. * Return the label of the status
  810. *
  811. * @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
  812. * @return string Label of status
  813. */
  814. public function getLabelStatus($mode = 0)
  815. {
  816. return $this->LibStatut($this->status, $mode);
  817. }
  818. /**
  819. * Return the label of the status
  820. *
  821. * @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
  822. * @return string Label of status
  823. */
  824. public function getLibStatut($mode = 0)
  825. {
  826. return $this->LibStatut($this->status, $mode);
  827. }
  828. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  829. /**
  830. * Return the label of a given status
  831. *
  832. * @param int $status Id status
  833. * @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
  834. * @return string Label of status
  835. */
  836. public function LibStatut($status, $mode = 0)
  837. {
  838. // phpcs:enable
  839. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  840. global $langs;
  841. //$langs->load("mymodule@mymodule");
  842. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  843. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  844. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  845. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  846. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  847. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  848. }
  849. $statusType = 'status'.$status;
  850. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  851. if ($status == self::STATUS_CANCELED) {
  852. $statusType = 'status6';
  853. }
  854. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  855. }
  856. /**
  857. * Load the info information in the object
  858. *
  859. * @param int $id Id of object
  860. * @return void
  861. */
  862. public function info($id)
  863. {
  864. $sql = "SELECT rowid,";
  865. $sql .= " date_creation as datec, tms as datem,";
  866. $sql .= " fk_user_creat, fk_user_modif";
  867. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  868. $sql .= " WHERE t.rowid = ".((int) $id);
  869. $result = $this->db->query($sql);
  870. if ($result) {
  871. if ($this->db->num_rows($result)) {
  872. $obj = $this->db->fetch_object($result);
  873. $this->id = $obj->rowid;
  874. $this->user_creation_id = $obj->fk_user_creat;
  875. $this->user_modification_id = $obj->fk_user_modif;
  876. if (!empty($obj->fk_user_valid)) {
  877. $this->user_validation_id = $obj->fk_user_valid;
  878. }
  879. $this->date_creation = $this->db->jdate($obj->datec);
  880. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  881. if (!empty($obj->datev)) {
  882. $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
  883. }
  884. }
  885. $this->db->free($result);
  886. } else {
  887. dol_print_error($this->db);
  888. }
  889. }
  890. /**
  891. * Initialise object with example values
  892. * Id must be 0 if object instance is a specimen
  893. *
  894. * @return void
  895. */
  896. public function initAsSpecimen()
  897. {
  898. // Set here init that are not commonf fields
  899. // $this->property1 = ...
  900. // $this->property2 = ...
  901. $this->initAsSpecimenCommon();
  902. }
  903. /**
  904. * Create an array of lines
  905. *
  906. * @return array|int array of lines if OK, <0 if KO
  907. */
  908. public function getLinesArray()
  909. {
  910. $this->lines = array();
  911. $objectline = new MyObjectLine($this->db);
  912. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.((int) $this->id)));
  913. if (is_numeric($result)) {
  914. $this->setErrorsFromObject($objectline);
  915. return $result;
  916. } else {
  917. $this->lines = $result;
  918. return $this->lines;
  919. }
  920. }
  921. /**
  922. * Returns the reference to the following non used object depending on the active numbering module.
  923. *
  924. * @return string Object free reference
  925. */
  926. public function getNextNumRef()
  927. {
  928. global $langs, $conf;
  929. $langs->load("mymodule@mymodule");
  930. if (empty(getDolGlobalString('MYMODULE_MYOBJECT_ADDON'))) {
  931. $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
  932. }
  933. if (!empty(getDolGlobalString('MYMODULE_MYOBJECT_ADDON'))) {
  934. $mybool = false;
  935. $file = getDolGlobalString('MYMODULE_MYOBJECT_ADDON').".php";
  936. $classname = getDolGlobalString('MYMODULE_MYOBJECT_ADDON');
  937. // Include file with class
  938. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  939. foreach ($dirmodels as $reldir) {
  940. $dir = dol_buildpath($reldir."core/modules/mymodule/");
  941. // Load file with numbering class (if found)
  942. $mybool |= @include_once $dir.$file;
  943. }
  944. if ($mybool === false) {
  945. dol_print_error('', "Failed to include file ".$file);
  946. return '';
  947. }
  948. if (class_exists($classname)) {
  949. $obj = new $classname();
  950. $numref = $obj->getNextValue($this);
  951. if ($numref != '' && $numref != '-1') {
  952. return $numref;
  953. } else {
  954. $this->error = $obj->error;
  955. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  956. return "";
  957. }
  958. } else {
  959. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  960. return "";
  961. }
  962. } else {
  963. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  964. return "";
  965. }
  966. }
  967. /**
  968. * Create a document onto disk according to template module.
  969. *
  970. * @param string $modele Force template to use ('' to not force)
  971. * @param Translate $outputlangs objet lang a utiliser pour traduction
  972. * @param int $hidedetails Hide details of lines
  973. * @param int $hidedesc Hide description
  974. * @param int $hideref Hide ref
  975. * @param null|array $moreparams Array to provide more information
  976. * @return int 0 if KO, 1 if OK
  977. */
  978. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  979. {
  980. global $conf, $langs;
  981. $result = 0;
  982. $includedocgeneration = 0;
  983. $langs->load("mymodule@mymodule");
  984. if (!dol_strlen($modele)) {
  985. $modele = 'standard_myobject';
  986. if (!empty($this->model_pdf)) {
  987. $modele = $this->model_pdf;
  988. } elseif (getDolGlobalString('MYOBJECT_ADDON_PDF')) {
  989. $modele = getDolGlobalString('MYOBJECT_ADDON_PDF');
  990. }
  991. }
  992. $modelpath = "core/modules/mymodule/doc/";
  993. if ($includedocgeneration && !empty($modele)) {
  994. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  995. }
  996. return $result;
  997. }
  998. /**
  999. * Action executed by scheduler
  1000. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  1001. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  1002. *
  1003. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  1004. */
  1005. public function doScheduledJob()
  1006. {
  1007. //global $conf, $langs;
  1008. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  1009. $error = 0;
  1010. $this->output = '';
  1011. $this->error = '';
  1012. dol_syslog(__METHOD__, LOG_DEBUG);
  1013. $now = dol_now();
  1014. $this->db->begin();
  1015. // ...
  1016. $this->db->commit();
  1017. return $error;
  1018. }
  1019. }
  1020. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  1021. /**
  1022. * Class MyObjectLine. You can also remove this and generate a CRUD class for lines objects.
  1023. */
  1024. class MyObjectLine extends CommonObjectLine
  1025. {
  1026. // To complete with content of an object MyObjectLine
  1027. // We should have a field rowid, fk_myobject and position
  1028. /**
  1029. * @var int Does object support extrafields ? 0=No, 1=Yes
  1030. */
  1031. public $isextrafieldmanaged = 0;
  1032. /**
  1033. * Constructor
  1034. *
  1035. * @param DoliDb $db Database handler
  1036. */
  1037. public function __construct(DoliDB $db)
  1038. {
  1039. $this->db = $db;
  1040. }
  1041. }