Merged changes from mai trunk up to 2.3.1
[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                         if (!is_array($contacts[0]))
407                                 $contacts = array($contacts); // change to array when single contact passed
408                         $this->contactData = $contacts;
409                         // as report is currently generated once despite number of email recipients
410                         // we select language for the first recipient as report language
411                         $this->formData['rep_lang'] = $contacts[0]['lang'];
412                 }
413         }
414         /*
415                 Set header handler
416         */
417         function SetHeaderType($name) {
418                 $this->headerTmpl = $name;
419         }
420         /*
421                 Header for sales/purchase documents
422         */
423         function Header2()
424         {
425                 global $path_to_root, $print_as_quote,
426                         $print_invoice_no, $packing_slip, $dflt_lang; // FIXME should be passed as params
427
428                 $doctype = $this->formData['doctype'];
429                 $header2type = true;
430                 
431                 $this->SetLang(@$this->formData['rep_lang'] ? $this->formData['rep_lang'] : $dflt_lang);
432
433                  // leave layout files names without path to enable including
434                  // modified versions from company/x/reporting directory
435                 include("includes/doctext.inc");
436                 include("includes/header2.inc");
437
438                 $this->row = $temp;
439         }
440
441         // Alternate header style which also supports a simple footer
442         function Header3()
443         {
444                 // Turn off cell padding for the main report header, restoring the current setting later
445                 $oldcMargin = $this->cMargin;
446                 $this->SetCellPadding(0);
447
448                 // Set some constants which control header item layout
449                 // only set them once or the PHP interpreter gets angry
450                 if ($this->pageNumber == 1)
451                 {
452                         define('COMPANY_WIDTH', 150);
453                         define('LOGO_HEIGHT', 50);
454                         define('LOGO_Y_POS_ADJ_FACTOR', 0.74);
455                         define('LABEL_WIDTH', 80);
456                         define('PAGE_NUM_WIDTH', 60);
457                         define('TITLE_FONT_SIZE', 14);
458                         define('HEADER1_FONT_SIZE', 10);
459                         define('HEADER2_FONT_SIZE', 9);
460                         define('FOOTER_FONT_SIZE', 10);
461                         define('FOOTER_MARGIN', 4);
462                 }
463                 // Set some variables which control header item layout
464                 $companyCol = $this->endLine - COMPANY_WIDTH;
465                 $headerFieldCol = $this->leftMargin + LABEL_WIDTH;
466                 $pageNumCol = $this->endLine - PAGE_NUM_WIDTH;
467                 $footerCol = $this->leftMargin + PAGE_NUM_WIDTH; 
468                 $footerRow = $this->bottomMargin - FOOTER_MARGIN;
469
470                 // Calling this function generates a new PDF page after the first instance
471 //              {
472 //                      // TODO: experimenting with line drawing to highlight current period
473 //                      $this->SetLineWidth(1);
474 //                      $this->LineTo($this->cols[3], 33, $this->cols[3], 534);
475 //                      $this->LineTo($this->cols[4], 33, $this->cols[4], 534);
476 //                      $this->SetLineWidth(0.1);
477                         
478 //                      $this->newPage();
479 //              }
480                 $this->row = $this->pageHeight - $this->topMargin;
481
482                 // Set the color of dividing lines we'll draw
483                 $oldDrawColor = $this->GetDrawColor();
484                 $this->SetDrawColor(128, 128, 128);
485
486                 // Tell TCPDF that we want to use its alias system to track the total number of pages
487                 $this->AliasNbPages();
488                 
489                 // Footer
490                 if ($this->footerEnable)
491                 {
492                         $this->Line($footerRow, 1);
493                         $prevFontSize = $this->fontSize;
494                         $this->fontSize = FOOTER_FONT_SIZE;
495                         $this->TextWrap($footerCol, $footerRow - ($this->fontSize + 1),
496                                 $pageNumCol - $footerCol, $this->footerText, $align = 'center',
497                                 $border = 0, $fill = 0, $link = NULL, $stretch = 1);
498                         $this->TextWrap($pageNumCol, $footerRow - ($this->fontSize + 1),
499                                 PAGE_NUM_WIDTH, _("Page") . ' ' . $this->pageNumber . '/' . $this->getAliasNbPages(),
500                                 $align = 'right', $border = 0, $fill = 0, $link = NULL, $stretch = 1);
501                         $this->fontSize = $prevFontSize;
502                 }
503
504                 //
505                 // Header
506                 //
507                 
508                 // Print gray line across the page
509                 $this->Line($this->row + 8, 1);
510
511                 $this->NewLine();
512
513                 // Print the report title nice and big
514                 $oldFontSize = $this->fontSize;
515                 $this->fontSize = TITLE_FONT_SIZE;
516                 $this->Font('B');
517                 $this->Text($this->leftMargin, $this->title, $companyCol);
518                 $this->fontSize = HEADER1_FONT_SIZE;
519
520                 // Print company logo if present and requested, or else just print company name
521                 if ($this->companyLogoEnable && ($this->company['coy_logo'] != ''))
522                 {
523                         // Build a string specifying the location of the company logo file
524                         $logo = company_path() . "/images/" . $this->company['coy_logo'];
525
526                         // Width being zero means that the image will be scaled to the specified height
527                         // keeping its aspect ratio intact.
528                         if ($this->scaleLogoWidth)
529                                 $this->AddImage($logo, $companyCol, $this->row, COMPANY_WIDTH, 0);
530                         else    
531                                 $this->AddImage($logo, $companyCol, $this->row - (LOGO_HEIGHT * LOGO_Y_POS_ADJ_FACTOR), 0, LOGO_HEIGHT);
532                 }
533                 else
534                         $this->Text($companyCol, $this->company['coy_name']);
535
536                 // Dimension 1 - optional
537                 // - only print if available and not blank
538                 if (count($this->params) > 3)
539                         if ($this->params[3]['from'] != '')
540                         {
541                                 $this->NewLine(1, 0, $this->fontSize + 2);
542                                 $str = $this->params[3]['text'] . ':';
543                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
544                                 $str = $this->params[3]['from'];
545                                 $this->Text($headerFieldCol, $str, $companyCol);
546                         }
547
548                 // Dimension 2 - optional
549                 // - only print if available and not blank
550                 if (count($this->params) > 4)
551                         if ($this->params[4]['from'] != '')
552                         {
553                                 $this->NewLine(1, 0, $this->fontSize + 2);
554                                 $str = $this->params[4]['text'] . ':';
555                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
556                                 $str = $this->params[4]['from'];
557                                 $this->Text($headerFieldCol, $str, $companyCol);
558                         }
559
560                 // Tags - optional
561                 // if present, it's an array of tag names
562                 if (count($this->params) > 5)
563                         if ($this->params[5]['from'] != '')
564                         {
565                                 $this->NewLine(1, 0, $this->fontSize + 2);
566                                 $str = $this->params[5]['text'] . ':';
567                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
568                                 $str = '';
569                                 for ($i = 0; $i < count($this->params[5]['from']); $i++)
570                                 {
571                                         if($i != 0)
572                                                 $str .= ', ';
573                                         $str .= $this->params[5]['from'][$i];
574                                 }
575                                 $this->Text($headerFieldCol, $str, $companyCol);
576                         }
577
578                 // Report Date - time period covered
579                 // - can specify a range, or just the end date (and the report contents
580                 //   should make it obvious what the beginning date is)
581                 $this->NewLine(1, 0, $this->fontSize + 2);
582                 $str = _("Report Period") . ':';
583                 $this->Text($this->leftMargin, $str, $headerFieldCol);
584                 $str = '';
585                 if (isset($this->params[1]['from']) && $this->params[1]['from'] != '')
586                         $str = $this->params[1]['from'] . ' - ';
587                 $str .= $this->params[1]['to'];
588                 $this->Text($headerFieldCol, $str, $companyCol);
589
590                 // Turn off Bold
591                 $this->Font();
592                 
593                 $this->NewLine(1, 0, $this->fontSize + 1);
594
595                 // Make the remaining report headings a little less important
596                 $this->fontSize = HEADER2_FONT_SIZE;
597
598                 // Timestamp of when this copy of the report was generated
599                 $str = _("Generated At") . ':';
600                 $this->Text($this->leftMargin, $str, $headerFieldCol);
601                 $str = Today() . '   ' . Now();
602                 if ($this->company['time_zone'])
603                         $str .= ' ' . date('O') . ' GMT';
604                 $this->Text($headerFieldCol, $str, $companyCol);
605
606                 // Name of the user that generated this copy of the report
607                 $this->NewLine(1, 0, $this->fontSize + 1);
608                 $str = _("Generated By") . ':';
609                 $this->Text($this->leftMargin, $str, $headerFieldCol);
610                 $str = $this->user;
611                 $this->Text($headerFieldCol, $str, $companyCol);
612
613                 // Display any user-generated comments for this copy of the report
614                 if ($this->params[0] != '') // Comments
615                 {
616                         $this->NewLine(1, 0, $this->fontSize + 1);
617                         $str = _("Comments") . ':';
618                         $this->Text($this->leftMargin, $str, $headerFieldCol);
619                         $this->Font('B');
620                         $this->Text($headerFieldCol, $this->params[0], $companyCol, 0, 0, 'left', 0, 0, $link=NULL, 1);
621                         $this->Font();
622                 }
623
624                 // Add page numbering to header if footer is turned off
625                 if (!$this->footerEnable)
626                 {
627                         $str = _("Page") . ' ' . $this->pageNumber . '/' . $this->getAliasNbPages();
628                         $this->Text($pageNumCol, $str, 0, 0, 0, 'right', 0, 0, NULL, 1);
629                 }
630                 
631                 // Print gray line across the page
632                 $this->Line($this->row - 5, 1);
633
634                 // Restore font size to user-defined size
635                 $this->fontSize = $oldFontSize;
636
637                 // restore user-specified cell padding for column headers
638                 $this->SetCellPadding($oldcMargin);
639
640                 // scoot down the page a bit
641                 $oldLineHeight = $this->lineHeight;
642                 $this->lineHeight = $this->fontSize + 1;
643                 $this->row -= ($this->lineHeight + 6);
644                 $this->lineHeight = $oldLineHeight;
645
646                 // Print the column headers!
647                 $this->Font('I');
648                 if ($this->headers2 != null)
649                 {
650                         $count = count($this->headers2);
651                         for ($i = 0; $i < $count; $i++)
652                                 $this->TextCol2($i, $i + 1,     $this->headers2[$i], $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1);
653                         $this->NewLine();
654                 }
655                 $count = count($this->headers);
656                 for ($i = 0; $i < $count; $i++)
657                         $this->TextCol($i, $i + 1, $this->headers[$i], $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1);
658                 $this->Font();
659
660                 $this->NewLine(2);
661
662                 // restore user-specified draw color
663                 $this->SetDrawColor($oldDrawColor[0], $oldDrawColor[1], $oldDrawColor[2]);              
664         }
665
666         /**
667          * Format a numeric string date into something nicer looking.
668          *
669          * @param string $date Date string to be formatted.
670          * @param int $input_format Format of the input string.  Possible values are:<ul><li>0: user's default (default)</li></ul>
671          * @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>
672          * @access public
673          */
674         function DatePrettyPrint($date, $input_format = 0, $output_format = 0)
675         {
676                 if ($date != '')
677                 {
678                         $date = date2sql($date);
679                         $year = (int) (substr($date, 0, 4));
680                         $month = (int) (substr($date, 5, 2));
681                         $day = (int) (substr($date, 8, 2));
682                         if ($output_format == 0)
683                                 return(date('F j, Y', mktime(12, 0, 0, $month, $day, $year)));
684                         elseif ($output_format == 1)
685                                 return(date('F Y', mktime(12, 0, 0, $month, $day, $year)));
686                         elseif ($output_format == 2)
687                                 return(date('M Y', mktime(12, 0, 0, $month, $day, $year)));
688                 }
689                 else
690                         return $date;
691         }
692
693         function AddImage($logo, $x, $y, $w, $h)
694         {
695                 if (strpos($logo, ".png") || strpos($logo, ".PNG"))
696                         $this->addPngFromFile($logo, $x, $y, $w, $h);
697                 else
698                         $this->addJpegFromFile($logo, $x, $y, $w, $h);
699         }
700
701         // Get current draw color setting from TCPDF object; returns array of RGB numbers
702         function GetDrawColor()
703         {
704                 // Convert the TCPDF stored DrawColor string into an array of strings
705                 $colorFields = explode(' ', $this->DrawColor);
706
707                 // Test last value: G == grayscale, single number; RG == RGB, 3 numbers
708                 if ($colorFields[count($colorFields) - 1] == 'G')
709                         // Convert a grayscale string value to the equivalent RGB value
710                         $drawColor = array((float) $colorFields[0], (float) $colorFields[0], (float) $colorFields[0]);
711                 else
712                         // Convert RGB string values to the a numeric array
713                         $drawColor = array((float) $colorFields[0], (float) $colorFields[1], (float) $colorFields[2]);
714                 
715                 return $drawColor;
716         }
717         
718         // Get current cell padding setting from TCPDF object
719         function GetCellPadding()
720         {
721                 return $this->cMargin;
722         }
723
724         // Set desired cell padding (aka "cell margin")
725         // Seems to be just left and right margins...
726         function SetCellPadding($pad)
727         {
728                 parent::SetCellPadding($pad);
729         }
730         
731         function Text($c, $txt, $n=0, $corr=0, $r=0, $align='left', $border=0, $fill=0, $link=NULL, $stretch=1)
732         {
733                 if ($n == 0)
734                         $n = $this->pageWidth - $this->rightMargin;
735
736                 return $this->TextWrap($c, $this->row - $r, $n - $c + $corr, $txt, $align, $border, $fill, $link, $stretch);
737         }
738
739         function TextWrap($xpos, $ypos, $len, $str, $align = 'left', $border = 0, $fill = 0, $link = NULL, $stretch = 1, $spacebreak=false)
740         {
741                 $str = strtr($str, array("\r"=>''));
742
743                 if ($this->fontSize != $this->oldFontSize)
744                 {
745                         $this->SetFontSize($this->fontSize);
746                         $this->oldFontSize = $this->fontSize;
747                 }
748                 return $this->addTextWrap($xpos, $ypos, $len, $this->fontSize, $str, $align, $border, $fill, $link, $stretch, $spacebreak);
749         }
750
751         function TextCol($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
752         {
753                 return $this->TextWrap($this->cols[$c], $this->row - $r, $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch);
754         }
755         
756         function AmountCol($c, $n, $txt, $dec=0, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1, $color_red=false)
757         {
758                 if ($color_red && $txt < 0)
759                         $this->SetTextColor(255, 0, 0);
760                 $ret = $this->TextCol($c, $n, number_format2($txt, $dec), $corr, $r, $border, $fill, $link, $stretch);
761                 if ($color_red && $txt < 0)
762                         $this->SetTextColor(0, 0, 0);
763                 return $ret;    
764         }
765
766         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')
767         {
768                 setlocale(LC_MONETARY, $amount_locale);
769                 if ($color_red && $txt < 0)
770                         $this->SetTextColor(255, 0, 0);
771                 $ret = $this->TextCol($c, $n, money_format($amount_format, $txt), $corr, $r, $border, $fill, $link, $stretch);
772                 if ($color_red && $txt < 0)
773                         $this->SetTextColor(0, 0, 0);
774                 return $ret;    
775         }
776         
777         function DateCol($c, $n, $txt, $conv=false, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
778         {
779                 if ($conv)
780                         $txt = sql2date($txt);
781                 return $this->TextCol($c, $n, $txt, $corr, $r, $border, $fill, $link, $stretch);
782         }
783
784         function TextCol2($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
785         {
786                 return $this->TextWrap($this->cols2[$c], $this->row - $r, $this->cols2[$n] - $this->cols2[$c] + $corr, $txt, $this->aligns2[$c], $border, $fill, $link, $stretch);
787         }
788
789         function TextColLines($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=0)
790         {
791                 $this->row -= $r;
792                 $this->TextWrapLines($this->cols[$c], $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch, true);
793         }
794
795         function TextWrapLines($c, $width, $txt, $align='left', $border=0, $fill=0, $link=NULL, $stretch=0, $spacebreak=true)
796         {
797                 $str = explode("\n", $txt);
798
799                 for ($i = 0; $i < count($str); $i++)
800                 {
801                         $l = $str[$i];
802                         do
803                         {
804                                 $l = $this->TextWrap($c, $this->row , $width, $l, $align, $border, $fill, $link, $stretch, $spacebreak);
805                                 $this->row -= $this->lineHeight;
806                         }
807                         while ($l != '');
808                 }
809         }
810
811         /**
812          * Expose the underlying calcTextWrap() function in this API.
813          */
814         function TextWrapCalc($txt, $width, $spacebreak=false)
815         {
816                 return $this->calcTextWrap($txt, $width, $spacebreak);
817         }
818         
819         /**
820          * Sets the line drawing style.
821          * 
822          * Takes an associative array as arg so you don't need to specify all values.
823          * 
824          * Array keys:
825          * width (float) - the thickness of the line in user units
826          * cap (string) - the type of cap to put on the line, values can be 'butt','round','square'
827          *    where the diffference between 'square' and 'butt' is that 'square' projects a flat end past the
828          *    end of the line.
829          * join (string) - can be 'miter', 'round', 'bevel'
830          * dash (mixed) - Dash pattern. Is 0 (without dash) or string with series of length values, which are the
831          *        lengths of the on and off dashes. For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...;
832          *        "2,1" is 2 on, 1 off, 2 on, 1 off, ... 
833          * phase (integer) - a modifier on the dash pattern which is used to shift the point at which the pattern starts.
834          * color (array) - draw color.  Format: array(GREY), or array(R,G,B) or array(C,M,Y,K).
835          */
836         function SetLineStyle($style)
837         {
838                 parent::SetLineStyle($style);
839         }
840
841         /**
842          * Sets the line drawing width.
843          */
844         function SetLineWidth($width)
845         {
846                 parent::SetLineWidth($width);
847         }
848         
849         function LineTo($from, $row, $to, $row2)
850         {
851                 parent::line($from, $row, $to, $row2);
852         }
853
854         function Line($row, $height = 0, $dummy1=null, $dummy2=null, $dummy3=null)
855         {
856                 $oldLineWidth = $this->GetLineWidth();
857                 $this->SetLineWidth($height + 1);
858                 parent::line($this->pageWidth - $this->rightMargin, $row ,$this->leftMargin, $row);
859                 $this->SetLineWidth($oldLineWidth);
860         }
861
862         /**
863         * Underlines the contents of a cell, but not the cell padding area.
864         * Primarily useful for the last line before a "totals" line.
865         * @param int $c Column number to underline.
866         * @param int $r Print the underline(s) this number of rows below the current position.  Can be negative in order to go up.
867         * @param int $type Type of underlining to draw.  Possible values are:<ul><li>1: single underline (default)</li><li>2: double underline</li></ul>
868         * @param int $linewidth Thickness of the line to draw.  Default value of zero will use the current line width defined for this document.
869         * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
870         * @access public
871         * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
872         */
873         function UnderlineCell($c, $r = 0, $type = 1, $linewidth = 0, $style = array())
874         {
875                 // If line width was specified, save current setting so we can reset it
876                 if ($linewidth != 0)
877                 {
878                         $oldLineWidth = $this->GetLineWidth();
879                         $this->SetLineWidth($linewidth);
880                 }
881
882                 // Figure out how far down to move the line based on current font size
883                 // Calculate this because printing underline directly at $this->row goes on top
884                 // of the parts of characters that "hang down", like the bottom of commas &
885                 // lowercase letter 'g', etc.
886                 if ($this->fontSize < 10)
887                         $y_adj = 2;
888                 else
889                         $y_adj = 3; 
890                 parent::line($this->cols[$c] + $this->cMargin, $this->row - $r - $y_adj, $this->cols[$c + 1] - $this->cMargin, $this->row - $r - $y_adj, $style);
891
892                 // Double underline, far enough below the first underline so as not to overlap
893                 // the first underline (depends on current line thickness (aka "line width")
894                 if ($type == 2)
895                         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);
896
897                 // If line width was specified, reset it back to the original setting
898                 if ($linewidth != 0)
899                         $this->SetLineWidth($oldLineWidth);
900         }
901         
902         function NewLine($l=1, $np=0, $h = NULL)
903         {
904                 // If the line height wasn't specified, use the current setting
905                 if ($h == NULL)
906                         $h = $this->lineHeight;
907
908                 // Move one line down the page
909                 $this->row -= ($l * $h);
910
911                 // Check to see if we're at the bottom and should insert a page break
912                 if ($this->row < $this->bottomMargin + ($np * $h))
913                         $this->NewPage();
914         }
915
916         function NewPage() 
917         {
918                 if ($this->pageNumber==0)
919                 {
920                         // check if there is pdf header template for this report
921                         // and set if it is found
922                         $tmpl_pdf = find_custom_file("/reporting/forms/".$this->headerTmpl.".pdf");
923                         if ($tmpl_pdf) {
924                                 $this->tmplSize = $this->setSourceFile($tmpl_pdf);
925                         }
926                 }
927
928                 $this->pageNumber++;
929                 parent::newPage();
930
931                 if ($this->tmplSize) {
932                         $this->row = $this->pageHeight - $this->topMargin; // reset row
933                         $id = $this->importPage(min($this->pageNumber, $this->tmplSize));
934                         $this->useTemplate($id);
935                 }
936
937                 // include related php file if any
938                 $tmpl_php = find_custom_file("/reporting/forms/".$this->headerTmpl.".php");
939                 if ($tmpl_php) {
940                         include($tmpl_php);
941                 }
942
943                 if (method_exists($this, $this->headerTmpl))    // draw predefined page layout if any
944                         $this->{$this->headerTmpl}();
945         }
946
947         function End($email=0, $subject=null, $myrow=null, $doctype = 0)
948         {
949                 global $pdf_debug, $path_to_root;
950
951                 if ($pdf_debug == 1)
952                 {
953                         $pdfcode = $this->Output('','S');
954                         $pdfcode = str_replace("\n", "\n<br>", htmlspecialchars($pdfcode));
955                         echo '<html><body>';
956                         echo trim($pdfcode);
957                         echo '</body></html>';
958                 }
959                 else
960                 {
961
962                         $dir =  company_path(). '/pdf_files';
963                         //save the file
964                         if (!file_exists($dir))
965                         {
966                                 mkdir ($dir,0777);
967                         }
968                         // do not use standard filenames or your sensitive company data 
969                         // are world readable
970                         if ($email == 1)
971                                 $fname = $dir.'/'.$this->filename;
972                         else    
973                                 $fname = $dir.'/'.uniqid('').'.pdf';
974                         $this->Output($fname, 'F');
975
976                         if ($email == 1)
977                         {
978                                 if(!count($this->contactData)) {
979                                         $this->SetLang(user_language());
980                                         display_error(_("You have no email contact defined for this type of document"));
981                                 } else {
982                                         $sent = 0;
983                                         foreach($this->contactData as $contact) {
984                                                 if (!isset($contact['email'])) 
985                                                         continue;
986                                                 $emailtype = true;
987                                                 $this->SetLang($contact['lang']);
988                                                 include("includes/doctext.inc");
989
990                                                 require_once($path_to_root . "/reporting/includes/class.mail.inc");
991                                         $mail = new email(str_replace(",", "", $this->company['coy_name']),
992                                                 $this->company['email']);
993                                                 $mail->charset = $this->encoding;
994
995                                         $to = str_replace(",", "", $contact['name'].' '.$contact['name2'])
996                                                 ." <" . $contact['email'] . ">";
997                                         $msg = $doc_Dear_Sirs . " " . $contact['name2'] . ",\n\n" 
998                                                 . $doc_AttachedFile . " " . $subject ."\n\n";
999                                                 if (isset($myrow['dimension_id']) && $myrow['dimension_id'] > 0 && $doctype == ST_SALESINVOICE) // helper for payment links
1000                                                 {
1001                                                         if ($myrow['dimension_id'] == 1)
1002                                                         {
1003                                                                 $amt = number_format($myrow["ov_freight"] + $myrow["ov_gst"] +  $myrow["ov_amount"], user_price_dec());
1004                                                                 $txt = $doc_Payment_Link . " PayPal: ";
1005                                                                 $nn = urlencode($this->title . " " . $myrow['reference']);
1006                                                                 $url = "https://www.paypal.com/xclick/business=" . $this->company['email'] . "&item_name=" .
1007                                                                         $nn . "&amount=" . $amt . "&currency_code=" . $myrow['curr_code'];
1008                                                                 $msg .= $txt . $url . "\n\n";
1009                                                         }
1010                                                 }
1011                                         $msg .= $doc_Kindest_regards . "\n\n";
1012                                         $sender = $this->user . "\n" . $this->company['coy_name'] . "\n" . $this->company['postal_address'] . "\n" . $this->company['email'] . "\n" . $this->company['phone'];
1013                                         $mail->to($to);
1014                                         $mail->subject($subject);
1015                                         $mail->text($msg . $sender);
1016                                         $mail->attachment($fname);
1017                                         if ($mail->send()) $sent++;
1018                                         } // foreach contact
1019                                         unlink($fname);
1020                                         $this->SetLang(user_language());
1021                                         if (!$sent)
1022                                                 display_error(_("Sending document by email failed"));
1023                                         else
1024                                                 display_notification($this->title . " " . $myrow['reference'] . " " 
1025                                                         . _("has been sent by email to destination."));
1026                                 }
1027                         }
1028                         else
1029                         {
1030                                 $printer = get_report_printer(user_print_profile(), $this->rep_id);
1031                                 if ($printer == false) {
1032                                         if (in_ajax()) {
1033                                                 global $Ajax;
1034
1035                                                 if (user_rep_popup()) 
1036                                                         $Ajax->popup($fname); // when embeded pdf viewer used
1037                                                 else
1038                                                         $Ajax->redirect($fname); // otherwise use faster method
1039                                         } else {
1040                                                 header('Content-type: application/pdf');
1041                                                 header('Content-Disposition: inline; filename='.$this->filename);
1042                                                 header('Expires: 0');
1043                                                 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1044                                                 header('Pragma: public');
1045 //                                              $this->Stream(basename($fname));
1046                                                 $this->Stream($this->filename);
1047                                         }
1048                                 } else { // send report to network printer
1049                                         $prn = new remote_printer($printer['queue'],$printer['host'],
1050                                                 $printer['port'], $printer['timeout']);
1051                                         $error = $prn->print_file($fname);
1052                                         if ($error)
1053                                                 display_error($error);
1054                                         else
1055                                                 display_notification(_('Report has been sent to network printer ').$printer['name']);
1056                                 }
1057                         }
1058                         // first have a look through the directory, 
1059                         // and remove old temporary pdfs
1060                         if ($d = @opendir($dir)) {
1061                                 while (($file = readdir($d)) !== false) {
1062                                         if (!is_file($dir.'/'.$file) || $file == 'index.php') continue;
1063                                 // then check to see if this one is too old
1064                                         $ftime = filemtime($dir.'/'.$file);
1065                                  // seems 3 min is enough for any report download, isn't it?
1066                                         if (time()-$ftime > 180){
1067                                                 unlink($dir.'/'.$file);
1068                                         }
1069                                 }
1070                                 closedir($d);
1071                         }
1072                 }
1073         }
1074 }
1075
1076 ?>