414151bafa3c8501e34d382bcaf7f586d0c50bf6
[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 /*
13         TODO:
14         . add StartReport/EndReport handlers for better bulk report support, with
15         . email/printer destination option should be selected on class creation instead
16          of End()
17         . add/use setter function for Header2 parameters (currently passed globally)
18         . in report files pass already prepared options to SetCommonData() to avoid need for
19          selection inside FrontReport generic class.
20 */
21 include_once(dirname(__FILE__)."/class.pdf.inc");
22 include_once(dirname(__FILE__)."/printer_class.inc");
23 include_once($path_to_root . "/admin/db/company_db.inc");
24 include_once($path_to_root . "/admin/db/fiscalyears_db.inc");
25 include_once($path_to_root . "/admin/db/printers_db.inc");
26 include_once($path_to_root . "/config.php");
27
28 class FrontReport extends Cpdf
29 {
30         var $size;
31         var $company;
32         var $user;
33         var $host;
34         var $fiscal_year;
35         var $title;
36         var $filename;
37         var $pageWidth;
38         var $pageHeight;
39         var $topMargin;
40         var $bottomMargin;
41         var $leftMargin;
42         var $rightMargin;
43         var $endLine;
44         var $lineHeight;
45         //var $rtl;
46
47         var $row;
48         var $cols;
49         var $params;
50         var $headers;
51         var $aligns;
52         var $headers2;
53         var $aligns2;
54         var $cols2;
55         var $pageNumber;
56         var $fontSize;
57         var $oldFontSize;
58         var $currency;
59         var $companyLogoEnable;  // select whether to use a company logo graphic in some header templates
60         var $scaleLogoWidth;
61         var $footerEnable;  // select whether to print a page footer or not
62         var $footerText;  // store user-generated footer text
63         var $headerTmpl;  // store the name of the currently selected header template
64         var $tmplSize; // pdf header template size in pages
65
66         var $rep_id;
67         var $formData; // common data used for printing headers footers etc.
68
69         var $dest;      // destination: email or printer
70         
71         function FrontReport($title, $filename, $size = 'A4', $fontsize = 9, $orientation = 'P', $margins = NULL, $excelColWidthFactor = NULL)
72         {
73                 global $page_security;
74
75                 $this->rep_id = $_POST['REP_ID'];       // FIXME
76                 
77                 if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
78                 {
79                         display_error(_("The security settings on your account do not permit you to print this report"));
80                         end_page();
81                         exit;
82                 }
83                 // Page margins - if user-specified, use those.  Otherwise, use defaults below.
84                 if (isset($margins))
85                 {
86                         $this->topMargin = $margins['top'];
87                         $this->bottomMargin = $margins['bottom'];
88                         $this->leftMargin = $margins['left'];
89                         $this->rightMargin = $margins['right'];
90                 }
91                 // Page orientation - P: portrait, L: landscape
92                 $orientation = strtoupper($orientation);
93                 // Page size name
94                 switch (strtoupper($size))
95                 {
96                         default:
97                   case 'A4':
98                           // Portrait
99                           if ($orientation == 'P')
100                           {
101                                   $this->pageWidth=595;
102                                   $this->pageHeight=842;
103                                   if (!isset($margins))
104                                   {
105                                           $this->topMargin=40;
106                                           $this->bottomMargin=30;
107                                           $this->leftMargin=40;
108                                           $this->rightMargin=30;
109                                   }
110                           }
111                           // Landscape
112                           else
113                           {
114                                   $this->pageWidth=842;
115                                   $this->pageHeight=595;
116                                   if (!isset($margins))
117                                   {
118                                           $this->topMargin=30;
119                                           $this->bottomMargin=30;
120                                           $this->leftMargin=40;
121                                           $this->rightMargin=30;
122                                   }
123                           }
124                           break;
125                    case 'A3':
126                           // Portrait
127                           if ($orientation == 'P')
128                           {
129                                   $this->pageWidth=842;
130                                   $this->pageHeight=1190;
131                                   if (!isset($margins))
132                                   {
133                                           $this->topMargin=50;
134                                           $this->bottomMargin=50;
135                                           $this->leftMargin=50;
136                                           $this->rightMargin=40;
137                                   }
138                           }
139                           // Landscape
140                           else
141                           {
142                                   $this->pageWidth=1190;
143                                   $this->pageHeight=842;
144                                   if (!isset($margins))
145                                   {
146                                           $this->topMargin=50;
147                                           $this->bottomMargin=50;
148                                           $this->leftMargin=50;
149                                           $this->rightMargin=40;
150                                   }
151                           }
152                           break;
153                    case 'LETTER':
154                           // Portrait
155                           if ($orientation == 'P')
156                           {
157                                   $this->pageWidth=612;
158                                   $this->pageHeight=792;
159                                   if (!isset($margins))
160                                   {
161                                           $this->topMargin=30;
162                                           $this->bottomMargin=30;
163                                           $this->leftMargin=30;
164                                           $this->rightMargin=25;
165                                   }
166                           }
167                           // Landscape
168                           else
169                           {
170                                   $this->pageWidth=792;
171                                   $this->pageHeight=612;
172                                   if (!isset($margins))
173                                   {
174                                           $this->topMargin=30;
175                                           $this->bottomMargin=30;
176                                           $this->leftMargin=30;
177                                           $this->rightMargin=25;
178                                   }
179                           }
180                           break;
181                    case 'LEGAL':
182                           // Portrait
183                           if ($orientation == 'P')
184                           {
185                                   $this->pageWidth=612;
186                                   $this->pageHeight=1008;
187                                   if (!isset($margins))
188                                   {
189                                           $this->topMargin=50;
190                                           $this->bottomMargin=40;
191                                           $this->leftMargin=30;
192                                           $this->rightMargin=25;
193                                   }
194                           }
195                           // Landscape
196                           else
197                           {
198                                   $this->pageWidth=1008;
199                                   $this->pageHeight=612;
200                                   if (!isset($margins))
201                                   {
202                                           $this->topMargin=50;
203                                           $this->bottomMargin=40;
204                                           $this->leftMargin=30;
205                                           $this->rightMargin=25;
206                                   }
207                           }
208                           break;
209                 }
210                 $this->size = array(0, 0, $this->pageWidth, $this->pageHeight);
211                 $this->title = $title;
212                 $this->filename = $filename.".pdf";
213                 $this->pageNumber = 0;
214                 $this->endLine = $this->pageWidth - $this->rightMargin;
215                 $this->lineHeight = 12;
216                 $this->fontSize = $fontsize;
217                 $this->oldFontSize = 0;
218                 $this->row = $this->pageHeight - $this->topMargin;
219                 $this->currency = '';
220                 $this->scaleLogoWidth = false; // if Logo, scale on width (else height).
221                 $this->SetHeaderType('Header'); // default
222                 
223                 $rtl = ($_SESSION['language']->dir === 'rtl' ? 'rtl' : 'ltr');
224                 $code = $_SESSION['language']->code;
225                 $enc = strtoupper($_SESSION['language']->encoding);
226                 // for the language array in class.pdf.inc
227                 $l = array('a_meta_charset' => $enc, 'a_meta_dir' => $rtl, 'a_meta_language' => $code, 'w_page' => 'page');
228                 $this->Cpdf($size, $l, $orientation);
229         }
230         
231         /*
232          * Select the font and style to use for following output until
233          * it's changed again.
234          * 
235          * $style is either:
236          *   * a special case string (for backwards compatible with older code):
237          *     * bold
238          *     * italic
239          *   * or a case-insensitive string where each char represents a style choice
240          *     and you can use more than one or none at all.  Possible choices:
241          *      * empty string: regular
242      *      * B: bold
243      *      * I: italic
244      *      * U: underline
245      *      * D: line trough (aka "strike through")
246          * $fontname should be a standard PDF font (like 'times', 'helvetica' or 'courier')
247          *   or one that's been installed on your system (see TCPDF docs for details).
248          *   An empty string can also be used which will retain the font currently in use if
249          *   you just want to change the style.
250          */
251         function Font($style = '', $fontname = '')
252         {
253                 $this->selectFont($fontname, $style);
254         }
255
256         function Info($params, $cols, $headers, $aligns,
257                 $cols2 = null, $headers2 = null, $aligns2 = null,
258                 $companylogoenable = false, $footerenable = false, $footertext = '')
259         {
260                 global $app_title, $version, $power_by, $power_url;
261
262                 $this->addinfo('Title', $this->title);
263                 $this->addinfo('Subject', $this->title);
264                 $this->addinfo('Author', $app_title . ' ' . $version);
265                 $this->addinfo('Creator',$power_by . ' - ' . $power_url);
266                 $year = get_current_fiscalyear();
267                 if ($year['closed'] == 0)
268                         $how = _("Active");
269                 else
270                         $how = _("Closed");
271                 $this->fiscal_year = sql2date($year['begin']) . " - " . sql2date($year['end']) . "  " . "(" . $how . ")";
272                 $this->company = get_company_prefs();
273                 $this->user = $_SESSION["wa_current_user"]->name;
274                 $this->host = $_SERVER['SERVER_NAME'];
275                 $this->params = $params;
276                 $this->cols = $cols;
277                 for ($i = 0; $i < count($this->cols); $i++)
278                         $this->cols[$i] += $this->leftMargin;
279                 $this->headers = $headers;
280                 $this->aligns = $aligns;
281                 $this->cols2 = $cols2;
282                 if ($this->cols2 != null)
283                 {
284                         for ($i = 0; $i < count($this->cols2); $i++)
285                                 $this->cols2[$i] += $this->leftMargin;
286                 }
287                 $this->headers2 = $headers2;
288                 $this->aligns2 = $aligns2;
289
290                 // Set whether to display company logo in some header templates
291                 $this->companyLogoEnable = $companylogoenable;
292                 
293                 // Store footer settings
294                 $this->footerEnable = $footerenable;
295                 $this->footerText = $footertext;        
296         }
297         //
298         //      Header for listings
299         //
300         function Header()
301         {
302                 $companyCol = $this->endLine - 150;
303                 $titleCol = $this->leftMargin + 100;
304
305                 $this->row = $this->pageHeight - $this->topMargin;
306
307                 $this->SetDrawColor(128, 128, 128);
308                 $this->Line($this->row + 5, 1);
309
310                 $this->NewLine();
311
312                 $this->fontSize += 4;
313                 $this->Font('bold');
314                 $this->Text($this->leftMargin, $this->title, $companyCol);
315                 $this->Font();
316                 $this->fontSize -= 4;
317                 $this->Text($companyCol, $this->company['coy_name']);
318                 $this->row -= ($this->lineHeight + 4);
319
320                 $str = _("Print Out Date") . ':';
321                 $this->Text($this->leftMargin, $str, $titleCol);
322                 $str = Today() . '   ' . Now();
323                 if ($this->company['time_zone'])
324                         $str .= ' ' . date('O') . ' GMT';
325                 $this->Text($titleCol, $str, $companyCol);
326                 $this->Text($companyCol, $this->host);
327
328                 $this->NewLine();
329                 $str = _("Fiscal Year") . ':';
330                 $this->Text($this->leftMargin, $str, $titleCol);
331                 $str = $this->fiscal_year;
332                 $this->Text($titleCol, $str, $companyCol);
333                 $this->Text($companyCol, $this->user);
334                 for ($i = 1; $i < count($this->params); $i++)
335                 {
336                         if ($this->params[$i]['from'] != '')
337                         {
338                                 $this->NewLine();
339                                 $str = $this->params[$i]['text'] . ':';
340                                 $this->Text($this->leftMargin, $str, $titleCol);
341                                 $str = $this->params[$i]['from'];
342                                 if ($this->params[$i]['to'] != '')
343                                         $str .= " - " . $this->params[$i]['to'];
344                                 $this->Text($titleCol, $str, $companyCol);
345                         }
346                 }
347                 if ($this->params[0] != '') // Comments
348                 {
349                         $this->NewLine();
350                         $str = _("Comments") . ':';
351                         $this->Text($this->leftMargin, $str, $titleCol);
352                         $this->Font('bold');
353                         $this->Text($titleCol, $this->params[0], $this->endLine - 35);
354                         $this->Font();
355                 }
356                 $str = _("Page") . ' ' . $this->pageNumber;
357                 $this->Text($this->endLine - 38, $str);
358                 $this->Line($this->row - 5, 1);
359
360                 $this->row -= ($this->lineHeight + 6);
361                 $this->Font('italic');
362                 if ($this->headers2 != null)
363                 {
364                         $count = count($this->headers2);
365                         for ($i = 0; $i < $count; $i++)
366                                 $this->TextCol2($i, $i + 1,     $this->headers2[$i]);
367                         $this->NewLine();
368                 }
369                 $count = count($this->headers);
370                 for ($i = 0; $i < $count; $i++)
371                         $this->TextCol($i, $i + 1, $this->headers[$i]);
372                 $this->Font();
373                 $this->Line($this->row - 5, 1);
374
375                 $this->NewLine(2);
376         }
377         /*
378                 Transition function 
379         */
380         function SetCommonData($myrow, $branch, $sales_order, $bankaccount, $doctype)
381         {
382 //              $this->formData = array_merge($myrow, $branch, $sales_order, 
383 //                      $bank_account, array('doctype' => $doctype));
384
385                 $this->formData = array();
386                 $datnames = array( 
387                 'myrow' => array('ord_date', 'date_', 'tran_date', 
388                         'order_no','reference', 'id', 'trans_no', 'name', 'location_name',
389                         'delivery_address', 'supp_name', 'address',
390                         'DebtorName', 'supp_account_no', 'wo_ref', 'debtor_ref','type', 'trans_no', 
391                         'StockItemName', 'tax_id', 'order_', 'delivery_date', 'units_issued',
392                         'due_date', 'required_by', 'payment_terms', 'curr_code',
393                         'ov_freight', 'ov_gst', 'ov_amount'),
394                 'branch' => array('br_address', 'br_name', 'salesman', 'disable_branch'),
395                 'sales_order' => array('deliver_to', 'delivery_address', 'customer_ref'),
396                 'bankaccount' => array('bank_name', 'bank_account_number')
397                 );
398         
399                 foreach($datnames as $var => $fields) {
400                         if (isset($$var)) {
401                                 foreach($fields as $locname) {
402                                         if (isset(${$var}[$locname])) {
403                                                 $this->formData[$locname] = ${$var}[$locname];
404                                         }
405                                 }
406                         }
407                 }
408                 $this->formData['doctype'] = $doctype;
409         }
410         /*
411                 Set header handler
412         */
413         function SetHeaderType($name) {
414                 $this->headerTmpl = $name;
415         }
416         /*
417                 Header for sales/purchase documents
418         */
419         function Header2()
420         {
421                 global $comp_path, $path_to_root, $print_as_quote, $print_invoice_no, $packing_slip; // FIXME
422
423                 $doctype = $this->formData['doctype'];
424                 $header2type = true;
425                 
426                  // leave layout files names without path to enable including
427                  // modified versions from comapny/x/reporting directory
428                 if (isset($myrow['curr_code']) && $this->currency != $myrow['curr_code'])
429                 {
430                         include("includes/doctext2.inc");
431                 }
432                 else
433                 {
434                         include("includes/doctext.inc");
435                 }
436                 
437                 include("includes/header2.inc");
438
439                 $this->row = $temp;
440         }
441
442         // Alternate header style which also supports a simple footer
443         function Header3()
444         {
445                 global $comp_path;
446
447                 // Turn off cell padding for the main report header, restoring the current setting later
448                 $oldcMargin = $this->cMargin;
449                 $this->SetCellPadding(0);
450
451                 // Set some constants which control header item layout
452                 // only set them once or the PHP interpreter gets angry
453                 if ($this->pageNumber == 1)
454                 {
455                         define('COMPANY_WIDTH', 150);
456                         define('LOGO_HEIGHT', 50);
457                         define('LOGO_Y_POS_ADJ_FACTOR', 0.74);
458                         define('LABEL_WIDTH', 80);
459                         define('PAGE_NUM_WIDTH', 60);
460                         define('TITLE_FONT_SIZE', 14);
461                         define('HEADER1_FONT_SIZE', 10);
462                         define('HEADER2_FONT_SIZE', 9);
463                         define('FOOTER_FONT_SIZE', 10);
464                         define('FOOTER_MARGIN', 4);
465                 }
466                 // Set some variables which control header item layout
467                 $companyCol = $this->endLine - COMPANY_WIDTH;
468                 $headerFieldCol = $this->leftMargin + LABEL_WIDTH;
469                 $pageNumCol = $this->endLine - PAGE_NUM_WIDTH;
470                 $footerCol = $this->leftMargin + PAGE_NUM_WIDTH; 
471                 $footerRow = $this->bottomMargin - FOOTER_MARGIN;
472
473                 // Calling this function generates a new PDF page after the first instance
474 //              {
475 //                      // TODO: experimenting with line drawing to highlight current period
476 //                      $this->SetLineWidth(1);
477 //                      $this->LineTo($this->cols[3], 33, $this->cols[3], 534);
478 //                      $this->LineTo($this->cols[4], 33, $this->cols[4], 534);
479 //                      $this->SetLineWidth(0.1);
480                         
481 //                      $this->newPage();
482 //              }
483                 $this->row = $this->pageHeight - $this->topMargin;
484
485                 // Set the color of dividing lines we'll draw
486                 $oldDrawColor = $this->GetDrawColor();
487                 $this->SetDrawColor(128, 128, 128);
488
489                 // Tell TCPDF that we want to use its alias system to track the total number of pages
490                 $this->AliasNbPages();
491                 
492                 // Footer
493                 if ($this->footerEnable)
494                 {
495                         $this->Line($footerRow, 1);
496                         $prevFontSize = $this->fontSize;
497                         $this->fontSize = FOOTER_FONT_SIZE;
498                         $this->TextWrap($footerCol, $footerRow - ($this->fontSize + 1),
499                                 $pageNumCol - $footerCol, $this->footerText, $align = 'center',
500                                 $border = 0, $fill = 0, $link = NULL, $stretch = 1);
501                         $this->TextWrap($pageNumCol, $footerRow - ($this->fontSize + 1),
502                                 PAGE_NUM_WIDTH, _("Page") . ' ' . $this->pageNumber . '/' . $this->getAliasNbPages(),
503                                 $align = 'right', $border = 0, $fill = 0, $link = NULL, $stretch = 1);
504                         $this->fontSize = $prevFontSize;
505                 }
506
507                 //
508                 // Header
509                 //
510                 
511                 // Print gray line across the page
512                 $this->Line($this->row + 8, 1);
513
514                 $this->NewLine();
515
516                 // Print the report title nice and big
517                 $oldFontSize = $this->fontSize;
518                 $this->fontSize = TITLE_FONT_SIZE;
519                 $this->Font('B');
520                 $this->Text($this->leftMargin, $this->title, $companyCol);
521                 $this->fontSize = HEADER1_FONT_SIZE;
522
523                 // Print company logo if present and requested, or else just print company name
524                 if ($this->companyLogoEnable && ($this->company['coy_logo'] != ''))
525                 {
526                         // Build a string specifying the location of the company logo file
527                         $logo = $comp_path .'/'. user_company() . "/images/" . $this->company['coy_logo'];
528
529                         // Width being zero means that the image will be scaled to the specified height
530                         // keeping its aspect ratio intact.
531                         if ($this->scaleLogoWidth)
532                                 $this->AddImage($logo, $companyCol, $this->row, COMPANY_WIDTH, 0);
533                         else    
534                                 $this->AddImage($logo, $companyCol, $this->row - (LOGO_HEIGHT * LOGO_Y_POS_ADJ_FACTOR), 0, LOGO_HEIGHT);
535                 }
536                 else
537                         $this->Text($companyCol, $this->company['coy_name']);
538
539                 // Dimension 1 - optional
540                 // - only print if available and not blank
541                 if (count($this->params) > 3)
542                         if ($this->params[3]['from'] != '')
543                         {
544                                 $this->NewLine(1, 0, $this->fontSize + 2);
545                                 $str = $this->params[3]['text'] . ':';
546                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
547                                 $str = $this->params[3]['from'];
548                                 $this->Text($headerFieldCol, $str, $companyCol);
549                         }
550
551                 // Dimension 2 - optional
552                 // - only print if available and not blank
553                 if (count($this->params) > 4)
554                         if ($this->params[4]['from'] != '')
555                         {
556                                 $this->NewLine(1, 0, $this->fontSize + 2);
557                                 $str = $this->params[4]['text'] . ':';
558                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
559                                 $str = $this->params[4]['from'];
560                                 $this->Text($headerFieldCol, $str, $companyCol);
561                         }
562
563                 // Tags - optional
564                 // if present, it's an array of tag names
565                 if (count($this->params) > 5)
566                         if ($this->params[5]['from'] != '')
567                         {
568                                 $this->NewLine(1, 0, $this->fontSize + 2);
569                                 $str = $this->params[5]['text'] . ':';
570                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
571                                 $str = '';
572                                 for ($i = 0; $i < count($this->params[5]['from']); $i++)
573                                 {
574                                         if($i != 0)
575                                                 $str .= ', ';
576                                         $str .= $this->params[5]['from'][$i];
577                                 }
578                                 $this->Text($headerFieldCol, $str, $companyCol);
579                         }
580
581                 // Report Date - time period covered
582                 // - can specify a range, or just the end date (and the report contents
583                 //   should make it obvious what the beginning date is)
584                 $this->NewLine(1, 0, $this->fontSize + 2);
585                 $str = _("Report Period") . ':';
586                 $this->Text($this->leftMargin, $str, $headerFieldCol);
587                 $str = '';
588                 if (isset($this->params[1]['from']) && $this->params[1]['from'] != '')
589                         $str = $this->params[1]['from'] . ' - ';
590                 $str .= $this->params[1]['to'];
591                 $this->Text($headerFieldCol, $str, $companyCol);
592
593                 // Turn off Bold
594                 $this->Font();
595                 
596                 $this->NewLine(1, 0, $this->fontSize + 1);
597
598                 // Make the remaining report headings a little less important
599                 $this->fontSize = HEADER2_FONT_SIZE;
600
601                 // Timestamp of when this copy of the report was generated
602                 $str = _("Generated At") . ':';
603                 $this->Text($this->leftMargin, $str, $headerFieldCol);
604                 $str = Today() . '   ' . Now();
605                 if ($this->company['time_zone'])
606                         $str .= ' ' . date('O') . ' GMT';
607                 $this->Text($headerFieldCol, $str, $companyCol);
608
609                 // Name of the user that generated this copy of the report
610                 $this->NewLine(1, 0, $this->fontSize + 1);
611                 $str = _("Generated By") . ':';
612                 $this->Text($this->leftMargin, $str, $headerFieldCol);
613                 $str = $this->user;
614                 $this->Text($headerFieldCol, $str, $companyCol);
615
616                 // Display any user-generated comments for this copy of the report
617                 if ($this->params[0] != '') // Comments
618                 {
619                         $this->NewLine(1, 0, $this->fontSize + 1);
620                         $str = _("Comments") . ':';
621                         $this->Text($this->leftMargin, $str, $headerFieldCol);
622                         $this->Font('B');
623                         $this->Text($headerFieldCol, $this->params[0], $companyCol, 0, 0, 'left', 0, 0, $link=NULL, 1);
624                         $this->Font();
625                 }
626
627                 // Add page numbering to header if footer is turned off
628                 if (!$this->footerEnable)
629                 {
630                         $str = _("Page") . ' ' . $this->pageNumber . '/' . $this->getAliasNbPages();
631                         $this->Text($pageNumCol, $str, 0, 0, 0, 'right', 0, 0, NULL, 1);
632                 }
633                 
634                 // Print gray line across the page
635                 $this->Line($this->row - 5, 1);
636
637                 // Restore font size to user-defined size
638                 $this->fontSize = $oldFontSize;
639
640                 // restore user-specified cell padding for column headers
641                 $this->SetCellPadding($oldcMargin);
642
643                 // scoot down the page a bit
644                 $oldLineHeight = $this->lineHeight;
645                 $this->lineHeight = $this->fontSize + 1;
646                 $this->row -= ($this->lineHeight + 6);
647                 $this->lineHeight = $oldLineHeight;
648
649                 // Print the column headers!
650                 $this->Font('I');
651                 if ($this->headers2 != null)
652                 {
653                         $count = count($this->headers2);
654                         for ($i = 0; $i < $count; $i++)
655                                 $this->TextCol2($i, $i + 1,     $this->headers2[$i], $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1);
656                         $this->NewLine();
657                 }
658                 $count = count($this->headers);
659                 for ($i = 0; $i < $count; $i++)
660                         $this->TextCol($i, $i + 1, $this->headers[$i], $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1);
661                 $this->Font();
662
663                 $this->NewLine(2);
664
665                 // restore user-specified draw color
666                 $this->SetDrawColor($oldDrawColor[0], $oldDrawColor[1], $oldDrawColor[2]);              
667         }
668
669         /**
670          * Format a numeric string date into something nicer looking.
671          *
672          * @param string $date Date string to be formatted.
673          * @param int $input_format Format of the input string.  Possible values are:<ul><li>0: user's default (default)</li></ul>
674          * @param int $output_format Format of the output string.  Possible values are:<ul><li>0: Month (word) Day (numeric), 4-digit Year - Example: January 1, 2000 (default)</li><li>1: Month 4-digit Year - Example: January 2000</li><li>2: Month Abbreviation 4-digit Year - Example: Jan 2000</li></ul>
675          * @access public
676          */
677         function DatePrettyPrint($date, $input_format = 0, $output_format = 0)
678         {
679                 if ($date != '')
680                 {
681                         $date = date2sql($date);
682                         $year = (int) (substr($date, 0, 4));
683                         $month = (int) (substr($date, 5, 2));
684                         $day = (int) (substr($date, 8, 2));
685                         if ($output_format == 0)
686                                 return(date('F j, Y', mktime(12, 0, 0, $month, $day, $year)));
687                         elseif ($output_format == 1)
688                                 return(date('F Y', mktime(12, 0, 0, $month, $day, $year)));
689                         elseif ($output_format == 2)
690                                 return(date('M Y', mktime(12, 0, 0, $month, $day, $year)));
691                 }
692                 else
693                         return $date;
694         }
695
696         function AddImage($logo, $x, $y, $w, $h)
697         {
698                 if (strpos($logo, ".png") || strpos($logo, ".PNG"))
699                         $this->addPngFromFile($logo, $x, $y, $w, $h);
700                 else
701                         $this->addJpegFromFile($logo, $x, $y, $w, $h);
702         }
703
704         // Get current draw color setting from TCPDF object; returns array of RGB numbers
705         function GetDrawColor()
706         {
707                 // Convert the TCPDF stored DrawColor string into an array of strings
708                 $colorFields = explode(' ', $this->DrawColor);
709
710                 // Test last value: G == grayscale, single number; RG == RGB, 3 numbers
711                 if ($colorFields[count($colorFields) - 1] == 'G')
712                         // Convert a grayscale string value to the equivalent RGB value
713                         $drawColor = array((float) $colorFields[0], (float) $colorFields[0], (float) $colorFields[0]);
714                 else
715                         // Convert RGB string values to the a numeric array
716                         $drawColor = array((float) $colorFields[0], (float) $colorFields[1], (float) $colorFields[2]);
717                 
718                 return $drawColor;
719         }
720         
721         function SetDrawColor($r, $g, $b)
722         {
723                 parent::SetDrawColor($r, $g, $b);
724         }
725
726         function SetTextColor($r, $g, $b)
727         {
728                 parent::SetTextColor($r, $g, $b);
729         }
730
731         /**
732      * Set the fill color for table cells.
733      * @see reporting/includes/TCPDF#SetFillColor($col1, $col2, $col3, $col4)
734      */
735         function SetFillColor($r, $g, $b)
736         {
737                 parent::SetFillColor($r, $g, $b);
738         }
739
740         // Get current cell padding setting from TCPDF object
741         function GetCellPadding()
742         {
743                 return $this->cMargin;
744         }
745
746         // Set desired cell padding (aka "cell margin")
747         // Seems to be just left and right margins...
748         function SetCellPadding($pad)
749         {
750                 parent::SetCellPadding($pad);
751         }
752         
753         function Text($c, $txt, $n=0, $corr=0, $r=0, $align='left', $border=0, $fill=0, $link=NULL, $stretch=1)
754         {
755                 if ($n == 0)
756                         $n = $this->pageWidth - $this->rightMargin;
757
758                 return $this->TextWrap($c, $this->row - $r, $n - $c + $corr, $txt, $align, $border, $fill, $link, $stretch);
759         }
760
761         function TextWrap($xpos, $ypos, $len, $str, $align = 'left', $border = 0, $fill = 0, $link = NULL, $stretch = 1)
762         {
763                 if ($this->fontSize != $this->oldFontSize)
764                 {
765                         $this->SetFontSize($this->fontSize);
766                         $this->oldFontSize = $this->fontSize;
767                 }
768                 return $this->addTextWrap($xpos, $ypos, $len, $this->fontSize, $str, $align, $border, $fill, $link, $stretch);
769         }
770
771         function TextCol($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
772         {
773                 return $this->TextWrap($this->cols[$c], $this->row - $r, $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch);
774         }
775         
776         function AmountCol($c, $n, $txt, $dec=0, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1, $color_red=false)
777         {
778                 if ($color_red && $txt < 0)
779                         $this->SetTextColor(255, 0, 0);
780                 $ret = $this->TextCol($c, $n, number_format2($txt, $dec), $corr, $r, $border, $fill, $link, $stretch);
781                 if ($color_red && $txt < 0)
782                         $this->SetTextColor(0, 0, 0);
783                 return $ret;    
784         }
785
786         function AmountCol2($c, $n, $txt, $dec=0, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1, $color_red=false, $amount_locale = 'en_US.UTF-8', $amount_format = '%(!.2n')
787         {
788                 setlocale(LC_MONETARY, $amount_locale);
789                 if ($color_red && $txt < 0)
790                         $this->SetTextColor(255, 0, 0);
791                 $ret = $this->TextCol($c, $n, money_format($amount_format, $txt), $corr, $r, $border, $fill, $link, $stretch);
792                 if ($color_red && $txt < 0)
793                         $this->SetTextColor(0, 0, 0);
794                 return $ret;    
795         }
796         
797         function DateCol($c, $n, $txt, $conv=false, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
798         {
799                 if ($conv)
800                         $txt = sql2date($txt);
801                 return $this->TextCol($c, $n, $txt, $corr, $r, $border, $fill, $link, $stretch);
802         }
803
804         function TextCol2($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
805         {
806                 return $this->TextWrap($this->cols2[$c], $this->row - $r, $this->cols2[$n] - $this->cols2[$c] + $corr, $txt, $this->aligns2[$c], $border, $fill, $link, $stretch);
807         }
808
809         function TextColLines($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
810         {
811                 $this->row -= $r;
812                 $this->TextWrapLines($this->cols[$c], $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch);
813         }
814
815         function TextWrapLines($c, $width, $txt, $align='left', $border=0, $fill=0, $link=NULL, $stretch=1)
816         {
817                 $str = Explode("\n", $txt);
818                 for ($i = 0; $i < count($str); $i++)
819                 {
820                         $l = $str[$i];
821                         do
822                         {
823                                 $l = $this->TextWrap($c, $this->row , $width, $l, $align, $border, $fill, $link, $stretch);
824                                 $this->row -= $this->lineHeight;
825                         }
826                         while ($l != '');
827                 }
828         }
829
830         /**
831          * Expose the underlying calcTextWrap() function in this API.
832          */
833         function TextWrapCalc($txt, $width, $spacebreak=false)
834         {
835                 return $this->calcTextWrap($txt, $width, $spacebreak);
836         }
837         
838         /**
839          * Sets the line drawing style.
840          * 
841          * Takes an associative array as arg so you don't need to specify all values.
842          * 
843          * Array keys:
844          * width (float) - the thickness of the line in user units
845          * cap (string) - the type of cap to put on the line, values can be 'butt','round','square'
846          *    where the diffference between 'square' and 'butt' is that 'square' projects a flat end past the
847          *    end of the line.
848          * join (string) - can be 'miter', 'round', 'bevel'
849          * dash (mixed) - Dash pattern. Is 0 (without dash) or string with series of length values, which are the
850          *        lengths of the on and off dashes. For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...;
851          *        "2,1" is 2 on, 1 off, 2 on, 1 off, ... 
852          * phase (integer) - a modifier on the dash pattern which is used to shift the point at which the pattern starts.
853          * color (array) - draw color.  Format: array(GREY), or array(R,G,B) or array(C,M,Y,K).
854          */
855         function SetLineStyle($style)
856         {
857                 parent::SetLineStyle($style);
858         }
859
860         /**
861          * Sets the line drawing width.
862          */
863         function SetLineWidth($width)
864         {
865                 parent::SetLineWidth($width);
866         }
867         
868         function LineTo($from, $row, $to, $row2)
869         {
870                 parent::line($from, $row, $to, $row2);
871         }
872
873         function Line($row, $height = 0)
874         {
875                 $oldLineWidth = $this->GetLineWidth();
876                 $this->SetLineWidth($height + 1);
877                 parent::line($this->pageWidth - $this->rightMargin, $row ,$this->leftMargin, $row);
878                 $this->SetLineWidth($oldLineWidth);
879         }
880
881         /**
882         * Underlines the contents of a cell, but not the cell padding area.
883         * Primarily useful for the last line before a "totals" line.
884         * @param int $c Column number to underline.
885         * @param int $r Print the underline(s) this number of rows below the current position.  Can be negative in order to go up.
886         * @param int $type Type of underlining to draw.  Possible values are:<ul><li>1: single underline (default)</li><li>2: double underline</li></ul>
887         * @param int $linewidth Thickness of the line to draw.  Default value of zero will use the current line width defined for this document.
888         * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
889         * @access public
890         * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
891         */
892         function UnderlineCell($c, $r = 0, $type = 1, $linewidth = 0, $style = array())
893         {
894                 // If line width was specified, save current setting so we can reset it
895                 if ($linewidth != 0)
896                 {
897                         $oldLineWidth = $this->GetLineWidth();
898                         $this->SetLineWidth($linewidth);
899                 }
900
901                 // Figure out how far down to move the line based on current font size
902                 // Calculate this because printing underline directly at $this->row goes on top
903                 // of the parts of characters that "hang down", like the bottom of commas &
904                 // lowercase letter 'g', etc.
905                 if ($this->fontSize < 10)
906                         $y_adj = 2;
907                 else
908                         $y_adj = 3; 
909                 parent::line($this->cols[$c] + $this->cMargin, $this->row - $r - $y_adj, $this->cols[$c + 1] - $this->cMargin, $this->row - $r - $y_adj, $style);
910
911                 // Double underline, far enough below the first underline so as not to overlap
912                 // the first underline (depends on current line thickness (aka "line width")
913                 if ($type == 2)
914                         parent::line($this->cols[$c] + $this->cMargin, $this->row - $r - $y_adj - ($this->GetLineWidth() + 2), $this->cols[$c + 1] - $this->cMargin, $this->row - $r - $y_adj - ($this->GetLineWidth() + 2), $style);
915
916                 // If line width was specified, reset it back to the original setting
917                 if ($linewidth != 0)
918                         $this->SetLineWidth($oldLineWidth);
919         }
920         
921         function NewLine($l=1, $np=0, $h = NULL)
922         {
923                 // If the line height wasn't specified, use the current setting
924                 if ($h == NULL)
925                         $h = $this->lineHeight;
926
927                 // Move one line down the page
928                 $this->row -= ($l * $h);
929
930                 // Check to see if we're at the bottom and should insert a page break
931                 if ($this->row < $this->bottomMargin + ($np * $h))
932                         $this->NewPage();
933         }
934
935         function NewPage() 
936         {
937                 if ($this->pageNumber==0)
938                 {
939                         // check if there is pdf header template for this report
940                         // and set if it is found
941                         $tmpl_pdf = find_custom_file("/reporting/forms/".$this->headerTmpl.".pdf");
942                         if ($tmpl_pdf) {
943                                 $this->tmplSize = $this->setSourceFile($tmpl_pdf);
944                         }
945                 }
946
947                 $this->pageNumber++;
948                 parent::newPage();
949
950                 if ($this->tmplSize) {
951                         $this->row = $this->pageHeight - $this->topMargin; // reset row
952                         $id = $this->importPage(min($this->pageNumber, $this->tmplSize));
953                         $this->useTemplate($id);
954                 }
955
956                 // include related php file if any
957                 $tmpl_php = find_custom_file("/reporting/forms/".$this->headerTmpl.".php");
958                 if ($tmpl_php) {
959                         include($tmpl_php);
960                 }
961
962                 if (method_exists($this, $this->headerTmpl))    // draw predefined page layout if any
963                         $this->{$this->headerTmpl}();
964         }
965
966         function End($email=0, $subject=null, $myrow=null, $doctype = 0)
967         {
968                 global $pdf_debug, $path_to_root, $comp_path;
969
970                 if ($pdf_debug == 1)
971                 {
972                         $pdfcode = $this->Output('','S');
973                         $pdfcode = str_replace("\n", "\n<br>", htmlspecialchars($pdfcode));
974                         echo '<html><body>';
975                         echo trim($pdfcode);
976                         echo '</body></html>';
977                 }
978                 else
979                 {
980
981                         $dir =  $comp_path.'/'.user_company(). '/pdf_files';
982                         //save the file
983                         if (!file_exists($dir))
984                         {
985                                 mkdir ($dir,0777);
986                         }
987                         // do not use standard filenames or your sensitive company data 
988                         // are world readable
989                         if ($email == 1)
990                                 $fname = $dir.'/'.$this->filename;
991                         else    
992                                 $fname = $dir.'/'.uniqid('').'.pdf';
993                         $this->Output($fname, 'F');
994                         if ($email == 1)
995                         {
996                                 $emailtype = true;
997                                 if ($this->currency != $myrow['curr_code'])
998                                 {
999                                         include("includes/doctext2.inc");
1000                                 }
1001                                 else
1002                                 {
1003                                         include("includes/doctext.inc");
1004                                 }
1005                                 require_once($path_to_root . "/reporting/includes/class.mail.inc");
1006                         $mail = new email(str_replace(",", "", $this->company['coy_name']), $this->company['email']);
1007                                 if (!isset($myrow['email']) || $myrow['email'] == '') 
1008                                         $myrow['email'] = isset($myrow['contact_email']) ? $myrow['contact_email'] : '';
1009                         $to = str_replace(",", "", $myrow['DebtorName']) . " <" . $myrow['email'] . ">";
1010                         $msg = $doc_Dear_Sirs . " " . $myrow['DebtorName'] . ",\n\n" . $doc_AttachedFile . " " . $subject .
1011                                 "\n\n";
1012                                 if (isset($myrow['dimension_id']) && $myrow['dimension_id'] > 0 && $doctype == ST_SALESINVOICE) // helper for payment links
1013                                 {
1014                                         if ($myrow['dimension_id'] == 1)
1015                                         {
1016                                                 $amt = number_format($myrow["ov_freight"] + $myrow["ov_gst"] +  $myrow["ov_amount"], user_price_dec());
1017                                                 $txt = $doc_Payment_Link . " PayPal: ";
1018                                                 $nn = urlencode($this->title . " " . $myrow['reference']);
1019                                                 $url = "https://www.paypal.com/xclick/business=" . $this->company['email'] . "&item_name=" .
1020                                                         $nn . "&amount=" . $amt . "&currency_code=" . $myrow['curr_code'];
1021                                                 $msg .= $txt . $url . "\n\n";
1022                                         }
1023                                 }
1024                         $msg .= $doc_Kindest_regards . "\n\n";
1025                         $sender = $this->user . "\n" . $this->company['coy_name'] . "\n" . $this->company['postal_address'] . "\n" . $this->company['email'] . "\n" . $this->company['phone'];
1026                         $mail->to($to);
1027                         $mail->subject($subject);
1028                         $mail->text($msg . $sender);
1029                         $mail->attachment($fname);
1030                         $ret = $mail->send();
1031                                 if (!$ret)
1032                                         display_error(_("Sending document by email failed"));
1033                                 else
1034                                         display_notification($this->title . " " . $myrow['reference'] . " " 
1035                                                 . _("has been sent by email."));
1036                                 unlink($fname);         
1037                         }
1038                         else
1039                         {
1040                                 $printer = get_report_printer(user_print_profile(), $this->rep_id);
1041                                 if ($printer == false) {
1042                                         if(in_ajax()) {
1043                                                 global $Ajax;
1044
1045                                                 if (user_rep_popup()) 
1046                                                         $Ajax->popup($fname); // when embeded pdf viewer used
1047                                                 else
1048                                                         $Ajax->redirect($fname); // otherwise use faster method
1049                                         } else {
1050                         header('Content-type: application/pdf');
1051                     header("Content-Disposition: inline; filename=$this->filename");
1052                         header('Expires: 0');
1053                     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1054                         header('Pragma: public');
1055
1056                         $this->Stream();
1057                                         }
1058                                 } else { // send report to network printer
1059                                         $prn = new remote_printer($printer['queue'],$printer['host'],
1060                                                 $printer['port'], $printer['timeout']);
1061                                         $error = $prn->print_file($fname);
1062                                         if ($error)
1063                                                 display_error($error);
1064                                         else
1065                                                 display_notification(_('Report has been sent to network printer ').$printer['name']);
1066                                 }
1067                         }
1068                         // first have a look through the directory, 
1069                         // and remove old temporary pdfs
1070                         if ($d = @opendir($dir)) {
1071                                 while (($file = readdir($d)) !== false) {
1072                                         if (!is_file($dir.'/'.$file) || $file == 'index.php') continue;
1073                                 // then check to see if this one is too old
1074                                         $ftime = filemtime($dir.'/'.$file);
1075                                  // seems 3 min is enough for any report download, isn't it?
1076                                         if (time()-$ftime > 180){
1077                                                 unlink($dir.'/'.$file);
1078                                         }
1079                                 }
1080                                 closedir($d);
1081                         }
1082                 }
1083         }
1084 }
1085
1086 ?>