actions_massactions.inc.php 54 KB

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