Passed
Branch develop (81cb55)
by
unknown
33:41
created

MyObjectLine::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

921
		/** @scrutinizer ignore-call */ 
922
  $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.$this->id));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
922
923
		if (is_numeric($result))
924
		{
925
			$this->error = $this->error;
926
			$this->errors = $this->errors;
927
			return $result;
928
		} else {
929
			$this->lines = $result;
930
			return $this->lines;
931
		}
932
	}
933
934
	/**
935
	 *  Returns the reference to the following non used object depending on the active numbering module.
936
	 *
937
	 *  @return string      		Object free reference
938
	 */
939
	public function getNextNumRef()
940
	{
941
		global $langs, $conf;
942
		$langs->load("mymodule@mymodule");
943
944
		if (empty($conf->global->MYMODULE_MYOBJECT_ADDON)) {
945
			$conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
946
		}
947
948
		if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON))
949
		{
950
			$mybool = false;
951
952
			$file = $conf->global->MYMODULE_MYOBJECT_ADDON.".php";
953
			$classname = $conf->global->MYMODULE_MYOBJECT_ADDON;
954
955
			// Include file with class
956
			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
957
			foreach ($dirmodels as $reldir)
958
			{
959
				$dir = dol_buildpath($reldir."core/modules/mymodule/");
960
961
				// Load file with numbering class (if found)
962
				$mybool |= @include_once $dir.$file;
963
			}
964
965
			if ($mybool === false)
966
			{
967
				dol_print_error('', "Failed to include file ".$file);
968
				return '';
969
			}
970
971
			if (class_exists($classname)) {
972
				$obj = new $classname();
973
				$numref = $obj->getNextValue($this);
974
975
				if ($numref != '' && $numref != '-1')
976
				{
977
					return $numref;
978
				} else {
979
					$this->error = $obj->error;
980
					//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
981
					return "";
982
				}
983
			} else {
984
				print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
985
				return "";
986
			}
987
		} else {
988
			print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
989
			return "";
990
		}
991
	}
992
993
	/**
994
	 *  Create a document onto disk according to template module.
995
	 *
996
	 *  @param	    string		$modele			Force template to use ('' to not force)
997
	 *  @param		Translate	$outputlangs	objet lang a utiliser pour traduction
998
	 *  @param      int			$hidedetails    Hide details of lines
999
	 *  @param      int			$hidedesc       Hide description
1000
	 *  @param      int			$hideref        Hide ref
1001
	 *  @param      null|array  $moreparams     Array to provide more information
1002
	 *  @return     int         				0 if KO, 1 if OK
1003
	 */
1004
	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1005
	{
1006
		global $conf, $langs;
1007
1008
		$result = 0;
1009
		$includedocgeneration = 0;
1010
1011
		$langs->load("mymodule@mymodule");
1012
1013
		if (!dol_strlen($modele)) {
1014
			$modele = 'standard_myobject';
1015
1016
			if ($this->modelpdf) {
1017
				$modele = $this->modelpdf;
1018
			} elseif (!empty($conf->global->MYOBJECT_ADDON_PDF)) {
1019
				$modele = $conf->global->MYOBJECT_ADDON_PDF;
1020
			}
1021
		}
1022
1023
		$modelpath = "core/modules/mymodule/doc/";
1024
1025
		if ($includedocgeneration) {
1026
			$result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1027
		}
1028
1029
		return $result;
1030
	}
1031
1032
	/**
1033
	 * Action executed by scheduler
1034
	 * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
1035
	 * Use public function doScheduledJob($param1, $param2, ...) to get parameters
1036
	 *
1037
	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
1038
	 */
1039
	public function doScheduledJob()
1040
	{
1041
		global $conf, $langs;
1042
1043
		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1044
1045
		$error = 0;
1046
		$this->output = '';
1047
		$this->error = '';
1048
1049
		dol_syslog(__METHOD__, LOG_DEBUG);
1050
1051
		$now = dol_now();
1052
1053
		$this->db->begin();
1054
1055
		// ...
1056
1057
		$this->db->commit();
1058
1059
		return $error;
1060
	}
1061
}
1062
1063
1064
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
1065
1066
/**
1067
 * Class MyObjectLine. You can also remove this and generate a CRUD class for lines objects.
1068
 */
1069
class MyObjectLine extends CommonObjectLine
1070
{
1071
	// To complete with content of an object MyObjectLine
1072
	// We should have a field rowid, fk_myobject and position
1073
1074
	/**
1075
	 * Constructor
1076
	 *
1077
	 * @param DoliDb $db Database handler
1078
	 */
1079
	public function __construct(DoliDB $db)
1080
	{
1081
		$this->db = $db;
1082
	}
1083
}
1084