1<?php
2/* Copyright (C) 2017  Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) ---Put here your own copyright and developer email---
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19/**
20 * \file        emailcollector/class/emailcollectorfilter.class.php
21 * \ingroup     emailcollector
22 * \brief       This file is a CRUD class file for EmailCollectorFilter (Create/Read/Update/Delete)
23 */
24
25// Put here all includes required by your class file
26require_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 EmailCollectorFilter
32 */
33class EmailCollectorFilter extends CommonObject
34{
35	/**
36	 * @var string ID to identify managed object
37	 */
38	public $element = 'emailcollectorfilter';
39
40	/**
41	 * @var string Name of table without prefix where object is stored
42	 */
43	public $table_element = 'emailcollector_emailcollectorfilter';
44
45	/**
46	 * @var int  Does emailcollectorfilter 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 emailcollectorfilter support extrafields ? 0=No, 1=Yes
52	 */
53	public $isextrafieldmanaged = 0;
54
55	/**
56	 * @var string String with name of icon for emailcollectorfilter. Must be the part after the 'object_' into object_emailcollectorfilter.png
57	 */
58	public $picto = 'emailcollectorfilter@emailcollector';
59
60
61	/**
62	 *  'type' if the field format.
63	 *  'label' the translation key.
64	 *  'enabled' is a condition when the field must be managed.
65	 *  '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. Using a negative value means field is not shown by default on list but can be selected for viewing)
66	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
67	 *  'default' is a default value for creation (can still be replaced by the global setup of default values)
68	 *  'index' if we want an index in database.
69	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
70	 *  'position' is the sort order of field.
71	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
72	 *  '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).
73	 *  'css' is the CSS style to use on field. For example: 'maxwidth200'
74	 *  'help' is a string visible as a tooltip on field
75	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
76	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
77	 *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
78	 */
79
80	// BEGIN MODULEBUILDER PROPERTIES
81	/**
82	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
83	 */
84	public $fields = array(
85		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
86		'fk_emailcollector' => array('type'=>'integer', 'label'=>'Id of emailcollector', 'foreignkey'=>'emailcollector.rowid'),
87		'type' => array('type'=>'varchar(128)', 'label'=>'Type', 'enabled'=>1, 'visible'=>1, 'position'=>10, 'notnull'=>1,),
88		'rulevalue' => array('type'=>'varchar(255)', 'label'=>'ValueOfRule', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'notnull'=>-1, 'help'=>"Value of Rule",),
89		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>500, 'notnull'=>1,),
90		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>1,),
91		'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>510, 'notnull'=>1, 'foreignkey'=>'llx_user.rowid',),
92		'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'position'=>511, 'notnull'=>-1,),
93		'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
94		'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'position'=>1000, 'notnull'=>1, 'default'=>1, 'arrayofkeyval'=>array('0'=>'Disabled', '1'=>'Enabled')),
95	);
96	public $rowid;
97	public $fk_emailcollector;
98	public $type;
99	public $rulevalue;
100
101	/**
102	 * @var integer|string date_creation
103	 */
104	public $date_creation;
105
106
107	public $tms;
108	public $fk_user_creat;
109	public $fk_user_modif;
110	public $import_key;
111	public $status;
112	// END MODULEBUILDER PROPERTIES
113
114
115
116	/**
117	 * Constructor
118	 *
119	 * @param DoliDb $db Database handler
120	 */
121	public function __construct(DoliDB $db)
122	{
123		global $conf, $langs;
124
125		$this->db = $db;
126
127		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
128		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
129
130		// Unset fields that are disabled
131		foreach ($this->fields as $key => $val)
132		{
133			if (isset($val['enabled']) && empty($val['enabled']))
134			{
135				unset($this->fields[$key]);
136			}
137		}
138
139		// Translate some data of arrayofkeyval
140		foreach ($this->fields as $key => $val)
141		{
142			if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
143			{
144				foreach ($val['arrayofkeyval'] as $key2 => $val2)
145				{
146					$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
147				}
148			}
149		}
150	}
151
152	/**
153	 * Create object into database
154	 *
155	 * @param  User $user      User that creates
156	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
157	 * @return int             <0 if KO, Id of created object if OK
158	 */
159	public function create(User $user, $notrigger = false)
160	{
161		global $langs;
162		if (empty($this->type))
163		{
164			$langs->load("errors");
165			$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"));
166			return -1;
167		}
168		if (!in_array($this->type, array('seen', 'unseen', 'unanswered', 'answered', 'withtrackingidinmsgid', 'withouttrackingidinmsgid', 'withtrackingid', 'withouttrackingid', 'isanswer', 'isnotanswer')) && empty($this->rulevalue))
169		{
170			$langs->load("errors");
171			$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SearchString"));
172			return -2;
173		}
174
175		return $this->createCommon($user, $notrigger);
176	}
177
178	/**
179	 * Clone and object into another one
180	 *
181	 * @param  	User 	$user      	User that creates
182	 * @param  	int 	$fromid     Id of object to clone
183	 * @return 	mixed 				New object created, <0 if KO
184	 */
185	public function createFromClone(User $user, $fromid)
186	{
187		global $langs, $hookmanager, $extrafields;
188		$error = 0;
189
190		dol_syslog(__METHOD__, LOG_DEBUG);
191
192		$object = new self($this->db);
193
194		$this->db->begin();
195
196		// Load source object
197		$object->fetchCommon($fromid);
198		// Reset some properties
199		unset($object->id);
200		unset($object->fk_user_creat);
201		unset($object->import_key);
202
203		// Clear fields
204		$object->ref = "copy_of_".$object->ref;
205		$object->title = $langs->trans("CopyOf")." ".$object->title;
206		// ...
207		// Clear extrafields that are unique
208		if (is_array($object->array_options) && count($object->array_options) > 0)
209		{
210			$extrafields->fetch_name_optionals_label($this->table_element);
211			foreach ($object->array_options as $key => $option)
212			{
213				$shortkey = preg_replace('/options_/', '', $key);
214				if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
215				{
216					//var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
217					unset($object->array_options[$key]);
218				}
219			}
220		}
221
222		// Create clone
223		$object->context['createfromclone'] = 'createfromclone';
224		$result = $object->createCommon($user);
225		if ($result < 0) {
226			$error++;
227			$this->error = $object->error;
228			$this->errors = $object->errors;
229		}
230
231		unset($object->context['createfromclone']);
232
233		// End
234		if (!$error) {
235			$this->db->commit();
236			return $object;
237		} else {
238			$this->db->rollback();
239			return -1;
240		}
241	}
242
243	/**
244	 * Load object in memory from the database
245	 *
246	 * @param int    $id   Id object
247	 * @param string $ref  Ref
248	 * @return int         <0 if KO, 0 if not found, >0 if OK
249	 */
250	public function fetch($id, $ref = null)
251	{
252		$result = $this->fetchCommon($id, $ref);
253		if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
254		return $result;
255	}
256
257	/**
258	 * Load object lines in memory from the database
259	 *
260	 * @return int         <0 if KO, 0 if not found, >0 if OK
261	 */
262	/*public function fetchLines()
263	{
264		$this->lines=array();
265
266		// Load lines with object EmailcollectorFilterLine
267
268		return count($this->lines)?1:0;
269	}*/
270
271	/**
272	 * Update object into database
273	 *
274	 * @param  User $user      User that modifies
275	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
276	 * @return int             <0 if KO, >0 if OK
277	 */
278	public function update(User $user, $notrigger = false)
279	{
280		return $this->updateCommon($user, $notrigger);
281	}
282
283	/**
284	 * Delete object in database
285	 *
286	 * @param User $user       User that deletes
287	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
288	 * @return int             <0 if KO, >0 if OK
289	 */
290	public function delete(User $user, $notrigger = false)
291	{
292		return $this->deleteCommon($user, $notrigger);
293	}
294
295	/**
296	 *  Return a link to the object card (with optionaly the picto)
297	 *
298	 *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
299	 *	@param	string	$option						On what the link point to ('nolink', ...)
300	 *  @param	int  	$notooltip					1=Disable tooltip
301	 *  @param  string  $morecss            		Add more css on link
302	 *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
303	 *	@return	string								String with URL
304	 */
305	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
306	{
307		global $db, $conf, $langs, $hookmanager;
308		global $dolibarr_main_authentication, $dolibarr_main_demo;
309		global $menumanager;
310
311		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
312
313		$result = '';
314		$companylink = '';
315
316		$label = '<u>'.$langs->trans("EmailcollectorFilter").'</u>';
317		$label .= '<br>';
318		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
319
320		$url = dol_buildpath('/emailcollector/emailcollectorfilter_card.php', 1).'?id='.$this->id;
321
322		if ($option != 'nolink')
323		{
324			// Add param to save lastsearch_values or not
325			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
326			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
327			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
328		}
329
330		$linkclose = '';
331		if (empty($notooltip))
332		{
333			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
334			{
335				$label = $langs->trans("ShowEmailcollectorFilter");
336				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
337			}
338			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
339			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
340
341			/*
342             $hookmanager->initHooks(array('emailcollectorfilterdao'));
343             $parameters=array('id'=>$this->id);
344             $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
345             if ($reshook > 0) $linkclose = $hookmanager->resPrint;
346             */
347		} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
348
349		$linkstart = '<a href="'.$url.'"';
350		$linkstart .= $linkclose.'>';
351		$linkend = '</a>';
352
353		$result .= $linkstart;
354		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);
355		if ($withpicto != 2) $result .= $this->ref;
356		$result .= $linkend;
357		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
358
359		global $action, $hookmanager;
360		$hookmanager->initHooks(array('emailcollectorfilterdao'));
361		$parameters = array('id'=>$this->id, 'getnomurl'=>$result);
362		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
363		if ($reshook > 0) $result = $hookmanager->resPrint;
364		else $result .= $hookmanager->resPrint;
365
366		return $result;
367	}
368
369	/**
370	 *  Return label of the status
371	 *
372	 *  @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
373	 *  @return	string 			       Label of status
374	 */
375	public function getLibStatut($mode = 0)
376	{
377		return $this->LibStatut($this->status, $mode);
378	}
379
380	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
381	/**
382	 *  Return the status
383	 *
384	 *  @param	int		$status        Id status
385	 *  @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
386	 *  @return string 			       Label of status
387	 */
388	public function LibStatut($status, $mode = 0)
389	{
390		// phpcs:enable
391		if (empty($this->labelStatus))
392		{
393			global $langs;
394			//$langs->load("emailcollector");
395			$this->labelStatus[1] = $langs->trans('Enabled');
396			$this->labelStatus[0] = $langs->trans('Disabled');
397		}
398
399		if ($mode == 0)
400		{
401			return $this->labelStatus[$status];
402		} elseif ($mode == 1)
403		{
404			return $this->labelStatus[$status];
405		} elseif ($mode == 2)
406		{
407			if ($status == 1) return img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status];
408			elseif ($status == 0) return img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status];
409		} elseif ($mode == 3)
410		{
411			if ($status == 1) return img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle');
412			elseif ($status == 0) return img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle');
413		} elseif ($mode == 4)
414		{
415			if ($status == 1) return img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status];
416			elseif ($status == 0) return img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status];
417		} elseif ($mode == 5)
418		{
419			if ($status == 1) return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle');
420			elseif ($status == 0) return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle');
421		} elseif ($mode == 6)
422		{
423			if ($status == 1) return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle');
424			elseif ($status == 0) return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle');
425		}
426	}
427
428	/**
429	 *	Charge les informations d'ordre info dans l'objet commande
430	 *
431	 *	@param  int		$id       Id of order
432	 *	@return	void
433	 */
434	public function info($id)
435	{
436		$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
437		$sql .= ' fk_user_creat, fk_user_modif';
438		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
439		$sql .= ' WHERE t.rowid = '.$id;
440		$result = $this->db->query($sql);
441		if ($result)
442		{
443			if ($this->db->num_rows($result))
444			{
445				$obj = $this->db->fetch_object($result);
446				$this->id = $obj->rowid;
447				if ($obj->fk_user_author)
448				{
449					$cuser = new User($this->db);
450					$cuser->fetch($obj->fk_user_author);
451					$this->user_creation = $cuser;
452				}
453
454				if ($obj->fk_user_valid)
455				{
456					$vuser = new User($this->db);
457					$vuser->fetch($obj->fk_user_valid);
458					$this->user_validation = $vuser;
459				}
460
461				if ($obj->fk_user_cloture)
462				{
463					$cluser = new User($this->db);
464					$cluser->fetch($obj->fk_user_cloture);
465					$this->user_cloture = $cluser;
466				}
467
468				$this->date_creation     = $this->db->jdate($obj->datec);
469				$this->date_modification = $this->db->jdate($obj->datem);
470				$this->date_validation   = $this->db->jdate($obj->datev);
471			}
472
473			$this->db->free($result);
474		} else {
475			dol_print_error($this->db);
476		}
477	}
478
479	/**
480	 * Initialise object with example values
481	 * Id must be 0 if object instance is a specimen
482	 *
483	 * @return void
484	 */
485	public function initAsSpecimen()
486	{
487		$this->initAsSpecimenCommon();
488	}
489}
490