actions_massactions.inc.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. <?php
  2. /* Copyright (C) 2015-2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  4. * Copyright (C) 2018 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
  6. * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. * or see https://www.gnu.org/
  21. */
  22. /**
  23. * \file htdocs/core/actions_massactions.inc.php
  24. * \brief Code for actions done with massaction button (send by email, merge pdf, delete, ...)
  25. */
  26. // $massaction must be defined
  27. // $objectclass and $objectlabel must be defined
  28. // $parameters, $object, $action must be defined for the hook.
  29. // $permissiontoread, $permissiontoadd, $permissiontodelete, $permissiontoclose may be defined
  30. // $uploaddir may be defined (example to $conf->projet->dir_output."/";)
  31. // $toselect may be defined
  32. // $diroutputmassaction may be defined
  33. // Protection
  34. if (empty($objectclass) || empty($uploaddir))
  35. {
  36. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined');
  37. exit;
  38. }
  39. // For backward compatibility
  40. if (!empty($permtoread) && empty($permissiontoread)) $permissiontoread = $permtoread;
  41. if (!empty($permtocreate) && empty($permissiontoadd)) $permissiontoadd = $permtocreate;
  42. if (!empty($permtodelete) && empty($permissiontodelete)) $permissiontodelete = $permtodelete;
  43. // Mass actions. Controls on number of lines checked.
  44. $maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
  45. if (!empty($massaction) && is_array($toselect) && count($toselect) < 1)
  46. {
  47. $error++;
  48. setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
  49. }
  50. if (!$error && is_array($toselect) && count($toselect) > $maxformassaction)
  51. {
  52. setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
  53. $error++;
  54. }
  55. if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
  56. {
  57. $massaction = 'presend';
  58. }
  59. if (!$error && $massaction == 'confirm_presend')
  60. {
  61. $resaction = '';
  62. $nbsent = 0;
  63. $nbignored = 0;
  64. $langs->load("mails");
  65. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  66. $listofobjectid = array();
  67. $listofobjectthirdparties = array();
  68. $listofobjectcontacts = array();
  69. $listofobjectref = array();
  70. $contactidtosend = array();
  71. $attachedfilesThirdpartyObj = array();
  72. $oneemailperrecipient = (GETPOST('oneemailperrecipient') == 'on' ? 1 : 0);
  73. if (!$error)
  74. {
  75. $thirdparty = new Societe($db);
  76. $objecttmp = new $objectclass($db);
  77. if ($objecttmp->element == 'expensereport') $thirdparty = new User($db);
  78. if ($objecttmp->element == 'holiday') $thirdparty = new User($db);
  79. foreach ($toselect as $toselectid)
  80. {
  81. $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
  82. $result = $objecttmp->fetch($toselectid);
  83. if ($result > 0)
  84. {
  85. $listofobjectid[$toselectid] = $toselectid;
  86. $thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
  87. if ($objecttmp->element == 'societe') $thirdpartyid = $objecttmp->id;
  88. if ($objecttmp->element == 'expensereport') $thirdpartyid = $objecttmp->fk_user_author;
  89. if ($objecttmp->element == 'holiday') $thirdpartyid = $objecttmp->fk_user;
  90. if (empty($thirdpartyid)) $thirdpartyid = 0;
  91. if ($objectclass == 'Facture') {
  92. $tmparraycontact = array();
  93. $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
  94. if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
  95. foreach ($tmparraycontact as $data_email) {
  96. $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
  97. }
  98. }
  99. }
  100. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  101. $listofobjectref[$thirdpartyid][$toselectid] = $objecttmp;
  102. }
  103. }
  104. }
  105. // Check mandatory parameters
  106. if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email))
  107. {
  108. $error++;
  109. setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
  110. $massaction = 'presend';
  111. }
  112. $receiver = $_POST['receiver'];
  113. if (!is_array($receiver))
  114. {
  115. if (empty($receiver) || $receiver == '-1') $receiver = array();
  116. else $receiver = array($receiver);
  117. }
  118. if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory
  119. {
  120. $error++;
  121. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
  122. $massaction = 'presend';
  123. }
  124. if (!GETPOST('subject', 'none'))
  125. {
  126. $error++;
  127. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
  128. $massaction = 'presend';
  129. }
  130. // Loop on each recipient/thirdparty
  131. if (!$error)
  132. {
  133. foreach ($listofobjectthirdparties as $thirdpartyid)
  134. {
  135. $result = $thirdparty->fetch($thirdpartyid);
  136. if ($result < 0)
  137. {
  138. dol_print_error($db);
  139. exit;
  140. }
  141. $sendto = '';
  142. $sendtocc = '';
  143. $sendtobcc = '';
  144. $sendtoid = array();
  145. // Define $sendto
  146. $tmparray = array();
  147. if (trim($_POST['sendto']))
  148. {
  149. // Recipients are provided into free text
  150. $tmparray[] = trim($_POST['sendto']);
  151. }
  152. if (count($receiver) > 0)
  153. {
  154. foreach ($receiver as $key=>$val)
  155. {
  156. // Recipient was provided from combo list
  157. if ($val == 'thirdparty') // Id of third party or user
  158. {
  159. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  160. }
  161. elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact
  162. {
  163. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  164. $sendtoid[] = $val;
  165. }
  166. }
  167. }
  168. $sendto = implode(',', $tmparray);
  169. // Define $sendtocc
  170. $receivercc = $_POST['receivercc'];
  171. if (!is_array($receivercc))
  172. {
  173. if ($receivercc == '-1') $receivercc = array();
  174. else $receivercc = array($receivercc);
  175. }
  176. $tmparray = array();
  177. if (trim($_POST['sendtocc']))
  178. {
  179. $tmparray[] = trim($_POST['sendtocc']);
  180. }
  181. if (count($receivercc) > 0)
  182. {
  183. foreach ($receivercc as $key=>$val)
  184. {
  185. // Recipient was provided from combo list
  186. if ($val == 'thirdparty') // Id of third party
  187. {
  188. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  189. }
  190. elseif ($val) // Id du contact
  191. {
  192. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  193. //$sendtoid[] = $val; TODO Add also id of contact in CC ?
  194. }
  195. }
  196. }
  197. $sendtocc = implode(',', $tmparray);
  198. //var_dump($listofobjectref);exit;
  199. $listofqualifiedobj = array();
  200. $listofqualifiedref = array();
  201. $thirdpartywithoutemail = array();
  202. foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
  203. {
  204. //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
  205. if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
  206. {
  207. $langs->load("errors");
  208. $nbignored++;
  209. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  210. continue; // Payment done or started or canceled
  211. }
  212. if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT)
  213. {
  214. $langs->load("errors");
  215. $nbignored++;
  216. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  217. continue;
  218. }
  219. if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT)
  220. {
  221. $langs->load("errors");
  222. $nbignored++;
  223. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  224. continue; // Payment done or started or canceled
  225. }
  226. // Test recipient
  227. if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send)
  228. {
  229. if ($objectobj->element == 'societe')
  230. {
  231. $sendto = $objectobj->email;
  232. }
  233. elseif ($objectobj->element == 'expensereport')
  234. {
  235. $fuser = new User($db);
  236. $fuser->fetch($objectobj->fk_user_author);
  237. $sendto = $fuser->email;
  238. }
  239. elseif ($objectobj->element == 'holiday')
  240. {
  241. $fuser = new User($db);
  242. $fuser->fetch($objectobj->fk_user);
  243. $sendto = $fuser->email;
  244. }
  245. elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid]))
  246. {
  247. $emails_to_sends = array();
  248. $objectobj->fetch_thirdparty();
  249. $contactidtosend = array();
  250. foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
  251. $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
  252. if (!in_array($contactemailid, $contactidtosend)) {
  253. $contactidtosend[] = $contactemailid;
  254. }
  255. }
  256. if (count($emails_to_sends) > 0) {
  257. $sendto = implode(',', $emails_to_sends);
  258. }
  259. }
  260. else
  261. {
  262. $objectobj->fetch_thirdparty();
  263. $sendto = $objectobj->thirdparty->email;
  264. }
  265. }
  266. if (empty($sendto))
  267. {
  268. if ($objectobj->element == 'societe') {
  269. $objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty
  270. }
  271. //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
  272. $nbignored++;
  273. if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
  274. {
  275. $resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
  276. }
  277. dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
  278. $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
  279. continue;
  280. }
  281. if ($_POST['addmaindocfile'])
  282. {
  283. // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
  284. // TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
  285. $filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
  286. $subdir = '';
  287. // TODO Set subdir to be compatible with multi levels dir trees
  288. // $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
  289. $filedir = $uploaddir.'/'.$subdir.dol_sanitizeFileName($objectobj->ref);
  290. $file = $filedir.'/'.$filename;
  291. // For supplier invoices, we use the file provided by supplier, not the one we generate
  292. if ($objectobj->element == 'invoice_supplier')
  293. {
  294. $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+');
  295. $file = $fileparams['fullname'];
  296. }
  297. $mime = dol_mimetype($file);
  298. if (dol_is_file($file))
  299. {
  300. // Create form object
  301. $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
  302. 'paths'=>array($file),
  303. 'names'=>array($filename),
  304. 'mimes'=>array($mime)
  305. );
  306. }
  307. else
  308. {
  309. $nbignored++;
  310. $langs->load("errors");
  311. $resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file).'</div><br>';
  312. dol_syslog('Failed to read file: '.$file, LOG_WARNING);
  313. continue;
  314. }
  315. }
  316. // Object of thirdparty qualified, we add it
  317. $listofqualifiedobj[$objectid] = $objectobj;
  318. $listofqualifiedref[$objectid] = $objectobj->ref;
  319. //var_dump($listofqualifiedref);
  320. }
  321. // Send email if there is at least one qualified object for current thirdparty
  322. if (count($listofqualifiedobj) > 0)
  323. {
  324. $langs->load("commercial");
  325. $reg = array();
  326. $fromtype = GETPOST('fromtype');
  327. if ($fromtype === 'user') {
  328. $from = $user->getFullName($langs).' <'.$user->email.'>';
  329. }
  330. elseif ($fromtype === 'company') {
  331. $from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  332. }
  333. elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
  334. $tmp = explode(',', $user->email_aliases);
  335. $from = trim($tmp[($reg[1] - 1)]);
  336. }
  337. elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
  338. $tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
  339. $from = trim($tmp[($reg[1] - 1)]);
  340. }
  341. elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
  342. $sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
  343. $resql = $db->query($sql);
  344. $obj = $db->fetch_object($resql);
  345. if ($obj)
  346. {
  347. $from = $obj->label.' <'.$obj->email.'>';
  348. }
  349. }
  350. else {
  351. $from = $_POST['fromname'].' <'.$_POST['frommail'].'>';
  352. }
  353. $replyto = $from;
  354. $subject = GETPOST('subject', 'none');
  355. $message = GETPOST('message', 'none');
  356. $sendtobcc = GETPOST('sendtoccc');
  357. if ($objectclass == 'Propal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
  358. if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
  359. if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
  360. if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
  361. if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
  362. if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
  363. if ($objectclass == 'Project') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO));
  364. // $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
  365. // $looparray will be an array with number of email to send for the current thirdparty (so 1 or n if n object for same thirdparty)
  366. $looparray = array();
  367. if (!$oneemailperrecipient)
  368. {
  369. $looparray = $listofqualifiedobj;
  370. foreach ($looparray as $key => $objecttmp)
  371. {
  372. $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
  373. }
  374. }
  375. else
  376. {
  377. $objectforloop = new $objectclass($db);
  378. $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
  379. $looparray[0] = $objectforloop;
  380. }
  381. //var_dump($looparray);exit;
  382. dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
  383. //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
  384. foreach ($looparray as $objectid => $objecttmp) // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object
  385. {
  386. // Make substitution in email content
  387. if (!empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project))
  388. {
  389. $objecttmp->fetch_projet();
  390. }
  391. $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
  392. $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
  393. $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
  394. $substitutionarray['__EMAIL__'] = $thirdparty->email;
  395. $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
  396. $parameters = array('mode'=>'formemail');
  397. if (!empty($listofobjectthirdparties)) {
  398. $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
  399. }
  400. if (!empty($listofobjectref)) {
  401. $parameters['listofobjectref'] = $listofobjectref;
  402. }
  403. complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
  404. $subjectreplaced = make_substitutions($subject, $substitutionarray);
  405. $messagereplaced = make_substitutions($message, $substitutionarray);
  406. $attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
  407. if ($oneemailperrecipient)
  408. {
  409. // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
  410. if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id]))
  411. {
  412. foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
  413. // Create form object
  414. $attachedfiles = array(
  415. 'paths'=>array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
  416. 'names'=>array_merge($attachedfiles['names'], $objAttachedFiles['names']),
  417. 'mimes'=>array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
  418. );
  419. }
  420. }
  421. }
  422. elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
  423. // Create form object
  424. // if "one email per recipient" isn't check we must separate $attachedfiles by object
  425. $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
  426. }
  427. $filepath = $attachedfiles['paths'];
  428. $filename = $attachedfiles['names'];
  429. $mimetype = $attachedfiles['mimes'];
  430. // Define the trackid when emails sent from the mass action
  431. if ($oneemailperrecipient)
  432. {
  433. $trackid = 'thi'.$thirdparty->id;
  434. if ($objecttmp->element == 'expensereport') $trackid = 'use'.$thirdparty->id;
  435. if ($objecttmp->element == 'holiday') $trackid = 'use'.$thirdparty->id;
  436. }
  437. else
  438. {
  439. $trackid = strtolower(get_class($objecttmp));
  440. if (get_class($objecttmp) == 'Contrat') $trackid = 'con';
  441. if (get_class($objecttmp) == 'Propal') $trackid = 'pro';
  442. if (get_class($objecttmp) == 'Commande') $trackid = 'ord';
  443. if (get_class($objecttmp) == 'Facture') $trackid = 'inv';
  444. if (get_class($objecttmp) == 'Supplier_Proposal') $trackid = 'spr';
  445. if (get_class($objecttmp) == 'CommandeFournisseur') $trackid = 'sor';
  446. if (get_class($objecttmp) == 'FactureFournisseur') $trackid = 'sin';
  447. $trackid .= $objecttmp->id;
  448. }
  449. //var_dump($filepath);
  450. //var_dump($trackid);exit;
  451. //var_dump($subjectreplaced);
  452. if (empty($sendcontext)) $sendcontext = 'standard';
  453. // Send mail (substitutionarray must be done just before this)
  454. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  455. $mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext);
  456. if ($mailfile->error)
  457. {
  458. $resaction .= '<div class="error">'.$mailfile->error.'</div>';
  459. }
  460. else
  461. {
  462. $result = $mailfile->sendfile();
  463. if ($result)
  464. {
  465. $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'<br>'; // Must not contain "
  466. $error = 0;
  467. // Insert logs into agenda
  468. foreach ($listofqualifiedobj as $objid2 => $objectobj2)
  469. {
  470. if ((!$oneemailperrecipient) && $objid2 != $objectid) continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
  471. dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
  472. /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
  473. if ($objectclass == 'Commande') $actiontypecode='AC_COM';
  474. if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
  475. if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
  476. if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
  477. if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
  478. $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
  479. if ($message)
  480. {
  481. if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
  482. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
  483. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
  484. $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
  485. }
  486. $actionmsg2 = '';
  487. // Initialisation donnees
  488. $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
  489. $objectobj2->actionmsg = $actionmsg; // Long text
  490. $objectobj2->actionmsg2 = $actionmsg2; // Short text
  491. $objectobj2->fk_element = $objid2;
  492. $objectobj2->elementtype = $objectobj2->element;
  493. $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
  494. if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYMAIL';
  495. if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYMAIL';
  496. if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYMAIL';
  497. if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYMAIL';
  498. if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYMAIL';
  499. if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
  500. if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
  501. if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
  502. if (!empty($triggername))
  503. {
  504. // Call trigger
  505. $result = $objectobj2->call_trigger($triggername, $user);
  506. if ($result < 0) $error++;
  507. // End call triggers
  508. if ($error)
  509. {
  510. setEventMessages($db->lasterror(), $errors, 'errors');
  511. dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
  512. }
  513. }
  514. $nbsent++; // Nb of object sent
  515. }
  516. }
  517. else
  518. {
  519. $langs->load("other");
  520. if ($mailfile->error)
  521. {
  522. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
  523. $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
  524. }
  525. else
  526. {
  527. $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
  528. }
  529. }
  530. }
  531. }
  532. }
  533. }
  534. $resaction .= ($resaction ? '<br>' : $resaction);
  535. $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
  536. $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
  537. $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
  538. $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
  539. if ($nbsent)
  540. {
  541. $action = ''; // Do not show form post if there was at least one successfull sent
  542. //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
  543. setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
  544. setEventMessages($resaction, null, 'mesgs');
  545. }
  546. else
  547. {
  548. //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
  549. setEventMessages($resaction, null, 'warnings');
  550. }
  551. $action = 'list';
  552. $massaction = '';
  553. }
  554. }
  555. if ($massaction == 'confirm_createbills') // Create bills from orders
  556. {
  557. $orders = GETPOST('toselect', 'array');
  558. $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
  559. $validate_invoices = GETPOST('validate_invoices', 'int');
  560. $TFact = array();
  561. $TFactThird = array();
  562. $nb_bills_created = 0;
  563. $db->begin();
  564. foreach ($orders as $id_order)
  565. {
  566. $cmd = new Commande($db);
  567. if ($cmd->fetch($id_order) <= 0) continue;
  568. $objecttmp = new Facture($db);
  569. if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order.
  570. else {
  571. // Load extrafields of order
  572. $cmd->fetch_optionals();
  573. $objecttmp->socid = $cmd->socid;
  574. $objecttmp->type = Facture::TYPE_STANDARD;
  575. $objecttmp->cond_reglement_id = $cmd->cond_reglement_id;
  576. $objecttmp->mode_reglement_id = $cmd->mode_reglement_id;
  577. $objecttmp->fk_project = $cmd->fk_project;
  578. $objecttmp->multicurrency_code = $cmd->multicurrency_code;
  579. if (empty($createbills_onebythird)) $objecttmp->ref_client = $cmd->ref_client;
  580. $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  581. if (empty($datefacture))
  582. {
  583. $datefacture = dol_now();
  584. }
  585. $objecttmp->date = $datefacture;
  586. $objecttmp->origin = 'commande';
  587. $objecttmp->origin_id = $id_order;
  588. $objecttmp->array_options = $cmd->array_options; // Copy extrafields
  589. $res = $objecttmp->create($user);
  590. if ($res > 0) $nb_bills_created++;
  591. }
  592. if ($objecttmp->id > 0)
  593. {
  594. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  595. $sql .= "fk_source";
  596. $sql .= ", sourcetype";
  597. $sql .= ", fk_target";
  598. $sql .= ", targettype";
  599. $sql .= ") VALUES (";
  600. $sql .= $id_order;
  601. $sql .= ", '".$objecttmp->origin."'";
  602. $sql .= ", ".$objecttmp->id;
  603. $sql .= ", '".$objecttmp->element."'";
  604. $sql .= ")";
  605. if (!$db->query($sql))
  606. {
  607. $error++;
  608. }
  609. if (!$error)
  610. {
  611. $lines = $cmd->lines;
  612. if (empty($lines) && method_exists($cmd, 'fetch_lines'))
  613. {
  614. $cmd->fetch_lines();
  615. $lines = $cmd->lines;
  616. }
  617. $fk_parent_line = 0;
  618. $num = count($lines);
  619. for ($i = 0; $i < $num; $i++)
  620. {
  621. $desc = ($lines[$i]->desc ? $lines[$i]->desc : '');
  622. // If we build one invoice for several order, we must put the invoice of order on the line
  623. if (!empty($createbills_onebythird))
  624. {
  625. $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day'));
  626. }
  627. if ($lines[$i]->subprice < 0)
  628. {
  629. // Negative line, we create a discount line
  630. $discount = new DiscountAbsolute($db);
  631. $discount->fk_soc = $objecttmp->socid;
  632. $discount->amount_ht = abs($lines[$i]->total_ht);
  633. $discount->amount_tva = abs($lines[$i]->total_tva);
  634. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  635. $discount->tva_tx = $lines[$i]->tva_tx;
  636. $discount->fk_user = $user->id;
  637. $discount->description = $desc;
  638. $discountid = $discount->create($user);
  639. if ($discountid > 0)
  640. {
  641. $result = $objecttmp->insert_discount($discountid);
  642. //$result=$discount->link_to_invoice($lineid,$id);
  643. }
  644. else
  645. {
  646. setEventMessages($discount->error, $discount->errors, 'errors');
  647. $error++;
  648. break;
  649. }
  650. }
  651. else
  652. {
  653. // Positive line
  654. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  655. // Date start
  656. $date_start = false;
  657. if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue;
  658. if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel;
  659. if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start;
  660. //Date end
  661. $date_end = false;
  662. if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue;
  663. if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel;
  664. if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end;
  665. // Reset fk_parent_line for no child products and special product
  666. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
  667. {
  668. $fk_parent_line = 0;
  669. }
  670. // Extrafields
  671. if (method_exists($lines[$i], 'fetch_optionals')) {
  672. $lines[$i]->fetch_optionals();
  673. $array_options = $lines[$i]->array_options;
  674. }
  675. $result = $objecttmp->addline(
  676. $desc,
  677. $lines[$i]->subprice,
  678. $lines[$i]->qty,
  679. $lines[$i]->tva_tx,
  680. $lines[$i]->localtax1_tx,
  681. $lines[$i]->localtax2_tx,
  682. $lines[$i]->fk_product,
  683. $lines[$i]->remise_percent,
  684. $date_start,
  685. $date_end,
  686. 0,
  687. $lines[$i]->info_bits,
  688. $lines[$i]->fk_remise_except,
  689. 'HT',
  690. 0,
  691. $product_type,
  692. $ii,
  693. $lines[$i]->special_code,
  694. $objecttmp->origin,
  695. $lines[$i]->rowid,
  696. $fk_parent_line,
  697. $lines[$i]->fk_fournprice,
  698. $lines[$i]->pa_ht,
  699. $lines[$i]->label,
  700. $array_options,
  701. 100,
  702. 0,
  703. $lines[$i]->fk_unit
  704. );
  705. if ($result > 0)
  706. {
  707. $lineid = $result;
  708. }
  709. else
  710. {
  711. $lineid = 0;
  712. $error++;
  713. break;
  714. }
  715. // Defined the new fk_parent_line
  716. if ($result > 0 && $lines[$i]->product_type == 9)
  717. {
  718. $fk_parent_line = $result;
  719. }
  720. }
  721. }
  722. }
  723. }
  724. //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module.
  725. if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
  726. else $TFact[$objecttmp->id] = $objecttmp;
  727. }
  728. // Build doc with all invoices
  729. $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
  730. $toselect = array();
  731. if (!$error && $validate_invoices)
  732. {
  733. $massaction = $action = 'builddoc';
  734. foreach ($TAllFact as &$objecttmp)
  735. {
  736. $result = $objecttmp->validate($user);
  737. if ($result <= 0)
  738. {
  739. $error++;
  740. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  741. break;
  742. }
  743. $id = $objecttmp->id; // For builddoc action
  744. $object = $objecttmp;
  745. // Builddoc
  746. $donotredirect = 1;
  747. $upload_dir = $conf->facture->dir_output;
  748. $permissiontoadd = $user->rights->facture->creer;
  749. // Call action to build doc
  750. $savobject = $object;
  751. $object = $objecttmp;
  752. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  753. $object = $savobject;
  754. }
  755. $massaction = $action = 'confirm_createbills';
  756. }
  757. if (!$error)
  758. {
  759. $db->commit();
  760. setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
  761. // Make a redirect to avoid to bill twice if we make a refresh or back
  762. $param = '';
  763. if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
  764. if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
  765. if ($sall) $param .= '&sall='.urlencode($sall);
  766. if ($socid > 0) $param .= '&socid='.urlencode($socid);
  767. if ($search_status != '') $param .= '&search_status='.urlencode($search_status);
  768. if ($search_orderday) $param .= '&search_orderday='.urlencode($search_orderday);
  769. if ($search_ordermonth) $param .= '&search_ordermonth='.urlencode($search_ordermonth);
  770. if ($search_orderyear) $param .= '&search_orderyear='.urlencode($search_orderyear);
  771. if ($search_deliveryday) $param .= '&search_deliveryday='.urlencode($search_deliveryday);
  772. if ($search_deliverymonth) $param .= '&search_deliverymonth='.urlencode($search_deliverymonth);
  773. if ($search_deliveryyear) $param .= '&search_deliveryyear='.urlencode($search_deliveryyear);
  774. if ($search_ref) $param .= '&search_ref='.urlencode($search_ref);
  775. if ($search_company) $param .= '&search_company='.urlencode($search_company);
  776. if ($search_ref_customer) $param .= '&search_ref_customer='.urlencode($search_ref_customer);
  777. if ($search_user > 0) $param .= '&search_user='.urlencode($search_user);
  778. if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale);
  779. if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht);
  780. if ($search_total_vat != '') $param .= '&search_total_vat='.urlencode($search_total_vat);
  781. if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc);
  782. if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref);
  783. if ($show_files) $param .= '&show_files='.urlencode($show_files);
  784. if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
  785. if ($billed != '') $param .= '&billed='.urlencode($billed);
  786. header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
  787. exit;
  788. }
  789. else
  790. {
  791. $db->rollback();
  792. $action = 'create';
  793. $_GET["origin"] = $_POST["origin"];
  794. $_GET["originid"] = $_POST["originid"];
  795. setEventMessages("Error", null, 'errors');
  796. $error++;
  797. }
  798. }
  799. if (!$error && $massaction == 'cancelorders')
  800. {
  801. $db->begin();
  802. $nbok = 0;
  803. $orders = GETPOST('toselect', 'array');
  804. foreach ($orders as $id_order)
  805. {
  806. $cmd = new Commande($db);
  807. if ($cmd->fetch($id_order) <= 0)
  808. continue;
  809. if ($cmd->statut != Commande::STATUS_VALIDATED)
  810. {
  811. $langs->load('errors');
  812. setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
  813. $error++;
  814. break;
  815. } else {
  816. // TODO We do not provide warehouse so no stock change here for the moment.
  817. $result = $cmd->cancel();
  818. }
  819. if ($result < 0)
  820. {
  821. setEventMessages($cmd->error, $cmd->errors, 'errors');
  822. $error++;
  823. break;
  824. }
  825. else
  826. $nbok++;
  827. }
  828. if (!$error)
  829. {
  830. if ($nbok > 1)
  831. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  832. else
  833. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  834. $db->commit();
  835. }
  836. else
  837. {
  838. $db->rollback();
  839. }
  840. }
  841. if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search'))
  842. {
  843. if (empty($diroutputmassaction))
  844. {
  845. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
  846. exit;
  847. }
  848. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  849. require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
  850. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  851. $objecttmp = new $objectclass($db);
  852. $listofobjectid = array();
  853. $listofobjectthirdparties = array();
  854. $listofobjectref = array();
  855. foreach ($toselect as $toselectid)
  856. {
  857. $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
  858. $result = $objecttmp->fetch($toselectid);
  859. if ($result > 0)
  860. {
  861. $listofobjectid[$toselectid] = $toselectid;
  862. $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
  863. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  864. $listofobjectref[$toselectid] = $objecttmp->ref;
  865. }
  866. }
  867. $arrayofinclusion = array();
  868. foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
  869. foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files
  870. $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
  871. // build list of files with full path
  872. $files = array();
  873. foreach ($listofobjectref as $basename)
  874. {
  875. $basename = dol_sanitizeFileName($basename);
  876. foreach ($listoffiles as $filefound)
  877. {
  878. if (strstr($filefound["name"], $basename))
  879. {
  880. $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
  881. break;
  882. }
  883. }
  884. }
  885. // Define output language (Here it is not used because we do only merging existing PDF)
  886. $outputlangs = $langs;
  887. $newlang = '';
  888. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  889. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $objecttmp->thirdparty->default_lang;
  890. if (!empty($newlang)) {
  891. $outputlangs = new Translate("", $conf);
  892. $outputlangs->setDefaultLang($newlang);
  893. }
  894. if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT))
  895. {
  896. // Create output dir if not exists
  897. dol_mkdir($diroutputmassaction);
  898. // Defined name of merged file
  899. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  900. $filename = preg_replace('/\s/', '_', $filename);
  901. // Save merged file
  902. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
  903. {
  904. if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  905. else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  906. }
  907. if ($year) $filename .= '_'.$year;
  908. if ($month) $filename .= '_'.$month;
  909. if (count($files) > 0)
  910. {
  911. $now = dol_now();
  912. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  913. $input_files = '';
  914. foreach ($files as $f) {
  915. $input_files .= ' '.escapeshellarg($f);
  916. }
  917. $cmd = 'pdftk ' . $input_files . ' cat output '.escapeshellarg($file);
  918. exec($cmd);
  919. // check if pdftk is installed
  920. if (file_exists($file)) {
  921. if (!empty($conf->global->MAIN_UMASK))
  922. @chmod($file, octdec($conf->global->MAIN_UMASK));
  923. $langs->load("exports");
  924. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  925. } else {
  926. setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
  927. }
  928. }
  929. else
  930. {
  931. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  932. }
  933. }
  934. else {
  935. // Create empty PDF
  936. $formatarray = pdf_getFormat();
  937. $page_largeur = $formatarray['width'];
  938. $page_hauteur = $formatarray['height'];
  939. $format = array($page_largeur, $page_hauteur);
  940. $pdf = pdf_getInstance($format);
  941. if (class_exists('TCPDF'))
  942. {
  943. $pdf->setPrintHeader(false);
  944. $pdf->setPrintFooter(false);
  945. }
  946. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  947. if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
  948. // Add all others
  949. foreach ($files as $file)
  950. {
  951. // Charge un document PDF depuis un fichier.
  952. $pagecount = $pdf->setSourceFile($file);
  953. for ($i = 1; $i <= $pagecount; $i++)
  954. {
  955. $tplidx = $pdf->importPage($i);
  956. $s = $pdf->getTemplatesize($tplidx);
  957. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  958. $pdf->useTemplate($tplidx);
  959. }
  960. }
  961. // Create output dir if not exists
  962. dol_mkdir($diroutputmassaction);
  963. // Defined name of merged file
  964. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  965. $filename = preg_replace('/\s/', '_', $filename);
  966. // Save merged file
  967. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
  968. {
  969. if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  970. else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  971. }
  972. if ($year) $filename .= '_'.$year;
  973. if ($month) $filename .= '_'.$month;
  974. if ($pagecount)
  975. {
  976. $now = dol_now();
  977. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  978. $pdf->Output($file, 'F');
  979. if (!empty($conf->global->MAIN_UMASK))
  980. @chmod($file, octdec($conf->global->MAIN_UMASK));
  981. $langs->load("exports");
  982. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  983. }
  984. else
  985. {
  986. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  987. }
  988. }
  989. }
  990. // Remove a file from massaction area
  991. if ($action == 'remove_file')
  992. {
  993. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  994. $langs->load("other");
  995. $upload_dir = $diroutputmassaction;
  996. $file = $upload_dir.'/'.GETPOST('file');
  997. $ret = dol_delete_file($file);
  998. if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
  999. else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
  1000. $action = '';
  1001. }
  1002. // Validate records
  1003. if (!$error && $massaction == 'validate' && $permissiontoadd)
  1004. {
  1005. $objecttmp = new $objectclass($db);
  1006. if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL))
  1007. {
  1008. $langs->load("errors");
  1009. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  1010. $error++;
  1011. }
  1012. if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
  1013. {
  1014. $langs->load("errors");
  1015. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  1016. $error++;
  1017. }
  1018. if (!$error)
  1019. {
  1020. $db->begin();
  1021. $nbok = 0;
  1022. foreach ($toselect as $toselectid)
  1023. {
  1024. $result = $objecttmp->fetch($toselectid);
  1025. if ($result > 0)
  1026. {
  1027. $result = $objecttmp->validate($user);
  1028. if ($result == 0)
  1029. {
  1030. $langs->load("errors");
  1031. setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
  1032. $error++;
  1033. break;
  1034. }
  1035. elseif ($result < 0)
  1036. {
  1037. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1038. $error++;
  1039. break;
  1040. }
  1041. else {
  1042. // validate() rename pdf but do not regenerate
  1043. // Define output language
  1044. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1045. $outputlangs = $langs;
  1046. $newlang = '';
  1047. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1048. $newlang = GETPOST('lang_id', 'aZ09');
  1049. }
  1050. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1051. $newlang = $objecttmp->thirdparty->default_lang;
  1052. }
  1053. if (!empty($newlang)) {
  1054. $outputlangs = new Translate("", $conf);
  1055. $outputlangs->setDefaultLang($newlang);
  1056. $outputlangs->load('products');
  1057. }
  1058. $model = $objecttmp->model_pdf;
  1059. $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
  1060. // To be sure vars is defined
  1061. $hidedetails = !empty($hidedetails) ? $hidedetails : 0;
  1062. $hidedesc = !empty($hidedesc) ? $hidedesc : 0;
  1063. $hideref = !empty($hideref) ? $hideref : 0;
  1064. $moreparams = !empty($moreparams) ? $moreparams : null;
  1065. $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1066. if ($result < 0) {
  1067. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1068. }
  1069. }
  1070. $nbok++;
  1071. }
  1072. }
  1073. else
  1074. {
  1075. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1076. $error++;
  1077. break;
  1078. }
  1079. }
  1080. if (!$error)
  1081. {
  1082. if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  1083. else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  1084. $db->commit();
  1085. }
  1086. else
  1087. {
  1088. $db->rollback();
  1089. }
  1090. //var_dump($listofobjectthirdparties);exit;
  1091. }
  1092. }
  1093. // Closed records
  1094. if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissiontoclose) {
  1095. $db->begin();
  1096. $objecttmp = new $objectclass($db);
  1097. $nbok = 0;
  1098. foreach ($toselect as $toselectid) {
  1099. $result = $objecttmp->fetch($toselectid);
  1100. if ($result > 0) {
  1101. $result = $objecttmp->cloture($user, 3);
  1102. if ($result <= 0) {
  1103. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1104. $error++;
  1105. break;
  1106. } else
  1107. $nbok++;
  1108. }
  1109. else {
  1110. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1111. $error++;
  1112. break;
  1113. }
  1114. }
  1115. if (!$error) {
  1116. if ($nbok > 1)
  1117. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  1118. else
  1119. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  1120. $db->commit();
  1121. }
  1122. else {
  1123. $db->rollback();
  1124. }
  1125. }
  1126. // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
  1127. if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete)
  1128. {
  1129. $db->begin();
  1130. $objecttmp = new $objectclass($db);
  1131. $nbok = 0;
  1132. foreach ($toselect as $toselectid)
  1133. {
  1134. $result = $objecttmp->fetch($toselectid);
  1135. if ($result > 0)
  1136. {
  1137. // Refuse deletion for some objects/status
  1138. if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT)
  1139. {
  1140. $langs->load("errors");
  1141. $nbignored++;
  1142. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
  1143. continue;
  1144. }
  1145. if ($objectclass == "Task" && $objecttmp->hasChildren() > 0)
  1146. {
  1147. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".$objecttmp->id;
  1148. $res = $db->query($sql);
  1149. if (!$res)
  1150. {
  1151. setEventMessage('ErrorRecordParentingNotModified', 'errors');
  1152. $error++;
  1153. }
  1154. }
  1155. if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
  1156. else $result = $objecttmp->delete($user);
  1157. if ($result <= 0)
  1158. {
  1159. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1160. $error++;
  1161. break;
  1162. }
  1163. else $nbok++;
  1164. }
  1165. else
  1166. {
  1167. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1168. $error++;
  1169. break;
  1170. }
  1171. }
  1172. if (!$error)
  1173. {
  1174. if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
  1175. else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
  1176. $db->commit();
  1177. }
  1178. else
  1179. {
  1180. $db->rollback();
  1181. }
  1182. //var_dump($listofobjectthirdparties);exit;
  1183. }
  1184. // Generate document foreach object according to model linked to object
  1185. // @todo : propose model selection
  1186. if (!$error && $massaction == 'generate_doc' && $permissiontoread)
  1187. {
  1188. $db->begin();
  1189. $objecttmp = new $objectclass($db);
  1190. $nbok = 0;
  1191. foreach ($toselect as $toselectid)
  1192. {
  1193. $result = $objecttmp->fetch($toselectid);
  1194. if ($result > 0)
  1195. {
  1196. $outputlangs = $langs;
  1197. $newlang = '';
  1198. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  1199. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
  1200. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang = $objecttmp->default_lang; // for thirdparty
  1201. if (!empty($newlang))
  1202. {
  1203. $outputlangs = new Translate("", $conf);
  1204. $outputlangs->setDefaultLang($newlang);
  1205. }
  1206. // To be sure vars is defined
  1207. if (empty($hidedetails)) $hidedetails = 0;
  1208. if (empty($hidedesc)) $hidedesc = 0;
  1209. if (empty($hideref)) $hideref = 0;
  1210. if (empty($moreparams)) $moreparams = null;
  1211. $result = $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1212. if ($result <= 0)
  1213. {
  1214. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1215. $error++;
  1216. break;
  1217. }
  1218. else $nbok++;
  1219. }
  1220. else
  1221. {
  1222. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1223. $error++;
  1224. break;
  1225. }
  1226. }
  1227. if (!$error)
  1228. {
  1229. if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
  1230. else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
  1231. $db->commit();
  1232. }
  1233. else
  1234. {
  1235. $db->rollback();
  1236. }
  1237. }
  1238. $parameters['toselect'] = $toselect;
  1239. $parameters['uploaddir'] = $uploaddir;
  1240. $parameters['massaction'] = $massaction;
  1241. $parameters['diroutputmassaction'] = $diroutputmassaction;
  1242. $reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1243. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');