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