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