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