actions_massactions.inc.php 40 KB

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