Completed
Branch develop (b51004)
by
unknown
35:30
created

EmailCollector::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2017  Laurent Destailleur <[email protected]>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
/**
19
 * \file        emailcollector/class/emailcollector.class.php
20
 * \ingroup     emailcollector
21
 * \brief       This file is a CRUD class file for EmailCollector (Create/Read/Update/Delete)
22
 */
23
24
// Put here all includes required by your class file
25
require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
26
require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
27
require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
28
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
29
require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
30
31
32
/**
33
 * Class for EmailCollector
34
 */
35
class EmailCollector extends CommonObject
36
{
37
	/**
38
	 * @var string ID to identify managed object
39
	 */
40
	public $element = 'emailcollector';
41
	/**
42
	 * @var string Name of table without prefix where object is stored
43
	 */
44
	public $table_element = 'emailcollector_emailcollector';
45
	/**
46
	 * @var int  Does emailcollector support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
47
	 */
48
	public $ismultientitymanaged = 1;
49
	/**
50
	 * @var int  Does emailcollector support extrafields ? 0=No, 1=Yes
51
	 */
52
	public $isextrafieldmanaged = 0;
53
	/**
54
	 * @var string String with name of icon for emailcollector. Must be the part after the 'object_' into object_emailcollector.png
55
	 */
56
	public $picto = 'generic';
57
58
59
	/**
60
	 *  'type' if the field format.
61
	 *  'label' the translation key.
62
	 *  'enabled' is a condition when the field must be managed.
63
	 *  '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)
64
	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
65
	 *  'default' is a default value for creation (can still be replaced by the global setup of default values)
66
	 *  'index' if we want an index in database.
67
	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
68
	 *  'position' is the sort order of field.
69
	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
70
	 *  '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).
71
	 *  'css' is the CSS style to use on field. For example: 'maxwidth200'
72
	 *  'help' is a string visible as a tooltip on field
73
	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
74
	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
75
	 *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
76
	 */
77
78
	// BEGIN MODULEBUILDER PROPERTIES
79
	/**
80
	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
81
	 */
82
	public $fields=array(
83
	    'rowid'         => array('type'=>'integer', 'label'=>'TechnicalID','visible'=>2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1),
84
		'entity'        =>array('type'=>'integer',      'label'=>'Entity',           'enabled'=>1, 'visible'=>0,  'default'=>1, 'notnull'=>1,  'index'=>1, 'position'=>20),
85
		'ref'           =>array('type'=>'varchar(128)', 'label'=>'Ref',              'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'help'=>'Example: MyCollector1'),
86
		'label'         => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>'Example: My Email collector'),
87
		'description'   => array('type'=>'text', 'label'=>'Description', 'visible'=>-1, 'enabled'=>1, 'position'=>60, 'notnull'=>-1),
88
		'host'          => array('type'=>'varchar(255)', 'label'=>'EMailHost', 'visible'=>1, 'enabled'=>1, 'position'=>100, 'notnull'=>1, 'searchall'=>1, 'comment'=>"IMAP server", 'help'=>'Example: imap.gmail.com'),
89
		'user'          => array('type'=>'varchar(128)', 'label'=>'Login', 'visible'=>1, 'enabled'=>1, 'position'=>101, 'notnull'=>1, 'index'=>1, 'comment'=>"IMAP login", 'help'=>'Example: [email protected]'),
90
		'password'      => array('type'=>'password', 'label'=>'Password', 'visible'=>-1, 'enabled'=>1, 'position'=>102, 'notnull'=>1, 'comment'=>"IMAP password"),
91
		'source_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxSourceDirectory', 'visible'=>-1, 'enabled'=>1, 'position'=>103, 'notnull'=>1, 'default' => 'Inbox', 'help'=>'Example: INBOX'),
92
		//'filter'		=> array('type'=>'text', 'label'=>'Filter', 'visible'=>1, 'enabled'=>1, 'position'=>105),
93
		//'actiontodo'	=> array('type'=>'varchar(255)', 'label'=>'ActionToDo', 'visible'=>1, 'enabled'=>1, 'position'=>106),
94
		'target_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxTargetDirectory', 'visible'=>1, 'enabled'=>1, 'position'=>110, 'notnull'=>0, 'comment'=>"Where to store messages once processed"),
95
		'datelastresult' => array('type'=>'datetime', 'label'=>'DateLastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>121, 'notnull'=>-1,),
96
		'codelastresult' => array('type'=>'varchar(16)', 'label'=>'CodeLastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>122, 'notnull'=>-1,),
97
		'lastresult'    => array('type'=>'varchar(255)', 'label'=>'LastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>123, 'notnull'=>-1,),
98
		'note_public'   => array('type'=>'html', 'label'=>'NotePublic', 'visible'=>0, 'enabled'=>1, 'position'=>61, 'notnull'=>-1,),
99
		'note_private'  => array('type'=>'html', 'label'=>'NotePrivate', 'visible'=>0, 'enabled'=>1, 'position'=>62, 'notnull'=>-1,),
100
		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
101
		'tms'           => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1,),
102
		//'date_validation'    =>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'position'=>502),
103
		'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'visible'=>-2, 'enabled'=>1, 'position'=>510, 'notnull'=>1,),
104
		'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'visible'=>-2, 'enabled'=>1, 'position'=>511, 'notnull'=>-1,),
105
		//'fk_user_valid' =>array('type'=>'integer',      'label'=>'UserValidation',        'enabled'=>1, 'visible'=>-1, 'position'=>512),
106
		'import_key'    => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-2, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1,),
107
		'status'        => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Inactive', '1'=>'Active'))
108
	);
109
110
111
	/**
112
	 * @var int ID
113
	 */
114
	public $rowid;
115
116
	/**
117
	 * @var string Ref
118
	 */
119
	public $ref;
120
121
	/**
122
	 * @var int Entity
123
	 */
124
	public $entity;
125
126
	/**
127
	 * @var string label
128
	 */
129
	public $label;
130
131
132
	/**
133
	 * @var int Status
134
	 */
135
	public $status;
136
137
	public $date_creation;
138
	public $tms;
139
140
	/**
141
	 * @var int ID
142
	 */
143
	public $fk_user_creat;
144
145
	/**
146
	 * @var int ID
147
	 */
148
	public $fk_user_modif;
149
150
	public $import_key;
151
152
153
	public $host;
154
	public $user;
155
	public $password;
156
	public $source_directory;
157
    public $target_directory;
158
    public $datelastresult;
159
	public $lastresult;
160
	// END MODULEBUILDER PROPERTIES
161
162
	public $filters;
163
	public $actions;
164
165
166
	/**
167
	 * Constructor
168
	 *
169
	 * @param DoliDb $db Database handler
170
	 */
171
	public function __construct(DoliDB $db)
172
	{
173
		global $conf, $langs, $user;
174
175
		$this->db = $db;
176
177
		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible']=0;
178
		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled']=0;
179
180
		// Unset fields that are disabled
181
		foreach($this->fields as $key => $val)
182
		{
183
			if (isset($val['enabled']) && empty($val['enabled']))
184
			{
185
				unset($this->fields[$key]);
186
			}
187
		}
188
189
		// Translate some data of arrayofkeyval
190
		foreach($this->fields as $key => $val)
191
		{
192
			if (is_array($this->fields['status']['arrayofkeyval']))
193
			{
194
				foreach($this->fields['status']['arrayofkeyval'] as $key2 => $val2)
195
				{
196
					$this->fields['status']['arrayofkeyval'][$key2]=$langs->trans($val2);
197
				}
198
			}
199
		}
200
	}
201
202
	/**
203
	 * Create object into database
204
	 *
205
	 * @param  User $user      User that creates
206
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
207
	 * @return int             <0 if KO, Id of created object if OK
208
	 */
209
	public function create(User $user, $notrigger = false)
210
	{
211
		return $this->createCommon($user, $notrigger);
212
	}
213
214
	/**
215
	 * Clone and object into another one
216
	 *
217
	 * @param  	User 	$user      	User that creates
218
	 * @param  	int 	$fromid     Id of object to clone
219
	 * @return 	mixed 				New object created, <0 if KO
220
	 */
221
	public function createFromClone(User $user, $fromid)
222
	{
223
		global $langs, $hookmanager, $extrafields;
224
		$error = 0;
225
226
	    dol_syslog(__METHOD__, LOG_DEBUG);
227
228
	    $object = new self($this->db);
229
230
	    $this->db->begin();
231
232
	    // Load source object
233
	    $object->fetchCommon($fromid);
234
	    // Reset some properties
235
	    unset($object->id);
236
	    unset($object->fk_user_creat);
237
	    unset($object->import_key);
238
239
	    // Clear fields
240
	    $object->ref = "copy_of_".$object->ref;
241
	    $object->title = $langs->trans("CopyOf")." ".$object->title;
242
	    // ...
243
	    // Clear extrafields that are unique
244
	    if (is_array($object->array_options) && count($object->array_options) > 0)
245
	    {
246
	    	$extrafields->fetch_name_optionals_label($this->element);
247
	    	foreach($object->array_options as $key => $option)
248
	    	{
249
	    		$shortkey = preg_replace('/options_/', '', $key);
250
	    		if (! empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
251
	    		{
252
	    			//var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
253
	    			unset($object->array_options[$key]);
254
	    		}
255
	    	}
256
	    }
257
258
	    // Create clone
259
		$object->context['createfromclone'] = 'createfromclone';
260
	    $result = $object->createCommon($user);
261
	    if ($result < 0) {
262
	        $error++;
263
	        $this->error = $object->error;
264
	        $this->errors = $object->errors;
265
	    }
266
267
	    // End
268
	    if (!$error) {
269
	        $this->db->commit();
270
	        return $object;
271
	    } else {
272
	        $this->db->rollback();
273
	        return -1;
274
	    }
275
	}
276
277
	/**
278
	 * Load object in memory from the database
279
	 *
280
	 * @param int    $id   Id object
281
	 * @param string $ref  Ref
282
	 * @return int         <0 if KO, 0 if not found, >0 if OK
283
	 */
284
	public function fetch($id, $ref = null)
285
	{
286
		$result = $this->fetchCommon($id, $ref);
287
		//if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
288
		return $result;
289
	}
290
291
	/**
292
	 * Load object lines in memory from the database
293
	 *
294
	 * @return int         <0 if KO, 0 if not found, >0 if OK
295
	 */
296
	/*public function fetchLines()
297
	{
298
		$this->lines=array();
299
300
		// Load lines with object EmailCollectorLine
301
302
		return count($this->lines)?1:0;
303
	}*/
304
305
	/**
306
	 * Fetch all account and load objects into an array
307
	 *
308
	 * @param   User    $user           User
309
	 * @param   int     $activeOnly     filter if active
310
	 * @param   string  $sortfield      field for sorting
311
	 * @param   string  $sortorder      sorting order
312
	 * @param   int     $limit          sort limit
313
	 * @param   int     $page           page to start on
314
	 * @return  array   Array with key => EmailCollector object
315
	 */
316
	public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0)
317
    {
318
		global $langs;
319
320
		$obj_ret = array();
321
322
        $socid = $user->societe_id ? $user->societe_id : '';
323
324
		$sql = "SELECT s.rowid";
325
        $sql.= " FROM ".MAIN_DB_PREFIX."emailcollector_emailcollector as s";
326
        $sql.= ' WHERE s.entity IN ('.getEntity('emailcollector').')';
327
        if ($activeOnly) {
328
            $sql.= " AND s.status = 1";
329
        }
330
        $sql.= $this->db->order($sortfield, $sortorder);
331
        if ($limit) {
332
            if ($page < 0) {
333
                $page = 0;
334
            }
335
            $offset = $limit * $page;
336
337
            $sql.= $this->db->plimit($limit + 1, $offset);
338
        }
339
340
        $result = $this->db->query($sql);
341
        if ($result) {
342
            $num = $this->db->num_rows($result);
343
            while ($i < $num)
0 ignored issues
show
Bug introduced by
The variable $i does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
344
            {
345
                $obj = $this->db->fetch_object($result);
346
                $emailcollector_static = new EmailCollector($this->db);
347
                if ($emailcollector_static->fetch($obj->rowid)) {
348
                    $obj_ret[] = $emailcollector_static;
349
                }
350
                $i++;
351
            }
352
        } else {
353
        	$this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list';
354
            dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
355
            $ret = -1;
356
        }
357
        if (! count($obj_ret)) {
358
        	dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
359
        }
360
361
        return $obj_ret;
362
	}
363
364
	/**
365
	 * Update object into database
366
	 *
367
	 * @param  User $user      User that modifies
368
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
369
	 * @return int             <0 if KO, >0 if OK
370
	 */
371
	public function update(User $user, $notrigger = false)
372
	{
373
		return $this->updateCommon($user, $notrigger);
374
	}
375
376
	/**
377
	 * Delete object in database
378
	 *
379
	 * @param User $user       User that deletes
380
	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
381
	 * @return int             <0 if KO, >0 if OK
382
	 */
383
	public function delete(User $user, $notrigger = false)
384
	{
385
		return $this->deleteCommon($user, $notrigger);
386
	}
387
388
	/**
389
	 *  Return a link to the object card (with optionaly the picto)
390
	 *
391
	 *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
392
	 *	@param	string	$option						On what the link point to ('nolink', ...)
393
     *  @param	int  	$notooltip					1=Disable tooltip
394
     *  @param  string  $morecss            		Add more css on link
395
     *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
396
	 *	@return	string								String with URL
397
	 */
398
	function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
399
	{
400
		global $db, $conf, $langs, $hookmanager;
401
        global $dolibarr_main_authentication, $dolibarr_main_demo;
402
        global $menumanager;
403
404
        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
405
406
        $result = '';
407
        $companylink = '';
408
409
        $label = '<u>' . $langs->trans("EmailCollector") . '</u>';
410
        $label.= '<br>';
411
        $label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
412
413
        $url = dol_buildpath('/admin/emailcollector_card.php', 1).'?id='.$this->id;
414
415
        if ($option != 'nolink')
416
        {
417
	        // Add param to save lastsearch_values or not
418
	        $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
419
	        if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
420
                $add_save_lastsearch_values=1;
421
            }
422
	        if ($add_save_lastsearch_values) {
423
                $url.='&save_lastsearch_values=1';
424
            }
425
        }
426
427
        $linkclose='';
428
        if (empty($notooltip))
429
        {
430
            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
431
            {
432
                $label=$langs->trans("ShowEmailCollector");
433
                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
434
            }
435
            $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"';
436
            $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
437
438
            /*
439
             $hookmanager->initHooks(array('myobjectdao'));
440
             $parameters=array('id'=>$this->id);
441
             $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
442
             if ($reshook > 0) $linkclose = $hookmanager->resPrint;
443
             */
444
        }
445
        else $linkclose = ($morecss?' class="'.$morecss.'"':'');
446
447
		$linkstart = '<a href="'.$url.'"';
448
		$linkstart.=$linkclose.'>';
449
		$linkend='</a>';
450
451
		$result .= $linkstart;
452
		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);
453
		if ($withpicto != 2) $result.= $this->ref;
454
		$result .= $linkend;
455
		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
456
457
		global $action,$hookmanager;
458
		$hookmanager->initHooks(array('emailcollectordao'));
459
		$parameters=array('id'=>$this->id, 'getnomurl'=>$result);
460
		$reshook=$hookmanager->executeHooks('getNomUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
461
		if ($reshook > 0) $result = $hookmanager->resPrint;
462
		else $result .= $hookmanager->resPrint;
463
464
		return $result;
465
	}
466
467
	/**
468
	 *  Return label of the status
469
	 *
470
	 *  @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
471
	 *  @return	string 			       Label of status
472
	 */
473
	public function getLibStatut($mode=0)
474
	{
475
		return $this->LibStatut($this->status, $mode);
476
	}
477
478
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
479
	/**
480
	 *  Return the status
481
	 *
482
	 *  @param	int		$status        Id status
483
	 *  @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
484
	 *  @return string 			       Label of status
485
	 */
486
	public function LibStatut($status, $mode=0)
487
	{
488
		// phpcs:enable
489
		if (empty($this->labelstatus))
490
		{
491
			global $langs;
492
			//$langs->load("mymodule");
493
			$this->labelstatus[1] = $langs->trans('Enabled');
494
			$this->labelstatus[0] = $langs->trans('Disabled');
495
		}
496
497
		if ($mode == 0)
498
		{
499
			return $this->labelstatus[$status];
500
		}
501
		elseif ($mode == 1)
502
		{
503
			return $this->labelstatus[$status];
504
		}
505
		elseif ($mode == 2)
506
		{
507
			if ($status == 1) return img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
508
			elseif ($status == 0) return img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
509
		}
510
		elseif ($mode == 3)
511
		{
512
			if ($status == 1) return img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle');
513
			elseif ($status == 0) return img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle');
514
		}
515
		elseif ($mode == 4)
516
		{
517
			if ($status == 1) return img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
518
			elseif ($status == 0) return img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
519
		}
520
		elseif ($mode == 5)
521
		{
522
			if ($status == 1) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle');
523
			elseif ($status == 0) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle');
524
		}
525
		elseif ($mode == 6)
526
		{
527
			if ($status == 1) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle');
528
			elseif ($status == 0) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle');
529
		}
530
	}
531
532
	/**
533
	 *	Charge les informations d'ordre info dans l'objet commande
534
	 *
535
	 *	@param  int		$id       Id of order
536
	 *	@return	void
537
	 */
538
	public function info($id)
539
	{
540
		$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
541
		$sql.= ' fk_user_creat, fk_user_modif';
542
		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
543
		$sql.= ' WHERE t.rowid = '.$id;
544
		$result=$this->db->query($sql);
545
		if ($result)
546
		{
547
			if ($this->db->num_rows($result))
548
			{
549
				$obj = $this->db->fetch_object($result);
550
				$this->id = $obj->rowid;
551
				if ($obj->fk_user_author)
552
				{
553
					$cuser = new User($this->db);
554
					$cuser->fetch($obj->fk_user_author);
555
					$this->user_creation   = $cuser;
556
				}
557
558
				if ($obj->fk_user_valid)
559
				{
560
					$vuser = new User($this->db);
561
					$vuser->fetch($obj->fk_user_valid);
562
					$this->user_validation = $vuser;
563
				}
564
565
				if ($obj->fk_user_cloture)
566
				{
567
					$cluser = new User($this->db);
568
					$cluser->fetch($obj->fk_user_cloture);
569
					$this->user_cloture   = $cluser;
570
				}
571
572
				$this->date_creation     = $this->db->jdate($obj->datec);
573
				$this->date_modification = $this->db->jdate($obj->datem);
574
				$this->date_validation   = $this->db->jdate($obj->datev);
575
			}
576
577
			$this->db->free($result);
578
		}
579
		else
580
		{
581
			dol_print_error($this->db);
582
		}
583
	}
584
585
	/**
586
	 * Initialise object with example values
587
	 * Id must be 0 if object instance is a specimen
588
	 *
589
	 * @return void
590
	 */
591
	public function initAsSpecimen()
592
	{
593
		$this->initAsSpecimenCommon();
594
	}
595
596
	/**
597
	 * Fetch filters
598
	 *
599
	 * @return 	int		<0 if KO, >0 if OK
600
	 */
601
	public function fetchFilters()
602
	{
603
		$this->filters = array();
604
605
		$sql='SELECT rowid, type, rulevalue, status FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectorfilter WHERE fk_emailcollector = '.$this->id;
606
607
		$resql = $this->db->query($sql);
608
		if ($resql)
609
		{
610
			$num=$this->db->num_rows($resql);
611
			$i = 0;
612
			while($i < $num)
613
			{
614
				$obj=$this->db->fetch_object($resql);
615
				$this->filters[$obj->rowid]=array('id'=>$obj->rowid, 'type'=>$obj->type, 'rulevalue'=>$obj->rulevalue, 'status'=>$obj->status);
616
				$i++;
617
			}
618
			$this->db->free($resql);
619
		}
620
		else dol_print_error($this->db);
621
622
		return 1;
623
	}
624
625
	/**
626
	 * Fetch actions
627
	 *
628
	 * @return 	int		<0 if KO, >0 if OK
629
	 */
630
	public function fetchActions()
631
	{
632
		$this->actions = array();
633
634
		$sql='SELECT rowid, type, actionparam, status FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectoraction WHERE fk_emailcollector = '.$this->id;
635
636
		$resql = $this->db->query($sql);
637
		if ($resql)
638
		{
639
			$num=$this->db->num_rows($resql);
640
			$i = 0;
641
			while($i < $num)
642
			{
643
				$obj=$this->db->fetch_object($resql);
644
				$this->actions[$obj->rowid]=array('id'=>$obj->rowid, 'type'=>$obj->type, 'actionparam'=>$obj->actionparam, 'status'=>$obj->status);
645
				$i++;
646
			}
647
			$this->db->free($resql);
648
		}
649
		else dol_print_error($this->db);
650
	}
651
652
653
	/**
654
	 * Return the connectstring to use with IMAP connection function
655
	 *
656
	 * @return string
657
	 */
658
	function getConnectStringIMAP()
659
	{
660
		// Connect to IMAP
661
		$flags ='/service=imap';		// IMAP
662
		$flags.='/ssl';					// '/tls'
663
		$flags.='/novalidate-cert';
664
		//$flags.='/readonly';
665
		//$flags.='/debug';
666
667
		$connectstringserver = '{'.$this->host.':993'.$flags.'}';
668
669
		return $connectstringserver;
670
	}
671
672
	/**
673
	 * Action executed by scheduler
674
	 * CAN BE A CRON TASK. In such a case, paramerts come from the schedule job setup field 'Parameters'
675
	 *
676
	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
677
	 */
678
	public function doCollect()
679
	{
680
		global $user;
681
682
		$nberror = 0;
683
684
		$arrayofcollectors = $this->fetchAll($user, 1);
685
686
		// Loop on each collector
687
		foreach($arrayofcollectors as $emailcollector)
688
		{
689
			$result = $emailcollector->doCollectOneCollector();
690
			dol_syslog("doCollect result = ".$result." for emailcollector->id = ".$emailcollector->id);
691
692
			$this->error.='EmailCollector ID '.$emailcollector->id.':'.$emailcollector->error.'<br>';
693
			if (! empty($emailcollector->errors)) $this->error.=join('<br>', $emailcollector->errors);
694
			$this->output.='EmailCollector ID '.$emailcollector->id.': '.$emailcollector->output.'<br>';
695
		}
696
697
		return $nberror;
698
	}
699
700
	/**
701
	 * overwitePropertiesOfObject
702
	 *
703
	 * @return	int		0=OK, Nb of error if error
704
	 */
705
	private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject)
706
	{
707
		$errorforthisaction = 0;
708
709
		// Overwrite values with values extracted from source email
710
		// $this->actionparam = 'opportunity_status=123;abc=REGEX:BODY:....'
711
		$arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '=');
712
		foreach($arrayvaluetouse as $propertytooverwrite => $valueforproperty)
713
		{
714
			$tmpclass=''; $tmpproperty='';
715
			$tmparray=explode('.', $propertytooverwrite);
716
			if (count($tmparray) == 2)
717
			{
718
				$tmpclass=$tmparray[0];
719
				$tmpproperty=$tmparray[1];
720
			}
721
			else
722
			{
723
				$tmpproperty=$tmparray[0];
724
			}
725
			if ($tmpclass && ($tmpclass != $object->element)) continue;	// Property is for another type of object
726
727
			if (property_exists($object, $tmpproperty))
728
			{
729
				$sourcestring='';
730
				$sourcefield='';
731
				$regexstring='';
732
				$transformationstring='';
733
				$regforregex=array();
734
				if (preg_match('/^REGEX:([a-zA-Z0-9]+):(.*):([^:])$/', $valueforproperty, $regforregex))
735
				{
736
					$sourcefield=$regforregex[0];
737
					$regexstring=$regforregex[1];
738
					$transofrmationstring=$regforregex[2];
739
				}
740
				elseif (preg_match('/^REGEX:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex))
741
				{
742
					$sourcefield=$regforregex[0];
743
					$regexstring=$regforregex[1];
744
				}
745
746
				if (! empty($sourcestring) && ! empty($regexstring))
747
				{
748
					if (strtolower($sourcefield) == 'body') $sourcestring=$messagetext;
749
					elseif (strtolower($sourcefield) == 'subject') $sourcestring=$subject;
750
751
					$regforval=array();
752
					if (preg_match('/'.preg_quote($regexstring, '/').'/', $sourcestring, $regforval))
753
					{
754
						// Overwrite param $tmpproperty
755
						$object->$tmpproperty = $regforval[0];
756
					}
757
					else
758
					{
759
						// Nothing can be done for this param
760
					}
761
				}
762
				elseif (preg_match('/^VALUE:(.*)$/', $valueforproperty, $reg))
763
				{
764
					$object->$tmpproperty = $reg[0];
765
				}
766
				else
767
				{
768
					$errorforthisaction++;
769
					$this->error = 'Bad syntax for description of action parameters: '.$actionparam;
770
					$this->errors[] = $this->error;
771
				}
772
			}
773
		}
774
775
		return $errorforthisaction;
776
	}
777
778
	/**
779
	 * Execute collect for current collector loaded previously with fetch.
780
	 *
781
	 * @return	int			<0 if KO, >0 if OK
782
	 */
783
	public function doCollectOneCollector()
784
	{
785
		global $conf, $langs, $user;
786
787
		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
788
789
		require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
790
791
		dol_syslog("EmailCollector::doCollectOneCollector start", LOG_DEBUG);
792
793
		$langs->loadLangs(array("project", "companies", "errors"));
794
795
		$error = 0;
796
		$this->output = '';
797
		$this->error='';
798
799
		$now = dol_now();
800
801
		if (empty($this->host))
802
		{
803
			$this->error=$langs->trans('ErrorFieldRequired', 'EMailHost');
804
			return -1;
805
		}
806
		if (empty($this->user))
807
		{
808
			$this->error=$langs->trans('ErrorFieldRequired', 'Login');
809
			return -1;
810
		}
811
		if (empty($this->source_directory))
812
		{
813
			$this->error=$langs->trans('ErrorFieldRequired', 'MailboxSourceDirectory');
814
			return -1;
815
		}
816
		if (! function_exists('imap_open'))
817
		{
818
			$this->error='IMAP function not enabled on your PHP';
819
			return -2;
820
		}
821
822
		$this->fetchFilters();
823
		$this->fetchActions();
824
825
		$sourcedir = $this->source_directory;
826
		$targetdir = ($this->target_directory ? $this->target_directory : '');			// Can be '[Gmail]/Trash' or 'mytag'
827
828
		$connectstringserver = $this->getConnectStringIMAP();
829
		$connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
830
		$connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
831
832
		$connection = imap_open($connectstringsource, $this->user, $this->password);
833
		if (! $connection)
834
		{
835
			$this->error = 'Failed to open IMAP connection '.$connectstringsource;
836
			return -3;
837
		}
838
839
		//$search='ALL';
840
		$search='UNDELETED';
841
		foreach($this->filters as $rule)
842
		{
843
			if (empty($rule['status'])) continue;
844
845
			if ($rule['type'] == 'to')      $search.=($search?' ':'').'TO "'.str_replace('"', '', $rule['rulevalue']).'"';
846
			if ($rule['type'] == 'bcc')     $search.=($search?' ':'').'BCC';
847
			if ($rule['type'] == 'cc')      $search.=($search?' ':'').'CC';
848
			if ($rule['type'] == 'from')    $search.=($search?' ':'').'FROM "'.str_replace('"', '', $rule['rulevalue']).'"';
849
			if ($rule['type'] == 'subject') $search.=($search?' ':'').'SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
850
			if ($rule['type'] == 'body')    $search.=($search?' ':'').'BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
851
			if ($rule['type'] == 'seen')    $search.=($search?' ':'').'SEEN';
852
			if ($rule['type'] == 'unseen')  $search.=($search?' ':'').'UNSEEN';
853
		}
854
855
		if (empty($targetdir))	// Use last date as filter if there is no targetdir defined.
856
		{
857
			$fromdate=0;
858
			if ($this->datelastresult && $this->codelastresult == 'OK') $fromdate = $this->datelastresult;
859
			if ($fromdate > 0) $search.=($search?' ':'').'SINCE '.dol_print_date($fromdate - 1,'dayhourrfc');
860
		}
861
		dol_syslog("IMAP search string = ".$search);
862
		//var_dump($search);
863
864
		$nbemailprocessed=0;
865
		$nbemailok=0;
866
		$nbactiondone=0;
867
868
		// Scan IMAP inbox
869
		$arrayofemail= imap_search($connection, $search);
870
		//var_dump($arrayofemail);exit;
871
872
		// Loop on each email found
873
		if (! empty($arrayofemail) && count($arrayofemail) > 0)
874
		{
875
			foreach($arrayofemail as $imapemail)
876
			{
877
				if ($nbemailprocessed > 100) break;			// Do not process more than 100 email per launch
878
879
				$thirdpartystatic=new Societe($this->db);
880
				$contactstatic=new Contact($this->db);
881
				$projectstatic=new Project($this->db);
882
883
				$nbactiondoneforemail = 0;
884
				$errorforemail = 0;
885
				$errorforactions = 0;
886
				$thirdpartyfoundby = '';
887
				$contactfoundby = '';
888
				$projectfoundby = '';
889
890
				$this->db->begin();
891
892
				$overview = imap_fetch_overview($connection, $imapemail, 0);
893
				$header = imap_fetchheader($connection, $imapemail, 0);
894
				//$message = imap_body($connection, $imapemail, 0);
895
				$structure = imap_fetchstructure($connection, $imapemail, 0);
896
				$partplain = $parthtml = -1;
897
				// Loop to get part html and plain
898
				foreach($structure->parts as $key => $part)
899
				{
900
					if ($part->subtype == 'HTML') $parthtml=$key;
901
					if ($part->subtype == 'PLAIN') $partplain=$key;
902
				}
903
904
				$matches=array();
905
				preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
906
				$headers = array_combine($matches[1], $matches[2]);
907
				//var_dump($headers);
908
909
				$messagetext = imap_fetchbody($connection, $imapemail, ($parthtml >= 0 ? $parthtml : ($partplain >= 0 ? $partplain : 0)));
910
911
				//var_dump($overview);
912
				//var_dump($header);
913
				//var_dump($message);
914
				//var_dump($messagetext);
915
				$fromstring=$overview[0]->from;
916
				$sender=$overview[0]->sender;
917
				$to=$overview[0]->to;
918
				$sendtocc=$overview[0]->cc;
919
				$sendtobcc=$overview[0]->bcc;
920
				$date=$overview[0]->udate;
921
				$msgid=str_replace(array('<','>'), '', $overview[0]->message_id);
922
				$subject=$overview[0]->subject;
923
				//var_dump($msgid);exit;
924
925
				$reg=array();
926
				if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg))
927
				{
928
					$from=$reg[1];
929
					$fromtext=$reg[0];
930
				}
931
				else
932
				{
933
					$from = $fromstring;
934
					$fromtext='';
935
				}
936
				$fk_element_id = 0; $fk_element_type = '';
937
938
				$contactid = 0; $thirdpartyid = 0; $projectid = 0;
939
940
				// Analyze TrackId
941
				$trackid = '';
942
				$reg=array();
943
				if (! empty($headers['X-Dolibarr-TrackId']) && preg_match('/:\s*([a-z]+)([0-9]+)$/', $headers['X-Dolibarr-TrackId'], $reg))
944
				{
945
					$trackid = $reg[0].$reg[1];
946
947
					$objectid = 0;
948
					$objectemail = null;
949
					if ($reg[0] == 'inv')
950
					{
951
						$objectid = $reg[1];
952
						$objectemail = new Facture($this->db);
953
					}
954
					if ($reg[0] == 'proj')
955
					{
956
						$objectid = $reg[1];
957
						$objectemail = new Project($this->db);
958
					}
959
					if ($reg[0] == 'con')
960
					{
961
						$objectid = $reg[1];
962
						$objectemail = new Contact($this->db);
963
					}
964
					if ($reg[0] == 'thi')
965
					{
966
						$objectid = $reg[1];
967
						$objectemail = new Societe($this->db);
968
					}
969
					if ($reg[0] == 'use')
970
					{
971
						$objectid = $reg[1];
972
						$objectemail = new User($this->db);
973
					}
974
975
					$result = $objectemail->fetch($objectid);
976
					if ($result > 0)
977
					{
978
						$fk_element_id = $objectemail->id;
979
						$fk_element_type = $objectemail->element;
980
						// Fix fk_element_type
981
						if ($fk_element_type == 'facture') $fk_element_type = 'invoice';
982
983
						$thirdpartyid = $objectemail->fk_soc;
984
						$contactid = $objectemail->fk_socpeople;
985
						$projectid = isset($objectemail->fk_project)?$objectemail->fk_project:$objectemail->fk_projet;
986
					}
987
988
					// Project
989
					if ($projectid > 0)
990
					{
991
						$result = $projectstatic->fetch($projectid);
992
						if ($result <= 0) $projectstatic->id = 0;
993
						else
994
						{
995
							$projectid = $projectstatic->id;
996
							$projectfoundby = 'trackid ('.$trackid.')';
997
							if (empty($contactid)) $contactid = $projectstatic->fk_contact;
998
							if (empty($thirdpartyid)) $thirdpartyid = $projectstatic->fk_soc;
999
						}
1000
					}
1001
					// Contact
1002
					if ($contactid > 0)
1003
					{
1004
						$result = $contactstatic->fetch($contactid);
1005
						if ($result <= 0) $contactstatic->id = 0;
1006
						else
1007
						{
1008
							$contactid = $contactstatic->id;
1009
							$contactfoundby = 'trackid ('.$trackid.')';
1010
							if (empty($thirdpartyid)) $thirdpartyid = $contactstatic->fk_soc;
1011
						}
1012
					}
1013
					// Thirdparty
1014
					if ($thirdpartyid > 0)
1015
					{
1016
						$result = $thirdpartystatic->fetch($thirdpartyid);
1017
						if ($result <= 0) $thirdpartystatic->id = 0;
1018
						else
1019
						{
1020
							$thirdpartyid = $thirdpartystatic->id;
1021
							$thirdpartyfoundby = 'trackid ('.$trackid.')';
1022
						}
1023
					}
1024
				}
1025
1026
				if (empty($contactid))		// Try to find contact using email
1027
				{
1028
					$result = $contactstatic->fetch(0, null, '', $from);
1029
					if ($result > 0)
1030
					{
1031
						$contactid = $contactstatic->id;
1032
						$contactfoundby = 'email of contact ('.$from.')';
1033
						if ($contactstatic->fk_soc > 0)
1034
						{
1035
							$result = $thirdpartystatic->fetch($contactstatic->fk_soc);
1036
							if ($result > 0)
1037
							{
1038
								$thirdpartyid = $thirdpartystatic->id;
1039
								$thirdpartyfoundby = 'email of contact ('.$from.')';
1040
							}
1041
						}
1042
					}
1043
1044
				}
1045
1046
				if (empty($thirdpartyid))		// Try to find thirdparty using email
1047
				{
1048
					$result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from);
1049
					if ($result > 0) $thirdpartyfoundby = 'email ('.$from.')';
1050
				}
1051
1052
1053
1054
				// Do operations
1055
				foreach($this->actions as $operation)
1056
				{
1057
					if ($errorforactions) break;
1058
					if (empty($operation['status'])) continue;
1059
1060
					// Make Operation
1061
1062
					// Search and create thirdparty
1063
					if ($operation['type'] == 'searchandcreatethirdparty')
1064
					{
1065
1066
1067
1068
1069
					}
1070
					// Create event
1071
					elseif ($operation['type'] == 'recordevent')
1072
					{
1073
						$actioncode = 'EMAIL_IN';
1074
1075
						// Insert record of emails sent
1076
						$actioncomm = new ActionComm($this->db);
1077
1078
						$actioncomm->type_code   = 'AC_OTH_AUTO';		// Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
1079
						$actioncomm->code        = 'AC_'.$actioncode;
1080
						$actioncomm->label       = $langs->trans("EmailReceived").' - '.$langs->trans("From").' '.$from;
1081
						$actioncomm->note        = $messagetext;
1082
						$actioncomm->fk_project  = $projectstatic->id;
1083
						$actioncomm->datep       = $date;
1084
						$actioncomm->datef       = $date;
1085
						$actioncomm->percentage  = -1;   // Not applicable
1086
						$actioncomm->socid       = $thirdpartystatic->id;
1087
						$actioncomm->contactid   = $contactstatic->id;
1088
						$actioncomm->authorid    = $user->id;   // User saving action
1089
						$actioncomm->userownerid = $user->id;	// Owner of action
1090
						// Fields when action is an email (content should be added into note)
1091
						$actioncomm->email_msgid = $msgid;
1092
						$actioncomm->email_from  = $fromstring;
1093
						$actioncomm->email_sender= $sender;
1094
						$actioncomm->email_to    = $to;
1095
						$actioncomm->email_tocc  = $sendtocc;
1096
						$actioncomm->email_tobcc = $sendtobcc;
1097
						$actioncomm->email_subject = $subject;
1098
						$actioncomm->errors_to   = '';
1099
1100
						$actioncomm->fk_element  = $fk_element_id;
1101
						$actioncomm->elementtype = $fk_element_type;
1102
1103
						//$actioncomm->extraparams = $extraparams;
1104
1105
1106
						// Overwrite values with values extracted from source email
1107
						$errorforthisaction = $this->overwritePropertiesOfObject($actioncommn, $operation['actionparam'], $messagetext, $subject);
1108
1109
						if ($errorforthisaction)
1110
						{
1111
							$errorforactions++;
1112
						}
1113
						else
1114
						{
1115
							$result = $actioncomm->create($user);
1116
							if ($result <= 0)
1117
							{
1118
								$errorforactions++;
1119
								$this->errors = $actioncomm->errors;
1120
							}
1121
						}
1122
					}
1123
					// Create event
1124
					elseif ($operation['type'] == 'project')
1125
					{
1126
						$note_private = $langs->trans("ProjectCreatedByEmailCollector", $msgid);
1127
						$projecttocreate = new Project($this->db);
1128
						if ($thirdpartystatic->id > 0)
1129
						{
1130
							$projecttocreate->fk_soc = $thirdpartystatic->id;
1131
							if ($thirdpartyfoundby) $note_private .= ' - Third party found from '.$thirdpartyfoundby;
1132
						}
1133
						if ($contactstatic->id > 0)
1134
						{
1135
							$projecttocreate->contact_id = $contactstatic->id;
1136
							if ($contactfoundby) $note_private .= ' - Contact/address found from '.$contactfoundby;
1137
						}
1138
1139
						$id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid');
1140
						$percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent');
1141
1142
						$projecttocreate->title = $subject;
1143
						$projecttocreate->date_start = $now;
1144
						$projecttocreate->opp_status = $id_opp_status;
1145
						$projecttocreate->opp_percent = $percent_opp_status;
1146
						$projecttocreate->description = ($note_private?$note_private."\n":'').$messagetext;
1147
						$projecttocreate->note_private = $note_private;
1148
						$projecttocreate->entity = $conf->entity;
1149
1150
						// Get next project Ref
1151
						$defaultref='';
1152
						$modele = empty($conf->global->PROJECT_ADDON)?'mod_project_simple':$conf->global->PROJECT_ADDON;
1153
1154
						// Search template files
1155
						$file=''; $classname=''; $filefound=0;
1156
						$dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
1157
						foreach($dirmodels as $reldir)
1158
						{
1159
							$file=dol_buildpath($reldir."core/modules/project/".$modele.'.php',0);
1160
							if (file_exists($file))
1161
							{
1162
								$filefound=1;
1163
								$classname = $modele;
1164
								break;
1165
							}
1166
						}
1167
1168
						if ($filefound)
1169
						{
1170
							$result=dol_include_once($reldir."core/modules/project/".$modele.'.php');
0 ignored issues
show
Bug introduced by
The variable $reldir seems to be defined by a foreach iteration on line 1157. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
1171
							$modProject = new $classname;
1172
1173
							$defaultref = $modProject->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
1174
						}
1175
1176
						$projecttocreate->ref = $defaultref;
1177
1178
						// Overwrite values with values extracted from source email
1179
						$errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject);
1180
1181
						if ($errorforthisaction)
1182
						{
1183
							$errorforactions++;
1184
						}
1185
						else
1186
						{
1187
							if (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)
1188
							{
1189
								$errorforactions++;
1190
								$this->error = 'Failed to create project: Can\'t get a valid value for project Ref';
1191
							}
1192
							else
1193
							{
1194
								// Create project
1195
								$result = $projecttocreate->create($user);
1196
								if ($result <= 0)
1197
								{
1198
									$errorforactions++;
1199
									$this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error);
1200
									$this->errors = $projecttocreate->errors;
1201
								}
1202
							}
1203
						}
1204
					}
1205
1206
					if (! $errorforactions)
1207
					{
1208
						$nbactiondoneforemail++;
1209
					}
1210
				}
1211
1212
				// Error for email or not ?
1213
				if (! $errorforactions)
1214
				{
1215
					if ($targetdir)
1216
					{
1217
						dol_syslog("EmailCollector::doCollectOneCollector move message ".$imapemail." to ".$connectstringtarget, LOG_DEBUG);
1218
						$res = imap_mail_move($connection, $imapemail, $targetdir, 0);
1219
						if ($res == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1220
							$errorforemail++;
1221
							$this->error = imap_last_error();
1222
							$this->errors[] = $this->error;
1223
							dol_syslog(imap_last_error());
1224
						}
1225
					}
1226
					else
1227
					{
1228
						dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG);
1229
1230
					}
1231
				}
1232
				else
1233
				{
1234
					$errorforemail++;
1235
				}
1236
1237
				if (! $errorforemail)
1238
				{
1239
					$nbactiondone += $nbactiondoneforemail;
1240
					$nbemailok++;
1241
1242
					$this->db->commit();
1243
				}
1244
				else
1245
				{
1246
					$error++;
1247
1248
					$this->db->rollback();
1249
				}
1250
1251
				$nbemailprocessed++;
1252
1253
				unset($objectemail);
1254
				unset($projectstatic);
1255
				unset($thirdpartystatic);
1256
				unset($contactstatic);
1257
			}
1258
1259
			$output=$langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
1260
		}
1261
		else
1262
		{
1263
			$output=$langs->trans('NoNewEmailToProcess');
1264
		}
1265
1266
		imap_expunge($connection);	// To validate any move
1267
1268
		imap_close($connection);
1269
1270
		$this->datelastresult = $now;
1271
		$this->lastresult = $output;
1272
		if (! empty($this->errors)) $this->lastresult.= " - ".join(" - ", $this->errors);
1273
		$this->codelastresult = ($error ? 'KO' : 'OK');
1274
		$this->update($user);
1275
1276
		dol_syslog("EmailCollector::doCollectOneCollector end", LOG_DEBUG);
1277
1278
		return $error?-1:1;
1279
	}
1280
}
1281