Passed
Branch develop (049034)
by
unknown
31:10
created

dolReceiptPrinter::initPrinter()   B

Complexity

Conditions 10
Paths 80

Size

Total Lines 50
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 43
nc 80
nop 1
dl 0
loc 50
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2015-2019  Frédéric France     <[email protected]>
3
 * Copyright (C) 2020       Andreu Bisquerra    <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
 * or see https://www.gnu.org/
18
 */
19
20
/**
21
 *  \file           htdocs/core/class/dolreceiptprinter.class.php
22
 *  \brief          Print receipt ticket on various ESC/POS printer
23
 */
24
25
/*
26
 * Tags for ticket template
27
 *
28
 * <dol_align_left>                                 Left align text
29
 * <dol_align_center>                               Center text
30
 * <dol_align_right>                                Right align text
31
 * <dol_use_font_a>                                 Use font A of printer
32
 * <dol_use_font_b>                                 Use font B of printer
33
 * <dol_use_font_c>                                 Use font C of printer
34
 * <dol_bold>                                       Text Bold
35
 * <dol_bold_disabled>                              Disable Text Bold
36
 * <dol_double_height>                              Text double height
37
 * <dol_double_width>                               Text double width
38
 * <dol_default_height_width>                       Text default height and width
39
 * <dol_underline>                                  Underline text
40
 * <dol_underline_disabled>                         Disable underline text
41
 * <dol_cut_paper_full>                             Cut ticket completely
42
 * <dol_cut_paper_partial>                          Cut ticket partially
43
 * <dol_open_drawer>                                Open cash drawer
44
 * <dol_beep>                                       Activate buzzer
45
 * <dol_print_barcode>                              Print barcode
46
 * <dol_print_logo>                                 Print logo stored on printer. Example : <print_logo>32|32
47
 * <dol_print_logo_old>                             Print logo stored on printer. Must be followed by logo code. For old printers.
48
 * <dol_print_object_lines>                         Print object lines
49
 * <dol_print_object_tax>                           Print object total tax
50
 * <dol_print_object_local_tax>                     Print object local tax
51
 * <dol_print_object_total>                         Print object total
52
 * <dol_print_order_lines>                          Print order lines for Printer
53
 * <dol_print_payment>                              Print payment method
54
 *
55
 * Code which can be placed everywhere
56
 * <dol_value_date>                                 Replaced by date AAAA-MM-DD
57
 * <dol_value_date_time>                            Replaced by date and time AAAA-MM-DD HH:MM:SS
58
 * <dol_value_year>                                 Replaced by Year
59
 * <dol_value_month_letters>                        Replaced by month in letters (example : november)
60
 * <dol_value_month>                                Replaced by month number
61
 * <dol_value_day>                                  Replaced by day number
62
 * <dol_value_day_letters>                          Replaced by day number
63
 * <dol_object_id>                                  Replaced by object id
64
 * <dol_object_ref>                                 Replaced by object ref
65
 * <dol_value_customer_firstname>                   Replaced by customer firstname
66
 * <dol_value_customer_lastname>                    Replaced by customer name
67
 * <dol_value_customer_mail>                        Replaced by customer mail
68
 * <dol_value_customer_phone>                       Replaced by customer phone
69
 * <dol_value_customer_mobile>                      Replaced by customer mobile
70
 * <dol_value_customer_skype>                       Replaced by customer skype
71
 * <dol_value_customer_tax_number>                  Replaced by customer VAT number
72
 * <dol_value_customer_account_balance>             Replaced by customer account balance
73
 * <dol_value_mysoc_name>                           Replaced by mysoc name
74
 * <dol_value_mysoc_address>                        Replaced by mysoc address
75
 * <dol_value_mysoc_zip>                            Replaced by mysoc zip
76
 * <dol_value_mysoc_town>                           Replaced by mysoc town
77
 * <dol_value_mysoc_country>                        Replaced by mysoc country
78
 * <dol_value_mysoc_idprof1>                        Replaced by mysoc idprof1
79
 * <dol_value_mysoc_idprof2>                        Replaced by mysoc idprof2
80
 * <dol_value_mysoc_idprof3>                        Replaced by mysoc idprof3
81
 * <dol_value_mysoc_idprof4>                        Replaced by mysoc idprof4
82
 * <dol_value_mysoc_idprof5>                        Replaced by mysoc idprof5
83
 * <dol_value_mysoc_idprof6>                        Replaced by mysoc idprof6
84
 * <dol_value_vendor_lastname>                      Replaced by vendor name
85
 * <dol_value_vendor_firstname>                     Replaced by vendor firstname
86
 * <dol_value_vendor_mail>                          Replaced by vendor mail
87
 * <dol_value_customer_points>                      Replaced by customer points
88
 * <dol_value_object_points>                        Replaced by number of points for this object
89
 *
90
 * Conditional code at line start (if then Print)
91
 * <dol_print_if_customer>                          Print the line IF a customer is affected to the object
92
 * <dol_print_if_vendor>                            Print the line IF a vendor is affected to the object
93
 * <dol_print_if_happy_hour>                        Print the line IF Happy Hour
94
 * <dol_print_if_num_object_unique>                 Print the line IF object is validated
95
 * <dol_print_if_customer_points>                   Print the line IF customer points > 0
96
 * <dol_print_if_object_points>                     Print the line IF points of the object > 0
97
 * <dol_print_if_customer_tax_number>               Print the line IF customer has vat number
98
 * <dol_print_if_customer_account_balance_positive> Print the line IF customer balance > 0
99
 *
100
 */
101
102
require_once DOL_DOCUMENT_ROOT.'/includes/mike42/escpos-php/autoload.php';
103
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
104
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
105
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
106
use Mike42\Escpos\PrintConnectors\CupsPrintConnector;
107
use Mike42\Escpos\PrintConnectors\DummyPrintConnector;
108
use Mike42\Escpos\CapabilityProfile;
109
use Mike42\Escpos\Printer;
110
use Mike42\Escpos\EscposImage;
111
112
113
/**
114
 * Class to manage Receipt Printers
115
 */
116
class dolReceiptPrinter extends Printer
117
{
118
    const CONNECTOR_DUMMY = 1;
119
    const CONNECTOR_FILE_PRINT = 2;
120
    const CONNECTOR_NETWORK_PRINT = 3;
121
    const CONNECTOR_WINDOWS_PRINT = 4;
122
    const CONNECTOR_CUPS_PRINT = 5;
123
124
    /**
125
     * @var DoliDB Database handler.
126
     */
127
    public $db;
128
129
    /*
130
     * @var string[] array of tags
131
     */
132
    public $tags;
133
    public $printer;
134
    public $template;
135
136
    /**
137
     * Number of order printer
138
     * @var int
139
     */
140
    public $orderprinter;
141
142
    /**
143
     * @var string Error code (or message)
144
     */
145
    public $error = '';
146
147
    /**
148
     * @var string[] Error codes (or messages)
149
     */
150
    public $errors = array();
151
152
    /**
153
     * Constructor
154
     *
155
     * @param   DoliDB      $db         database
156
     */
157
    public function __construct($db)
158
    {
159
        $this->db = $db;
160
        $this->tags = array(
161
            'dol_line_feed' => 'DOL_LINE_FEED',
162
        	'dol_line_feed_reverse' => 'DOL_LINE_FEED_REVERSE',
163
            'dol_align_left' => 'DOL_ALIGN_LEFT',
164
            'dol_align_center' => 'DOL_ALIGN_CENTER',
165
            'dol_align_right' => 'DOL_ALIGN_RIGHT',
166
            'dol_use_font_a' => 'DOL_USE_FONT_A',
167
            'dol_use_font_b' => 'DOL_USE_FONT_B',
168
        	'dol_use_font_c' => 'DOL_USE_FONT_C',
169
        	'dol_bold' => 'DOL_BOLD',
170
        	'dol_bold_disabled' => 'DOL_BOLD_DISABLED',
171
        	'dol_double_height' => 'DOL_DOUBLE_HEIGHT',
172
        	'dol_double_width' => 'DOL_DOUBLE_WIDTH',
173
        	'dol_default_height_width' => 'DOL_DEFAULT_HEIGHT_WIDTH',
174
        	'dol_underline' => 'DOL_UNDERLINE',
175
        	'dol_underline_disabled' => 'DOL_UNDERLINE_DISABLED',
176
        	'dol_cut_paper_full' => 'DOL_CUT_PAPER_FULL',
177
        	'dol_cut_paper_partial' => 'DOL_CUT_PAPER_PARTIAL',
178
        	'dol_open_drawer' => 'DOL_OPEN_DRAWER',
179
        	'dol_beep' => 'DOL_BEEP',
180
        	'dol_print_text' => 'DOL_PRINT_TEXT',
181
        	'dol_print_barcode' => 'DOL_PRINT_BARCODE',
182
        	'dol_value_date' => 'DateInvoice',
183
        	'dol_value_date_time' => 'DateInvoiceWithTime',
184
        	'dol_value_year' => 'YearInvoice',
185
        	'dol_value_month_letters' => 'DOL_VALUE_MONTH_LETTERS',
186
        	'dol_value_month' => 'DOL_VALUE_MONTH',
187
        	'dol_value_day' => 'DOL_VALUE_DAY',
188
        	'dol_value_day_letters' => 'DOL_VALUE_DAY',
189
            //'dol_print_payment',
190
        	'dol_print_logo' => 'DOL_PRINT_LOGO',
191
        	'dol_print_logo_old' => 'DOL_PRINT_LOGO_OLD',
192
        	'dol_value_object_id' => 'InvoiceID',
193
        	'dol_value_object_ref' => 'InvoiceRef',
194
        	'dol_print_object_lines' => 'DOL_PRINT_OBJECT_LINES',
195
        	'dol_print_object_tax' => 'TotalVAT',
196
        	'dol_print_object_local_tax1' => 'TotalLT1',
197
        	'dol_print_object_local_tax2' => 'TotalLT2',
198
        	'dol_print_object_total' => 'Total',
199
        	'dol_print_object_number' => 'DOL_PRINT_OBJECT_NUMBER',
200
        	//'dol_value_object_points' => 'DOL_VALUE_OBJECT_POINTS',
201
        	'dol_print_order_lines' => 'DOL_PRINT_ORDER_LINES',
202
        	'dol_value_customer_firstname' => 'DOL_VALUE_CUSTOMER_FIRSTNAME',
203
        	'dol_value_customer_lastname' => 'DOL_VALUE_CUSTOMER_LASTNAME',
204
        	'dol_value_customer_mail' => 'DOL_VALUE_CUSTOMER_MAIL',
205
        	'dol_value_customer_phone' => 'DOL_VALUE_CUSTOMER_PHONE',
206
        	'dol_value_customer_skype' => 'DOL_VALUE_CUSTOMER_SKYPE',
207
        	'dol_value_customer_tax_number' => 'DOL_VALUE_CUSTOMER_TAX_NUMBER',
208
        	//'dol_value_customer_account_balance' => 'DOL_VALUE_CUSTOMER_ACCOUNT_BALANCE',
209
        	//'dol_value_customer_points' => 'DOL_VALUE_CUSTOMER_POINTS',
210
        	'dol_value_mysoc_name' => 'DOL_VALUE_MYSOC_NAME',
211
        	'dol_value_mysoc_address' => 'Address',
212
        	'dol_value_mysoc_zip' => 'Zip',
213
        	'dol_value_mysoc_town' => 'Town',
214
        	'dol_value_mysoc_country' => 'Country',
215
        	'dol_value_mysoc_idprof1' => 'ProfId1',
216
        	'dol_value_mysoc_idprof2' => 'ProfId2',
217
        	'dol_value_mysoc_idprof3' => 'ProfId3',
218
        	'dol_value_mysoc_idprof4' => 'ProfId4',
219
        	'dol_value_mysoc_idprof5' => 'ProfId5',
220
        	'dol_value_mysoc_idprof6' => 'ProfId6',
221
        	'dol_value_mysoc_tva_intra' => 'VATIntra',
222
        	'dol_value_mysoc_capital' => 'Capital',
223
        	'dol_value_vendor_lastname' => 'VendorLastname',
224
        	'dol_value_vendor_firstname' => 'VendorFirstname',
225
        	'dol_value_vendor_mail' => 'VendorEmail',
226
        );
227
    }
228
229
    /**
230
     * list printers
231
     *
232
     * @return  int                     0 if OK; >0 if KO
233
     */
234
    public function listPrinters()
235
    {
236
        global $conf;
237
        $error = 0;
238
        $line = 0;
239
        $obj = array();
240
        $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter';
241
        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
242
        $sql .= ' WHERE entity = '.$conf->entity;
243
        $resql = $this->db->query($sql);
244
        if ($resql) {
245
            $num = $this->db->num_rows($resql);
246
            while ($line < $num) {
247
                $row = $this->db->fetch_array($resql);
248
                switch ($row['fk_type']) {
249
                    case 1:
250
                        $row['fk_type_name'] = 'CONNECTOR_DUMMY';
251
                        break;
252
                    case 2:
253
                        $row['fk_type_name'] = 'CONNECTOR_FILE_PRINT';
254
                        break;
255
                    case 3:
256
                        $row['fk_type_name'] = 'CONNECTOR_NETWORK_PRINT';
257
                        break;
258
                    case 4:
259
                        $row['fk_type_name'] = 'CONNECTOR_WINDOWS_PRINT';
260
                        break;
261
                    case 5:
262
                        $row['fk_type_name'] = 'CONNECTOR_CUPS_PRINT';
263
                        break;
264
                    default:
265
                        $row['fk_type_name'] = 'CONNECTOR_UNKNOWN';
266
                        break;
267
                }
268
                switch ($row['fk_profile']) {
269
                    case 0:
270
                        $row['fk_profile_name'] = 'PROFILE_DEFAULT';
271
                        break;
272
                    case 1:
273
                        $row['fk_profile_name'] = 'PROFILE_SIMPLE';
274
                        break;
275
                    case 2:
276
                        $row['fk_profile_name'] = 'PROFILE_EPOSTEP';
277
                        break;
278
                    case 3:
279
                        $row['fk_profile_name'] = 'PROFILE_P822D';
280
                        break;
281
                    default:
282
                        $row['fk_profile_name'] = 'PROFILE_STAR';
283
                        break;
284
                }
285
                $obj[] = $row;
286
                $line++;
287
            }
288
        } else {
289
            $error++;
290
            $this->errors[] = $this->db->lasterror;
291
        }
292
        $this->listprinters = $obj;
293
        return $error;
294
    }
295
296
297
    /**
298
     * List printers templates
299
     *
300
     * @return  int                     0 if OK; >0 if KO
301
     */
302
    public function listPrintersTemplates()
303
    {
304
        global $conf;
305
        $error = 0;
306
        $line = 0;
307
        $obj = array();
308
        $sql = 'SELECT rowid, name, template';
309
        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
310
        $sql .= ' WHERE entity = '.$conf->entity;
311
        $resql = $this->db->query($sql);
312
        if ($resql) {
313
            $num = $this->db->num_rows($resql);
314
            while ($line < $num) {
315
                $obj[] = $this->db->fetch_array($resql);
316
                $line++;
317
            }
318
        } else {
319
            $error++;
320
            $this->errors[] = $this->db->lasterror;
321
        }
322
        $this->listprinterstemplates = $obj;
323
        return $error;
324
    }
325
326
327
    /**
328
     *  Form to Select type printer
329
     *
330
     *  @param    string    $selected       Id printer type pre-selected
331
     *  @param    string    $htmlname       select html name
332
     *  @return  int                        0 if OK; >0 if KO
333
     */
334
    public function selectTypePrinter($selected = '', $htmlname = 'printertypeid')
335
    {
336
        global $langs;
337
338
        $options = array(
339
            1 => $langs->trans('CONNECTOR_DUMMY'),
340
            2 => $langs->trans('CONNECTOR_FILE_PRINT'),
341
            3 => $langs->trans('CONNECTOR_NETWORK_PRINT'),
342
            4 => $langs->trans('CONNECTOR_WINDOWS_PRINT'),
343
			5 => $langs->trans('CONNECTOR_CUPS_PRINT'),
344
        );
345
346
        $this->resprint = Form::selectarray($htmlname, $options, $selected);
347
348
        return 0;
349
    }
350
351
352
    /**
353
     *  Form to Select Profile printer
354
     *
355
     *  @param    string    $selected       Id printer profile pre-selected
356
     *  @param    string    $htmlname       select html name
357
     *  @return  int                        0 if OK; >0 if KO
358
     */
359
    public function selectProfilePrinter($selected = '', $htmlname = 'printerprofileid')
360
    {
361
        global $langs;
362
363
        $options = array(
364
            0 => $langs->trans('PROFILE_DEFAULT'),
365
            1 => $langs->trans('PROFILE_SIMPLE'),
366
            2 => $langs->trans('PROFILE_EPOSTEP'),
367
            3 => $langs->trans('PROFILE_P822D'),
368
            4 => $langs->trans('PROFILE_STAR'),
369
        );
370
371
        $this->profileresprint = Form::selectarray($htmlname, $options, $selected);
372
        return 0;
373
    }
374
375
376
    /**
377
     *  Function to Add a printer in db
378
     *
379
     *  @param    string    $name           Printer name
380
     *  @param    int       $type           Printer type
381
     *  @param    int       $profile        Printer profile
382
     *  @param    string    $parameter      Printer parameter
383
     *  @return  int                        0 if OK; >0 if KO
384
     */
385
    public function addPrinter($name, $type, $profile, $parameter)
386
    {
387
        global $conf;
388
        $error = 0;
389
        $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt';
390
        $sql .= ' (name, fk_type, fk_profile, parameter, entity)';
391
        $sql .= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')';
392
        $resql = $this->db->query($sql);
393
        if (!$resql) {
394
            $error++;
395
            $this->errors[] = $this->db->lasterror;
396
        }
397
        return $error;
398
    }
399
400
    /**
401
     *  Function to Update a printer in db
402
     *
403
     *  @param    string    $name           Printer name
404
     *  @param    int       $type           Printer type
405
     *  @param    int       $profile        Printer profile
406
     *  @param    string    $parameter      Printer parameter
407
     *  @param    int       $printerid      Printer id
408
     *  @return  int                        0 if OK; >0 if KO
409
     */
410
    public function updatePrinter($name, $type, $profile, $parameter, $printerid)
411
    {
412
        global $conf;
413
        $error = 0;
414
        $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt';
415
        $sql .= ' SET name="'.$this->db->escape($name).'"';
416
        $sql .= ', fk_type='.$type;
417
        $sql .= ', fk_profile='.$profile;
418
        $sql .= ', parameter="'.$this->db->escape($parameter).'"';
419
        $sql .= ' WHERE rowid='.$printerid;
420
        $resql = $this->db->query($sql);
421
        if (!$resql) {
422
            $error++;
423
            $this->errors[] = $this->db->lasterror;
424
        }
425
        return $error;
426
    }
427
428
    /**
429
     *  Function to Delete a printer from db
430
     *
431
     *  @param    int       $printerid      Printer id
432
     *  @return  int                        0 if OK; >0 if KO
433
     */
434
    public function deletePrinter($printerid)
435
    {
436
        global $conf;
437
        $error = 0;
438
        $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt';
439
        $sql .= ' WHERE rowid='.$printerid;
440
        $resql = $this->db->query($sql);
441
        if (!$resql) {
442
            $error++;
443
            $this->errors[] = $this->db->lasterror;
444
        }
445
        return $error;
446
    }
447
448
    /**
449
     *  Function to add a printer template in db
450
     *
451
     *  @param    string    $name           Template name
452
     *  @param    int       $template       Template
453
     *  @return   int                       0 if OK; >0 if KO
454
     */
455
    public function addTemplate($name, $template)
456
    {
457
        global $conf;
458
        $error = 0;
459
        $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt_template';
460
        $sql .= ' (name, template, entity) VALUES ("'.$this->db->escape($name).'"';
461
        $sql .= ', "'.$this->db->escape($template).'", '.$conf->entity.')';
462
        $resql = $this->db->query($sql);
463
        if (!$resql) {
464
            $error++;
465
            $this->errors[] = $this->db->lasterror;
466
        }
467
        return $error;
468
    }
469
470
    /**
471
     *  Function to delete a printer template in db
472
     *
473
     *  @param    int       $templateid     Template ID
474
     *  @return   int                       0 if OK; >0 if KO
475
     */
476
    public function deleteTemplate($templateid)
477
    {
478
    	global $conf;
479
    	$error = 0;
480
    	$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
481
    	$sql .= " WHERE rowid = ".((int) $this->db->escape($templateid));
482
    	$sql .= " AND entity = ".$conf->entity;
483
    	$resql = $this->db->query($sql);
484
    	if (!$resql) {
485
    		$error++;
486
    		$this->errors[] = $this->db->lasterror;
487
    	}
488
    	return $error;
489
    }
490
491
    /**
492
     *  Function to Update a printer template in db
493
     *
494
     *  @param    string    $name           Template name
495
     *  @param    int       $template       Template
496
     *  @param    int       $templateid     Template id
497
     *  @return   int                       0 if OK; >0 if KO
498
     */
499
    public function updateTemplate($name, $template, $templateid)
500
    {
501
        global $conf;
502
        $error = 0;
503
        $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt_template';
504
        $sql .= ' SET name="'.$this->db->escape($name).'"';
505
        $sql .= ', template="'.$this->db->escape($template).'"';
506
        $sql .= ' WHERE rowid='.$templateid;
507
        $resql = $this->db->query($sql);
508
        if (!$resql) {
509
            $error++;
510
            $this->errors[] = $this->db->lasterror;
511
        }
512
        return $error;
513
    }
514
515
516
    /**
517
     *  Function to Send Test page to Printer
518
     *
519
     *  @param    int       $printerid      Printer id
520
     *  @return  int                        0 if OK; >0 if KO
521
     */
522
    public function sendTestToPrinter($printerid)
523
    {
524
        global $conf;
525
        $error = 0;
526
        $img = EscposImage::load(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo_bw.png');
527
        //$this->profile = CapabilityProfile::load("TM-T88IV");
528
        $ret = $this->initPrinter($printerid);
529
        if ($ret > 0) {
530
            setEventMessages($this->error, $this->errors, 'errors');
531
        } else {
532
            try {
533
                $this->printer->bitImage($img);
534
                $this->printer->text("Hello World!\n");
535
                $testStr = "1234567890";
536
                $this->printer->barcode($testStr);
537
                //$this->printer->qrcode($testStr, Printer::QR_ECLEVEL_M, 5, Printer::QR_MODEL_1);
538
                $this->printer->text("Most simple example\n");
539
                $this->printer->feed();
540
                $this->printer->cut();
541
542
				// If is DummyPrintConnector send to log to debugging
543
				if ($this->printer->connector instanceof DummyPrintConnector)
544
				{
545
					$data = $this->printer->connector-> getData();
546
					dol_syslog($data);
547
				}
548
                $this->printer->close();
549
            } catch (Exception $e) {
550
                $this->errors[] = $e->getMessage();
551
                $error++;
552
            }
553
        }
554
        return $error;
555
    }
556
557
    /**
558
     *  Function to Print Receipt Ticket
559
     *
560
     *  @param   Facture|Commande   $object         Order or invoice object
561
     *  @param   int       			$templateid     Template id
562
     *  @param   int       			$printerid      Printer id
563
     *  @return  int                				0 if OK; >0 if KO
564
     */
565
    public function sendToPrinter($object, $templateid, $printerid)
566
    {
567
        global $conf, $mysoc, $langs, $user;
568
        $error = 0;
569
        $ret = $this->loadTemplate($templateid);
570
571
        // tags a remplacer par leur valeur avant de parser (dol_value_xxx)
572
        $this->template = str_replace('<dol_value_object_id>', $object->id, $this->template);
573
        $this->template = str_replace('<dol_value_object_ref>', $object->ref, $this->template);
574
        //$this->template = str_replace('<dol_value_object_points>', $object->points, $this->template);
575
        $this->template = str_replace('<dol_value_date>', dol_print_date($object->date, 'day'), $this->template);
576
        $this->template = str_replace('<dol_value_date_time>', dol_print_date($object->date, 'dayhour'), $this->template);
577
        $this->template = str_replace('<dol_value_year>', dol_print_date($object->date, '%Y'), $this->template);
578
        $this->template = str_replace('<dol_value_month_letters>', $langs->trans("Month".dol_print_date($object->date, '%m')), $this->template);
579
        $this->template = str_replace('<dol_value_month>', dol_print_date($object->date, '%m'), $this->template);
580
        $this->template = str_replace('<dol_value_day>', dol_print_date($object->date, '%d'), $this->template);
581
        $this->template = str_replace('<dol_value_day_letters>', $langs->trans("Day".dol_print_date($object->date, '%m')[1]), $this->template);
582
583
        $this->template = str_replace('<dol_value_customer_firstname>', $object->thirdparty->firstname, $this->template);
584
        $this->template = str_replace('<dol_value_customer_lastname>', $object->thirdparty->lastname, $this->template);
585
        $this->template = str_replace('<dol_value_customer_mail>', $object->thirdparty->email, $this->template);
586
        $this->template = str_replace('<dol_value_customer_phone>', $object->thirdparty->phone, $this->template);
587
        //$this->template = str_replace('<dol_value_customer_mobile>', $object->thirdparty->mobile, $this->template);
588
        $this->template = str_replace('<dol_value_customer_tax_number>', $object->thirdparty->tva_intra, $this->template);
589
        //$this->template = str_replace('<dol_value_customer_account_balance>', $object->customer_account_balance, $this->template);
590
        //$this->template = str_replace('<dol_value_customer_points>', $object->customer_points, $this->template);
591
592
        $this->template = str_replace('<dol_value_mysoc_name>', $mysoc->name, $this->template);
593
        $this->template = str_replace('<dol_value_mysoc_address>', $mysoc->address, $this->template);
594
        $this->template = str_replace('<dol_value_mysoc_zip>', $mysoc->zip, $this->template);
595
        $this->template = str_replace('<dol_value_mysoc_town>', $mysoc->town, $this->template);
596
        $this->template = str_replace('<dol_value_mysoc_country>', $mysoc->country, $this->template);
597
        $this->template = str_replace('<dol_value_mysoc_idprof1>', $mysoc->idprof1, $this->template);
598
        $this->template = str_replace('<dol_value_mysoc_idprof2>', $mysoc->idprof2, $this->template);
599
        $this->template = str_replace('<dol_value_mysoc_idprof3>', $mysoc->idprof3, $this->template);
600
        $this->template = str_replace('<dol_value_mysoc_idprof4>', $mysoc->idprof4, $this->template);
601
        $this->template = str_replace('<dol_value_mysoc_idprof5>', $mysoc->idprof5, $this->template);
602
        $this->template = str_replace('<dol_value_mysoc_idprof6>', $mysoc->idprof6, $this->template);
603
        $this->template = str_replace('<dol_value_mysoc_tva_intra>', $mysoc->tva_intra, $this->template);
604
        $this->template = str_replace('<dol_value_mysoc_capital>', $mysoc->capital, $this->template);
605
606
        $this->template = str_replace('<dol_value_vendor_firstname>', $user->firstname, $this->template);
607
        $this->template = str_replace('<dol_value_vendor_lastname>', $user->lastname, $this->template);
608
        $this->template = str_replace('<dol_value_vendor_mail>', $user->email, $this->template);
609
610
        // parse template
611
        $p = xml_parser_create();
612
        xml_parse_into_struct($p, $this->template, $vals, $index);
613
        xml_parser_free($p);
614
        //print '<pre>'.print_r($index, true).'</pre>';
615
        //print '<pre>'.print_r($vals, true).'</pre>';
616
        // print ticket
617
        $level = 0;
618
        $nbcharactbyline = (!empty($conf->global->RECEIPT_PRINTER_NB_CHARACT_BY_LINE) ? $conf->global->RECEIPT_PRINTER_NB_CHARACT_BY_LINE : 48);
619
        $ret = $this->initPrinter($printerid);
620
        if ($ret > 0) {
621
            setEventMessages($this->error, $this->errors, 'errors');
622
        } else {
623
            $nboflines = count($vals);
624
            for ($tplline = 0; $tplline < $nboflines; $tplline++) {
625
                //var_dump($vals[$tplline]['value']);
626
                switch ($vals[$tplline]['tag']) {
627
                    case 'DOL_PRINT_TEXT':
628
                        $this->printer->text($vals[$tplline]['value']);
629
                        break;
630
                    case 'DOL_PRINT_OBJECT_LINES':
631
                        foreach ($object->lines as $line) {
632
                            //var_dump($line);
633
                            $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1;
634
                            $spaces = str_repeat(' ', $spacestoadd);
635
                            $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n");
636
                            $this->printer->text(strip_tags(htmlspecialchars_decode($line->product_label))."\n");
637
                        }
638
                        break;
639
                    case 'DOL_PRINT_OBJECT_TAX':
640
                        //var_dump($object);
641
                        $vatarray = array();
642
                        foreach ($object->lines as $line) {
643
                            $vatarray[$line->tva_tx] += $line->total_tva;
644
                        }
645
                        foreach ($vatarray as $vatkey => $vatvalue) {
646
                             $spacestoadd = $nbcharactbyline - strlen($vatkey) - 12;
647
                             $spaces = str_repeat(' ', $spacestoadd);
648
                             $this->printer->text($spaces.$vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n");
649
                        }
650
                        break;
651
                    case 'DOL_PRINT_OBJECT_TAX1':
652
                    	//var_dump($object);
653
                    	$total_localtax1 = 0;
654
                    	foreach ($object->lines as $line) {
655
                    		$total_localtax1 += $line->total_localtax1;
656
                    	}
657
                    	foreach ($vatarray as $vatkey => $vatvalue) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $vatarray does not seem to be defined for all execution paths leading up to this point.
Loading history...
658
                    		$this->printer->text(str_pad(price($total_localtax1), 10, ' ', STR_PAD_LEFT)."\n");
659
                    	}
660
                    	break;
661
                    case 'DOL_PRINT_OBJECT_TAX2':
662
                    	//var_dump($object);
663
                    	$total_localtax2 = 0;
664
                    	foreach ($object->lines as $line) {
665
                    		$total_localtax2 += $line->total_localtax2;
666
                    	}
667
                    	foreach ($vatarray as $vatkey => $vatvalue) {
668
                    		$this->printer->text(str_pad(price($total_localtax2), 10, ' ', STR_PAD_LEFT)."\n");
669
                    	}
670
                    	break;
671
                    case 'DOL_PRINT_OBJECT_TOTAL':
672
                        $title = $langs->trans('TotalHT');
673
                        $spacestoadd = $nbcharactbyline - strlen($title) - 10;
674
                        $spaces = str_repeat(' ', $spacestoadd);
675
                        $this->printer->text($title.$spaces.str_pad(price($object->total_ht), 10, ' ', STR_PAD_LEFT)."\n");
676
                        $title = $langs->trans('TotalVAT');
677
                        $spacestoadd = $nbcharactbyline - strlen($title) - 10;
678
                        $spaces = str_repeat(' ', $spacestoadd);
679
                        $this->printer->text($title.$spaces.str_pad(price($object->total_tva), 10, ' ', STR_PAD_LEFT)."\n");
680
                        $title = $langs->trans('TotalTTC');
681
                        $spacestoadd = $nbcharactbyline - strlen($title) - 10;
682
                        $spaces = str_repeat(' ', $spacestoadd);
683
                        $this->printer->text($title.$spaces.str_pad(price($object->total_ttc), 10, ' ', STR_PAD_LEFT)."\n");
684
                        break;
685
                    case 'DOL_LINE_FEED':
686
                        $this->printer->feed();
687
                        break;
688
                    case 'DOL_LINE_FEED_REVERSE':
689
                        $this->printer->feedReverse();
690
                        break;
691
                    case 'DOL_ALIGN_CENTER':
692
                        $this->printer->setJustification(Printer::JUSTIFY_CENTER);
693
                        break;
694
                    case 'DOL_ALIGN_RIGHT':
695
                        $this->printer->setJustification(Printer::JUSTIFY_RIGHT);
696
                        break;
697
                    case 'DOL_ALIGN_LEFT':
698
                        $this->printer->setJustification(Printer::JUSTIFY_LEFT);
699
                        break;
700
                    case 'DOL_OPEN_DRAWER':
701
                        $this->printer->pulse();
702
                        break;
703
                    case 'DOL_ACTIVATE_BUZZER':
704
                        //$this->printer->buzzer();
705
                        break;
706
                    case 'DOL_PRINT_BARCODE':
707
                        // $vals[$tplline]['value'] -> barcode($content, $type)
708
                        // var_dump($vals[$tplline]['value']);
709
                        try {
710
                            $this->printer->barcode($vals[$tplline]['value']);
711
                        } catch (Exception $e) {
712
                            $this->errors[] = 'Invalid Barcode value: '.$vals[$tplline]['value'];
713
                            $error++;
714
                        }
715
                        break;
716
                    case 'DOL_PRINT_LOGO':
717
                        $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo);
718
                        $this->printer->graphics($img);
719
                        break;
720
                    case 'DOL_PRINT_LOGO_OLD':
721
                        $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo);
722
                        $this->printer->bitImage($img);
723
                        break;
724
                    case 'DOL_PRINT_QRCODE':
725
                        // $vals[$tplline]['value'] -> qrCode($content, $ec, $size, $model)
726
                        $this->printer->qrcode($vals[$tplline]['value']);
727
                        break;
728
                    case 'DOL_CUT_PAPER_FULL':
729
                        $this->printer->cut(Printer::CUT_FULL);
730
                        break;
731
                    case 'DOL_CUT_PAPER_PARTIAL':
732
                        $this->printer->cut(Printer::CUT_PARTIAL);
733
                        break;
734
                    case 'DOL_USE_FONT_A':
735
                        $this->printer->setFont(Printer::FONT_A);
736
                        break;
737
                    case 'DOL_USE_FONT_B':
738
                        $this->printer->setFont(Printer::FONT_B);
739
                        break;
740
                    case 'DOL_USE_FONT_C':
741
                        $this->printer->setFont(Printer::FONT_C);
742
                        break;
743
					case 'DOL_BOLD':
744
                        $this->printer->setEmphasis(true);
745
                        break;
746
					case 'DOL_BOLD_DISABLED':
747
                        $this->printer->setEmphasis(false);
748
                        break;
749
					case 'DOL_DOUBLE_HEIGHT':
750
                        $this->printer->setTextSize(1, 2);
751
                        break;
752
					case 'DOL_DOUBLE_WIDTH':
753
                        $this->printer->setTextSize(2, 1);
754
                        break;
755
					case 'DOL_DEFAULT_HEIGHT_WIDTH':
756
                        $this->printer->setTextSize(1, 1);
757
                        break;
758
					case 'DOL_UNDERLINE':
759
                        $this->printer->setUnderline(true);
760
                        break;
761
					case 'DOL_UNDERLINE_DISABLED':
762
                        $this->printer->setUnderline(false);
763
                        break;
764
					case 'DOL_BEEP':
765
                        $this->printer->getPrintConnector() -> write("\x1e");
766
                        break;
767
					case 'DOL_PRINT_ORDER_LINES':
768
						foreach ($object->lines as $line) {
769
							if ($line->special_code == $this->orderprinter)
770
							{
771
								$spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1;
772
								$spaces = str_repeat(' ', $spacestoadd);
773
								$this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n");
774
								$this->printer->text(strip_tags(htmlspecialchars_decode($line->desc))."\n");
775
							}
776
                        }
777
						break;
778
                    default:
779
                        $this->printer->text($vals[$tplline]['tag']);
780
                        $this->printer->text($vals[$tplline]['value']);
781
                        $this->errors[] = 'UnknowTag: &lt;'.strtolower($vals[$tplline]['tag']).'&gt;';
782
                        $error++;
783
                        break;
784
                }
785
            }
786
            // If is DummyPrintConnector send to log to debugging
787
			if ($this->printer->connector instanceof DummyPrintConnector)
788
			{
789
				$data = $this->printer->connector->getData();
790
				dol_syslog($data);
791
			}
792
			// Close and print
793
            $this->printer->close();
794
        }
795
        return $error;
796
    }
797
798
    /**
799
     *  Function to load Template
800
     *
801
     *  @param   int       $templateid          Template id
802
     *  @return  int                            0 if OK; >0 if KO
803
     */
804
    public function loadTemplate($templateid)
805
    {
806
        global $conf;
807
        $error = 0;
808
        $sql = 'SELECT template';
809
        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
810
        $sql .= ' WHERE rowid='.$templateid;
811
        $sql .= ' AND entity = '.$conf->entity;
812
        $resql = $this->db->query($sql);
813
        if ($resql) {
814
            $obj = $this->db->fetch_array($resql);
815
        } else {
816
            $error++;
817
            $this->errors[] = $this->db->lasterror;
818
        }
819
        if (empty($obj)) {
820
            $error++;
821
            $this->errors[] = 'TemplateDontExist';
822
        } else {
823
            $this->template = $obj['0'];
824
        }
825
826
        return $error;
827
    }
828
829
830
    /**
831
     *  Function Init Printer
832
     *
833
     *  @param   int       $printerid       Printer id
834
     *  @return  int                        0 if OK; >0 if KO
835
     */
836
    public function initPrinter($printerid)
837
    {
838
        global $conf;
839
        $error = 0;
840
        $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter';
841
        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
842
        $sql .= ' WHERE rowid = '.$printerid;
843
        $sql .= ' AND entity = '.$conf->entity;
844
        $resql = $this->db->query($sql);
845
        if ($resql) {
846
            $obj = $this->db->fetch_array($resql);
847
        } else {
848
            $error++;
849
            $this->errors[] = $this->db->lasterror;
850
        }
851
        if (empty($obj)) {
852
            $error++;
853
            $this->errors[] = 'PrinterDontExist';
854
        }
855
        if (!$error) {
856
            $parameter = $obj['parameter'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $obj does not seem to be defined for all execution paths leading up to this point.
Loading history...
857
            try {
858
                switch ($obj['fk_type']) {
859
                    case 1:
860
                        $this->connector = new DummyPrintConnector();
861
                        break;
862
                    case 2:
863
                        $this->connector = new FilePrintConnector($parameter);
864
                        break;
865
                    case 3:
866
                        $parameters = explode(':', $parameter);
867
                        $this->connector = new NetworkPrintConnector($parameters[0], $parameters[1]);
868
                        break;
869
                    case 4:
870
                        $this->connector = new WindowsPrintConnector($parameter);
871
                        break;
872
					case 5:
873
                        $this->connector = new CupsPrintConnector($parameter);
874
                        break;
875
                    default:
876
                        $this->connector = 'CONNECTOR_UNKNOWN';
877
                        break;
878
                }
879
                $this->printer = new Printer($this->connector, $this->profile);
880
            } catch (Exception $e) {
881
                $this->errors[] = $e->getMessage();
882
                $error++;
883
            }
884
        }
885
        return $error;
886
    }
887
}
888