actions_massactions.inc.php 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  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 (isModEnabled('project') && 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) {
  505. $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 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 ($triggername == 'PROJET_SENTBYMAIL') {
  561. $triggername = 'PROJECT_SENTBYMAIL';
  562. }
  563. if (!empty($triggername)) {
  564. // Call trigger
  565. $result = $objectobj2->call_trigger($triggername, $user);
  566. if ($result < 0) {
  567. $error++;
  568. }
  569. // End call triggers
  570. if ($error) {
  571. setEventMessages($db->lasterror(), $errors, 'errors');
  572. dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
  573. }
  574. }
  575. $nbsent++; // Nb of object sent
  576. }
  577. } else {
  578. $langs->load("other");
  579. if ($mailfile->error) {
  580. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
  581. $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
  582. } elseif (!empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
  583. $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
  584. } else {
  585. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto) . '<br><div class="error">(unhandled error)</div>';
  586. }
  587. }
  588. }
  589. }
  590. }
  591. }
  592. $resaction .= ($resaction ? '<br>' : $resaction);
  593. $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
  594. $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
  595. $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
  596. $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
  597. if ($nbsent) {
  598. $action = ''; // Do not show form post if there was at least one successfull sent
  599. //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
  600. setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
  601. setEventMessages($resaction, null, 'mesgs');
  602. } else {
  603. //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
  604. setEventMessages($resaction, null, 'warnings');
  605. }
  606. $action = 'list';
  607. $massaction = '';
  608. }
  609. }
  610. if (!$error && $massaction == 'cancelorders') {
  611. $db->begin();
  612. $nbok = 0;
  613. $orders = GETPOST('toselect', 'array');
  614. foreach ($orders as $id_order) {
  615. $cmd = new Commande($db);
  616. if ($cmd->fetch($id_order) <= 0) {
  617. continue;
  618. }
  619. if ($cmd->statut != Commande::STATUS_VALIDATED) {
  620. $langs->load('errors');
  621. setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
  622. $error++;
  623. break;
  624. } else {
  625. // TODO We do not provide warehouse so no stock change here for the moment.
  626. $result = $cmd->cancel();
  627. }
  628. if ($result < 0) {
  629. setEventMessages($cmd->error, $cmd->errors, 'errors');
  630. $error++;
  631. break;
  632. } else {
  633. $nbok++;
  634. }
  635. }
  636. if (!$error) {
  637. if ($nbok > 1) {
  638. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  639. } else {
  640. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  641. }
  642. $db->commit();
  643. } else {
  644. $db->rollback();
  645. }
  646. }
  647. if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
  648. if (empty($diroutputmassaction)) {
  649. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
  650. exit;
  651. }
  652. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  653. require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
  654. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  655. $objecttmp = new $objectclass($db);
  656. $listofobjectid = array();
  657. $listofobjectthirdparties = array();
  658. $listofobjectref = array();
  659. foreach ($toselect as $toselectid) {
  660. $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
  661. $result = $objecttmp->fetch($toselectid);
  662. if ($result > 0) {
  663. $listofobjectid[$toselectid] = $toselectid;
  664. $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
  665. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  666. $listofobjectref[$toselectid] = $objecttmp->ref;
  667. }
  668. }
  669. $arrayofinclusion = array();
  670. foreach ($listofobjectref as $tmppdf) {
  671. $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
  672. }
  673. foreach ($listofobjectref as $tmppdf) {
  674. $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files
  675. }
  676. $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
  677. // build list of files with full path
  678. $files = array();
  679. foreach ($listofobjectref as $basename) {
  680. $basename = dol_sanitizeFileName($basename);
  681. foreach ($listoffiles as $filefound) {
  682. if (strstr($filefound["name"], $basename)) {
  683. $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
  684. break;
  685. }
  686. }
  687. }
  688. // Define output language (Here it is not used because we do only merging existing PDF)
  689. $outputlangs = $langs;
  690. $newlang = '';
  691. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  692. $newlang = GETPOST('lang_id', 'aZ09');
  693. }
  694. //elseif (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
  695. // $newlang = $objecttmp->thirdparty->default_lang;
  696. //}
  697. if (!empty($newlang)) {
  698. $outputlangs = new Translate("", $conf);
  699. $outputlangs->setDefaultLang($newlang);
  700. }
  701. if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) {
  702. // Create output dir if not exists
  703. dol_mkdir($diroutputmassaction);
  704. // Defined name of merged file
  705. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  706. $filename = preg_replace('/\s/', '_', $filename);
  707. // Save merged file
  708. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  709. if ($option == 'late') {
  710. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  711. } else {
  712. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  713. }
  714. }
  715. if ($year) {
  716. $filename .= '_'.$year;
  717. }
  718. if ($month) {
  719. $filename .= '_'.$month;
  720. }
  721. if (count($files) > 0) {
  722. $now = dol_now();
  723. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  724. $input_files = '';
  725. foreach ($files as $f) {
  726. $input_files .= ' '.escapeshellarg($f);
  727. }
  728. $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
  729. exec($cmd);
  730. // check if pdftk is installed
  731. if (file_exists($file)) {
  732. if (!empty($conf->global->MAIN_UMASK)) {
  733. @chmod($file, octdec($conf->global->MAIN_UMASK));
  734. }
  735. $langs->load("exports");
  736. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  737. } else {
  738. setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
  739. }
  740. } else {
  741. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  742. }
  743. } else {
  744. // Create empty PDF
  745. $formatarray = pdf_getFormat();
  746. $page_largeur = $formatarray['width'];
  747. $page_hauteur = $formatarray['height'];
  748. $format = array($page_largeur, $page_hauteur);
  749. $pdf = pdf_getInstance($format);
  750. if (class_exists('TCPDF')) {
  751. $pdf->setPrintHeader(false);
  752. $pdf->setPrintFooter(false);
  753. }
  754. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  755. if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
  756. $pdf->SetCompression(false);
  757. }
  758. // Add all others
  759. foreach ($files as $file) {
  760. // Charge un document PDF depuis un fichier.
  761. $pagecount = $pdf->setSourceFile($file);
  762. for ($i = 1; $i <= $pagecount; $i++) {
  763. $tplidx = $pdf->importPage($i);
  764. $s = $pdf->getTemplatesize($tplidx);
  765. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  766. $pdf->useTemplate($tplidx);
  767. }
  768. }
  769. // Create output dir if not exists
  770. dol_mkdir($diroutputmassaction);
  771. // Defined name of merged file
  772. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  773. $filename = preg_replace('/\s/', '_', $filename);
  774. // Save merged file
  775. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  776. if ($option == 'late') {
  777. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  778. } else {
  779. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  780. }
  781. }
  782. if ($year) {
  783. $filename .= '_'.$year;
  784. }
  785. if ($month) {
  786. $filename .= '_'.$month;
  787. }
  788. if ($pagecount) {
  789. $now = dol_now();
  790. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  791. $pdf->Output($file, 'F');
  792. if (!empty($conf->global->MAIN_UMASK)) {
  793. @chmod($file, octdec($conf->global->MAIN_UMASK));
  794. }
  795. $langs->load("exports");
  796. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  797. } else {
  798. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  799. }
  800. }
  801. }
  802. // Remove a file from massaction area
  803. if ($action == 'remove_file') {
  804. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  805. $langs->load("other");
  806. $upload_dir = $diroutputmassaction;
  807. $file = $upload_dir.'/'.GETPOST('file');
  808. $ret = dol_delete_file($file);
  809. if ($ret) {
  810. setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
  811. } else {
  812. setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
  813. }
  814. $action = '';
  815. }
  816. // Validate records
  817. if (!$error && $massaction == 'validate' && $permissiontoadd) {
  818. $objecttmp = new $objectclass($db);
  819. if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  820. $langs->load("errors");
  821. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  822. $error++;
  823. }
  824. if ($objecttmp->element == 'invoice_supplier' && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  825. $langs->load("errors");
  826. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  827. $error++;
  828. }
  829. if ($objecttmp->element == 'facture') {
  830. if (!empty($toselect) && !empty($conf->global->INVOICE_CHECK_POSTERIOR_DATE)) {
  831. // order $toselect by date
  832. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture";
  833. $sql .= " WHERE rowid IN (".$db->sanitize(implode(",", $toselect)).")";
  834. $sql .= " ORDER BY datef";
  835. $resql = $db->query($sql);
  836. if ($resql) {
  837. $toselectnew = [];
  838. while ( !empty($arr = $db->fetch_row($resql))) {
  839. $toselectnew[] = $arr[0];
  840. }
  841. $toselect = (empty($toselectnew)) ? $toselect : $toselectnew;
  842. } else {
  843. dol_print_error($db);
  844. $error++;
  845. }
  846. }
  847. }
  848. if (!$error) {
  849. $db->begin();
  850. $nbok = 0;
  851. foreach ($toselect as $toselectid) {
  852. $result = $objecttmp->fetch($toselectid);
  853. if ($result > 0) {
  854. $result = $objecttmp->validate($user);
  855. if ($result == 0) {
  856. $langs->load("errors");
  857. setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
  858. $error++;
  859. break;
  860. } elseif ($result < 0) {
  861. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  862. $error++;
  863. break;
  864. } else {
  865. // validate() rename pdf but do not regenerate
  866. // Define output language
  867. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  868. $outputlangs = $langs;
  869. $newlang = '';
  870. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  871. $newlang = GETPOST('lang_id', 'aZ09');
  872. }
  873. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  874. $newlang = $objecttmp->thirdparty->default_lang;
  875. }
  876. if (!empty($newlang)) {
  877. $outputlangs = new Translate("", $conf);
  878. $outputlangs->setDefaultLang($newlang);
  879. $outputlangs->load('products');
  880. }
  881. $model = $objecttmp->model_pdf;
  882. $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
  883. // To be sure vars is defined
  884. $hidedetails = !empty($hidedetails) ? $hidedetails : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  885. $hidedesc = !empty($hidedesc) ? $hidedesc : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  886. $hideref = !empty($hideref) ? $hideref : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  887. $moreparams = !empty($moreparams) ? $moreparams : null;
  888. $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  889. if ($result < 0) {
  890. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  891. }
  892. }
  893. $nbok++;
  894. }
  895. } else {
  896. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  897. $error++;
  898. break;
  899. }
  900. }
  901. if (!$error) {
  902. if ($nbok > 1) {
  903. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  904. } else {
  905. setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
  906. }
  907. $db->commit();
  908. } else {
  909. $db->rollback();
  910. }
  911. //var_dump($listofobjectthirdparties);exit;
  912. }
  913. }
  914. //var_dump($_POST);var_dump($massaction);exit;
  915. // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
  916. if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
  917. $db->begin();
  918. $objecttmp = new $objectclass($db);
  919. $nbok = 0;
  920. $TMsg = array();
  921. foreach ($toselect as $toselectid) {
  922. $result = $objecttmp->fetch($toselectid);
  923. if ($result > 0) {
  924. // Refuse deletion for some objects/status
  925. if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) {
  926. $langs->load("errors");
  927. $nbignored++;
  928. $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
  929. continue;
  930. }
  931. if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
  932. $langs->load("errors");
  933. $nbignored++;
  934. $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
  935. continue;
  936. }
  937. if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
  938. $nbignored++;
  939. $resaction .= '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
  940. continue;
  941. }
  942. if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
  943. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
  944. $res = $db->query($sql);
  945. if (!$res) {
  946. setEventMessage('ErrorRecordParentingNotModified', 'errors');
  947. $error++;
  948. }
  949. }
  950. if (in_array($objecttmp->element, array('societe', 'member'))) {
  951. $result = $objecttmp->delete($objecttmp->id, $user, 1);
  952. } elseif (in_array($objecttmp->element, array('action'))) {
  953. $result = $objecttmp->delete();
  954. } else {
  955. $result = $objecttmp->delete($user);
  956. }
  957. if (empty($result)) { // if delete returns 0, there is at least one object linked
  958. $TMsg = array_merge($objecttmp->errors, $TMsg);
  959. } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
  960. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  961. $error++;
  962. break;
  963. } else {
  964. $nbok++;
  965. }
  966. } else {
  967. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  968. $error++;
  969. break;
  970. }
  971. }
  972. if (empty($error)) {
  973. // Message for elements well deleted
  974. if ($nbok > 1) {
  975. setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
  976. } elseif ($nbok > 0) {
  977. setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
  978. } else {
  979. setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
  980. }
  981. // Message for elements which can't be deleted
  982. if (!empty($TMsg)) {
  983. sort($TMsg);
  984. setEventMessages('', array_unique($TMsg), 'warnings');
  985. }
  986. $db->commit();
  987. } else {
  988. $db->rollback();
  989. }
  990. //var_dump($listofobjectthirdparties);exit;
  991. }
  992. // Generate document foreach object according to model linked to object
  993. // @todo : propose model selection
  994. if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
  995. $db->begin();
  996. $objecttmp = new $objectclass($db);
  997. $nbok = 0;
  998. foreach ($toselect as $toselectid) {
  999. $result = $objecttmp->fetch($toselectid);
  1000. if ($result > 0) {
  1001. $outputlangs = $langs;
  1002. $newlang = '';
  1003. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1004. $newlang = GETPOST('lang_id', 'aZ09');
  1005. }
  1006. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
  1007. $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
  1008. }
  1009. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->default_lang)) {
  1010. $newlang = $objecttmp->default_lang; // for thirdparty
  1011. }
  1012. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && empty($objecttmp->thirdparty)) { //load lang from thirdparty
  1013. $objecttmp->fetch_thirdparty();
  1014. $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
  1015. }
  1016. if (!empty($newlang)) {
  1017. $outputlangs = new Translate("", $conf);
  1018. $outputlangs->setDefaultLang($newlang);
  1019. }
  1020. // To be sure vars is defined
  1021. if (empty($hidedetails)) {
  1022. $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  1023. }
  1024. if (empty($hidedesc)) {
  1025. $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  1026. }
  1027. if (empty($hideref)) {
  1028. $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  1029. }
  1030. if (empty($moreparams)) {
  1031. $moreparams = null;
  1032. }
  1033. $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1034. if ($result <= 0) {
  1035. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1036. $error++;
  1037. break;
  1038. } else {
  1039. $nbok++;
  1040. }
  1041. } else {
  1042. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1043. $error++;
  1044. break;
  1045. }
  1046. }
  1047. if (!$error) {
  1048. if ($nbok > 1) {
  1049. setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
  1050. } else {
  1051. setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
  1052. }
  1053. $db->commit();
  1054. } else {
  1055. $db->rollback();
  1056. }
  1057. }
  1058. if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
  1059. $db->begin();
  1060. $affecttag_type=GETPOST('affecttag_type', 'alpha');
  1061. if (!empty($affecttag_type)) {
  1062. $affecttag_type_array=explode(',', $affecttag_type);
  1063. } else {
  1064. setEventMessage('CategTypeNotFound', 'errors');
  1065. }
  1066. if (!empty($affecttag_type_array)) {
  1067. //check if tag type submited exists into Tag Map categorie class
  1068. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1069. $categ = new Categorie($db);
  1070. $to_affecttag_type_array=array();
  1071. $categ_type_array=$categ->getMapList();
  1072. foreach ($categ_type_array as $categdef) {
  1073. if (in_array($categdef['code'], $affecttag_type_array)) {
  1074. $to_affecttag_type_array[] = $categdef['code'];
  1075. }
  1076. }
  1077. //For each valid categ type set common categ
  1078. $nbok = 0;
  1079. if (!empty($to_affecttag_type_array)) {
  1080. foreach ($to_affecttag_type_array as $categ_type) {
  1081. $contcats = GETPOST('contcats_' . $categ_type, 'array');
  1082. //var_dump($toselect);exit;
  1083. foreach ($toselect as $toselectid) {
  1084. $result = $object->fetch($toselectid);
  1085. //var_dump($contcats);exit;
  1086. if ($result > 0) {
  1087. $result = $object->setCategoriesCommon($contcats, $categ_type, false);
  1088. if ($result > 0) {
  1089. $nbok++;
  1090. } else {
  1091. setEventMessages($object->error, $object->errors, 'errors');
  1092. }
  1093. } else {
  1094. setEventMessages($object->error, $object->errors, 'errors');
  1095. $error++;
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. }
  1101. }
  1102. if (!$error) {
  1103. if ($nbok > 1) {
  1104. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1105. } else {
  1106. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1107. }
  1108. $db->commit();
  1109. $toselect=array();
  1110. } else {
  1111. $db->rollback();
  1112. }
  1113. }
  1114. if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
  1115. $db->begin();
  1116. $objecttmp = new $objectclass($db);
  1117. $nbok = 0;
  1118. foreach ($toselect as $toselectid) {
  1119. $result = $objecttmp->fetch($toselectid);
  1120. if ($result>0) {
  1121. if (in_array($objecttmp->element, array('societe'))) {
  1122. $result =$objecttmp->setStatut(1);
  1123. }
  1124. if ($result <= 0) {
  1125. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1126. $error++;
  1127. break;
  1128. } else {
  1129. $nbok++;
  1130. }
  1131. } else {
  1132. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1133. $error++;
  1134. break;
  1135. }
  1136. }
  1137. if (!$error) {
  1138. if ($nbok > 1) {
  1139. setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
  1140. } else {
  1141. setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
  1142. }
  1143. $db->commit();
  1144. } else {
  1145. $db->rollback();
  1146. }
  1147. }
  1148. if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
  1149. $db->begin();
  1150. $objecttmp = new $objectclass($db);
  1151. $nbok = 0;
  1152. foreach ($toselect as $toselectid) {
  1153. $result = $objecttmp->fetch($toselectid);
  1154. if ($result>0) {
  1155. if (in_array($objecttmp->element, array('societe'))) {
  1156. $result =$objecttmp->setStatut(0);
  1157. }
  1158. if ($result <= 0) {
  1159. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1160. $error++;
  1161. break;
  1162. } else {
  1163. $nbok++;
  1164. }
  1165. } else {
  1166. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1167. $error++;
  1168. break;
  1169. }
  1170. }
  1171. if (!$error) {
  1172. if ($nbok > 1) {
  1173. setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
  1174. } else {
  1175. setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
  1176. }
  1177. $db->commit();
  1178. } else {
  1179. $db->rollback();
  1180. }
  1181. }
  1182. if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
  1183. $db->begin();
  1184. $objecttmp = new $objectclass($db);
  1185. $e = new ExtraFields($db);// fetch optionals attributes and labels
  1186. $e->fetch_name_optionals_label($objecttmp->table_element);
  1187. $nbok = 0;
  1188. $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
  1189. foreach ($toselect as $toselectid) {
  1190. /** @var CommonObject $objecttmp */
  1191. $objecttmp = new $objectclass($db); // to avoid ghost data
  1192. $result = $objecttmp->fetch($toselectid);
  1193. if ($result>0) {
  1194. // Fill array 'array_options' with data from add form
  1195. $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
  1196. if ($ret > 0) {
  1197. $objecttmp->insertExtraFields();
  1198. } else {
  1199. $error++;
  1200. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1201. }
  1202. } else {
  1203. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1204. $error++;
  1205. break;
  1206. }
  1207. }
  1208. if (!$error) {
  1209. if ($nbok > 1) {
  1210. setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
  1211. } else {
  1212. setEventMessages($langs->trans("save"), null, 'mesgs');
  1213. }
  1214. $db->commit();
  1215. } else {
  1216. $db->rollback();
  1217. }
  1218. }
  1219. if (!$error && ($massaction == 'affectcommercial' || ($action == 'affectcommercial' && $confirm == 'yes')) && $permissiontoadd) {
  1220. $db->begin();
  1221. $objecttmp = new $objectclass($db);
  1222. $nbok = 0;
  1223. foreach ($toselect as $toselectid) {
  1224. $result = $objecttmp->fetch($toselectid);
  1225. if ($result>0) {
  1226. if (in_array($objecttmp->element, array('societe'))) {
  1227. $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
  1228. }
  1229. if ($result <= 0) {
  1230. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1231. $error++;
  1232. break;
  1233. } else {
  1234. $nbok++;
  1235. }
  1236. } else {
  1237. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1238. $error++;
  1239. break;
  1240. }
  1241. }
  1242. if (!$error) {
  1243. if ($nbok > 1) {
  1244. setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
  1245. } else {
  1246. setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
  1247. }
  1248. $db->commit();
  1249. } else {
  1250. $db->rollback();
  1251. }
  1252. }
  1253. // Approve for leave only
  1254. if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
  1255. $db->begin();
  1256. $objecttmp = new $objectclass($db);
  1257. $nbok = 0;
  1258. foreach ($toselect as $toselectid) {
  1259. $result = $objecttmp->fetch($toselectid);
  1260. if ($result > 0) {
  1261. if ($objecttmp->statut != Holiday::STATUS_VALIDATED) {
  1262. setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
  1263. continue;
  1264. }
  1265. if ($user->id == $objecttmp->fk_validator) {
  1266. $objecttmp->oldcopy = dol_clone($objecttmp);
  1267. $objecttmp->date_valid = dol_now();
  1268. $objecttmp->fk_user_valid = $user->id;
  1269. $objecttmp->statut = Holiday::STATUS_APPROVED;
  1270. $verif = $objecttmp->approve($user);
  1271. if ($verif <= 0) {
  1272. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1273. $error++;
  1274. }
  1275. // If no SQL error, we redirect to the request form
  1276. if (!$error) {
  1277. // Calculcate number of days consummed
  1278. $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
  1279. $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
  1280. $newSolde = ($soldeActuel - $nbopenedday);
  1281. // The modification is added to the LOG
  1282. $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
  1283. if ($result < 0) {
  1284. $error++;
  1285. setEventMessages(null, $objecttmp->errors, 'errors');
  1286. }
  1287. // Update balance
  1288. $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
  1289. if ($result < 0) {
  1290. $error++;
  1291. setEventMessages(null, $objecttmp->errors, 'errors');
  1292. }
  1293. }
  1294. if (!$error) {
  1295. // To
  1296. $destinataire = new User($db);
  1297. $destinataire->fetch($objecttmp->fk_user);
  1298. $emailTo = $destinataire->email;
  1299. if (!$emailTo) {
  1300. dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
  1301. } else {
  1302. // From
  1303. $expediteur = new User($db);
  1304. $expediteur->fetch($objecttmp->fk_validator);
  1305. //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
  1306. $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;
  1307. // Subject
  1308. $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
  1309. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  1310. $societeName = $conf->global->MAIN_APPLICATION_TITLE;
  1311. }
  1312. $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
  1313. // Content
  1314. $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
  1315. $message .= "\n";
  1316. $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
  1317. $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
  1318. $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
  1319. $message .= "\n";
  1320. $trackid = 'leav'.$objecttmp->id;
  1321. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1322. $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
  1323. // Sending email
  1324. $result = $mail->sendfile();
  1325. if (!$result) {
  1326. setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
  1327. $action = '';
  1328. }
  1329. }
  1330. }
  1331. } else {
  1332. $langs->load("errors");
  1333. setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
  1334. }
  1335. } else {
  1336. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1337. $error++;
  1338. break;
  1339. }
  1340. }
  1341. if (!$error) {
  1342. if ($nbok > 1) {
  1343. setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
  1344. } elseif ($nbok == 1) {
  1345. setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
  1346. }
  1347. $db->commit();
  1348. } else {
  1349. $db->rollback();
  1350. }
  1351. }
  1352. if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove) {
  1353. $db->begin();
  1354. $objecttmp = new $objectclass($db);
  1355. $nbok = 0;
  1356. $typeholiday = GETPOST('typeholiday', 'alpha');
  1357. $nbdaysholidays = GETPOST('nbdaysholidays', 'double');
  1358. if ($nbdaysholidays <= 0) {
  1359. setEventMessages($langs->trans("WrongAmount"), "", 'errors');
  1360. $error++;
  1361. }
  1362. if (!$error) {
  1363. foreach ($toselect as $toselectid) {
  1364. $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
  1365. if (!empty($balancecpuser)) {
  1366. $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
  1367. } else {
  1368. $newnbdaysholidays = $nbdaysholidays;
  1369. }
  1370. $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
  1371. if ($result <= 0) {
  1372. setEventMessages($holiday->error, $holiday->errors, 'errors');
  1373. $error++;
  1374. break;
  1375. }
  1376. $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
  1377. if ($result > 0) {
  1378. $nbok++;
  1379. } else {
  1380. setEventMessages("", $langs->trans("ErrorUpdatingUsersCP"), 'errors');
  1381. $error++;
  1382. break;
  1383. }
  1384. }
  1385. }
  1386. if (!$error) {
  1387. if ($nbok > 1) {
  1388. setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
  1389. } elseif ($nbok == 1) {
  1390. setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
  1391. }
  1392. $db->commit();
  1393. $toselect=array();
  1394. } else {
  1395. $db->rollback();
  1396. }
  1397. }
  1398. $parameters['toselect'] = $toselect;
  1399. $parameters['uploaddir'] = $uploaddir;
  1400. $parameters['massaction'] = $massaction;
  1401. $parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
  1402. $reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1403. if ($reshook < 0) {
  1404. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1405. }