actions_massactions.inc.php 55 KB

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