actions_massactions.inc.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. * or see http://www.gnu.org/
  19. */
  20. /**
  21. * \file htdocs/core/actions_massactions.inc.php
  22. * \brief Code for actions done with massaction button (send by email, merge pdf, delete, ...)
  23. */
  24. // $massaction must be defined
  25. // $objectclass and $objectlabel must be defined
  26. // $parameters, $object, $action must be defined for the hook.
  27. // $permtoread, $permtocreate and $permtodelete may be defined
  28. // $uploaddir may be defined (example to $conf->projet->dir_output."/";)
  29. // $toselect may be defined
  30. // Protection
  31. if (empty($objectclass) || empty($uploaddir))
  32. {
  33. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined');
  34. exit;
  35. }
  36. // Mass actions. Controls on number of lines checked.
  37. $maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
  38. if (! empty($massaction) && count($toselect) < 1)
  39. {
  40. $error++;
  41. setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
  42. }
  43. if (! $error && is_array($toselect) && count($toselect) > $maxformassaction)
  44. {
  45. setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors');
  46. $error++;
  47. }
  48. 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
  49. {
  50. $massaction='presend';
  51. }
  52. if (! $error && $massaction == 'confirm_presend')
  53. {
  54. $resaction = '';
  55. $nbsent = 0;
  56. $nbignored = 0;
  57. $langs->load("mails");
  58. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  59. $listofobjectid=array();
  60. $listofobjectthirdparties=array();
  61. $listofobjectref=array();
  62. if (! $error)
  63. {
  64. $thirdparty=new Societe($db);
  65. if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
  66. $objecttmp=new $objectclass($db);
  67. foreach($toselect as $toselectid)
  68. {
  69. $objecttmp=new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
  70. $result=$objecttmp->fetch($toselectid);
  71. if ($result > 0)
  72. {
  73. $listofobjectid[$toselectid]=$toselectid;
  74. $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
  75. if ($objecttmp->element == 'societe') $thirdpartyid=$objecttmp->id;
  76. if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
  77. $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
  78. $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
  79. }
  80. }
  81. }
  82. // Check mandatory parameters
  83. if (empty($user->email))
  84. {
  85. $error++;
  86. setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
  87. $massaction='presend';
  88. }
  89. $receiver=$_POST['receiver'];
  90. if (! is_array($receiver))
  91. {
  92. if (empty($receiver) || $receiver == '-1') $receiver=array();
  93. else $receiver=array($receiver);
  94. }
  95. if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory
  96. {
  97. $error++;
  98. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
  99. $massaction='presend';
  100. }
  101. if (! GETPOST('subject','none'))
  102. {
  103. $error++;
  104. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
  105. $massaction='presend';
  106. }
  107. // Loop on each recipient/thirdparty
  108. if (! $error)
  109. {
  110. foreach ($listofobjectthirdparties as $thirdpartyid)
  111. {
  112. $result = $thirdparty->fetch($thirdpartyid);
  113. if ($result < 0)
  114. {
  115. dol_print_error($db);
  116. exit;
  117. }
  118. $sendto='';
  119. $sendtocc='';
  120. $sendtobcc='';
  121. $sendtoid = array();
  122. // Define $sendto
  123. $tmparray=array();
  124. if (trim($_POST['sendto']))
  125. {
  126. // Recipients are provided into free text
  127. $tmparray[] = trim($_POST['sendto']);
  128. }
  129. if (count($receiver)>0)
  130. {
  131. foreach($receiver as $key=>$val)
  132. {
  133. // Recipient was provided from combo list
  134. if ($val == 'thirdparty') // Id of third party or user
  135. {
  136. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  137. }
  138. elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact
  139. {
  140. $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
  141. $sendtoid[] = $val;
  142. }
  143. }
  144. }
  145. $sendto=implode(',',$tmparray);
  146. // Define $sendtocc
  147. $receivercc=$_POST['receivercc'];
  148. if (! is_array($receivercc))
  149. {
  150. if ($receivercc == '-1') $receivercc=array();
  151. else $receivercc=array($receivercc);
  152. }
  153. $tmparray=array();
  154. if (trim($_POST['sendtocc']))
  155. {
  156. $tmparray[] = trim($_POST['sendtocc']);
  157. }
  158. if (count($receivercc) > 0)
  159. {
  160. foreach($receivercc as $key=>$val)
  161. {
  162. // Recipient was provided from combo list
  163. if ($val == 'thirdparty') // Id of third party
  164. {
  165. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  166. }
  167. elseif ($val) // Id du contact
  168. {
  169. $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
  170. //$sendtoid[] = $val; TODO Add also id of contact in CC ?
  171. }
  172. }
  173. }
  174. $sendtocc=implode(',',$tmparray);
  175. //var_dump($listofobjectref);exit;
  176. $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
  177. $listofqualifiedobj=array();
  178. $listofqualifiedref=array();
  179. $thirdpartywithoutemail=array();
  180. foreach($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
  181. {
  182. //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
  183. if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
  184. {
  185. $langs->load("errors");
  186. $nbignored++;
  187. $resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
  188. continue; // Payment done or started or canceled
  189. }
  190. if ($objectclass == 'Commande' && $objectoj->statut == Commande::STATUS_DRAFT)
  191. {
  192. $langs->load("errors");
  193. $nbignored++;
  194. $resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
  195. continue;
  196. }
  197. if ($objectclass == 'Facture' && $objectobj->statut != Facture::STATUS_VALIDATED)
  198. {
  199. $langs->load("errors");
  200. $nbignored++;
  201. $resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$objectobj->ref).'</div><br>';
  202. continue; // Payment done or started or canceled
  203. }
  204. // Test recipient
  205. if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send)
  206. {
  207. if ($objectobj->element == 'expensereport')
  208. {
  209. $fuser = new User($db);
  210. $fuser->fetch($objectobj->fk_user_author);
  211. $sendto = $fuser->email;
  212. }
  213. else
  214. {
  215. $objectobj->fetch_thirdparty();
  216. $sendto = $objectobj->thirdparty->email;
  217. }
  218. }
  219. if (empty($sendto))
  220. {
  221. //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
  222. $nbignored++;
  223. if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
  224. {
  225. $resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$objectobj->thirdparty->name).'</div><br>';
  226. }
  227. dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
  228. $thirdpartywithoutemail[$objectobj->thirdparty->id]=1;
  229. continue;
  230. }
  231. if ($_POST['addmaindocfile'])
  232. {
  233. // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
  234. // TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
  235. $filename=dol_sanitizeFileName($objectobj->ref).'.pdf';
  236. $filedir=$uploaddir . '/' . dol_sanitizeFileName($objectobj->ref);
  237. $file = $filedir . '/' . $filename;
  238. $mime = dol_mimetype($file);
  239. if (dol_is_file($file))
  240. {
  241. // Create form object
  242. $attachedfiles=array(
  243. 'paths'=>array_merge($attachedfiles['paths'],array($file)),
  244. 'names'=>array_merge($attachedfiles['names'],array($filename)),
  245. 'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
  246. );
  247. }
  248. else
  249. {
  250. $nbignored++;
  251. $langs->load("errors");
  252. $resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>';
  253. dol_syslog('Failed to read file: '.$file, LOG_WARNING);
  254. continue;
  255. }
  256. }
  257. // Object of thirdparty qualified
  258. $listofqualifiedobj[$objectid]=$objectobj;
  259. $listofqualifiedref[$objectid]=$objectobj->ref;
  260. //var_dump($listofqualifiedref);
  261. }
  262. // Send email if there is at least one qualified record
  263. if (count($listofqualifiedobj) > 0)
  264. {
  265. $langs->load("commercial");
  266. $fromtype = GETPOST('fromtype');
  267. if ($fromtype === 'user') {
  268. $from = $user->getFullName($langs) .' <'.$user->email.'>';
  269. }
  270. elseif ($fromtype === 'company') {
  271. $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  272. }
  273. elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
  274. $tmp=explode(',', $user->email_aliases);
  275. $from = trim($tmp[($reg[1] - 1)]);
  276. }
  277. elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
  278. $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
  279. $from = trim($tmp[($reg[1] - 1)]);
  280. }
  281. elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
  282. $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
  283. $resql = $db->query($sql);
  284. $obj = $db->fetch_object($resql);
  285. if ($obj)
  286. {
  287. $from = $obj->label.' <'.$obj->email.'>';
  288. }
  289. }
  290. else {
  291. $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
  292. }
  293. $replyto = $from;
  294. $subject = GETPOST('subject','none');
  295. $message = GETPOST('message','none');
  296. $sendtobcc = GETPOST('sendtoccc');
  297. if ($objectclass == 'Propale') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
  298. if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
  299. if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
  300. if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
  301. if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
  302. if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
  303. // $listofqualifiedobj is array with key = object id of qualified objects for the current thirdparty
  304. $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
  305. $looparray=array();
  306. if (! $oneemailperrecipient)
  307. {
  308. $looparray = $listofqualifiedobj;
  309. }
  310. else
  311. {
  312. $objectforloop=new $objectclass($db);
  313. $objectforloop->thirdparty = $thirdparty;
  314. $looparray[0]=$objectforloop;
  315. }
  316. //var_dump($looparray);exit;
  317. foreach ($looparray as $objecttmp) // $objecttmp is a real object or an empty if we choose to send one email per thirdparty instead of per record
  318. {
  319. // Make substitution in email content
  320. $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
  321. $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
  322. $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
  323. $substitutionarray['__EMAIL__'] = $thirdparty->email;
  324. $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"/>';
  325. $parameters=array('mode'=>'formemail');
  326. if ( ! empty( $listofobjectthirdparties ) ) {
  327. $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
  328. }
  329. if ( ! empty( $listofobjectref ) ) {
  330. $parameters['listofobjectref'] = $listofobjectref;
  331. }
  332. complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
  333. $subject=make_substitutions($subject, $substitutionarray);
  334. $message=make_substitutions($message, $substitutionarray);
  335. $filepath = $attachedfiles['paths'];
  336. $filename = $attachedfiles['names'];
  337. $mimetype = $attachedfiles['mimes'];
  338. //var_dump($filepath);
  339. // Send mail (substitutionarray must be done just before this)
  340. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  341. $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1);
  342. if ($mailfile->error)
  343. {
  344. $resaction.='<div class="error">'.$mailfile->error.'</div>';
  345. }
  346. else
  347. {
  348. $result=$mailfile->sendfile();
  349. if ($result)
  350. {
  351. $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>'; // Must not contain "
  352. $error=0;
  353. // Insert logs into agenda
  354. foreach($listofqualifiedobj as $objid => $objectobj)
  355. {
  356. /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
  357. if ($objectclass == 'Commande') $actiontypecode='AC_COM';
  358. if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
  359. if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
  360. if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
  361. if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
  362. $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
  363. if ($message)
  364. {
  365. if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
  366. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
  367. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
  368. $actionmsg = dol_concatdesc($actionmsg, $message);
  369. }
  370. $actionmsg2='';
  371. // Initialisation donnees
  372. $objectobj->sendtoid = 0;
  373. $objectobj->actionmsg = $actionmsg; // Long text
  374. $objectobj->actionmsg2 = $actionmsg2; // Short text
  375. $objectobj->fk_element = $objid;
  376. $objectobj->elementtype = $objectobj->element;
  377. $triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
  378. if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYEMAIL';
  379. if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYEMAIL';
  380. if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYEMAIL';
  381. if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYEMAIL';
  382. if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL';
  383. if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
  384. if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
  385. if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
  386. if (! empty($trigger_name))
  387. {
  388. // Appel des triggers
  389. include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
  390. $interface=new Interfaces($db);
  391. $result=$interface->run_triggers($trigger_name, $objectobj, $user, $langs, $conf);
  392. if ($result < 0) { $error++; $errors=$interface->errors; }
  393. // Fin appel triggers
  394. if ($error)
  395. {
  396. setEventMessages($db->lasterror(), $errors, 'errors');
  397. dol_syslog("Error in trigger ".$trigger_name.' '.$db->lasterror(), LOG_ERR);
  398. }
  399. }
  400. $nbsent++;
  401. }
  402. }
  403. else
  404. {
  405. $langs->load("other");
  406. if ($mailfile->error)
  407. {
  408. $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
  409. $resaction.='<br><div class="error">'.$mailfile->error.'</div>';
  410. }
  411. else
  412. {
  413. $resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
  414. }
  415. }
  416. }
  417. }
  418. }
  419. }
  420. $resaction.=($resaction?'<br>':$resaction);
  421. $resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
  422. $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
  423. $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
  424. $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
  425. if ($nbsent)
  426. {
  427. $action=''; // Do not show form post if there was at least one successfull sent
  428. //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
  429. setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
  430. setEventMessages($resaction, null, 'mesgs');
  431. }
  432. else
  433. {
  434. //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
  435. setEventMessages($resaction, null, 'warnings');
  436. }
  437. $action='list';
  438. $massaction='';
  439. }
  440. }
  441. if ($massaction == 'confirm_createbills')
  442. {
  443. $orders = GETPOST('toselect','array');
  444. $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
  445. $validate_invoices = GETPOST('valdate_invoices', 'int');
  446. $TFact = array();
  447. $TFactThird = array();
  448. $nb_bills_created = 0;
  449. $db->begin();
  450. foreach($orders as $id_order)
  451. {
  452. $cmd = new Commande($db);
  453. if ($cmd->fetch($id_order) <= 0) continue;
  454. $objecttmp = new Facture($db);
  455. 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.
  456. else {
  457. $objecttmp->socid = $cmd->socid;
  458. $objecttmp->type = Facture::TYPE_STANDARD;
  459. $objecttmp->cond_reglement_id = $cmd->cond_reglement_id;
  460. $objecttmp->mode_reglement_id = $cmd->mode_reglement_id;
  461. $objecttmp->fk_project = $cmd->fk_project;
  462. $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  463. if (empty($datefacture))
  464. {
  465. $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y"));
  466. }
  467. $objecttmp->date = $datefacture;
  468. $objecttmp->origin = 'commande';
  469. $objecttmp->origin_id = $id_order;
  470. $res = $objecttmp->create($user);
  471. if($res > 0) $nb_bills_created++;
  472. }
  473. if ($objecttmp->id > 0)
  474. {
  475. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  476. $sql.= "fk_source";
  477. $sql.= ", sourcetype";
  478. $sql.= ", fk_target";
  479. $sql.= ", targettype";
  480. $sql.= ") VALUES (";
  481. $sql.= $id_order;
  482. $sql.= ", '".$objecttmp->origin."'";
  483. $sql.= ", ".$objecttmp->id;
  484. $sql.= ", '".$objecttmp->element."'";
  485. $sql.= ")";
  486. if (! $db->query($sql))
  487. {
  488. $error++;
  489. }
  490. if (! $error)
  491. {
  492. $lines = $cmd->lines;
  493. if (empty($lines) && method_exists($cmd, 'fetch_lines'))
  494. {
  495. $cmd->fetch_lines();
  496. $lines = $cmd->lines;
  497. }
  498. $fk_parent_line=0;
  499. $num=count($lines);
  500. for ($i=0;$i<$num;$i++)
  501. {
  502. $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
  503. if ($lines[$i]->subprice < 0)
  504. {
  505. // Negative line, we create a discount line
  506. $discount = new DiscountAbsolute($db);
  507. $discount->fk_soc=$objecttmp->socid;
  508. $discount->amount_ht=abs($lines[$i]->total_ht);
  509. $discount->amount_tva=abs($lines[$i]->total_tva);
  510. $discount->amount_ttc=abs($lines[$i]->total_ttc);
  511. $discount->tva_tx=$lines[$i]->tva_tx;
  512. $discount->fk_user=$user->id;
  513. $discount->description=$desc;
  514. $discountid=$discount->create($user);
  515. if ($discountid > 0)
  516. {
  517. $result=$objecttmp->insert_discount($discountid);
  518. //$result=$discount->link_to_invoice($lineid,$id);
  519. }
  520. else
  521. {
  522. setEventMessages($discount->error, $discount->errors, 'errors');
  523. $error++;
  524. break;
  525. }
  526. }
  527. else
  528. {
  529. // Positive line
  530. $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
  531. // Date start
  532. $date_start=false;
  533. if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
  534. if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
  535. if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
  536. //Date end
  537. $date_end=false;
  538. if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
  539. if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
  540. if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
  541. // Reset fk_parent_line for no child products and special product
  542. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
  543. {
  544. $fk_parent_line = 0;
  545. }
  546. // Extrafields
  547. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
  548. $lines[$i]->fetch_optionals($lines[$i]->rowid);
  549. $array_options = $lines[$i]->array_options;
  550. }
  551. $result = $objecttmp->addline(
  552. $desc,
  553. $lines[$i]->subprice,
  554. $lines[$i]->qty,
  555. $lines[$i]->tva_tx,
  556. $lines[$i]->localtax1_tx,
  557. $lines[$i]->localtax2_tx,
  558. $lines[$i]->fk_product,
  559. $lines[$i]->remise_percent,
  560. $date_start,
  561. $date_end,
  562. 0,
  563. $lines[$i]->info_bits,
  564. $lines[$i]->fk_remise_except,
  565. 'HT',
  566. 0,
  567. $product_type,
  568. $ii,
  569. $lines[$i]->special_code,
  570. $objecttmp->origin,
  571. $lines[$i]->rowid,
  572. $fk_parent_line,
  573. $lines[$i]->fk_fournprice,
  574. $lines[$i]->pa_ht,
  575. $lines[$i]->label,
  576. $array_options
  577. );
  578. if ($result > 0)
  579. {
  580. $lineid=$result;
  581. }
  582. else
  583. {
  584. $lineid=0;
  585. $error++;
  586. break;
  587. }
  588. // Defined the new fk_parent_line
  589. if ($result > 0 && $lines[$i]->product_type == 9)
  590. {
  591. $fk_parent_line = $result;
  592. }
  593. }
  594. }
  595. }
  596. }
  597. //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module.
  598. if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
  599. else $TFact[$objecttmp->id] = $objecttmp;
  600. }
  601. // Build doc with all invoices
  602. $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
  603. $toselect = array();
  604. if (! $error && $validate_invoices)
  605. {
  606. $massaction = $action = 'builddoc';
  607. foreach($TAllFact as &$objecttmp)
  608. {
  609. $result = $objecttmp->validate($user);
  610. if ($result <= 0)
  611. {
  612. $error++;
  613. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  614. break;
  615. }
  616. $id = $objecttmp->id; // For builddoc action
  617. // Builddoc
  618. $donotredirect = 1;
  619. $upload_dir = $conf->facture->dir_output;
  620. $permissioncreate=$user->rights->facture->creer;
  621. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  622. }
  623. $massaction = $action = 'confirm_createbills';
  624. }
  625. if (! $error)
  626. {
  627. $db->commit();
  628. setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
  629. // Make a redirect to avoid to bill twice if we make a refresh or back
  630. $param='';
  631. if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
  632. if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
  633. if ($sall) $param.='&sall='.urlencode($sall);
  634. if ($socid > 0) $param.='&socid='.urlencode($socid);
  635. if ($viewstatut != '') $param.='&viewstatut='.urlencode($viewstatut);
  636. if ($search_orderday) $param.='&search_orderday='.urlencode($search_orderday);
  637. if ($search_ordermonth) $param.='&search_ordermonth='.urlencode($search_ordermonth);
  638. if ($search_orderyear) $param.='&search_orderyear='.urlencode($search_orderyear);
  639. if ($search_deliveryday) $param.='&search_deliveryday='.urlencode($search_deliveryday);
  640. if ($search_deliverymonth) $param.='&search_deliverymonth='.urlencode($search_deliverymonth);
  641. if ($search_deliveryyear) $param.='&search_deliveryyear='.urlencode($search_deliveryyear);
  642. if ($search_ref) $param.='&search_ref='.urlencode($search_ref);
  643. if ($search_company) $param.='&search_company='.urlencode($search_company);
  644. if ($search_ref_customer) $param.='&search_ref_customer='.urlencode($search_ref_customer);
  645. if ($search_user > 0) $param.='&search_user='.urlencode($search_user);
  646. if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale);
  647. if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
  648. if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
  649. if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
  650. if ($search_project_ref >= 0) $param.="&search_project_ref=".urlencode($search_project_ref);
  651. if ($show_files) $param.='&show_files=' .urlencode($show_files);
  652. if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
  653. if ($billed != '') $param.='&billed='.urlencode($billed);
  654. header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
  655. exit;
  656. }
  657. else
  658. {
  659. $db->rollback();
  660. $action='create';
  661. $_GET["origin"]=$_POST["origin"];
  662. $_GET["originid"]=$_POST["originid"];
  663. setEventMessages("Error", null, 'errors');
  664. $error++;
  665. }
  666. }
  667. if (!$error && $massaction == 'cancelorders')
  668. {
  669. $db->begin();
  670. $nbok = 0;
  671. $orders = GETPOST('toselect', 'array');
  672. foreach ($orders as $id_order)
  673. {
  674. $cmd = new Commande($db);
  675. if ($cmd->fetch($id_order) <= 0)
  676. continue;
  677. if ($cmd->statut != Commande::STATUS_VALIDATED)
  678. {
  679. $langs->load('errors');
  680. setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
  681. $error++;
  682. break;
  683. }
  684. else
  685. $result = $cmd->cancel();
  686. if ($result < 0)
  687. {
  688. setEventMessages($cmd->error, $cmd->errors, 'errors');
  689. $error++;
  690. break;
  691. }
  692. else
  693. $nbok++;
  694. }
  695. if (!$error)
  696. {
  697. if ($nbok > 1)
  698. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  699. else
  700. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  701. $db->commit();
  702. }
  703. else
  704. {
  705. $db->rollback();
  706. }
  707. }
  708. if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search'))
  709. {
  710. if (empty($diroutputmassaction))
  711. {
  712. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
  713. exit;
  714. }
  715. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  716. require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
  717. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  718. $objecttmp=new $objectclass($db);
  719. $listofobjectid=array();
  720. $listofobjectthirdparties=array();
  721. $listofobjectref=array();
  722. foreach($toselect as $toselectid)
  723. {
  724. $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
  725. $result=$objecttmp->fetch($toselectid);
  726. if ($result > 0)
  727. {
  728. $listofobjectid[$toselectid]=$toselectid;
  729. $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
  730. $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
  731. $listofobjectref[$toselectid]=$objecttmp->ref;
  732. }
  733. }
  734. $arrayofinclusion=array();
  735. foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf).'.pdf','/').'$';
  736. $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
  737. // build list of files with full path
  738. $files = array();
  739. foreach($listofobjectref as $basename)
  740. {
  741. $basename = dol_sanitizeFileName($basename);
  742. foreach($listoffiles as $filefound)
  743. {
  744. if (strstr($filefound["name"],$basename))
  745. {
  746. $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
  747. break;
  748. }
  749. }
  750. }
  751. // Define output language (Here it is not used because we do only merging existing PDF)
  752. $outputlangs = $langs;
  753. $newlang='';
  754. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
  755. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
  756. if (! empty($newlang))
  757. {
  758. $outputlangs = new Translate("",$conf);
  759. $outputlangs->setDefaultLang($newlang);
  760. }
  761. if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT))
  762. {
  763. // Create output dir if not exists
  764. dol_mkdir($diroutputmassaction);
  765. // Defined name of merged file
  766. $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  767. $filename=preg_replace('/\s/','_',$filename);
  768. // Save merged file
  769. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
  770. {
  771. if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  772. else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  773. }
  774. if ($year) $filename.='_'.$year;
  775. if ($month) $filename.='_'.$month;
  776. if (count($files)>0)
  777. {
  778. $now=dol_now();
  779. $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
  780. $input_files = '';
  781. foreach($files as $f) {
  782. $input_files.=' '.escapeshellarg($f);
  783. }
  784. $cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
  785. exec($cmd);
  786. if (! empty($conf->global->MAIN_UMASK))
  787. @chmod($file, octdec($conf->global->MAIN_UMASK));
  788. $langs->load("exports");
  789. setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
  790. }
  791. else
  792. {
  793. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  794. }
  795. }
  796. else {
  797. // Create empty PDF
  798. $formatarray=pdf_getFormat();
  799. $page_largeur = $formatarray['width'];
  800. $page_hauteur = $formatarray['height'];
  801. $format = array($page_largeur,$page_hauteur);
  802. $pdf=pdf_getInstance($format);
  803. if (class_exists('TCPDF'))
  804. {
  805. $pdf->setPrintHeader(false);
  806. $pdf->setPrintFooter(false);
  807. }
  808. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  809. if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
  810. // Add all others
  811. foreach($files as $file)
  812. {
  813. // Charge un document PDF depuis un fichier.
  814. $pagecount = $pdf->setSourceFile($file);
  815. for ($i = 1; $i <= $pagecount; $i++)
  816. {
  817. $tplidx = $pdf->importPage($i);
  818. $s = $pdf->getTemplatesize($tplidx);
  819. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  820. $pdf->useTemplate($tplidx);
  821. }
  822. }
  823. // Create output dir if not exists
  824. dol_mkdir($diroutputmassaction);
  825. // Defined name of merged file
  826. $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  827. $filename=preg_replace('/\s/','_',$filename);
  828. // Save merged file
  829. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
  830. {
  831. if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  832. else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  833. }
  834. if ($year) $filename.='_'.$year;
  835. if ($month) $filename.='_'.$month;
  836. if ($pagecount)
  837. {
  838. $now=dol_now();
  839. $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
  840. $pdf->Output($file,'F');
  841. if (! empty($conf->global->MAIN_UMASK))
  842. @chmod($file, octdec($conf->global->MAIN_UMASK));
  843. $langs->load("exports");
  844. setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
  845. }
  846. else
  847. {
  848. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  849. }
  850. }
  851. }
  852. // Remove a file from massaction area
  853. if ($action == 'remove_file')
  854. {
  855. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  856. $langs->load("other");
  857. $upload_dir = $diroutputmassaction;
  858. $file = $upload_dir . '/' . GETPOST('file');
  859. $ret=dol_delete_file($file);
  860. if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
  861. else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
  862. $action='';
  863. }
  864. // Validate records
  865. if (! $error && $massaction == 'validate' && $permtocreate)
  866. {
  867. $objecttmp=new $objectclass($db);
  868. if ($objecttmp->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
  869. {
  870. $langs->load("errors");
  871. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  872. $error++;
  873. }
  874. if ($objecttmp->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
  875. {
  876. $langs->load("errors");
  877. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  878. $error++;
  879. }
  880. if (! $error)
  881. {
  882. $db->begin();
  883. $nbok = 0;
  884. foreach($toselect as $toselectid)
  885. {
  886. $result=$objecttmp->fetch($toselectid);
  887. if ($result > 0)
  888. {
  889. //if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
  890. //else
  891. $result = $objecttmp->validate($user);
  892. if ($result == 0)
  893. {
  894. $langs->load("errors");
  895. setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
  896. $error++;
  897. break;
  898. }
  899. elseif ($result < 0)
  900. {
  901. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  902. $error++;
  903. break;
  904. }
  905. else $nbok++;
  906. }
  907. else
  908. {
  909. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  910. $error++;
  911. break;
  912. }
  913. }
  914. if (! $error)
  915. {
  916. if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  917. else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  918. $db->commit();
  919. }
  920. else
  921. {
  922. $db->rollback();
  923. }
  924. //var_dump($listofobjectthirdparties);exit;
  925. }
  926. }
  927. // Closed records
  928. if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permtoclose) {
  929. $db->begin();
  930. $objecttmp = new $objectclass($db);
  931. $nbok = 0;
  932. foreach ($toselect as $toselectid) {
  933. $result = $objecttmp->fetch($toselectid);
  934. if ($result > 0) {
  935. $result = $objecttmp->cloture($user, 3);
  936. if ($result <= 0) {
  937. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  938. $error++;
  939. break;
  940. } else
  941. $nbok++;
  942. }
  943. else {
  944. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  945. $error++;
  946. break;
  947. }
  948. }
  949. if (!$error) {
  950. if ($nbok > 1)
  951. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  952. else
  953. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  954. $db->commit();
  955. }
  956. else {
  957. $db->rollback();
  958. }
  959. }
  960. // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
  961. if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete)
  962. {
  963. $db->begin();
  964. $objecttmp=new $objectclass($db);
  965. $nbok = 0;
  966. foreach($toselect as $toselectid)
  967. {
  968. $result=$objecttmp->fetch($toselectid);
  969. if ($result > 0)
  970. {
  971. // Refuse deletion for some objects/status
  972. if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT)
  973. {
  974. $langs->load("errors");
  975. $nbignored++;
  976. $resaction.='<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'</div><br>';
  977. continue;
  978. }
  979. if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
  980. else $result = $objecttmp->delete($user);
  981. if ($result <= 0)
  982. {
  983. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  984. $error++;
  985. break;
  986. }
  987. else $nbok++;
  988. }
  989. else
  990. {
  991. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  992. $error++;
  993. break;
  994. }
  995. }
  996. if (! $error)
  997. {
  998. if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
  999. else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
  1000. $db->commit();
  1001. }
  1002. else
  1003. {
  1004. $db->rollback();
  1005. }
  1006. //var_dump($listofobjectthirdparties);exit;
  1007. }
  1008. $parameters['toselect']=$toselect;
  1009. $parameters['uploaddir']=$uploaddir;
  1010. $reshook=$hookmanager->executeHooks('doMassActions',$parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1011. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');