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