actions_sendmails.inc.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. <?php
  2. /* Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. * or see http://www.gnu.org/
  17. */
  18. /**
  19. * \file htdocs/core/actions_sendmails.inc.php
  20. * \brief Code for actions on sending mails from object page
  21. */
  22. // $mysoc must be defined
  23. // $id must be defined
  24. // $paramname must be defined
  25. // $mode must be defined
  26. // $trigger_name must be set (can be '')
  27. // $actiontypecode can be set
  28. // $object and $uobject may be defined
  29. /*
  30. * Add file in email form
  31. */
  32. if (GETPOST('addfile'))
  33. {
  34. $trackid = GETPOST('trackid','aZ09');
  35. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  36. // Set tmp user directory
  37. $vardir=$conf->user->dir_output."/".$user->id;
  38. $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
  39. dol_add_file_process($upload_dir_tmp, 0, 0, 'addedfile', '', null, $trackid);
  40. $action='presend';
  41. }
  42. /*
  43. * Remove file in email form
  44. */
  45. if (! empty($_POST['removedfile']) && empty($_POST['removAll']))
  46. {
  47. $trackid = GETPOST('trackid','aZ09');
  48. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  49. // Set tmp user directory
  50. $vardir=$conf->user->dir_output."/".$user->id;
  51. $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
  52. // TODO Delete only files that was uploaded from email form. This can be addressed by adding the trackid into the temp path then changing donotdeletefile to 2 instead of 1 to say "delete only if into temp dir"
  53. // GETPOST('removedfile','alpha') is position of file into $_SESSION["listofpaths"...] array.
  54. dol_remove_file_process(GETPOST('removedfile','alpha'), 0, 1, $trackid); // We do not delete because if file is the official PDF of doc, we don't want to remove it physically
  55. $action='presend';
  56. }
  57. /*
  58. * Remove all files in email form
  59. */
  60. if (GETPOST('removAll'))
  61. {
  62. $trackid = GETPOST('trackid','aZ09');
  63. $listofpaths=array();
  64. $listofnames=array();
  65. $listofmimes=array();
  66. $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
  67. if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
  68. if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
  69. if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
  70. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  71. $formmail = new FormMail($db);
  72. $formmail->trackid = $trackid;
  73. foreach($listofpaths as $key => $value)
  74. {
  75. $pathtodelete = $value;
  76. $filetodelete = $listofnames[$key];
  77. $result = dol_delete_file($pathtodelete,1); // Delete uploded Files
  78. $langs->load("other");
  79. setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs');
  80. $formmail->remove_attached_files($key); // Update Session
  81. }
  82. }
  83. /*
  84. * Send mail
  85. */
  86. if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_POST['removAll'] && ! $_POST['removedfile'] && ! $_POST['cancel'] && !$_POST['modelselected'])
  87. {
  88. $trackid = GETPOST('trackid','aZ09');
  89. $subject='';$actionmsg='';$actionmsg2='';
  90. if (! empty($conf->dolimail->enabled)) $langs->load("dolimail@dolimail");
  91. $langs->load('mails');
  92. if (is_object($object))
  93. {
  94. $result=$object->fetch($id);
  95. $sendtosocid=0; // Thirdparty on object
  96. if (method_exists($object,"fetch_thirdparty") && $object->element != 'societe')
  97. {
  98. $result=$object->fetch_thirdparty();
  99. if ($object->element == 'user' && $result == 0) $result=1; // Even if not found, we consider ok
  100. $thirdparty=$object->thirdparty;
  101. $sendtosocid=$thirdparty->id;
  102. }
  103. else if ($object->element == 'societe')
  104. {
  105. $thirdparty=$object;
  106. if ($thirdparty->id > 0) $sendtosocid=$thirdparty->id;
  107. elseif (! empty($conf->dolimail->enabled))
  108. {
  109. $dolimail = new Dolimail($db);
  110. $possibleaccounts=$dolimail->get_societe_by_email($_POST['sendto'],"1");
  111. $possibleuser=$dolimail->get_from_user_by_mail($_POST['sendto'],"1"); // suche in llx_societe and socpeople
  112. if (!$possibleaccounts && !$possibleuser)
  113. {
  114. setEventMessages($langs->trans('ErrorFailedToFindSocieteRecord',$_POST['sendto']), null, 'errors');
  115. }
  116. elseif (count($possibleaccounts)>1)
  117. {
  118. $sendtosocid=$possibleaccounts[1]['id'];
  119. $result=$object->fetch($sendtosocid);
  120. setEventMessages($langs->trans('ErrorFoundMoreThanOneRecordWithEmail',$_POST['sendto'],$object->name), null, 'mesgs');
  121. }
  122. else
  123. {
  124. if($possibleaccounts){
  125. $sendtosocid=$possibleaccounts[1]['id'];
  126. $result=$object->fetch($sendtosocid);
  127. }elseif($possibleuser){
  128. $sendtosocid=$possibleuser[0]['id'];
  129. $result=$uobject->fetch($sendtosocid);
  130. $object=$uobject;
  131. }
  132. }
  133. }
  134. }
  135. else dol_print_error('','Use actions_sendmails.in.php for an element/object that is not supported');
  136. }
  137. else $thirdparty = $mysoc;
  138. if ($result > 0)
  139. {
  140. $sendto='';
  141. $sendtocc='';
  142. $sendtobcc='';
  143. $sendtoid = array();
  144. // Define $sendto
  145. $receiver=$_POST['receiver'];
  146. if (! is_array($receiver))
  147. {
  148. if ($receiver == '-1') $receiver=array();
  149. else $receiver=array($receiver);
  150. }
  151. $tmparray=array();
  152. if (trim($_POST['sendto']))
  153. {
  154. // Recipients are provided into free text
  155. $tmparray[] = trim($_POST['sendto']);
  156. }
  157. if (count($receiver)>0)
  158. {
  159. foreach($receiver as $key=>$val)
  160. {
  161. // Recipient was provided from combo list
  162. if ($val == 'thirdparty') // Id of third party
  163. {
  164. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  165. }
  166. elseif ($val) // Id du contact
  167. {
  168. $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
  169. $sendtoid[] = $val;
  170. }
  171. }
  172. }
  173. $sendto=implode(',',$tmparray);
  174. // Define $sendtocc
  175. $receivercc=$_POST['receivercc'];
  176. if (! is_array($receivercc))
  177. {
  178. if ($receivercc == '-1') $receivercc=array();
  179. else $receivercc=array($receivercc);
  180. }
  181. $tmparray=array();
  182. if (trim($_POST['sendtocc']))
  183. {
  184. $tmparray[] = trim($_POST['sendtocc']);
  185. }
  186. if (count($receivercc) > 0)
  187. {
  188. foreach($receivercc as $key=>$val)
  189. {
  190. // Recipient was provided from combo list
  191. if ($val == 'thirdparty') // Id of third party
  192. {
  193. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  194. }
  195. elseif ($val) // Id du contact
  196. {
  197. $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
  198. //$sendtoid[] = $val; TODO Add also id of contact in CC ?
  199. }
  200. }
  201. }
  202. $sendtocc=implode(',',$tmparray);
  203. if (dol_strlen($sendto))
  204. {
  205. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  206. $langs->load("commercial");
  207. $fromtype = GETPOST('fromtype');
  208. if ($fromtype === 'user') {
  209. $from = $user->getFullName($langs) .' <'.$user->email.'>';
  210. }
  211. elseif ($fromtype === 'company') {
  212. $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  213. }
  214. elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
  215. $tmp=explode(',', $user->email_aliases);
  216. $from = trim($tmp[($reg[1] - 1)]);
  217. }
  218. elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
  219. $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
  220. $from = trim($tmp[($reg[1] - 1)]);
  221. }
  222. else {
  223. $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
  224. }
  225. $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>';
  226. $message = $_POST['message'];
  227. $sendtobcc= GETPOST('sendtoccc');
  228. if ($mode == 'emailfromproposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
  229. if ($mode == 'emailfromorder') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
  230. if ($mode == 'emailfrominvoice') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
  231. if ($mode == 'emailfromsupplierproposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
  232. if ($mode == 'emailfromsupplierorder') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
  233. if ($mode == 'emailfromsupplierinvoice') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
  234. $deliveryreceipt = $_POST['deliveryreceipt'];
  235. if ($action == 'send' || $action == 'relance')
  236. {
  237. if (dol_strlen($_POST['subject'])) $subject = $_POST['subject'];
  238. $actionmsg2=$langs->transnoentities('MailSentBy').' '.CMailFile::getValidAddress($from,4,0,1).' '.$langs->transnoentities('To').' '.CMailFile::getValidAddress($sendto,4,0,1);
  239. if ($message)
  240. {
  241. $actionmsg=$langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from);
  242. $actionmsg=dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto));
  243. if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . dol_escape_htmltag($sendtocc));
  244. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
  245. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
  246. $actionmsg = dol_concatdesc($actionmsg, $message);
  247. }
  248. }
  249. // Create form object
  250. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  251. $formmail = new FormMail($db);
  252. $formmail->trackid = $trackid; // $trackid must be defined
  253. $attachedfiles=$formmail->get_attached_files();
  254. $filepath = $attachedfiles['paths'];
  255. $filename = $attachedfiles['names'];
  256. $mimetype = $attachedfiles['mimes'];
  257. // Feature to push mail sent into Sent folder
  258. if (! empty($conf->dolimail->enabled))
  259. {
  260. $mailfromid = explode("#", $_POST['frommail'],3); // $_POST['frommail'] = 'aaa#Sent# <aaa@aaa.com>' // TODO Use a better way to define Sent dir.
  261. if (count($mailfromid)==0) $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
  262. else
  263. {
  264. $mbid = $mailfromid[1];
  265. /*IMAP Postbox*/
  266. $mailboxconfig = new IMAP($db);
  267. $mailboxconfig->fetch($mbid);
  268. if ($mailboxconfig->mailbox_imap_host) $ref=$mailboxconfig->get_ref();
  269. $mailboxconfig->folder_id=$mailboxconfig->mailbox_imap_outbox;
  270. $mailboxconfig->userfolder_fetch();
  271. if ($mailboxconfig->mailbox_save_sent_mails == 1)
  272. {
  273. $folder=str_replace($ref, '', $mailboxconfig->folder_cache_key);
  274. if (!$folder) $folder = "Sent"; // Default Sent folder
  275. $mailboxconfig->mbox = imap_open($mailboxconfig->get_connector_url().$folder, $mailboxconfig->mailbox_imap_login, $mailboxconfig->mailbox_imap_password);
  276. if (FALSE === $mailboxconfig->mbox)
  277. {
  278. $info = FALSE;
  279. $err = $langs->trans('Error3_Imap_Connection_Error');
  280. setEventMessages($err,$mailboxconfig->element, null, 'errors');
  281. }
  282. else
  283. {
  284. $mailboxconfig->mailboxid=$_POST['frommail'];
  285. $mailboxconfig->foldername=$folder;
  286. $from = $mailfromid[0] . $mailfromid[2];
  287. $imap=1;
  288. }
  289. }
  290. }
  291. }
  292. // Send mail
  293. $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid);
  294. if ($mailfile->error)
  295. {
  296. setEventMessage($mailfile->error, 'errors');
  297. $action='presend';
  298. }
  299. else
  300. {
  301. $result=$mailfile->sendfile();
  302. if ($result)
  303. {
  304. $error=0;
  305. // FIXME This must be moved into the trigger for action $trigger_name
  306. if (! empty($conf->dolimail->enabled))
  307. {
  308. $mid = (GETPOST('mid','int') ? GETPOST('mid','int') : 0); // Original mail id is set ?
  309. if ($mid)
  310. {
  311. // set imap flag answered if it is an answered mail
  312. $dolimail=new DoliMail($db);
  313. $dolimail->id = $mid;
  314. $res=$dolimail->set_prop($user, 'answered',1);
  315. }
  316. if ($imap==1)
  317. {
  318. // write mail to IMAP Server
  319. $movemail = $mailboxconfig->putMail($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$folder,$deliveryreceipt,$mailfile);
  320. if ($movemail) setEventMessages($langs->trans("MailMovedToImapFolder",$folder), null, 'mesgs');
  321. else setEventMessages($langs->trans("MailMovedToImapFolder_Warning",$folder), null, 'warnings');
  322. }
  323. }
  324. // Initialisation of datas
  325. if (is_object($object))
  326. {
  327. if (empty($actiontypecode)) $actiontypecode='AC_OTH_AUTO'; // Event insert into agenda automatically
  328. $object->socid = $sendtosocid; // To link to a company
  329. $object->sendtoid = $sendtoid; // To link to contacts/addresses. This is an array.
  330. $object->actiontypecode = $actiontypecode; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
  331. $object->actionmsg = $actionmsg; // Long text
  332. $object->actionmsg2 = $actionmsg2; // Short text
  333. $object->trackid = $trackid;
  334. $object->fk_element = $object->id;
  335. $object->elementtype = $object->element;
  336. // Call of triggers
  337. if (! empty($trigger_name))
  338. {
  339. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  340. $interface=new Interfaces($db);
  341. $result=$interface->run_triggers($trigger_name,$object,$user,$langs,$conf);
  342. if ($result < 0) {
  343. $error++; $errors=$interface->errors;
  344. }
  345. }
  346. }
  347. if ($error)
  348. {
  349. dol_print_error($db);
  350. }
  351. else
  352. {
  353. // Redirect here
  354. // This avoid sending mail twice if going out and then back to page
  355. $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2));
  356. setEventMessages($mesg, null, 'mesgs');
  357. if ($conf->dolimail->enabled)
  358. {
  359. header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.(is_object($object)?$object->id:'').'&'.($paramname2?$paramname2:'mid').'='.$parm2val);
  360. exit;
  361. }
  362. header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.(is_object($object)?$object->id:''));
  363. exit;
  364. }
  365. }
  366. else
  367. {
  368. $langs->load("other");
  369. $mesg='<div class="error">';
  370. if ($mailfile->error)
  371. {
  372. $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
  373. $mesg.='<br>'.$mailfile->error;
  374. }
  375. else
  376. {
  377. $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
  378. }
  379. $mesg.='</div>';
  380. setEventMessages($mesg, null, 'warnings');
  381. $action = 'presend';
  382. }
  383. }
  384. }
  385. else
  386. {
  387. $langs->load("errors");
  388. setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("MailTo")), null, 'warnings');
  389. dol_syslog('Try to send email with no recipiend defined', LOG_WARNING);
  390. $action = 'presend';
  391. }
  392. }
  393. else
  394. {
  395. $langs->load("other");
  396. setEventMessages($langs->trans('ErrorFailedToReadEntity',$object->element), null, 'errors');
  397. dol_syslog('Failed to read data of object id='.$object->id.' element='.$object->element);
  398. $action = 'presend';
  399. }
  400. }