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