dolibarr 21.0.0-beta
printgcp.modules.php
Go to the documentation of this file.
1<?php
2/*
3 * Copyright (C) 2014-2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
27include_once DOL_DOCUMENT_ROOT.'/core/modules/printing/modules_printing.php';
28require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
29
30use OAuth\Common\Storage\DoliStorage;
31use OAuth\Common\Consumer\Credentials;
32
37{
41 public $name = 'printgcp';
42
46 public $desc = 'PrintGCPDesc';
47
51 public $picto = 'printer';
52
56 public $active = 'PRINTING_PRINTGCP';
57
61 public $conf = array();
62
66 public $google_id = '';
67
71 public $google_secret = '';
72
76 public $db;
77
81 private $OAUTH_SERVICENAME_GOOGLE = 'Google';
82
83 const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token';
84 const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search';
85 const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs';
86 const PRINT_URL = 'https://www.google.com/cloudprint/submit';
87
88
94 public function __construct($db)
95 {
96 global $conf, $langs, $dolibarr_main_url_root;
97
98 // Define $urlwithroot
99 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
100 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
101 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
102
103 $this->db = $db;
104
105 if (!$conf->oauth->enabled) {
106 $this->conf[] = array(
107 'varname' => 'PRINTGCP_INFO',
108 'info' => $langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"),
109 'type' => 'info',
110 );
111 } else {
112 $keyforprovider = ''; // @FIXME
113
114 $this->google_id = getDolGlobalString('OAUTH_GOOGLE_ID');
115 $this->google_secret = getDolGlobalString('OAUTH_GOOGLE_SECRET');
116 // Token storage
117 $storage = new DoliStorage($this->db, $conf, $keyforprovider);
118 //$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE);
119 // Setup the credentials for the requests
120 $credentials = new Credentials(
121 $this->google_id,
122 $this->google_secret,
123 $urlwithroot.'/core/modules/oauth/google_oauthcallback.php'
124 );
125 $access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken');
126 $serviceFactory = new \OAuth\ServiceFactory();
127 $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
128 '@phan-var-force OAuth\OAuth2\Service\Google $apiService'; // createService is only ServiceInterface
129 $token_ok = true;
130 try {
131 $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
132 } catch (Exception $e) {
133 $this->errors[] = $e->getMessage();
134 $token_ok = false;
135 }
136
137 $expire = false;
138 // Is token expired or will token expire in the next 30 seconds
139 if ($token_ok) {
140 $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
141 }
142
143 // Token expired so we refresh it
144 if ($token_ok && $expire) {
145 try {
146 // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
147 $refreshtoken = $token->getRefreshToken();
148 $token = $apiService->refreshAccessToken($token);
149 $token->setRefreshToken($refreshtoken);
150 $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
151 } catch (Exception $e) {
152 $this->errors[] = $e->getMessage();
153 }
154 }
155 if ($this->google_id != '' && $this->google_secret != '') {
156 $this->conf[] = array('varname' => 'PRINTGCP_INFO', 'info' => 'GoogleAuthConfigured', 'type' => 'info');
157 $this->conf[] = array(
158 'varname' => 'PRINTGCP_TOKEN_ACCESS',
159 'info' => $access,
160 'type' => 'info',
161 'renew' => $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'),
162 'delete' => ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp') : '')
163 );
164 if ($token_ok) {
165 $expiredat = '';
166
167 $refreshtoken = $token->getRefreshToken();
168
169 $endoflife = $token->getEndOfLife();
170
171 if ($endoflife == $token::EOL_NEVER_EXPIRES) {
172 $expiredat = $langs->trans("Never");
173 } elseif ($endoflife == $token::EOL_UNKNOWN) {
174 $expiredat = $langs->trans("Unknown");
175 } else {
176 $expiredat = dol_print_date($endoflife, "dayhour");
177 }
178
179 $this->conf[] = array('varname' => 'TOKEN_REFRESH', 'info' => ((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type' => 'info');
180 $this->conf[] = array('varname' => 'TOKEN_EXPIRED', 'info' => ($expire ? 'Yes' : 'No'), 'type' => 'info');
181 $this->conf[] = array('varname' => 'TOKEN_EXPIRE_AT', 'info' => ($expiredat), 'type' => 'info');
182 }
183 /*
184 if ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE)) {
185 $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'authlink');
186 $this->conf[] = array('varname'=>'DELETE_TOKEN', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'delete');
187 } else {
188 $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'authlink');
189 }*/
190 } else {
191 $this->conf[] = array('varname' => 'PRINTGCP_INFO', 'info' => 'GoogleAuthNotConfigured', 'type' => 'info');
192 }
193 }
194 // do not display submit button
195 $this->conf[] = array('enabled' => 0, 'type' => 'submit');
196 }
197
203 public function listAvailablePrinters()
204 {
205 global $conf, $langs;
206 $error = 0;
207 $langs->load('printing');
208
209 $html = '<tr class="liste_titre">';
210 $html .= '<td>'.$langs->trans('GCP_Name').'</td>';
211 $html .= '<td>'.$langs->trans('GCP_displayName').'</td>';
212 $html .= '<td>'.$langs->trans('GCP_Id').'</td>';
213 $html .= '<td>'.$langs->trans('GCP_OwnerName').'</td>';
214 $html .= '<td>'.$langs->trans('GCP_State').'</td>';
215 $html .= '<td>'.$langs->trans('GCP_connectionStatus').'</td>';
216 $html .= '<td>'.$langs->trans('GCP_Type').'</td>';
217 $html .= '<td class="center">'.$langs->trans("Select").'</td>';
218 $html .= '</tr>'."\n";
219 $list = $this->getlistAvailablePrinters();
220 //$html.= '<td><pre>'.print_r($list,true).'</pre></td>';
221 foreach ($list['available'] as $printer_det) {
222 $html .= '<tr class="oddeven">';
223 $html .= '<td>'.$printer_det['name'].'</td>';
224 $html .= '<td>'.$printer_det['displayName'].'</td>';
225 $html .= '<td>'.$printer_det['id'].'</td>'; // id to identify printer to use
226 $html .= '<td>'.$printer_det['ownerName'].'</td>';
227 $html .= '<td>'.$printer_det['status'].'</td>';
228 $html .= '<td>'.$langs->trans('STATE_'.$printer_det['connectionStatus']).'</td>';
229 $html .= '<td>'.$langs->trans('TYPE_'.$printer_det['type']).'</td>';
230 // Default
231 $html .= '<td class="center">';
232 if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) {
233 $html .= img_picto($langs->trans("Default"), 'on');
234 } else {
235 $html .= '<a href="'.$_SERVER["PHP_SELF"].'?action=setvalue&token='.newToken().'&mode=test&varname=PRINTING_GCP_DEFAULT&driver=printgcp&value='.urlencode($printer_det['id']).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
236 }
237 $html .= '</td>';
238 $html .= '</tr>'."\n";
239 }
240 $this->resprint = $html;
241 return $error;
242 }
243
244
250 public function getlistAvailablePrinters()
251 {
252 global $conf;
253 $ret = array();
254
255 $keyforprovider = ''; // @FIXME
256
257 // Token storage
258 $storage = new DoliStorage($this->db, $conf, $keyforprovider);
259 // Setup the credentials for the requests
260 $credentials = new Credentials(
261 $this->google_id,
262 $this->google_secret,
263 DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php'
264 );
265 $serviceFactory = new \OAuth\ServiceFactory();
266 $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
267 '@phan-var-force OAuth\OAuth2\Service\Google $apiService'; // createService is only ServiceInterface
268 // Check if we have auth token
269 $token_ok = true;
270 try {
271 $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
272 } catch (Exception $e) {
273 $this->errors[] = $e->getMessage();
274 $token_ok = false;
275 }
276 $expire = false;
277 // Is token expired or will token expire in the next 30 seconds
278 if ($token_ok) {
279 $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
280 }
281
282 // Token expired so we refresh it
283 if ($token_ok && $expire) {
284 try {
285 // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
286 $refreshtoken = $token->getRefreshToken();
287 $token = $apiService->refreshAccessToken($token);
288 $token->setRefreshToken($refreshtoken);
289 $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
290 } catch (Exception $e) {
291 $this->errors[] = $e->getMessage();
292 }
293 }
294 // Send a request with api
295 try {
296 $response = $apiService->request(self::PRINTERS_SEARCH_URL);
297 } catch (Exception $e) {
298 $this->errors[] = $e->getMessage();
299 print '<pre>'.print_r($e->getMessage(), true).'</pre>';
300 }
301 //print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
302 $responsedata = json_decode($response, true);
303 $printers = $responsedata['printers'];
304 // Check if we have printers?
305 if (is_array($printers) && count($printers) == 0) {
306 // We don't have printers so return blank array
307 $ret['available'] = array();
308 } else {
309 // We have printers so returns printers as array
310 $ret['available'] = $printers;
311 }
312 return $ret;
313 }
314
323 public function printFile($file, $module, $subdir = '')
324 {
325 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
326
327 global $conf, $user;
328 $error = 0;
329
330 $fileprint = $conf->{$module}->dir_output;
331 if ($subdir != '') {
332 $fileprint .= '/'.$subdir;
333 }
334 $fileprint .= '/'.$file;
335 $mimetype = dol_mimetype($fileprint);
336 $printer_id = '';
337 // select printer uri for module order, propal,...
338 $sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$this->db->escape($module)."' AND driver='printgcp' AND userid=".((int) $user->id);
339 $result = $this->db->query($sql);
340 if ($result) {
341 $obj = $this->db->fetch_object($result);
342 if ($obj) {
343 $printer_id = $obj->printer_id;
344 } else {
345 if (getDolGlobalString('PRINTING_GCP_DEFAULT')) {
346 $printer_id = getDolGlobalString('PRINTING_GCP_DEFAULT');
347 } else {
348 $this->errors[] = 'NoDefaultPrinterDefined';
349 $error++;
350 return $error;
351 }
352 }
353 } else {
354 dol_print_error($this->db);
355 }
356
357 $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype);
358 $this->error = 'PRINTGCP: '.$ret['errormessage'];
359 if ($ret['status'] != 1) {
360 $error++;
361 }
362 return $error;
363 }
364
374 public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype)
375 {
376 global $conf;
377 // Check if printer id
378 if (empty($printerid)) {
379 return array('status' => 0, 'errorcode' => '', 'errormessage' => 'No provided printer ID');
380 }
381 // Open the file which needs to be print
382 $handle = fopen($filepath, "rb");
383 if (!$handle) {
384 return array('status' => 0, 'errorcode' => '', 'errormessage' => 'Could not read the file.');
385 }
386 // Read file content
387 $contents = fread($handle, filesize($filepath));
388 fclose($handle);
389 // Prepare post fields for sending print
390 $post_fields = array(
391 'printerid' => $printerid,
392 'title' => $printjobtitle,
393 'contentTransferEncoding' => 'base64',
394 'content' => base64_encode($contents), // encode file content as base64
395 'contentType' => $contenttype,
396 );
397
398 $keyforprovider = ''; // @FIXME
399
400 // Dolibarr Token storage
401 $storage = new DoliStorage($this->db, $conf, $keyforprovider);
402 // Setup the credentials for the requests
403 $credentials = new Credentials(
404 $this->google_id,
405 $this->google_secret,
406 DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google'
407 );
408 $serviceFactory = new \OAuth\ServiceFactory();
409 $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
410 '@phan-var-force OAuth\OAuth2\Service\Google $apiService'; // createService is only ServiceInterface
411
412 // Check if we have auth token and refresh it
413 $token_ok = true;
414 try {
415 $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
416 } catch (Exception $e) {
417 $this->errors[] = $e->getMessage();
418 $token_ok = false;
419 }
420 if ($token_ok) {
421 try {
422 // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
423 $refreshtoken = $token->getRefreshToken();
424 $token = $apiService->refreshAccessToken($token);
425 $token->setRefreshToken($refreshtoken);
426 $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
427 } catch (Exception $e) {
428 $this->errors[] = $e->getMessage();
429 }
430 }
431
432 // Send a request with api
433 $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true);
434 //print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
435 return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']);
436 }
437
438
446 public function listJobs($module = null)
447 {
448 global $conf, $langs;
449
450 $error = 0;
451 $html = '';
452
453 $keyforprovider = ''; // @FIXME
454
455 // Token storage
456 $storage = new DoliStorage($this->db, $conf, $keyforprovider);
457 // Setup the credentials for the requests
458 $credentials = new Credentials(
459 $this->google_id,
460 $this->google_secret,
461 DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php'
462 );
463 $serviceFactory = new \OAuth\ServiceFactory();
464 $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
465 '@phan-var-force OAuth\OAuth2\Service\Google $apiService'; // createService is only ServiceInterface
466 // Check if we have auth token
467 $token_ok = true;
468 try {
469 $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
470 } catch (Exception $e) {
471 $this->errors[] = $e->getMessage();
472 $token_ok = false;
473 $error++;
474 }
475 $expire = false;
476 // Is token expired or will token expire in the next 30 seconds
477 if ($token_ok) {
478 $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
479 }
480
481 // Token expired so we refresh it
482 if ($token_ok && $expire) {
483 try {
484 // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
485 $refreshtoken = $token->getRefreshToken();
486 $token = $apiService->refreshAccessToken($token);
487 $token->setRefreshToken($refreshtoken);
488 $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
489 } catch (Exception $e) {
490 $this->errors[] = $e->getMessage();
491 $error++;
492 }
493 }
494 // Getting Jobs
495 // Send a request with api
496 try {
497 $response = $apiService->request(self::PRINTERS_GET_JOBS);
498 } catch (Exception $e) {
499 $this->errors[] = $e->getMessage();
500 $error++;
501 }
502 $responsedata = json_decode($response, true);
503 //$html .= '<pre>'.print_r($responsedata,true).'</pre>';
504 $html .= '<div class="div-table-responsive">';
505 $html .= '<table width="100%" class="noborder">';
506 $html .= '<tr class="liste_titre">';
507 $html .= '<td>'.$langs->trans("Id").'</td>';
508 $html .= '<td>'.$langs->trans("Date").'</td>';
509 $html .= '<td>'.$langs->trans("Owner").'</td>';
510 $html .= '<td>'.$langs->trans("Printer").'</td>';
511 $html .= '<td>'.$langs->trans("Filename").'</td>';
512 $html .= '<td>'.$langs->trans("Status").'</td>';
513 $html .= '<td>'.$langs->trans("Cancel").'</td>';
514 $html .= '</tr>'."\n";
515
516 $jobs = $responsedata['jobs'];
517 //$html .= '<pre>'.print_r($jobs['0'],true).'</pre>';
518 if (is_array($jobs)) {
519 foreach ($jobs as $value) {
520 $html .= '<tr class="oddeven">';
521 $html .= '<td>'.$value['id'].'</td>';
522 $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour');
523 $html .= '<td>'.$dates.'</td>';
524 $html .= '<td>'.$value['ownerId'].'</td>';
525 $html .= '<td>'.$value['printerName'].'</td>';
526 $html .= '<td>'.$value['title'].'</td>';
527 $html .= '<td>'.$value['status'].'</td>';
528 $html .= '<td>&nbsp;</td>';
529 $html .= '</tr>';
530 }
531 } else {
532 $html .= '<tr class="oddeven">';
533 $html .= '<td colspan="7" class="opacitymedium">'.$langs->trans("None").'</td>';
534 $html .= '</tr>';
535 }
536 $html .= '</table>';
537 $html .= '</div>';
538
539 $this->resprint = $html;
540
541 return $error;
542 }
543}
Parent class of emailing target selectors modules.
Class to provide printing with Google Cloud Print.
listJobs($module=null)
List jobs print.
__construct($db)
Constructor.
listAvailablePrinters()
Return list of available printers.
printFile($file, $module, $subdir='')
Print selected file.
getlistAvailablePrinters()
Return list of available printers.
sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype)
Sends document to the printer.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition inc.php:420
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79