Passed
Branch develop (a94721)
by
unknown
26:42
created

MyObject::doScheduledJob()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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

886
	    /** @scrutinizer ignore-call */ 
887
     $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...
887
888
	    if (is_numeric($result))
889
	    {
890
	        $this->error = $this->error;
891
	        $this->errors = $this->errors;
892
	        return $result;
893
	    }
894
	    else
895
	    {
896
	        $this->lines = $result;
897
	        return $this->lines;
898
	    }
899
	}
900
901
	/**
902
	 *  Returns the reference to the following non used object depending on the active numbering module.
903
	 *
904
	 *  @return string      		Object free reference
905
	 */
906
	public function getNextNumRef()
907
	{
908
		global $langs, $conf;
909
		$langs->load("mymodule@myobject");
910
911
		if (empty($conf->global->MYMODULE_MYOBJECT_ADDON)) {
912
			$conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_mymobject_standard';
913
		}
914
915
		if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON))
916
		{
917
			$mybool = false;
918
919
			$file = $conf->global->MYMODULE_MYOBJECT_ADDON.".php";
920
			$classname = $conf->global->MYMODULE_MYOBJECT_ADDON;
921
922
			// Include file with class
923
			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
924
			foreach ($dirmodels as $reldir)
925
			{
926
				$dir = dol_buildpath($reldir."core/modules/mymodule/");
927
928
				// Load file with numbering class (if found)
929
				$mybool |= @include_once $dir.$file;
930
			}
931
932
			if ($mybool === false)
933
			{
934
				dol_print_error('', "Failed to include file ".$file);
935
				return '';
936
			}
937
938
			$obj = new $classname();
939
			$numref = $obj->getNextValue($this);
940
941
			if ($numref != "")
942
			{
943
				return $numref;
944
			}
945
			else
946
			{
947
				$this->error = $obj->error;
948
				//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
949
				return "";
950
			}
951
		}
952
		else
953
		{
954
			print $langs->trans("Error")." ".$langs->trans("Error_MYMODULE_MYOBJECT_ADDON_NotDefined");
955
			return "";
956
		}
957
	}
958
959
	/**
960
	 *  Create a document onto disk according to template module.
961
	 *
962
	 *  @param	    string		$modele			Force template to use ('' to not force)
963
	 *  @param		Translate	$outputlangs	objet lang a utiliser pour traduction
964
	 *  @param      int			$hidedetails    Hide details of lines
965
	 *  @param      int			$hidedesc       Hide description
966
	 *  @param      int			$hideref        Hide ref
967
	 *  @param      null|array  $moreparams     Array to provide more information
968
	 *  @return     int         				0 if KO, 1 if OK
969
	 */
970
	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
971
	{
972
		global $conf, $langs;
973
974
		$langs->load("mymodule@mymodule");
975
976
		if (!dol_strlen($modele)) {
977
			$modele = 'standard';
978
979
			if ($this->modelpdf) {
980
				$modele = $this->modelpdf;
981
			} elseif (!empty($conf->global->MYOBJECT_ADDON_PDF)) {
982
				$modele = $conf->global->MYOBJECT_ADDON_PDF;
983
			}
984
		}
985
986
		$modelpath = "core/modules/mymodule/doc/";
987
988
		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
989
	}
990
991
	/**
992
	 * Action executed by scheduler
993
	 * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
994
	 *
995
	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
996
	 */
997
	//public function doScheduledJob($param1, $param2, ...)
998
	public function doScheduledJob()
999
	{
1000
		global $conf, $langs;
1001
1002
		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1003
1004
		$error = 0;
1005
		$this->output = '';
1006
		$this->error = '';
1007
1008
		dol_syslog(__METHOD__, LOG_DEBUG);
1009
1010
		$now = dol_now();
1011
1012
		$this->db->begin();
1013
1014
		// ...
1015
1016
		$this->db->commit();
1017
1018
		return $error;
1019
	}
1020
}
1021
1022
/**
1023
 * Class MyObjectLine. You can also remove this and generate a CRUD class for lines objects.
1024
 */
1025
class MyObjectLine
1026
{
1027
	// To complete with content of an object MyObjectLine
1028
	// We should have a field rowid, fk_myobject and position
1029
}
1030