| Total Complexity | 683 |
| Total Lines | 3819 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like EmailCollector often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use EmailCollector, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 63 | class EmailCollector extends CommonObject |
||
| 64 | { |
||
| 65 | /** |
||
| 66 | * @var string ID to identify managed object |
||
| 67 | */ |
||
| 68 | public $element = 'emailcollector'; |
||
| 69 | |||
| 70 | /** |
||
| 71 | * @var string Name of table without prefix where object is stored |
||
| 72 | */ |
||
| 73 | public $table_element = 'emailcollector_emailcollector'; |
||
| 74 | |||
| 75 | /** |
||
| 76 | * @var string String with name of icon for emailcollector. Must be the part after the 'object_' into object_emailcollector.png |
||
| 77 | */ |
||
| 78 | public $picto = 'email'; |
||
| 79 | |||
| 80 | /** |
||
| 81 | * @var string Field with ID of parent key if this field has a parent |
||
| 82 | */ |
||
| 83 | public $fk_element = 'fk_emailcollector'; |
||
| 84 | |||
| 85 | /** |
||
| 86 | * @var array<string, array<string>> List of child tables. To test if we can delete object. |
||
| 87 | */ |
||
| 88 | protected $childtables = array(); |
||
| 89 | |||
| 90 | /** |
||
| 91 | * @var string[] List of child tables. To know object to delete on cascade. |
||
| 92 | */ |
||
| 93 | protected $childtablesoncascade = array('emailcollector_emailcollectorfilter', 'emailcollector_emailcollectoraction'); |
||
| 94 | |||
| 95 | |||
| 96 | /** |
||
| 97 | * 'type' if the field format. |
||
| 98 | * 'label' the translation key. |
||
| 99 | * 'enabled' is a condition when the field must be managed. |
||
| 100 | * '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) |
||
| 101 | * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). |
||
| 102 | * 'default' is a default value for creation (can still be replaced by the global setup of default values) |
||
| 103 | * 'index' if we want an index in database. |
||
| 104 | * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...). |
||
| 105 | * 'position' is the sort order of field. |
||
| 106 | * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. |
||
| 107 | * '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). |
||
| 108 | * 'css' is the CSS style to use on field. For example: 'maxwidth200' |
||
| 109 | * 'help' is a string visible as a tooltip on field |
||
| 110 | * 'comment' is not used. You can store here any text of your choice. It is not used by application. |
||
| 111 | * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record |
||
| 112 | * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") |
||
| 113 | */ |
||
| 114 | |||
| 115 | // BEGIN MODULEBUILDER PROPERTIES |
||
| 116 | /** |
||
| 117 | * @var array<string,array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string}> Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. |
||
|
|
|||
| 118 | */ |
||
| 119 | public $fields = array( |
||
| 120 | 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'visible' => 2, 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'index' => 1), |
||
| 121 | 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'default' => 1, 'notnull' => 1, 'index' => 1, 'position' => 20), |
||
| 122 | 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1, 'help' => 'Example: MyCollector1', 'csslist' => 'tdoverflowmax200'), |
||
| 123 | 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'visible' => 1, 'enabled' => 1, 'position' => 30, 'notnull' => -1, 'searchall' => 1, 'help' => 'Example: My Email collector', 'csslist' => 'tdoverflowmax150', 'tdcss' => 'titlefieldmiddle'), |
||
| 124 | 'description' => array('type' => 'text', 'label' => 'Description', 'visible' => -1, 'enabled' => 1, 'position' => 60, 'notnull' => -1, 'cssview' => 'small', 'csslist' => 'small tdoverflowmax200'), |
||
| 125 | 'host' => array('type' => 'varchar(255)', 'label' => 'EMailHost', 'visible' => 1, 'enabled' => 1, 'position' => 90, 'notnull' => 1, 'searchall' => 1, 'comment' => "IMAP server", 'help' => 'Example: imap.gmail.com', 'csslist' => 'tdoverflowmax125'), |
||
| 126 | 'port' => array('type' => 'varchar(10)', 'label' => 'EMailHostPort', 'visible' => 1, 'enabled' => 1, 'position' => 91, 'notnull' => 1, 'searchall' => 0, 'comment' => "IMAP server port", 'help' => 'Example: 993', 'csslist' => 'tdoverflowmax50', 'default' => '993'), |
||
| 127 | 'imap_encryption' => array('type' => 'varchar(16)', 'label' => 'ImapEncryption', 'visible' => -1, 'enabled' => 1, 'position' => 92, 'searchall' => 0, 'comment' => "IMAP encryption", 'help' => 'ImapEncryptionHelp', 'arrayofkeyval' => array('ssl' => 'SSL', 'tls' => 'TLS', 'notls' => 'NOTLS'), 'default' => 'ssl'), |
||
| 128 | 'hostcharset' => array('type' => 'varchar(16)', 'label' => 'HostCharset', 'visible' => -1, 'enabled' => 1, 'position' => 93, 'notnull' => 0, 'searchall' => 0, 'comment' => "IMAP server charset", 'help' => 'Example: "UTF-8" (May be "US-ASCII" with some Office365)', 'default' => 'UTF-8'), |
||
| 129 | 'norsh' => array('type' => 'integer', 'label' => 'NoRSH', 'visible' => -1, 'enabled' => "!getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position' => 94, 'searchall' => 0, 'help' => 'NoRSHHelp', 'arrayofkeyval' => array(0 => 'No', 1 => 'Yes'), 'default' => 0), |
||
| 130 | 'acces_type' => array('type' => 'integer', 'label' => 'AuthenticationMethod', 'visible' => -1, 'enabled' => "getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position' => 101, 'notnull' => 1, 'index' => 1, 'comment' => "IMAP login type", 'arrayofkeyval' => array('0' => 'loginPassword', '1' => 'oauthToken'), 'default' => '0', 'help' => ''), |
||
| 131 | 'login' => array('type' => 'varchar(128)', 'label' => 'Login', 'visible' => -1, 'enabled' => 1, 'position' => 102, 'notnull' => -1, 'index' => 1, 'comment' => "IMAP login", 'help' => 'Example: [email protected]'), |
||
| 132 | 'password' => array('type' => 'password', 'label' => 'Password', 'visible' => -1, 'enabled' => "1", 'position' => 103, 'notnull' => -1, 'comment' => "IMAP password", 'help' => 'WithGMailYouCanCreateADedicatedPassword'), |
||
| 133 | 'oauth_service' => array('type' => 'varchar(128)', 'label' => 'oauthService', 'visible' => -1, 'enabled' => "getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position' => 104, 'notnull' => 0, 'index' => 1, 'comment' => "IMAP login oauthService", 'arrayofkeyval' => array(), 'help' => 'TokenMustHaveBeenCreated'), |
||
| 134 | 'source_directory' => array('type' => 'varchar(255)', 'label' => 'MailboxSourceDirectory', 'visible' => -1, 'enabled' => 1, 'position' => 109, 'notnull' => 1, 'default' => 'Inbox', 'csslist' => 'tdoverflowmax100', 'help' => 'Example: INBOX, [Gmail]/Spam, [Gmail]/Draft, [Gmail]/Brouillons, [Gmail]/Sent Mail, [Gmail]/Messages envoyés, ...'), |
||
| 135 | 'target_directory' => array('type' => 'varchar(255)', 'label' => 'MailboxTargetDirectory', 'visible' => 1, 'enabled' => 1, 'position' => 110, 'notnull' => 0, 'csslist' => 'tdoverflowmax100', 'help' => "EmailCollectorTargetDir"), |
||
| 136 | 'maxemailpercollect' => array('type' => 'integer', 'label' => 'MaxEmailCollectPerCollect', 'visible' => -1, 'enabled' => 1, 'position' => 111, 'default' => 50), |
||
| 137 | 'datelastresult' => array('type' => 'datetime', 'label' => 'DateLastCollectResult', 'visible' => 1, 'enabled' => '$action != "create" && $action != "edit"', 'position' => 121, 'notnull' => -1, 'csslist' => 'nowraponall'), |
||
| 138 | 'codelastresult' => array('type' => 'varchar(16)', 'label' => 'CodeLastResult', 'visible' => 1, 'enabled' => '$action != "create" && $action != "edit"', 'position' => 122, 'notnull' => -1,), |
||
| 139 | 'lastresult' => array('type' => 'varchar(255)', 'label' => 'LastResult', 'visible' => 1, 'enabled' => '$action != "create" && $action != "edit"', 'position' => 123, 'notnull' => -1, 'cssview' => 'small', 'csslist' => 'small tdoverflowmax200'), |
||
| 140 | 'datelastok' => array('type' => 'datetime', 'label' => 'DateLastcollectResultOk', 'visible' => 1, 'enabled' => '$action != "create"', 'position' => 125, 'notnull' => -1, 'csslist' => 'nowraponall'), |
||
| 141 | 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'visible' => 0, 'enabled' => 1, 'position' => 61, 'notnull' => -1,), |
||
| 142 | 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'visible' => 0, 'enabled' => 1, 'position' => 62, 'notnull' => -1,), |
||
| 143 | 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'visible' => -2, 'enabled' => 1, 'position' => 500, 'notnull' => 1,), |
||
| 144 | 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'visible' => -2, 'enabled' => 1, 'position' => 501, 'notnull' => 1,), |
||
| 145 | //'date_validation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), |
||
| 146 | 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'visible' => -2, 'enabled' => 1, 'position' => 510, 'notnull' => 1,), |
||
| 147 | 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'visible' => -2, 'enabled' => 1, 'position' => 511, 'notnull' => -1,), |
||
| 148 | //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), |
||
| 149 | 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'visible' => -2, 'enabled' => 1, 'position' => 1000, 'notnull' => -1,), |
||
| 150 | 'status' => array('type' => 'integer', 'label' => 'Status', 'visible' => 1, 'enabled' => 1, 'position' => 1000, 'notnull' => 1, 'default' => '0', 'index' => 1, 'arrayofkeyval' => array('0' => 'Inactive', '1' => 'Active')) |
||
| 151 | ); |
||
| 152 | |||
| 153 | |||
| 154 | /** |
||
| 155 | * @var int ID |
||
| 156 | */ |
||
| 157 | public $rowid; |
||
| 158 | |||
| 159 | /** |
||
| 160 | * @var string Ref |
||
| 161 | */ |
||
| 162 | public $ref; |
||
| 163 | |||
| 164 | /** |
||
| 165 | * @var int Entity |
||
| 166 | */ |
||
| 167 | public $entity; |
||
| 168 | |||
| 169 | /** |
||
| 170 | * @var string label |
||
| 171 | */ |
||
| 172 | public $label; |
||
| 173 | |||
| 174 | /** |
||
| 175 | * @var string description |
||
| 176 | */ |
||
| 177 | public $description; |
||
| 178 | |||
| 179 | /** |
||
| 180 | * @var int Status |
||
| 181 | */ |
||
| 182 | public $status; |
||
| 183 | |||
| 184 | /** |
||
| 185 | * @var integer|string date_creation |
||
| 186 | */ |
||
| 187 | public $date_creation; |
||
| 188 | |||
| 189 | /** |
||
| 190 | * @var int ID |
||
| 191 | */ |
||
| 192 | public $fk_user_creat; |
||
| 193 | |||
| 194 | /** |
||
| 195 | * @var int ID |
||
| 196 | */ |
||
| 197 | public $fk_user_modif; |
||
| 198 | |||
| 199 | /** |
||
| 200 | * @var string import key |
||
| 201 | */ |
||
| 202 | public $import_key; |
||
| 203 | |||
| 204 | public $host; |
||
| 205 | public $port; |
||
| 206 | public $hostcharset; |
||
| 207 | public $login; |
||
| 208 | public $password; |
||
| 209 | public $acces_type; |
||
| 210 | public $oauth_service; |
||
| 211 | public $imap_encryption; |
||
| 212 | public $norsh; |
||
| 213 | public $source_directory; |
||
| 214 | public $target_directory; |
||
| 215 | public $maxemailpercollect; |
||
| 216 | |||
| 217 | /** |
||
| 218 | * @var integer|string $datelastresult |
||
| 219 | */ |
||
| 220 | public $datelastresult; |
||
| 221 | |||
| 222 | public $codelastresult; |
||
| 223 | public $lastresult; |
||
| 224 | public $datelastok; |
||
| 225 | // END MODULEBUILDER PROPERTIES |
||
| 226 | |||
| 227 | public $filters; |
||
| 228 | public $actions; |
||
| 229 | |||
| 230 | public $debuginfo; |
||
| 231 | |||
| 232 | const STATUS_DISABLED = 0; |
||
| 233 | const STATUS_ENABLED = 1; |
||
| 234 | |||
| 235 | |||
| 236 | /** |
||
| 237 | * Constructor |
||
| 238 | * |
||
| 239 | * @param DoliDB $db Database handler |
||
| 240 | */ |
||
| 241 | public function __construct(DoliDB $db) |
||
| 242 | { |
||
| 243 | global $conf, $langs; |
||
| 244 | |||
| 245 | $this->db = $db; |
||
| 246 | |||
| 247 | $this->ismultientitymanaged = 1; |
||
| 248 | $this->isextrafieldmanaged = 0; |
||
| 249 | |||
| 250 | if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) { |
||
| 251 | $this->fields['rowid']['visible'] = 0; |
||
| 252 | } |
||
| 253 | if (!isModEnabled('multicompany') && isset($this->fields['entity'])) { |
||
| 254 | $this->fields['entity']['enabled'] = 0; |
||
| 255 | } |
||
| 256 | |||
| 257 | // List of oauth services |
||
| 258 | $oauthservices = array(); |
||
| 259 | |||
| 260 | foreach ($conf->global as $key => $val) { |
||
| 261 | if (!empty($val) && preg_match('/^OAUTH_.*_ID$/', $key)) { |
||
| 262 | $key = preg_replace('/^OAUTH_/', '', $key); |
||
| 263 | $key = preg_replace('/_ID$/', '', $key); |
||
| 264 | if (preg_match('/^.*-/', $key)) { |
||
| 265 | $name = preg_replace('/^.*-/', '', $key); |
||
| 266 | } else { |
||
| 267 | $name = $langs->trans("NoName"); |
||
| 268 | } |
||
| 269 | $provider = preg_replace('/-.*$/', '', $key); |
||
| 270 | $provider = ucfirst(strtolower($provider)); |
||
| 271 | |||
| 272 | $oauthservices[$key] = $name . " (" . $provider . ")"; |
||
| 273 | } |
||
| 274 | } |
||
| 275 | |||
| 276 | $this->fields['oauth_service']['arrayofkeyval'] = $oauthservices; |
||
| 277 | |||
| 278 | // Unset fields that are disabled |
||
| 279 | foreach ($this->fields as $key => $val) { |
||
| 280 | if (isset($val['enabled']) && empty($val['enabled'])) { |
||
| 281 | unset($this->fields[$key]); |
||
| 282 | } |
||
| 283 | } |
||
| 284 | |||
| 285 | // Translate some data of arrayofkeyval |
||
| 286 | foreach ($this->fields as $key => $val) { |
||
| 287 | if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { |
||
| 288 | foreach ($val['arrayofkeyval'] as $key2 => $val2) { |
||
| 289 | $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); |
||
| 290 | } |
||
| 291 | } |
||
| 292 | } |
||
| 293 | } |
||
| 294 | |||
| 295 | /** |
||
| 296 | * Create object into database |
||
| 297 | * |
||
| 298 | * @param User $user User that creates |
||
| 299 | * @param int $notrigger 0=launch triggers after, 1=disable triggers |
||
| 300 | * @return int Return integer <0 if KO, Id of created object if OK |
||
| 301 | */ |
||
| 302 | public function create(User $user, $notrigger = 0) |
||
| 303 | { |
||
| 304 | global $langs; |
||
| 305 | |||
| 306 | // Check parameters |
||
| 307 | if ($this->host && preg_match('/^http:/i', trim($this->host))) { |
||
| 308 | $langs->load("errors"); |
||
| 309 | $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host); |
||
| 310 | return -1; |
||
| 311 | } |
||
| 312 | |||
| 313 | include_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php'; |
||
| 314 | $this->password = dolEncrypt($this->password); |
||
| 315 | |||
| 316 | $id = $this->createCommon($user, $notrigger); |
||
| 317 | |||
| 318 | $this->password = dolDecrypt($this->password); |
||
| 319 | |||
| 320 | if (is_array($this->filters) && count($this->filters)) { |
||
| 321 | $emailcollectorfilter = new EmailCollectorFilter($this->db); |
||
| 322 | |||
| 323 | foreach ($this->filters as $filter) { |
||
| 324 | $emailcollectorfilter->type = $filter['type']; |
||
| 325 | $emailcollectorfilter->rulevalue = $filter['rulevalue']; |
||
| 326 | $emailcollectorfilter->fk_emailcollector = $this->id; |
||
| 327 | $emailcollectorfilter->status = $filter['status']; |
||
| 328 | |||
| 329 | $emailcollectorfilter->create($user); |
||
| 330 | } |
||
| 331 | } |
||
| 332 | |||
| 333 | if (is_array($this->actions) && count($this->actions)) { |
||
| 334 | $emailcollectoroperation = new EmailCollectorAction($this->db); |
||
| 335 | |||
| 336 | foreach ($this->actions as $operation) { |
||
| 337 | $emailcollectoroperation->type = $operation['type']; |
||
| 338 | $emailcollectoroperation->actionparam = $operation['actionparam']; |
||
| 339 | $emailcollectoroperation->fk_emailcollector = $this->id; |
||
| 340 | $emailcollectoroperation->status = $operation['status']; |
||
| 341 | $emailcollectoroperation->position = $operation['position']; |
||
| 342 | |||
| 343 | $emailcollectoroperation->create($user); |
||
| 344 | } |
||
| 345 | } |
||
| 346 | |||
| 347 | return $id; |
||
| 348 | } |
||
| 349 | |||
| 350 | /** |
||
| 351 | * Clone and object into another one |
||
| 352 | * |
||
| 353 | * @param User $user User that creates |
||
| 354 | * @param int $fromid Id of object to clone |
||
| 355 | * @return mixed New object created, <0 if KO |
||
| 356 | */ |
||
| 357 | public function createFromClone(User $user, $fromid) |
||
| 358 | { |
||
| 359 | global $langs, $extrafields; |
||
| 360 | $error = 0; |
||
| 361 | |||
| 362 | dol_syslog(__METHOD__, LOG_DEBUG); |
||
| 363 | |||
| 364 | $object = new self($this->db); |
||
| 365 | |||
| 366 | $this->db->begin(); |
||
| 367 | |||
| 368 | // Load source object |
||
| 369 | $object->fetchCommon($fromid); |
||
| 370 | |||
| 371 | $object->fetchFilters(); // Rules |
||
| 372 | $object->fetchActions(); // Operations |
||
| 373 | |||
| 374 | // Reset some properties |
||
| 375 | unset($object->id); |
||
| 376 | unset($object->fk_user_creat); |
||
| 377 | unset($object->import_key); |
||
| 378 | unset($object->password); |
||
| 379 | unset($object->lastresult); |
||
| 380 | unset($object->codelastresult); |
||
| 381 | unset($object->datelastresult); |
||
| 382 | unset($object->datelastok); |
||
| 383 | unset($object->debuginfo); |
||
| 384 | |||
| 385 | // Clear fields |
||
| 386 | $object->ref = "copy_of_" . $object->ref; |
||
| 387 | $object->label = $langs->trans("CopyOf") . " " . $object->label; |
||
| 388 | if (empty($object->host)) { |
||
| 389 | $object->host = 'imap.example.com'; |
||
| 390 | } |
||
| 391 | // Clear extrafields that are unique |
||
| 392 | if (is_array($object->array_options) && count($object->array_options) > 0) { |
||
| 393 | $extrafields->fetch_name_optionals_label($this->table_element); |
||
| 394 | foreach ($object->array_options as $key => $option) { |
||
| 395 | $shortkey = preg_replace('/options_/', '', $key); |
||
| 396 | if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) { |
||
| 397 | //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; |
||
| 398 | unset($object->array_options[$key]); |
||
| 399 | } |
||
| 400 | } |
||
| 401 | } |
||
| 402 | |||
| 403 | // Create clone |
||
| 404 | $object->context['createfromclone'] = 'createfromclone'; |
||
| 405 | $result = $object->create($user); |
||
| 406 | if ($result < 0) { |
||
| 407 | $error++; |
||
| 408 | $this->error = $object->error; |
||
| 409 | $this->errors = $object->errors; |
||
| 410 | } |
||
| 411 | |||
| 412 | unset($object->context['createfromclone']); |
||
| 413 | |||
| 414 | // End |
||
| 415 | if (!$error) { |
||
| 416 | $this->db->commit(); |
||
| 417 | return $object; |
||
| 418 | } else { |
||
| 419 | $this->db->rollback(); |
||
| 420 | return -1; |
||
| 421 | } |
||
| 422 | } |
||
| 423 | |||
| 424 | /** |
||
| 425 | * Load object in memory from the database |
||
| 426 | * |
||
| 427 | * @param int $id Id object |
||
| 428 | * @param string $ref Ref |
||
| 429 | * @return int Return integer <0 if KO, 0 if not found, >0 if OK |
||
| 430 | */ |
||
| 431 | public function fetch($id, $ref = null) |
||
| 432 | { |
||
| 433 | $result = $this->fetchCommon($id, $ref); |
||
| 434 | |||
| 435 | include_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php'; |
||
| 436 | $this->password = dolDecrypt($this->password); |
||
| 437 | |||
| 438 | //if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); |
||
| 439 | return $result; |
||
| 440 | } |
||
| 441 | |||
| 442 | /** |
||
| 443 | * Load object lines in memory from the database |
||
| 444 | * |
||
| 445 | * @return int Return integer <0 if KO, 0 if not found, >0 if OK |
||
| 446 | */ |
||
| 447 | /* |
||
| 448 | public function fetchLines() |
||
| 449 | { |
||
| 450 | $this->lines=array(); |
||
| 451 | |||
| 452 | // Load lines with object EmailCollectorLine |
||
| 453 | |||
| 454 | return count($this->lines)?1:0; |
||
| 455 | } |
||
| 456 | */ |
||
| 457 | |||
| 458 | /** |
||
| 459 | * Fetch all account and load objects into an array |
||
| 460 | * |
||
| 461 | * @param User $user User |
||
| 462 | * @param int $activeOnly filter if active |
||
| 463 | * @param string $sortfield field for sorting |
||
| 464 | * @param string $sortorder sorting order |
||
| 465 | * @param int $limit sort limit |
||
| 466 | * @param int $page page to start on |
||
| 467 | * @return array Array with key => EmailCollector object |
||
| 468 | */ |
||
| 469 | public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0) |
||
| 470 | { |
||
| 471 | global $langs; |
||
| 472 | |||
| 473 | $obj_ret = array(); |
||
| 474 | |||
| 475 | $sql = "SELECT s.rowid"; |
||
| 476 | $sql .= " FROM " . MAIN_DB_PREFIX . "emailcollector_emailcollector as s"; |
||
| 477 | $sql .= ' WHERE s.entity IN (' . getEntity('emailcollector') . ')'; |
||
| 478 | if ($activeOnly) { |
||
| 479 | $sql .= " AND s.status = 1"; |
||
| 480 | } |
||
| 481 | $sql .= $this->db->order($sortfield, $sortorder); |
||
| 482 | if ($limit) { |
||
| 483 | if ($page < 0) { |
||
| 484 | $page = 0; |
||
| 485 | } |
||
| 486 | $offset = $limit * $page; |
||
| 487 | |||
| 488 | $sql .= $this->db->plimit($limit + 1, $offset); |
||
| 489 | } |
||
| 490 | |||
| 491 | $result = $this->db->query($sql); |
||
| 492 | if ($result) { |
||
| 493 | $num = $this->db->num_rows($result); |
||
| 494 | $i = 0; |
||
| 495 | while ($i < $num) { |
||
| 496 | $obj = $this->db->fetch_object($result); |
||
| 497 | $emailcollector_static = new EmailCollector($this->db); |
||
| 498 | if ($emailcollector_static->fetch($obj->rowid)) { |
||
| 499 | $obj_ret[] = $emailcollector_static; |
||
| 500 | } |
||
| 501 | $i++; |
||
| 502 | } |
||
| 503 | } else { |
||
| 504 | $this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list'; |
||
| 505 | dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR); |
||
| 506 | $ret = -1; |
||
| 507 | } |
||
| 508 | if (!count($obj_ret)) { |
||
| 509 | dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG); |
||
| 510 | } |
||
| 511 | |||
| 512 | return $obj_ret; |
||
| 513 | } |
||
| 514 | |||
| 515 | /** |
||
| 516 | * Update object into database |
||
| 517 | * |
||
| 518 | * @param User $user User that modifies |
||
| 519 | * @param int $notrigger 0=launch triggers after, 1=disable triggers |
||
| 520 | * @return int Return integer <0 if KO, >0 if OK |
||
| 521 | */ |
||
| 522 | public function update(User $user, $notrigger = 0) |
||
| 523 | { |
||
| 524 | global $langs; |
||
| 525 | |||
| 526 | // Check parameters |
||
| 527 | if ($this->host && preg_match('/^http:/i', trim($this->host))) { |
||
| 528 | $langs->load("errors"); |
||
| 529 | $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host); |
||
| 530 | return -1; |
||
| 531 | } |
||
| 532 | |||
| 533 | include_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php'; |
||
| 534 | $this->password = dolEncrypt($this->password); |
||
| 535 | |||
| 536 | $result = $this->updateCommon($user, $notrigger); |
||
| 537 | |||
| 538 | $this->password = dolDecrypt($this->password); |
||
| 539 | |||
| 540 | return $result; |
||
| 541 | } |
||
| 542 | |||
| 543 | /** |
||
| 544 | * Delete object in database |
||
| 545 | * |
||
| 546 | * @param User $user User that deletes |
||
| 547 | * @param int $notrigger 0=launch triggers after, 1=disable triggers |
||
| 548 | * @return int Return integer <0 if KO, >0 if OK |
||
| 549 | */ |
||
| 550 | public function delete(User $user, $notrigger = 0) |
||
| 551 | { |
||
| 552 | return $this->deleteCommon($user, $notrigger, 1); |
||
| 553 | } |
||
| 554 | |||
| 555 | /** |
||
| 556 | * Return a link to the object card (with optionally the picto) |
||
| 557 | * |
||
| 558 | * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) |
||
| 559 | * @param string $option On what the link point to ('nolink', ...) |
||
| 560 | * @param int $notooltip 1=Disable tooltip |
||
| 561 | * @param string $morecss Add more css on link |
||
| 562 | * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking |
||
| 563 | * @return string String with URL |
||
| 564 | */ |
||
| 565 | public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) |
||
| 566 | { |
||
| 567 | global $conf, $langs, $action, $hookmanager; |
||
| 568 | |||
| 569 | if (!empty($conf->dol_no_mouse_hover)) { |
||
| 570 | $notooltip = 1; // Force disable tooltips |
||
| 571 | } |
||
| 572 | |||
| 573 | $result = ''; |
||
| 574 | |||
| 575 | $label = '<u>' . $langs->trans("EmailCollector") . '</u>'; |
||
| 576 | $label .= '<br>'; |
||
| 577 | $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref; |
||
| 578 | |||
| 579 | $url = constant('BASE_URL') . '/admin/emailcollector_card.php?id=' . $this->id; |
||
| 580 | |||
| 581 | if ($option != 'nolink') { |
||
| 582 | // Add param to save lastsearch_values or not |
||
| 583 | $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); |
||
| 584 | if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { |
||
| 585 | $add_save_lastsearch_values = 1; |
||
| 586 | } |
||
| 587 | if ($add_save_lastsearch_values) { |
||
| 588 | $url .= '&save_lastsearch_values=1'; |
||
| 589 | } |
||
| 590 | } |
||
| 591 | |||
| 592 | $linkclose = ''; |
||
| 593 | if (empty($notooltip)) { |
||
| 594 | if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) { |
||
| 595 | $label = $langs->trans("ShowEmailCollector"); |
||
| 596 | $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"'; |
||
| 597 | } |
||
| 598 | $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"'; |
||
| 599 | $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"'; |
||
| 600 | } else { |
||
| 601 | $linkclose = ($morecss ? ' class="' . $morecss . '"' : ''); |
||
| 602 | } |
||
| 603 | |||
| 604 | $linkstart = '<a href="' . $url . '"'; |
||
| 605 | $linkstart .= $linkclose . '>'; |
||
| 606 | $linkend = '</a>'; |
||
| 607 | |||
| 608 | $result .= $linkstart; |
||
| 609 | if ($withpicto) { |
||
| 610 | $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); |
||
| 611 | } |
||
| 612 | if ($withpicto != 2) { |
||
| 613 | $result .= $this->ref; |
||
| 614 | } |
||
| 615 | $result .= $linkend; |
||
| 616 | //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); |
||
| 617 | |||
| 618 | $hookmanager->initHooks(array('emailcollectordao')); |
||
| 619 | $parameters = array('id' => $this->id, 'getnomurl' => &$result); |
||
| 620 | $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks |
||
| 621 | if ($reshook > 0) { |
||
| 622 | $result = $hookmanager->resPrint; |
||
| 623 | } else { |
||
| 624 | $result .= $hookmanager->resPrint; |
||
| 625 | } |
||
| 626 | |||
| 627 | return $result; |
||
| 628 | } |
||
| 629 | |||
| 630 | /** |
||
| 631 | * Return label of the status |
||
| 632 | * |
||
| 633 | * @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 |
||
| 634 | * @return string Label of status |
||
| 635 | */ |
||
| 636 | public function getLibStatut($mode = 0) |
||
| 637 | { |
||
| 638 | return $this->LibStatut($this->status, $mode); |
||
| 639 | } |
||
| 640 | |||
| 641 | // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps |
||
| 642 | /** |
||
| 643 | * Return the status |
||
| 644 | * |
||
| 645 | * @param int $status Id status |
||
| 646 | * @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 |
||
| 647 | * @return string Label of status |
||
| 648 | */ |
||
| 649 | public function LibStatut($status, $mode = 0) |
||
| 650 | { |
||
| 651 | // phpcs:enable |
||
| 652 | if (empty($this->labelStatus) || empty($this->labelStatusShort)) { |
||
| 653 | global $langs; |
||
| 654 | //$langs->load("mymodule"); |
||
| 655 | $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled'); |
||
| 656 | $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled'); |
||
| 657 | $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled'); |
||
| 658 | $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled'); |
||
| 659 | } |
||
| 660 | |||
| 661 | $statusType = 'status5'; |
||
| 662 | if ($status == self::STATUS_ENABLED) { |
||
| 663 | $statusType = 'status4'; |
||
| 664 | } |
||
| 665 | |||
| 666 | return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); |
||
| 667 | } |
||
| 668 | |||
| 669 | /** |
||
| 670 | * Charge les information d'ordre info dans l'objet commande |
||
| 671 | * |
||
| 672 | * @param int $id Id of order |
||
| 673 | * @return void |
||
| 674 | */ |
||
| 675 | public function info($id) |
||
| 676 | { |
||
| 677 | $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; |
||
| 678 | $sql .= ' fk_user_creat, fk_user_modif'; |
||
| 679 | $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; |
||
| 680 | $sql .= ' WHERE t.rowid = ' . ((int) $id); |
||
| 681 | $result = $this->db->query($sql); |
||
| 682 | if ($result) { |
||
| 683 | if ($this->db->num_rows($result)) { |
||
| 684 | $obj = $this->db->fetch_object($result); |
||
| 685 | |||
| 686 | $this->id = $obj->rowid; |
||
| 687 | |||
| 688 | $this->user_creation_id = $obj->fk_user_creat; |
||
| 689 | $this->user_modification_id = $obj->fk_user_modif; |
||
| 690 | $this->date_creation = $this->db->jdate($obj->datec); |
||
| 691 | $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem); |
||
| 692 | } |
||
| 693 | |||
| 694 | $this->db->free($result); |
||
| 695 | } else { |
||
| 696 | dol_print_error($this->db); |
||
| 697 | } |
||
| 698 | } |
||
| 699 | |||
| 700 | /** |
||
| 701 | * Initialise object with example values |
||
| 702 | * Id must be 0 if object instance is a specimen |
||
| 703 | * |
||
| 704 | * @return int |
||
| 705 | */ |
||
| 706 | public function initAsSpecimen() |
||
| 707 | { |
||
| 708 | $this->host = 'localhost'; |
||
| 709 | $this->login = 'alogin'; |
||
| 710 | |||
| 711 | return $this->initAsSpecimenCommon(); |
||
| 712 | } |
||
| 713 | |||
| 714 | /** |
||
| 715 | * Fetch filters |
||
| 716 | * |
||
| 717 | * @return int Return integer <0 if KO, >0 if OK |
||
| 718 | * @see fetchActions() |
||
| 719 | */ |
||
| 720 | public function fetchFilters() |
||
| 721 | { |
||
| 722 | $this->filters = array(); |
||
| 723 | |||
| 724 | $sql = 'SELECT rowid, type, rulevalue, status'; |
||
| 725 | $sql .= ' FROM ' . MAIN_DB_PREFIX . 'emailcollector_emailcollectorfilter'; |
||
| 726 | $sql .= ' WHERE fk_emailcollector = ' . ((int) $this->id); |
||
| 727 | //$sql.= ' ORDER BY position'; |
||
| 728 | |||
| 729 | $resql = $this->db->query($sql); |
||
| 730 | if ($resql) { |
||
| 731 | $num = $this->db->num_rows($resql); |
||
| 732 | $i = 0; |
||
| 733 | while ($i < $num) { |
||
| 734 | $obj = $this->db->fetch_object($resql); |
||
| 735 | $this->filters[$obj->rowid] = array('id' => $obj->rowid, 'type' => $obj->type, 'rulevalue' => $obj->rulevalue, 'status' => $obj->status); |
||
| 736 | $i++; |
||
| 737 | } |
||
| 738 | $this->db->free($resql); |
||
| 739 | } else { |
||
| 740 | dol_print_error($this->db); |
||
| 741 | } |
||
| 742 | |||
| 743 | return 1; |
||
| 744 | } |
||
| 745 | |||
| 746 | /** |
||
| 747 | * Fetch actions |
||
| 748 | * |
||
| 749 | * @return int Return integer <0 if KO, >0 if OK |
||
| 750 | * @see fetchFilters() |
||
| 751 | */ |
||
| 752 | public function fetchActions() |
||
| 753 | { |
||
| 754 | $this->actions = array(); |
||
| 755 | |||
| 756 | $sql = 'SELECT rowid, type, actionparam, status'; |
||
| 757 | $sql .= ' FROM ' . MAIN_DB_PREFIX . 'emailcollector_emailcollectoraction'; |
||
| 758 | $sql .= ' WHERE fk_emailcollector = ' . ((int) $this->id); |
||
| 759 | $sql .= ' ORDER BY position'; |
||
| 760 | |||
| 761 | $resql = $this->db->query($sql); |
||
| 762 | if ($resql) { |
||
| 763 | $num = $this->db->num_rows($resql); |
||
| 764 | $i = 0; |
||
| 765 | while ($i < $num) { |
||
| 766 | $obj = $this->db->fetch_object($resql); |
||
| 767 | $this->actions[$obj->rowid] = array('id' => $obj->rowid, 'type' => $obj->type, 'actionparam' => $obj->actionparam, 'status' => $obj->status); |
||
| 768 | $i++; |
||
| 769 | } |
||
| 770 | $this->db->free($resql); |
||
| 771 | |||
| 772 | return 1; |
||
| 773 | } else { |
||
| 774 | dol_print_error($this->db); |
||
| 775 | |||
| 776 | return -1; |
||
| 777 | } |
||
| 778 | } |
||
| 779 | |||
| 780 | |||
| 781 | /** |
||
| 782 | * Return the connectstring to use with IMAP connection function |
||
| 783 | * |
||
| 784 | * @return string |
||
| 785 | */ |
||
| 786 | public function getConnectStringIMAP() |
||
| 787 | { |
||
| 788 | // Connect to IMAP |
||
| 789 | $flags = '/service=imap'; // IMAP |
||
| 790 | if (getDolGlobalString('IMAP_FORCE_TLS')) { |
||
| 791 | $flags .= '/tls'; |
||
| 792 | } elseif (empty($this->imap_encryption) || ($this->imap_encryption == 'ssl' && getDolGlobalString('IMAP_FORCE_NOSSL'))) { |
||
| 793 | $flags .= ''; |
||
| 794 | } else { |
||
| 795 | $flags .= '/' . $this->imap_encryption; |
||
| 796 | } |
||
| 797 | |||
| 798 | $flags .= '/novalidate-cert'; |
||
| 799 | //$flags.='/readonly'; |
||
| 800 | //$flags.='/debug'; |
||
| 801 | if (!empty($this->norsh) || getDolGlobalString('IMAP_FORCE_NORSH')) { |
||
| 802 | $flags .= '/norsh'; |
||
| 803 | } |
||
| 804 | //Used in shared mailbox from Office365 |
||
| 805 | if (!empty($this->login) && strpos($this->login, '/') != false) { |
||
| 806 | $partofauth = explode('/', $this->login); |
||
| 807 | $flags .= '/authuser=' . $partofauth[0] . '/user=' . $partofauth[1]; |
||
| 808 | } |
||
| 809 | |||
| 810 | $connectstringserver = '{' . $this->host . ':' . $this->port . $flags . '}'; |
||
| 811 | |||
| 812 | return $connectstringserver; |
||
| 813 | } |
||
| 814 | |||
| 815 | /** |
||
| 816 | * Convert str to UTF-7 imap. Used to forge mailbox names. |
||
| 817 | * |
||
| 818 | * @param string $str String to encode |
||
| 819 | * @return string|false Encoded string, or false if error |
||
| 820 | */ |
||
| 821 | public function getEncodedUtf7($str) |
||
| 822 | { |
||
| 823 | if (function_exists('mb_convert_encoding')) { |
||
| 824 | // change spaces by entropy because mb_convert fail with spaces |
||
| 825 | $str = preg_replace("/ /", "xxxSPACExxx", $str); // the replacement string must be valid in utf7 so _ can't be used |
||
| 826 | $str = preg_replace("/\[Gmail\]/", "xxxGMAILxxx", $str); // the replacement string must be valid in utf7 so _ can't be used |
||
| 827 | // if mb_convert work |
||
| 828 | if ($str = mb_convert_encoding($str, "UTF-7")) { |
||
| 829 | // change characters |
||
| 830 | $str = preg_replace("/\+A/", "&A", $str); |
||
| 831 | // change to spaces again |
||
| 832 | $str = preg_replace("/xxxSPACExxx/", " ", $str); |
||
| 833 | // change to [Gmail] again |
||
| 834 | $str = preg_replace("/xxxGMAILxxx/", "[Gmail]", $str); |
||
| 835 | return $str; |
||
| 836 | } else { |
||
| 837 | // print error and return false |
||
| 838 | $this->error = "error: is not possible to encode this string '" . $str . "'"; |
||
| 839 | return false; |
||
| 840 | } |
||
| 841 | } else { |
||
| 842 | return $str; |
||
| 843 | } |
||
| 844 | } |
||
| 845 | |||
| 846 | /** |
||
| 847 | * Action executed by scheduler |
||
| 848 | * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters' |
||
| 849 | * |
||
| 850 | * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) |
||
| 851 | */ |
||
| 852 | public function doCollect() |
||
| 853 | { |
||
| 854 | global $user; |
||
| 855 | |||
| 856 | $nberror = 0; |
||
| 857 | |||
| 858 | $arrayofcollectors = $this->fetchAll($user, 1); |
||
| 859 | |||
| 860 | // Loop on each collector |
||
| 861 | foreach ($arrayofcollectors as $emailcollector) { |
||
| 862 | $result = $emailcollector->doCollectOneCollector(0); |
||
| 863 | dol_syslog("doCollect result = " . $result . " for emailcollector->id = " . $emailcollector->id); |
||
| 864 | |||
| 865 | $this->error .= 'EmailCollector ID ' . $emailcollector->id . ':' . $emailcollector->error . '<br>'; |
||
| 866 | if (!empty($emailcollector->errors)) { |
||
| 867 | $this->error .= implode('<br>', $emailcollector->errors); |
||
| 868 | } |
||
| 869 | $this->output .= 'EmailCollector ID ' . $emailcollector->id . ': ' . $emailcollector->lastresult . '<br>'; |
||
| 870 | } |
||
| 871 | |||
| 872 | return $nberror; |
||
| 873 | } |
||
| 874 | |||
| 875 | /** |
||
| 876 | * overwitePropertiesOfObject |
||
| 877 | * |
||
| 878 | * @param object $object Current object we will set ->properties |
||
| 879 | * @param string $actionparam Action parameters |
||
| 880 | * @param string $messagetext Body |
||
| 881 | * @param string $subject Subject |
||
| 882 | * @param string $header Header |
||
| 883 | * @param string $operationslog String with logs of operations done |
||
| 884 | * @return int 0=OK, Nb of error if error |
||
| 885 | */ |
||
| 886 | private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header, &$operationslog) |
||
| 887 | { |
||
| 888 | global $conf, $langs; |
||
| 889 | |||
| 890 | $errorforthisaction = 0; |
||
| 891 | |||
| 892 | // set output lang |
||
| 893 | $outputlangs = $langs; |
||
| 894 | $newlang = ''; |
||
| 895 | if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) { |
||
| 896 | $newlang = GETPOST('lang_id', 'aZ09'); |
||
| 897 | } |
||
| 898 | if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) { |
||
| 899 | $newlang = !empty($object->thirdparty->default_lang) ? $object->thirdparty->default_lang : $newlang; |
||
| 900 | } |
||
| 901 | if (!empty($newlang)) { |
||
| 902 | $outputlangs = new Translate('', $conf); |
||
| 903 | $outputlangs->setDefaultLang($newlang); |
||
| 904 | } |
||
| 905 | |||
| 906 | // Overwrite values with values extracted from source email |
||
| 907 | // $this->actionparam = 'opportunity_status=123;abc=EXTRACT:BODY:....' |
||
| 908 | $arrayvaluetouse = dolExplodeIntoArray($actionparam, '(\n\r|\r|\n|;)', '='); |
||
| 909 | |||
| 910 | $tmp = array(); |
||
| 911 | |||
| 912 | // Loop on each property set into actionparam |
||
| 913 | foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) { |
||
| 914 | $tmpclass = ''; |
||
| 915 | $tmpproperty = ''; |
||
| 916 | $tmparray = explode('.', $propertytooverwrite); |
||
| 917 | if (count($tmparray) == 2) { |
||
| 918 | $tmpclass = $tmparray[0]; |
||
| 919 | $tmpproperty = $tmparray[1]; |
||
| 920 | } else { |
||
| 921 | $tmpproperty = $tmparray[0]; |
||
| 922 | } |
||
| 923 | if ($tmpclass && ($tmpclass != $object->element)) { |
||
| 924 | continue; // Property is for another type of object |
||
| 925 | } |
||
| 926 | |||
| 927 | //if (property_exists($object, $tmpproperty) || preg_match('/^options_/', $tmpproperty)) |
||
| 928 | if ($tmpproperty) { |
||
| 929 | $sourcestring = ''; |
||
| 930 | $sourcefield = ''; |
||
| 931 | $regexstring = ''; |
||
| 932 | //$transformationstring=''; |
||
| 933 | $regforregex = array(); |
||
| 934 | if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) { |
||
| 935 | $sourcefield = $regforregex[1]; |
||
| 936 | $regexstring = $regforregex[2]; |
||
| 937 | //$transofrmationstring=$regforregex[3]; |
||
| 938 | } elseif (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) { |
||
| 939 | $sourcefield = $regforregex[1]; |
||
| 940 | $regexstring = $regforregex[2]; |
||
| 941 | } |
||
| 942 | |||
| 943 | if (!empty($sourcefield) && !empty($regexstring)) { |
||
| 944 | if (strtolower($sourcefield) == 'body') { |
||
| 945 | $sourcestring = $messagetext; |
||
| 946 | } elseif (strtolower($sourcefield) == 'subject') { |
||
| 947 | $sourcestring = $subject; |
||
| 948 | } elseif (strtolower($sourcefield) == 'header') { |
||
| 949 | $sourcestring = $header; |
||
| 950 | } |
||
| 951 | |||
| 952 | if ($sourcestring) { |
||
| 953 | $regforval = array(); |
||
| 954 | $regexoptions = ''; |
||
| 955 | if (strtolower($sourcefield) == 'body') { |
||
| 956 | $regexoptions = 'ms'; // The m means ^ and $ char is valid at each new line. The s means the char '.' is valid for new lines char too |
||
| 957 | } |
||
| 958 | if (strtolower($sourcefield) == 'header') { |
||
| 959 | $regexoptions = 'm'; // The m means ^ and $ char is valid at each new line. |
||
| 960 | } |
||
| 961 | |||
| 962 | //var_dump($tmpproperty.' - '.$regexstring.' - '.$regexoptions.' - '.$sourcestring); |
||
| 963 | if (preg_match('/' . $regexstring . '/' . $regexoptions, $sourcestring, $regforval)) { |
||
| 964 | // Overwrite param $tmpproperty |
||
| 965 | $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; |
||
| 966 | if (strtolower($sourcefield) == 'header') { // extract from HEADER |
||
| 967 | if (preg_match('/^options_/', $tmpproperty)) { |
||
| 968 | $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $this->decodeSMTPSubject($valueextracted); |
||
| 969 | } else { |
||
| 970 | if (property_exists($object, $tmpproperty)) { |
||
| 971 | $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted); |
||
| 972 | } else { |
||
| 973 | $tmp[$tmpproperty] = $this->decodeSMTPSubject($valueextracted); |
||
| 974 | } |
||
| 975 | } |
||
| 976 | } else { // extract from BODY |
||
| 977 | if (preg_match('/^options_/', $tmpproperty)) { |
||
| 978 | $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $this->decodeSMTPSubject($valueextracted); |
||
| 979 | } else { |
||
| 980 | if (property_exists($object, $tmpproperty)) { |
||
| 981 | $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted); |
||
| 982 | } else { |
||
| 983 | $tmp[$tmpproperty] = $this->decodeSMTPSubject($valueextracted); |
||
| 984 | } |
||
| 985 | } |
||
| 986 | } |
||
| 987 | if (preg_match('/^options_/', $tmpproperty)) { |
||
| 988 | $operationslog .= '<br>Regex /' . dol_escape_htmltag($regexstring) . '/' . dol_escape_htmltag($regexoptions) . ' into ' . strtolower($sourcefield) . ' -> found ' . dol_escape_htmltag(dol_trunc($object->array_options[preg_replace('/^options_/', '', $tmpproperty)], 128)); |
||
| 989 | } else { |
||
| 990 | if (property_exists($object, $tmpproperty)) { |
||
| 991 | $operationslog .= '<br>Regex /' . dol_escape_htmltag($regexstring) . '/' . dol_escape_htmltag($regexoptions) . ' into ' . strtolower($sourcefield) . ' -> found ' . dol_escape_htmltag(dol_trunc($object->$tmpproperty, 128)); |
||
| 992 | } else { |
||
| 993 | $operationslog .= '<br>Regex /' . dol_escape_htmltag($regexstring) . '/' . dol_escape_htmltag($regexoptions) . ' into ' . strtolower($sourcefield) . ' -> found ' . dol_escape_htmltag(dol_trunc($tmp[$tmpproperty], 128)); |
||
| 994 | } |
||
| 995 | } |
||
| 996 | } else { |
||
| 997 | // Regex not found |
||
| 998 | if (property_exists($object, $tmpproperty)) { |
||
| 999 | $object->$tmpproperty = null; |
||
| 1000 | } else { |
||
| 1001 | $tmp[$tmpproperty] = null; |
||
| 1002 | } |
||
| 1003 | |||
| 1004 | $operationslog .= '<br>Regex /' . dol_escape_htmltag($regexstring) . '/' . dol_escape_htmltag($regexoptions) . ' into ' . strtolower($sourcefield) . ' -> not found, so property ' . dol_escape_htmltag($tmpproperty) . ' is set to null.'; |
||
| 1005 | } |
||
| 1006 | } else { |
||
| 1007 | // Nothing can be done for this param |
||
| 1008 | $errorforthisaction++; |
||
| 1009 | $this->error = 'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)'; |
||
| 1010 | $this->errors[] = $this->error; |
||
| 1011 | |||
| 1012 | $operationslog .= '<br>' . $this->error; |
||
| 1013 | } |
||
| 1014 | } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) { |
||
| 1015 | $valuecurrent = ''; |
||
| 1016 | if (preg_match('/^options_/', $tmpproperty)) { |
||
| 1017 | $valuecurrent = $object->array_options[preg_replace('/^options_/', '', $tmpproperty)]; |
||
| 1018 | } else { |
||
| 1019 | if (property_exists($object, $tmpproperty)) { |
||
| 1020 | $valuecurrent = $object->$tmpproperty; |
||
| 1021 | } else { |
||
| 1022 | $valuecurrent = $tmp[$tmpproperty]; |
||
| 1023 | } |
||
| 1024 | } |
||
| 1025 | |||
| 1026 | if ($regforregex[1] == 'SET' || empty($valuecurrent)) { |
||
| 1027 | $valuetouse = $regforregex[2]; |
||
| 1028 | $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); |
||
| 1029 | complete_substitutions_array($substitutionarray, $outputlangs, $object); |
||
| 1030 | $matcharray = array(); |
||
| 1031 | preg_match_all('/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray); |
||
| 1032 | //var_dump($tmpproperty.' - '.$object->$tmpproperty.' - '.$valuetouse); var_dump($matcharray); |
||
| 1033 | if (is_array($matcharray[1])) { // $matcharray[1] is an array with the list of substitution key found without the __X__ syntax into the SET entry |
||
| 1034 | foreach ($matcharray[1] as $keytoreplace) { |
||
| 1035 | if ($keytoreplace) { |
||
| 1036 | if (preg_match('/^options_/', $keytoreplace)) { |
||
| 1037 | $substitutionarray['__' . $keytoreplace . '__'] = $object->array_options[preg_replace('/^options_/', '', $keytoreplace)]; |
||
| 1038 | } else { |
||
| 1039 | if (property_exists($object, $keytoreplace)) { |
||
| 1040 | $substitutionarray['__' . $keytoreplace . '__'] = $object->$keytoreplace; |
||
| 1041 | } else { |
||
| 1042 | $substitutionarray['__' . $keytoreplace . '__'] = $tmp[$keytoreplace]; |
||
| 1043 | } |
||
| 1044 | } |
||
| 1045 | } |
||
| 1046 | } |
||
| 1047 | } |
||
| 1048 | //var_dump($substitutionarray); |
||
| 1049 | //dol_syslog('substitutionarray='.var_export($substitutionarray, true)); |
||
| 1050 | |||
| 1051 | $valuetouse = make_substitutions($valuetouse, $substitutionarray); |
||
| 1052 | if (preg_match('/^options_/', $tmpproperty)) { |
||
| 1053 | $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetouse; |
||
| 1054 | |||
| 1055 | $operationslog .= '<br>Set value ' . dol_escape_htmltag($valuetouse) . ' into object->array_options[' . dol_escape_htmltag(preg_replace('/^options_/', '', $tmpproperty)) . ']'; |
||
| 1056 | } else { |
||
| 1057 | if (property_exists($object, $tmpproperty)) { |
||
| 1058 | $object->$tmpproperty = $valuetouse; |
||
| 1059 | } else { |
||
| 1060 | $tmp[$tmpproperty] = $valuetouse; |
||
| 1061 | } |
||
| 1062 | |||
| 1063 | $operationslog .= '<br>Set value ' . dol_escape_htmltag($valuetouse) . ' into object->' . dol_escape_htmltag($tmpproperty); |
||
| 1064 | } |
||
| 1065 | } |
||
| 1066 | } else { |
||
| 1067 | $errorforthisaction++; |
||
| 1068 | $this->error = 'Bad syntax for description of action parameters: ' . $actionparam; |
||
| 1069 | $this->errors[] = $this->error; |
||
| 1070 | } |
||
| 1071 | } |
||
| 1072 | } |
||
| 1073 | |||
| 1074 | return $errorforthisaction; |
||
| 1075 | } |
||
| 1076 | |||
| 1077 | /** |
||
| 1078 | * Execute collect for current collector loaded previously with fetch. |
||
| 1079 | * |
||
| 1080 | * @param int $mode 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates |
||
| 1081 | * @return int Return integer <0 if KO, >0 if OK |
||
| 1082 | */ |
||
| 1083 | public function doCollectOneCollector($mode = 0) |
||
| 1084 | { |
||
| 1085 | global $db, $conf, $langs, $user; |
||
| 1086 | global $hookmanager; |
||
| 1087 | |||
| 1088 | //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log'; |
||
| 1089 | |||
| 1090 | require_once constant('DOL_DOCUMENT_ROOT') . '/comm/action/class/actioncomm.class.php'; |
||
| 1091 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1092 | require_once constant('DOL_DOCUMENT_ROOT') . '/includes/webklex/php-imap/vendor/autoload.php'; |
||
| 1093 | } |
||
| 1094 | |||
| 1095 | dol_syslog("EmailCollector::doCollectOneCollector start for id=" . $this->id . " - " . $this->ref, LOG_INFO); |
||
| 1096 | |||
| 1097 | $langs->loadLangs(array("project", "companies", "mails", "errors", "ticket", "agenda", "commercial")); |
||
| 1098 | |||
| 1099 | $error = 0; |
||
| 1100 | $this->output = ''; |
||
| 1101 | $this->error = ''; |
||
| 1102 | $this->debuginfo = ''; |
||
| 1103 | |||
| 1104 | $search = ''; |
||
| 1105 | $searchhead = ''; |
||
| 1106 | $searchfilterdoltrackid = 0; |
||
| 1107 | $searchfilternodoltrackid = 0; |
||
| 1108 | $searchfilterisanswer = 0; |
||
| 1109 | $searchfilterisnotanswer = 0; |
||
| 1110 | $searchfilterreplyto = 0; |
||
| 1111 | $searchfilterexcludebodyarray = array(); |
||
| 1112 | $searchfilterexcludesubjectarray = array(); |
||
| 1113 | $operationslog = ''; |
||
| 1114 | $rulesreplyto = array(); |
||
| 1115 | |||
| 1116 | $now = dol_now(); |
||
| 1117 | |||
| 1118 | if (empty($this->host)) { |
||
| 1119 | $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMailHost')); |
||
| 1120 | return -1; |
||
| 1121 | } |
||
| 1122 | if (empty($this->login)) { |
||
| 1123 | $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Login')); |
||
| 1124 | return -1; |
||
| 1125 | } |
||
| 1126 | if (empty($this->source_directory)) { |
||
| 1127 | $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('MailboxSourceDirectory')); |
||
| 1128 | return -1; |
||
| 1129 | } |
||
| 1130 | |||
| 1131 | $sourcedir = $this->source_directory; |
||
| 1132 | $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag' |
||
| 1133 | |||
| 1134 | $this->fetchFilters(); |
||
| 1135 | $this->fetchActions(); |
||
| 1136 | |||
| 1137 | $sourcedir = $this->source_directory; |
||
| 1138 | $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag' |
||
| 1139 | |||
| 1140 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1141 | if ($this->acces_type == 1) { |
||
| 1142 | // Mode OAUth2 (access_type == 1) with PHP-IMAP |
||
| 1143 | $this->debuginfo .= 'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>'; |
||
| 1144 | |||
| 1145 | require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/oauth.lib.php'; |
||
| 1146 | |||
| 1147 | $supportedoauth2array = getSupportedOauth2Array(); |
||
| 1148 | |||
| 1149 | $keyforsupportedoauth2array = $this->oauth_service; |
||
| 1150 | if (preg_match('/^.*-/', $keyforsupportedoauth2array)) { |
||
| 1151 | $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array); |
||
| 1152 | } else { |
||
| 1153 | $keyforprovider = ''; |
||
| 1154 | } |
||
| 1155 | $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array); |
||
| 1156 | $keyforsupportedoauth2array = 'OAUTH_' . $keyforsupportedoauth2array . '_NAME'; |
||
| 1157 | |||
| 1158 | $OAUTH_SERVICENAME = 'Unknown'; |
||
| 1159 | if ( |
||
| 1160 | array_key_exists($keyforsupportedoauth2array, $supportedoauth2array) |
||
| 1161 | && array_key_exists('name', $supportedoauth2array[$keyforsupportedoauth2array]) |
||
| 1162 | && !empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) |
||
| 1163 | ) { |
||
| 1164 | $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array]['name'] . (!empty($keyforprovider) ? '-' . $keyforprovider : ''); |
||
| 1165 | } |
||
| 1166 | |||
| 1167 | require_once constant('DOL_DOCUMENT_ROOT') . '/includes/OAuth/bootstrap.php'; |
||
| 1168 | //$debugtext = "Host: ".$this->host."<br>Port: ".$this->port."<br>Login: ".$this->login."<br>Password: ".$this->password."<br>access type: ".$this->acces_type."<br>oauth service: ".$this->oauth_service."<br>Max email per collect: ".$this->maxemailpercollect; |
||
| 1169 | //dol_syslog($debugtext); |
||
| 1170 | |||
| 1171 | $token = ''; |
||
| 1172 | |||
| 1173 | $storage = new DoliStorage($db, $conf, $keyforprovider); |
||
| 1174 | |||
| 1175 | try { |
||
| 1176 | $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); |
||
| 1177 | |||
| 1178 | $expire = true; |
||
| 1179 | // TODO |
||
| 1180 | // Is token expired or will token expire in the next 30 seconds |
||
| 1181 | // if (is_object($tokenobj)) { |
||
| 1182 | // $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30)); |
||
| 1183 | // } |
||
| 1184 | // Token expired so we refresh it |
||
| 1185 | if (is_object($tokenobj) && $expire) { |
||
| 1186 | $this->debuginfo .= 'Refresh token<br>'; |
||
| 1187 | $credentials = new Credentials( |
||
| 1188 | getDolGlobalString('OAUTH_' . $this->oauth_service . '_ID'), |
||
| 1189 | getDolGlobalString('OAUTH_' . $this->oauth_service . '_SECRET'), |
||
| 1190 | getDolGlobalString('OAUTH_' . $this->oauth_service . '_URLAUTHORIZE') |
||
| 1191 | ); |
||
| 1192 | $serviceFactory = new \OAuth\ServiceFactory(); |
||
| 1193 | $oauthname = explode('-', $OAUTH_SERVICENAME); |
||
| 1194 | // ex service is Google-Emails we need only the first part Google |
||
| 1195 | $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array()); |
||
| 1196 | // We have to save the token because Google give it only once |
||
| 1197 | $refreshtoken = $tokenobj->getRefreshToken(); |
||
| 1198 | $tokenobj = $apiService->refreshAccessToken($tokenobj); |
||
| 1199 | $tokenobj->setRefreshToken($refreshtoken); |
||
| 1200 | $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj); |
||
| 1201 | } |
||
| 1202 | $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); |
||
| 1203 | if (is_object($tokenobj)) { |
||
| 1204 | $token = $tokenobj->getAccessToken(); |
||
| 1205 | } else { |
||
| 1206 | $this->error = "Token not found"; |
||
| 1207 | return -1; |
||
| 1208 | } |
||
| 1209 | } catch (Exception $e) { |
||
| 1210 | // Return an error if token not found |
||
| 1211 | $this->error = $e->getMessage(); |
||
| 1212 | dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR); |
||
| 1213 | return -1; |
||
| 1214 | } |
||
| 1215 | |||
| 1216 | $cm = new ClientManager(); |
||
| 1217 | $client = $cm->make([ |
||
| 1218 | 'host' => $this->host, |
||
| 1219 | 'port' => $this->port, |
||
| 1220 | 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false, |
||
| 1221 | 'validate_cert' => true, |
||
| 1222 | 'protocol' => 'imap', |
||
| 1223 | 'username' => $this->login, |
||
| 1224 | 'password' => $token, |
||
| 1225 | 'authentication' => "oauth", |
||
| 1226 | ]); |
||
| 1227 | } else { |
||
| 1228 | // Mode LOGIN (login/pass) with PHP-IMAP |
||
| 1229 | $this->debuginfo .= 'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>'; |
||
| 1230 | |||
| 1231 | $cm = new ClientManager(); |
||
| 1232 | $client = $cm->make([ |
||
| 1233 | 'host' => $this->host, |
||
| 1234 | 'port' => $this->port, |
||
| 1235 | 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false, |
||
| 1236 | 'validate_cert' => true, |
||
| 1237 | 'protocol' => 'imap', |
||
| 1238 | 'username' => $this->login, |
||
| 1239 | 'password' => $this->password, |
||
| 1240 | 'authentication' => "login", |
||
| 1241 | ]); |
||
| 1242 | } |
||
| 1243 | |||
| 1244 | try { |
||
| 1245 | $client->connect(); |
||
| 1246 | } catch (ConnectionFailedException $e) { |
||
| 1247 | $this->error = $e->getMessage(); |
||
| 1248 | $this->errors[] = $this->error; |
||
| 1249 | dol_syslog("EmailCollector::doCollectOneCollector " . $this->error, LOG_ERR); |
||
| 1250 | return -1; |
||
| 1251 | } |
||
| 1252 | |||
| 1253 | $host = dol_getprefix('email'); |
||
| 1254 | } else { |
||
| 1255 | // Use native IMAP functions |
||
| 1256 | $this->debuginfo .= 'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>'; |
||
| 1257 | |||
| 1258 | if (!function_exists('imap_open')) { |
||
| 1259 | $this->error = 'IMAP function not enabled on your PHP'; |
||
| 1260 | return -2; |
||
| 1261 | } |
||
| 1262 | |||
| 1263 | $connectstringserver = $this->getConnectStringIMAP(); |
||
| 1264 | if (!getDolGlobalString('MAIL_DISABLE_UTF7_ENCODE_OF_DIR')) { |
||
| 1265 | $connectstringsource = $connectstringserver . $this->getEncodedUtf7($sourcedir); |
||
| 1266 | $connectstringtarget = $connectstringserver . $this->getEncodedUtf7($targetdir); |
||
| 1267 | } else { |
||
| 1268 | $connectstringsource = $connectstringserver . $sourcedir; |
||
| 1269 | $connectstringtarget = $connectstringserver . $targetdir; |
||
| 1270 | } |
||
| 1271 | |||
| 1272 | $this->debuginfo .= 'connectstringsource = ' . $connectstringsource . ', $connectstringtarget=' . $connectstringtarget . '<br>'; |
||
| 1273 | |||
| 1274 | $connection = imap_open($connectstringsource, $this->login, $this->password); |
||
| 1275 | if (!$connection) { |
||
| 1276 | $this->error = 'Failed to open IMAP connection ' . $connectstringsource . ' ' . imap_last_error(); |
||
| 1277 | return -3; |
||
| 1278 | } |
||
| 1279 | imap_errors(); // Clear stack of errors. |
||
| 1280 | |||
| 1281 | $host = dol_getprefix('email'); |
||
| 1282 | //$host = '123456'; |
||
| 1283 | |||
| 1284 | // Define the IMAP search string |
||
| 1285 | // See https://tools.ietf.org/html/rfc3501#section-6.4.4 for IMAPv4 (PHP not yet compatible) |
||
| 1286 | // See https://tools.ietf.org/html/rfc1064 page 13 for IMAPv2 |
||
| 1287 | //$search='ALL'; |
||
| 1288 | } |
||
| 1289 | |||
| 1290 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1291 | // Use PHPIMAP external library |
||
| 1292 | $criteria = array(array('UNDELETED')); // Seems not supported by some servers |
||
| 1293 | foreach ($this->filters as $rule) { |
||
| 1294 | if (empty($rule['status'])) { |
||
| 1295 | continue; |
||
| 1296 | } |
||
| 1297 | |||
| 1298 | $not = ''; |
||
| 1299 | if (strpos($rule['rulevalue'], '!') === 0) { |
||
| 1300 | // The value start with !, so we exclude the criteria |
||
| 1301 | $not = 'NOT '; |
||
| 1302 | // Then remove the ! from the string for next filters |
||
| 1303 | $rule['rulevalue'] = substr($rule['rulevalue'], 1); |
||
| 1304 | } |
||
| 1305 | |||
| 1306 | if ($rule['type'] == 'from') { |
||
| 1307 | $tmprulevaluearray = explode('*', $rule['rulevalue']); |
||
| 1308 | if (count($tmprulevaluearray) >= 2) { |
||
| 1309 | foreach ($tmprulevaluearray as $tmprulevalue) { |
||
| 1310 | array_push($criteria, array($not . "FROM" => $tmprulevalue)); |
||
| 1311 | } |
||
| 1312 | } else { |
||
| 1313 | array_push($criteria, array($not . "FROM" => $rule['rulevalue'])); |
||
| 1314 | } |
||
| 1315 | } |
||
| 1316 | if ($rule['type'] == 'to') { |
||
| 1317 | $tmprulevaluearray = explode('*', $rule['rulevalue']); |
||
| 1318 | if (count($tmprulevaluearray) >= 2) { |
||
| 1319 | foreach ($tmprulevaluearray as $tmprulevalue) { |
||
| 1320 | array_push($criteria, array($not . "TO" => $tmprulevalue)); |
||
| 1321 | } |
||
| 1322 | } else { |
||
| 1323 | array_push($criteria, array($not . "TO" => $rule['rulevalue'])); |
||
| 1324 | } |
||
| 1325 | } |
||
| 1326 | if ($rule['type'] == 'bcc') { |
||
| 1327 | array_push($criteria, array($not . "BCC" => $rule['rulevalue'])); |
||
| 1328 | } |
||
| 1329 | if ($rule['type'] == 'cc') { |
||
| 1330 | array_push($criteria, array($not . "CC" => $rule['rulevalue'])); |
||
| 1331 | } |
||
| 1332 | if ($rule['type'] == 'subject') { |
||
| 1333 | if (strpos($rule['rulevalue'], '!') === 0) { |
||
| 1334 | //array_push($criteria, array("NOT SUBJECT" => $rule['rulevalue'])); |
||
| 1335 | $searchfilterexcludesubjectarray[] = preg_replace('/^!/', '', $rule['rulevalue']); |
||
| 1336 | } else { |
||
| 1337 | array_push($criteria, array("SUBJECT" => $rule['rulevalue'])); |
||
| 1338 | } |
||
| 1339 | } |
||
| 1340 | if ($rule['type'] == 'body') { |
||
| 1341 | if (strpos($rule['rulevalue'], '!') === 0) { |
||
| 1342 | //array_push($criteria, array("NOT BODY" => $rule['rulevalue'])); |
||
| 1343 | $searchfilterexcludebodyarray[] = preg_replace('/^!/', '', $rule['rulevalue']); |
||
| 1344 | } else { |
||
| 1345 | array_push($criteria, array("BODY" => $rule['rulevalue'])); |
||
| 1346 | } |
||
| 1347 | } |
||
| 1348 | if ($rule['type'] == 'header') { |
||
| 1349 | array_push($criteria, array($not . "HEADER" => $rule['rulevalue'])); |
||
| 1350 | } |
||
| 1351 | |||
| 1352 | /* seems not used */ |
||
| 1353 | /* |
||
| 1354 | if ($rule['type'] == 'notinsubject') { |
||
| 1355 | array_push($criteria, array($not."SUBJECT NOT" => $rule['rulevalue'])); |
||
| 1356 | } |
||
| 1357 | if ($rule['type'] == 'notinbody') { |
||
| 1358 | array_push($criteria, array($not."BODY NOT" => $rule['rulevalue'])); |
||
| 1359 | }*/ |
||
| 1360 | |||
| 1361 | if ($rule['type'] == 'seen') { |
||
| 1362 | array_push($criteria, array($not . "SEEN")); |
||
| 1363 | } |
||
| 1364 | if ($rule['type'] == 'unseen') { |
||
| 1365 | array_push($criteria, array($not . "UNSEEN")); |
||
| 1366 | } |
||
| 1367 | if ($rule['type'] == 'unanswered') { |
||
| 1368 | array_push($criteria, array($not . "UNANSWERED")); |
||
| 1369 | } |
||
| 1370 | if ($rule['type'] == 'answered') { |
||
| 1371 | array_push($criteria, array($not . "ANSWERED")); |
||
| 1372 | } |
||
| 1373 | if ($rule['type'] == 'smaller') { |
||
| 1374 | array_push($criteria, array($not . "SMALLER")); |
||
| 1375 | } |
||
| 1376 | if ($rule['type'] == 'larger') { |
||
| 1377 | array_push($criteria, array($not . "LARGER")); |
||
| 1378 | } |
||
| 1379 | |||
| 1380 | // Rules to filter after the search imap |
||
| 1381 | if ($rule['type'] == 'withtrackingidinmsgid') { |
||
| 1382 | $searchfilterdoltrackid++; |
||
| 1383 | $searchhead .= '/Message-ID.*@' . preg_quote($host, '/') . '/'; |
||
| 1384 | } |
||
| 1385 | if ($rule['type'] == 'withouttrackingidinmsgid') { |
||
| 1386 | $searchfilterdoltrackid++; |
||
| 1387 | $searchhead .= '/Message-ID.*@' . preg_quote($host, '/') . '/'; |
||
| 1388 | } |
||
| 1389 | if ($rule['type'] == 'withtrackingid') { |
||
| 1390 | $searchfilterdoltrackid++; |
||
| 1391 | $searchhead .= '/References.*@' . preg_quote($host, '/') . '/'; |
||
| 1392 | } |
||
| 1393 | if ($rule['type'] == 'withouttrackingid') { |
||
| 1394 | $searchfilternodoltrackid++; |
||
| 1395 | $searchhead .= '! /References.*@' . preg_quote($host, '/') . '/'; |
||
| 1396 | } |
||
| 1397 | |||
| 1398 | if ($rule['type'] == 'isanswer') { |
||
| 1399 | $searchfilterisanswer++; |
||
| 1400 | $searchhead .= '/References.*@.*/'; |
||
| 1401 | } |
||
| 1402 | if ($rule['type'] == 'isnotanswer') { |
||
| 1403 | $searchfilterisnotanswer++; |
||
| 1404 | $searchhead .= '! /References.*@.*/'; |
||
| 1405 | } |
||
| 1406 | |||
| 1407 | if ($rule['type'] == 'replyto') { |
||
| 1408 | $searchfilterreplyto++; |
||
| 1409 | $rulesreplyto[] = $rule['rulevalue']; |
||
| 1410 | $searchhead .= '/Reply-To.*' . preg_quote($rule['rulevalue'], '/') . '/'; |
||
| 1411 | } |
||
| 1412 | } |
||
| 1413 | |||
| 1414 | if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined. |
||
| 1415 | $fromdate = 0; |
||
| 1416 | if ($this->datelastok) { |
||
| 1417 | $fromdate = $this->datelastok; |
||
| 1418 | } |
||
| 1419 | if ($fromdate > 0) { |
||
| 1420 | // $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10) |
||
| 1421 | array_push($criteria, array("SINCE" => date('j-M-Y', $fromdate - 1))); |
||
| 1422 | } |
||
| 1423 | //$search.=($search?' ':'').'SINCE 8-Apr-2022'; |
||
| 1424 | } |
||
| 1425 | |||
| 1426 | dol_syslog("IMAP search string = " . var_export($criteria, true)); |
||
| 1427 | $search = var_export($criteria, true); |
||
| 1428 | } else { |
||
| 1429 | // Use native IMAP functions |
||
| 1430 | $search = 'UNDELETED'; // Seems not supported by some servers |
||
| 1431 | foreach ($this->filters as $rule) { |
||
| 1432 | if (empty($rule['status'])) { |
||
| 1433 | continue; |
||
| 1434 | } |
||
| 1435 | |||
| 1436 | // Forge the IMAP search string. |
||
| 1437 | // See https://www.rfc-editor.org/rfc/rfc3501 |
||
| 1438 | |||
| 1439 | $not = ''; |
||
| 1440 | if (!empty($rule['rulevalue']) && strpos($rule['rulevalue'], '!') === 0) { |
||
| 1441 | // The value start with !, so we exclude the criteria |
||
| 1442 | $not = 'NOT '; |
||
| 1443 | // Then remove the ! from the string for next filters |
||
| 1444 | $rule['rulevalue'] = substr($rule['rulevalue'], 1); |
||
| 1445 | } |
||
| 1446 | |||
| 1447 | if ($rule['type'] == 'from') { |
||
| 1448 | $tmprulevaluearray = explode('*', $rule['rulevalue']); // Search on abc*def means searching on 'abc' and on 'def' |
||
| 1449 | if (count($tmprulevaluearray) >= 2) { |
||
| 1450 | foreach ($tmprulevaluearray as $tmprulevalue) { |
||
| 1451 | $search .= ($search ? ' ' : '') . $not . 'FROM "' . str_replace('"', '', $tmprulevalue) . '"'; |
||
| 1452 | } |
||
| 1453 | } else { |
||
| 1454 | $search .= ($search ? ' ' : '') . $not . 'FROM "' . str_replace('"', '', $rule['rulevalue']) . '"'; |
||
| 1455 | } |
||
| 1456 | } |
||
| 1457 | if ($rule['type'] == 'to') { |
||
| 1458 | $tmprulevaluearray = explode('*', $rule['rulevalue']); // Search on abc*def means searching on 'abc' and on 'def' |
||
| 1459 | if (count($tmprulevaluearray) >= 2) { |
||
| 1460 | foreach ($tmprulevaluearray as $tmprulevalue) { |
||
| 1461 | $search .= ($search ? ' ' : '') . $not . 'TO "' . str_replace('"', '', $tmprulevalue) . '"'; |
||
| 1462 | } |
||
| 1463 | } else { |
||
| 1464 | $search .= ($search ? ' ' : '') . $not . 'TO "' . str_replace('"', '', $rule['rulevalue']) . '"'; |
||
| 1465 | } |
||
| 1466 | } |
||
| 1467 | if ($rule['type'] == 'bcc') { |
||
| 1468 | $search .= ($search ? ' ' : '') . $not . 'BCC'; |
||
| 1469 | } |
||
| 1470 | if ($rule['type'] == 'cc') { |
||
| 1471 | $search .= ($search ? ' ' : '') . $not . 'CC'; |
||
| 1472 | } |
||
| 1473 | if ($rule['type'] == 'subject') { |
||
| 1474 | if ($not) { |
||
| 1475 | //$search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"'; |
||
| 1476 | $searchfilterexcludesubjectarray[] = $rule['rulevalue']; |
||
| 1477 | } else { |
||
| 1478 | $search .= ($search ? ' ' : '') . 'SUBJECT "' . str_replace('"', '', $rule['rulevalue']) . '"'; |
||
| 1479 | } |
||
| 1480 | } |
||
| 1481 | if ($rule['type'] == 'body') { |
||
| 1482 | if ($not) { |
||
| 1483 | //$search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"'; |
||
| 1484 | $searchfilterexcludebodyarray[] = $rule['rulevalue']; |
||
| 1485 | } else { |
||
| 1486 | // Warning: Google doesn't implement IMAP properly, and only matches whole words, |
||
| 1487 | $search .= ($search ? ' ' : '') . 'BODY "' . str_replace('"', '', $rule['rulevalue']) . '"'; |
||
| 1488 | } |
||
| 1489 | } |
||
| 1490 | if ($rule['type'] == 'header') { |
||
| 1491 | $search .= ($search ? ' ' : '') . $not . 'HEADER ' . $rule['rulevalue']; |
||
| 1492 | } |
||
| 1493 | |||
| 1494 | /* seems not used */ |
||
| 1495 | /* |
||
| 1496 | if ($rule['type'] == 'notinsubject') { |
||
| 1497 | $search .= ($search ? ' ' : '').'NOT SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"'; |
||
| 1498 | } |
||
| 1499 | if ($rule['type'] == 'notinbody') { |
||
| 1500 | $search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"'; |
||
| 1501 | }*/ |
||
| 1502 | |||
| 1503 | if ($rule['type'] == 'seen') { |
||
| 1504 | $search .= ($search ? ' ' : '') . $not . 'SEEN'; |
||
| 1505 | } |
||
| 1506 | if ($rule['type'] == 'unseen') { |
||
| 1507 | $search .= ($search ? ' ' : '') . $not . 'UNSEEN'; |
||
| 1508 | } |
||
| 1509 | if ($rule['type'] == 'unanswered') { |
||
| 1510 | $search .= ($search ? ' ' : '') . $not . 'UNANSWERED'; |
||
| 1511 | } |
||
| 1512 | if ($rule['type'] == 'answered') { |
||
| 1513 | $search .= ($search ? ' ' : '') . $not . 'ANSWERED'; |
||
| 1514 | } |
||
| 1515 | if ($rule['type'] == 'smaller') { |
||
| 1516 | $search .= ($search ? ' ' : '') . $not . 'SMALLER "' . str_replace('"', '', $rule['rulevalue']) . '"'; |
||
| 1517 | } |
||
| 1518 | if ($rule['type'] == 'larger') { |
||
| 1519 | $search .= ($search ? ' ' : '') . $not . 'LARGER "' . str_replace('"', '', $rule['rulevalue']) . '"'; |
||
| 1520 | } |
||
| 1521 | |||
| 1522 | // Rules to filter after the search imap |
||
| 1523 | if ($rule['type'] == 'withtrackingidinmsgid') { |
||
| 1524 | $searchfilterdoltrackid++; |
||
| 1525 | $searchhead .= '/Message-ID.*@' . preg_quote($host, '/') . '/'; |
||
| 1526 | } |
||
| 1527 | if ($rule['type'] == 'withouttrackingidinmsgid') { |
||
| 1528 | $searchfilterdoltrackid++; |
||
| 1529 | $searchhead .= '/Message-ID.*@' . preg_quote($host, '/') . '/'; |
||
| 1530 | } |
||
| 1531 | if ($rule['type'] == 'withtrackingid') { |
||
| 1532 | $searchfilterdoltrackid++; |
||
| 1533 | $searchhead .= '/References.*@' . preg_quote($host, '/') . '/'; |
||
| 1534 | } |
||
| 1535 | if ($rule['type'] == 'withouttrackingid') { |
||
| 1536 | $searchfilternodoltrackid++; |
||
| 1537 | $searchhead .= '! /References.*@' . preg_quote($host, '/') . '/'; |
||
| 1538 | } |
||
| 1539 | |||
| 1540 | if ($rule['type'] == 'isanswer') { |
||
| 1541 | $searchfilterisanswer++; |
||
| 1542 | $searchhead .= '/References.*@.*/'; |
||
| 1543 | } |
||
| 1544 | if ($rule['type'] == 'isnotanswer') { |
||
| 1545 | $searchfilterisnotanswer++; |
||
| 1546 | $searchhead .= '! /References.*@.*/'; |
||
| 1547 | } |
||
| 1548 | |||
| 1549 | if ($rule['type'] == 'replyto') { |
||
| 1550 | $searchfilterreplyto++; |
||
| 1551 | $rulesreplyto[] = $rule['rulevalue']; |
||
| 1552 | $searchhead .= '/Reply-To.*' . preg_quote($rule['rulevalue'], '/') . '/'; |
||
| 1553 | } |
||
| 1554 | } |
||
| 1555 | |||
| 1556 | if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined. |
||
| 1557 | $fromdate = 0; |
||
| 1558 | if ($this->datelastok) { |
||
| 1559 | $fromdate = $this->datelastok; |
||
| 1560 | } |
||
| 1561 | if ($fromdate > 0) { |
||
| 1562 | $search .= ($search ? ' ' : '') . 'SINCE ' . date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10) |
||
| 1563 | } |
||
| 1564 | //$search.=($search?' ':'').'SINCE 8-Apr-2018'; |
||
| 1565 | } |
||
| 1566 | |||
| 1567 | dol_syslog("IMAP search string = " . $search); |
||
| 1568 | //var_dump($search); |
||
| 1569 | } |
||
| 1570 | |||
| 1571 | $nbemailprocessed = 0; |
||
| 1572 | $nbemailok = 0; |
||
| 1573 | $nbactiondone = 0; |
||
| 1574 | $charset = ($this->hostcharset ? $this->hostcharset : "UTF-8"); |
||
| 1575 | |||
| 1576 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1577 | try { |
||
| 1578 | // Uncomment this to output debug info |
||
| 1579 | //$client->getConnection()->enableDebug(); |
||
| 1580 | |||
| 1581 | $tmpsourcedir = $sourcedir; |
||
| 1582 | if (!getDolGlobalString('MAIL_DISABLE_UTF7_ENCODE_OF_DIR')) { |
||
| 1583 | $tmpsourcedir = $this->getEncodedUtf7($sourcedir); |
||
| 1584 | } |
||
| 1585 | |||
| 1586 | $f = $client->getFolders(false, $tmpsourcedir); // Note the search of directory do a search on sourcedir* |
||
| 1587 | if ($f) { |
||
| 1588 | $folder = $f[0]; |
||
| 1589 | if ($folder instanceof Webklex\PHPIMAP\Folder) { |
||
| 1590 | $Query = $folder->messages()->where($criteria); |
||
| 1591 | } else { |
||
| 1592 | $error++; |
||
| 1593 | $this->error = "Source directory " . $sourcedir . " not found"; |
||
| 1594 | $this->errors[] = $this->error; |
||
| 1595 | dol_syslog("EmailCollector::doCollectOneCollector " . $this->error, LOG_WARNING); |
||
| 1596 | return -1; |
||
| 1597 | } |
||
| 1598 | } else { |
||
| 1599 | $error++; |
||
| 1600 | $this->error = "Failed to execute getfolders"; |
||
| 1601 | $this->errors[] = $this->error; |
||
| 1602 | dol_syslog("EmailCollector::doCollectOneCollector " . $this->error, LOG_ERR); |
||
| 1603 | return -1; |
||
| 1604 | } |
||
| 1605 | } catch (InvalidWhereQueryCriteriaException $e) { |
||
| 1606 | $this->error = $e->getMessage(); |
||
| 1607 | $this->errors[] = $this->error; |
||
| 1608 | dol_syslog("EmailCollector::doCollectOneCollector " . $this->error, LOG_ERR); |
||
| 1609 | return -1; |
||
| 1610 | } catch (Exception $e) { |
||
| 1611 | $this->error = $e->getMessage(); |
||
| 1612 | $this->errors[] = $this->error; |
||
| 1613 | dol_syslog("EmailCollector::doCollectOneCollector " . $this->error, LOG_ERR); |
||
| 1614 | return -1; |
||
| 1615 | } |
||
| 1616 | |||
| 1617 | try { |
||
| 1618 | //var_dump($Query->count()); |
||
| 1619 | if ($mode > 0) { |
||
| 1620 | $Query->leaveUnread(); |
||
| 1621 | } |
||
| 1622 | $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder("asc")->get(); |
||
| 1623 | //var_dump($arrayofemail); |
||
| 1624 | } catch (Exception $e) { |
||
| 1625 | $this->error = $e->getMessage(); |
||
| 1626 | $this->errors[] = $this->error; |
||
| 1627 | dol_syslog("EmailCollector::doCollectOneCollector " . $this->error, LOG_ERR); |
||
| 1628 | return -1; |
||
| 1629 | } |
||
| 1630 | } else { |
||
| 1631 | // Scan IMAP dir (for native IMAP, the source dir is inside the $connection variable) |
||
| 1632 | $arrayofemail = imap_search($connection, $search, SE_UID, $charset); |
||
| 1633 | |||
| 1634 | if ($arrayofemail === false) { |
||
| 1635 | // Nothing found or search string not understood |
||
| 1636 | $mapoferrrors = imap_errors(); |
||
| 1637 | if ($mapoferrrors !== false) { |
||
| 1638 | $error++; |
||
| 1639 | $this->error = "Search string not understood - " . implode(',', $mapoferrrors); |
||
| 1640 | $this->errors[] = $this->error; |
||
| 1641 | } |
||
| 1642 | } |
||
| 1643 | } |
||
| 1644 | |||
| 1645 | $arrayofemailtodelete = array(); // Track email to delete to make the deletion at end. |
||
| 1646 | |||
| 1647 | // Loop on each email found |
||
| 1648 | if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) { |
||
| 1649 | // Loop to get part html and plain |
||
| 1650 | /* |
||
| 1651 | 0 multipart/mixed |
||
| 1652 | 1 multipart/alternative |
||
| 1653 | 1.1 text/plain |
||
| 1654 | 1.2 text/html |
||
| 1655 | 2 message/rfc822 |
||
| 1656 | 2 multipart/mixed |
||
| 1657 | 2.1 multipart/alternative |
||
| 1658 | 2.1.1 text/plain |
||
| 1659 | 2.1.2 text/html |
||
| 1660 | 2.2 message/rfc822 |
||
| 1661 | 2.2 multipart/alternative |
||
| 1662 | 2.2.1 text/plain |
||
| 1663 | 2.2.2 text/html |
||
| 1664 | */ |
||
| 1665 | dol_syslog("Start of loop on email", LOG_INFO, 1); |
||
| 1666 | |||
| 1667 | $iforemailloop = 0; |
||
| 1668 | foreach ($arrayofemail as $imapemail) { |
||
| 1669 | if ($nbemailprocessed > 1000) { |
||
| 1670 | break; // Do not process more than 1000 email per launch (this is a different protection than maxnbcollectedpercollect) |
||
| 1671 | } |
||
| 1672 | $iforemailloop++; |
||
| 1673 | |||
| 1674 | |||
| 1675 | // GET header and overview datas |
||
| 1676 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1677 | $header = $imapemail->getHeader()->raw; |
||
| 1678 | $overview = $imapemail->getAttributes(); |
||
| 1679 | } else { |
||
| 1680 | $header = imap_fetchheader($connection, $imapemail, FT_UID); |
||
| 1681 | $overview = imap_fetch_overview($connection, $imapemail, FT_UID); |
||
| 1682 | } |
||
| 1683 | |||
| 1684 | $header = preg_replace('/\r\n\s+/m', ' ', $header); // When a header line is on several lines, merge lines |
||
| 1685 | |||
| 1686 | $matches = array(); |
||
| 1687 | preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches); |
||
| 1688 | $headers = array_combine($matches[1], $matches[2]); |
||
| 1689 | //var_dump($headers);exit; |
||
| 1690 | |||
| 1691 | if (!empty($headers['in-reply-to']) && empty($headers['In-Reply-To'])) { |
||
| 1692 | $headers['In-Reply-To'] = $headers['in-reply-to']; |
||
| 1693 | } |
||
| 1694 | if (!empty($headers['references']) && empty($headers['References'])) { |
||
| 1695 | $headers['References'] = $headers['references']; |
||
| 1696 | } |
||
| 1697 | if (!empty($headers['message-id']) && empty($headers['Message-ID'])) { |
||
| 1698 | $headers['Message-ID'] = $headers['message-id']; |
||
| 1699 | } |
||
| 1700 | if (!empty($headers['subject']) && empty($headers['Subject'])) { |
||
| 1701 | $headers['Subject'] = $headers['subject']; |
||
| 1702 | } |
||
| 1703 | |||
| 1704 | $headers['Subject'] = $this->decodeSMTPSubject($headers['Subject']); |
||
| 1705 | |||
| 1706 | $emailto = $this->decodeSMTPSubject($overview[0]->to); |
||
| 1707 | |||
| 1708 | $operationslog .= '<br>** Process email #' . dol_escape_htmltag($iforemailloop); |
||
| 1709 | |||
| 1710 | if (getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1711 | /** @var Webklex\PHPIMAP\Message $imapemail */ |
||
| 1712 | // $operationslog .= " - ".dol_escape_htmltag((string) $imapemail); |
||
| 1713 | $msgid = str_replace(array('<', '>'), '', $overview['message_id']); |
||
| 1714 | } else { |
||
| 1715 | $operationslog .= " - " . dol_escape_htmltag((string) $imapemail); |
||
| 1716 | $msgid = str_replace(array('<', '>'), '', $overview[0]->message_id); |
||
| 1717 | } |
||
| 1718 | $operationslog .= " - MsgId: " . $msgid . " - References: " . dol_escape_htmltag($headers['References'] ?? '') . " - Subject: " . dol_escape_htmltag($headers['Subject']); |
||
| 1719 | |||
| 1720 | dol_syslog("-- Process email " . $iforemailloop . " References: " . ($headers['References'] ?? '') . " Subject: " . $headers['Subject']); |
||
| 1721 | |||
| 1722 | |||
| 1723 | $trackidfoundintorecipienttype = ''; |
||
| 1724 | $trackidfoundintorecipientid = 0; |
||
| 1725 | $reg = array(); |
||
| 1726 | // See also later list of all supported tags... |
||
| 1727 | // Note: "th[i]" to avoid matching a codespell suggestion to convert to "this". |
||
| 1728 | // TODO Add host after the @'.preg_quote($host, '/') |
||
| 1729 | if (preg_match('/\+(th[i]|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) { |
||
| 1730 | $trackidfoundintorecipienttype = $reg[1]; |
||
| 1731 | $trackidfoundintorecipientid = $reg[2]; |
||
| 1732 | } elseif (preg_match('/\+emailing-(\w+)@/', $emailto, $reg)) { // Can be 'emailing-test' or 'emailing-IdMailing-IdRecipient' |
||
| 1733 | $trackidfoundintorecipienttype = 'emailing'; |
||
| 1734 | $trackidfoundintorecipientid = $reg[1]; |
||
| 1735 | } |
||
| 1736 | |||
| 1737 | $trackidfoundintomsgidtype = ''; |
||
| 1738 | $trackidfoundintomsgidid = 0; |
||
| 1739 | $reg = array(); |
||
| 1740 | // See also later list of all supported tags... |
||
| 1741 | // Note: "th[i]" to avoid matching a codespell suggestion to convert to "this". |
||
| 1742 | // TODO Add host after the @ |
||
| 1743 | if (preg_match('/(?:[\+\-])(th[i]|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $msgid, $reg)) { |
||
| 1744 | $trackidfoundintomsgidtype = $reg[1]; |
||
| 1745 | $trackidfoundintomsgidid = $reg[2]; |
||
| 1746 | } elseif (preg_match('/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) { // Can be 'emailing-test' or 'emailing-IdMailing-IdRecipient' |
||
| 1747 | $trackidfoundintomsgidtype = 'emailing'; |
||
| 1748 | $trackidfoundintomsgidid = $reg[1]; |
||
| 1749 | } |
||
| 1750 | |||
| 1751 | // If there is an emailcollecter filter on trackid |
||
| 1752 | if ($searchfilterdoltrackid > 0) { |
||
| 1753 | if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) { |
||
| 1754 | if (empty($headers['References']) || !preg_match('/@' . preg_quote($host, '/') . '/', $headers['References'])) { |
||
| 1755 | $nbemailprocessed++; |
||
| 1756 | dol_syslog(" Discarded - No suffix in email recipient and no Header References found matching the signature of the application, so with a trackid coming from the application"); |
||
| 1757 | continue; // Exclude email |
||
| 1758 | } |
||
| 1759 | } |
||
| 1760 | } |
||
| 1761 | if ($searchfilternodoltrackid > 0) { |
||
| 1762 | if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($headers['References']) && preg_match('/@' . preg_quote($host, '/') . '/', $headers['References']))) { |
||
| 1763 | $nbemailprocessed++; |
||
| 1764 | dol_syslog(" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid"); |
||
| 1765 | continue; // Exclude email |
||
| 1766 | } |
||
| 1767 | } |
||
| 1768 | |||
| 1769 | if ($searchfilterisanswer > 0) { |
||
| 1770 | if (empty($headers['In-Reply-To'])) { |
||
| 1771 | $nbemailprocessed++; |
||
| 1772 | dol_syslog(" Discarded - Email is not an answer (no In-Reply-To header)"); |
||
| 1773 | continue; // Exclude email |
||
| 1774 | } |
||
| 1775 | $isanswer = 0; |
||
| 1776 | if (preg_match('/^(Re|AW)\s*:\s+/i', $headers['Subject'])) { |
||
| 1777 | $isanswer = 1; |
||
| 1778 | } |
||
| 1779 | if (getDolGlobalString('EMAILCOLLECTOR_USE_IN_REPLY_TO_TO_DETECT_ANSWERS')) { |
||
| 1780 | // Note: "In-Reply-To" to detect if mail is an answer of another mail is not reliable because we can have: |
||
| 1781 | // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer but may be NOT (for example a transfer of an email rewritten) |
||
| 1782 | if (!empty($headers['In-Reply-To'])) { |
||
| 1783 | $isanswer = 1; |
||
| 1784 | } |
||
| 1785 | } |
||
| 1786 | //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply |
||
| 1787 | //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1; |
||
| 1788 | |||
| 1789 | if (!$isanswer) { |
||
| 1790 | $nbemailprocessed++; |
||
| 1791 | dol_syslog(" Discarded - Email is not an answer (no RE prefix in subject)"); |
||
| 1792 | continue; // Exclude email |
||
| 1793 | } |
||
| 1794 | } |
||
| 1795 | if ($searchfilterisnotanswer > 0) { |
||
| 1796 | if (!empty($headers['In-Reply-To'])) { |
||
| 1797 | // Note: we can have |
||
| 1798 | // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewritten) |
||
| 1799 | $isanswer = 0; |
||
| 1800 | if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) { |
||
| 1801 | $isanswer = 1; |
||
| 1802 | } |
||
| 1803 | //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply |
||
| 1804 | //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1; |
||
| 1805 | if ($isanswer) { |
||
| 1806 | $nbemailprocessed++; |
||
| 1807 | dol_syslog(" Discarded - Email is an answer"); |
||
| 1808 | continue; // Exclude email |
||
| 1809 | } |
||
| 1810 | } |
||
| 1811 | } |
||
| 1812 | if ($searchfilterreplyto > 0) { |
||
| 1813 | if (!empty($headers['Reply-To'])) { |
||
| 1814 | $isreplytook = 0; |
||
| 1815 | foreach ($rulesreplyto as $key => $rulereplyto) { |
||
| 1816 | if (preg_match('/' . preg_quote($rulereplyto, '/') . '/', $headers['Reply-To'])) { |
||
| 1817 | $isreplytook++; |
||
| 1818 | } |
||
| 1819 | } |
||
| 1820 | |||
| 1821 | if (!$isreplytook || $isreplytook != count($rulesreplyto)) { |
||
| 1822 | $nbemailprocessed++; |
||
| 1823 | dol_syslog(" Discarded - Reply-to does not match"); |
||
| 1824 | continue; // Exclude email |
||
| 1825 | } |
||
| 1826 | } |
||
| 1827 | } |
||
| 1828 | |||
| 1829 | //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." selected<br>\n"; |
||
| 1830 | |||
| 1831 | $thirdpartystatic = new Societe($this->db); |
||
| 1832 | $contactstatic = new Contact($this->db); |
||
| 1833 | $projectstatic = new Project($this->db); |
||
| 1834 | |||
| 1835 | $nbactiondoneforemail = 0; |
||
| 1836 | $errorforemail = 0; |
||
| 1837 | $errorforactions = 0; |
||
| 1838 | $thirdpartyfoundby = ''; |
||
| 1839 | $contactfoundby = ''; |
||
| 1840 | $projectfoundby = ''; |
||
| 1841 | $ticketfoundby = ''; |
||
| 1842 | $candidaturefoundby = ''; |
||
| 1843 | |||
| 1844 | |||
| 1845 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1846 | dol_syslog("msgid=" . $overview['message_id'] . " date=" . dol_print_date($overview['date'], 'dayrfc', 'gmt') . " from=" . $overview['from'] . " to=" . $overview['to'] . " subject=" . $overview['subject']); |
||
| 1847 | |||
| 1848 | // Removed emojis |
||
| 1849 | $overview['subject'] = removeEmoji($overview['subject'], getDolGlobalInt('MAIN_EMAIL_COLLECTOR_ACCEPT_EMOJIS', 1)); |
||
| 1850 | } else { |
||
| 1851 | dol_syslog("msgid=" . $overview[0]->message_id . " date=" . dol_print_date($overview[0]->udate, 'dayrfc', 'gmt') . " from=" . $overview[0]->from . " to=" . $overview[0]->to . " subject=" . $overview[0]->subject); |
||
| 1852 | |||
| 1853 | $overview[0]->subject = $this->decodeSMTPSubject($overview[0]->subject); |
||
| 1854 | |||
| 1855 | $overview[0]->from = $this->decodeSMTPSubject($overview[0]->from); |
||
| 1856 | |||
| 1857 | // Removed emojis |
||
| 1858 | $overview[0]->subject = removeEmoji($overview[0]->subject, getDolGlobalInt('MAIN_EMAIL_COLLECTOR_ACCEPT_EMOJIS', 1)); |
||
| 1859 | } |
||
| 1860 | // GET IMAP email structure/content |
||
| 1861 | global $htmlmsg, $plainmsg, $charset, $attachments; |
||
| 1862 | |||
| 1863 | if (getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1864 | /** @var Webklex\PHPIMAP\Message $imapemail */ |
||
| 1865 | if ($imapemail->hasHTMLBody()) { |
||
| 1866 | $htmlmsg = $imapemail->getHTMLBody(); |
||
| 1867 | } |
||
| 1868 | if ($imapemail->hasTextBody()) { |
||
| 1869 | $plainmsg = $imapemail->getTextBody(); |
||
| 1870 | } |
||
| 1871 | if ($imapemail->hasAttachments()) { |
||
| 1872 | $attachments = $imapemail->getAttachments()->all(); |
||
| 1873 | } else { |
||
| 1874 | $attachments = []; |
||
| 1875 | } |
||
| 1876 | } else { |
||
| 1877 | $this->getmsg($connection, $imapemail); // This set global var $charset, $htmlmsg, $plainmsg, $attachments |
||
| 1878 | } |
||
| 1879 | '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments'; |
||
| 1880 | |||
| 1881 | //print $plainmsg; |
||
| 1882 | //var_dump($plainmsg); exit; |
||
| 1883 | |||
| 1884 | //$htmlmsg,$plainmsg,$charset,$attachments |
||
| 1885 | $messagetext = $plainmsg ? $plainmsg : dol_string_nohtmltag($htmlmsg, 0); |
||
| 1886 | // Removed emojis |
||
| 1887 | |||
| 1888 | if (utf8_valid($messagetext)) { |
||
| 1889 | $messagetext = removeEmoji($messagetext, getDolGlobalInt('MAIN_EMAIL_COLLECTOR_ACCEPT_EMOJIS', 1)); |
||
| 1890 | } else { |
||
| 1891 | $operationslog .= '<br>Discarded - Email body is not valid utf8'; |
||
| 1892 | dol_syslog(" Discarded - Email body is not valid utf8"); |
||
| 1893 | continue; // Exclude email |
||
| 1894 | } |
||
| 1895 | |||
| 1896 | if (!empty($searchfilterexcludebodyarray)) { |
||
| 1897 | foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) { |
||
| 1898 | if (preg_match('/' . preg_quote($searchfilterexcludebody, '/') . '/ms', $messagetext)) { |
||
| 1899 | $nbemailprocessed++; |
||
| 1900 | $operationslog .= '<br>Discarded - Email body contains string ' . $searchfilterexcludebody; |
||
| 1901 | dol_syslog(" Discarded - Email body contains string " . $searchfilterexcludebody); |
||
| 1902 | continue 2; // Exclude email |
||
| 1903 | } |
||
| 1904 | } |
||
| 1905 | } |
||
| 1906 | |||
| 1907 | //var_dump($plainmsg); |
||
| 1908 | //var_dump($htmlmsg); |
||
| 1909 | //var_dump($messagetext); |
||
| 1910 | //var_dump($charset); |
||
| 1911 | //var_dump($attachments); |
||
| 1912 | //exit; |
||
| 1913 | |||
| 1914 | // Parse IMAP email structure |
||
| 1915 | /* |
||
| 1916 | $structure = imap_fetchstructure($connection, $imapemail, FT_UID); |
||
| 1917 | |||
| 1918 | $partplain = $parthtml = -1; |
||
| 1919 | $encodingplain = $encodinghtml = ''; |
||
| 1920 | |||
| 1921 | $result = createPartArray($structure, ''); |
||
| 1922 | |||
| 1923 | foreach($result as $part) |
||
| 1924 | { |
||
| 1925 | // $part['part_object']->type seems 0 for content |
||
| 1926 | // $part['part_object']->type seems 5 for attachment |
||
| 1927 | if (empty($part['part_object'])) continue; |
||
| 1928 | if ($part['part_object']->subtype == 'HTML') |
||
| 1929 | { |
||
| 1930 | $parthtml=$part['part_number']; |
||
| 1931 | if ($part['part_object']->encoding == 4) |
||
| 1932 | { |
||
| 1933 | $encodinghtml = 'aaa'; |
||
| 1934 | } |
||
| 1935 | } |
||
| 1936 | if ($part['part_object']->subtype == 'PLAIN') |
||
| 1937 | { |
||
| 1938 | $partplain=$part['part_number']; |
||
| 1939 | if ($part['part_object']->encoding == 4) |
||
| 1940 | { |
||
| 1941 | $encodingplain = 'rr'; |
||
| 1942 | } |
||
| 1943 | } |
||
| 1944 | } |
||
| 1945 | //var_dump($result); |
||
| 1946 | //var_dump($partplain); |
||
| 1947 | //var_dump($parthtml); |
||
| 1948 | |||
| 1949 | //var_dump($structure); |
||
| 1950 | //var_dump($parthtml); |
||
| 1951 | //var_dump($partplain); |
||
| 1952 | |||
| 1953 | $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 1)), FT_PEEK|FTP_UID); |
||
| 1954 | */ |
||
| 1955 | |||
| 1956 | //var_dump($messagetext); |
||
| 1957 | //var_dump($structure->parts[0]->parts); |
||
| 1958 | //print $header; |
||
| 1959 | //print $messagetext; |
||
| 1960 | //exit; |
||
| 1961 | |||
| 1962 | $fromstring = ''; |
||
| 1963 | $replytostring = ''; |
||
| 1964 | |||
| 1965 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 1966 | $fromstring = $overview['from']; |
||
| 1967 | $replytostring = empty($overview['in_reply-to']) ? $headers['Reply-To'] : $overview['in_reply-to']; |
||
| 1968 | |||
| 1969 | $sender = $overview['sender']; |
||
| 1970 | $to = $overview['to']; |
||
| 1971 | $sendtocc = empty($overview['cc']) ? '' : $overview['cc']; |
||
| 1972 | $sendtobcc = empty($overview['bcc']) ? '' : $overview['bcc']; |
||
| 1973 | |||
| 1974 | $tmpdate = $overview['date']->toDate(); |
||
| 1975 | $tmptimezone = $tmpdate->getTimezone()->getName(); |
||
| 1976 | |||
| 1977 | $dateemail = dol_stringtotime((string) $overview['date'], 'gmt'); // if $overview['timezone'] is "+00:00" |
||
| 1978 | if (preg_match('/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) { |
||
| 1979 | if ($reg[1] == '+' && ($reg[2] != '00' || $reg[3] != '00')) { |
||
| 1980 | $dateemail -= (3600 * (int) $reg[2]); |
||
| 1981 | $dateemail -= (60 * (int) $reg[3]); |
||
| 1982 | } |
||
| 1983 | if ($reg[1] == '-' && ($reg[2] != '00' || $reg[3] != '00')) { |
||
| 1984 | $dateemail += (3600 * (int) $reg[2]); |
||
| 1985 | $dateemail += (60 * (int) $reg[3]); |
||
| 1986 | } |
||
| 1987 | } |
||
| 1988 | $subject = $overview['subject']; |
||
| 1989 | } else { |
||
| 1990 | $fromstring = $overview[0]->from; |
||
| 1991 | $replytostring = (!empty($overview['in_reply-to']) ? $overview['in_reply-to'] : (!empty($headers['Reply-To']) ? $headers['Reply-To'] : "")) ; |
||
| 1992 | |||
| 1993 | $sender = !empty($overview[0]->sender) ? $overview[0]->sender : ''; |
||
| 1994 | $to = $overview[0]->to; |
||
| 1995 | $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc : ''; |
||
| 1996 | $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc : ''; |
||
| 1997 | $dateemail = dol_stringtotime((string) $overview[0]->udate, 'gmt'); |
||
| 1998 | $subject = $overview[0]->subject; |
||
| 1999 | //var_dump($msgid);exit; |
||
| 2000 | } |
||
| 2001 | |||
| 2002 | if (!empty($searchfilterexcludesubjectarray)) { |
||
| 2003 | foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) { |
||
| 2004 | if (preg_match('/' . preg_quote($searchfilterexcludesubject, '/') . '/ms', $subject)) { |
||
| 2005 | $nbemailprocessed++; |
||
| 2006 | $operationslog .= '<br>Discarded - Email subject contains string ' . $searchfilterexcludesubject; |
||
| 2007 | dol_syslog(" Discarded - Email subject contains string " . $searchfilterexcludesubject); |
||
| 2008 | continue 2; // Exclude email |
||
| 2009 | } |
||
| 2010 | } |
||
| 2011 | } |
||
| 2012 | |||
| 2013 | $reg = array(); |
||
| 2014 | if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) { |
||
| 2015 | $from = $reg[2]; |
||
| 2016 | $fromtext = $reg[1]; |
||
| 2017 | } else { |
||
| 2018 | $from = $fromstring; |
||
| 2019 | $fromtext = ''; |
||
| 2020 | } |
||
| 2021 | if (preg_match('/^(.*)<(.*)>$/', $replytostring, $reg)) { |
||
| 2022 | $replyto = $reg[2]; |
||
| 2023 | $replytotext = $reg[1]; |
||
| 2024 | } else { |
||
| 2025 | $replyto = $replytostring; |
||
| 2026 | $replytotext = ''; |
||
| 2027 | } |
||
| 2028 | $fk_element_id = 0; |
||
| 2029 | $fk_element_type = ''; |
||
| 2030 | |||
| 2031 | |||
| 2032 | $this->db->begin(); |
||
| 2033 | |||
| 2034 | $contactid = 0; |
||
| 2035 | $thirdpartyid = 0; |
||
| 2036 | $projectid = 0; |
||
| 2037 | $ticketid = 0; |
||
| 2038 | |||
| 2039 | // Analyze TrackId in field References (already analyzed previously into the "To:" and "Message-Id"). |
||
| 2040 | // For example: |
||
| 2041 | // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e> |
||
| 2042 | // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e> |
||
| 2043 | // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e> |
||
| 2044 | $trackid = ''; |
||
| 2045 | $objectid = 0; |
||
| 2046 | $objectemail = null; |
||
| 2047 | |||
| 2048 | $reg = array(); |
||
| 2049 | $arrayofreferences = array(); |
||
| 2050 | if (!empty($headers['References'])) { |
||
| 2051 | $arrayofreferences = preg_split('/(,|\s+)/', $headers['References']); |
||
| 2052 | } |
||
| 2053 | if (!in_array('<' . $msgid . '>', $arrayofreferences)) { |
||
| 2054 | $arrayofreferences = array_merge($arrayofreferences, array('<' . $msgid . '>')); |
||
| 2055 | } |
||
| 2056 | // var_dump($headers['References']); |
||
| 2057 | // var_dump($arrayofreferences); |
||
| 2058 | |||
| 2059 | foreach ($arrayofreferences as $reference) { |
||
| 2060 | //print "Process mail ".$iforemailloop." email_msgid ".$msgid.", date ".dol_print_date($dateemail, 'dayhour', 'gmt').", subject ".$subject.", reference ".dol_escape_htmltag($reference)."<br>\n"; |
||
| 2061 | if (!empty($trackidfoundintorecipienttype)) { |
||
| 2062 | $resultsearchtrackid = -1; // trackid found |
||
| 2063 | $reg[1] = $trackidfoundintorecipienttype; |
||
| 2064 | $reg[2] = $trackidfoundintorecipientid; |
||
| 2065 | } elseif (!empty($trackidfoundintomsgidtype)) { |
||
| 2066 | $resultsearchtrackid = -1; // trackid found |
||
| 2067 | $reg[1] = $trackidfoundintomsgidtype; |
||
| 2068 | $reg[2] = $trackidfoundintomsgidid; |
||
| 2069 | } else { |
||
| 2070 | $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@' . preg_quote($host, '/') . '/', $reference, $reg); // trackid found or not |
||
| 2071 | if (empty($resultsearchtrackid) && getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE')) { |
||
| 2072 | $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@' . preg_quote(getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE'), '/') . '/', $reference, $reg); // trackid found |
||
| 2073 | } |
||
| 2074 | } |
||
| 2075 | |||
| 2076 | if (!empty($resultsearchtrackid)) { |
||
| 2077 | // We found a tracker (in recipient email or msgid or into a Reference matching the Dolibarr server) |
||
| 2078 | $trackid = $reg[1] . $reg[2]; |
||
| 2079 | |||
| 2080 | $objectid = $reg[2]; |
||
| 2081 | // See also list into interface_50_modAgenda_ActionsAuto |
||
| 2082 | if ($reg[1] == 'thi') { // Third-party |
||
| 2083 | $objectemail = new Societe($this->db); |
||
| 2084 | } |
||
| 2085 | if ($reg[1] == 'ctc') { // Contact |
||
| 2086 | $objectemail = new Contact($this->db); |
||
| 2087 | } |
||
| 2088 | if ($reg[1] == 'inv') { // Customer Invoice |
||
| 2089 | $objectemail = new Facture($this->db); |
||
| 2090 | } |
||
| 2091 | if ($reg[1] == 'sinv') { // Supplier Invoice |
||
| 2092 | $objectemail = new FactureFournisseur($this->db); |
||
| 2093 | } |
||
| 2094 | if ($reg[1] == 'pro') { // Customer Proposal |
||
| 2095 | $objectemail = new Propal($this->db); |
||
| 2096 | } |
||
| 2097 | if ($reg[1] == 'ord') { // Sale Order |
||
| 2098 | $objectemail = new Commande($this->db); |
||
| 2099 | } |
||
| 2100 | if ($reg[1] == 'shi') { // Shipment |
||
| 2101 | $objectemail = new Expedition($this->db); |
||
| 2102 | } |
||
| 2103 | if ($reg[1] == 'spro') { // Supplier Proposal |
||
| 2104 | $objectemail = new SupplierProposal($this->db); |
||
| 2105 | } |
||
| 2106 | if ($reg[1] == 'sord') { // Supplier Order |
||
| 2107 | $objectemail = new CommandeFournisseur($this->db); |
||
| 2108 | } |
||
| 2109 | if ($reg[1] == 'rec') { // Reception |
||
| 2110 | $objectemail = new Reception($this->db); |
||
| 2111 | } |
||
| 2112 | if ($reg[1] == 'proj') { // Project |
||
| 2113 | $objectemail = new Project($this->db); |
||
| 2114 | $projectfoundby = 'TrackID dolibarr-' . $trackid . '@...'; |
||
| 2115 | } |
||
| 2116 | if ($reg[1] == 'tas') { // Task |
||
| 2117 | $objectemail = new Task($this->db); |
||
| 2118 | } |
||
| 2119 | if ($reg[1] == 'con') { // Contact |
||
| 2120 | $objectemail = new Contact($this->db); |
||
| 2121 | } |
||
| 2122 | if ($reg[1] == 'use') { // User |
||
| 2123 | $objectemail = new User($this->db); |
||
| 2124 | } |
||
| 2125 | if ($reg[1] == 'tic') { // Ticket |
||
| 2126 | $objectemail = new Ticket($this->db); |
||
| 2127 | $ticketfoundby = 'TrackID dolibarr-' . $trackid . '@...'; |
||
| 2128 | } |
||
| 2129 | if ($reg[1] == 'recruitmentcandidature') { // Recruiting Candidate |
||
| 2130 | $objectemail = new RecruitmentCandidature($this->db); |
||
| 2131 | $candidaturefoundby = 'TrackID dolibarr-' . $trackid . '@...'; |
||
| 2132 | } |
||
| 2133 | if ($reg[1] == 'mem') { // Member |
||
| 2134 | $objectemail = new Adherent($this->db); |
||
| 2135 | } |
||
| 2136 | /*if ($reg[1] == 'leav') { // Leave / Holiday |
||
| 2137 | $objectemail = new Holiday($db); |
||
| 2138 | } |
||
| 2139 | if ($reg[1] == 'exp') { // ExpenseReport |
||
| 2140 | $objectemail = new ExpenseReport($db); |
||
| 2141 | }*/ |
||
| 2142 | } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) { |
||
| 2143 | // This is an external reference, we check if we have it in our database |
||
| 2144 | if (is_null($objectemail) && isModEnabled('ticket')) { |
||
| 2145 | $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "ticket"; |
||
| 2146 | $sql .= " WHERE email_msgid = '" . $this->db->escape($reg[1]) . "' OR origin_references like '%" . $this->db->escape($this->db->escapeforlike($reg[1])) . "%'"; |
||
| 2147 | $resql = $this->db->query($sql); |
||
| 2148 | if ($resql) { |
||
| 2149 | $obj = $this->db->fetch_object($resql); |
||
| 2150 | if ($obj) { |
||
| 2151 | $objectid = $obj->rowid; |
||
| 2152 | $objectemail = new Ticket($this->db); |
||
| 2153 | $ticketfoundby = $langs->transnoentitiesnoconv("EmailMsgID") . ' (' . $reg[1] . ')'; |
||
| 2154 | } |
||
| 2155 | } else { |
||
| 2156 | $errorforemail++; |
||
| 2157 | } |
||
| 2158 | } |
||
| 2159 | |||
| 2160 | if (!is_object($objectemail) && isModEnabled('project')) { |
||
| 2161 | $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "projet where email_msgid = '" . $this->db->escape($reg[1]) . "'"; |
||
| 2162 | $resql = $this->db->query($sql); |
||
| 2163 | if ($resql) { |
||
| 2164 | $obj = $this->db->fetch_object($resql); |
||
| 2165 | if ($obj) { |
||
| 2166 | $objectid = $obj->rowid; |
||
| 2167 | $objectemail = new Project($this->db); |
||
| 2168 | $projectfoundby = $langs->transnoentitiesnoconv("EmailMsgID") . ' (' . $reg[1] . ')'; |
||
| 2169 | } |
||
| 2170 | } else { |
||
| 2171 | $errorforemail++; |
||
| 2172 | } |
||
| 2173 | } |
||
| 2174 | |||
| 2175 | if (!is_object($objectemail) && isModEnabled('recruitment')) { |
||
| 2176 | $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "recruitment_recruitmentcandidature where email_msgid = '" . $this->db->escape($reg[1]) . "'"; |
||
| 2177 | $resql = $this->db->query($sql); |
||
| 2178 | if ($resql) { |
||
| 2179 | $obj = $this->db->fetch_object($resql); |
||
| 2180 | if ($obj) { |
||
| 2181 | $objectid = $obj->rowid; |
||
| 2182 | $objectemail = new RecruitmentCandidature($this->db); |
||
| 2183 | $candidaturefoundby = $langs->transnoentitiesnoconv("EmailMsgID") . ' (' . $reg[1] . ')'; |
||
| 2184 | } |
||
| 2185 | } else { |
||
| 2186 | $errorforemail++; |
||
| 2187 | } |
||
| 2188 | } |
||
| 2189 | } |
||
| 2190 | |||
| 2191 | // Load object linked to email |
||
| 2192 | if (is_object($objectemail)) { |
||
| 2193 | $result = $objectemail->fetch($objectid); |
||
| 2194 | if ($result > 0) { |
||
| 2195 | $fk_element_id = $objectemail->id; |
||
| 2196 | $fk_element_type = $objectemail->element; |
||
| 2197 | // Fix fk_element_type |
||
| 2198 | if ($fk_element_type == 'facture') { |
||
| 2199 | $fk_element_type = 'invoice'; |
||
| 2200 | } |
||
| 2201 | |||
| 2202 | if (get_class($objectemail) != 'Societe') { |
||
| 2203 | $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid; |
||
| 2204 | } else { |
||
| 2205 | $thirdpartyid = $objectemail->id; |
||
| 2206 | } |
||
| 2207 | |||
| 2208 | if (get_class($objectemail) != 'Contact') { |
||
| 2209 | $contactid = $objectemail->fk_socpeople; |
||
| 2210 | } else { |
||
| 2211 | $contactid = $objectemail->id; |
||
| 2212 | } |
||
| 2213 | |||
| 2214 | if (get_class($objectemail) != 'Project') { |
||
| 2215 | $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet; |
||
| 2216 | } else { |
||
| 2217 | $projectid = $objectemail->id; |
||
| 2218 | } |
||
| 2219 | |||
| 2220 | if (get_class($objectemail) == 'Ticket') { |
||
| 2221 | $ticketid = $objectemail->id; |
||
| 2222 | |||
| 2223 | $changeonticket_references = false; |
||
| 2224 | if (empty($trackid)) { |
||
| 2225 | $trackid = $objectemail->track_id; |
||
| 2226 | } |
||
| 2227 | if (empty($objectemail->origin_references)) { |
||
| 2228 | $objectemail->origin_references = $headers['References']; |
||
| 2229 | $changeonticket_references = true; |
||
| 2230 | } else { |
||
| 2231 | foreach ($arrayofreferences as $key => $referencetmp) { |
||
| 2232 | if (!str_contains($objectemail->origin_references, $referencetmp)) { |
||
| 2233 | $objectemail->origin_references .= " " . $referencetmp; |
||
| 2234 | $changeonticket_references = true; |
||
| 2235 | } |
||
| 2236 | } |
||
| 2237 | } |
||
| 2238 | if ($changeonticket_references) { |
||
| 2239 | $objectemail->update($user); |
||
| 2240 | } |
||
| 2241 | } |
||
| 2242 | } |
||
| 2243 | } |
||
| 2244 | |||
| 2245 | // Project |
||
| 2246 | if ($projectid > 0) { |
||
| 2247 | $result = $projectstatic->fetch($projectid); |
||
| 2248 | if ($result <= 0) { |
||
| 2249 | $projectstatic->id = 0; |
||
| 2250 | } else { |
||
| 2251 | $projectid = $projectstatic->id; |
||
| 2252 | if ($trackid) { |
||
| 2253 | $projectfoundby = 'trackid (' . $trackid . ')'; |
||
| 2254 | } |
||
| 2255 | if (empty($contactid)) { |
||
| 2256 | $contactid = $projectstatic->fk_contact; |
||
| 2257 | } |
||
| 2258 | if (empty($thirdpartyid)) { |
||
| 2259 | $thirdpartyid = $projectstatic->fk_soc; |
||
| 2260 | } |
||
| 2261 | } |
||
| 2262 | } |
||
| 2263 | // Contact |
||
| 2264 | if ($contactid > 0) { |
||
| 2265 | $result = $contactstatic->fetch($contactid); |
||
| 2266 | if ($result <= 0) { |
||
| 2267 | $contactstatic->id = 0; |
||
| 2268 | } else { |
||
| 2269 | $contactid = $contactstatic->id; |
||
| 2270 | if ($trackid) { |
||
| 2271 | $contactfoundby = 'trackid (' . $trackid . ')'; |
||
| 2272 | } |
||
| 2273 | if (empty($thirdpartyid)) { |
||
| 2274 | $thirdpartyid = $contactstatic->fk_soc; |
||
| 2275 | } |
||
| 2276 | } |
||
| 2277 | } |
||
| 2278 | // Thirdparty |
||
| 2279 | if ($thirdpartyid > 0) { |
||
| 2280 | $result = $thirdpartystatic->fetch($thirdpartyid); |
||
| 2281 | if ($result <= 0) { |
||
| 2282 | $thirdpartystatic->id = 0; |
||
| 2283 | } else { |
||
| 2284 | $thirdpartyid = $thirdpartystatic->id; |
||
| 2285 | if ($trackid) { |
||
| 2286 | $thirdpartyfoundby = 'trackid (' . $trackid . ')'; |
||
| 2287 | } |
||
| 2288 | } |
||
| 2289 | } |
||
| 2290 | |||
| 2291 | if (is_object($objectemail)) { |
||
| 2292 | break; // Exit loop of references. We already found an accurate reference |
||
| 2293 | } |
||
| 2294 | } |
||
| 2295 | |||
| 2296 | if (empty($contactid)) { // Try to find contact using email |
||
| 2297 | $result = $contactstatic->fetch(0, null, '', $from); |
||
| 2298 | |||
| 2299 | if ($result > 0) { |
||
| 2300 | dol_syslog("We found a contact with the email " . $from); |
||
| 2301 | $contactid = $contactstatic->id; |
||
| 2302 | $contactfoundby = 'email of contact (' . $from . ')'; |
||
| 2303 | if (empty($thirdpartyid) && $contactstatic->socid > 0) { |
||
| 2304 | $result = $thirdpartystatic->fetch($contactstatic->socid); |
||
| 2305 | if ($result > 0) { |
||
| 2306 | $thirdpartyid = $thirdpartystatic->id; |
||
| 2307 | $thirdpartyfoundby = 'email of contact (' . $from . ')'; |
||
| 2308 | } |
||
| 2309 | } |
||
| 2310 | } |
||
| 2311 | } |
||
| 2312 | |||
| 2313 | if (empty($thirdpartyid)) { // Try to find thirdparty using email |
||
| 2314 | $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from); |
||
| 2315 | if ($result > 0) { |
||
| 2316 | dol_syslog("We found a thirdparty with the email " . $from); |
||
| 2317 | $thirdpartyid = $thirdpartystatic->id; |
||
| 2318 | $thirdpartyfoundby = 'email (' . $from . ')'; |
||
| 2319 | } |
||
| 2320 | } |
||
| 2321 | |||
| 2322 | /* |
||
| 2323 | if ($replyto) { |
||
| 2324 | if (empty($contactid)) { // Try to find contact using email |
||
| 2325 | $result = $contactstatic->fetch(0, null, '', $replyto); |
||
| 2326 | |||
| 2327 | if ($result > 0) { |
||
| 2328 | dol_syslog("We found a contact with the email ".$replyto); |
||
| 2329 | $contactid = $contactstatic->id; |
||
| 2330 | $contactfoundby = 'email of contact ('.$replyto.')'; |
||
| 2331 | if (empty($thirdpartyid) && $contactstatic->socid > 0) { |
||
| 2332 | $result = $thirdpartystatic->fetch($contactstatic->socid); |
||
| 2333 | if ($result > 0) { |
||
| 2334 | $thirdpartyid = $thirdpartystatic->id; |
||
| 2335 | $thirdpartyfoundby = 'email of contact ('.$replyto.')'; |
||
| 2336 | } |
||
| 2337 | } |
||
| 2338 | } |
||
| 2339 | } |
||
| 2340 | |||
| 2341 | if (empty($thirdpartyid)) { // Try to find thirdparty using email |
||
| 2342 | $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $replyto); |
||
| 2343 | if ($result > 0) { |
||
| 2344 | dol_syslog("We found a thirdparty with the email ".$replyto); |
||
| 2345 | $thirdpartyid = $thirdpartystatic->id; |
||
| 2346 | $thirdpartyfoundby = 'email ('.$replyto.')'; |
||
| 2347 | } |
||
| 2348 | } |
||
| 2349 | } |
||
| 2350 | */ |
||
| 2351 | |||
| 2352 | // Do operations (extract variables and creating data) |
||
| 2353 | if ($mode < 2) { // 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates |
||
| 2354 | foreach ($this->actions as $operation) { |
||
| 2355 | $errorforthisaction = 0; |
||
| 2356 | $ticketalreadyexists = 0; |
||
| 2357 | if ($errorforactions) { |
||
| 2358 | break; |
||
| 2359 | } |
||
| 2360 | if (empty($operation['status'])) { |
||
| 2361 | continue; |
||
| 2362 | } |
||
| 2363 | |||
| 2364 | $operationslog .= '<br>* Process operation ' . $operation['type']; |
||
| 2365 | |||
| 2366 | // Make Operation |
||
| 2367 | dol_syslog("Execute action " . $operation['type'] . " actionparam=" . $operation['actionparam'] . ' thirdpartystatic->id=' . $thirdpartystatic->id . ' contactstatic->id=' . $contactstatic->id . ' projectstatic->id=' . $projectstatic->id); |
||
| 2368 | dol_syslog("Execute action fk_element_id=" . $fk_element_id . " fk_element_type=" . $fk_element_type); // If a Dolibarr tracker id is found, we should now the id of object |
||
| 2369 | |||
| 2370 | // Try to guess if this is an email in or out. |
||
| 2371 | $actioncode = 'EMAIL_IN'; |
||
| 2372 | // If we scan the Sent box, we use the code for out email |
||
| 2373 | if (preg_match('/Sent$/', $sourcedir) || preg_match('/envoyés$/i', $sourcedir)) { |
||
| 2374 | $actioncode = 'EMAIL'; |
||
| 2375 | } |
||
| 2376 | // If sender is in the list MAIL_FROM_EMAILS_TO_CONSIDER_SENDING |
||
| 2377 | $arrayofemailtoconsideresender = explode(',', getDolGlobalString('MAIL_FROM_EMAILS_TO_CONSIDER_SENDING')); |
||
| 2378 | foreach ($arrayofemailtoconsideresender as $emailtoconsidersender) { |
||
| 2379 | if (preg_match('/' . preg_quote($emailtoconsidersender, '/') . '/', $fromstring)) { |
||
| 2380 | $actioncode = 'EMAIL'; |
||
| 2381 | } |
||
| 2382 | } |
||
| 2383 | $operationslog .= '<br>Email will have actioncode=' . $actioncode; |
||
| 2384 | |||
| 2385 | $description = $descriptiontitle = $descriptionmeta = $descriptionfull = ''; |
||
| 2386 | |||
| 2387 | $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid); |
||
| 2388 | $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic") . ' : ' . dol_escape_htmltag($subject)); |
||
| 2389 | $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailDate") . ($langs->trans("MailDate") != 'Date' ? ' (Date)' : '') . ' : ' . dol_escape_htmltag(dol_print_date($dateemail, "dayhourtext", "gmt"))); |
||
| 2390 | $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom") . ($langs->trans("MailFrom") != 'From' ? ' (From)' : '') . ' : ' . dol_escape_htmltag($fromstring)); |
||
| 2391 | if ($sender) { |
||
| 2392 | $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender") . ($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '') . ' : ' . dol_escape_htmltag($sender)); |
||
| 2393 | } |
||
| 2394 | $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo") . ($langs->trans("MailTo") != 'To' ? ' (To)' : '') . ' : ' . dol_escape_htmltag($to)); |
||
| 2395 | if ($replyto) { |
||
| 2396 | $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailReply") . ($langs->trans("MailReply") != 'Reply to' ? ' (Reply to)' : '') . ' : ' . dol_escape_htmltag($replyto)); |
||
| 2397 | } |
||
| 2398 | if ($sendtocc) { |
||
| 2399 | $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC") . ($langs->trans("MailCC") != 'CC' ? ' (CC)' : '') . ' : ' . dol_escape_htmltag($sendtocc)); |
||
| 2400 | } |
||
| 2401 | |||
| 2402 | if ($operation['type'] == 'ticket') { |
||
| 2403 | // Verify if ticket already exists to fall back on the right operation |
||
| 2404 | $tickettocreate = new Ticket($this->db); |
||
| 2405 | $errorfetchticket = 0; |
||
| 2406 | $alreadycreated = 0; |
||
| 2407 | if (!empty($trackid)) { |
||
| 2408 | $alreadycreated = $tickettocreate->fetch(0, '', $trackid); |
||
| 2409 | } |
||
| 2410 | if ($alreadycreated == 0 && !empty($msgid)) { |
||
| 2411 | $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid); |
||
| 2412 | } |
||
| 2413 | if ($alreadycreated < 0) { |
||
| 2414 | $errorfetchticket++; |
||
| 2415 | } |
||
| 2416 | if (empty($errorfetchticket)) { |
||
| 2417 | if ($alreadycreated == 0) { |
||
| 2418 | $operationslog .= '<br>Ticket not found using trackid=' . $trackid . ' or msgid=' . $msgid; |
||
| 2419 | $ticketalreadyexists = 0; |
||
| 2420 | } else { |
||
| 2421 | $operationslog .= '<br>Ticket already found using trackid=' . $trackid . ' or msgid=' . $msgid; // We change the operation type to do |
||
| 2422 | $ticketalreadyexists = 1; |
||
| 2423 | $operation['type'] = 'recordevent'; |
||
| 2424 | } |
||
| 2425 | } else { |
||
| 2426 | $ticketalreadyexists = -1; |
||
| 2427 | } |
||
| 2428 | } |
||
| 2429 | |||
| 2430 | // Process now the operation type |
||
| 2431 | |||
| 2432 | // Search and create thirdparty |
||
| 2433 | if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') { |
||
| 2434 | if (empty($operation['actionparam'])) { |
||
| 2435 | $errorforactions++; |
||
| 2436 | $this->error = "Action loadthirdparty or loadandcreatethirdparty has empty parameter. Must be a rule like 'name=HEADER:^From:(.*);' or 'name=SET:xxx' or 'name=EXTRACT:(body|subject):regex where 'name' can be replaced with 'id' or 'email' to define how to set or extract data. More properties can also be set, for example client=SET:2;"; |
||
| 2437 | $this->errors[] = $this->error; |
||
| 2438 | } else { |
||
| 2439 | $actionparam = $operation['actionparam']; |
||
| 2440 | $idtouseforthirdparty = ''; |
||
| 2441 | $nametouseforthirdparty = ''; |
||
| 2442 | $emailtouseforthirdparty = ''; |
||
| 2443 | $namealiastouseforthirdparty = ''; |
||
| 2444 | |||
| 2445 | $operationslog .= '<br>Loop on each property to set into actionparam'; |
||
| 2446 | |||
| 2447 | // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....' |
||
| 2448 | $arrayvaluetouse = dolExplodeIntoArray($actionparam, '(\n\r|\r|\n|;)', '='); |
||
| 2449 | foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) { |
||
| 2450 | $sourcestring = ''; |
||
| 2451 | $sourcefield = ''; |
||
| 2452 | $regexstring = ''; |
||
| 2453 | $regforregex = array(); |
||
| 2454 | |||
| 2455 | if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) { |
||
| 2456 | $sourcefield = $regforregex[1]; |
||
| 2457 | $regexstring = $regforregex[2]; |
||
| 2458 | } |
||
| 2459 | |||
| 2460 | if (!empty($sourcefield) && !empty($regexstring)) { |
||
| 2461 | if (strtolower($sourcefield) == 'body') { |
||
| 2462 | $sourcestring = $messagetext; |
||
| 2463 | } elseif (strtolower($sourcefield) == 'subject') { |
||
| 2464 | $sourcestring = $subject; |
||
| 2465 | } elseif (strtolower($sourcefield) == 'header') { |
||
| 2466 | $sourcestring = $header; |
||
| 2467 | } |
||
| 2468 | |||
| 2469 | if ($sourcestring) { |
||
| 2470 | $regforval = array(); |
||
| 2471 | //var_dump($regexstring);var_dump($sourcestring); |
||
| 2472 | if (preg_match('/' . $regexstring . '/ms', $sourcestring, $regforval)) { |
||
| 2473 | //var_dump($regforval[count($regforval)-1]);exit; |
||
| 2474 | // Overwrite param $tmpproperty |
||
| 2475 | if ($propertytooverwrite == 'id') { |
||
| 2476 | $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; |
||
| 2477 | |||
| 2478 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' Regex /' . dol_escape_htmltag($regexstring) . '/ms into ' . strtoupper($sourcefield) . ' -> Found idtouseforthirdparty=' . dol_escape_htmltag($idtouseforthirdparty); |
||
| 2479 | } elseif ($propertytooverwrite == 'email') { |
||
| 2480 | $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; |
||
| 2481 | |||
| 2482 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' Regex /' . dol_escape_htmltag($regexstring) . '/ms into ' . strtoupper($sourcefield) . ' -> Found emailtouseforthirdparty=' . dol_escape_htmltag($emailtouseforthirdparty); |
||
| 2483 | } elseif ($propertytooverwrite == 'name') { |
||
| 2484 | $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; |
||
| 2485 | |||
| 2486 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' Regex /' . dol_escape_htmltag($regexstring) . '/ms into ' . strtoupper($sourcefield) . ' -> Found nametouseforthirdparty=' . dol_escape_htmltag($nametouseforthirdparty); |
||
| 2487 | } elseif ($propertytooverwrite == 'name_alias') { |
||
| 2488 | $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; |
||
| 2489 | |||
| 2490 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' Regex /' . dol_escape_htmltag($regexstring) . '/ms into ' . strtoupper($sourcefield) . ' -> Found namealiastouseforthirdparty=' . dol_escape_htmltag($namealiastouseforthirdparty); |
||
| 2491 | } else { |
||
| 2492 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' Regex /' . dol_escape_htmltag($regexstring) . '/ms into ' . strtoupper($sourcefield) . ' -> We discard this, not a field used to search an existing thirdparty'; |
||
| 2493 | } |
||
| 2494 | } else { |
||
| 2495 | // Regex not found |
||
| 2496 | if (in_array($propertytooverwrite, array('id', 'email', 'name', 'name_alias'))) { |
||
| 2497 | $idtouseforthirdparty = null; |
||
| 2498 | $nametouseforthirdparty = null; |
||
| 2499 | $emailtouseforthirdparty = null; |
||
| 2500 | $namealiastouseforthirdparty = null; |
||
| 2501 | |||
| 2502 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' Regex /' . dol_escape_htmltag($regexstring) . '/ms into ' . strtoupper($sourcefield) . ' -> Not found. Property searched is critical so we cancel the search.'; |
||
| 2503 | } else { |
||
| 2504 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' Regex /' . dol_escape_htmltag($regexstring) . '/ms into ' . strtoupper($sourcefield) . ' -> Not found'; |
||
| 2505 | } |
||
| 2506 | } |
||
| 2507 | //var_dump($object->$tmpproperty);exit; |
||
| 2508 | } else { |
||
| 2509 | // Nothing can be done for this param |
||
| 2510 | $errorforactions++; |
||
| 2511 | $this->error = 'The extract rule to use to load thirdparty for email ' . $msgid . ' has an unknown source (must be HEADER, SUBJECT or BODY)'; |
||
| 2512 | $this->errors[] = $this->error; |
||
| 2513 | |||
| 2514 | $operationslog .= '<br>' . $this->error; |
||
| 2515 | } |
||
| 2516 | } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) { |
||
| 2517 | //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1]; |
||
| 2518 | //else $object->$tmpproperty = $reg[1]; |
||
| 2519 | // Example: id=SETIFEMPTY:123 |
||
| 2520 | if ($propertytooverwrite == 'id') { |
||
| 2521 | $idtouseforthirdparty = $reg[2]; |
||
| 2522 | |||
| 2523 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' We set property idtouseforthrdparty=' . dol_escape_htmltag($idtouseforthirdparty); |
||
| 2524 | } elseif ($propertytooverwrite == 'email') { |
||
| 2525 | $emailtouseforthirdparty = $reg[2]; |
||
| 2526 | |||
| 2527 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' We set property emailtouseforthrdparty=' . dol_escape_htmltag($emailtouseforthirdparty); |
||
| 2528 | } elseif ($propertytooverwrite == 'name') { |
||
| 2529 | $nametouseforthirdparty = $reg[2]; |
||
| 2530 | |||
| 2531 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' We set property nametouseforthirdparty=' . dol_escape_htmltag($nametouseforthirdparty); |
||
| 2532 | } elseif ($propertytooverwrite == 'name_alias') { |
||
| 2533 | $namealiastouseforthirdparty = $reg[2]; |
||
| 2534 | |||
| 2535 | $operationslog .= '<br>propertytooverwrite=' . $propertytooverwrite . ' We set property namealiastouseforthirdparty=' . dol_escape_htmltag($namealiastouseforthirdparty); |
||
| 2536 | } |
||
| 2537 | } else { |
||
| 2538 | $errorforactions++; |
||
| 2539 | $this->error = 'Bad syntax for description of action parameters: ' . $actionparam; |
||
| 2540 | $this->errors[] = $this->error; |
||
| 2541 | break; |
||
| 2542 | } |
||
| 2543 | } |
||
| 2544 | |||
| 2545 | if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) { |
||
| 2546 | // We make another search on thirdparty |
||
| 2547 | $operationslog .= '<br>We have this data to search thirdparty: id=' . $idtouseforthirdparty . ', email=' . $emailtouseforthirdparty . ', name=' . $nametouseforthirdparty . ', name_alias=' . $namealiastouseforthirdparty; |
||
| 2548 | |||
| 2549 | $tmpobject = new stdClass(); |
||
| 2550 | $tmpobject->element = 'generic'; |
||
| 2551 | $tmpobject->id = $idtouseforthirdparty; |
||
| 2552 | $tmpobject->name = $nametouseforthirdparty; |
||
| 2553 | $tmpobject->name_alias = $namealiastouseforthirdparty; |
||
| 2554 | $tmpobject->email = $emailtouseforthirdparty; |
||
| 2555 | |||
| 2556 | $this->overwritePropertiesOfObject($tmpobject, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 2557 | |||
| 2558 | $idtouseforthirdparty = $tmpobject->id; |
||
| 2559 | $nametouseforthirdparty = $tmpobject->name; |
||
| 2560 | $namealiastouseforthirdparty = $tmpobject->name_alias; |
||
| 2561 | $emailtouseforthirdparty = $tmpobject->email; |
||
| 2562 | |||
| 2563 | $operationslog .= '<br>We try to search existing thirdparty with ' . $idtouseforthirdparty . ' ' . $emailtouseforthirdparty . ' ' . $nametouseforthirdparty . ' ' . $namealiastouseforthirdparty; |
||
| 2564 | |||
| 2565 | $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty, '', '', '', '', '', '', '', '', $emailtouseforthirdparty, $namealiastouseforthirdparty); |
||
| 2566 | if ($result < 0) { |
||
| 2567 | $errorforactions++; |
||
| 2568 | $this->error = 'Error when getting thirdparty with name ' . $nametouseforthirdparty . ' (may be 2 record exists with same name ?)'; |
||
| 2569 | $this->errors[] = $this->error; |
||
| 2570 | break; |
||
| 2571 | } elseif ($result == 0) { |
||
| 2572 | if ($operation['type'] == 'loadthirdparty') { |
||
| 2573 | dol_syslog("Third party with id=" . $idtouseforthirdparty . " email=" . $emailtouseforthirdparty . " name=" . $nametouseforthirdparty . " name_alias=" . $namealiastouseforthirdparty . " was not found"); |
||
| 2574 | |||
| 2575 | //search into contacts of thirdparty |
||
| 2576 | $resultContact = $contactstatic->fetch('', '', '', $emailtouseforthirdparty); |
||
| 2577 | if ($resultContact > 0) { |
||
| 2578 | $idtouseforthirdparty = $contactstatic->socid; |
||
| 2579 | $result = $thirdpartystatic->fetch($idtouseforthirdparty); |
||
| 2580 | if ($result > 0) { |
||
| 2581 | dol_syslog("Third party with id=" . $idtouseforthirdparty . " email=" . $emailtouseforthirdparty . " name=" . $nametouseforthirdparty . " name_alias=" . $namealiastouseforthirdparty . " was found thanks to linked contact search"); |
||
| 2582 | } else { |
||
| 2583 | $errorforactions++; |
||
| 2584 | $langs->load("errors"); |
||
| 2585 | $this->error = $langs->trans('ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty); |
||
| 2586 | $this->errors[] = $this->error; |
||
| 2587 | } |
||
| 2588 | } else { |
||
| 2589 | $errorforactions++; |
||
| 2590 | $langs->load("errors"); |
||
| 2591 | $this->error = $langs->trans('ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty); |
||
| 2592 | $this->errors[] = $this->error; |
||
| 2593 | } |
||
| 2594 | } elseif ($operation['type'] == 'loadandcreatethirdparty') { |
||
| 2595 | dol_syslog("Third party with id=" . $idtouseforthirdparty . " email=" . $emailtouseforthirdparty . " name=" . $nametouseforthirdparty . " name_alias=" . $namealiastouseforthirdparty . " was not found. We try to create it."); |
||
| 2596 | |||
| 2597 | // Create thirdparty |
||
| 2598 | $thirdpartystatic = new Societe($db); |
||
| 2599 | $thirdpartystatic->name = $nametouseforthirdparty; |
||
| 2600 | if (!empty($namealiastouseforthirdparty)) { |
||
| 2601 | if ($namealiastouseforthirdparty != $nametouseforthirdparty) { |
||
| 2602 | $thirdpartystatic->name_alias = $namealiastouseforthirdparty; |
||
| 2603 | } |
||
| 2604 | } else { |
||
| 2605 | $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ? '' : $fromtext) : $replytostring); |
||
| 2606 | } |
||
| 2607 | $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ? '' : $from) : $replyto) : $emailtouseforthirdparty); |
||
| 2608 | |||
| 2609 | // Overwrite values with values extracted from source email |
||
| 2610 | $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 2611 | |||
| 2612 | if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) { |
||
| 2613 | $thirdpartystatic->code_client = 'auto'; |
||
| 2614 | } |
||
| 2615 | if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) { |
||
| 2616 | $thirdpartystatic->code_fournisseur = 'auto'; |
||
| 2617 | } |
||
| 2618 | |||
| 2619 | if ($errorforthisaction) { |
||
| 2620 | $errorforactions++; |
||
| 2621 | } else { |
||
| 2622 | $result = $thirdpartystatic->create($user); |
||
| 2623 | if ($result <= 0) { |
||
| 2624 | $errorforactions++; |
||
| 2625 | $this->error = $thirdpartystatic->error; |
||
| 2626 | $this->errors = $thirdpartystatic->errors; |
||
| 2627 | } else { |
||
| 2628 | $operationslog .= '<br>Thirdparty created -> id = ' . dol_escape_htmltag($thirdpartystatic->id); |
||
| 2629 | } |
||
| 2630 | } |
||
| 2631 | } |
||
| 2632 | } else { |
||
| 2633 | dol_syslog("One and only one existing third party has been found"); |
||
| 2634 | |||
| 2635 | $operationslog .= '<br>Thirdparty already exists with id = ' . dol_escape_htmltag($thirdpartystatic->id); |
||
| 2636 | } |
||
| 2637 | } |
||
| 2638 | } |
||
| 2639 | } elseif ($operation['type'] == 'loadandcreatecontact') { // Search and create contact |
||
| 2640 | if (empty($operation['actionparam'])) { |
||
| 2641 | $errorforactions++; |
||
| 2642 | $this->error = "Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data"; |
||
| 2643 | $this->errors[] = $this->error; |
||
| 2644 | } else { |
||
| 2645 | $contact_static = new Contact($this->db); |
||
| 2646 | // Overwrite values with values extracted from source email |
||
| 2647 | $errorforthisaction = $this->overwritePropertiesOfObject($contact_static, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 2648 | if ($errorforthisaction) { |
||
| 2649 | $errorforactions++; |
||
| 2650 | } else { |
||
| 2651 | if (!empty($contact_static->email) && $contact_static->email != $from) { |
||
| 2652 | $from = $contact_static->email; |
||
| 2653 | } |
||
| 2654 | |||
| 2655 | $result = $contactstatic->fetch(0, null, '', $from); |
||
| 2656 | if ($result < 0) { |
||
| 2657 | $errorforactions++; |
||
| 2658 | $this->error = 'Error when getting contact with email ' . $from; |
||
| 2659 | $this->errors[] = $this->error; |
||
| 2660 | break; |
||
| 2661 | } elseif ($result == 0) { |
||
| 2662 | dol_syslog("Contact with email " . $from . " was not found. We try to create it."); |
||
| 2663 | $contactstatic = new Contact($this->db); |
||
| 2664 | |||
| 2665 | // Create contact |
||
| 2666 | $contactstatic->email = $from; |
||
| 2667 | $operationslog .= '<br>We set property email=' . dol_escape_htmltag($from); |
||
| 2668 | |||
| 2669 | // Overwrite values with values extracted from source email |
||
| 2670 | $errorforthisaction = $this->overwritePropertiesOfObject($contactstatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 2671 | |||
| 2672 | if ($errorforthisaction) { |
||
| 2673 | $errorforactions++; |
||
| 2674 | } else { |
||
| 2675 | // Search country by name or code |
||
| 2676 | if (!empty($contactstatic->country)) { |
||
| 2677 | require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/company.lib.php'; |
||
| 2678 | $result = getCountry('', 3, $this->db, '', 1, $contactstatic->country); |
||
| 2679 | if ($result == 'NotDefined') { |
||
| 2680 | $errorforactions++; |
||
| 2681 | $this->error = "Error country not found by this name '" . $contactstatic->country . "'"; |
||
| 2682 | } elseif (!($result > 0)) { |
||
| 2683 | $errorforactions++; |
||
| 2684 | $this->error = "Error when search country by this name '" . $contactstatic->country . "'"; |
||
| 2685 | $this->errors[] = $this->db->lasterror(); |
||
| 2686 | } else { |
||
| 2687 | $contactstatic->country_id = $result; |
||
| 2688 | $operationslog .= '<br>We set property country_id=' . dol_escape_htmltag($result); |
||
| 2689 | } |
||
| 2690 | } elseif (!empty($contactstatic->country_code)) { |
||
| 2691 | require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/company.lib.php'; |
||
| 2692 | $result = getCountry($contactstatic->country_code, 3, $this->db); |
||
| 2693 | if ($result == 'NotDefined') { |
||
| 2694 | $errorforactions++; |
||
| 2695 | $this->error = "Error country not found by this code '" . $contactstatic->country_code . "'"; |
||
| 2696 | } elseif (!($result > 0)) { |
||
| 2697 | $errorforactions++; |
||
| 2698 | $this->error = "Error when search country by this code '" . $contactstatic->country_code . "'"; |
||
| 2699 | $this->errors[] = $this->db->lasterror(); |
||
| 2700 | } else { |
||
| 2701 | $contactstatic->country_id = $result; |
||
| 2702 | $operationslog .= '<br>We set property country_id=' . dol_escape_htmltag($result); |
||
| 2703 | } |
||
| 2704 | } |
||
| 2705 | |||
| 2706 | if (!$errorforactions) { |
||
| 2707 | // Search state by name or code (for country if defined) |
||
| 2708 | if (!empty($contactstatic->state)) { |
||
| 2709 | require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/functions.lib.php'; |
||
| 2710 | $result = dol_getIdFromCode($this->db, $contactstatic->state, 'c_departements', 'nom', 'rowid'); |
||
| 2711 | if (empty($result)) { |
||
| 2712 | $errorforactions++; |
||
| 2713 | $this->error = "Error state not found by this name '" . $contactstatic->state . "'"; |
||
| 2714 | } elseif (!($result > 0)) { |
||
| 2715 | $errorforactions++; |
||
| 2716 | $this->error = "Error when search state by this name '" . $contactstatic->state . "'"; |
||
| 2717 | $this->errors[] = $this->db->lasterror(); |
||
| 2718 | } else { |
||
| 2719 | $contactstatic->state_id = $result; |
||
| 2720 | $operationslog .= '<br>We set property state_id=' . dol_escape_htmltag($result); |
||
| 2721 | } |
||
| 2722 | } elseif (!empty($contactstatic->state_code)) { |
||
| 2723 | require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/functions.lib.php'; |
||
| 2724 | $result = dol_getIdFromCode($this->db, $contactstatic->state_code, 'c_departements', 'code_departement', 'rowid'); |
||
| 2725 | if (empty($result)) { |
||
| 2726 | $errorforactions++; |
||
| 2727 | $this->error = "Error state not found by this code '" . $contactstatic->state_code . "'"; |
||
| 2728 | } elseif (!($result > 0)) { |
||
| 2729 | $errorforactions++; |
||
| 2730 | $this->error = "Error when search state by this code '" . $contactstatic->state_code . "'"; |
||
| 2731 | $this->errors[] = $this->db->lasterror(); |
||
| 2732 | } else { |
||
| 2733 | $contactstatic->state_id = $result; |
||
| 2734 | $operationslog .= '<br>We set property state_id=' . dol_escape_htmltag($result); |
||
| 2735 | } |
||
| 2736 | } |
||
| 2737 | } |
||
| 2738 | |||
| 2739 | if (!$errorforactions) { |
||
| 2740 | $result = $contactstatic->create($user); |
||
| 2741 | if ($result <= 0) { |
||
| 2742 | $errorforactions++; |
||
| 2743 | $this->error = $contactstatic->error; |
||
| 2744 | $this->errors = $contactstatic->errors; |
||
| 2745 | } else { |
||
| 2746 | $operationslog .= '<br>Contact created -> id = ' . dol_escape_htmltag($contactstatic->id); |
||
| 2747 | } |
||
| 2748 | } |
||
| 2749 | } |
||
| 2750 | } |
||
| 2751 | } |
||
| 2752 | } |
||
| 2753 | } elseif ($operation['type'] == 'recordevent') { |
||
| 2754 | // Create event |
||
| 2755 | $actioncomm = new ActionComm($this->db); |
||
| 2756 | |||
| 2757 | $alreadycreated = $actioncomm->fetch(0, '', '', $msgid); |
||
| 2758 | if ($alreadycreated == 0) { |
||
| 2759 | $operationslog .= '<br>We did not find existing actionmail with msgid=' . $msgid; |
||
| 2760 | |||
| 2761 | if ($projectstatic->id > 0) { |
||
| 2762 | if ($projectfoundby) { |
||
| 2763 | $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from ' . $projectfoundby); |
||
| 2764 | } |
||
| 2765 | } |
||
| 2766 | if ($thirdpartystatic->id > 0) { |
||
| 2767 | if ($thirdpartyfoundby) { |
||
| 2768 | $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from ' . $thirdpartyfoundby); |
||
| 2769 | } |
||
| 2770 | } |
||
| 2771 | if ($contactstatic->id > 0) { |
||
| 2772 | if ($contactfoundby) { |
||
| 2773 | $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from ' . $contactfoundby); |
||
| 2774 | } |
||
| 2775 | } |
||
| 2776 | |||
| 2777 | $description = $descriptiontitle; |
||
| 2778 | $description = dol_concatdesc($description, "-----"); |
||
| 2779 | $description = dol_concatdesc($description, $descriptionmeta); |
||
| 2780 | $description = dol_concatdesc($description, "-----"); |
||
| 2781 | $description = dol_concatdesc($description, $messagetext); |
||
| 2782 | |||
| 2783 | $descriptionfull = $description; |
||
| 2784 | if (!getDolGlobalString('MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER')) { |
||
| 2785 | $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); |
||
| 2786 | $descriptionfull = dol_concatdesc($descriptionfull, $header); |
||
| 2787 | } |
||
| 2788 | |||
| 2789 | // Insert record of emails sent |
||
| 2790 | $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) |
||
| 2791 | $actioncomm->code = 'AC_' . $actioncode; |
||
| 2792 | $actioncomm->label = $langs->trans("ActionAC_" . $actioncode) . ' - ' . $langs->trans("MailFrom") . ' ' . $from; |
||
| 2793 | $actioncomm->note_private = $descriptionfull; |
||
| 2794 | $actioncomm->fk_project = $projectstatic->id; |
||
| 2795 | $actioncomm->datep = $dateemail; // date of email |
||
| 2796 | $actioncomm->datef = $dateemail; // date of email |
||
| 2797 | $actioncomm->percentage = -1; // Not applicable |
||
| 2798 | $actioncomm->socid = $thirdpartystatic->id; |
||
| 2799 | $actioncomm->contact_id = $contactstatic->id; |
||
| 2800 | $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array()); |
||
| 2801 | $actioncomm->authorid = $user->id; // User saving action |
||
| 2802 | $actioncomm->userownerid = $user->id; // Owner of action |
||
| 2803 | // Fields when action is an email (content should be added into note) |
||
| 2804 | $actioncomm->email_msgid = $msgid; |
||
| 2805 | $actioncomm->email_from = $fromstring; |
||
| 2806 | $actioncomm->email_sender = $sender; |
||
| 2807 | $actioncomm->email_to = $to; |
||
| 2808 | $actioncomm->email_tocc = $sendtocc; |
||
| 2809 | $actioncomm->email_tobcc = $sendtobcc; |
||
| 2810 | $actioncomm->email_subject = $subject; |
||
| 2811 | $actioncomm->errors_to = ''; |
||
| 2812 | |||
| 2813 | if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) { |
||
| 2814 | $actioncomm->fk_element = $fk_element_id; |
||
| 2815 | $actioncomm->elementid = $fk_element_id; |
||
| 2816 | $actioncomm->elementtype = $fk_element_type; |
||
| 2817 | if (is_object($objectemail) && $objectemail->module) { |
||
| 2818 | $actioncomm->elementtype .= '@' . $objectemail->module; |
||
| 2819 | } |
||
| 2820 | } |
||
| 2821 | |||
| 2822 | //$actioncomm->extraparams = $extraparams; |
||
| 2823 | |||
| 2824 | // Overwrite values with values extracted from source email |
||
| 2825 | $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 2826 | |||
| 2827 | if ($errorforthisaction) { |
||
| 2828 | $errorforactions++; |
||
| 2829 | } else { |
||
| 2830 | $result = $actioncomm->create($user); |
||
| 2831 | if ($result <= 0) { |
||
| 2832 | $errorforactions++; |
||
| 2833 | $this->errors = $actioncomm->errors; |
||
| 2834 | } else { |
||
| 2835 | if ($fk_element_type == "ticket" && is_object($objectemail)) { |
||
| 2836 | if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED) { |
||
| 2837 | if ($objectemail->fk_user_assign != null) { |
||
| 2838 | $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED); |
||
| 2839 | } else { |
||
| 2840 | $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ); |
||
| 2841 | } |
||
| 2842 | |||
| 2843 | if ($res) { |
||
| 2844 | $operationslog .= '<br>Ticket Re-Opened successfully -> ref=' . $objectemail->ref; |
||
| 2845 | } else { |
||
| 2846 | $errorforactions++; |
||
| 2847 | $this->error = 'Error while changing the ticket status -> ref=' . $objectemail->ref; |
||
| 2848 | $this->errors[] = $this->error; |
||
| 2849 | } |
||
| 2850 | } |
||
| 2851 | if (!empty($attachments)) { |
||
| 2852 | // There is an attachment for the ticket -> store attachment |
||
| 2853 | $ticket = new Ticket($this->db); |
||
| 2854 | $ticket->fetch($fk_element_id); |
||
| 2855 | $destdir = $conf->ticket->dir_output . '/' . $ticket->ref; |
||
| 2856 | if (!dol_is_dir($destdir)) { |
||
| 2857 | dol_mkdir($destdir); |
||
| 2858 | } |
||
| 2859 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 2860 | foreach ($attachments as $attachment) { |
||
| 2861 | $attachment->save($destdir . '/'); |
||
| 2862 | } |
||
| 2863 | } else { |
||
| 2864 | $this->getmsg($connection, $imapemail, $destdir); |
||
| 2865 | } |
||
| 2866 | } |
||
| 2867 | } |
||
| 2868 | |||
| 2869 | $operationslog .= '<br>Event created -> id=' . dol_escape_htmltag($actioncomm->id); |
||
| 2870 | } |
||
| 2871 | } |
||
| 2872 | } |
||
| 2873 | } elseif ($operation['type'] == 'recordjoinpiece') { |
||
| 2874 | $data = []; |
||
| 2875 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 2876 | foreach ($attachments as $attachment) { |
||
| 2877 | if ($attachment->getName() === 'undefined') { |
||
| 2878 | continue; |
||
| 2879 | } |
||
| 2880 | $data[$attachment->getName()] = $attachment->getContent(); |
||
| 2881 | } |
||
| 2882 | } else { |
||
| 2883 | $pj = getAttachments($imapemail, $connection); |
||
| 2884 | foreach ($pj as $key => $val) { |
||
| 2885 | $data[$val['filename']] = getFileData($imapemail, $val['pos'], $val['type'], $connection); |
||
| 2886 | } |
||
| 2887 | } |
||
| 2888 | if (count($data) > 0) { |
||
| 2889 | $sql = "SELECT rowid as id FROM " . MAIN_DB_PREFIX . "user WHERE email LIKE '%" . $this->db->escape($from) . "%'"; |
||
| 2890 | $resql = $this->db->query($sql); |
||
| 2891 | if ($this->db->num_rows($resql) == 0) { |
||
| 2892 | $this->errors[] = "User Not allowed to add documents ({$from})"; |
||
| 2893 | } |
||
| 2894 | $arrayobject = array( |
||
| 2895 | 'propale' => array('table' => 'propal', |
||
| 2896 | 'fields' => array('ref'), |
||
| 2897 | 'class' => 'comm/propal/class/propal.class.php', |
||
| 2898 | 'object' => 'Propal'), |
||
| 2899 | 'holiday' => array('table' => 'holiday', |
||
| 2900 | 'fields' => array('ref'), |
||
| 2901 | 'class' => 'holiday/class/holiday.class.php', |
||
| 2902 | 'object' => 'Holiday'), |
||
| 2903 | 'expensereport' => array('table' => 'expensereport', |
||
| 2904 | 'fields' => array('ref'), |
||
| 2905 | 'class' => 'expensereport/class/expensereport.class.php', |
||
| 2906 | 'object' => 'ExpenseReport'), |
||
| 2907 | 'recruitment/recruitmentjobposition' => array('table' => 'recruitment_recruitmentjobposition', |
||
| 2908 | 'fields' => array('ref'), |
||
| 2909 | 'class' => 'recruitment/class/recruitmentjobposition.class.php', |
||
| 2910 | 'object' => 'RecruitmentJobPosition'), |
||
| 2911 | 'recruitment/recruitmentcandidature' => array('table' => 'recruitment_recruitmentcandidature', |
||
| 2912 | 'fields' => array('ref'), |
||
| 2913 | 'class' => 'recruitment/class/recruitmentcandidature.class.php', |
||
| 2914 | 'object' => ' RecruitmentCandidature'), |
||
| 2915 | 'societe' => array('table' => 'societe', |
||
| 2916 | 'fields' => array('code_client', 'code_fournisseur'), |
||
| 2917 | 'class' => 'societe/class/societe.class.php', |
||
| 2918 | 'object' => 'Societe'), |
||
| 2919 | 'commande' => array('table' => 'commande', |
||
| 2920 | 'fields' => array('ref'), |
||
| 2921 | 'class' => 'commande/class/commande.class.php', |
||
| 2922 | 'object' => 'Commande'), |
||
| 2923 | 'expedition' => array('table' => 'expedition', |
||
| 2924 | 'fields' => array('ref'), |
||
| 2925 | 'class' => 'expedition/class/expedition.class.php', |
||
| 2926 | 'object' => 'Expedition'), |
||
| 2927 | 'contract' => array('table' => 'contrat', |
||
| 2928 | 'fields' => array('ref'), |
||
| 2929 | 'class' => 'contrat/class/contrat.class.php', |
||
| 2930 | 'object' => 'Contrat'), |
||
| 2931 | 'fichinter' => array('table' => 'fichinter', |
||
| 2932 | 'fields' => array('ref'), |
||
| 2933 | 'class' => 'fichinter/class/fichinter.class.php', |
||
| 2934 | 'object' => 'Fichinter'), |
||
| 2935 | 'ticket' => array('table' => 'ticket', |
||
| 2936 | 'fields' => array('ref'), |
||
| 2937 | 'class' => 'ticket/class/ticket.class.php', |
||
| 2938 | 'object' => 'Ticket'), |
||
| 2939 | 'knowledgemanagement' => array('table' => 'knowledgemanagement_knowledgerecord', |
||
| 2940 | 'fields' => array('ref'), |
||
| 2941 | 'class' => 'knowledgemanagement/class/knowledgemanagement.class.php', |
||
| 2942 | 'object' => 'KnowledgeRecord'), |
||
| 2943 | 'supplier_proposal' => array('table' => 'supplier_proposal', |
||
| 2944 | 'fields' => array('ref'), |
||
| 2945 | 'class' => 'supplier_proposal/class/supplier_proposal.class.php', |
||
| 2946 | 'object' => 'SupplierProposal'), |
||
| 2947 | 'fournisseur/commande' => array('table' => 'commande_fournisseur', |
||
| 2948 | 'fields' => array('ref', 'ref_supplier'), |
||
| 2949 | 'class' => 'fourn/class/fournisseur.commande.class.php', |
||
| 2950 | 'object' => 'SupplierProposal'), |
||
| 2951 | 'facture' => array('table' => 'facture', |
||
| 2952 | 'fields' => array('ref'), |
||
| 2953 | 'class' => 'compta/facture/class/facture.class.php', |
||
| 2954 | 'object' => 'Facture'), |
||
| 2955 | 'fournisseur/facture' => array('table' => 'facture_fourn', |
||
| 2956 | 'fields' => array('ref', 'ref_client'), |
||
| 2957 | 'class' => 'fourn/class/fournisseur.facture.class.php', |
||
| 2958 | 'object' => 'FactureFournisseur'), |
||
| 2959 | 'produit' => array('table' => 'product', |
||
| 2960 | 'fields' => array('ref'), |
||
| 2961 | 'class' => 'product/class/product.class.php', |
||
| 2962 | 'object' => 'Product'), |
||
| 2963 | 'productlot' => array('table' => 'product_lot', |
||
| 2964 | 'fields' => array('batch'), |
||
| 2965 | 'class' => 'product/stock/class/productlot.class.php', |
||
| 2966 | 'object' => 'Productlot'), |
||
| 2967 | 'projet' => array('table' => 'projet', |
||
| 2968 | 'fields' => array('ref'), |
||
| 2969 | 'class' => 'projet/class/projet.class.php', |
||
| 2970 | 'object' => 'Project'), |
||
| 2971 | 'projet_task' => array('table' => 'projet_task', |
||
| 2972 | 'fields' => array('ref'), |
||
| 2973 | 'class' => 'projet/class/task.class.php', |
||
| 2974 | 'object' => 'Task'), |
||
| 2975 | 'ressource' => array('table' => 'resource', |
||
| 2976 | 'fields' => array('ref'), |
||
| 2977 | 'class' => 'ressource/class/dolressource.class.php', |
||
| 2978 | 'object' => 'Dolresource'), |
||
| 2979 | 'bom' => array('table' => 'bom_bom', |
||
| 2980 | 'fields' => array('ref'), |
||
| 2981 | 'class' => 'bom/class/bom.class.php', |
||
| 2982 | 'object' => 'BOM'), |
||
| 2983 | 'mrp' => array('table' => 'mrp_mo', |
||
| 2984 | 'fields' => array('ref'), |
||
| 2985 | 'class' => 'mrp/class/mo.class.php', |
||
| 2986 | 'object' => 'Mo'), |
||
| 2987 | ); |
||
| 2988 | |||
| 2989 | if (!is_object($hookmanager)) { |
||
| 2990 | include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; |
||
| 2991 | $hookmanager = new HookManager($this->db); |
||
| 2992 | } |
||
| 2993 | $hookmanager->initHooks(array('emailcolector')); |
||
| 2994 | $parameters = array('arrayobject' => $arrayobject); |
||
| 2995 | $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks |
||
| 2996 | if ($reshook > 0) { |
||
| 2997 | $arrayobject = $hookmanager->resArray; |
||
| 2998 | } |
||
| 2999 | |||
| 3000 | $resultobj = array(); |
||
| 3001 | |||
| 3002 | foreach ($arrayobject as $key => $objectdesc) { |
||
| 3003 | $sql = 'SELECT DISTINCT t.rowid '; |
||
| 3004 | $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc['table']) . ' AS t'; |
||
| 3005 | $sql .= ' WHERE '; |
||
| 3006 | foreach ($objectdesc['fields'] as $field) { |
||
| 3007 | $sql .= "('" . $this->db->escape($subject) . "' LIKE CONCAT('%', t." . $this->db->sanitize($field) . ", '%') AND t." . $this->db->sanitize($field) . " <> '') OR "; |
||
| 3008 | } |
||
| 3009 | $sql = substr($sql, 0, -4); |
||
| 3010 | |||
| 3011 | $ressqlobj = $this->db->query($sql); |
||
| 3012 | if ($ressqlobj) { |
||
| 3013 | while ($obj = $this->db->fetch_object($ressqlobj)) { |
||
| 3014 | $resultobj[$key][] = $obj->rowid; |
||
| 3015 | } |
||
| 3016 | } |
||
| 3017 | } |
||
| 3018 | $dirs = array(); |
||
| 3019 | foreach ($resultobj as $mod => $ids) { |
||
| 3020 | $moddesc = $arrayobject[$mod]; |
||
| 3021 | $elementpath = $mod; |
||
| 3022 | dol_include_once($moddesc['class']); |
||
| 3023 | $objectmanaged = new $moddesc['object']($this->db); |
||
| 3024 | foreach ($ids as $val) { |
||
| 3025 | $res = $objectmanaged->fetch($val); |
||
| 3026 | if ($res) { |
||
| 3027 | $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : ''); |
||
| 3028 | $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/'; |
||
| 3029 | } else { |
||
| 3030 | $this->errors[] = 'object not found'; |
||
| 3031 | } |
||
| 3032 | } |
||
| 3033 | } |
||
| 3034 | foreach ($dirs as $target) { |
||
| 3035 | $prefix = $this->actions[$this->id]['actionparam']; |
||
| 3036 | foreach ($data as $filename => $content) { |
||
| 3037 | $resr = saveAttachment($target, $prefix . '_' . $filename, $content); |
||
| 3038 | if ($resr == -1) { |
||
| 3039 | $this->errors[] = 'Doc not saved'; |
||
| 3040 | } |
||
| 3041 | } |
||
| 3042 | } |
||
| 3043 | |||
| 3044 | $operationslog .= '<br>Save attachment files on disk'; |
||
| 3045 | } else { |
||
| 3046 | $this->errors[] = 'no joined piece'; |
||
| 3047 | |||
| 3048 | $operationslog .= '<br>No joinded files'; |
||
| 3049 | } |
||
| 3050 | } elseif ($operation['type'] == 'project') { |
||
| 3051 | // Create project / lead |
||
| 3052 | $projecttocreate = new Project($this->db); |
||
| 3053 | $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid); |
||
| 3054 | if ($alreadycreated == 0) { |
||
| 3055 | if ($thirdpartystatic->id > 0) { |
||
| 3056 | $projecttocreate->socid = $thirdpartystatic->id; |
||
| 3057 | if ($thirdpartyfoundby) { |
||
| 3058 | $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from ' . $thirdpartyfoundby); |
||
| 3059 | } |
||
| 3060 | } |
||
| 3061 | if ($contactstatic->id > 0) { |
||
| 3062 | $projecttocreate->contact_id = $contactstatic->id; |
||
| 3063 | if ($contactfoundby) { |
||
| 3064 | $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from ' . $contactfoundby); |
||
| 3065 | } |
||
| 3066 | } |
||
| 3067 | |||
| 3068 | $description = $descriptiontitle; |
||
| 3069 | $description = dol_concatdesc($description, "-----"); |
||
| 3070 | $description = dol_concatdesc($description, $descriptionmeta); |
||
| 3071 | $description = dol_concatdesc($description, "-----"); |
||
| 3072 | $description = dol_concatdesc($description, $messagetext); |
||
| 3073 | |||
| 3074 | $descriptionfull = $description; |
||
| 3075 | if (!getDolGlobalString('MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER')) { |
||
| 3076 | $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); |
||
| 3077 | $descriptionfull = dol_concatdesc($descriptionfull, $header); |
||
| 3078 | } |
||
| 3079 | |||
| 3080 | $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid'); |
||
| 3081 | $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent'); |
||
| 3082 | |||
| 3083 | $projecttocreate->title = $subject; |
||
| 3084 | $projecttocreate->date_start = $date; // date of email |
||
| 3085 | $projecttocreate->date_end = 0; |
||
| 3086 | $projecttocreate->opp_status = $id_opp_status; |
||
| 3087 | $projecttocreate->opp_percent = $percent_opp_status; |
||
| 3088 | $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...' . $langs->transnoentities("SeePrivateNote") . '...'); |
||
| 3089 | $projecttocreate->note_private = $descriptionfull; |
||
| 3090 | $projecttocreate->entity = $conf->entity; |
||
| 3091 | $projecttocreate->email_msgid = $msgid; |
||
| 3092 | |||
| 3093 | $savesocid = $projecttocreate->socid; |
||
| 3094 | |||
| 3095 | // Overwrite values with values extracted from source email. |
||
| 3096 | // This may overwrite any $projecttocreate->xxx properties. |
||
| 3097 | $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 3098 | |||
| 3099 | // Set project ref if not yet defined |
||
| 3100 | if (empty($projecttocreate->ref)) { |
||
| 3101 | // Get next Ref |
||
| 3102 | $defaultref = ''; |
||
| 3103 | $modele = !getDolGlobalString('PROJECT_ADDON') ? 'mod_project_simple' : $conf->global->PROJECT_ADDON; |
||
| 3104 | |||
| 3105 | // Search template files |
||
| 3106 | $file = ''; |
||
| 3107 | $classname = ''; |
||
| 3108 | $reldir = ''; |
||
| 3109 | $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); |
||
| 3110 | foreach ($dirmodels as $reldir) { |
||
| 3111 | $file = dol_buildpath($reldir . "core/modules/project/" . $modele . '.php', 0); |
||
| 3112 | if (file_exists($file)) { |
||
| 3113 | $classname = $modele; |
||
| 3114 | break; |
||
| 3115 | } |
||
| 3116 | } |
||
| 3117 | |||
| 3118 | if ($classname !== '') { |
||
| 3119 | if ($savesocid > 0) { |
||
| 3120 | if ($savesocid != $projecttocreate->socid) { |
||
| 3121 | $errorforactions++; |
||
| 3122 | setEventMessages('You loaded a thirdparty (id=' . $savesocid . ') and you force another thirdparty id (id=' . $projecttocreate->socid . ') by setting socid in operation with a different value', null, 'errors'); |
||
| 3123 | } |
||
| 3124 | } else { |
||
| 3125 | if ($projecttocreate->socid > 0) { |
||
| 3126 | $thirdpartystatic->fetch($projecttocreate->socid); |
||
| 3127 | } |
||
| 3128 | } |
||
| 3129 | |||
| 3130 | $result = dol_include_once($reldir . "core/modules/project/" . $modele . '.php'); |
||
| 3131 | $modModuleToUseForNextValue = new $classname(); |
||
| 3132 | $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate); |
||
| 3133 | } |
||
| 3134 | $projecttocreate->ref = $defaultref; |
||
| 3135 | } |
||
| 3136 | |||
| 3137 | |||
| 3138 | if ($errorforthisaction) { |
||
| 3139 | $errorforactions++; |
||
| 3140 | } else { |
||
| 3141 | if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) { |
||
| 3142 | $errorforactions++; |
||
| 3143 | $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = ' . $modele . ', thirdparty id = ' . $thirdpartystatic->id; |
||
| 3144 | |||
| 3145 | $operationslog .= '<br>' . $this->error; |
||
| 3146 | } else { |
||
| 3147 | // Create project |
||
| 3148 | $result = $projecttocreate->create($user); |
||
| 3149 | if ($result <= 0) { |
||
| 3150 | $errorforactions++; |
||
| 3151 | $this->error = 'Failed to create project: ' . $langs->trans($projecttocreate->error); |
||
| 3152 | $this->errors = $projecttocreate->errors; |
||
| 3153 | |||
| 3154 | $operationslog .= '<br>' . $this->error; |
||
| 3155 | } else { |
||
| 3156 | if ($attachments) { |
||
| 3157 | $destdir = $conf->project->dir_output . '/' . $projecttocreate->ref; |
||
| 3158 | if (!dol_is_dir($destdir)) { |
||
| 3159 | dol_mkdir($destdir); |
||
| 3160 | } |
||
| 3161 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 3162 | foreach ($attachments as $attachment) { |
||
| 3163 | // $attachment->save($destdir.'/'); |
||
| 3164 | $typeattachment = (string) $attachment->getDisposition(); |
||
| 3165 | $filename = $attachment->getFilename(); |
||
| 3166 | $content = $attachment->getContent(); |
||
| 3167 | $this->saveAttachment($destdir, $filename, $content); |
||
| 3168 | } |
||
| 3169 | } else { |
||
| 3170 | $this->getmsg($connection, $imapemail, $destdir); |
||
| 3171 | } |
||
| 3172 | |||
| 3173 | $operationslog .= '<br>Project created with attachments -> id=' . dol_escape_htmltag($projecttocreate->id); |
||
| 3174 | } else { |
||
| 3175 | $operationslog .= '<br>Project created without attachments -> id=' . dol_escape_htmltag($projecttocreate->id); |
||
| 3176 | } |
||
| 3177 | } |
||
| 3178 | } |
||
| 3179 | } |
||
| 3180 | } else { |
||
| 3181 | dol_syslog("Project already exists for msgid = " . dol_escape_htmltag($msgid) . ", so we do not recreate it."); |
||
| 3182 | |||
| 3183 | $operationslog .= '<br>Project already exists for msgid =' . dol_escape_htmltag($msgid); |
||
| 3184 | } |
||
| 3185 | } elseif ($operation['type'] == 'ticket') { |
||
| 3186 | // Create ticket |
||
| 3187 | $tickettocreate = new Ticket($this->db); |
||
| 3188 | if ($ticketalreadyexists == 0) { |
||
| 3189 | if ($thirdpartystatic->id > 0) { |
||
| 3190 | $tickettocreate->socid = $thirdpartystatic->id; |
||
| 3191 | $tickettocreate->fk_soc = $thirdpartystatic->id; |
||
| 3192 | if ($thirdpartyfoundby) { |
||
| 3193 | $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from ' . $thirdpartyfoundby); |
||
| 3194 | } |
||
| 3195 | } |
||
| 3196 | if ($contactstatic->id > 0) { |
||
| 3197 | $tickettocreate->contact_id = $contactstatic->id; |
||
| 3198 | if ($contactfoundby) { |
||
| 3199 | $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from ' . $contactfoundby); |
||
| 3200 | } |
||
| 3201 | } |
||
| 3202 | |||
| 3203 | $description = $descriptiontitle; |
||
| 3204 | $description = dol_concatdesc($description, "-----"); |
||
| 3205 | $description = dol_concatdesc($description, $descriptionmeta); |
||
| 3206 | $description = dol_concatdesc($description, "-----"); |
||
| 3207 | $description = dol_concatdesc($description, $messagetext); |
||
| 3208 | |||
| 3209 | $descriptionfull = $description; |
||
| 3210 | if (!getDolGlobalString('MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER')) { |
||
| 3211 | $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); |
||
| 3212 | $descriptionfull = dol_concatdesc($descriptionfull, $header); |
||
| 3213 | } |
||
| 3214 | |||
| 3215 | $tickettocreate->subject = $subject; |
||
| 3216 | $tickettocreate->message = $description; |
||
| 3217 | $tickettocreate->type_code = (getDolGlobalString('MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE') ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_type', 'use_default', 'code', 1)); |
||
| 3218 | $tickettocreate->category_code = (getDolGlobalString('MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE') ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_category', 'use_default', 'code', 1)); |
||
| 3219 | $tickettocreate->severity_code = (getDolGlobalString('MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE') ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_severity', 'use_default', 'code', 1)); |
||
| 3220 | $tickettocreate->origin_email = $from; |
||
| 3221 | $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto : null); |
||
| 3222 | $tickettocreate->origin_references = (!empty($headers['References']) ? $headers['References'] : null); |
||
| 3223 | $tickettocreate->fk_user_create = $user->id; |
||
| 3224 | $tickettocreate->datec = dol_now(); |
||
| 3225 | $tickettocreate->fk_project = $projectstatic->id; |
||
| 3226 | $tickettocreate->notify_tiers_at_create = getDolGlobalInt('TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION'); |
||
| 3227 | $tickettocreate->note_private = $descriptionfull; |
||
| 3228 | $tickettocreate->entity = $conf->entity; |
||
| 3229 | $tickettocreate->email_msgid = $msgid; |
||
| 3230 | $tickettocreate->email_date = $date; |
||
| 3231 | //$tickettocreate->fk_contact = $contactstatic->id; |
||
| 3232 | |||
| 3233 | $savesocid = $tickettocreate->socid; |
||
| 3234 | |||
| 3235 | // Overwrite values with values extracted from source email. |
||
| 3236 | // This may overwrite any $projecttocreate->xxx properties. |
||
| 3237 | $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 3238 | |||
| 3239 | // Set ticket ref if not yet defined |
||
| 3240 | if (empty($tickettocreate->ref)) { |
||
| 3241 | // Get next Ref |
||
| 3242 | $defaultref = ''; |
||
| 3243 | $modele = getDolGlobalString('TICKET_ADDON', 'mod_ticket_simple'); |
||
| 3244 | |||
| 3245 | // Search template files |
||
| 3246 | $file = ''; |
||
| 3247 | $classname = ''; |
||
| 3248 | $reldir = ''; |
||
| 3249 | $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); |
||
| 3250 | foreach ($dirmodels as $reldir) { |
||
| 3251 | $file = dol_buildpath($reldir . "core/modules/ticket/" . $modele . '.php', 0); |
||
| 3252 | if (file_exists($file)) { |
||
| 3253 | $classname = $modele; |
||
| 3254 | break; |
||
| 3255 | } |
||
| 3256 | } |
||
| 3257 | |||
| 3258 | if ($classname !== '') { |
||
| 3259 | if ($savesocid > 0) { |
||
| 3260 | if ($savesocid != $tickettocreate->socid) { |
||
| 3261 | $errorforactions++; |
||
| 3262 | setEventMessages('You loaded a thirdparty (id=' . $savesocid . ') and you force another thirdparty id (id=' . $tickettocreate->socid . ') by setting socid in operation with a different value', null, 'errors'); |
||
| 3263 | } |
||
| 3264 | } else { |
||
| 3265 | if ($tickettocreate->socid > 0) { |
||
| 3266 | $thirdpartystatic->fetch($tickettocreate->socid); |
||
| 3267 | } |
||
| 3268 | } |
||
| 3269 | |||
| 3270 | $result = dol_include_once($reldir . "core/modules/ticket/" . $modele . '.php'); |
||
| 3271 | $modModuleToUseForNextValue = new $classname(); |
||
| 3272 | $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); |
||
| 3273 | } |
||
| 3274 | $tickettocreate->ref = $defaultref; |
||
| 3275 | } |
||
| 3276 | |||
| 3277 | if ($errorforthisaction) { |
||
| 3278 | $errorforactions++; |
||
| 3279 | } else { |
||
| 3280 | if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) { |
||
| 3281 | $errorforactions++; |
||
| 3282 | $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = ' . $modele . ', thirdparty id = ' . $thirdpartystatic->id; |
||
| 3283 | } else { |
||
| 3284 | // Create ticket |
||
| 3285 | $result = $tickettocreate->create($user); |
||
| 3286 | if ($result <= 0) { |
||
| 3287 | $errorforactions++; |
||
| 3288 | $this->error = 'Failed to create ticket: ' . $langs->trans($tickettocreate->error); |
||
| 3289 | $this->errors = $tickettocreate->errors; |
||
| 3290 | } else { |
||
| 3291 | if ($attachments) { |
||
| 3292 | $destdir = $conf->ticket->dir_output . '/' . $tickettocreate->ref; |
||
| 3293 | if (!dol_is_dir($destdir)) { |
||
| 3294 | dol_mkdir($destdir); |
||
| 3295 | } |
||
| 3296 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 3297 | foreach ($attachments as $attachment) { |
||
| 3298 | // $attachment->save($destdir.'/'); |
||
| 3299 | $typeattachment = (string) $attachment->getDisposition(); |
||
| 3300 | $filename = $attachment->getFilename(); |
||
| 3301 | $content = $attachment->getContent(); |
||
| 3302 | $this->saveAttachment($destdir, $filename, $content); |
||
| 3303 | } |
||
| 3304 | } else { |
||
| 3305 | $this->getmsg($connection, $imapemail, $destdir); |
||
| 3306 | } |
||
| 3307 | |||
| 3308 | $operationslog .= '<br>Ticket created with attachments -> id=' . dol_escape_htmltag($tickettocreate->id); |
||
| 3309 | } else { |
||
| 3310 | $operationslog .= '<br>Ticket created without attachments -> id=' . dol_escape_htmltag($tickettocreate->id); |
||
| 3311 | } |
||
| 3312 | } |
||
| 3313 | } |
||
| 3314 | } |
||
| 3315 | } |
||
| 3316 | } elseif ($operation['type'] == 'candidature') { |
||
| 3317 | // Create candidature |
||
| 3318 | $candidaturetocreate = new RecruitmentCandidature($this->db); |
||
| 3319 | |||
| 3320 | $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid); |
||
| 3321 | if ($alreadycreated == 0) { |
||
| 3322 | $description = $descriptiontitle; |
||
| 3323 | $description = dol_concatdesc($description, "-----"); |
||
| 3324 | $description = dol_concatdesc($description, $descriptionmeta); |
||
| 3325 | $description = dol_concatdesc($description, "-----"); |
||
| 3326 | $description = dol_concatdesc($description, $messagetext); |
||
| 3327 | |||
| 3328 | $descriptionfull = $description; |
||
| 3329 | $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); |
||
| 3330 | $descriptionfull = dol_concatdesc($descriptionfull, $header); |
||
| 3331 | |||
| 3332 | $candidaturetocreate->subject = $subject; |
||
| 3333 | $candidaturetocreate->message = $description; |
||
| 3334 | $candidaturetocreate->type_code = 0; |
||
| 3335 | $candidaturetocreate->category_code = null; |
||
| 3336 | $candidaturetocreate->severity_code = null; |
||
| 3337 | $candidaturetocreate->email = $from; |
||
| 3338 | //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$from; |
||
| 3339 | $candidaturetocreate->fk_user_creat = $user->id; |
||
| 3340 | $candidaturetocreate->date_creation = dol_now(); |
||
| 3341 | $candidaturetocreate->fk_project = $projectstatic->id; |
||
| 3342 | $candidaturetocreate->description = $description; |
||
| 3343 | $candidaturetocreate->note_private = $descriptionfull; |
||
| 3344 | $candidaturetocreate->entity = $conf->entity; |
||
| 3345 | $candidaturetocreate->email_msgid = $msgid; |
||
| 3346 | $candidaturetocreate->email_date = $date; // date of email |
||
| 3347 | $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT; |
||
| 3348 | //$candidaturetocreate->fk_contact = $contactstatic->id; |
||
| 3349 | |||
| 3350 | // Overwrite values with values extracted from source email. |
||
| 3351 | // This may overwrite any $projecttocreate->xxx properties. |
||
| 3352 | $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog); |
||
| 3353 | |||
| 3354 | // Set candidature ref if not yet defined |
||
| 3355 | /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status |
||
| 3356 | { |
||
| 3357 | // Get next Ref |
||
| 3358 | $defaultref = ''; |
||
| 3359 | $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON; |
||
| 3360 | |||
| 3361 | // Search template files |
||
| 3362 | $file = ''; $classname = ''; $filefound = 0; $reldir = ''; |
||
| 3363 | $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); |
||
| 3364 | foreach ($dirmodels as $reldir) |
||
| 3365 | { |
||
| 3366 | $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0); |
||
| 3367 | if (file_exists($file)) { |
||
| 3368 | $filefound = 1; |
||
| 3369 | $classname = $modele; |
||
| 3370 | break; |
||
| 3371 | } |
||
| 3372 | } |
||
| 3373 | |||
| 3374 | if ($filefound) { |
||
| 3375 | if ($savesocid > 0) { |
||
| 3376 | if ($savesocid != $candidaturetocreate->socid) { |
||
| 3377 | $errorforactions++; |
||
| 3378 | setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$candidaturetocreate->socid.') by setting socid in operation with a different value', null, 'errors'); |
||
| 3379 | } |
||
| 3380 | } else { |
||
| 3381 | if ($candidaturetocreate->socid > 0) |
||
| 3382 | { |
||
| 3383 | $thirdpartystatic->fetch($candidaturetocreate->socid); |
||
| 3384 | } |
||
| 3385 | } |
||
| 3386 | |||
| 3387 | $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php'); |
||
| 3388 | $modModuleToUseForNextValue = new $classname; |
||
| 3389 | $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); |
||
| 3390 | } |
||
| 3391 | $candidaturetocreate->ref = $defaultref; |
||
| 3392 | }*/ |
||
| 3393 | |||
| 3394 | if ($errorforthisaction) { |
||
| 3395 | $errorforactions++; |
||
| 3396 | } else { |
||
| 3397 | // Create project |
||
| 3398 | $result = $candidaturetocreate->create($user); |
||
| 3399 | if ($result <= 0) { |
||
| 3400 | $errorforactions++; |
||
| 3401 | $this->error = 'Failed to create candidature: ' . implode(', ', $candidaturetocreate->errors); |
||
| 3402 | $this->errors = $candidaturetocreate->errors; |
||
| 3403 | } |
||
| 3404 | |||
| 3405 | $operationslog .= '<br>Candidature created without attachments -> id=' . dol_escape_htmltag($candidaturetocreate->id); |
||
| 3406 | } |
||
| 3407 | } |
||
| 3408 | } elseif (substr($operation['type'], 0, 4) == 'hook') { |
||
| 3409 | // Create event specific on hook |
||
| 3410 | // this code action is hook..... for support this call |
||
| 3411 | if (!is_object($hookmanager)) { |
||
| 3412 | include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; |
||
| 3413 | $hookmanager = new HookManager($this->db); |
||
| 3414 | $hookmanager->initHooks(['emailcolector']); |
||
| 3415 | } |
||
| 3416 | |||
| 3417 | $parameters = array( |
||
| 3418 | 'connection' => $connection, |
||
| 3419 | 'imapemail' => $imapemail, |
||
| 3420 | 'overview' => $overview, |
||
| 3421 | |||
| 3422 | 'from' => $from, |
||
| 3423 | 'fromtext' => $fromtext, |
||
| 3424 | |||
| 3425 | 'actionparam' => $operation['actionparam'], |
||
| 3426 | |||
| 3427 | 'thirdpartyid' => $thirdpartyid, |
||
| 3428 | 'objectid' => $objectid, |
||
| 3429 | 'objectemail' => $objectemail, |
||
| 3430 | |||
| 3431 | 'messagetext' => $messagetext, |
||
| 3432 | 'subject' => $subject, |
||
| 3433 | 'header' => $header, |
||
| 3434 | 'attachments' => $attachments, |
||
| 3435 | ); |
||
| 3436 | $reshook = $hookmanager->executeHooks('doCollectImapOneCollector', $parameters, $this, $operation['type']); |
||
| 3437 | |||
| 3438 | if ($reshook < 0) { |
||
| 3439 | $errorforthisaction++; |
||
| 3440 | $this->error = $hookmanager->resPrint; |
||
| 3441 | } |
||
| 3442 | if ($errorforthisaction) { |
||
| 3443 | $errorforactions++; |
||
| 3444 | $operationslog .= '<br>Hook doCollectImapOneCollector executed with error'; |
||
| 3445 | } else { |
||
| 3446 | $operationslog .= '<br>Hook doCollectImapOneCollector executed without error'; |
||
| 3447 | } |
||
| 3448 | } |
||
| 3449 | |||
| 3450 | if (!$errorforactions) { |
||
| 3451 | $nbactiondoneforemail++; |
||
| 3452 | } |
||
| 3453 | } |
||
| 3454 | } |
||
| 3455 | |||
| 3456 | // Error for email or not ? |
||
| 3457 | if (!$errorforactions) { |
||
| 3458 | if (!empty($targetdir)) { |
||
| 3459 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 3460 | // Move mail using PHP-IMAP |
||
| 3461 | dol_syslog("EmailCollector::doCollectOneCollector move message " . ($imapemail->getHeader()->get('subject')) . " to " . $targetdir, LOG_DEBUG); |
||
| 3462 | |||
| 3463 | if (empty($mode)) { // $mode > 0 is test |
||
| 3464 | $operationslog .= '<br>Move mail ' . ($this->uidAsString($imapemail)) . ' - ' . $msgid . ' to ' . $targetdir; |
||
| 3465 | |||
| 3466 | $tmptargetdir = $targetdir; |
||
| 3467 | if (!getDolGlobalString('MAIL_DISABLE_UTF7_ENCODE_OF_DIR')) { |
||
| 3468 | $tmptargetdir = $this->getEncodedUtf7($targetdir); |
||
| 3469 | } |
||
| 3470 | |||
| 3471 | try { |
||
| 3472 | $result = $imapemail->move($tmptargetdir); |
||
| 3473 | } catch (Exception $e) { |
||
| 3474 | // Nothing to do. $result will remain 0 |
||
| 3475 | } |
||
| 3476 | if (empty($result)) { |
||
| 3477 | dol_syslog("Failed to move email into target directory " . $targetdir); |
||
| 3478 | $operationslog .= '<br>Failed to move email into target directory ' . $targetdir; |
||
| 3479 | $errorforemail++; |
||
| 3480 | } |
||
| 3481 | } else { |
||
| 3482 | $operationslog .= '<br>Do not move mail ' . ($this->uidAsString($imapemail)) . ' - ' . $msgid . ' (test mode)'; |
||
| 3483 | } |
||
| 3484 | } else { |
||
| 3485 | dol_syslog("EmailCollector::doCollectOneCollector move message " . ($this->uidAsString($imapemail)) . " to " . $connectstringtarget, LOG_DEBUG); |
||
| 3486 | $operationslog .= '<br>Move mail ' . ($this->uidAsString($imapemail)) . ' - ' . $msgid; |
||
| 3487 | |||
| 3488 | $arrayofemailtodelete[$imapemail] = $msgid; |
||
| 3489 | // Note: Real move is done later using $arrayofemailtodelete |
||
| 3490 | } |
||
| 3491 | } else { |
||
| 3492 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 3493 | dol_syslog("EmailCollector::doCollectOneCollector message '" . ($imapemail->getHeader()->get('subject')) . "' using this->host=" . $this->host . ", this->access_type=" . $this->acces_type . " was set to read", LOG_DEBUG); |
||
| 3494 | } else { |
||
| 3495 | dol_syslog("EmailCollector::doCollectOneCollector message " . ($this->uidAsString($imapemail)) . " to " . $connectstringtarget . " was set to read", LOG_DEBUG); |
||
| 3496 | } |
||
| 3497 | } |
||
| 3498 | } else { |
||
| 3499 | $errorforemail++; |
||
| 3500 | } |
||
| 3501 | |||
| 3502 | |||
| 3503 | unset($objectemail); |
||
| 3504 | unset($projectstatic); |
||
| 3505 | unset($thirdpartystatic); |
||
| 3506 | unset($contactstatic); |
||
| 3507 | |||
| 3508 | $nbemailprocessed++; |
||
| 3509 | |||
| 3510 | if (!$errorforemail) { |
||
| 3511 | $nbactiondone += $nbactiondoneforemail; |
||
| 3512 | $nbemailok++; |
||
| 3513 | |||
| 3514 | if (empty($mode)) { |
||
| 3515 | $this->db->commit(); |
||
| 3516 | } else { |
||
| 3517 | $this->db->rollback(); |
||
| 3518 | } |
||
| 3519 | |||
| 3520 | // Stop the loop to process email if we reach maximum collected per collect |
||
| 3521 | if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) { |
||
| 3522 | dol_syslog("EmailCollect::doCollectOneCollector We reach maximum of " . $nbemailok . " collected with success, so we stop this collector now."); |
||
| 3523 | break; |
||
| 3524 | } |
||
| 3525 | } else { |
||
| 3526 | $error++; |
||
| 3527 | |||
| 3528 | $this->db->rollback(); |
||
| 3529 | } |
||
| 3530 | } |
||
| 3531 | |||
| 3532 | $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone); |
||
| 3533 | |||
| 3534 | dol_syslog("End of loop on emails", LOG_INFO, -1); |
||
| 3535 | } else { |
||
| 3536 | $langs->load("admin"); |
||
| 3537 | $output = $langs->trans('NoNewEmailToProcess'); |
||
| 3538 | $output .= ' (defaultlang=' . $langs->defaultlang . ')'; |
||
| 3539 | } |
||
| 3540 | |||
| 3541 | // Disconnect |
||
| 3542 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 3543 | $client->disconnect(); |
||
| 3544 | } else { |
||
| 3545 | foreach ($arrayofemailtodelete as $imapemail => $msgid) { |
||
| 3546 | dol_syslog("EmailCollect::doCollectOneCollector delete email " . $imapemail . " " . $msgid); |
||
| 3547 | |||
| 3548 | $operationslog .= "<br> delete email " . $imapemail . " " . $msgid; |
||
| 3549 | |||
| 3550 | if (empty($mode) && empty($error)) { |
||
| 3551 | $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID); |
||
| 3552 | if ($res == false) { |
||
| 3553 | // $errorforemail++; // Not in loop, not needed, not initialised |
||
| 3554 | $this->error = imap_last_error(); |
||
| 3555 | $this->errors[] = $this->error; |
||
| 3556 | |||
| 3557 | $operationslog .= '<br>Error in move ' . $this->error; |
||
| 3558 | |||
| 3559 | dol_syslog(imap_last_error()); |
||
| 3560 | } |
||
| 3561 | } |
||
| 3562 | } |
||
| 3563 | |||
| 3564 | if (empty($mode) && empty($error)) { |
||
| 3565 | dol_syslog("Expunge", LOG_DEBUG); |
||
| 3566 | $operationslog .= "<br>Expunge"; |
||
| 3567 | |||
| 3568 | imap_expunge($connection); // To validate all moves |
||
| 3569 | } |
||
| 3570 | imap_close($connection); |
||
| 3571 | } |
||
| 3572 | |||
| 3573 | $this->datelastresult = $now; |
||
| 3574 | $this->lastresult = $output; |
||
| 3575 | if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) { |
||
| 3576 | $this->debuginfo .= 'IMAP search array used : ' . $search; |
||
| 3577 | } else { |
||
| 3578 | $this->debuginfo .= 'IMAP search string used : ' . $search; |
||
| 3579 | } |
||
| 3580 | if ($searchhead) { |
||
| 3581 | $this->debuginfo .= '<br>Then search string into email header : ' . dol_escape_htmltag($searchhead); |
||
| 3582 | } |
||
| 3583 | if ($operationslog) { |
||
| 3584 | $this->debuginfo .= $operationslog; |
||
| 3585 | } |
||
| 3586 | |||
| 3587 | if (empty($error) && empty($mode)) { |
||
| 3588 | $this->datelastok = $now; |
||
| 3589 | } |
||
| 3590 | |||
| 3591 | if (!empty($this->errors)) { |
||
| 3592 | $this->lastresult .= "<br>" . implode("<br>", $this->errors); |
||
| 3593 | } |
||
| 3594 | $this->codelastresult = ($error ? 'KO' : 'OK'); |
||
| 3595 | |||
| 3596 | if (empty($mode)) { |
||
| 3597 | $this->update($user); |
||
| 3598 | } |
||
| 3599 | |||
| 3600 | dol_syslog("EmailCollector::doCollectOneCollector end", LOG_INFO); |
||
| 3601 | |||
| 3602 | return $error ? -1 : 1; |
||
| 3603 | } |
||
| 3604 | |||
| 3605 | |||
| 3606 | |||
| 3607 | // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation |
||
| 3608 | |||
| 3609 | /** |
||
| 3610 | * getmsg |
||
| 3611 | * |
||
| 3612 | * @param Object $mbox Structure |
||
| 3613 | * @param string $mid UID email |
||
| 3614 | * @param string $destdir Target dir for attachments. Leave blank to parse without writing to disk. |
||
| 3615 | * @return void |
||
| 3616 | */ |
||
| 3617 | private function getmsg($mbox, $mid, $destdir = '') |
||
| 3640 | } |
||
| 3641 | } |
||
| 3642 | } |
||
| 3643 | |||
| 3644 | /* partno string |
||
| 3645 | 0 multipart/mixed |
||
| 3646 | 1 multipart/alternative |
||
| 3647 | 1.1 text/plain |
||
| 3648 | 1.2 text/html |
||
| 3649 | 2 message/rfc822 |
||
| 3650 | 2 multipart/mixed |
||
| 3651 | 2.1 multipart/alternative |
||
| 3652 | 2.1.1 text/plain |
||
| 3653 | 2.1.2 text/html |
||
| 3654 | 2.2 message/rfc822 |
||
| 3655 | 2.2 multipart/alternative |
||
| 3656 | 2.2.1 text/plain |
||
| 3657 | 2.2.2 text/html |
||
| 3658 | */ |
||
| 3659 | |||
| 3660 | /** |
||
| 3661 | * Sub function for getpart(). Only called by createPartArray() and itself. |
||
| 3662 | * |
||
| 3663 | * @param Object $mbox Structure |
||
| 3664 | * @param string $mid Part no |
||
| 3665 | * @param Object $p Object p |
||
| 3666 | * @param string $partno Partno |
||
| 3667 | * @param string $destdir Target dir for attachments. Leave blank to parse without writing to disk. |
||
| 3668 | * @return void |
||
| 3669 | */ |
||
| 3670 | private function getpart($mbox, $mid, $p, $partno, $destdir = '') |
||
| 3671 | { |
||
| 3672 | // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple |
||
| 3673 | global $htmlmsg, $plainmsg, $charset, $attachments; |
||
| 3674 | |||
| 3675 | // DECODE DATA |
||
| 3676 | $data = ($partno) ? |
||
| 3677 | imap_fetchbody($mbox, $mid, $partno, FT_UID) : // multipart @phan-suppress-current-line PhanTypeMismatchArgumentInternal |
||
| 3678 | imap_body($mbox, $mid, FT_UID); // simple @phan-suppress-current-line PhanTypeMismatchArgumentInternal |
||
| 3679 | // Any part may be encoded, even plain text messages, so check everything. |
||
| 3680 | if ($p->encoding == 4) { |
||
| 3681 | $data = quoted_printable_decode($data); |
||
| 3682 | } elseif ($p->encoding == 3) { |
||
| 3683 | $data = base64_decode($data); |
||
| 3684 | } |
||
| 3685 | |||
| 3686 | // PARAMETERS |
||
| 3687 | // get all parameters, like charset, filenames of attachments, etc. |
||
| 3688 | $params = array(); |
||
| 3689 | if ($p->parameters) { |
||
| 3690 | foreach ($p->parameters as $x) { |
||
| 3691 | $params[strtolower($x->attribute)] = $x->value; |
||
| 3692 | } |
||
| 3693 | } |
||
| 3694 | if (!empty($p->dparameters)) { |
||
| 3695 | foreach ($p->dparameters as $x) { |
||
| 3696 | $params[strtolower($x->attribute)] = $x->value; |
||
| 3697 | } |
||
| 3698 | } |
||
| 3699 | '@phan-var-force array{filename?:string,name?:string,charset?:string} $params'; |
||
| 3700 | |||
| 3701 | // ATTACHMENT |
||
| 3702 | // Any part with a filename is an attachment, |
||
| 3703 | // so an attached text file (type 0) is not mistaken as the message. |
||
| 3704 | if (!empty($params['filename']) || !empty($params['name'])) { |
||
| 3705 | // filename may be given as 'Filename' or 'Name' or both |
||
| 3706 | $filename = $params['filename'] ?? $params['name']; |
||
| 3707 | // filename may be encoded, so see imap_mime_header_decode() |
||
| 3708 | $attachments[$filename] = $data; // this is a problem if two files have same name |
||
| 3709 | |||
| 3710 | if (strlen($destdir)) { |
||
| 3711 | if (substr($destdir, -1) != '/') { |
||
| 3712 | $destdir .= '/'; |
||
| 3713 | } |
||
| 3714 | |||
| 3715 | // Get file name (with extension) |
||
| 3716 | $file_name_complete = $filename; |
||
| 3717 | $destination = $destdir . $file_name_complete; |
||
| 3718 | |||
| 3719 | // Extract file extension |
||
| 3720 | $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION); |
||
| 3721 | |||
| 3722 | // Extract file name without extension |
||
| 3723 | $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME); |
||
| 3724 | |||
| 3725 | // Save an original file name variable to track while renaming if file already exists |
||
| 3726 | $file_name_original = $file_name; |
||
| 3727 | |||
| 3728 | // Increment file name by 1 |
||
| 3729 | $num = 1; |
||
| 3730 | |||
| 3731 | /** |
||
| 3732 | * Check if the same file name already exists in the upload folder, |
||
| 3733 | * append increment number to the original filename |
||
| 3734 | */ |
||
| 3735 | while (file_exists($destdir . $file_name . "." . $extension)) { |
||
| 3736 | $file_name = $file_name_original . ' (' . $num . ')'; |
||
| 3737 | $file_name_complete = $file_name . "." . $extension; |
||
| 3738 | $destination = $destdir . $file_name_complete; |
||
| 3739 | $num++; |
||
| 3740 | } |
||
| 3741 | |||
| 3742 | $destination = dol_sanitizePathName($destination); |
||
| 3743 | |||
| 3744 | file_put_contents($destination, $data); |
||
| 3745 | } |
||
| 3746 | } |
||
| 3747 | |||
| 3748 | // TEXT |
||
| 3749 | if ($p->type == 0 && $data) { |
||
| 3750 | if (!empty($params['charset'])) { |
||
| 3751 | $data = $this->convertStringEncoding($data, $params['charset']); |
||
| 3752 | } |
||
| 3753 | // Messages may be split in different parts because of inline attachments, |
||
| 3754 | // so append parts together with blank row. |
||
| 3755 | if (strtolower($p->subtype) == 'plain') { |
||
| 3756 | $plainmsg .= trim($data) . "\n\n"; |
||
| 3757 | } else { |
||
| 3758 | $htmlmsg .= $data . "<br><br>"; |
||
| 3759 | } |
||
| 3760 | $charset = $params['charset']; // assume all parts are same charset |
||
| 3761 | } elseif ($p->type == 2 && $data) { |
||
| 3762 | // EMBEDDED MESSAGE |
||
| 3763 | // Many bounce notifications embed the original message as type 2, |
||
| 3764 | // but AOL uses type 1 (multipart), which is not handled here. |
||
| 3765 | // There are no PHP functions to parse embedded messages, |
||
| 3766 | // so this just appends the raw source to the main message. |
||
| 3767 | if (!empty($params['charset'])) { |
||
| 3768 | $data = $this->convertStringEncoding($data, $params['charset']); |
||
| 3769 | } |
||
| 3770 | $plainmsg .= $data . "\n\n"; |
||
| 3771 | } |
||
| 3772 | |||
| 3773 | // SUBPART RECURSION |
||
| 3774 | if (!empty($p->parts)) { |
||
| 3775 | foreach ($p->parts as $partno0 => $p2) { |
||
| 3776 | $this->getpart($mbox, $mid, $p2, $partno . '.' . ($partno0 + 1), $destdir); // 1.2, 1.2.1, etc. |
||
| 3777 | } |
||
| 3778 | } |
||
| 3779 | } |
||
| 3780 | |||
| 3781 | /** |
||
| 3782 | * Converts a string from one encoding to another. |
||
| 3783 | * |
||
| 3784 | * @param string $string String to convert |
||
| 3785 | * @param string $fromEncoding String encoding |
||
| 3786 | * @param string $toEncoding String return encoding |
||
| 3787 | * @return string Converted string if conversion was successful, or the original string if not |
||
| 3788 | * @throws Exception |
||
| 3789 | */ |
||
| 3790 | protected function convertStringEncoding($string, $fromEncoding, $toEncoding = 'UTF-8') |
||
| 3791 | { |
||
| 3792 | if (!$string || $fromEncoding == $toEncoding) { |
||
| 3793 | return $string; |
||
| 3794 | } |
||
| 3795 | $convertedString = function_exists('iconv') ? @iconv($fromEncoding, $toEncoding . '//IGNORE', $string) : null; |
||
| 3796 | if (!$convertedString && extension_loaded('mbstring')) { |
||
| 3797 | $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding); |
||
| 3798 | } |
||
| 3799 | if (!$convertedString) { |
||
| 3800 | throw new Exception('Mime string encoding conversion failed'); |
||
| 3801 | } |
||
| 3802 | return $convertedString; |
||
| 3803 | } |
||
| 3804 | |||
| 3805 | /** |
||
| 3806 | * Decode a subject string according to RFC2047 |
||
| 3807 | * Example: '=?Windows-1252?Q?RE=A0:_ABC?=' => 'RE : ABC...' |
||
| 3808 | * Example: '=?UTF-8?Q?A=C3=A9B?=' => 'AéB' |
||
| 3809 | * Example: '=?UTF-8?B?2KLYstmF2KfbjNi0?=' => |
||
| 3810 | * Example: '=?utf-8?B?UkU6IG1vZHVsZSBkb2xpYmFyciBnZXN0aW9ubmFpcmUgZGUgZmljaGllcnMg?= =?utf-8?B?UsOpZsOpcmVuY2UgZGUgbGEgY29tbWFuZGUgVFVHRURJSklSIOKAkyBwYXNz?= =?utf-8?B?w6llIGxlIDIyLzA0LzIwMjA=?=' |
||
| 3811 | * |
||
| 3812 | * @param string $subject Subject |
||
| 3813 | * @return string Decoded subject (in UTF-8) |
||
| 3814 | */ |
||
| 3815 | protected function decodeSMTPSubject($subject) |
||
| 3816 | { |
||
| 3817 | // Decode $overview[0]->subject according to RFC2047 |
||
| 3818 | // Can use also imap_mime_header_decode($str) |
||
| 3819 | // Can use also mb_decode_mimeheader($str) |
||
| 3820 | // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8') |
||
| 3821 | if (function_exists('imap_mime_header_decode') && function_exists('iconv_mime_decode')) { |
||
| 3822 | $elements = imap_mime_header_decode($subject); |
||
| 3823 | $newstring = ''; |
||
| 3824 | if (!empty($elements)) { |
||
| 3825 | $num = count($elements); |
||
| 3826 | for ($i = 0; $i < $num; $i++) { |
||
| 3827 | $stringinutf8 = (in_array(strtoupper($elements[$i]->charset), array('DEFAULT', 'UTF-8')) ? $elements[$i]->text : iconv_mime_decode($elements[$i]->text, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $elements[$i]->charset)); |
||
| 3828 | $newstring .= $stringinutf8; |
||
| 3829 | } |
||
| 3830 | $subject = $newstring; |
||
| 3831 | } |
||
| 3832 | } elseif (!function_exists('mb_decode_mimeheader')) { |
||
| 3833 | $subject = mb_decode_mimeheader($subject); |
||
| 3834 | } elseif (function_exists('iconv_mime_decode')) { |
||
| 3835 | $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8'); |
||
| 3836 | } |
||
| 3837 | |||
| 3838 | return $subject; |
||
| 3839 | } |
||
| 3840 | |||
| 3841 | /** |
||
| 3842 | * saveAttachment |
||
| 3843 | * |
||
| 3844 | * @param string $destdir destination |
||
| 3845 | * @param string $filename filename |
||
| 3846 | * @param string $content content |
||
| 3847 | * @return void |
||
| 3848 | */ |
||
| 3849 | private function saveAttachment($destdir, $filename, $content) |
||
| 3868 | } |
||
| 3869 | |||
| 3870 | /** |
||
| 3871 | * Get UID of message as a string |
||
| 3872 | * |
||
| 3873 | * @param int|Webklex\PHPIMAP\Message $imapemail UID as int (if native IMAP) or as object (if external library) |
||
| 3874 | * @return string UID as string |
||
| 3875 | */ |
||
| 3876 | protected function uidAsString($imapemail) |
||
| 3877 | { |
||
| 3882 | } |
||
| 3883 | } |
||
| 3884 | } |
||
| 3885 |