From 111e5ba3f0cef38dfe407a44a3ffc16bfd8dd969 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 16 Sep 2022 14:50:25 +0200 Subject: [PATCH] NEW Add a button "Test collect" in email collector --- htdocs/admin/emailcollector_card.php | 19 +- .../class/emailcollector.class.php | 1236 +++++++++-------- htdocs/langs/en_US/admin.lang | 1 + 3 files changed, 643 insertions(+), 613 deletions(-) diff --git a/htdocs/admin/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index 19486510f58..971b470babc 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -235,10 +235,25 @@ if ($action == 'deleteoperation') { } } +if ($action == 'collecttest') { + dol_include_once('/emailcollector/class/emailcollector.class.php'); + + $res = $object->doCollectOneCollector(2); + if ($res > 0) { + $debuginfo = $object->debuginfo; + setEventMessages($object->lastresult, null, 'mesgs'); + } else { + $debuginfo = $object->debuginfo; + setEventMessages($object->error, null, 'errors'); + } + + $action = ''; +} + if ($action == 'confirm_collect') { dol_include_once('/emailcollector/class/emailcollector.class.php'); - $res = $object->doCollectOneCollector(); + $res = $object->doCollectOneCollector(0); if ($res > 0) { $debuginfo = $object->debuginfo; setEventMessages($object->lastresult, null, 'mesgs'); @@ -784,6 +799,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
'.$langs->trans("ToClone").'
'; // Collect now + print '
'.$langs->trans("TestCollectNow").'
'; + if (count($object->actions) > 0) { print '
'.$langs->trans("CollectNow").'
'; } else { diff --git a/htdocs/emailcollector/class/emailcollector.class.php b/htdocs/emailcollector/class/emailcollector.class.php index 47d62197a70..12a36e2e9c5 100644 --- a/htdocs/emailcollector/class/emailcollector.class.php +++ b/htdocs/emailcollector/class/emailcollector.class.php @@ -126,8 +126,8 @@ class EmailCollector extends CommonObject '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'=>'tdoverflowmax150'), 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>'Example: My Email collector', 'csslist'=>'tdoverflowmax150'), 'description' => array('type'=>'text', 'label'=>'Description', 'visible'=>-1, 'enabled'=>1, 'position'=>60, 'notnull'=>-1, 'csslist'=>'small'), - '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'=>'tdoverflow125'), - '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'=>'tdoverflow125', 'default'=>'993'), + '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'), + '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'), 'hostcharset' => array('type'=>'varchar(16)', 'label'=>'HostCharset', 'visible'=>-1, 'enabled'=>1, 'position'=>92, 'notnull'=>0, 'searchall'=>0, 'comment'=>"IMAP server charset", 'help'=>'Example: "UTF-8" (May be "US-ASCII" with some Office365)', 'default'=>'UTF-8'), 'acces_type' => array('type'=>'integer', 'label'=>'accessType', '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'=>''), 'login' => array('type'=>'varchar(128)', 'label'=>'Login', 'visible'=>-1, 'enabled'=>1, 'position'=>102, 'notnull'=>-1, 'index'=>1, 'comment'=>"IMAP login", 'help'=>'Example: myaccount@gmail.com'), @@ -1001,9 +1001,10 @@ class EmailCollector extends CommonObject /** * Execute collect for current collector loaded previously with fetch. * - * @return int <0 if KO, >0 if OK + * @param int $mode 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates + * @return int <0 if KO, >0 if OK */ - public function doCollectOneCollector() + public function doCollectOneCollector($mode = 0) { global $db, $conf, $langs, $user; global $hookmanager; @@ -1019,6 +1020,7 @@ class EmailCollector extends CommonObject $error = 0; $this->output = ''; $this->error = ''; + $this->debuginfo = ''; $now = dol_now(); @@ -1950,268 +1952,269 @@ class EmailCollector extends CommonObject } // Do operations - foreach ($this->actions as $operation) { - $errorforthisaction = 0; + if ($mode < 2) { + foreach ($this->actions as $operation) { + $errorforthisaction = 0; - if ($errorforactions) { - break; - } - if (empty($operation['status'])) { - continue; - } - - // Make Operation - dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id); - 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 - - $actioncode = 'EMAIL_IN'; - // If we scan the Sent box, we use the code for out email - if ($this->source_directory == 'Sent') { - $actioncode = 'EMAIL_OUT'; - } - - $description = $descriptiontitle = $descriptionmeta = $descriptionfull = ''; - - $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid); - - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject)); - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring)); - if ($sender) { - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender)); - } - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to)); - if ($sendtocc) { - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc)); - } - - // Search and create thirdparty - if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') { - if (empty($operation['actionparam'])) { - $errorforactions++; - $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;"; - $this->errors[] = $this->error; - } else { - $actionparam = $operation['actionparam']; - $idtouseforthirdparty = ''; - $nametouseforthirdparty = ''; - $emailtouseforthirdparty = ''; - - // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....' - $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '='); - foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) { - $sourcestring = ''; - $sourcefield = ''; - $regexstring = ''; - $regforregex = array(); - - if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) { - $sourcefield = $regforregex[1]; - $regexstring = $regforregex[2]; - } - - if (!empty($sourcefield) && !empty($regexstring)) { - if (strtolower($sourcefield) == 'body') { - $sourcestring = $messagetext; - } elseif (strtolower($sourcefield) == 'subject') { - $sourcestring = $subject; - } elseif (strtolower($sourcefield) == 'header') { - $sourcestring = $header; - } - - if ($sourcestring) { - $regforval = array(); - //var_dump($regexstring);var_dump($sourcestring); - if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) { - //var_dump($regforval[count($regforval)-1]);exit; - // Overwrite param $tmpproperty - if ($propertytooverwrite == 'id') { - $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; - } elseif ($propertytooverwrite == 'email') { - $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; - } else { - $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; - } - } else { - // Regex not found - $idtouseforthirdparty = null; - $nametouseforthirdparty = null; - $emailtouseforthirdparty = null; - } - //var_dump($object->$tmpproperty);exit; - } else { - // Nothing can be done for this param - $errorforactions++; - $this->error = 'The extract rule to use to load thirdparty has on an unknown source (must be HEADER, SUBJECT or BODY)'; - $this->errors[] = $this->error; - } - } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) { - //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1]; - //else $object->$tmpproperty = $reg[1]; - if ($propertytooverwrite == 'id') { - $idtouseforthirdparty = $reg[2]; - } elseif ($propertytooverwrite == 'email') { - $emailtouseforthirdparty = $reg[2]; - } else { - $nametouseforthirdparty = $reg[2]; - } - } else { - $errorforactions++; - $this->error = 'Bad syntax for description of action parameters: '.$actionparam; - $this->errors[] = $this->error; - break; - } - } - - if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty)) { - $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty, '', '', '', '', '', '', '', '', $emailtouseforthirdparty); - if ($result < 0) { - $errorforactions++; - $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)'; - $this->errors[] = $this->error; - break; - } elseif ($result == 0) { - if ($operation['type'] == 'loadthirdparty') { - dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." was not found"); - - $errorforactions++; - $langs->load("errors"); - $this->error = $langs->trans('ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty); - $this->errors[] = $this->error; - } elseif ($operation['type'] == 'loadandcreatethirdparty') { - dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." was not found. We try to create it."); - - // Create thirdparty - $thirdpartystatic->name = $nametouseforthirdparty; - if ($fromtext != $nametouseforthirdparty) { - $thirdpartystatic->name_alias = $fromtext; - } - $thirdpartystatic->email = ($emailtouseforthirdparty ? $emailtouseforthirdparty : $from); - - // Overwrite values with values extracted from source email - $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header); - - if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) { - $thirdpartystatic->code_client = 'auto'; - } - if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) { - $thirdpartystatic->code_fournisseur = 'auto'; - } - - if ($errorforthisaction) { - $errorforactions++; - } else { - $result = $thirdpartystatic->create($user); - if ($result <= 0) { - $errorforactions++; - $this->error = $thirdpartystatic->error; - $this->errors = $thirdpartystatic->errors; - } - } - } - } - } + if ($errorforactions) { + break; + } + if (empty($operation['status'])) { + continue; } - } elseif ($operation['type'] == 'recordevent') { - // Create event - $actioncomm = new ActionComm($this->db); - $alreadycreated = $actioncomm->fetch(0, '', '', $msgid); - if ($alreadycreated == 0) { - if ($projectstatic->id > 0) { - if ($projectfoundby) { - $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby); - } - } - if ($thirdpartystatic->id > 0) { - if ($thirdpartyfoundby) { - $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); - } - } - if ($contactstatic->id > 0) { - if ($contactfoundby) { - $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); - } - } + // Make Operation + dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id); + 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 - $description = $descriptiontitle; - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $descriptionmeta); - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $messagetext); + $actioncode = 'EMAIL_IN'; + // If we scan the Sent box, we use the code for out email + if ($this->source_directory == 'Sent') { + $actioncode = 'EMAIL_OUT'; + } - $descriptionfull = $description; - if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { - $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); - $descriptionfull = dol_concatdesc($descriptionfull, $header); - } + $description = $descriptiontitle = $descriptionmeta = $descriptionfull = ''; - // Insert record of emails sent - $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) - $actioncomm->code = 'AC_'.$actioncode; - $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from; - $actioncomm->note_private = $descriptionfull; - $actioncomm->fk_project = $projectstatic->id; - $actioncomm->datep = $date; // date of email - $actioncomm->datef = $date; // date of email - $actioncomm->percentage = -1; // Not applicable - $actioncomm->socid = $thirdpartystatic->id; - $actioncomm->contact_id = $contactstatic->id; - $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id => '') : array()); - $actioncomm->authorid = $user->id; // User saving action - $actioncomm->userownerid = $user->id; // Owner of action - // Fields when action is an email (content should be added into note) - $actioncomm->email_msgid = $msgid; - $actioncomm->email_from = $fromstring; - $actioncomm->email_sender = $sender; - $actioncomm->email_to = $to; - $actioncomm->email_tocc = $sendtocc; - $actioncomm->email_tobcc = $sendtobcc; - $actioncomm->email_subject = $subject; - $actioncomm->errors_to = ''; + $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid); - if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) { - $actioncomm->fk_element = $fk_element_id; - $actioncomm->elementid = $fk_element_id; - $actioncomm->elementtype = $fk_element_type; - if (is_object($objectemail) && $objectemail->module) { - $actioncomm->elementtype .= '@'.$objectemail->module; - } - } + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject)); + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring)); + if ($sender) { + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender)); + } + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to)); + if ($sendtocc) { + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc)); + } - //$actioncomm->extraparams = $extraparams; - - // Overwrite values with values extracted from source email - $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header); - - //var_dump($fk_element_id); - //var_dump($fk_element_type); - //var_dump($alreadycreated); - //var_dump($operation['type']); - //var_dump($actioncomm); - //exit; - - if ($errorforthisaction) { + // Search and create thirdparty + if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') { + if (empty($operation['actionparam'])) { $errorforactions++; + $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;"; + $this->errors[] = $this->error; } else { - $result = $actioncomm->create($user); - if ($result <= 0) { - $errorforactions++; - $this->errors = $actioncomm->errors; + $actionparam = $operation['actionparam']; + $idtouseforthirdparty = ''; + $nametouseforthirdparty = ''; + $emailtouseforthirdparty = ''; + + // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....' + $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '='); + foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) { + $sourcestring = ''; + $sourcefield = ''; + $regexstring = ''; + $regforregex = array(); + + if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) { + $sourcefield = $regforregex[1]; + $regexstring = $regforregex[2]; + } + + if (!empty($sourcefield) && !empty($regexstring)) { + if (strtolower($sourcefield) == 'body') { + $sourcestring = $messagetext; + } elseif (strtolower($sourcefield) == 'subject') { + $sourcestring = $subject; + } elseif (strtolower($sourcefield) == 'header') { + $sourcestring = $header; + } + + if ($sourcestring) { + $regforval = array(); + //var_dump($regexstring);var_dump($sourcestring); + if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) { + //var_dump($regforval[count($regforval)-1]);exit; + // Overwrite param $tmpproperty + if ($propertytooverwrite == 'id') { + $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; + } elseif ($propertytooverwrite == 'email') { + $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; + } else { + $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; + } + } else { + // Regex not found + $idtouseforthirdparty = null; + $nametouseforthirdparty = null; + $emailtouseforthirdparty = null; + } + //var_dump($object->$tmpproperty);exit; + } else { + // Nothing can be done for this param + $errorforactions++; + $this->error = 'The extract rule to use to load thirdparty has on an unknown source (must be HEADER, SUBJECT or BODY)'; + $this->errors[] = $this->error; + } + } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) { + //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1]; + //else $object->$tmpproperty = $reg[1]; + if ($propertytooverwrite == 'id') { + $idtouseforthirdparty = $reg[2]; + } elseif ($propertytooverwrite == 'email') { + $emailtouseforthirdparty = $reg[2]; + } else { + $nametouseforthirdparty = $reg[2]; + } + } else { + $errorforactions++; + $this->error = 'Bad syntax for description of action parameters: '.$actionparam; + $this->errors[] = $this->error; + break; + } + } + + if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty)) { + $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty, '', '', '', '', '', '', '', '', $emailtouseforthirdparty); + if ($result < 0) { + $errorforactions++; + $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)'; + $this->errors[] = $this->error; + break; + } elseif ($result == 0) { + if ($operation['type'] == 'loadthirdparty') { + dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." was not found"); + + $errorforactions++; + $langs->load("errors"); + $this->error = $langs->trans('ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty); + $this->errors[] = $this->error; + } elseif ($operation['type'] == 'loadandcreatethirdparty') { + dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." was not found. We try to create it."); + + // Create thirdparty + $thirdpartystatic->name = $nametouseforthirdparty; + if ($fromtext != $nametouseforthirdparty) { + $thirdpartystatic->name_alias = $fromtext; + } + $thirdpartystatic->email = ($emailtouseforthirdparty ? $emailtouseforthirdparty : $from); + + // Overwrite values with values extracted from source email + $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header); + + if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) { + $thirdpartystatic->code_client = 'auto'; + } + if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) { + $thirdpartystatic->code_fournisseur = 'auto'; + } + + if ($errorforthisaction) { + $errorforactions++; + } else { + $result = $thirdpartystatic->create($user); + if ($result <= 0) { + $errorforactions++; + $this->error = $thirdpartystatic->error; + $this->errors = $thirdpartystatic->errors; + } + } + } + } } } - } - } elseif ($operation['type'] == 'recordjoinpiece') { - $pj = getAttachments($imapemail, $connection); - foreach ($pj as $key => $val) { - $data[$val['filename']] = getFileData($imapemail, $val['pos'], $val['type'], $connection); - } - if (count($pj) > 0) { - $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."user WHERE email LIKE '%".$this->db->escape($from)."%'"; - $resql = $this->db->query($sql); - if ($this->db->num_rows($resql) == 0) { - $this->errors[] = 'User Not allowed to add documents'; + } elseif ($operation['type'] == 'recordevent') { + // Create event + $actioncomm = new ActionComm($this->db); + + $alreadycreated = $actioncomm->fetch(0, '', '', $msgid); + if ($alreadycreated == 0) { + if ($projectstatic->id > 0) { + if ($projectfoundby) { + $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby); + } + } + if ($thirdpartystatic->id > 0) { + if ($thirdpartyfoundby) { + $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); + } + } + if ($contactstatic->id > 0) { + if ($contactfoundby) { + $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); + } + } + + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); + + $descriptionfull = $description; + if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { + $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); + $descriptionfull = dol_concatdesc($descriptionfull, $header); + } + + // Insert record of emails sent + $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) + $actioncomm->code = 'AC_'.$actioncode; + $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from; + $actioncomm->note_private = $descriptionfull; + $actioncomm->fk_project = $projectstatic->id; + $actioncomm->datep = $date; // date of email + $actioncomm->datef = $date; // date of email + $actioncomm->percentage = -1; // Not applicable + $actioncomm->socid = $thirdpartystatic->id; + $actioncomm->contact_id = $contactstatic->id; + $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id => '') : array()); + $actioncomm->authorid = $user->id; // User saving action + $actioncomm->userownerid = $user->id; // Owner of action + // Fields when action is an email (content should be added into note) + $actioncomm->email_msgid = $msgid; + $actioncomm->email_from = $fromstring; + $actioncomm->email_sender = $sender; + $actioncomm->email_to = $to; + $actioncomm->email_tocc = $sendtocc; + $actioncomm->email_tobcc = $sendtobcc; + $actioncomm->email_subject = $subject; + $actioncomm->errors_to = ''; + + if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) { + $actioncomm->fk_element = $fk_element_id; + $actioncomm->elementid = $fk_element_id; + $actioncomm->elementtype = $fk_element_type; + if (is_object($objectemail) && $objectemail->module) { + $actioncomm->elementtype .= '@'.$objectemail->module; + } + } + + //$actioncomm->extraparams = $extraparams; + + // Overwrite values with values extracted from source email + $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header); + + //var_dump($fk_element_id); + //var_dump($fk_element_type); + //var_dump($alreadycreated); + //var_dump($operation['type']); + //var_dump($actioncomm); + //exit; + + if ($errorforthisaction) { + $errorforactions++; + } else { + $result = $actioncomm->create($user); + if ($result <= 0) { + $errorforactions++; + $this->errors = $actioncomm->errors; + } + } } - $arrayobject = array( + } elseif ($operation['type'] == 'recordjoinpiece') { + $pj = getAttachments($imapemail, $connection); + foreach ($pj as $key => $val) { + $data[$val['filename']] = getFileData($imapemail, $val['pos'], $val['type'], $connection); + } + if (count($pj) > 0) { + $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."user WHERE email LIKE '%".$this->db->escape($from)."%'"; + $resql = $this->db->query($sql); + if ($this->db->num_rows($resql) == 0) { + $this->errors[] = 'User Not allowed to add documents'; + } + $arrayobject = array( 'propale' => array('table' => 'propal', 'fields' => array('ref'), 'class' => 'comm/propal/class/propal.class.php', @@ -2304,347 +2307,347 @@ class EmailCollector extends CommonObject 'fields' => array('ref'), 'class' => 'mrp/class/mo.class.php', 'object' => 'Mo'), - ); + ); - if (!is_object($hookmanager)) { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($this->db); - } - $hookmanager->initHooks(array('emailcolector')); - $parameters = array('arrayobject' => $arrayobject); - $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - $arrayobject = $hookmanager->resArray; - } - - $resultobj = array(); - - foreach ($arrayobject as $key => $objectdesc) { - $sql = 'SELECT DISTINCT t.rowid '; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $objectdesc['table'] . ' AS t'; - $sql .= ' WHERE '; - foreach ($objectdesc['fields'] as $field) { - $sql .= "'" .$this->db->escape($subject) . "' LIKE CONCAT('%', t." . $field . ", '%') OR "; + if (!is_object($hookmanager)) { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($this->db); + } + $hookmanager->initHooks(array('emailcolector')); + $parameters = array('arrayobject' => $arrayobject); + $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + $arrayobject = $hookmanager->resArray; } - $sql = substr($sql, 0, -4); - $ressqlobj = $this->db->query($sql); - if ($ressqlobj) { - while ($obj = $this->db->fetch_object($ressqlobj)) { - $resultobj[$key][] = $obj->rowid; + $resultobj = array(); + + foreach ($arrayobject as $key => $objectdesc) { + $sql = 'SELECT DISTINCT t.rowid '; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $objectdesc['table'] . ' AS t'; + $sql .= ' WHERE '; + foreach ($objectdesc['fields'] as $field) { + $sql .= "'" .$this->db->escape($subject) . "' LIKE CONCAT('%', t." . $field . ", '%') OR "; + } + $sql = substr($sql, 0, -4); + + $ressqlobj = $this->db->query($sql); + if ($ressqlobj) { + while ($obj = $this->db->fetch_object($ressqlobj)) { + $resultobj[$key][] = $obj->rowid; + } } } + $dirs = array(); + foreach ($resultobj as $mod => $ids) { + $moddesc = $arrayobject[$mod]; + $elementpath = $mod; + dol_include_once($moddesc['class']); + $objectmanaged = new $moddesc['object']($this->db); + foreach ($ids as $val) { + $res = $objectmanaged->fetch($val); + if ($res) { + $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : ''); + $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/'; + } else { + $this->errors[] = 'object not found'; + } + } + } + foreach ($dirs as $target) { + foreach ($data as $filename => $content) { + $prefix = $this->actions[$this->id]['actionparam']; + + $resr = saveAttachment($target, $prefix . '_' . $filename, $content); + if ($resr == -1) { + $this->errors[] = 'Doc not saved'; + } + } + } + } else { + $this->errors[] = 'no joined piece'; } - $dirs = array(); - foreach ($resultobj as $mod => $ids) { - $moddesc = $arrayobject[$mod]; - $elementpath = $mod; - dol_include_once($moddesc['class']); - $objectmanaged = new $moddesc['object']($this->db); - foreach ($ids as $val) { - $res = $objectmanaged->fetch($val); - if ($res) { - $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : ''); - $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/'; + } elseif ($operation['type'] == 'project') { + // Create project / lead + $projecttocreate = new Project($this->db); + $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid); + if ($alreadycreated == 0) { + if ($thirdpartystatic->id > 0) { + $projecttocreate->socid = $thirdpartystatic->id; + if ($thirdpartyfoundby) { + $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); + } + } + if ($contactstatic->id > 0) { + $projecttocreate->contact_id = $contactstatic->id; + if ($contactfoundby) { + $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); + } + } + + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); + + $descriptionfull = $description; + if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { + $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); + $descriptionfull = dol_concatdesc($descriptionfull, $header); + } + + $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid'); + $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent'); + + $projecttocreate->title = $subject; + $projecttocreate->date_start = $date; // date of email + $projecttocreate->date_end = ''; + $projecttocreate->opp_status = $id_opp_status; + $projecttocreate->opp_percent = $percent_opp_status; + $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...'); + $projecttocreate->note_private = $descriptionfull; + $projecttocreate->entity = $conf->entity; + $projecttocreate->email_msgid = $msgid; + + $savesocid = $projecttocreate->socid; + + // Overwrite values with values extracted from source email. + // This may overwrite any $projecttocreate->xxx properties. + $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header); + + // Set project ref if not yet defined + if (empty($projecttocreate->ref)) { + // Get next Ref + $defaultref = ''; + $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON; + + // Search template files + $file = ''; $classname = ''; $filefound = 0; $reldir = ''; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0); + if (file_exists($file)) { + $filefound = 1; + $classname = $modele; + break; + } + } + + if ($filefound) { + if ($savesocid > 0) { + if ($savesocid != $projecttocreate->socid) { + $errorforactions++; + 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'); + } + } else { + if ($projecttocreate->socid > 0) { + $thirdpartystatic->fetch($projecttocreate->socid); + } + } + + $result = dol_include_once($reldir."core/modules/project/".$modele.'.php'); + $modModuleToUseForNextValue = new $classname; + $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate); + } + $projecttocreate->ref = $defaultref; + } + + + if ($errorforthisaction) { + $errorforactions++; + } else { + if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) { + $errorforactions++; + $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; } else { - $this->errors[] = 'object not found'; + // Create project + $result = $projecttocreate->create($user); + if ($result <= 0) { + $errorforactions++; + $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error); + $this->errors = $projecttocreate->errors; + } else { + if ($attachments) { + $destdir = $conf->project->dir_output.'/'.$projecttocreate->ref; + if (!dol_is_dir($destdir)) { + dol_mkdir($destdir); + } + if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) { + foreach ($attachments as $attachment) { + $attachment->save($destdir.'/'); + } + } else { + $this->getmsg($connection, $imapemail, $destdir); + } + } + } } } } - foreach ($dirs as $target) { - foreach ($data as $filename => $content) { - $prefix = $this->actions[$this->id]['actionparam']; + } elseif ($operation['type'] == 'ticket') { + // Create ticket + $tickettocreate = new Ticket($this->db); - $resr = saveAttachment($target, $prefix . '_' . $filename, $content); - if ($resr == -1) { - $this->errors[] = 'Doc not saved'; + $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid); + if ($alreadycreated == 0) { + if ($thirdpartystatic->id > 0) { + $tickettocreate->socid = $thirdpartystatic->id; + $tickettocreate->fk_soc = $thirdpartystatic->id; + if ($thirdpartyfoundby) { + $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); + } + } + if ($contactstatic->id > 0) { + $tickettocreate->contact_id = $contactstatic->id; + if ($contactfoundby) { + $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); + } + } + + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); + + $descriptionfull = $description; + if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { + $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); + $descriptionfull = dol_concatdesc($descriptionfull, $header); + } + + $tickettocreate->subject = $subject; + $tickettocreate->message = $description; + $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)); + $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)); + $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)); + $tickettocreate->origin_email = $from; + $tickettocreate->fk_user_create = $user->id; + $tickettocreate->datec = dol_now(); + $tickettocreate->fk_project = $projectstatic->id; + $tickettocreate->notify_tiers_at_create = 0; + $tickettocreate->note_private = $descriptionfull; + $tickettocreate->entity = $conf->entity; + $tickettocreate->email_msgid = $msgid; + $tickettocreate->email_date = $date; + //$tickettocreate->fk_contact = $contactstatic->id; + + $savesocid = $tickettocreate->socid; + + // Overwrite values with values extracted from source email. + // This may overwrite any $projecttocreate->xxx properties. + $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header); + + // Set ticket ref if not yet defined + if (empty($tickettocreate->ref)) { + // Get next Ref + $defaultref = ''; + $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON; + + // Search template files + $file = ''; $classname = ''; $filefound = 0; $reldir = ''; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0); + if (file_exists($file)) { + $filefound = 1; + $classname = $modele; + break; + } + } + + if ($filefound) { + if ($savesocid > 0) { + if ($savesocid != $tickettocreate->socid) { + $errorforactions++; + 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'); + } + } else { + if ($tickettocreate->socid > 0) { + $thirdpartystatic->fetch($tickettocreate->socid); + } + } + + $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php'); + $modModuleToUseForNextValue = new $classname; + $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); + } + $tickettocreate->ref = $defaultref; + } + + if ($errorforthisaction) { + $errorforactions++; + } else { + if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) { + $errorforactions++; + $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; + } else { + // Create project + $result = $tickettocreate->create($user); + if ($result <= 0) { + $errorforactions++; + $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error); + $this->errors = $tickettocreate->errors; + } else { + if ($attachments) { + $destdir = $conf->ticket->dir_output.'/'.$tickettocreate->ref; + if (!dol_is_dir($destdir)) { + dol_mkdir($destdir); + } + if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) { + foreach ($attachments as $attachment) { + $attachment->save($destdir.'/'); + } + } else { + $this->getmsg($connection, $imapemail, $destdir); + } + } + } } } } - } else { - $this->errors[] = 'no joined piece'; - } - } elseif ($operation['type'] == 'project') { - // Create project / lead - $projecttocreate = new Project($this->db); - $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid); - if ($alreadycreated == 0) { - if ($thirdpartystatic->id > 0) { - $projecttocreate->socid = $thirdpartystatic->id; - if ($thirdpartyfoundby) { - $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); - } - } - if ($contactstatic->id > 0) { - $projecttocreate->contact_id = $contactstatic->id; - if ($contactfoundby) { - $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); - } - } + } elseif ($operation['type'] == 'candidature') { + // Create candidature + $candidaturetocreate = new RecruitmentCandidature($this->db); - $description = $descriptiontitle; - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $descriptionmeta); - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $messagetext); + $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid); + if ($alreadycreated == 0) { + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); - $descriptionfull = $description; - if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { + $descriptionfull = $description; $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); $descriptionfull = dol_concatdesc($descriptionfull, $header); - } - $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid'); - $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent'); + $candidaturetocreate->subject = $subject; + $candidaturetocreate->message = $description; + $candidaturetocreate->type_code = 0; + $candidaturetocreate->category_code = null; + $candidaturetocreate->severity_code = null; + $candidaturetocreate->email = $from; + //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$from; + $candidaturetocreate->fk_user_creat = $user->id; + $candidaturetocreate->date_creation = dol_now(); + $candidaturetocreate->fk_project = $projectstatic->id; + $candidaturetocreate->description = $description; + $candidaturetocreate->note_private = $descriptionfull; + $candidaturetocreate->entity = $conf->entity; + $candidaturetocreate->email_msgid = $msgid; + $candidaturetocreate->email_date = $date; // date of email + $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT; + //$candidaturetocreate->fk_contact = $contactstatic->id; - $projecttocreate->title = $subject; - $projecttocreate->date_start = $date; // date of email - $projecttocreate->date_end = ''; - $projecttocreate->opp_status = $id_opp_status; - $projecttocreate->opp_percent = $percent_opp_status; - $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...'); - $projecttocreate->note_private = $descriptionfull; - $projecttocreate->entity = $conf->entity; - $projecttocreate->email_msgid = $msgid; + // Overwrite values with values extracted from source email. + // This may overwrite any $projecttocreate->xxx properties. + $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header); - $savesocid = $projecttocreate->socid; - - // Overwrite values with values extracted from source email. - // This may overwrite any $projecttocreate->xxx properties. - $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header); - - // Set project ref if not yet defined - if (empty($projecttocreate->ref)) { - // Get next Ref - $defaultref = ''; - $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON; - - // Search template files - $file = ''; $classname = ''; $filefound = 0; $reldir = ''; - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0); - if (file_exists($file)) { - $filefound = 1; - $classname = $modele; - break; - } - } - - if ($filefound) { - if ($savesocid > 0) { - if ($savesocid != $projecttocreate->socid) { - $errorforactions++; - 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'); - } - } else { - if ($projecttocreate->socid > 0) { - $thirdpartystatic->fetch($projecttocreate->socid); - } - } - - $result = dol_include_once($reldir."core/modules/project/".$modele.'.php'); - $modModuleToUseForNextValue = new $classname; - $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate); - } - $projecttocreate->ref = $defaultref; - } - - - if ($errorforthisaction) { - $errorforactions++; - } else { - if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) { - $errorforactions++; - $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; - } else { - // Create project - $result = $projecttocreate->create($user); - if ($result <= 0) { - $errorforactions++; - $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error); - $this->errors = $projecttocreate->errors; - } else { - if ($attachments) { - $destdir = $conf->project->dir_output.'/'.$projecttocreate->ref; - if (!dol_is_dir($destdir)) { - dol_mkdir($destdir); - } - if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) { - foreach ($attachments as $attachment) { - $attachment->save($destdir.'/'); - } - } else { - $this->getmsg($connection, $imapemail, $destdir); - } - } - } - } - } - } - } elseif ($operation['type'] == 'ticket') { - // Create ticket - $tickettocreate = new Ticket($this->db); - - $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid); - if ($alreadycreated == 0) { - if ($thirdpartystatic->id > 0) { - $tickettocreate->socid = $thirdpartystatic->id; - $tickettocreate->fk_soc = $thirdpartystatic->id; - if ($thirdpartyfoundby) { - $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); - } - } - if ($contactstatic->id > 0) { - $tickettocreate->contact_id = $contactstatic->id; - if ($contactfoundby) { - $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); - } - } - - $description = $descriptiontitle; - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $descriptionmeta); - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $messagetext); - - $descriptionfull = $description; - if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { - $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); - $descriptionfull = dol_concatdesc($descriptionfull, $header); - } - - $tickettocreate->subject = $subject; - $tickettocreate->message = $description; - $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)); - $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)); - $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)); - $tickettocreate->origin_email = $from; - $tickettocreate->fk_user_create = $user->id; - $tickettocreate->datec = dol_now(); - $tickettocreate->fk_project = $projectstatic->id; - $tickettocreate->notify_tiers_at_create = 0; - $tickettocreate->note_private = $descriptionfull; - $tickettocreate->entity = $conf->entity; - $tickettocreate->email_msgid = $msgid; - $tickettocreate->email_date = $date; - //$tickettocreate->fk_contact = $contactstatic->id; - - $savesocid = $tickettocreate->socid; - - // Overwrite values with values extracted from source email. - // This may overwrite any $projecttocreate->xxx properties. - $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header); - - // Set ticket ref if not yet defined - if (empty($tickettocreate->ref)) { - // Get next Ref - $defaultref = ''; - $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON; - - // Search template files - $file = ''; $classname = ''; $filefound = 0; $reldir = ''; - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0); - if (file_exists($file)) { - $filefound = 1; - $classname = $modele; - break; - } - } - - if ($filefound) { - if ($savesocid > 0) { - if ($savesocid != $tickettocreate->socid) { - $errorforactions++; - 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'); - } - } else { - if ($tickettocreate->socid > 0) { - $thirdpartystatic->fetch($tickettocreate->socid); - } - } - - $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php'); - $modModuleToUseForNextValue = new $classname; - $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); - } - $tickettocreate->ref = $defaultref; - } - - if ($errorforthisaction) { - $errorforactions++; - } else { - if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) { - $errorforactions++; - $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; - } else { - // Create project - $result = $tickettocreate->create($user); - if ($result <= 0) { - $errorforactions++; - $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error); - $this->errors = $tickettocreate->errors; - } else { - if ($attachments) { - $destdir = $conf->ticket->dir_output.'/'.$tickettocreate->ref; - if (!dol_is_dir($destdir)) { - dol_mkdir($destdir); - } - if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) { - foreach ($attachments as $attachment) { - $attachment->save($destdir.'/'); - } - } else { - $this->getmsg($connection, $imapemail, $destdir); - } - } - } - } - } - } - } elseif ($operation['type'] == 'candidature') { - // Create candidature - $candidaturetocreate = new RecruitmentCandidature($this->db); - - $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid); - if ($alreadycreated == 0) { - $description = $descriptiontitle; - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $descriptionmeta); - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $messagetext); - - $descriptionfull = $description; - $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); - $descriptionfull = dol_concatdesc($descriptionfull, $header); - - $candidaturetocreate->subject = $subject; - $candidaturetocreate->message = $description; - $candidaturetocreate->type_code = 0; - $candidaturetocreate->category_code = null; - $candidaturetocreate->severity_code = null; - $candidaturetocreate->email = $from; - //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$from; - $candidaturetocreate->fk_user_creat = $user->id; - $candidaturetocreate->date_creation = dol_now(); - $candidaturetocreate->fk_project = $projectstatic->id; - $candidaturetocreate->description = $description; - $candidaturetocreate->note_private = $descriptionfull; - $candidaturetocreate->entity = $conf->entity; - $candidaturetocreate->email_msgid = $msgid; - $candidaturetocreate->email_date = $date; // date of email - $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT; - //$candidaturetocreate->fk_contact = $contactstatic->id; - - // Overwrite values with values extracted from source email. - // This may overwrite any $projecttocreate->xxx properties. - $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header); - - // Set candidature ref if not yet defined - /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status - { + // Set candidature ref if not yet defined + /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status + { // Get next Ref $defaultref = ''; $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON; @@ -2680,29 +2683,29 @@ class EmailCollector extends CommonObject $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); } $candidaturetocreate->ref = $defaultref; - }*/ + }*/ - if ($errorforthisaction) { - $errorforactions++; - } else { - // Create project - $result = $candidaturetocreate->create($user); - if ($result <= 0) { + if ($errorforthisaction) { $errorforactions++; - $this->error = 'Failed to create ticket: '.join(', ', $candidaturetocreate->errors); - $this->errors = $candidaturetocreate->errors; + } else { + // Create project + $result = $candidaturetocreate->create($user); + if ($result <= 0) { + $errorforactions++; + $this->error = 'Failed to create ticket: '.join(', ', $candidaturetocreate->errors); + $this->errors = $candidaturetocreate->errors; + } } } - } - } elseif (substr($operation['type'], 0, 4) == 'hook') { - // Create event specific on hook - // this code action is hook..... for support this call - if (!is_object($hookmanager)) { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($this->db); - } + } elseif (substr($operation['type'], 0, 4) == 'hook') { + // Create event specific on hook + // this code action is hook..... for support this call + if (!is_object($hookmanager)) { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($this->db); + } - $parameters = array( + $parameters = array( 'connection'=> $connection, 'imapemail'=>$imapemail, 'overview'=>$overview, @@ -2720,28 +2723,29 @@ class EmailCollector extends CommonObject 'subject'=>$subject, 'header'=>$header, 'attachments'=>$attachments, - ); - $reshook = $hookmanager->executeHooks('doColleimapctOneCollector', $parameters, $this, $operation['type']); + ); + $reshook = $hookmanager->executeHooks('doColleimapctOneCollector', $parameters, $this, $operation['type']); - if ($reshook < 0) { - $errorforthisaction++; - $this->error = $hookmanager->resPrint; + if ($reshook < 0) { + $errorforthisaction++; + $this->error = $hookmanager->resPrint; + } + if ($errorforthisaction) { + $errorforactions++; + } } - if ($errorforthisaction) { - $errorforactions++; + + + if (!$errorforactions) { + $nbactiondoneforemail++; } } - - - if (!$errorforactions) { - $nbactiondoneforemail++; - } } // Error for email or not ? if (!$errorforactions) { - if (empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) { - if ($targetdir) { + if ($targetdir && empty($mode)) { + if (empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) { dol_syslog("EmailCollector::doCollectOneCollector move message ".$imapemail." to ".$connectstringtarget, LOG_DEBUG); $res = imap_mail_move($connection, $imapemail, $targetdir, 0); if ($res == false) { @@ -2751,9 +2755,10 @@ class EmailCollector extends CommonObject dol_syslog(imap_last_error()); } } else { - dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG); - // TODO Make the move + // TODO Move mail using PHP-IMAP } + } else { + dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG); } } else { $errorforemail++; @@ -2771,7 +2776,11 @@ class EmailCollector extends CommonObject $nbactiondone += $nbactiondoneforemail; $nbemailok++; - $this->db->commit(); + if (empty($mode)) { + $this->db->commit(); + } else { + $this->db->rollback(); + } // Stop the loop to process email if we reach maximum collected per collect if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) { @@ -2802,12 +2811,12 @@ class EmailCollector extends CommonObject $this->datelastresult = $now; $this->lastresult = $output; - $this->debuginfo = 'IMAP search string used : '.$search; + $this->debuginfo .= 'IMAP search string used : '.$search; if ($searchhead) { $this->debuginfo .= '
Then search string into email header : '.$searchhead; } - if (!$error) { + if (empty($error) && empty($mode)) { $this->datelastok = $now; } @@ -2815,11 +2824,14 @@ class EmailCollector extends CommonObject $this->lastresult .= "
".join("
", $this->errors); } $this->codelastresult = ($error ? 'KO' : 'OK'); - $this->update($user); + + if (empty($mode)) { + $this->update($user); + } dol_syslog("EmailCollector::doCollectOneCollector end", LOG_DEBUG); - return $error ?-1 : 1; + return $error ? -1 : 1; } diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 704d9ed238e..6a1146a2f9d 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -2081,6 +2081,7 @@ MailboxTargetDirectory=Mailbox target directory EmailcollectorOperations=Operations to do by collector EmailcollectorOperationsDesc=Operations are executed from top to bottom order MaxEmailCollectPerCollect=Max number of emails collected per collect +TestCollectNow=Test collect CollectNow=Collect now ConfirmCloneEmailCollector=Are you sure you want to clone the Email collector %s? DateLastCollectResult=Date of latest collect try