1082 global $db, $conf, $langs, $user;
1083 global $hookmanager;
1087 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1088 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1089 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1092 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1094 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1099 $this->debuginfo =
'';
1103 $searchfilterdoltrackid = 0;
1104 $searchfilternodoltrackid = 0;
1105 $searchfilterisanswer = 0;
1106 $searchfilterisnotanswer = 0;
1107 $searchfilterreplyto = 0;
1108 $searchfilterexcludebodyarray = array();
1109 $searchfilterexcludesubjectarray = array();
1110 $operationslog =
'';
1115 if (empty($this->host)) {
1116 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1119 if (empty($this->login)) {
1120 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1123 if (empty($this->source_directory)) {
1124 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1131 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1133 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1134 if ($this->acces_type == 1) {
1136 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1137 $keyforsupportedoauth2array = $this->oauth_service;
1138 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1139 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1141 $keyforprovider =
'';
1143 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1144 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1146 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1148 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1154 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1157 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1165 if (is_object($tokenobj) && $expire) {
1166 $credentials =
new Credentials(
1171 $serviceFactory = new \OAuth\ServiceFactory();
1172 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1174 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1176 $refreshtoken = $tokenobj->getRefreshToken();
1177 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1178 $tokenobj->setRefreshToken($refreshtoken);
1179 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1181 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1182 if (is_object($tokenobj)) {
1183 $token = $tokenobj->getAccessToken();
1185 $this->error =
"Token not found";
1190 $this->error = $e->getMessage();
1191 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1195 $cm =
new ClientManager();
1196 $client = $cm->make([
1197 'host' => $this->host,
1198 'port' => $this->port,
1199 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption :
false,
1200 'validate_cert' =>
true,
1201 'protocol' =>
'imap',
1202 'username' => $this->login,
1203 'password' => $token,
1204 'authentication' =>
"oauth",
1208 $cm =
new ClientManager();
1209 $client = $cm->make([
1210 'host' => $this->host,
1211 'port' => $this->port,
1212 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption :
false,
1213 'validate_cert' =>
true,
1214 'protocol' =>
'imap',
1215 'username' => $this->login,
1216 'password' => $this->password,
1217 'authentication' =>
"login",
1223 }
catch (ConnectionFailedException $e) {
1224 $this->error = $e->getMessage();
1225 $this->errors[] = $this->error;
1226 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1230 $host = dol_getprefix(
'email');
1233 if (!function_exists(
'imap_open')) {
1234 $this->error =
'IMAP function not enabled on your PHP';
1237 $sourcedir = $this->source_directory;
1240 $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
1241 $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
1243 $connection = imap_open($connectstringsource, $this->login, $this->password);
1245 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1250 $host = dol_getprefix(
'email');
1259 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1261 $criteria = array(array(
'UNDELETED'));
1262 foreach ($this->filters as $rule) {
1263 if (empty($rule[
'status'])) {
1268 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1272 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1275 if ($rule[
'type'] ==
'from') {
1276 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1277 if (count($tmprulevaluearray) >= 2) {
1278 foreach ($tmprulevaluearray as $tmprulevalue) {
1279 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1282 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1285 if ($rule[
'type'] ==
'to') {
1286 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1287 if (count($tmprulevaluearray) >= 2) {
1288 foreach ($tmprulevaluearray as $tmprulevalue) {
1289 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1292 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1295 if ($rule[
'type'] ==
'bcc') {
1296 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1298 if ($rule[
'type'] ==
'cc') {
1299 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1301 if ($rule[
'type'] ==
'subject') {
1302 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1304 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1306 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1309 if ($rule[
'type'] ==
'body') {
1310 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1312 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1314 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1317 if ($rule[
'type'] ==
'header') {
1318 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1330 if ($rule[
'type'] ==
'seen') {
1331 array_push($criteria, array($not.
"SEEN"));
1333 if ($rule[
'type'] ==
'unseen') {
1334 array_push($criteria, array($not.
"UNSEEN"));
1336 if ($rule[
'type'] ==
'unanswered') {
1337 array_push($criteria, array($not.
"UNANSWERED"));
1339 if ($rule[
'type'] ==
'answered') {
1340 array_push($criteria, array($not.
"ANSWERED"));
1342 if ($rule[
'type'] ==
'smaller') {
1343 array_push($criteria, array($not.
"SMALLER"));
1345 if ($rule[
'type'] ==
'larger') {
1346 array_push($criteria, array($not.
"LARGER"));
1350 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1351 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1353 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1354 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1356 if ($rule[
'type'] ==
'withtrackingid') {
1357 $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1359 if ($rule[
'type'] ==
'withouttrackingid') {
1360 $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1363 if ($rule[
'type'] ==
'isanswer') {
1364 $searchfilterisanswer++; $searchhead .=
'/References.*@.*/';
1366 if ($rule[
'type'] ==
'isnotanswer') {
1367 $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/';
1370 if ($rule[
'type'] ==
'replyto') {
1371 $searchfilterreplyto++; $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1375 if (empty($targetdir)) {
1377 if ($this->datelastok) {
1378 $fromdate = $this->datelastok;
1380 if ($fromdate > 0) {
1382 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1387 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1388 $search = var_export($criteria,
true);
1391 $search =
'UNDELETED';
1392 foreach ($this->filters as $rule) {
1393 if (empty($rule[
'status'])) {
1401 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1405 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1408 if ($rule[
'type'] ==
'from') {
1409 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1410 if (count($tmprulevaluearray) >= 2) {
1411 foreach ($tmprulevaluearray as $tmprulevalue) {
1412 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1415 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1418 if ($rule[
'type'] ==
'to') {
1419 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1420 if (count($tmprulevaluearray) >= 2) {
1421 foreach ($tmprulevaluearray as $tmprulevalue) {
1422 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1425 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1428 if ($rule[
'type'] ==
'bcc') {
1429 $search .= ($search ?
' ' :
'').$not.
'BCC';
1431 if ($rule[
'type'] ==
'cc') {
1432 $search .= ($search ?
' ' :
'').$not.
'CC';
1434 if ($rule[
'type'] ==
'subject') {
1435 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1437 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1439 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1442 if ($rule[
'type'] ==
'body') {
1443 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1445 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1448 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1451 if ($rule[
'type'] ==
'header') {
1452 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1464 if ($rule[
'type'] ==
'seen') {
1465 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1467 if ($rule[
'type'] ==
'unseen') {
1468 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1470 if ($rule[
'type'] ==
'unanswered') {
1471 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1473 if ($rule[
'type'] ==
'answered') {
1474 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1476 if ($rule[
'type'] ==
'smaller') {
1477 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1479 if ($rule[
'type'] ==
'larger') {
1480 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1484 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1485 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1487 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1488 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1490 if ($rule[
'type'] ==
'withtrackingid') {
1491 $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1493 if ($rule[
'type'] ==
'withouttrackingid') {
1494 $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1497 if ($rule[
'type'] ==
'isanswer') {
1498 $searchfilterisanswer++; $searchhead .=
'/References.*@.*/';
1500 if ($rule[
'type'] ==
'isnotanswer') {
1501 $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/';
1504 if ($rule[
'type'] ==
'replyto') {
1505 $searchfilterreplyto++; $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1509 if (empty($targetdir)) {
1511 if ($this->datelastok) {
1512 $fromdate = $this->datelastok;
1514 if ($fromdate > 0) {
1515 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1524 $nbemailprocessed = 0;
1527 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1529 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1533 $f = $client->getFolders(
false, $this->source_directory);
1534 $Query = $f[0]->messages()->where($criteria);
1535 }
catch (InvalidWhereQueryCriteriaException $e) {
1536 $this->error = $e->getMessage();
1537 $this->errors[] = $this->error;
1538 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1541 $this->error = $e->getMessage();
1542 $this->errors[] = $this->error;
1543 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1550 $Query->leaveUnread();
1552 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1555 $this->error = $e->getMessage();
1556 $this->errors[] = $this->error;
1557 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1562 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1564 if ($arrayofemail ===
false) {
1566 $mapoferrrors = imap_errors();
1567 if ($mapoferrrors !==
false) {
1569 $this->error =
"Search string not understood - ".join(
',', $mapoferrrors);
1570 $this->errors[] = $this->error;
1575 $arrayofemailtodelete = array();
1578 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1595 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1598 foreach ($arrayofemail as $imapemail) {
1599 if ($nbemailprocessed > 1000) {
1606 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1607 $header = $imapemail->getHeader()->raw;
1608 $overview = $imapemail->getAttributes();
1610 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1611 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1614 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1617 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
1618 $headers = array_combine($matches[1], $matches[2]);
1621 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1622 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1624 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1625 $headers[
'References'] = $headers[
'references'];
1627 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1628 $headers[
'Message-ID'] = $headers[
'message-id'];
1630 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1631 $headers[
'Subject'] = $headers[
'subject'];
1639 dol_syslog(
"** Process email ".$iforemailloop.
" References: ".$headers[
'References'].
" Subject: ".$headers[
'Subject']);
1642 $trackidfoundintorecipienttype =
'';
1643 $trackidfoundintorecipientid = 0;
1646 if (preg_match(
'/\+(thi|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) {
1647 $trackidfoundintorecipienttype = $reg[1];
1648 $trackidfoundintorecipientid = $reg[2];
1649 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1650 $trackidfoundintorecipienttype =
'emailing';
1651 $trackidfoundintorecipientid = $reg[1];
1655 if ($searchfilterdoltrackid > 0) {
1656 if (empty($trackidfoundintorecipienttype)) {
1657 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1658 $nbemailprocessed++;
1659 dol_syslog(
" Discarded - No suffix in email recipient and no Header References found matching signature of application so with a trackid");
1664 if ($searchfilternodoltrackid > 0) {
1665 if (!empty($trackidfoundintorecipienttype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1666 $nbemailprocessed++;
1667 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1672 if ($searchfilterisanswer > 0) {
1673 if (empty($headers[
'In-Reply-To'])) {
1674 $nbemailprocessed++;
1675 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1681 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1688 $nbemailprocessed++;
1689 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1693 if ($searchfilterisnotanswer > 0) {
1694 if (!empty($headers[
'In-Reply-To'])) {
1698 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1704 $nbemailprocessed++;
1705 dol_syslog(
" Discarded - Email is an answer");
1713 $thirdpartystatic =
new Societe($this->db);
1714 $contactstatic =
new Contact($this->db);
1715 $projectstatic =
new Project($this->db);
1717 $nbactiondoneforemail = 0;
1719 $errorforactions = 0;
1720 $thirdpartyfoundby =
'';
1721 $contactfoundby =
'';
1722 $projectfoundby =
'';
1723 $ticketfoundby =
'';
1724 $candidaturefoundby =
'';
1727 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1728 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1731 $overview[
'subject'] = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[
'subject']);
1733 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);
1740 $overview[0]->subject = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[0]->subject);
1743 global $htmlmsg, $plainmsg, $charset, $attachments;
1745 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1746 if ($imapemail->hasHTMLBody()) {
1747 $htmlmsg = $imapemail->getHTMLBody();
1749 if ($imapemail->hasTextBody()) {
1750 $plainmsg = $imapemail->getTextBody();
1752 if ($imapemail->hasAttachments()) {
1753 $attachments = $imapemail->getAttachments()->all();
1758 $getMsg = $this->
getmsg($connection, $imapemail);
1760 $this->errors = array_merge($this->errors, [$this->error]);
1775 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1776 dol_syslog(
" Discarded - Email body is not valid utf8");
1780 if (!empty($searchfilterexcludebodyarray)) {
1781 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
1782 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
1783 $nbemailprocessed++;
1784 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
1785 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
1847 $replytostring =
'';
1849 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1850 $fromstring = $overview[
'from'];
1853 $sender = $overview[
'sender'];
1854 $to = $overview[
'to'];
1855 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
1856 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
1857 $date = $overview[
'date'];
1858 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1859 $subject = $overview[
'subject'];
1861 $fromstring = $overview[0]->from;
1864 $sender = $overview[0]->sender;
1865 $to = $overview[0]->to;
1866 $sendtocc = $overview[0]->cc;
1867 $sendtobcc = $overview[0]->bcc;
1868 $date = $overview[0]->udate;
1869 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1870 $subject = $overview[0]->subject;
1874 if (!empty($searchfilterexcludesubjectarray)) {
1875 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
1876 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
1877 $nbemailprocessed++;
1878 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
1879 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
1886 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
1888 $fromtext = $reg[1];
1890 $from = $fromstring;
1893 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
1895 $replytotext = $reg[1];
1897 $replyto = $replytostring;
1900 $fk_element_id = 0; $fk_element_type =
'';
1904 $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
1912 $objectemail =
null;
1915 if (!empty($headers[
'References'])) {
1916 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
1920 foreach ($arrayofreferences as $reference) {
1922 if (!empty($trackidfoundintorecipienttype)) {
1923 $resultsearchtrackid = -1;
1924 $reg[1] = $trackidfoundintorecipienttype;
1925 $reg[2] = $trackidfoundintorecipientid;
1927 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
1928 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
1929 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
1933 if (!empty($resultsearchtrackid)) {
1935 $trackid = $reg[1].$reg[2];
1937 $objectid = $reg[2];
1939 if ($reg[1] ==
'thi') {
1940 $objectemail =
new Societe($this->db);
1942 if ($reg[1] ==
'ctc') {
1943 $objectemail =
new Contact($this->db);
1945 if ($reg[1] ==
'inv') {
1946 $objectemail =
new Facture($this->db);
1948 if ($reg[1] ==
'sinv') {
1951 if ($reg[1] ==
'pro') {
1952 $objectemail =
new Propal($this->db);
1954 if ($reg[1] ==
'ord') {
1955 $objectemail =
new Commande($this->db);
1957 if ($reg[1] ==
'shi') {
1960 if ($reg[1] ==
'spro') {
1963 if ($reg[1] ==
'sord') {
1966 if ($reg[1] ==
'rec') {
1967 $objectemail =
new Reception($this->db);
1969 if ($reg[1] ==
'proj') {
1970 $objectemail =
new Project($this->db);
1972 if ($reg[1] ==
'tas') {
1973 $objectemail =
new Task($this->db);
1975 if ($reg[1] ==
'con') {
1976 $objectemail =
new Contact($this->db);
1978 if ($reg[1] ==
'use') {
1979 $objectemail =
new User($this->db);
1981 if ($reg[1] ==
'tic') {
1982 $objectemail =
new Ticket($this->db);
1984 if ($reg[1] ==
'recruitmentcandidature') {
1987 if ($reg[1] ==
'mem') {
1988 $objectemail =
new Adherent($this->db);
1996 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
1998 if (!is_object($objectemail)) {
1999 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket where email_msgid = '".$this->db->escape($reg[1]).
"'";
2000 $resql = $this->db->query($sql);
2002 $obj = $this->db->fetch_object($resql);
2004 $objectid = $obj->rowid;
2005 $objectemail =
new Ticket($this->db);
2006 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2013 if (!is_object($objectemail)) {
2014 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2015 $resql = $this->db->query($sql);
2017 $obj = $this->db->fetch_object($resql);
2019 $objectid = $obj->rowid;
2020 $objectemail =
new Project($this->db);
2021 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2028 if (!is_object($objectemail)) {
2029 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2030 $resql = $this->db->query($sql);
2032 $obj = $this->db->fetch_object($resql);
2034 $objectid = $obj->rowid;
2036 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2045 if (is_object($objectemail)) {
2046 $result = $objectemail->fetch($objectid);
2048 $fk_element_id = $objectemail->id;
2049 $fk_element_type = $objectemail->element;
2051 if ($fk_element_type ==
'facture') {
2052 $fk_element_type =
'invoice';
2055 if (get_class($objectemail) !=
'Societe') {
2056 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2058 $thirdpartyid = $objectemail->id;
2061 if (get_class($objectemail) !=
'Contact') {
2062 $contactid = $objectemail->fk_socpeople;
2064 $contactid = $objectemail->id;
2067 if (get_class($objectemail) !=
'Project') {
2068 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2070 $projectid = $objectemail->id;
2076 if ($projectid > 0) {
2077 $result = $projectstatic->fetch($projectid);
2079 $projectstatic->id = 0;
2081 $projectid = $projectstatic->id;
2083 $projectfoundby =
'trackid ('.$trackid.
')';
2085 if (empty($contactid)) {
2086 $contactid = $projectstatic->fk_contact;
2088 if (empty($thirdpartyid)) {
2089 $thirdpartyid = $projectstatic->fk_soc;
2094 if ($contactid > 0) {
2095 $result = $contactstatic->fetch($contactid);
2097 $contactstatic->id = 0;
2099 $contactid = $contactstatic->id;
2101 $contactfoundby =
'trackid ('.$trackid.
')';
2103 if (empty($thirdpartyid)) {
2104 $thirdpartyid = $contactstatic->fk_soc;
2109 if ($thirdpartyid > 0) {
2110 $result = $thirdpartystatic->fetch($thirdpartyid);
2112 $thirdpartystatic->id = 0;
2114 $thirdpartyid = $thirdpartystatic->id;
2116 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2121 if (is_object($objectemail)) {
2127 if (empty($contactid)) {
2128 $result = $contactstatic->fetch(0,
null,
'', $from);
2131 dol_syslog(
"We found a contact with the email ".$from);
2132 $contactid = $contactstatic->id;
2133 $contactfoundby =
'email of contact ('.$from.
')';
2134 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2135 $result = $thirdpartystatic->fetch($contactstatic->socid);
2137 $thirdpartyid = $thirdpartystatic->id;
2138 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2144 if (empty($thirdpartyid)) {
2145 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2147 dol_syslog(
"We found a thirdparty with the email ".$from);
2148 $thirdpartyid = $thirdpartystatic->id;
2149 $thirdpartyfoundby =
'email ('.$from.
')';
2185 foreach ($this->actions as $operation) {
2186 $errorforthisaction = 0;
2188 if ($errorforactions) {
2191 if (empty($operation[
'status'])) {
2195 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2198 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2199 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2201 $actioncode =
'EMAIL_IN';
2203 if ($this->source_directory ==
'Sent') {
2204 $actioncode =
'EMAIL_OUT';
2207 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2209 $descriptiontitle = $langs->trans(
"RecordCreatedByEmailCollector", $this->ref, $msgid);
2212 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2214 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2216 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2218 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2222 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2223 if (empty($operation[
'actionparam'])) {
2225 $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;";
2226 $this->errors[] = $this->error;
2228 $actionparam = $operation[
'actionparam'];
2229 $idtouseforthirdparty =
'';
2230 $nametouseforthirdparty =
'';
2231 $emailtouseforthirdparty =
'';
2232 $namealiastouseforthirdparty =
'';
2234 $operationslog .=
'<br>Loop on each property to set into actionparam';
2238 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2242 $regforregex = array();
2244 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2245 $sourcefield = $regforregex[1];
2246 $regexstring = $regforregex[2];
2249 if (!empty($sourcefield) && !empty($regexstring)) {
2250 if (strtolower($sourcefield) ==
'body') {
2251 $sourcestring = $messagetext;
2252 } elseif (strtolower($sourcefield) ==
'subject') {
2253 $sourcestring = $subject;
2254 } elseif (strtolower($sourcefield) ==
'header') {
2255 $sourcestring = $header;
2258 if ($sourcestring) {
2259 $regforval = array();
2261 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2264 if ($propertytooverwrite ==
'id') {
2265 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2267 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2268 } elseif ($propertytooverwrite ==
'email') {
2269 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2271 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2272 } elseif ($propertytooverwrite ==
'name') {
2273 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2275 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2276 } elseif ($propertytooverwrite ==
'name_alias') {
2277 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2279 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2281 $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';
2285 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2286 $idtouseforthirdparty =
null;
2287 $nametouseforthirdparty =
null;
2288 $emailtouseforthirdparty =
null;
2289 $namealiastouseforthirdparty =
null;
2291 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2293 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2300 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2301 $this->errors[] = $this->error;
2303 $operationslog .=
'<br>'.$this->error;
2305 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2309 if ($propertytooverwrite ==
'id') {
2310 $idtouseforthirdparty = $reg[2];
2312 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2313 } elseif ($propertytooverwrite ==
'email') {
2314 $emailtouseforthirdparty = $reg[2];
2316 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2317 } elseif ($propertytooverwrite ==
'name') {
2318 $nametouseforthirdparty = $reg[2];
2320 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2321 } elseif ($propertytooverwrite ==
'name_alias') {
2322 $namealiastouseforthirdparty = $reg[2];
2324 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2328 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2329 $this->errors[] = $this->error;
2334 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2336 $operationslog .=
'<br>We have this data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty;
2338 $tmpobject =
new stdClass();
2339 $tmpobject->element ==
'generic';
2340 $tmpobject->id = $idtouseforthirdparty;
2341 $tmpobject->name = $nametouseforthirdparty;
2342 $tmpobject->name_alias = $namealiastouseforthirdparty;
2343 $tmpobject->email = $emailtouseforthirdparty;
2347 $idtouseforthirdparty = $tmpobject->id;
2348 $nametouseforthirdparty = $tmpobject->name;
2349 $namealiastouseforthirdparty = $tmpobject->name_alias;
2350 $emailtouseforthirdparty = $tmpobject->email;
2352 $operationslog .=
'<br>We try to search existing thirdparty with '.$idtouseforthirdparty.
' '.$emailtouseforthirdparty.
' '.$nametouseforthirdparty.
' '.$namealiastouseforthirdparty;
2354 $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2357 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2358 $this->errors[] = $this->error;
2360 } elseif ($result == 0) {
2361 if ($operation[
'type'] ==
'loadthirdparty') {
2362 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2365 $resultContact = $contactstatic->fetch(
'',
'',
'', $emailtouseforthirdparty);
2366 if ($resultContact > 0) {
2367 $idtouseforthirdparty = $contactstatic->socid;
2368 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2370 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2373 $langs->load(
"errors");
2374 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2375 $this->errors[] = $this->error;
2379 $langs->load(
"errors");
2380 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2381 $this->errors[] = $this->error;
2383 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2384 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2387 $thirdpartystatic =
new Societe($db);
2388 $thirdpartystatic->name = $nametouseforthirdparty;
2389 if (!empty($namealiastouseforthirdparty)) {
2390 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2391 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2394 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'': $fromtext) : $replytostring);
2396 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2399 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2401 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2402 $thirdpartystatic->code_client =
'auto';
2404 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2405 $thirdpartystatic->code_fournisseur =
'auto';
2408 if ($errorforthisaction) {
2411 $result = $thirdpartystatic->create($user);
2414 $this->error = $thirdpartystatic->error;
2415 $this->errors = $thirdpartystatic->errors;
2417 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2422 dol_syslog(
"One and only one existing third party has been found");
2424 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id);
2428 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2429 if (empty($operation[
'actionparam'])) {
2431 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2432 $this->errors[] = $this->error;
2434 $contact_static =
new Contact($this->db);
2436 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2437 if ($errorforthisaction) {
2440 if (!empty($contact_static->email) && $contact_static->email != $from) $from = $contact_static->email;
2442 $result = $contactstatic->fetch(0,
null,
'', $from);
2445 $this->error =
'Error when getting contact with email ' . $from;
2446 $this->errors[] = $this->error;
2448 } elseif ($result == 0) {
2449 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2450 $contactstatic =
new Contact($this->db);
2453 $contactstatic->email = $from;
2454 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2457 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2459 if ($errorforthisaction) {
2463 if (!empty($contactstatic->country)) {
2464 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2465 $result =
getCountry(
'', 3, $this->db,
'', 1, $contactstatic->country);
2466 if ($result ==
'NotDefined') {
2468 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2469 } elseif (!($result > 0)) {
2471 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2472 $this->errors[] = $this->db->lasterror();
2474 $contactstatic->country_id = $result;
2475 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2477 } elseif (!empty($contactstatic->country_code)) {
2478 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2479 $result =
getCountry($contactstatic->country_code, 3, $this->db);
2480 if ($result ==
'NotDefined') {
2482 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2483 } elseif (!($result > 0)) {
2485 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2486 $this->errors[] = $this->db->lasterror();
2488 $contactstatic->country_id = $result;
2489 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2493 if (!$errorforactions) {
2495 if (!empty($contactstatic->state)) {
2496 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2497 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2498 if (empty($result)) {
2500 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2501 } elseif (!($result > 0)) {
2503 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2504 $this->errors[] = $this->db->lasterror();
2506 $contactstatic->state_id = $result;
2507 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2509 } elseif (!empty($contactstatic->state_code)) {
2510 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2511 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2512 if (empty($result)) {
2514 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2515 } elseif (!($result > 0)) {
2517 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2518 $this->errors[] = $this->db->lasterror();
2520 $contactstatic->state_id = $result;
2521 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2526 if (!$errorforactions) {
2527 $result = $contactstatic->create($user);
2530 $this->error = $contactstatic->error;
2531 $this->errors = $contactstatic->errors;
2533 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
2540 } elseif ($operation[
'type'] ==
'recordevent') {
2544 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2545 if ($alreadycreated == 0) {
2546 if ($projectstatic->id > 0) {
2547 if ($projectfoundby) {
2548 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2551 if ($thirdpartystatic->id > 0) {
2552 if ($thirdpartyfoundby) {
2553 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2556 if ($contactstatic->id > 0) {
2557 if ($contactfoundby) {
2558 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2562 $description = $descriptiontitle;
2568 $descriptionfull = $description;
2569 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2570 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2575 $actioncomm->type_code =
'AC_OTH_AUTO';
2576 $actioncomm->code =
'AC_'.$actioncode;
2577 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2578 $actioncomm->note_private = $descriptionfull;
2579 $actioncomm->fk_project = $projectstatic->id;
2580 $actioncomm->datep = $date;
2581 $actioncomm->datef = $date;
2582 $actioncomm->percentage = -1;
2583 $actioncomm->socid = $thirdpartystatic->id;
2584 $actioncomm->contact_id = $contactstatic->id;
2585 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id =>
'') : array());
2586 $actioncomm->authorid = $user->id;
2587 $actioncomm->userownerid = $user->id;
2589 $actioncomm->email_msgid = $msgid;
2590 $actioncomm->email_from = $fromstring;
2591 $actioncomm->email_sender = $sender;
2592 $actioncomm->email_to = $to;
2593 $actioncomm->email_tocc = $sendtocc;
2594 $actioncomm->email_tobcc = $sendtobcc;
2595 $actioncomm->email_subject = $subject;
2596 $actioncomm->errors_to =
'';
2598 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2599 $actioncomm->fk_element = $fk_element_id;
2600 $actioncomm->elementid = $fk_element_id;
2601 $actioncomm->elementtype = $fk_element_type;
2602 if (is_object($objectemail) && $objectemail->module) {
2603 $actioncomm->elementtype .=
'@'.$objectemail->module;
2610 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2619 if ($errorforthisaction) {
2622 $result = $actioncomm->create($user);
2625 $this->errors = $actioncomm->errors;
2627 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2631 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2633 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
2634 foreach ($attachments as $attachment) {
2635 if ($attachment->getName() ===
'undefined') {
2638 $data[$attachment->getName()] = $attachment->getContent();
2642 foreach ($pj as $key => $val) {
2643 $data[$val[
'filename']] =
getFileData($imapemail, $val[
'pos'], $val[
'type'], $connection);
2646 if (count($data) > 0) {
2647 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
2648 $resql = $this->db->query($sql);
2649 if ($this->db->num_rows($resql) == 0) {
2650 $this->errors[] =
"User Not allowed to add documents ({$from})";
2652 $arrayobject = array(
2653 'propale' => array(
'table' =>
'propal',
2654 'fields' => array(
'ref'),
2655 'class' =>
'comm/propal/class/propal.class.php',
2656 'object' =>
'Propal'),
2657 'holiday' => array(
'table' =>
'holiday',
2658 'fields' => array(
'ref'),
2659 'class' =>
'holiday/class/holiday.class.php',
2660 'object' =>
'Holiday'),
2661 'expensereport' => array(
'table' =>
'expensereport',
2662 'fields' => array(
'ref'),
2663 'class' =>
'expensereport/class/expensereport.class.php',
2664 'object' =>
'ExpenseReport'),
2665 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
2666 'fields' => array(
'ref'),
2667 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
2668 'object' =>
'RecruitmentJobPosition'),
2669 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
2670 'fields' => array(
'ref'),
2671 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
2672 'object' =>
' RecruitmentCandidature'),
2673 'societe' => array(
'table' =>
'societe',
2674 'fields' => array(
'code_client',
'code_fournisseur'),
2675 'class' =>
'societe/class/societe.class.php',
2676 'object' =>
'Societe'),
2677 'commande' => array(
'table' =>
'commande',
2678 'fields' => array(
'ref'),
2679 'class' =>
'commande/class/commande.class.php',
2680 'object' =>
'Commande'),
2681 'expedition' => array(
'table' =>
'expedition',
2682 'fields' => array(
'ref'),
2683 'class' =>
'expedition/class/expedition.class.php',
2684 'object' =>
'Expedition'),
2685 'contract' => array(
'table' =>
'contrat',
2686 'fields' => array(
'ref'),
2687 'class' =>
'contrat/class/contrat.class.php',
2688 'object' =>
'Contrat'),
2689 'fichinter' => array(
'table' =>
'fichinter',
2690 'fields' => array(
'ref'),
2691 'class' =>
'fichinter/class/fichinter.class.php',
2692 'object' =>
'Fichinter'),
2693 'ticket' => array(
'table' =>
'ticket',
2694 'fields' => array(
'ref'),
2695 'class' =>
'ticket/class/ticket.class.php',
2696 'object' =>
'Ticket'),
2697 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
2698 'fields' => array(
'ref'),
2699 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
2700 'object' =>
'KnowledgeRecord'),
2701 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
2702 'fields' => array(
'ref'),
2703 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
2704 'object' =>
'SupplierProposal'),
2705 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
2706 'fields' => array(
'ref',
'ref_supplier'),
2707 'class' =>
'fourn/class/fournisseur.commande.class.php',
2708 'object' =>
'SupplierProposal'),
2709 'facture' => array(
'table' =>
'facture',
2710 'fields' => array(
'ref'),
2711 'class' =>
'compta/facture/class/facture.class.php',
2712 'object' =>
'Facture'),
2713 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
2714 'fields' => array(
'ref',
'ref_client'),
2715 'class' =>
'fourn/class/fournisseur.facture.class.php',
2716 'object' =>
'FactureFournisseur'),
2717 'produit' => array(
'table' =>
'product',
2718 'fields' => array(
'ref'),
2719 'class' =>
'product/class/product.class.php',
2720 'object' =>
'Product'),
2721 'productlot' => array(
'table' =>
'product_lot',
2722 'fields' => array(
'batch'),
2723 'class' =>
'product/stock/class/productlot.class.php',
2724 'object' =>
'Productlot'),
2725 'projet' => array(
'table' =>
'projet',
2726 'fields' => array(
'ref'),
2727 'class' =>
'projet/class/projet.class.php',
2728 'object' =>
'Project'),
2729 'projet_task' => array(
'table' =>
'projet_task',
2730 'fields' => array(
'ref'),
2731 'class' =>
'projet/class/task.class.php',
2732 'object' =>
'Task'),
2733 'ressource' => array(
'table' =>
'resource',
2734 'fields' => array(
'ref'),
2735 'class' =>
'ressource/class/dolressource.class.php',
2736 'object' =>
'Dolresource'),
2737 'bom' => array(
'table' =>
'bom_bom',
2738 'fields' => array(
'ref'),
2739 'class' =>
'bom/class/bom.class.php',
2741 'mrp' => array(
'table' =>
'mrp_mo',
2742 'fields' => array(
'ref'),
2743 'class' =>
'mrp/class/mo.class.php',
2747 if (!is_object($hookmanager)) {
2748 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
2751 $hookmanager->initHooks(array(
'emailcolector'));
2752 $parameters = array(
'arrayobject' => $arrayobject);
2753 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
2755 $arrayobject = $hookmanager->resArray;
2758 $resultobj = array();
2760 foreach ($arrayobject as $key => $objectdesc) {
2761 $sql =
'SELECT DISTINCT t.rowid ';
2762 $sql .=
' FROM ' . MAIN_DB_PREFIX . $objectdesc[
'table'] .
' AS t';
2764 foreach ($objectdesc[
'fields'] as $field) {
2765 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $field .
", '%') AND t." . $field .
"<>'') OR ";
2767 $sql = substr($sql, 0, -4);
2769 $ressqlobj = $this->db->query($sql);
2771 while ($obj = $this->db->fetch_object($ressqlobj)) {
2772 $resultobj[$key][] = $obj->rowid;
2777 foreach ($resultobj as $mod => $ids) {
2778 $moddesc = $arrayobject[$mod];
2779 $elementpath = $mod;
2781 $objectmanaged =
new $moddesc[
'object']($this->db);
2782 foreach ($ids as $val) {
2783 $res = $objectmanaged->fetch($val);
2785 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
2786 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
2788 $this->errors[] =
'object not found';
2792 foreach ($dirs as $target) {
2793 $prefix = $this->actions[$this->id][
'actionparam'];
2794 foreach ($data as $filename => $content) {
2795 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
2797 $this->errors[] =
'Doc not saved';
2802 $operationslog .=
'<br>Save attachment files on disk';
2804 $this->errors[] =
'no joined piece';
2806 $operationslog .=
'<br>No joinded files';
2808 } elseif ($operation[
'type'] ==
'project') {
2810 $projecttocreate =
new Project($this->db);
2811 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
2812 if ($alreadycreated == 0) {
2813 if ($thirdpartystatic->id > 0) {
2814 $projecttocreate->socid = $thirdpartystatic->id;
2815 if ($thirdpartyfoundby) {
2816 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2819 if ($contactstatic->id > 0) {
2820 $projecttocreate->contact_id = $contactstatic->id;
2821 if ($contactfoundby) {
2822 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2826 $description = $descriptiontitle;
2832 $descriptionfull = $description;
2833 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2834 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2838 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
2839 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
2841 $projecttocreate->title = $subject;
2842 $projecttocreate->date_start = $date;
2843 $projecttocreate->date_end =
'';
2844 $projecttocreate->opp_status = $id_opp_status;
2845 $projecttocreate->opp_percent = $percent_opp_status;
2847 $projecttocreate->note_private = $descriptionfull;
2848 $projecttocreate->entity = $conf->entity;
2849 $projecttocreate->email_msgid = $msgid;
2851 $savesocid = $projecttocreate->socid;
2855 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2858 if (empty($projecttocreate->ref)) {
2861 $modele = empty($conf->global->PROJECT_ADDON) ?
'mod_project_simple' : $conf->global->PROJECT_ADDON;
2864 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
2865 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2866 foreach ($dirmodels as $reldir) {
2867 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
2868 if (file_exists($file)) {
2870 $classname = $modele;
2876 if ($savesocid > 0) {
2877 if ($savesocid != $projecttocreate->socid) {
2879 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');
2882 if ($projecttocreate->socid > 0) {
2883 $thirdpartystatic->fetch($projecttocreate->socid);
2887 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
2888 $modModuleToUseForNextValue =
new $classname;
2889 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $projecttocreate);
2891 $projecttocreate->ref = $defaultref;
2895 if ($errorforthisaction) {
2898 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
2900 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2902 $operationslog .=
'<br>'.$this->error;
2905 $result = $projecttocreate->create($user);
2908 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
2909 $this->errors = $projecttocreate->errors;
2911 $operationslog .=
'<br>'.$this->error;
2914 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
2918 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
2919 foreach ($attachments as $attachment) {
2920 $attachment->save($destdir.
'/');
2923 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
2925 $this->errors = array_merge($this->errors, [$this->error]);
2930 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2932 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2940 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
2942 } elseif ($operation[
'type'] ==
'ticket') {
2944 $tickettocreate =
new Ticket($this->db);
2946 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2947 if ($alreadycreated == 0) {
2948 if ($thirdpartystatic->id > 0) {
2949 $tickettocreate->socid = $thirdpartystatic->id;
2950 $tickettocreate->fk_soc = $thirdpartystatic->id;
2951 if ($thirdpartyfoundby) {
2952 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2955 if ($contactstatic->id > 0) {
2956 $tickettocreate->contact_id = $contactstatic->id;
2957 if ($contactfoundby) {
2958 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2962 $description = $descriptiontitle;
2968 $descriptionfull = $description;
2969 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2970 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2974 $tickettocreate->subject = $subject;
2975 $tickettocreate->message = $description;
2976 $tickettocreate->type_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE :
dol_getIdFromCode($this->db, 1,
'c_ticket_type',
'use_default',
'code', 1));
2977 $tickettocreate->category_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE :
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1));
2978 $tickettocreate->severity_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE :
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1));
2979 $tickettocreate->origin_email = $from;
2980 $tickettocreate->fk_user_create = $user->id;
2981 $tickettocreate->datec =
dol_now();
2982 $tickettocreate->fk_project = $projectstatic->id;
2983 $tickettocreate->notify_tiers_at_create = 0;
2984 $tickettocreate->note_private = $descriptionfull;
2985 $tickettocreate->entity = $conf->entity;
2986 $tickettocreate->email_msgid = $msgid;
2987 $tickettocreate->email_date = $date;
2990 $savesocid = $tickettocreate->socid;
2994 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2997 if (empty($tickettocreate->ref)) {
3000 $modele = empty($conf->global->TICKET_ADDON) ?
'mod_ticket_simple' : $conf->global->TICKET_ADDON;
3003 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
3004 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3005 foreach ($dirmodels as $reldir) {
3006 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3007 if (file_exists($file)) {
3009 $classname = $modele;
3015 if ($savesocid > 0) {
3016 if ($savesocid != $tickettocreate->socid) {
3018 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');
3021 if ($tickettocreate->socid > 0) {
3022 $thirdpartystatic->fetch($tickettocreate->socid);
3027 $modModuleToUseForNextValue =
new $classname;
3028 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $tickettocreate);
3030 $tickettocreate->ref = $defaultref;
3033 if ($errorforthisaction) {
3036 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3038 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3041 $result = $tickettocreate->create($user);
3044 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3045 $this->errors = $tickettocreate->errors;
3048 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3052 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3053 foreach ($attachments as $attachment) {
3054 $attachment->save($destdir.
'/');
3057 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3059 $this->errors = array_merge($this->errors, [$this->error]);
3064 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3066 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3072 } elseif ($operation[
'type'] ==
'candidature') {
3076 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3077 if ($alreadycreated == 0) {
3078 $description = $descriptiontitle;
3084 $descriptionfull = $description;
3085 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3088 $candidaturetocreate->subject = $subject;
3089 $candidaturetocreate->message = $description;
3090 $candidaturetocreate->type_code = 0;
3091 $candidaturetocreate->category_code =
null;
3092 $candidaturetocreate->severity_code =
null;
3093 $candidaturetocreate->email = $from;
3095 $candidaturetocreate->fk_user_creat = $user->id;
3096 $candidaturetocreate->date_creation =
dol_now();
3097 $candidaturetocreate->fk_project = $projectstatic->id;
3098 $candidaturetocreate->description = $description;
3099 $candidaturetocreate->note_private = $descriptionfull;
3100 $candidaturetocreate->entity = $conf->entity;
3101 $candidaturetocreate->email_msgid = $msgid;
3102 $candidaturetocreate->email_date = $date;
3103 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3108 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3150 if ($errorforthisaction) {
3154 $result = $candidaturetocreate->create($user);
3157 $this->error =
'Failed to create candidature: '.join(
', ', $candidaturetocreate->errors);
3158 $this->errors = $candidaturetocreate->errors;
3161 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
3164 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3167 if (!is_object($hookmanager)) {
3168 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3172 $parameters = array(
3173 'connection'=> $connection,
3174 'imapemail'=>$imapemail,
3175 'overview'=>$overview,
3178 'fromtext' => $fromtext,
3180 'actionparam'=> $operation[
'actionparam'],
3182 'thirdpartyid' => $thirdpartyid,
3183 'objectid'=> $objectid,
3184 'objectemail'=> $objectemail,
3186 'messagetext'=>$messagetext,
3187 'subject'=>$subject,
3189 'attachments'=>$attachments,
3191 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3194 $errorforthisaction++;
3195 $this->error = $hookmanager->resPrint;
3197 if ($errorforthisaction) {
3199 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3201 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3205 if (!$errorforactions) {
3206 $nbactiondoneforemail++;
3212 if (!$errorforactions) {
3213 if (!empty($targetdir)) {
3214 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3216 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3218 $imapemail->move($targetdir);
3221 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3222 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3224 $arrayofemailtodelete[$imapemail] = $msgid;
3227 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3228 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);
3230 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3238 unset($objectemail);
3239 unset($projectstatic);
3240 unset($thirdpartystatic);
3241 unset($contactstatic);
3243 $nbemailprocessed++;
3245 if (!$errorforemail) {
3246 $nbactiondone += $nbactiondoneforemail;
3250 $this->db->commit();
3252 $this->db->rollback();
3256 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3257 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3263 $this->db->rollback();
3267 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3269 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3271 $langs->load(
"admin");
3272 $output = $langs->trans(
'NoNewEmailToProcess');
3276 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3277 $client->disconnect();
3279 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3280 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3282 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid;
3284 if (empty($mode) && empty($error)) {
3285 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3286 if ($res ==
false) {
3288 $this->error = imap_last_error();
3289 $this->errors[] = $this->error;
3291 $operationslog .=
'<br>Error in move '.$this->error;
3298 if (empty($mode) && empty($error)) {
3300 $operationslog .=
"<br>Expunge";
3302 imap_expunge($connection);
3304 imap_close($connection);
3307 $this->datelastresult = $now;
3308 $this->lastresult = $output;
3309 $this->debuginfo .=
'IMAP search string used : '.$search;
3311 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3313 if ($operationslog) {
3314 $this->debuginfo .= $operationslog;
3317 if (empty($error) && empty($mode)) {
3318 $this->datelastok = $now;
3321 if (!empty($this->errors)) {
3322 $this->lastresult .=
"<br>".join(
"<br>", $this->errors);
3324 $this->codelastresult = ($error ?
'KO' :
'OK');
3330 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3332 return $error ? -1 : 1;