Merged changes in main branch up to v.2.1.2
[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                 $this->Text($this->titleCol, $str, $this->companyCol);
207                 $this->Text($this->companyCol, $this->host);
208
209                 $this->NewLine();
210                 $str = _("Fiscal Year") . ':';
211                 $this->Text($this->leftMargin, $str, $this->titleCol);
212                 $str = $this->fiscal_year;
213                 $this->Text($this->titleCol, $str, $this->companyCol);
214                 $this->Text($this->companyCol, $this->user);
215                 for ($i = 1; $i < count($this->params); $i++)
216                 {
217                         if ($this->params[$i]['from'] != '')
218                         {
219                                 $this->NewLine();
220                                 $str = $this->params[$i]['text'] . ':';
221                                 $this->Text($this->leftMargin, $str, $this->titleCol);
222                                 $str = $this->params[$i]['from'];
223                                 if ($this->params[$i]['to'] != '')
224                                         $str .= " - " . $this->params[$i]['to'];
225                                 $this->Text($this->titleCol, $str, $this->companyCol);
226                         }
227                 }
228                 if ($this->params[0] != '') // Comments
229                 {
230                         $this->NewLine();
231                         $str = _("Comments") . ':';
232                         $this->Text($this->leftMargin, $str, $this->titleCol);
233                         $this->Font('bold');
234                         $this->Text($this->titleCol, $this->params[0], $this->endLine - 35);
235                         $this->Font();
236                 }
237                 $str = _("Page") . ' ' . $this->pageNumber;
238                 $this->Text($this->endLine - 38, $str);
239                 $this->Line($this->row - 5, 1);
240
241                 $this->row -= ($this->lineHeight + 6);
242                 $this->Font('italic');
243                 if ($this->headers2 != null)
244                 {
245                         $count = count($this->headers2);
246                         for ($i = 0; $i < $count; $i++)
247                                 $this->TextCol2($i, $i + 1,     $this->headers2[$i]);
248                         $this->NewLine();
249                 }
250                 $count = count($this->headers);
251                 for ($i = 0; $i < $count; $i++)
252                         $this->TextCol($i, $i + 1, $this->headers[$i]);
253                 $this->Font();
254                 $this->Line($this->row - 5, 1);
255
256                 $this->NewLine(2);
257         }
258
259         function Header2($myrow, $branch, $sales_order, $bankaccount, $doctype)
260         {
261                 global $comp_path, $path_to_root, $print_as_quote, $print_invoice_no;
262
263                 $this->pageNumber++;
264                 if ($this->pageNumber > 1)
265                         $this->newPage();
266                 $header2type = true;
267                 if ($this->currency != $myrow['curr_code'])
268                 {
269                         include($path_to_root . "/reporting/includes/doctext2.inc");
270                 }
271                 else
272                 {
273                         include($path_to_root . "/reporting/includes/doctext.inc");
274                 }
275
276                 include($path_to_root . "/reporting/includes/header2.inc");
277
278                 $this->row = $temp;
279         }
280
281         function AddImage($logo, $x, $y, $w, $h)
282         {
283                 if (strpos($logo, ".png") || strpos($logo, ".PNG"))
284                         $this->addPngFromFile($logo, $x, $y, $w, $h);
285                 else
286                         $this->addJpegFromFile($logo, $x, $y, $w, $h);
287         }
288
289         function SetDrawColor($r, $g, $b)
290         {
291                 $this->setStrokeColor($r, $g, $b);
292         }
293
294         function SetTextColor($r, $g, $b)
295         {
296                 TCPDF::SetTextColor($r, $g, $b);
297         }
298
299         function Text($c, $txt, $n=0, $corr=0, $r=0)
300         {
301                 if ($n == 0)
302                         $n = $this->pageWidth - $this->rightMargin;
303
304                 return $this->TextWrap($c, $this->row - $r, $n - $c + $corr, $txt, 'left');
305         }
306
307         function TextWrap($xpos, $ypos, $len, $str, $align = 'left')
308         {
309                 if ($this->fontSize != $this->oldFontSize)
310                 {
311                         $this->SetFontSize($this->fontSize);
312                         $this->oldFontSize = $this->fontSize;
313                 }
314                 return $this->addTextWrap($xpos, $ypos, $len, $this->fontSize, $str, $align);
315         }
316
317         function TextCol($c, $n, $txt, $corr=0, $r=0)
318         {
319                 return $this->TextWrap($this->cols[$c], $this->row - $r, $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c]);
320         }
321         
322         function AmountCol($c, $n, $txt, $dec=0, $corr=0, $r=0)
323         {
324                 return $this->TextCol($c, $n, number_format2($txt, $dec), $corr, $r);
325         }
326
327         function DateCol($c, $n, $txt, $conv=false, $corr=0, $r=0)
328         {
329                 if ($conv)
330                         $txt = sql2date($txt);
331                 return $this->TextCol($c, $n, $txt, $corr, $r);
332         }
333
334         function TextCol2($c, $n, $txt, $corr=0, $r=0)
335         {
336                 return $this->TextWrap($this->cols2[$c], $this->row - $r, $this->cols2[$n] - $this->cols2[$c] + $corr, $txt, $this->aligns2[$c]);
337         }
338
339         function TextColLines($c, $n, $txt, $corr=0, $r=0)
340         {
341                 $this->row -= $r;
342                 $this->TextWrapLines($this->cols[$c], $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c]);
343         }
344
345         function TextWrapLines($c, $width, $txt, $align='left')
346         {
347                 $str = Explode("\n", $txt);
348                 for ($i = 0; $i < count($str); $i++)
349                 {
350                         $l = $str[$i];
351                         do
352                         {
353                                 $l = $this->TextWrap($c, $this->row , $width, $l, $align);
354                                 $this->NewLine();
355                         }
356                         while ($l != '');
357                 }
358         }
359
360         function LineTo($from, $row, $to, $row2)
361         {
362                 Cpdf::line($from, $row, $to, $row2);
363         }
364
365         function Line($row, $height = 0)
366         {
367                 $this->setLineStyle($height + 1);
368                 Cpdf::line($this->pageWidth - $this->rightMargin, $row ,$this->leftMargin, $row);
369         }
370
371         function NewLine($l=1, $np=0)
372         {
373                 $this->row -= ($l * $this->lineHeight);
374                 if ($this->row < $this->bottomMargin + ($np * $this->lineHeight))
375                         $this->Header();
376         }
377
378         function End($email=0, $subject=null, $myrow=null, $doctype = 0)
379         {
380                 global $pdf_debug, $path_to_root, $comp_path;
381
382                 if ($pdf_debug == 1)
383                 {
384                         $pdfcode = $this->Output('','S');
385                         $pdfcode = str_replace("\n", "\n<br>", htmlspecialchars($pdfcode));
386                         echo '<html><body>';
387                         echo trim($pdfcode);
388                         echo '</body></html>';
389                         //header("Content-Length: $len");
390                         //header("Content-Disposition: inline; filename=" . $this->filename);
391                         //header('Expires: 0');
392                         //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
393                         //header('Pragma: public');
394
395                         //$this->pdf->stream();
396                 }
397                 else
398                 {
399
400                         $dir =  $comp_path.'/'.user_company(). '/pdf_files';
401                         //save the file
402                         if (!file_exists($dir))
403                         {
404                                 mkdir ($dir,0777);
405                         }
406                         // do not use standard filenames or your sensitive company data 
407                         // are world readable
408                         $fname = $dir.'/'.uniqid('').'.pdf';
409                         $this->Output($fname, 'F');
410                         if ($email == 1)
411                         {
412                                 $emailtype = true;
413                                 if ($this->currency != $myrow['curr_code'])
414                                 {
415                                         include("doctext2.inc");
416                                 }
417                                 else
418                                 {
419                                         include("doctext.inc");
420                                 }
421                                 require_once($path_to_root . "/reporting/includes/class.mail.inc");
422                         $mail = new email($this->company['coy_name'], $this->company['email']);
423                         $from = $this->company['coy_name'] . " <" . $this->company['email'] . ">";
424                         $to = $myrow['DebtorName'] . " <" . $myrow['email'] . ">";
425                         $msg = $doc_Dear_Sirs . ",\n\n" . $doc_AttachedFile . " " . $subject .
426                                 "\n\n";
427                                 if ($myrow['dimension_id'] > 0 && $doctype == 10) // helper for payment links
428                                 {
429                                         if ($myrow['dimension_id'] == 1)
430                                         {
431                                                 $amt = number_format($myrow["ov_freight"] + $myrow["ov_gst"] +  $myrow["ov_amount"], user_price_dec());
432                                                 $txt = $doc_Payment_Link . " PayPal: ";
433                                                 $nn = urlencode($this->title . " " . $myrow['reference']);
434                                                 $url = "https://www.paypal.com/xclick/business=" . $this->company['email'] . "&item_name=" .
435                                                         $nn . "&amount=" . $amt . "&currency_code=" . $myrow['curr_code'];
436                                                 $msg .= $txt . $url . "\n\n";
437                                         }
438                                 }
439                         $msg .= $doc_Kindest_regards . "\n\n";
440                         $sender = $this->user . "\n" . $this->company['coy_name'];
441                         $mail->to($to);
442                         $mail->subject($subject);
443                         $mail->text($msg . $sender);
444                         $mail->attachment($fname);
445                         $ret = $mail->send();
446                         if (1 == 1) // just for fun and for debugging purposes!!
447                         {
448                                 $from = str_replace("<", "(", $from);
449                                 $from = str_replace(">", ")", $from);
450                                 $to = str_replace("<", "(", $to);
451                                 $to = str_replace(">", ")", $to);
452                                 $msg2 = "<br>From: " . $from;
453                                 $msg2 .= "<br>To: " . $to;
454                                 $msg2 .= "<br>Subject: " . $subject;
455                                 $msg2 .= "<br>Msg: " . nl2br($msg);
456                                 $msg2 .= nl2br($sender) . "<br>";
457                                 $msg2 .= "<br>Filepath: " . $fname . "<br>Filename: " . $this->filename . "<br>";
458                         }
459                                 if (!$ret)
460                                         display_error(_("Sending document by email failed"));
461                                 else
462                                         display_notification($this->title . " " . $myrow['reference'] . " " 
463                                                 . _("has been sent by email."));
464                         }
465                         else
466                         {
467                                 $printer = get_report_printer(user_print_profile(), $_POST['REP_ID']);
468                                 if ($printer == false) {
469                                         if(in_ajax()) {
470                                                 global $Ajax;
471
472                                                 if (user_rep_popup()) 
473                                                         $Ajax->popup($fname); // when embeded pdf viewer used
474                                                 else
475                                                         $Ajax->redirect($fname); // otherwise use faster method
476                                         } else {
477                                         //echo '<html>
478                                         //              <head>
479                                         //                <SCRIPT LANGUAGE="JavaScript"><!--
480                                         //            function go_now () { window.location.href = "'.$fname.'"; }
481                                         //            //--></SCRIPT>
482                                         //        </head>
483                                         //        <body onLoad="go_now()"; >
484                                         //          <a href="'.$fname.'">click here</a> if you are not re-directed.
485                                         //        </body>
486                                         //    </html>';
487                         header('Content-type: application/pdf');
488                     header("Content-Disposition: inline; filename=$this->filename");
489                         header('Expires: 0');
490                     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
491                         header('Pragma: public');
492                         $this->Stream();
493                                         }
494                                 } else { // send report to network printer
495                                         $prn = new remote_printer($printer['queue'],$printer['host'],
496                                                 $printer['port'], $printer['timeout']);
497                                         $error = $prn->print_file($fname);
498                                         if ($error)
499                                                 display_error($error);
500                                         else
501                                                 display_notification(_('Report has been sent to network printer ').$printer['name']);
502                                 }
503                         }
504                         // first have a look through the directory, 
505                         // and remove old temporary pdfs
506                         if ($d = @opendir($dir)) {
507                                 while (($file = readdir($d)) !== false) {
508                                         if (!is_file($dir.'/'.$file) || $file == 'index.php') continue;
509                                 // then check to see if this one is too old
510                                         $ftime = filemtime($dir.'/'.$file);
511                                  // seems 3 min is enough for any report download, isn't it?
512                                         if (time()-$ftime > 180){
513                                                 unlink($dir.'/'.$file);
514                                         }
515                                 }
516                                 closedir($d);
517                         }
518                 }
519         }
520 }
521
522 ?>