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