actions_massactions.inc.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  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->projet->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. $listofobjectid = array();
  68. $listofobjectthirdparties = array();
  69. $listofobjectcontacts = array();
  70. $listofobjectref = array();
  71. $contactidtosend = array();
  72. $attachedfilesThirdpartyObj = array();
  73. $oneemailperrecipient = (GETPOST('oneemailperrecipient') == 'on' ? 1 : 0);
  74. if (!$error) {
  75. $thirdparty = new Societe($db);
  76. $objecttmp = new $objectclass($db);
  77. if ($objecttmp->element == 'expensereport') {
  78. $thirdparty = new User($db);
  79. }
  80. if ($objecttmp->element == 'partnership' && $conf->global->PARTNERSHIP_IS_MANAGED_FOR == 'member') {
  81. $thirdparty = new Adherent($db);
  82. }
  83. if ($objecttmp->element == 'holiday') {
  84. $thirdparty = new User($db);
  85. }
  86. foreach ($toselect as $toselectid) {
  87. $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
  88. $result = $objecttmp->fetch($toselectid);
  89. if ($result > 0) {
  90. $listofobjectid[$toselectid] = $toselectid;
  91. $thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
  92. if ($objecttmp->element == 'societe') {
  93. $thirdpartyid = $objecttmp->id;
  94. }
  95. if ($objecttmp->element == 'expensereport') {
  96. $thirdpartyid = $objecttmp->fk_user_author;
  97. }
  98. if ($objecttmp->element == 'partnership' && $conf->global->PARTNERSHIP_IS_MANAGED_FOR == 'member') {
  99. $thirdpartyid = $objecttmp->fk_member;
  100. }
  101. if ($objecttmp->element == 'holiday') {
  102. $thirdpartyid = $objecttmp->fk_user;
  103. }
  104. if (empty($thirdpartyid)) {
  105. $thirdpartyid = 0;
  106. }
  107. if ($objectclass == 'Facture') {
  108. $tmparraycontact = array();
  109. $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
  110. if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
  111. foreach ($tmparraycontact as $data_email) {
  112. $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
  113. }
  114. }
  115. }
  116. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  117. $listofobjectref[$thirdpartyid][$toselectid] = $objecttmp;
  118. }
  119. }
  120. }
  121. // Check mandatory parameters
  122. if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) {
  123. $error++;
  124. setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
  125. $massaction = 'presend';
  126. }
  127. $receiver = $_POST['receiver'];
  128. if (!is_array($receiver)) {
  129. if (empty($receiver) || $receiver == '-1') {
  130. $receiver = array();
  131. } else {
  132. $receiver = array($receiver);
  133. }
  134. }
  135. if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory
  136. $error++;
  137. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
  138. $massaction = 'presend';
  139. }
  140. if (!GETPOST('subject', 'restricthtml')) {
  141. $error++;
  142. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
  143. $massaction = 'presend';
  144. }
  145. // Loop on each recipient/thirdparty
  146. if (!$error) {
  147. foreach ($listofobjectthirdparties as $thirdpartyid) {
  148. $result = $thirdparty->fetch($thirdpartyid);
  149. if ($result < 0) {
  150. dol_print_error($db);
  151. exit;
  152. }
  153. $sendto = '';
  154. $sendtocc = '';
  155. $sendtobcc = '';
  156. $sendtoid = array();
  157. // Define $sendto
  158. $tmparray = array();
  159. if (trim($_POST['sendto'])) {
  160. // Recipients are provided into free text
  161. $tmparray[] = trim($_POST['sendto']);
  162. }
  163. if (count($receiver) > 0) {
  164. foreach ($receiver as $key => $val) {
  165. // Recipient was provided from combo list
  166. if ($val == 'thirdparty') { // Id of third party or user
  167. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  168. } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact
  169. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  170. $sendtoid[] = $val;
  171. }
  172. }
  173. }
  174. $sendto = implode(',', $tmparray);
  175. // Define $sendtocc
  176. $receivercc = $_POST['receivercc'];
  177. if (!is_array($receivercc)) {
  178. if ($receivercc == '-1') {
  179. $receivercc = array();
  180. } else {
  181. $receivercc = array($receivercc);
  182. }
  183. }
  184. $tmparray = array();
  185. if (trim($_POST['sendtocc'])) {
  186. $tmparray[] = trim($_POST['sendtocc']);
  187. }
  188. if (count($receivercc) > 0) {
  189. foreach ($receivercc as $key => $val) {
  190. // Recipient was provided from combo list
  191. if ($val == 'thirdparty') { // Id of third party
  192. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  193. } elseif ($val) { // Id du contact
  194. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  195. //$sendtoid[] = $val; TODO Add also id of contact in CC ?
  196. }
  197. }
  198. }
  199. $sendtocc = implode(',', $tmparray);
  200. //var_dump($listofobjectref);exit;
  201. $listofqualifiedobj = array();
  202. $listofqualifiedref = array();
  203. $thirdpartywithoutemail = array();
  204. foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) {
  205. //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
  206. if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) {
  207. $langs->load("errors");
  208. $nbignored++;
  209. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  210. continue; // Payment done or started or canceled
  211. }
  212. if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) {
  213. $langs->load("errors");
  214. $nbignored++;
  215. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  216. continue;
  217. }
  218. if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) {
  219. $langs->load("errors");
  220. $nbignored++;
  221. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  222. continue; // Payment done or started or canceled
  223. }
  224. // Test recipient
  225. if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send)
  226. if ($objectobj->element == 'societe') {
  227. $sendto = $objectobj->email;
  228. } elseif ($objectobj->element == 'expensereport') {
  229. $fuser = new User($db);
  230. $fuser->fetch($objectobj->fk_user_author);
  231. $sendto = $fuser->email;
  232. } elseif ($objectobj->element == 'partnership' && $conf->global->PARTNERSHIP_IS_MANAGED_FOR == 'member') {
  233. $fadherent = new Adherent($db);
  234. $fadherent->fetch($objectobj->fk_member);
  235. $sendto = $fadherent->email;
  236. } elseif ($objectobj->element == 'holiday') {
  237. $fuser = new User($db);
  238. $fuser->fetch($objectobj->fk_user);
  239. $sendto = $fuser->email;
  240. } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) {
  241. $emails_to_sends = array();
  242. $objectobj->fetch_thirdparty();
  243. $contactidtosend = array();
  244. foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
  245. $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
  246. if (!in_array($contactemailid, $contactidtosend)) {
  247. $contactidtosend[] = $contactemailid;
  248. }
  249. }
  250. if (count($emails_to_sends) > 0) {
  251. $sendto = implode(',', $emails_to_sends);
  252. }
  253. } else {
  254. $objectobj->fetch_thirdparty();
  255. $sendto = $objectobj->thirdparty->email;
  256. }
  257. }
  258. if (empty($sendto)) {
  259. if ($objectobj->element == 'societe') {
  260. $objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty
  261. }
  262. //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
  263. $nbignored++;
  264. if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) {
  265. $resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
  266. }
  267. dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
  268. $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
  269. continue;
  270. }
  271. if ($_POST['addmaindocfile']) {
  272. // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
  273. // TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc.
  274. $filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
  275. $subdir = '';
  276. // TODO Set subdir to be compatible with multi levels dir trees
  277. // $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
  278. $filedir = $uploaddir.'/'.$subdir.dol_sanitizeFileName($objectobj->ref);
  279. $file = $filedir.'/'.$filename;
  280. // Added By MMI Mathieu Moulin iProspective
  281. // Fix search by filename
  282. if (!file_exists($file)) {
  283. $files = glob($filedir.'/'.dol_sanitizeFileName($objectobj->ref).'*.pdf');
  284. if (!empty($files))
  285. $file = $files[0];
  286. }
  287. // For supplier invoices, we use the file provided by supplier, not the one we generate
  288. if ($objectobj->element == 'invoice_supplier') {
  289. $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+');
  290. $file = $fileparams['fullname'];
  291. }
  292. $mime = dol_mimetype($file);
  293. if (dol_is_file($file)) {
  294. // Create form object
  295. $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
  296. 'paths'=>array($file),
  297. 'names'=>array($filename),
  298. 'mimes'=>array($mime)
  299. );
  300. } else {
  301. $nbignored++;
  302. $langs->load("errors");
  303. $resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file).'</div><br>';
  304. dol_syslog('Failed to read file: '.$file, LOG_WARNING);
  305. continue;
  306. }
  307. }
  308. // Object of thirdparty qualified, we add it
  309. $listofqualifiedobj[$objectid] = $objectobj;
  310. $listofqualifiedref[$objectid] = $objectobj->ref;
  311. //var_dump($listofqualifiedref);
  312. }
  313. // Send email if there is at least one qualified object for current thirdparty
  314. if (count($listofqualifiedobj) > 0) {
  315. $langs->load("commercial");
  316. $reg = array();
  317. $fromtype = GETPOST('fromtype');
  318. if ($fromtype === 'user') {
  319. $from = $user->getFullName($langs).' <'.$user->email.'>';
  320. } elseif ($fromtype === 'company') {
  321. $from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  322. } elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
  323. $tmp = explode(',', $user->email_aliases);
  324. $from = trim($tmp[($reg[1] - 1)]);
  325. } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
  326. $tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
  327. $from = trim($tmp[($reg[1] - 1)]);
  328. } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
  329. $sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
  330. $resql = $db->query($sql);
  331. $obj = $db->fetch_object($resql);
  332. if ($obj) {
  333. $from = $obj->label.' <'.$obj->email.'>';
  334. }
  335. } else {
  336. $from = $_POST['fromname'].' <'.$_POST['frommail'].'>';
  337. }
  338. $replyto = $from;
  339. $subject = GETPOST('subject', 'restricthtml');
  340. $message = GETPOST('message', 'restricthtml');
  341. $sendtobcc = GETPOST('sendtoccc');
  342. if ($objectclass == 'Propal') {
  343. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
  344. }
  345. if ($objectclass == 'Commande') {
  346. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
  347. }
  348. if ($objectclass == 'Facture') {
  349. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
  350. }
  351. if ($objectclass == 'Supplier_Proposal') {
  352. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
  353. }
  354. if ($objectclass == 'CommandeFournisseur') {
  355. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
  356. }
  357. if ($objectclass == 'FactureFournisseur') {
  358. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
  359. }
  360. if ($objectclass == 'Project') {
  361. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO));
  362. }
  363. // $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)
  364. // $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)
  365. $looparray = array();
  366. if (!$oneemailperrecipient) {
  367. $looparray = $listofqualifiedobj;
  368. foreach ($looparray as $key => $objecttmp) {
  369. $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
  370. }
  371. } else {
  372. $objectforloop = new $objectclass($db);
  373. $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
  374. $looparray[0] = $objectforloop;
  375. }
  376. //var_dump($looparray);exit;
  377. dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
  378. //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
  379. 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
  380. // Make substitution in email content
  381. if (!empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) {
  382. $objecttmp->fetch_projet();
  383. }
  384. $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
  385. $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
  386. $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
  387. $substitutionarray['__EMAIL__'] = $thirdparty->email;
  388. $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"/>';
  389. $parameters = array('mode'=>'formemail');
  390. if (!empty($listofobjectthirdparties)) {
  391. $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
  392. }
  393. if (!empty($listofobjectref)) {
  394. $parameters['listofobjectref'] = $listofobjectref;
  395. }
  396. complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
  397. $subjectreplaced = make_substitutions($subject, $substitutionarray);
  398. $messagereplaced = make_substitutions($message, $substitutionarray);
  399. $attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
  400. if ($oneemailperrecipient) {
  401. // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
  402. if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) {
  403. foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
  404. // Create form object
  405. $attachedfiles = array(
  406. 'paths'=>array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
  407. 'names'=>array_merge($attachedfiles['names'], $objAttachedFiles['names']),
  408. 'mimes'=>array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
  409. );
  410. }
  411. }
  412. } elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
  413. // Create form object
  414. // if "one email per recipient" isn't check we must separate $attachedfiles by object
  415. $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
  416. }
  417. $filepath = $attachedfiles['paths'];
  418. $filename = $attachedfiles['names'];
  419. $mimetype = $attachedfiles['mimes'];
  420. // Define the trackid when emails sent from the mass action
  421. if ($oneemailperrecipient) {
  422. $trackid = 'thi'.$thirdparty->id;
  423. if ($objecttmp->element == 'expensereport') {
  424. $trackid = 'use'.$thirdparty->id;
  425. }
  426. if ($objecttmp->element == 'holiday') {
  427. $trackid = 'use'.$thirdparty->id;
  428. }
  429. } else {
  430. $trackid = strtolower(get_class($objecttmp));
  431. if (get_class($objecttmp) == 'Contrat') {
  432. $trackid = 'con';
  433. }
  434. if (get_class($objecttmp) == 'Propal') {
  435. $trackid = 'pro';
  436. }
  437. if (get_class($objecttmp) == 'Commande') {
  438. $trackid = 'ord';
  439. }
  440. if (get_class($objecttmp) == 'Facture') {
  441. $trackid = 'inv';
  442. }
  443. if (get_class($objecttmp) == 'Supplier_Proposal') {
  444. $trackid = 'spr';
  445. }
  446. if (get_class($objecttmp) == 'CommandeFournisseur') {
  447. $trackid = 'sor';
  448. }
  449. if (get_class($objecttmp) == 'FactureFournisseur') {
  450. $trackid = 'sin';
  451. }
  452. $trackid .= $objecttmp->id;
  453. }
  454. //var_dump($filepath);
  455. //var_dump($trackid);exit;
  456. //var_dump($subjectreplaced);
  457. if (empty($sendcontext)) {
  458. $sendcontext = 'standard';
  459. }
  460. // Send mail (substitutionarray must be done just before this)
  461. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  462. $mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext);
  463. if ($mailfile->error) {
  464. $resaction .= '<div class="error">'.$mailfile->error.'</div>';
  465. } else {
  466. $result = $mailfile->sendfile();
  467. if ($result) {
  468. $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'<br>'; // Must not contain "
  469. $error = 0;
  470. // Insert logs into agenda
  471. foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
  472. if ((!$oneemailperrecipient) && $objid2 != $objectid) {
  473. continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
  474. }
  475. dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
  476. /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
  477. if ($objectclass == 'Commande') $actiontypecode='AC_COM';
  478. if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
  479. if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
  480. if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
  481. if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
  482. $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
  483. if ($message) {
  484. if ($sendtocc) {
  485. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
  486. }
  487. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
  488. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
  489. $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
  490. }
  491. $actionmsg2 = '';
  492. // Initialisation donnees
  493. $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
  494. $objectobj2->actionmsg = $actionmsg; // Long text
  495. $objectobj2->actionmsg2 = $actionmsg2; // Short text
  496. $objectobj2->fk_element = $objid2;
  497. $objectobj2->elementtype = $objectobj2->element;
  498. $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
  499. if ($triggername == 'SOCIETE_SENTBYMAIL') {
  500. $triggername = 'COMPANY_SENTBYMAIL';
  501. }
  502. if ($triggername == 'CONTRAT_SENTBYMAIL') {
  503. $triggername = 'CONTRACT_SENTBYMAIL';
  504. }
  505. if ($triggername == 'COMMANDE_SENTBYMAIL') {
  506. $triggername = 'ORDER_SENTBYMAIL';
  507. }
  508. if ($triggername == 'FACTURE_SENTBYMAIL') {
  509. $triggername = 'BILL_SENTBYMAIL';
  510. }
  511. if ($triggername == 'EXPEDITION_SENTBYMAIL') {
  512. $triggername = 'SHIPPING_SENTBYMAIL';
  513. }
  514. if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
  515. $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
  516. }
  517. if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
  518. $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
  519. }
  520. if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
  521. $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
  522. }
  523. if (!empty($triggername)) {
  524. // Call trigger
  525. $result = $objectobj2->call_trigger($triggername, $user);
  526. if ($result < 0) {
  527. $error++;
  528. }
  529. // End call triggers
  530. if ($error) {
  531. setEventMessages($db->lasterror(), $errors, 'errors');
  532. dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
  533. }
  534. }
  535. $nbsent++; // Nb of object sent
  536. }
  537. } else {
  538. $langs->load("other");
  539. if ($mailfile->error) {
  540. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
  541. $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
  542. } elseif (!empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
  543. $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
  544. } else {
  545. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto) . '<br><div class="error">(unhandled error)</div>';
  546. }
  547. }
  548. }
  549. }
  550. }
  551. }
  552. $resaction .= ($resaction ? '<br>' : $resaction);
  553. $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
  554. $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
  555. $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
  556. $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
  557. if ($nbsent) {
  558. $action = ''; // Do not show form post if there was at least one successfull sent
  559. //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
  560. setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
  561. setEventMessages($resaction, null, 'mesgs');
  562. } else {
  563. //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
  564. setEventMessages($resaction, null, 'warnings');
  565. }
  566. $action = 'list';
  567. $massaction = '';
  568. }
  569. }
  570. // TODO Move this action into commande/list.php if called only by this page.
  571. if ($massaction == 'confirm_createbills') { // Create bills from orders.
  572. $orders = GETPOST('toselect', 'array');
  573. $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
  574. $validate_invoices = GETPOST('validate_invoices', 'int');
  575. $errors = array();
  576. $TFact = array();
  577. $TFactThird = array();
  578. $nb_bills_created = 0;
  579. $lastid= 0;
  580. $lastref = '';
  581. $db->begin();
  582. foreach ($orders as $id_order) {
  583. $cmd = new Commande($db);
  584. if ($cmd->fetch($id_order) <= 0) {
  585. continue;
  586. }
  587. $cmd->fetch_thirdparty();
  588. $objecttmp = new Facture($db);
  589. if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) {
  590. // If option "one bill per third" is set, and an invoice for this thirdparty was already created, we re-use it.
  591. $objecttmp = $TFactThird[$cmd->socid];
  592. } else {
  593. // If we want one invoice per order or if there is no first invoice yet for this thirdparty.
  594. $objecttmp->socid = $cmd->socid;
  595. $objecttmp->type = $objecttmp::TYPE_STANDARD;
  596. $objecttmp->cond_reglement_id = !empty($cmd->cond_reglement_id) ? $cmd->cond_reglement_id : $cmd->thirdparty->cond_reglement_id;
  597. $objecttmp->mode_reglement_id = !empty($cmd->mode_reglement_id) ? $cmd->mode_reglement_id : $cmd->thirdparty->mode_reglement_id;
  598. $objecttmp->fk_project = $cmd->fk_project;
  599. $objecttmp->multicurrency_code = $cmd->multicurrency_code;
  600. if (empty($createbills_onebythird)) {
  601. $objecttmp->ref_client = $cmd->ref_client;
  602. }
  603. $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  604. if (empty($datefacture)) {
  605. $datefacture = dol_now();
  606. }
  607. $objecttmp->date = $datefacture;
  608. $objecttmp->origin = 'commande';
  609. $objecttmp->origin_id = $id_order;
  610. $objecttmp->array_options = $cmd->array_options; // Copy extrafields
  611. $res = $objecttmp->create($user);
  612. if ($res > 0) {
  613. $nb_bills_created++;
  614. $lastref = $objecttmp->ref;
  615. $lastid = $objecttmp->id;
  616. $TFactThird[$cmd->socid] = $objecttmp;
  617. } else {
  618. $langs->load("errors");
  619. $errors[] = $cmd->ref.' : '.$langs->trans($objecttmp->error);
  620. $error++;
  621. }
  622. }
  623. if ($objecttmp->id > 0) {
  624. $res = $objecttmp->add_object_linked($objecttmp->origin, $id_order);
  625. if ($res == 0) {
  626. $errors[] = $objecttmp->error;
  627. $error++;
  628. }
  629. if (!$error) {
  630. $lines = $cmd->lines;
  631. if (empty($lines) && method_exists($cmd, 'fetch_lines')) {
  632. $cmd->fetch_lines();
  633. $lines = $cmd->lines;
  634. }
  635. $fk_parent_line = 0;
  636. $num = count($lines);
  637. for ($i = 0; $i < $num; $i++) {
  638. $desc = ($lines[$i]->desc ? $lines[$i]->desc : '');
  639. // If we build one invoice for several orders, we must put the ref of order on the invoice line
  640. if (!empty($createbills_onebythird)) {
  641. $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day'));
  642. }
  643. if ($lines[$i]->subprice < 0) {
  644. // Negative line, we create a discount line
  645. $discount = new DiscountAbsolute($db);
  646. $discount->fk_soc = $objecttmp->socid;
  647. $discount->amount_ht = abs($lines[$i]->total_ht);
  648. $discount->amount_tva = abs($lines[$i]->total_tva);
  649. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  650. $discount->tva_tx = $lines[$i]->tva_tx;
  651. $discount->fk_user = $user->id;
  652. $discount->description = $desc;
  653. $discountid = $discount->create($user);
  654. if ($discountid > 0) {
  655. $result = $objecttmp->insert_discount($discountid);
  656. //$result=$discount->link_to_invoice($lineid,$id);
  657. } else {
  658. setEventMessages($discount->error, $discount->errors, 'errors');
  659. $error++;
  660. break;
  661. }
  662. } else {
  663. // Positive line
  664. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  665. // Date start
  666. $date_start = false;
  667. if ($lines[$i]->date_debut_prevue) {
  668. $date_start = $lines[$i]->date_debut_prevue;
  669. }
  670. if ($lines[$i]->date_debut_reel) {
  671. $date_start = $lines[$i]->date_debut_reel;
  672. }
  673. if ($lines[$i]->date_start) {
  674. $date_start = $lines[$i]->date_start;
  675. }
  676. //Date end
  677. $date_end = false;
  678. if ($lines[$i]->date_fin_prevue) {
  679. $date_end = $lines[$i]->date_fin_prevue;
  680. }
  681. if ($lines[$i]->date_fin_reel) {
  682. $date_end = $lines[$i]->date_fin_reel;
  683. }
  684. if ($lines[$i]->date_end) {
  685. $date_end = $lines[$i]->date_end;
  686. }
  687. // Reset fk_parent_line for no child products and special product
  688. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  689. $fk_parent_line = 0;
  690. }
  691. // Extrafields
  692. if (method_exists($lines[$i], 'fetch_optionals')) {
  693. $lines[$i]->fetch_optionals();
  694. $array_options = $lines[$i]->array_options;
  695. }
  696. $objecttmp->context['createfromclone'];
  697. $result = $objecttmp->addline(
  698. $desc,
  699. $lines[$i]->subprice,
  700. $lines[$i]->qty,
  701. $lines[$i]->tva_tx,
  702. $lines[$i]->localtax1_tx,
  703. $lines[$i]->localtax2_tx,
  704. $lines[$i]->fk_product,
  705. $lines[$i]->remise_percent,
  706. $date_start,
  707. $date_end,
  708. 0,
  709. $lines[$i]->info_bits,
  710. $lines[$i]->fk_remise_except,
  711. 'HT',
  712. 0,
  713. $product_type,
  714. $lines[$i]->rang,
  715. $lines[$i]->special_code,
  716. $objecttmp->origin,
  717. $lines[$i]->rowid,
  718. $fk_parent_line,
  719. $lines[$i]->fk_fournprice,
  720. $lines[$i]->pa_ht,
  721. $lines[$i]->label,
  722. $array_options,
  723. 100,
  724. 0,
  725. $lines[$i]->fk_unit
  726. );
  727. if ($result > 0) {
  728. $lineid = $result;
  729. } else {
  730. $lineid = 0;
  731. $error++;
  732. break;
  733. }
  734. // Defined the new fk_parent_line
  735. if ($result > 0 && $lines[$i]->product_type == 9) {
  736. $fk_parent_line = $result;
  737. }
  738. }
  739. }
  740. }
  741. }
  742. //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module.
  743. if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) {
  744. $TFactThird[$cmd->socid] = $objecttmp;
  745. } else {
  746. $TFact[$objecttmp->id] = $objecttmp;
  747. }
  748. }
  749. // Build doc with all invoices
  750. $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
  751. $toselect = array();
  752. if (!$error && $validate_invoices) {
  753. $massaction = $action = 'builddoc';
  754. foreach ($TAllFact as &$objecttmp) {
  755. $result = $objecttmp->validate($user);
  756. if ($result <= 0) {
  757. $error++;
  758. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  759. break;
  760. }
  761. $id = $objecttmp->id; // For builddoc action
  762. // Builddoc
  763. $donotredirect = 1;
  764. $upload_dir = $conf->facture->dir_output;
  765. $permissiontoadd = $user->rights->facture->creer;
  766. // Call action to build doc
  767. $savobject = $object;
  768. $object = $objecttmp;
  769. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  770. $object = $savobject;
  771. }
  772. $massaction = $action = 'confirm_createbills';
  773. }
  774. if (!$error) {
  775. $db->commit();
  776. if ($nb_bills_created == 1) {
  777. $texttoshow = $langs->trans('BillXCreated', '{s1}');
  778. $texttoshow = str_replace('{s1}', '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?id='.urlencode($lastid).'">'.$lastref.'</a>', $texttoshow);
  779. setEventMessages($texttoshow, null, 'mesgs');
  780. } else {
  781. setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
  782. }
  783. // Make a redirect to avoid to bill twice if we make a refresh or back
  784. $param = '';
  785. if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
  786. $param .= '&contextpage='.urlencode($contextpage);
  787. }
  788. if ($limit > 0 && $limit != $conf->liste_limit) {
  789. $param .= '&limit='.urlencode($limit);
  790. }
  791. if ($sall) {
  792. $param .= '&sall='.urlencode($sall);
  793. }
  794. if ($socid > 0) {
  795. $param .= '&socid='.urlencode($socid);
  796. }
  797. if ($search_status != '') {
  798. $param .= '&search_status='.urlencode($search_status);
  799. }
  800. if ($search_orderday) {
  801. $param .= '&search_orderday='.urlencode($search_orderday);
  802. }
  803. if ($search_ordermonth) {
  804. $param .= '&search_ordermonth='.urlencode($search_ordermonth);
  805. }
  806. if ($search_orderyear) {
  807. $param .= '&search_orderyear='.urlencode($search_orderyear);
  808. }
  809. if ($search_deliveryday) {
  810. $param .= '&search_deliveryday='.urlencode($search_deliveryday);
  811. }
  812. if ($search_deliverymonth) {
  813. $param .= '&search_deliverymonth='.urlencode($search_deliverymonth);
  814. }
  815. if ($search_deliveryyear) {
  816. $param .= '&search_deliveryyear='.urlencode($search_deliveryyear);
  817. }
  818. if ($search_ref) {
  819. $param .= '&search_ref='.urlencode($search_ref);
  820. }
  821. if ($search_company) {
  822. $param .= '&search_company='.urlencode($search_company);
  823. }
  824. if ($search_ref_customer) {
  825. $param .= '&search_ref_customer='.urlencode($search_ref_customer);
  826. }
  827. if ($search_user > 0) {
  828. $param .= '&search_user='.urlencode($search_user);
  829. }
  830. if ($search_sale > 0) {
  831. $param .= '&search_sale='.urlencode($search_sale);
  832. }
  833. if ($search_total_ht != '') {
  834. $param .= '&search_total_ht='.urlencode($search_total_ht);
  835. }
  836. if ($search_total_vat != '') {
  837. $param .= '&search_total_vat='.urlencode($search_total_vat);
  838. }
  839. if ($search_total_ttc != '') {
  840. $param .= '&search_total_ttc='.urlencode($search_total_ttc);
  841. }
  842. if ($search_project_ref >= 0) {
  843. $param .= "&search_project_ref=".urlencode($search_project_ref);
  844. }
  845. if ($show_files) {
  846. $param .= '&show_files='.urlencode($show_files);
  847. }
  848. if ($optioncss != '') {
  849. $param .= '&optioncss='.urlencode($optioncss);
  850. }
  851. if ($billed != '') {
  852. $param .= '&billed='.urlencode($billed);
  853. }
  854. header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
  855. exit;
  856. } else {
  857. $db->rollback();
  858. $action = 'create';
  859. $_GET["origin"] = $_POST["origin"];
  860. $_GET["originid"] = $_POST["originid"];
  861. setEventMessages("Error", null, 'errors');
  862. $error++;
  863. }
  864. }
  865. if (!$error && $massaction == 'cancelorders') {
  866. $db->begin();
  867. $nbok = 0;
  868. $orders = GETPOST('toselect', 'array');
  869. foreach ($orders as $id_order) {
  870. $cmd = new Commande($db);
  871. if ($cmd->fetch($id_order) <= 0) {
  872. continue;
  873. }
  874. if ($cmd->statut != Commande::STATUS_VALIDATED) {
  875. $langs->load('errors');
  876. setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
  877. $error++;
  878. break;
  879. } else {
  880. // TODO We do not provide warehouse so no stock change here for the moment.
  881. $result = $cmd->cancel();
  882. }
  883. if ($result < 0) {
  884. setEventMessages($cmd->error, $cmd->errors, 'errors');
  885. $error++;
  886. break;
  887. } else {
  888. $nbok++;
  889. }
  890. }
  891. if (!$error) {
  892. if ($nbok > 1) {
  893. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  894. } else {
  895. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  896. }
  897. $db->commit();
  898. } else {
  899. $db->rollback();
  900. }
  901. }
  902. if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
  903. if (empty($diroutputmassaction)) {
  904. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
  905. exit;
  906. }
  907. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  908. require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
  909. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  910. $objecttmp = new $objectclass($db);
  911. $listofobjectid = array();
  912. $listofobjectthirdparties = array();
  913. $listofobjectref = array();
  914. foreach ($toselect as $toselectid) {
  915. $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
  916. $result = $objecttmp->fetch($toselectid);
  917. if ($result > 0) {
  918. $listofobjectid[$toselectid] = $toselectid;
  919. $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
  920. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  921. $listofobjectref[$toselectid] = $objecttmp->ref;
  922. }
  923. }
  924. $arrayofinclusion = array();
  925. foreach ($listofobjectref as $tmppdf) {
  926. $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
  927. }
  928. foreach ($listofobjectref as $tmppdf) {
  929. $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files
  930. }
  931. $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
  932. // build list of files with full path
  933. $files = array();
  934. foreach ($listofobjectref as $basename) {
  935. $basename = dol_sanitizeFileName($basename);
  936. foreach ($listoffiles as $filefound) {
  937. if (strstr($filefound["name"], $basename)) {
  938. $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
  939. break;
  940. }
  941. }
  942. }
  943. // Define output language (Here it is not used because we do only merging existing PDF)
  944. $outputlangs = $langs;
  945. $newlang = '';
  946. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  947. $newlang = GETPOST('lang_id', 'aZ09');
  948. }
  949. //elseif ($conf->global->MAIN_MULTILANGS && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
  950. // $newlang = $objecttmp->thirdparty->default_lang;
  951. //}
  952. if (!empty($newlang)) {
  953. $outputlangs = new Translate("", $conf);
  954. $outputlangs->setDefaultLang($newlang);
  955. }
  956. if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) {
  957. // Create output dir if not exists
  958. dol_mkdir($diroutputmassaction);
  959. // Defined name of merged file
  960. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  961. $filename = preg_replace('/\s/', '_', $filename);
  962. // Save merged file
  963. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  964. if ($option == 'late') {
  965. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  966. } else {
  967. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  968. }
  969. }
  970. if ($year) {
  971. $filename .= '_'.$year;
  972. }
  973. if ($month) {
  974. $filename .= '_'.$month;
  975. }
  976. if (count($files) > 0) {
  977. $now = dol_now();
  978. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  979. $input_files = '';
  980. foreach ($files as $f) {
  981. $input_files .= ' '.escapeshellarg($f);
  982. }
  983. $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
  984. exec($cmd);
  985. // check if pdftk is installed
  986. if (file_exists($file)) {
  987. if (!empty($conf->global->MAIN_UMASK)) {
  988. @chmod($file, octdec($conf->global->MAIN_UMASK));
  989. }
  990. $langs->load("exports");
  991. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  992. } else {
  993. setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
  994. }
  995. } else {
  996. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  997. }
  998. } else {
  999. // Create empty PDF
  1000. $formatarray = pdf_getFormat();
  1001. $page_largeur = $formatarray['width'];
  1002. $page_hauteur = $formatarray['height'];
  1003. $format = array($page_largeur, $page_hauteur);
  1004. $pdf = pdf_getInstance($format);
  1005. if (class_exists('TCPDF')) {
  1006. $pdf->setPrintHeader(false);
  1007. $pdf->setPrintFooter(false);
  1008. }
  1009. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  1010. if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
  1011. $pdf->SetCompression(false);
  1012. }
  1013. // Add all others
  1014. foreach ($files as $file) {
  1015. // Charge un document PDF depuis un fichier.
  1016. $pagecount = $pdf->setSourceFile($file);
  1017. for ($i = 1; $i <= $pagecount; $i++) {
  1018. $tplidx = $pdf->importPage($i);
  1019. $s = $pdf->getTemplatesize($tplidx);
  1020. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  1021. $pdf->useTemplate($tplidx);
  1022. }
  1023. }
  1024. // Create output dir if not exists
  1025. dol_mkdir($diroutputmassaction);
  1026. // Defined name of merged file
  1027. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  1028. $filename = preg_replace('/\s/', '_', $filename);
  1029. // Save merged file
  1030. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  1031. if ($option == 'late') {
  1032. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  1033. } else {
  1034. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  1035. }
  1036. }
  1037. if ($year) {
  1038. $filename .= '_'.$year;
  1039. }
  1040. if ($month) {
  1041. $filename .= '_'.$month;
  1042. }
  1043. if ($pagecount) {
  1044. $now = dol_now();
  1045. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  1046. $pdf->Output($file, 'F');
  1047. if (!empty($conf->global->MAIN_UMASK)) {
  1048. @chmod($file, octdec($conf->global->MAIN_UMASK));
  1049. }
  1050. $langs->load("exports");
  1051. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  1052. } else {
  1053. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  1054. }
  1055. }
  1056. }
  1057. // Remove a file from massaction area
  1058. if ($action == 'remove_file') {
  1059. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1060. $langs->load("other");
  1061. $upload_dir = $diroutputmassaction;
  1062. $file = $upload_dir.'/'.GETPOST('file');
  1063. $ret = dol_delete_file($file);
  1064. if ($ret) {
  1065. setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
  1066. } else {
  1067. setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
  1068. }
  1069. $action = '';
  1070. }
  1071. // Validate records
  1072. if (!$error && $massaction == 'validate' && $permissiontoadd) {
  1073. $objecttmp = new $objectclass($db);
  1074. if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  1075. $langs->load("errors");
  1076. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  1077. $error++;
  1078. }
  1079. if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  1080. $langs->load("errors");
  1081. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  1082. $error++;
  1083. }
  1084. if (!$error) {
  1085. $db->begin();
  1086. $nbok = 0;
  1087. foreach ($toselect as $toselectid) {
  1088. $result = $objecttmp->fetch($toselectid);
  1089. if ($result > 0) {
  1090. $result = $objecttmp->validate($user);
  1091. if ($result == 0) {
  1092. $langs->load("errors");
  1093. setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
  1094. $error++;
  1095. break;
  1096. } elseif ($result < 0) {
  1097. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1098. $error++;
  1099. break;
  1100. } else {
  1101. // validate() rename pdf but do not regenerate
  1102. // Define output language
  1103. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1104. $outputlangs = $langs;
  1105. $newlang = '';
  1106. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1107. $newlang = GETPOST('lang_id', 'aZ09');
  1108. }
  1109. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1110. $newlang = $objecttmp->thirdparty->default_lang;
  1111. }
  1112. if (!empty($newlang)) {
  1113. $outputlangs = new Translate("", $conf);
  1114. $outputlangs->setDefaultLang($newlang);
  1115. $outputlangs->load('products');
  1116. }
  1117. $model = $objecttmp->model_pdf;
  1118. $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
  1119. // To be sure vars is defined
  1120. $hidedetails = !empty($hidedetails) ? $hidedetails : 0;
  1121. $hidedesc = !empty($hidedesc) ? $hidedesc : 0;
  1122. $hideref = !empty($hideref) ? $hideref : 0;
  1123. $moreparams = !empty($moreparams) ? $moreparams : null;
  1124. $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1125. if ($result < 0) {
  1126. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1127. }
  1128. }
  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("RecordsModified", $nbok), null, 'mesgs');
  1140. } else {
  1141. setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
  1142. }
  1143. $db->commit();
  1144. } else {
  1145. $db->rollback();
  1146. }
  1147. //var_dump($listofobjectthirdparties);exit;
  1148. }
  1149. }
  1150. //var_dump($_POST);var_dump($massaction);exit;
  1151. // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
  1152. if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
  1153. $db->begin();
  1154. $objecttmp = new $objectclass($db);
  1155. $nbok = 0;
  1156. foreach ($toselect as $toselectid) {
  1157. $result = $objecttmp->fetch($toselectid);
  1158. if ($result > 0) {
  1159. // Refuse deletion for some objects/status
  1160. if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) {
  1161. $langs->load("errors");
  1162. $nbignored++;
  1163. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
  1164. continue;
  1165. }
  1166. if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
  1167. $nbignored++;
  1168. $resaction .= '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
  1169. continue;
  1170. }
  1171. if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
  1172. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
  1173. $res = $db->query($sql);
  1174. if (!$res) {
  1175. setEventMessage('ErrorRecordParentingNotModified', 'errors');
  1176. $error++;
  1177. }
  1178. }
  1179. if (in_array($objecttmp->element, array('societe', 'member'))) {
  1180. $result = $objecttmp->delete($objecttmp->id, $user, 1);
  1181. } else {
  1182. $result = $objecttmp->delete($user);
  1183. }
  1184. if ($result <= 0) {
  1185. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1186. $error++;
  1187. break;
  1188. } else {
  1189. $nbok++;
  1190. }
  1191. } else {
  1192. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1193. $error++;
  1194. break;
  1195. }
  1196. }
  1197. if (!$error) {
  1198. if ($nbok > 1) {
  1199. setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
  1200. } elseif ($nbok > 0) {
  1201. setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
  1202. } else {
  1203. setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
  1204. }
  1205. $db->commit();
  1206. } else {
  1207. $db->rollback();
  1208. }
  1209. //var_dump($listofobjectthirdparties);exit;
  1210. }
  1211. // Generate document foreach object according to model linked to object
  1212. // @todo : propose model selection
  1213. if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
  1214. $db->begin();
  1215. $objecttmp = new $objectclass($db);
  1216. $nbok = 0;
  1217. foreach ($toselect as $toselectid) {
  1218. $result = $objecttmp->fetch($toselectid);
  1219. if ($result > 0) {
  1220. $outputlangs = $langs;
  1221. $newlang = '';
  1222. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1223. $newlang = GETPOST('lang_id', 'aZ09');
  1224. }
  1225. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
  1226. $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
  1227. }
  1228. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) {
  1229. $newlang = $objecttmp->default_lang; // for thirdparty
  1230. }
  1231. if (!empty($newlang)) {
  1232. $outputlangs = new Translate("", $conf);
  1233. $outputlangs->setDefaultLang($newlang);
  1234. }
  1235. // To be sure vars is defined
  1236. if (empty($hidedetails)) {
  1237. $hidedetails = 0;
  1238. }
  1239. if (empty($hidedesc)) {
  1240. $hidedesc = 0;
  1241. }
  1242. if (empty($hideref)) {
  1243. $hideref = 0;
  1244. }
  1245. if (empty($moreparams)) {
  1246. $moreparams = null;
  1247. }
  1248. $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1249. if ($result <= 0) {
  1250. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1251. $error++;
  1252. break;
  1253. } else {
  1254. $nbok++;
  1255. }
  1256. } else {
  1257. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1258. $error++;
  1259. break;
  1260. }
  1261. }
  1262. if (!$error) {
  1263. if ($nbok > 1) {
  1264. setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
  1265. } else {
  1266. setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
  1267. }
  1268. $db->commit();
  1269. } else {
  1270. $db->rollback();
  1271. }
  1272. }
  1273. if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
  1274. $db->begin();
  1275. $affecttag_type=GETPOST('affecttag_type', 'alpha');
  1276. if (!empty($affecttag_type)) {
  1277. $affecttag_type_array=explode(',', $affecttag_type);
  1278. } else {
  1279. setEventMessage('CategTypeNotFound', 'errors');
  1280. }
  1281. if (!empty($affecttag_type_array)) {
  1282. //check if tag type submited exists into Tag Map categorie class
  1283. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1284. $categ = new Categorie($db);
  1285. $to_affecttag_type_array=array();
  1286. $categ_type_array=$categ->getMapList();
  1287. foreach ($categ_type_array as $categdef) {
  1288. if (in_array($categdef['code'], $affecttag_type_array)) {
  1289. $to_affecttag_type_array[] = $categdef['code'];
  1290. }
  1291. }
  1292. //For each valid categ type set common categ
  1293. $nbok = 0;
  1294. if (!empty($to_affecttag_type_array)) {
  1295. foreach ($to_affecttag_type_array as $categ_type) {
  1296. $contcats = GETPOST('contcats_' . $categ_type, 'array');
  1297. //var_dump($toselect);exit;
  1298. foreach ($toselect as $toselectid) {
  1299. $result = $object->fetch($toselectid);
  1300. //var_dump($contcats);exit;
  1301. if ($result > 0) {
  1302. $result = $object->setCategoriesCommon($contcats, $categ_type, false);
  1303. if ($result > 0) {
  1304. $nbok++;
  1305. } else {
  1306. setEventMessages($object->error, $object->errors, 'errors');
  1307. }
  1308. } else {
  1309. setEventMessages($object->error, $object->errors, 'errors');
  1310. $error++;
  1311. break;
  1312. }
  1313. }
  1314. }
  1315. }
  1316. }
  1317. if (!$error) {
  1318. if ($nbok > 1) {
  1319. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1320. } else {
  1321. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1322. }
  1323. $db->commit();
  1324. $toselect=array();
  1325. } else {
  1326. $db->rollback();
  1327. }
  1328. }
  1329. $parameters['toselect'] = $toselect;
  1330. $parameters['uploaddir'] = $uploaddir;
  1331. $parameters['massaction'] = $massaction;
  1332. $parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
  1333. $reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1334. if ($reshook < 0) {
  1335. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1336. }