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