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