[0005735] Problems with sending emails with encoding other than ASCII - fixed.
[fa-stable.git] / reporting / includes / pdf_report.inc
index 627031f587f550923034774d4bb72b339bef9499..a803fe3f9a640a030b8f7208d16400a8d5c00d5d 100644 (file)
@@ -9,12 +9,24 @@
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
 ***********************************************************************/
-//include_once($path_to_root . "reporting/includes/class.pdf.inc");
+/*
+       TODO:
+       . add StartReport/EndReport handlers for better bulk report support, with
+       . email/printer destination option should be selected on class creation instead
+        of End()
+       . add/use setter function for Header2 parameters (currently passed globally)
+       . in report files pass already prepared options to SetCommonData() to avoid need for
+        selection inside FrontReport generic class.
+*/
 include_once(dirname(__FILE__)."/class.pdf.inc");
 include_once(dirname(__FILE__)."/printer_class.inc");
+include_once($path_to_root . "/reporting/includes/reporting.inc");
 include_once($path_to_root . "/admin/db/company_db.inc");
+include_once($path_to_root . "/admin/db/fiscalyears_db.inc");
 include_once($path_to_root . "/admin/db/printers_db.inc");
+include_once($path_to_root . "/includes/ui/ui_globals.inc");
 include_once($path_to_root . "/config.php");
+
 class FrontReport extends Cpdf
 {
        var $size;
@@ -34,6 +46,7 @@ class FrontReport extends Cpdf
        var $lineHeight;
        //var $rtl;
 
+       var $row;
        var $cols;
        var $params;
        var $headers;
@@ -49,11 +62,21 @@ class FrontReport extends Cpdf
        var $scaleLogoWidth;
        var $footerEnable;  // select whether to print a page footer or not
        var $footerText;  // store user-generated footer text
-       var $headerFunc;  // store the name of the currently selected header function
+       var $headerTmpl;  // store the name of the currently selected header template
+       var $tmplSize; // pdf header template size in pages
 
-       function FrontReport($title, $filename, $size = 'A4', $fontsize = 9, $orientation = 'P', $margins = NULL, $excelColWidthFactor = NULL)
+       var $rep_id;
+       var $formData; // common data used for printing headers footers etc.
+       var $contactData; // contact data for sending emials/reportlanguage selection
+       
+       var $dest;      // destination: email or printer
+       
+       function __construct($title, $filename, $size = 'A4', $fontsize = 9, $orientation = 'P', $margins = NULL, $excelColWidthFactor = NULL)
        {
                global $page_security;
+
+               $this->rep_id = $_POST['REP_ID'];       // FIXME
+               
                if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
                {
                        display_error(_("The security settings on your account do not permit you to print this report"));
@@ -198,15 +221,11 @@ class FrontReport extends Cpdf
                $this->row = $this->pageHeight - $this->topMargin;
                $this->currency = '';
                $this->scaleLogoWidth = false; // if Logo, scale on width (else height).
-               $this->headerFunc = 'Header';  // default to the original header template
-               $rtl = ($_SESSION['language']->dir === 'rtl' ? 'rtl' : 'ltr');
-               $code = $_SESSION['language']->code;
-               $enc = strtoupper($_SESSION['language']->encoding);
-               // for the language array in class.pdf.inc
-               $l = array('a_meta_charset' => $enc, 'a_meta_dir' => $rtl, 'a_meta_language' => $code, 'w_page' => 'page');
-               $this->Cpdf($size, $l, $orientation);
-       }
+               $this->SetHeaderType('Header'); // default
 
+               parent::__construct($size, $_SESSION['language']->code, $orientation);
+       }
+       
        /*
         * Select the font and style to use for following output until
         * it's changed again.
@@ -236,12 +255,12 @@ class FrontReport extends Cpdf
                $cols2 = null, $headers2 = null, $aligns2 = null,
                $companylogoenable = false, $footerenable = false, $footertext = '')
        {
-               global $app_title, $version, $power_by, $power_url;
+               global $SysPrefs, $version;
 
-               $this->addinfo('Title', $this->title);
-               $this->addinfo('Subject', $this->title);
-               $this->addinfo('Author', $app_title . ' ' . $version);
-               $this->addinfo('Creator',$power_by . ' - ' . $power_url);
+               $this->addInfo('Title', $this->title);
+               $this->addInfo('Subject', $this->title);
+               $this->addInfo('Author', $SysPrefs->app_title . ' ' . $version);
+               $this->addInfo('Creator',$SysPrefs->power_by . ' - ' . $SysPrefs->power_url);
                $year = get_current_fiscalyear();
                if ($year['closed'] == 0)
                        $how = _("Active");
@@ -273,15 +292,16 @@ class FrontReport extends Cpdf
                $this->footerEnable = $footerenable;
                $this->footerText = $footertext;        
        }
-
+       //
+       //      Header for listings
+       //
        function Header()
        {
+               global $SysPrefs;
+               
                $companyCol = $this->endLine - 150;
                $titleCol = $this->leftMargin + 100;
 
-               $this->pageNumber++;
-               if ($this->pageNumber > 1)
-                       $this->newPage();
                $this->row = $this->pageHeight - $this->topMargin;
 
                $this->SetDrawColor(128, 128, 128);
@@ -294,9 +314,20 @@ class FrontReport extends Cpdf
                $this->Text($this->leftMargin, $this->title, $companyCol);
                $this->Font();
                $this->fontSize -= 4;
-               $this->Text($companyCol, $this->company['coy_name']);
-               $this->row -= ($this->lineHeight + 4);
-
+               $logo = company_path() . "/images/" . $this->company['coy_logo'];
+               if (!empty($SysPrefs->prefs['company_logo_report']) && $this->company['coy_logo'] != '' && file_exists($logo))
+               {
+                       $size = getimagesize($logo);
+                       $height = $size[0] > 150 ? $size[1] * 150 / $size[0] : 30; 
+                       $this->row -= ($height / 2);
+                       $this->AddImage($logo, $companyCol, $this->row, 0, $height);
+                       $this->row -= 6;
+               }
+               else
+               {
+                       $this->Text($companyCol, $this->company['coy_name']);
+                       $this->row -= ($this->lineHeight + 4);
+               }
                $str = _("Print Out Date") . ':';
                $this->Text($this->leftMargin, $str, $titleCol);
                $str = Today() . '   ' . Now();
@@ -311,7 +342,7 @@ class FrontReport extends Cpdf
                $str = $this->fiscal_year;
                $this->Text($titleCol, $str, $companyCol);
                $this->Text($companyCol, $this->user);
-               for ($i = 1; $i < count($this->params); $i++)
+               for ($i = 1; $i < count_array($this->params); $i++)
                {
                        if ($this->params[$i]['from'] != '')
                        {
@@ -341,12 +372,12 @@ class FrontReport extends Cpdf
                $this->Font('italic');
                if ($this->headers2 != null)
                {
-                       $count = count($this->headers2);
+                       $count = count_array($this->headers2);
                        for ($i = 0; $i < $count; $i++)
                                $this->TextCol2($i, $i + 1,     $this->headers2[$i]);
                        $this->NewLine();
                }
-               $count = count($this->headers);
+               $count = count_array($this->headers);
                for ($i = 0; $i < $count; $i++)
                        $this->TextCol($i, $i + 1, $this->headers[$i]);
                $this->Font();
@@ -354,25 +385,71 @@ class FrontReport extends Cpdf
 
                $this->NewLine(2);
        }
-
-       function Header2($myrow, $branch, $sales_order, $bankaccount, $doctype)
+       /*
+               Transition function 
+       */
+       function SetCommonData($myrow, $branch, $sales_order, $bankaccount, $doctype, $contacts)
        {
-               global $comp_path, $path_to_root, $print_as_quote, $print_invoice_no, $packing_slip;
-
-               $this->pageNumber++;
-               if ($this->pageNumber > 1)
-                       $this->newPage();
-               $header2type = true;
-               if (isset($myrow['curr_code']) && $this->currency != $myrow['curr_code'])
-               {
-                       include($path_to_root . "/reporting/includes/doctext2.inc");
+               $this->pageNumber = 0;
+               $this->formData = array();
+               $datnames = array( 
+               'myrow' => array('ord_date', 'date_', 'tran_date', 
+                       'order_no','reference', 'id', 'trans_no', 'name', 'location_name',
+                       'delivery_address', 'supp_name', 'address',
+                       'DebtorName', 'supp_account_no', 'wo_ref', 'debtor_ref','type', 'trans_no', 
+                       'StockItemName', 'tax_id', 'order_', 'delivery_date', 'units_issued',
+                       'due_date', 'required_by', 'payment_terms', 'curr_code',
+                       'ov_freight', 'ov_gst', 'ov_amount', 'prepaid', 'requisition_no', 'contact'),
+               'branch' => array('br_address', 'br_name', 'salesman', 'disable_branch'),
+               'sales_order' => array('deliver_to', 'delivery_address', 'customer_ref'),
+               'bankaccount' => array('bank_name', 'bank_account_number', 'payment_service')
+               );
+
+               foreach($datnames as $var => $fields) {
+                       if (isset($$var)) {
+                               foreach($fields as $locname) {
+                                       if (isset(${$var}[$locname]) && (${$var}[$locname]!==null)) {
+                                               $this->formData[$locname] = ${$var}[$locname];
+                                       }
+                               }
+                       }
                }
-               else
-               {
-                       include($path_to_root . "/reporting/includes/doctext.inc");
+               $this->formData['doctype'] = $doctype;
+               $this->formData['document_amount'] = @$this->formData['ov_amount']+@$this->formData['ov_freight']+@$this->formData['ov_gst'];
+               if (count($contacts)) {
+                       if (!is_array($contacts[0]))
+                               $contacts = array($contacts); // change to array when single contact passed
+                       $this->contactData = $contacts;
+                       // as report is currently generated once despite number of email recipients
+                       // we select language for the first recipient as report language
+                       $this->formData['rep_lang'] = $contacts[0]['lang'];
                }
+       }
+       /*
+               Set header handler
+       */
+       function SetHeaderType($name) {
+               $this->headerTmpl = $name;
+       }
+       /*
+               Header for sales/purchase documents
+       */
+       function Header2()
+       {
+               global $dflt_lang; // FIXME should be passed as params
+
+               $this->SetLang(@$this->formData['rep_lang'] ? $this->formData['rep_lang'] : $dflt_lang);
+               $doctype = $this->formData['doctype'];
+               $header2type = true;
 
-               include($path_to_root . "/reporting/includes/header2.inc");
+               $lang = user_language();
+               $this->SetLang(@$this->formData['rep_lang'] ? $this->formData['rep_lang']
+                       : ( $lang ? $lang : $dflt_lang));
+
+                // leave layout files names without path to enable including
+                // modified versions from company/x/reporting directory
+               include("includes/doctext.inc");
+               include("includes/header2.inc");
 
                $this->row = $temp;
        }
@@ -380,18 +457,13 @@ class FrontReport extends Cpdf
        // Alternate header style which also supports a simple footer
        function Header3()
        {
-               global $comp_path;
-
-               // Make this header the default for the current report ( used by NewLine() )
-               $this->headerFunc = 'Header3';
-               
                // Turn off cell padding for the main report header, restoring the current setting later
                $oldcMargin = $this->cMargin;
                $this->SetCellPadding(0);
 
                // Set some constants which control header item layout
                // only set them once or the PHP interpreter gets angry
-               if ($this->pageNumber == 0)
+               if ($this->pageNumber == 1)
                {
                        define('COMPANY_WIDTH', 150);
                        define('LOGO_HEIGHT', 50);
@@ -411,18 +483,6 @@ class FrontReport extends Cpdf
                $footerCol = $this->leftMargin + PAGE_NUM_WIDTH; 
                $footerRow = $this->bottomMargin - FOOTER_MARGIN;
 
-               // Calling this function generates a new PDF page after the first instance
-               $this->pageNumber++;
-               if ($this->pageNumber > 1)
-               {
-//                     // TODO: experimenting with line drawing to highlight current period
-//                     $this->SetLineWidth(1);
-//                     $this->LineTo($this->cols[3], 33, $this->cols[3], 534);
-//                     $this->LineTo($this->cols[4], 33, $this->cols[4], 534);
-//                     $this->SetLineWidth(0.1);
-                       
-                       $this->newPage();
-               }
                $this->row = $this->pageHeight - $this->topMargin;
 
                // Set the color of dividing lines we'll draw
@@ -464,15 +524,14 @@ class FrontReport extends Cpdf
                $this->fontSize = HEADER1_FONT_SIZE;
 
                // Print company logo if present and requested, or else just print company name
-               if ($this->companyLogoEnable && ($this->company['coy_logo'] != ''))
+               // Build a string specifying the location of the company logo file
+               $logo = company_path() . "/images/" . $this->company['coy_logo'];
+               if ($this->companyLogoEnable && ($this->company['coy_logo'] != '') && file_exists($logo))
                {
-                       // Build a string specifying the location of the company logo file
-                       $logo = $comp_path .'/'. user_company() . "/images/" . $this->company['coy_logo'];
-
                        // Width being zero means that the image will be scaled to the specified height
                        // keeping its aspect ratio intact.
                        if ($this->scaleLogoWidth)
-                               $this->AddImage($logo, $companyCol, $this->row, COMPANY_WIDTH, 0);
+                               $this->AddImage($logo, $companyCol, $this->row + 15, COMPANY_WIDTH, 0);
                        else    
                                $this->AddImage($logo, $companyCol, $this->row - (LOGO_HEIGHT * LOGO_Y_POS_ADJ_FACTOR), 0, LOGO_HEIGHT);
                }
@@ -661,25 +720,6 @@ class FrontReport extends Cpdf
                return $drawColor;
        }
        
-       function SetDrawColor($r, $g, $b)
-       {
-               parent::SetDrawColor($r, $g, $b);
-       }
-
-       function SetTextColor($r, $g, $b)
-       {
-               parent::SetTextColor($r, $g, $b);
-       }
-
-       /**
-     * Set the fill color for table cells.
-     * @see reporting/includes/TCPDF#SetFillColor($col1, $col2, $col3, $col4)
-     */
-       function SetFillColor($r, $g, $b)
-       {
-               parent::SetFillColor($r, $g, $b);
-       }
-
        // Get current cell padding setting from TCPDF object
        function GetCellPadding()
        {
@@ -701,14 +741,16 @@ class FrontReport extends Cpdf
                return $this->TextWrap($c, $this->row - $r, $n - $c + $corr, $txt, $align, $border, $fill, $link, $stretch);
        }
 
-       function TextWrap($xpos, $ypos, $len, $str, $align = 'left', $border = 0, $fill = 0, $link = NULL, $stretch = 1)
+       function TextWrap($xpos, $ypos, $len, $str, $align = 'left', $border = 0, $fill = 0, $link = NULL, $stretch = 1, $spacebreak=false)
        {
+               $str = ($str != NULL ? strtr($str, array("\r"=>'')) : "");
+
                if ($this->fontSize != $this->oldFontSize)
                {
                        $this->SetFontSize($this->fontSize);
                        $this->oldFontSize = $this->fontSize;
                }
-               return $this->addTextWrap($xpos, $ypos, $len, $this->fontSize, $str, $align, $border, $fill, $link, $stretch);
+               return $this->addTextWrap($xpos, $ypos, $len, $this->fontSize, $str, $align, $border, $fill, $link, $stretch, $spacebreak);
        }
 
        function TextCol($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
@@ -731,7 +773,7 @@ class FrontReport extends Cpdf
                setlocale(LC_MONETARY, $amount_locale);
                if ($color_red && $txt < 0)
                        $this->SetTextColor(255, 0, 0);
-               $ret = $this->TextCol($c, $n, money_format($amount_format, $txt), $corr, $r, $border, $fill, $link, $stretch);
+               $ret = $this->TextCol($c, $n, price_format($txt), $corr, $r, $border, $fill, $link, $stretch);
                if ($color_red && $txt < 0)
                        $this->SetTextColor(0, 0, 0);
                return $ret;    
@@ -749,21 +791,22 @@ class FrontReport extends Cpdf
                return $this->TextWrap($this->cols2[$c], $this->row - $r, $this->cols2[$n] - $this->cols2[$c] + $corr, $txt, $this->aligns2[$c], $border, $fill, $link, $stretch);
        }
 
-       function TextColLines($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=1)
+       function TextColLines($c, $n, $txt, $corr=0, $r=0, $border=0, $fill=0, $link=NULL, $stretch=0)
        {
                $this->row -= $r;
-               $this->TextWrapLines($this->cols[$c], $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch);
+               $this->TextWrapLines($this->cols[$c], $this->cols[$n] - $this->cols[$c] + $corr, $txt, $this->aligns[$c], $border, $fill, $link, $stretch, true);
        }
 
-       function TextWrapLines($c, $width, $txt, $align='left', $border=0, $fill=0, $link=NULL, $stretch=1)
+       function TextWrapLines($c, $width, $txt, $align='left', $border=0, $fill=0, $link=NULL, $stretch=0, $spacebreak=true)
        {
-               $str = Explode("\n", $txt);
+               $str = ($txt != NULL ? explode("\n", $txt) : array());
+
                for ($i = 0; $i < count($str); $i++)
                {
                        $l = $str[$i];
                        do
                        {
-                               $l = $this->TextWrap($c, $this->row , $width, $l, $align, $border, $fill, $link, $stretch);
+                               $l = $this->TextWrap($c, $this->row , $width, $l, $align, $border, $fill, $link, $stretch, $spacebreak);
                                $this->row -= $this->lineHeight;
                        }
                        while ($l != '');
@@ -813,7 +856,7 @@ class FrontReport extends Cpdf
                parent::line($from, $row, $to, $row2);
        }
 
-       function Line($row, $height = 0)
+       function Line($row, $height = 0, $dummy1=null, $dummy2=null, $dummy3=null)
        {
                $oldLineWidth = $this->GetLineWidth();
                $this->SetLineWidth($height + 1);
@@ -869,36 +912,61 @@ class FrontReport extends Cpdf
 
                // Move one line down the page
                $this->row -= ($l * $h);
-               // Reset the "current line height" for the new line
-               $this->curLineHeight = $this->fontSize;
+
                // Check to see if we're at the bottom and should insert a page break
                if ($this->row < $this->bottomMargin + ($np * $h))
-                       $this->{$this->headerFunc}();  // call header template chosen by current report
+                       $this->NewPage();
+       }
+
+       function NewPage() 
+       {
+               if ($this->pageNumber==0)
+               {
+                       // check if there is pdf header template for this report
+                       // and set if it is found
+                       $tmpl_pdf = find_custom_file("/reporting/forms/".$this->headerTmpl.".pdf");
+                       if ($tmpl_pdf) {
+                               $this->tmplSize = $this->setSourceFile($tmpl_pdf);
+                       }
+               }
+
+               $this->pageNumber++;
+               parent::newPage();
+
+               if ($this->tmplSize) {
+                       $this->row = $this->pageHeight - $this->topMargin; // reset row
+                       $id = $this->importPage(min($this->pageNumber, $this->tmplSize));
+                       $this->useTemplate($id);
+               }
+
+               // include related php file if any
+               $tmpl_php = find_custom_file("/reporting/forms/".$this->headerTmpl.".php");
+               if ($tmpl_php) {
+                       include($tmpl_php);
+               }
+
+               if (method_exists($this, $this->headerTmpl))    // draw predefined page layout if any
+                       $this->{$this->headerTmpl}();
        }
 
-       function End($email=0, $subject=null, $myrow=null, $doctype = 0)
+       function End($email=0, $subject='')
        {
-               global $pdf_debug, $path_to_root, $comp_path;
+               global $SysPrefs, $path_to_root;
 
-               if ($pdf_debug == 1)
+               if (!empty($SysPrefs->prefs['print_dialog_direct']))            
+                       $this->includeJS("print();"); // force to open print dialog
+
+               if ($SysPrefs->pdf_debug == 1)
                {
                        $pdfcode = $this->Output('','S');
-                       $pdfcode = str_replace("\n", "\n<br>", htmlspecialchars($pdfcode));
+                       $pdfcode = str_replace("\n", "\n<br>", html_specials_encode($pdfcode));
                        echo '<html><body>';
                        echo trim($pdfcode);
                        echo '</body></html>';
-                       //header("Content-Length: $len");
-                       //header("Content-Disposition: inline; filename=" . $this->filename);
-                       //header('Expires: 0');
-                       //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
-                       //header('Pragma: public');
-
-                       //$this->pdf->stream();
                }
                else
                {
-
-                       $dir =  $comp_path.'/'.user_company(). '/pdf_files';
+                       $dir =  company_path(). '/pdf_files';
                        //save the file
                        if (!file_exists($dir))
                        {
@@ -906,60 +974,81 @@ class FrontReport extends Cpdf
                        }
                        // do not use standard filenames or your sensitive company data 
                        // are world readable
-                       if ($email == 1)
-                               $fname = $dir.'/'.$this->filename;
-                       else    
-                               $fname = $dir.'/'.uniqid('').'.pdf';
+                       $fname = $dir.'/'.random_id().'.pdf';
                        $this->Output($fname, 'F');
+
                        if ($email == 1)
                        {
-                               $emailtype = true;
-                               if ($this->currency != $myrow['curr_code'])
-                               {
-                                       include("doctext2.inc");
-                               }
-                               else
-                               {
-                                       include("doctext.inc");
-                               }
-                               require_once($path_to_root . "/reporting/includes/class.mail.inc");
-                       $mail = new email($this->company['coy_name'], $this->company['email']);
-                               if (!isset($myrow['email']) || $myrow['email'] == '') 
-                                       $myrow['email'] = isset($myrow['contact_email']) ? $myrow['contact_email'] : '';
-                       $to = $myrow['DebtorName'] . " <" . $myrow['email'] . ">";
-                       $msg = $doc_Dear_Sirs . " " . $myrow['DebtorName'] . ",\n\n" . $doc_AttachedFile . " " . $subject .
-                               "\n\n";
-                               if (isset($myrow['dimension_id']) && $myrow['dimension_id'] > 0 && $doctype == ST_SALESINVOICE) // helper for payment links
-                               {
-                                       if ($myrow['dimension_id'] == 1)
-                                       {
-                                               $amt = number_format($myrow["ov_freight"] + $myrow["ov_gst"] +  $myrow["ov_amount"], user_price_dec());
-                                               $txt = $doc_Payment_Link . " PayPal: ";
-                                               $nn = urlencode($this->title . " " . $myrow['reference']);
-                                               $url = "https://www.paypal.com/xclick/business=" . $this->company['email'] . "&item_name=" .
-                                                       $nn . "&amount=" . $amt . "&currency_code=" . $myrow['curr_code'];
-                                               $msg .= $txt . $url . "\n\n";
-                                       }
+                               $contactData = array();
+                               if ($this->contactData)
+                                       foreach($this->contactData as $contact)
+                                               if (!empty($contact['email']))
+                                                       $contactData[] = $contact;
+
+                               if(!count($contactData)) {
+                                       $this->SetLang(user_language());
+                                       display_warning(sprintf(_("You have no email contact defined for this type of document for '%s'."), $this->formData['recipient_name']));
+                               } else {
+                                       $sent = $try = 0;
+                                       $emails = "";
+                                       if(!$subject)
+                                               $subject = $this->formData['document_name'] . ' '. $this->formData['document_number'];
+                                       foreach($contactData as $contact) {
+                                               if (!isset($contact['email'])) 
+                                                       continue;
+                                               $emailtype = true;
+                                               $this->SetLang($contact['lang']);
+                                               $coy_name = @html_entity_decode($this->company['coy_name'], ENT_QUOTES, $_SESSION['language']->encoding=='iso-8859-2' ? 'ISO-8859-1' : $_SESSION['language']->encoding);
+
+                                               require_once($path_to_root . "/reporting/includes/class.mail.inc");
+                                       $mail = new email(str_replace(",", "", $coy_name),
+                                               $this->company['email']);
+                                               $mail->charset = $this->encoding;
+
+                                       $msg = _("Dear") . " " . $contact['name2'] . ",\n\n" 
+                                               . _("Attached you will find ") . " " . $subject ."\n\n";
+
+                                               if (isset($this->formData['payment_service']))
+                                               {
+                                                       $amt = number_format($this->formData['document_amount'], user_price_dec());
+                                                       $service = $this->formData['payment_service'];
+                                                       $url = payment_link($service, array(
+                                                                       'company_email' => $this->company['email'],
+                                                                       'amount' => $amt,
+                                                                       'currency' => $this->formData['curr_code'],
+                                                                       'comment' => $this->title . " " . $this->formData['document_number']
+                                                                       ));
+                                                       if ($url)
+                                                               $msg.= _("You can pay through"). " $service: $url\n\n";
+                                               }
+
+                                       $msg .= _("Kindest regards") . "\n\n";
+                                       $sender = $this->user . "\n" . $coy_name . "\n" . $this->company['postal_address'] . "\n" . $this->company['email'] . "\n" . $this->company['phone'];
+                                       $mail->to(str_replace(",", "", $contact['name'].' '.$contact['name2']), $contact['email']);
+                                       $try++;
+                                       $mail->subject($subject);
+                                       $mail->text($msg . $sender);
+                                       $mail->attachment($fname, $this->filename);
+                                       $emails .= " " . $contact['email'];
+                                       if ($mail->send()) $sent++;
+                                       } // foreach contact
+                                       unlink($fname);
+                                       $this->SetLang(user_language());
+                                       if (!$try) {
+                                               display_warning(sprintf(_("You have no email contact defined for this type of document for '%s'."), $this->formData['recipient_name']));
+                                       } elseif (!$sent)
+                                               display_warning($this->title . " " . $this->formData['document_number'] . ". "
+                                                       . _("Sending document by email failed") . ". " . _("Email:") . $emails);
+                                       else
+                                               display_notification($this->title . " " . $this->formData['document_number'] . " " 
+                                                       . _("has been sent by email to destination.") . " " . _("Email:") . $emails);
                                }
-                       $msg .= $doc_Kindest_regards . "\n\n";
-                       $sender = $this->user . "\n" . $this->company['coy_name'] . "\n" . $this->company['postal_address'] . "\n" . $this->company['email'] . "\n" . $this->company['phone'];
-                       $mail->to($to);
-                       $mail->subject($subject);
-                       $mail->text($msg . $sender);
-                       $mail->attachment($fname);
-                       $ret = $mail->send();
-                               if (!$ret)
-                                       display_error(_("Sending document by email failed"));
-                               else
-                                       display_notification($this->title . " " . $myrow['reference'] . " " 
-                                               . _("has been sent by email."));
-                               unlink($fname);         
                        }
                        else
                        {
-                               $printer = get_report_printer(user_print_profile(), $_POST['REP_ID']);
+                               $printer = get_report_printer(user_print_profile(), $this->rep_id);
                                if ($printer == false) {
-                                       if(in_ajax()) {
+                                       if (in_ajax()) {
                                                global $Ajax;
 
                                                if (user_rep_popup()) 
@@ -967,23 +1056,12 @@ class FrontReport extends Cpdf
                                                else
                                                        $Ajax->redirect($fname); // otherwise use faster method
                                        } else {
-                                       //echo '<html>
-                                       //              <head>
-                                       //                <SCRIPT LANGUAGE="JavaScript"><!--
-                                       //            function go_now () { window.location.href = "'.$fname.'"; }
-                                       //            //--></SCRIPT>
-                                       //        </head>
-                                       //        <body onLoad="go_now()"; >
-                                       //          <a href="'.$fname.'">click here</a> if you are not re-directed.
-                                       //        </body>
-                                       //    </html>';
-                       header('Content-type: application/pdf');
-                   header("Content-Disposition: inline; filename=$this->filename");
-                       header('Expires: 0');
-                   header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
-                       header('Pragma: public');
-
-                       $this->Stream();
+                                               header('Content-type: application/pdf');
+                                               header('Content-Disposition: inline; filename='.$this->filename);
+                                               header('Expires: 0');
+                                               header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+                                               header('Pragma: public');
+                                               $this->Stream($this->filename);
                                        }
                                } else { // send report to network printer
                                        $prn = new remote_printer($printer['queue'],$printer['host'],
@@ -1013,4 +1091,3 @@ class FrontReport extends Cpdf
        }
 }
 
-?>
\ No newline at end of file