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