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