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