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