Bugs in sending sales orders as email.
[fa-stable.git] / reporting / includes / pdf_report.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 /* $Revision$ */
13 $page_security = 8;
14 //include_once($path_to_root . "reporting/includes/class.pdf.inc");
15 include_once(dirname(__FILE__)."/class.pdf.inc");
16 include_once(dirname(__FILE__)."/printer_class.inc");
17 include_once($path_to_root . "/admin/db/company_db.inc");
18 include_once($path_to_root . "/admin/db/printers_db.inc");
19 include_once($path_to_root . "/config.php");
20 class FrontReport extends Cpdf
21 {
22         var $size;
23         var $company;
24         var $user;
25         var $host;
26         var $fiscal_year;
27         var $title;
28         var $filename;
29         var $pageWidth;
30         var $pageHeight;
31         var $topMargin;
32         var $bottomMargin;
33         var $leftMargin;
34         var $rightMargin;
35         var $endLine;
36         var $lineHeight;
37         //var $rtl;
38
39         var $cols;
40         var $params;
41         var $headers;
42         var $aligns;
43         var $headers2;
44         var $aligns2;
45         var $cols2;
46         var $companyCol;
47         var $titleCol;
48         var $pageNumber;
49         var $fontSize;
50         var $oldFontSize;
51         var $currency;
52
53         function FrontReport($title, $filename, $size = 'A4', $fontsize = 9)
54         {
55                 switch ($size)
56                 {
57                         default:
58                   case 'A4':
59                   case 'a4':
60                           $this->pageWidth=595;
61                           $this->pageHeight=842;
62                           $this->topMargin=40;
63                           $this->bottomMargin=30;
64                           $this->leftMargin=40;
65                           $this->rightMargin=30;
66                           break;
67                   case 'A4_Landscape':
68                           $this->pageWidth=842;
69                           $this->pageHeight=595;
70                           $this->topMargin=30;
71                           $this->bottomMargin=30;
72                           $this->leftMargin=40;
73                           $this->rightMargin=30;
74                           break;
75                    case 'A3':
76                           $this->pageWidth=842;
77                           $this->pageHeight=1190;
78                           $this->topMargin=50;
79                           $this->bottomMargin=50;
80                           $this->leftMargin=50;
81                           $this->rightMargin=40;
82                           break;
83                    case 'A3_landscape':
84                           $this->pageWidth=1190;
85                           $this->pageHeight=842;
86                           $this->topMargin=50;
87                           $this->bottomMargin=50;
88                           $this->leftMargin=50;
89                           $this->rightMargin=40;
90                           break;
91                    case 'letter':
92                    case 'Letter':
93                           $this->pageWidth=612;
94                           $this->pageHeight=792;
95                           $this->topMargin=30;
96                           $this->bottomMargin=30;
97                           $this->leftMargin=30;
98                           $this->rightMargin=25;
99                           break;
100                    case 'letter_landscape':
101                           $this->pageWidth=792;
102                           $this->pageHeight=612;
103                           $this->topMargin=30;
104                           $this->bottomMargin=30;
105                           $this->leftMargin=30;
106                           $this->rightMargin=25;
107                           break;
108                    case 'legal':
109                           $this->pageWidth=612;
110                           $this->pageHeight=1008;
111                           $this->topMargin=50;
112                           $this->bottomMargin=40;
113                           $this->leftMargin=30;
114                           $this->rightMargin=25;
115                           break;
116                    case 'legal_landscape':
117                           $this->pageWidth=1008;
118                           $this->pageHeight=612;
119                           $this->topMargin=50;
120                           $this->bottomMargin=40;
121                           $this->leftMargin=30;
122                           $this->rightMargin=25;
123                           break;
124                 }
125                 $this->size = array(0, 0, $this->pageWidth, $this->pageHeight);
126                 $this->title = $title;
127                 $this->filename = $filename.".pdf";
128                 $this->pageNumber = 0;
129                 $this->endLine = $this->pageWidth - $this->rightMargin;
130                 $this->companyCol = $this->endLine - 150;
131                 $this->titleCol = $this->leftMargin + 100;
132                 $this->lineHeight = 12;
133                 $this->fontSize = $fontsize;
134                 $this->oldFontSize = 0;
135                 $this->row = $this->pageHeight - $this->topMargin;
136                 $this->currency = '';
137                 $rtl = ($_SESSION['language']->dir === 'rtl' ? 'rtl' : 'ltr');
138                 $code = $_SESSION['language']->code;
139                 $enc = strtoupper($_SESSION['language']->encoding);
140                 // for the language array in class.pdf.inc
141                 $l = array('a_meta_charset' => $enc, 'a_meta_dir' => $rtl, 'a_meta_language' => $code, 'w_page' => 'page');
142                 $this->Cpdf($size, $l);
143         }
144
145         function Font($style = 'normal')
146         {
147                 $this->selectFont("", $style);
148         }
149
150         function Info($params, $cols, $headers, $aligns,
151                 $cols2 = null, $headers2 = null, $aligns2 = null)
152         {
153                 global $app_title, $version, $power_by, $power_url;
154
155                 $this->addinfo('Title', $this->title);
156                 $this->addinfo('Subject', $this->title);
157                 $this->addinfo('Author', $app_title . ' ' . $version);
158                 $this->addinfo('Creator',$power_by . ' - ' . $power_url);
159                 $year = get_current_fiscalyear();
160                 if ($year['closed'] == 0)
161                         $how = _("Active");
162                 else
163                         $how = _("Closed");
164                 $this->fiscal_year = sql2date($year['begin']) . " - " . sql2date($year['end']) . "  " . "(" . $how . ")";
165                 $this->company = get_company_prefs();
166                 $this->user = $_SESSION["wa_current_user"]->name;
167                 $this->host = $_SERVER['SERVER_NAME'];
168                 $this->params = $params;
169                 $this->cols = $cols;
170                 for ($i = 0; $i < count($this->cols); $i++)
171                         $this->cols[$i] += $this->leftMargin;
172                 $this->headers = $headers;
173                 $this->aligns = $aligns;
174                 $this->cols2 = $cols2;
175                 if ($this->cols2 != null)
176                 {
177                         for ($i = 0; $i < count($this->cols2); $i++)
178                                 $this->cols2[$i] += $this->leftMargin;
179                 }
180                 $this->headers2 = $headers2;
181                 $this->aligns2 = $aligns2;
182         }
183
184         function Header()
185         {
186                 $this->pageNumber++;
187                 if ($this->pageNumber > 1)
188                         $this->newPage();
189                 $this->row = $this->pageHeight - $this->topMargin;
190
191                 $this->SetDrawColor(128, 128, 128);
192                 $this->Line($this->row + 5, 1);
193
194                 $this->NewLine();
195
196                 $this->fontSize += 4;
197                 $this->Font('bold');
198                 $this->Text($this->leftMargin, $this->title, $this->companyCol);
199                 $this->Font();
200                 $this->fontSize -= 4;
201                 $this->Text($this->companyCol, $this->company['coy_name']);
202                 $this->row -= ($this->lineHeight + 4);
203
204                 $str = _("Print Out Date") . ':';
205                 $this->Text($this->leftMargin, $str, $this->titleCol);
206                 $str = Today() . '   ' . Now();
207                 $this->Text($this->titleCol, $str, $this->companyCol);
208                 $this->Text($this->companyCol, $this->host);
209
210                 $this->NewLine();
211                 $str = _("Fiscal Year") . ':';
212                 $this->Text($this->leftMargin, $str, $this->titleCol);
213                 $str = $this->fiscal_year;
214                 $this->Text($this->titleCol, $str, $this->companyCol);
215                 $this->Text($this->companyCol, $this->user);
216                 for ($i = 1; $i < count($this->params); $i++)
217                 {
218                         if ($this->params[$i]['from'] != '')
219                         {
220                                 $this->NewLine();
221                                 $str = $this->params[$i]['text'] . ':';
222                                 $this->Text($this->leftMargin, $str, $this->titleCol);
223                                 $str = $this->params[$i]['from'];
224                                 if ($this->params[$i]['to'] != '')
225                                         $str .= " - " . $this->params[$i]['to'];
226                                 $this->Text($this->titleCol, $str, $this->companyCol);
227                         }
228                 }
229                 if ($this->params[0] != '') // Comments
230                 {
231                         $this->NewLine();
232                         $str = _("Comments") . ':';
233                         $this->Text($this->leftMargin, $str, $this->titleCol);
234                         $this->Font('bold');
235                         $this->Text($this->titleCol, $this->params[0], $this->endLine - 35);
236                         $this->Font();
237                 }
238                 $str = _("Page") . ' ' . $this->pageNumber;
239                 $this->Text($this->endLine - 38, $str);
240                 $this->Line($this->row - 5, 1);
241
242                 $this->row -= ($this->lineHeight + 6);
243                 $this->Font('italic');
244                 if ($this->headers2 != null)
245                 {
246                         $count = count($this->headers2);
247                         for ($i = 0; $i < $count; $i++)
248                                 $this->TextCol2($i, $i + 1,     $this->headers2[$i]);
249                         $this->NewLine();
250                 }
251                 $count = count($this->headers);
252                 for ($i = 0; $i < $count; $i++)
253                         $this->TextCol($i, $i + 1, $this->headers[$i]);
254                 $this->Font();
255                 $this->Line($this->row - 5, 1);
256
257                 $this->NewLine(2);
258         }
259
260         function Header2($myrow, $branch, $sales_order, $bankaccount, $doctype)
261         {
262                 global $comp_path, $path_to_root, $print_as_quote, $print_invoice_no;
263
264                 $this->pageNumber++;
265                 if ($this->pageNumber > 1)
266                         $this->newPage();
267                 $header2type = true;
268                 if ($this->currency != $myrow['curr_code'])
269                 {
270                         include($path_to_root . "/reporting/includes/doctext2.inc");
271                 }
272                 else
273                 {
274                         include($path_to_root . "/reporting/includes/doctext.inc");
275                 }
276
277                 include($path_to_root . "/reporting/includes/header2.inc");
278
279                 $this->row = $temp;
280         }
281
282         function AddImage($logo, $x, $y, $w, $h)
283         {
284                 if (strpos($logo, ".png") || strpos($logo, ".PNG"))
285                         $this->addPngFromFile($logo, $x, $y, $w, $h);
286                 else
287                         $this->addJpegFromFile($logo, $x, $y, $w, $h);
288         }
289
290         function SetDrawColor($r, $g, $b)
291         {
292                 $this->setStrokeColor($r, $g, $b);
293         }
294
295         function SetTextColor($r, $g, $b)
296         {
297                 TCPDF::SetTextColor($r, $g, $b);
298         }
299
300         function Text($c, $txt, $n=0, $corr=0, $r=0)
301         {
302                 if ($n == 0)
303                         $n = $this->pageWidth - $this->rightMargin;
304
305                 return $this->TextWrap($c, $this->row - $r, $n - $c + $corr, $txt, 'left');
306         }
307
308         function TextWrap($xpos, $ypos, $len, $str, $align = 'left')
309         {
310                 if ($this->fontSize != $this->oldFontSize)
311                 {
312                         $this->SetFontSize($this->fontSize);
313                         $this->oldFontSize = $this->fontSize;
314                 }
315                 return $this->addTextWrap($xpos, $ypos, $len, $this->fontSize, $str, $align);
316         }
317
318         function TextCol($c, $n, $txt, $corr=0, $r=0)
319         {
320                 return $this->TextWrap($this->cols[$c], $this->row - $r, $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c]);
321         }
322         
323         function AmountCol($c, $n, $txt, $dec=0, $corr=0, $r=0)
324         {
325                 return $this->TextCol($c, $n, number_format2($txt, $dec), $corr, $r);
326         }
327
328         function DateCol($c, $n, $txt, $conv=false, $corr=0, $r=0)
329         {
330                 if ($conv)
331                         $txt = sql2date($txt);
332                 return $this->TextCol($c, $n, $txt, $corr, $r);
333         }
334
335         function TextCol2($c, $n, $txt, $corr=0, $r=0)
336         {
337                 return $this->TextWrap($this->cols2[$c], $this->row - $r, $this->cols2[$n] - $this->cols2[$c] + $corr, $txt, $this->aligns2[$c]);
338         }
339
340         function TextColLines($c, $n, $txt, $corr=0, $r=0)
341         {
342                 $this->row -= $r;
343                 $this->TextWrapLines($this->cols[$c], $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c]);
344         }
345
346         function TextWrapLines($c, $width, $txt, $align='left')
347         {
348                 $str = Explode("\n", $txt);
349                 for ($i = 0; $i < count($str); $i++)
350                 {
351                         $l = $str[$i];
352                         do
353                         {
354                                 $l = $this->TextWrap($c, $this->row , $width, $l, $align);
355                                 $this->NewLine();
356                         }
357                         while ($l != '');
358                 }
359         }
360
361         function LineTo($from, $row, $to, $row2)
362         {
363                 Cpdf::line($from, $row, $to, $row2);
364         }
365
366         function Line($row, $height = 0)
367         {
368                 $this->setLineStyle($height + 1);
369                 Cpdf::line($this->pageWidth - $this->rightMargin, $row ,$this->leftMargin, $row);
370         }
371
372         function NewLine($l=1, $np=0)
373         {
374                 $this->row -= ($l * $this->lineHeight);
375                 if ($this->row < $this->bottomMargin + ($np * $this->lineHeight))
376                         $this->Header();
377         }
378
379         function End($email=0, $subject=null, $myrow=null, $doctype = 0)
380         {
381                 global $pdf_debug, $path_to_root, $comp_path;
382
383                 if ($pdf_debug == 1)
384                 {
385                         $pdfcode = $this->Output('','S');
386                         $pdfcode = str_replace("\n", "\n<br>", htmlspecialchars($pdfcode));
387                         echo '<html><body>';
388                         echo trim($pdfcode);
389                         echo '</body></html>';
390                         //header("Content-Length: $len");
391                         //header("Content-Disposition: inline; filename=" . $this->filename);
392                         //header('Expires: 0');
393                         //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
394                         //header('Pragma: public');
395
396                         //$this->pdf->stream();
397                 }
398                 else
399                 {
400
401                         $dir =  $comp_path.'/'.user_company(). '/pdf_files';
402                         //save the file
403                         if (!file_exists($dir))
404                         {
405                                 mkdir ($dir,0777);
406                         }
407                         // do not use standard filenames or your sensitive company data 
408                         // are world readable
409                         $fname = $dir.'/'.uniqid('').'.pdf';
410                         $this->Output($fname, 'F');
411                         if ($email == 1)
412                         {
413                                 $emailtype = true;
414                                 if ($this->currency != $myrow['curr_code'])
415                                 {
416                                         include("doctext2.inc");
417                                 }
418                                 else
419                                 {
420                                         include("doctext.inc");
421                                 }
422                                 require_once($path_to_root . "/reporting/includes/class.mail.inc");
423                         $mail = new email($this->company['coy_name'], $this->company['email']);
424                         $from = $this->company['coy_name'] . " <" . $this->company['email'] . ">";
425                                 if (!isset($myrow['email']) || $myrow['email'] == '') $myrow['email'] = $myrow['contact_email'];
426                         $to = $myrow['DebtorName'] . " <" . $myrow['email'] . ">";
427                         $msg = $doc_Dear_Sirs . " " . $myrow['DebtorName'] . ",\n\n" . $doc_AttachedFile . " " . $subject .
428                                 "\n\n";
429                                 if (isset($myrow['dimension_id']) && $myrow['dimension_id'] > 0 && $doctype == 10) // helper for payment links
430                                 {
431                                         if ($myrow['dimension_id'] == 1)
432                                         {
433                                                 $amt = number_format($myrow["ov_freight"] + $myrow["ov_gst"] +  $myrow["ov_amount"], user_price_dec());
434                                                 $txt = $doc_Payment_Link . " PayPal: ";
435                                                 $nn = urlencode($this->title . " " . $myrow['reference']);
436                                                 $url = "https://www.paypal.com/xclick/business=" . $this->company['email'] . "&item_name=" .
437                                                         $nn . "&amount=" . $amt . "&currency_code=" . $myrow['curr_code'];
438                                                 $msg .= $txt . $url . "\n\n";
439                                         }
440                                 }
441                         $msg .= $doc_Kindest_regards . "\n\n";
442                         $sender = $this->user . "\n" . $this->company['coy_name'] . "\n" . $this->company['postal_address'] . "\n" . $this->company['email'] . "\n" . $this->company['phone'];
443                         $mail->to($to);
444                         $mail->subject($subject);
445                         $mail->text($msg . $sender);
446                         $mail->attachment($fname);
447                         $ret = $mail->send();
448                         if (1 == 1) // just for fun and for debugging purposes!!
449                         {
450                                 $from = str_replace("<", "(", $from);
451                                 $from = str_replace(">", ")", $from);
452                                 $to = str_replace("<", "(", $to);
453                                 $to = str_replace(">", ")", $to);
454                                 $msg2 = "<br>From: " . $from;
455                                 $msg2 .= "<br>To: " . $to;
456                                 $msg2 .= "<br>Subject: " . $subject;
457                                 $msg2 .= "<br>Msg: " . nl2br($msg);
458                                 $msg2 .= nl2br($sender) . "<br>";
459                                 $msg2 .= "<br>Filepath: " . $fname . "<br>Filename: " . $this->filename . "<br>";
460                         }
461                         if (!isset($myrow['reference'])) $myrow['reference'] = '';
462                                 if (!$ret)
463                                         display_error(_("Sending document by email failed"));
464                                 else
465                                         display_notification($this->title . " " . $myrow['reference'] . " " 
466                                                 . _("has been sent by email."));
467                         }
468                         else
469                         {
470                                 $printer = get_report_printer(user_print_profile(), $_POST['REP_ID']);
471                                 if ($printer == false) {
472                                         if(in_ajax()) {
473                                                 global $Ajax;
474
475                                                 if (user_rep_popup()) 
476                                                         $Ajax->popup($fname); // when embeded pdf viewer used
477                                                 else
478                                                         $Ajax->redirect($fname); // otherwise use faster method
479                                         } else {
480                                         //echo '<html>
481                                         //              <head>
482                                         //                <SCRIPT LANGUAGE="JavaScript"><!--
483                                         //            function go_now () { window.location.href = "'.$fname.'"; }
484                                         //            //--></SCRIPT>
485                                         //        </head>
486                                         //        <body onLoad="go_now()"; >
487                                         //          <a href="'.$fname.'">click here</a> if you are not re-directed.
488                                         //        </body>
489                                         //    </html>';
490                         header('Content-type: application/pdf');
491                     header("Content-Disposition: inline; filename=$this->filename");
492                         header('Expires: 0');
493                     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
494                         header('Pragma: public');
495                         $this->Stream();
496                                         }
497                                 } else { // send report to network printer
498                                         $prn = new remote_printer($printer['queue'],$printer['host'],
499                                                 $printer['port'], $printer['timeout']);
500                                         $error = $prn->print_file($fname);
501                                         if ($error)
502                                                 display_error($error);
503                                         else
504                                                 display_notification(_('Report has been sent to network printer ').$printer['name']);
505                                 }
506                         }
507                         // first have a look through the directory, 
508                         // and remove old temporary pdfs
509                         if ($d = @opendir($dir)) {
510                                 while (($file = readdir($d)) !== false) {
511                                         if (!is_file($dir.'/'.$file) || $file == 'index.php') continue;
512                                 // then check to see if this one is too old
513                                         $ftime = filemtime($dir.'/'.$file);
514                                  // seems 3 min is enough for any report download, isn't it?
515                                         if (time()-$ftime > 180){
516                                                 unlink($dir.'/'.$file);
517                                         }
518                                 }
519                                 closedir($d);
520                         }
521                 }
522         }
523 }
524
525 ?>