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