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