Option for showing company logo on reports. On company base.
[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                 global $SysPrefs;
300                 
301                 $companyCol = $this->endLine - 150;
302                 $titleCol = $this->leftMargin + 100;
303
304                 $this->row = $this->pageHeight - $this->topMargin;
305
306                 $this->SetDrawColor(128, 128, 128);
307                 $this->Line($this->row + 5, 1);
308
309                 $this->NewLine();
310
311                 $this->fontSize += 4;
312                 $this->Font('bold');
313                 $this->Text($this->leftMargin, $this->title, $companyCol);
314                 $this->Font();
315                 $this->fontSize -= 4;
316                 $logo = company_path() . "/images/" . $this->company['coy_logo'];
317                 if (!empty($SysPrefs->prefs['company_logo_report']) && $this->company['coy_logo'] != '' && file_exists($logo))
318                 {
319                         $this->row -= ($this->lineHeight + 3);
320                         $this->AddImage($logo, $companyCol, $this->row, 0, 30);
321                         $this->row -= 6;
322                 }
323                 else
324                 {
325                         $this->Text($companyCol, $this->company['coy_name']);
326                         $this->row -= ($this->lineHeight + 4);
327                 }
328                 $str = _("Print Out Date") . ':';
329                 $this->Text($this->leftMargin, $str, $titleCol);
330                 $str = Today() . '   ' . Now();
331                 if ($this->company['time_zone'])
332                         $str .= ' ' . date('O') . ' GMT';
333                 $this->Text($titleCol, $str, $companyCol);
334                 $this->Text($companyCol, $this->host);
335
336                 $this->NewLine();
337                 $str = _("Fiscal Year") . ':';
338                 $this->Text($this->leftMargin, $str, $titleCol);
339                 $str = $this->fiscal_year;
340                 $this->Text($titleCol, $str, $companyCol);
341                 $this->Text($companyCol, $this->user);
342                 for ($i = 1; $i < count($this->params); $i++)
343                 {
344                         if ($this->params[$i]['from'] != '')
345                         {
346                                 $this->NewLine();
347                                 $str = $this->params[$i]['text'] . ':';
348                                 $this->Text($this->leftMargin, $str, $titleCol);
349                                 $str = $this->params[$i]['from'];
350                                 if ($this->params[$i]['to'] != '')
351                                         $str .= " - " . $this->params[$i]['to'];
352                                 $this->Text($titleCol, $str, $companyCol);
353                         }
354                 }
355                 if ($this->params[0] != '') // Comments
356                 {
357                         $this->NewLine();
358                         $str = _("Comments") . ':';
359                         $this->Text($this->leftMargin, $str, $titleCol);
360                         $this->Font('bold');
361                         $this->Text($titleCol, $this->params[0], $this->endLine - 35);
362                         $this->Font();
363                 }
364                 $str = _("Page") . ' ' . $this->pageNumber;
365                 $this->Text($this->endLine - 38, $str);
366                 $this->Line($this->row - 5, 1);
367
368                 $this->row -= ($this->lineHeight + 6);
369                 $this->Font('italic');
370                 if ($this->headers2 != null)
371                 {
372                         $count = count($this->headers2);
373                         for ($i = 0; $i < $count; $i++)
374                                 $this->TextCol2($i, $i + 1,     $this->headers2[$i]);
375                         $this->NewLine();
376                 }
377                 $count = count($this->headers);
378                 for ($i = 0; $i < $count; $i++)
379                         $this->TextCol($i, $i + 1, $this->headers[$i]);
380                 $this->Font();
381                 $this->Line($this->row - 5, 1);
382
383                 $this->NewLine(2);
384         }
385         /*
386                 Transition function 
387         */
388         function SetCommonData($myrow, $branch, $sales_order, $bankaccount, $doctype, $contacts)
389         {
390
391                 $this->formData = array();
392                 $datnames = array( 
393                 'myrow' => array('ord_date', 'date_', 'tran_date', 
394                         'order_no','reference', 'id', 'trans_no', 'name', 'location_name',
395                         'delivery_address', 'supp_name', 'address',
396                         'DebtorName', 'supp_account_no', 'wo_ref', 'debtor_ref','type', 'trans_no', 
397                         'StockItemName', 'tax_id', 'order_', 'delivery_date', 'units_issued',
398                         'due_date', 'required_by', 'payment_terms', 'curr_code',
399                         'ov_freight', 'ov_gst', 'ov_amount', 'prepaid', 'requisition_no', 'contact'),
400                 'branch' => array('br_address', 'br_name', 'salesman', 'disable_branch'),
401                 'sales_order' => array('deliver_to', 'delivery_address', 'customer_ref'),
402                 'bankaccount' => array('bank_name', 'bank_account_number', 'payment_service')
403                 );
404
405                 foreach($datnames as $var => $fields) {
406                         if (isset($$var)) {
407                                 foreach($fields as $locname) {
408                                         if (isset(${$var}[$locname]) && (${$var}[$locname]!==null)) {
409                                                 $this->formData[$locname] = ${$var}[$locname];
410                                         }
411                                 }
412                         }
413                 }
414                 $this->formData['doctype'] = $doctype;
415                 $this->formData['document_amount'] = @$this->formData['ov_amount']+@$this->formData['ov_freight']+@$this->formData['ov_gst'];
416                 if (count($contacts)) {
417                         if (!is_array($contacts[0]))
418                                 $contacts = array($contacts); // change to array when single contact passed
419                         $this->contactData = $contacts;
420                         // as report is currently generated once despite number of email recipients
421                         // we select language for the first recipient as report language
422                         $this->formData['rep_lang'] = $contacts[0]['lang'];
423                 }
424         }
425         /*
426                 Set header handler
427         */
428         function SetHeaderType($name) {
429                 $this->headerTmpl = $name;
430         }
431         /*
432                 Header for sales/purchase documents
433         */
434         function Header2()
435         {
436                 global $dflt_lang; // FIXME should be passed as params
437
438                 $this->SetLang(@$this->formData['rep_lang'] ? $this->formData['rep_lang'] : $dflt_lang);
439                 $doctype = $this->formData['doctype'];
440                 $header2type = true;
441
442                 $lang = user_language();
443                 $this->SetLang(@$this->formData['rep_lang'] ? $this->formData['rep_lang']
444                         : ( $lang ? $lang : $dflt_lang));
445
446                  // leave layout files names without path to enable including
447                  // modified versions from company/x/reporting directory
448                 include("includes/doctext.inc");
449                 include("includes/header2.inc");
450
451                 $this->row = $temp;
452         }
453
454         // Alternate header style which also supports a simple footer
455         function Header3()
456         {
457                 // Turn off cell padding for the main report header, restoring the current setting later
458                 $oldcMargin = $this->cMargin;
459                 $this->SetCellPadding(0);
460
461                 // Set some constants which control header item layout
462                 // only set them once or the PHP interpreter gets angry
463                 if ($this->pageNumber == 1)
464                 {
465                         define('COMPANY_WIDTH', 150);
466                         define('LOGO_HEIGHT', 50);
467                         define('LOGO_Y_POS_ADJ_FACTOR', 0.74);
468                         define('LABEL_WIDTH', 80);
469                         define('PAGE_NUM_WIDTH', 60);
470                         define('TITLE_FONT_SIZE', 14);
471                         define('HEADER1_FONT_SIZE', 10);
472                         define('HEADER2_FONT_SIZE', 9);
473                         define('FOOTER_FONT_SIZE', 10);
474                         define('FOOTER_MARGIN', 4);
475                 }
476                 // Set some variables which control header item layout
477                 $companyCol = $this->endLine - COMPANY_WIDTH;
478                 $headerFieldCol = $this->leftMargin + LABEL_WIDTH;
479                 $pageNumCol = $this->endLine - PAGE_NUM_WIDTH;
480                 $footerCol = $this->leftMargin + PAGE_NUM_WIDTH; 
481                 $footerRow = $this->bottomMargin - FOOTER_MARGIN;
482
483                 $this->row = $this->pageHeight - $this->topMargin;
484
485                 // Set the color of dividing lines we'll draw
486                 $oldDrawColor = $this->GetDrawColor();
487                 $this->SetDrawColor(128, 128, 128);
488
489                 // Tell TCPDF that we want to use its alias system to track the total number of pages
490                 $this->AliasNbPages();
491                 
492                 // Footer
493                 if ($this->footerEnable)
494                 {
495                         $this->Line($footerRow, 1);
496                         $prevFontSize = $this->fontSize;
497                         $this->fontSize = FOOTER_FONT_SIZE;
498                         $this->TextWrap($footerCol, $footerRow - ($this->fontSize + 1),
499                                 $pageNumCol - $footerCol, $this->footerText, $align = 'center',
500                                 $border = 0, $fill = 0, $link = NULL, $stretch = 1);
501                         $this->TextWrap($pageNumCol, $footerRow - ($this->fontSize + 1),
502                                 PAGE_NUM_WIDTH, _("Page") . ' ' . $this->pageNumber . '/' . $this->getAliasNbPages(),
503                                 $align = 'right', $border = 0, $fill = 0, $link = NULL, $stretch = 1);
504                         $this->fontSize = $prevFontSize;
505                 }
506
507                 //
508                 // Header
509                 //
510                 
511                 // Print gray line across the page
512                 $this->Line($this->row + 8, 1);
513
514                 $this->NewLine();
515
516                 // Print the report title nice and big
517                 $oldFontSize = $this->fontSize;
518                 $this->fontSize = TITLE_FONT_SIZE;
519                 $this->Font('B');
520                 $this->Text($this->leftMargin, $this->title, $companyCol);
521                 $this->fontSize = HEADER1_FONT_SIZE;
522
523                 // Print company logo if present and requested, or else just print company name
524                 // Build a string specifying the location of the company logo file
525                 $logo = company_path() . "/images/" . $this->company['coy_logo'];
526                 if ($this->companyLogoEnable && ($this->company['coy_logo'] != '') && file_exists($logo))
527                 {
528                         // Width being zero means that the image will be scaled to the specified height
529                         // keeping its aspect ratio intact.
530                         if ($this->scaleLogoWidth)
531                                 $this->AddImage($logo, $companyCol, $this->row + 15, COMPANY_WIDTH, 0);
532                         else    
533                                 $this->AddImage($logo, $companyCol, $this->row - (LOGO_HEIGHT * LOGO_Y_POS_ADJ_FACTOR), 0, LOGO_HEIGHT);
534                 }
535                 else
536                         $this->Text($companyCol, $this->company['coy_name']);
537
538                 // Dimension 1 - optional
539                 // - only print if available and not blank
540                 if (count($this->params) > 3)
541                         if ($this->params[3]['from'] != '')
542                         {
543                                 $this->NewLine(1, 0, $this->fontSize + 2);
544                                 $str = $this->params[3]['text'] . ':';
545                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
546                                 $str = $this->params[3]['from'];
547                                 $this->Text($headerFieldCol, $str, $companyCol);
548                         }
549
550                 // Dimension 2 - optional
551                 // - only print if available and not blank
552                 if (count($this->params) > 4)
553                         if ($this->params[4]['from'] != '')
554                         {
555                                 $this->NewLine(1, 0, $this->fontSize + 2);
556                                 $str = $this->params[4]['text'] . ':';
557                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
558                                 $str = $this->params[4]['from'];
559                                 $this->Text($headerFieldCol, $str, $companyCol);
560                         }
561
562                 // Tags - optional
563                 // if present, it's an array of tag names
564                 if (count($this->params) > 5)
565                         if ($this->params[5]['from'] != '')
566                         {
567                                 $this->NewLine(1, 0, $this->fontSize + 2);
568                                 $str = $this->params[5]['text'] . ':';
569                                 $this->Text($this->leftMargin, $str, $headerFieldCol);
570                                 $str = '';
571                                 for ($i = 0; $i < count($this->params[5]['from']); $i++)
572                                 {
573                                         if($i != 0)
574                                                 $str .= ', ';
575                                         $str .= $this->params[5]['from'][$i];
576                                 }
577                                 $this->Text($headerFieldCol, $str, $companyCol);
578                         }
579
580                 // Report Date - time period covered
581                 // - can specify a range, or just the end date (and the report contents
582                 //   should make it obvious what the beginning date is)
583                 $this->NewLine(1, 0, $this->fontSize + 2);
584                 $str = _("Report Period") . ':';
585                 $this->Text($this->leftMargin, $str, $headerFieldCol);
586                 $str = '';
587                 if (isset($this->params[1]['from']) && $this->params[1]['from'] != '')
588                         $str = $this->params[1]['from'] . ' - ';
589                 $str .= $this->params[1]['to'];
590                 $this->Text($headerFieldCol, $str, $companyCol);
591
592                 // Turn off Bold
593                 $this->Font();
594                 
595                 $this->NewLine(1, 0, $this->fontSize + 1);
596
597                 // Make the remaining report headings a little less important
598                 $this->fontSize = HEADER2_FONT_SIZE;
599
600                 // Timestamp of when this copy of the report was generated
601                 $str = _("Generated At") . ':';
602                 $this->Text($this->leftMargin, $str, $headerFieldCol);
603                 $str = Today() . '   ' . Now();
604                 if ($this->company['time_zone'])
605                         $str .= ' ' . date('O') . ' GMT';
606                 $this->Text($headerFieldCol, $str, $companyCol);
607
608                 // Name of the user that generated this copy of the report
609                 $this->NewLine(1, 0, $this->fontSize + 1);
610                 $str = _("Generated By") . ':';
611                 $this->Text($this->leftMargin, $str, $headerFieldCol);
612                 $str = $this->user;
613                 $this->Text($headerFieldCol, $str, $companyCol);
614
615                 // Display any user-generated comments for this copy of the report
616                 if ($this->params[0] != '') // Comments
617                 {
618                         $this->NewLine(1, 0, $this->fontSize + 1);
619                         $str = _("Comments") . ':';
620                         $this->Text($this->leftMargin, $str, $headerFieldCol);
621                         $this->Font('B');
622                         $this->Text($headerFieldCol, $this->params[0], $companyCol, 0, 0, 'left', 0, 0, $link=NULL, 1);
623                         $this->Font();
624                 }
625
626                 // Add page numbering to header if footer is turned off
627                 if (!$this->footerEnable)
628                 {
629                         $str = _("Page") . ' ' . $this->pageNumber . '/' . $this->getAliasNbPages();
630                         $this->Text($pageNumCol, $str, 0, 0, 0, 'right', 0, 0, NULL, 1);
631                 }
632                 
633                 // Print gray line across the page
634                 $this->Line($this->row - 5, 1);
635
636                 // Restore font size to user-defined size
637                 $this->fontSize = $oldFontSize;
638
639                 // restore user-specified cell padding for column headers
640                 $this->SetCellPadding($oldcMargin);
641
642                 // scoot down the page a bit
643                 $oldLineHeight = $this->lineHeight;
644                 $this->lineHeight = $this->fontSize + 1;
645                 $this->row -= ($this->lineHeight + 6);
646                 $this->lineHeight = $oldLineHeight;
647
648                 // Print the column headers!
649                 $this->Font('I');
650                 if ($this->headers2 != null)
651                 {
652                         $count = count($this->headers2);
653                         for ($i = 0; $i < $count; $i++)
654                                 $this->TextCol2($i, $i + 1,     $this->headers2[$i], $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1);
655                         $this->NewLine();
656                 }
657                 $count = count($this->headers);
658                 for ($i = 0; $i < $count; $i++)
659                         $this->TextCol($i, $i + 1, $this->headers[$i], $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1);
660                 $this->Font();
661
662                 $this->NewLine(2);
663
664                 // restore user-specified draw color
665                 $this->SetDrawColor($oldDrawColor[0], $oldDrawColor[1], $oldDrawColor[2]);              
666         }
667
668         /**
669          * Format a numeric string date into something nicer looking.
670          *
671          * @param string $date Date string to be formatted.
672          * @param int $input_format Format of the input string.  Possible values are:<ul><li>0: user's default (default)</li></ul>
673          * @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>
674          * @access public
675          */
676         function DatePrettyPrint($date, $input_format = 0, $output_format = 0)
677         {
678                 if ($date != '')
679                 {
680                         $date = date2sql($date);
681                         $year = (int) (substr($date, 0, 4));
682                         $month = (int) (substr($date, 5, 2));
683                         $day = (int) (substr($date, 8, 2));
684                         if ($output_format == 0)
685                                 return(date('F j, Y', mktime(12, 0, 0, $month, $day, $year)));
686                         elseif ($output_format == 1)
687                                 return(date('F Y', mktime(12, 0, 0, $month, $day, $year)));
688                         elseif ($output_format == 2)
689                                 return(date('M Y', mktime(12, 0, 0, $month, $day, $year)));
690                 }
691                 else
692                         return $date;
693         }
694
695         function AddImage($logo, $x, $y, $w, $h)
696         {
697                 if (strpos($logo, ".png") || strpos($logo, ".PNG"))
698                         $this->addPngFromFile($logo, $x, $y, $w, $h);
699                 else
700                         $this->addJpegFromFile($logo, $x, $y, $w, $h);
701         }
702
703         // Get current draw color setting from TCPDF object; returns array of RGB numbers
704         function GetDrawColor()
705         {
706                 // Convert the TCPDF stored DrawColor string into an array of strings
707                 $colorFields = explode(' ', $this->DrawColor);
708
709                 // Test last value: G == grayscale, single number; RG == RGB, 3 numbers
710                 if ($colorFields[count($colorFields) - 1] == 'G')
711                         // Convert a grayscale string value to the equivalent RGB value
712                         $drawColor = array((float) $colorFields[0], (float) $colorFields[0], (float) $colorFields[0]);
713                 else
714                         // Convert RGB string values to the a numeric array
715                         $drawColor = array((float) $colorFields[0], (float) $colorFields[1], (float) $colorFields[2]);
716                 
717                 return $drawColor;
718         }
719         
720         // Get current cell padding setting from TCPDF object
721         function GetCellPadding()
722         {
723                 return $this->cMargin;
724         }
725
726         // Set desired cell padding (aka "cell margin")
727         // Seems to be just left and right margins...
728         function SetCellPadding($pad)
729         {
730                 parent::SetCellPadding($pad);
731         }
732         
733         function Text($c, $txt, $n=0, $corr=0, $r=0, $align='left', $border=0, $fill=0, $link=NULL, $stretch=1)
734         {
735                 if ($n == 0)
736                         $n = $this->pageWidth - $this->rightMargin;
737
738                 return $this->TextWrap($c, $this->row - $r, $n - $c + $corr, $txt, $align, $border, $fill, $link, $stretch);
739         }
740
741         function TextWrap($xpos, $ypos, $len, $str, $align = 'left', $border = 0, $fill = 0, $link = NULL, $stretch = 1, $spacebreak=false)
742         {
743                 $str = strtr($str, array("\r"=>''));
744
745                 if ($this->fontSize != $this->oldFontSize)
746                 {
747                         $this->SetFontSize($this->fontSize);
748                         $this->oldFontSize = $this->fontSize;
749                 }
750                 return $this->addTextWrap($xpos, $ypos, $len, $this->fontSize, $str, $align, $border, $fill, $link, $stretch, $spacebreak);
751         }
752
753         function TextCol($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
754         {
755                 return $this->TextWrap($this->cols[$c], $this->row - $r, $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch);
756         }
757         
758         function AmountCol($c, $n, $txt, $dec=0, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1, $color_red=false)
759         {
760                 if ($color_red && $txt < 0)
761                         $this->SetTextColor(255, 0, 0);
762                 $ret = $this->TextCol($c, $n, number_format2($txt, $dec), $corr, $r, $border, $fill, $link, $stretch);
763                 if ($color_red && $txt < 0)
764                         $this->SetTextColor(0, 0, 0);
765                 return $ret;    
766         }
767
768         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')
769         {
770                 setlocale(LC_MONETARY, $amount_locale);
771                 if ($color_red && $txt < 0)
772                         $this->SetTextColor(255, 0, 0);
773                 $ret = $this->TextCol($c, $n, money_format($amount_format, $txt), $corr, $r, $border, $fill, $link, $stretch);
774                 if ($color_red && $txt < 0)
775                         $this->SetTextColor(0, 0, 0);
776                 return $ret;    
777         }
778         
779         function DateCol($c, $n, $txt, $conv=false, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
780         {
781                 if ($conv)
782                         $txt = sql2date($txt);
783                 return $this->TextCol($c, $n, $txt, $corr, $r, $border, $fill, $link, $stretch);
784         }
785
786         function TextCol2($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
787         {
788                 return $this->TextWrap($this->cols2[$c], $this->row - $r, $this->cols2[$n] - $this->cols2[$c] + $corr, $txt, $this->aligns2[$c], $border, $fill, $link, $stretch);
789         }
790
791         function TextColLines($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=0)
792         {
793                 $this->row -= $r;
794                 $this->TextWrapLines($this->cols[$c], $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch, true);
795         }
796
797         function TextWrapLines($c, $width, $txt, $align='left', $border=0, $fill=0, $link=NULL, $stretch=0, $spacebreak=true)
798         {
799                 $str = explode("\n", $txt);
800
801                 for ($i = 0; $i < count($str); $i++)
802                 {
803                         $l = $str[$i];
804                         do
805                         {
806                                 $l = $this->TextWrap($c, $this->row , $width, $l, $align, $border, $fill, $link, $stretch, $spacebreak);
807                                 $this->row -= $this->lineHeight;
808                         }
809                         while ($l != '');
810                 }
811         }
812
813         /**
814          * Expose the underlying calcTextWrap() function in this API.
815          */
816         function TextWrapCalc($txt, $width, $spacebreak=false)
817         {
818                 return $this->calcTextWrap($txt, $width, $spacebreak);
819         }
820         
821         /**
822          * Sets the line drawing style.
823          * 
824          * Takes an associative array as arg so you don't need to specify all values.
825          * 
826          * Array keys:
827          * width (float) - the thickness of the line in user units
828          * cap (string) - the type of cap to put on the line, values can be 'butt','round','square'
829          *    where the diffference between 'square' and 'butt' is that 'square' projects a flat end past the
830          *    end of the line.
831          * join (string) - can be 'miter', 'round', 'bevel'
832          * dash (mixed) - Dash pattern. Is 0 (without dash) or string with series of length values, which are the
833          *        lengths of the on and off dashes. For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...;
834          *        "2,1" is 2 on, 1 off, 2 on, 1 off, ... 
835          * phase (integer) - a modifier on the dash pattern which is used to shift the point at which the pattern starts.
836          * color (array) - draw color.  Format: array(GREY), or array(R,G,B) or array(C,M,Y,K).
837          */
838         function SetLineStyle($style)
839         {
840                 parent::SetLineStyle($style);
841         }
842
843         /**
844          * Sets the line drawing width.
845          */
846         function SetLineWidth($width)
847         {
848                 parent::SetLineWidth($width);
849         }
850         
851         function LineTo($from, $row, $to, $row2)
852         {
853                 parent::line($from, $row, $to, $row2);
854         }
855
856         function Line($row, $height = 0, $dummy1=null, $dummy2=null, $dummy3=null)
857         {
858                 $oldLineWidth = $this->GetLineWidth();
859                 $this->SetLineWidth($height + 1);
860                 parent::line($this->pageWidth - $this->rightMargin, $row ,$this->leftMargin, $row);
861                 $this->SetLineWidth($oldLineWidth);
862         }
863
864         /**
865         * Underlines the contents of a cell, but not the cell padding area.
866         * Primarily useful for the last line before a "totals" line.
867         * @param int $c Column number to underline.
868         * @param int $r Print the underline(s) this number of rows below the current position.  Can be negative in order to go up.
869         * @param int $type Type of underlining to draw.  Possible values are:<ul><li>1: single underline (default)</li><li>2: double underline</li></ul>
870         * @param int $linewidth Thickness of the line to draw.  Default value of zero will use the current line width defined for this document.
871         * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array).
872         * @access public
873         * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
874         */
875         function UnderlineCell($c, $r = 0, $type = 1, $linewidth = 0, $style = array())
876         {
877                 // If line width was specified, save current setting so we can reset it
878                 if ($linewidth != 0)
879                 {
880                         $oldLineWidth = $this->GetLineWidth();
881                         $this->SetLineWidth($linewidth);
882                 }
883
884                 // Figure out how far down to move the line based on current font size
885                 // Calculate this because printing underline directly at $this->row goes on top
886                 // of the parts of characters that "hang down", like the bottom of commas &
887                 // lowercase letter 'g', etc.
888                 if ($this->fontSize < 10)
889                         $y_adj = 2;
890                 else
891                         $y_adj = 3; 
892                 parent::line($this->cols[$c] + $this->cMargin, $this->row - $r - $y_adj, $this->cols[$c + 1] - $this->cMargin, $this->row - $r - $y_adj, $style);
893
894                 // Double underline, far enough below the first underline so as not to overlap
895                 // the first underline (depends on current line thickness (aka "line width")
896                 if ($type == 2)
897                         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);
898
899                 // If line width was specified, reset it back to the original setting
900                 if ($linewidth != 0)
901                         $this->SetLineWidth($oldLineWidth);
902         }
903         
904         function NewLine($l=1, $np=0, $h = NULL)
905         {
906                 // If the line height wasn't specified, use the current setting
907                 if ($h == NULL)
908                         $h = $this->lineHeight;
909
910                 // Move one line down the page
911                 $this->row -= ($l * $h);
912
913                 // Check to see if we're at the bottom and should insert a page break
914                 if ($this->row < $this->bottomMargin + ($np * $h))
915                         $this->NewPage();
916         }
917
918         function NewPage() 
919         {
920                 if ($this->pageNumber==0)
921                 {
922                         // check if there is pdf header template for this report
923                         // and set if it is found
924                         $tmpl_pdf = find_custom_file("/reporting/forms/".$this->headerTmpl.".pdf");
925                         if ($tmpl_pdf) {
926                                 $this->tmplSize = $this->setSourceFile($tmpl_pdf);
927                         }
928                 }
929
930                 $this->pageNumber++;
931                 parent::newPage();
932
933                 if ($this->tmplSize) {
934                         $this->row = $this->pageHeight - $this->topMargin; // reset row
935                         $id = $this->importPage(min($this->pageNumber, $this->tmplSize));
936                         $this->useTemplate($id);
937                 }
938
939                 // include related php file if any
940                 $tmpl_php = find_custom_file("/reporting/forms/".$this->headerTmpl.".php");
941                 if ($tmpl_php) {
942                         include($tmpl_php);
943                 }
944
945                 if (method_exists($this, $this->headerTmpl))    // draw predefined page layout if any
946                         $this->{$this->headerTmpl}();
947         }
948
949         function End($email=0, $subject='')
950         {
951                 global $SysPrefs, $path_to_root;
952
953                 if ($SysPrefs->pdf_debug == 1)
954                 {
955                         $pdfcode = $this->Output('','S');
956                         $pdfcode = str_replace("\n", "\n<br>", html_specials_encode($pdfcode));
957                         echo '<html><body>';
958                         echo trim($pdfcode);
959                         echo '</body></html>';
960                 }
961                 else
962                 {
963                         $dir =  company_path(). '/pdf_files';
964                         //save the file
965                         if (!file_exists($dir))
966                         {
967                                 mkdir ($dir,0777);
968                         }
969                         // do not use standard filenames or your sensitive company data 
970                         // are world readable
971                         $fname = $dir.'/'.random_id().'.pdf';
972                         $this->Output($fname, 'F');
973
974                         if ($email == 1)
975                         {
976                                 $contactData = array();
977                                 if ($this->contactData)
978                                         foreach($this->contactData as $contact)
979                                                 if (!empty($contact['email']))
980                                                         $contactData[] = $contact;
981
982                                 if(!count($contactData)) {
983                                         $this->SetLang(user_language());
984                                         display_warning(sprintf(_("You have no email contact defined for this type of document for '%s'."), $this->formData['recipient_name']));
985                                 } else {
986                                         $sent = $try = 0;
987                                         $emails = "";
988                                         if(!$subject)
989                                                 $subject = $this->formData['document_name'] . ' '. $this->formData['document_number'];
990                                         foreach($contactData as $contact) {
991                                                 if (!isset($contact['email'])) 
992                                                         continue;
993                                                 $emailtype = true;
994                                                 $this->SetLang($contact['lang']);
995
996                                                 require_once($path_to_root . "/reporting/includes/class.mail.inc");
997                                         $mail = new email(str_replace(",", "", $this->company['coy_name']),
998                                                 $this->company['email']);
999                                                 $mail->charset = $this->encoding;
1000
1001                                         $to = str_replace(",", "", $contact['name'].' '.$contact['name2'])
1002                                                 ." <" . $contact['email'] . ">";
1003                                         $msg = _("Dear") . " " . $contact['name2'] . ",\n\n" 
1004                                                 . _("Attached you will find ") . " " . $subject ."\n\n";
1005
1006                                                 if (isset($this->formData['payment_service']))
1007                                                 {
1008                                                         $amt = number_format($this->formData['document_amount'], user_price_dec());
1009                                                         $service = $this->formData['payment_service'];
1010                                                         $url = payment_link($service, array(
1011                                                                         'company_email' => $this->company['email'],
1012                                                                         'amount' => $amt,
1013                                                                         'currency' => $this->formData['curr_code'],
1014                                                                         'comment' => $this->title . " " . $this->formData['document_number']
1015                                                                         ));
1016                                                         if ($url)
1017                                                                 $msg.= _("You can pay through"). " $service: $url\n\n";
1018                                                 }
1019
1020                                         $msg .= _("Kindest regards") . "\n\n";
1021                                         $sender = $this->user . "\n" . $this->company['coy_name'] . "\n" . $this->company['postal_address'] . "\n" . $this->company['email'] . "\n" . $this->company['phone'];
1022                                         $mail->to($to); $try++;
1023                                         $mail->subject($subject);
1024                                         $mail->text($msg . $sender);
1025                                         $mail->attachment($fname, $this->filename);
1026                                         $emails .= " " . $contact['email'];
1027                                         if ($mail->send()) $sent++;
1028                                         } // foreach contact
1029                                         unlink($fname);
1030                                         $this->SetLang(user_language());
1031                                         if (!$try) {
1032                                                 display_warning(sprintf(_("You have no email contact defined for this type of document for '%s'."), $this->formData['recipient_name']));
1033                                         } elseif (!$sent)
1034                                                 display_warning($this->title . " " . $this->formData['document_number'] . ". "
1035                                                         . _("Sending document by email failed") . ". " . _("Email:") . $emails);
1036                                         else
1037                                                 display_notification($this->title . " " . $this->formData['document_number'] . " " 
1038                                                         . _("has been sent by email to destination.") . " " . _("Email:") . $emails);
1039                                 }
1040                         }
1041                         else
1042                         {
1043                                 $printer = get_report_printer(user_print_profile(), $this->rep_id);
1044                                 if ($printer == false) {
1045                                         if (in_ajax()) {
1046                                                 global $Ajax;
1047
1048                                                 if (user_rep_popup()) 
1049                                                         $Ajax->popup($fname); // when embeded pdf viewer used
1050                                                 else
1051                                                         $Ajax->redirect($fname); // otherwise use faster method
1052                                         } else {
1053                                                 header('Content-type: application/pdf');
1054                                                 header('Content-Disposition: inline; filename='.$this->filename);
1055                                                 header('Expires: 0');
1056                                                 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1057                                                 header('Pragma: public');
1058                                                 $this->Stream($this->filename);
1059                                         }
1060                                 } else { // send report to network printer
1061                                         $prn = new remote_printer($printer['queue'],$printer['host'],
1062                                                 $printer['port'], $printer['timeout']);
1063                                         $error = $prn->print_file($fname);
1064                                         if ($error)
1065                                                 display_error($error);
1066                                         else
1067                                                 display_notification(_('Report has been sent to network printer ').$printer['name']);
1068                                 }
1069                         }
1070                         // first have a look through the directory, 
1071                         // and remove old temporary pdfs
1072                         if ($d = @opendir($dir)) {
1073                                 while (($file = readdir($d)) !== false) {
1074                                         if (!is_file($dir.'/'.$file) || $file == 'index.php') continue;
1075                                 // then check to see if this one is too old
1076                                         $ftime = filemtime($dir.'/'.$file);
1077                                  // seems 3 min is enough for any report download, isn't it?
1078                                         if (time()-$ftime > 180){
1079                                                 unlink($dir.'/'.$file);
1080                                         }
1081                                 }
1082                                 closedir($d);
1083                         }
1084                 }
1085         }
1086 }
1087