dolibarr  x.y.z
printgcp.modules.php
Go to the documentation of this file.
1 <?php
2 /*
3  * Copyright (C) 2014-2019 Frédéric France <frederic.france@netlogic.fr>
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 
26 include_once DOL_DOCUMENT_ROOT.'/core/modules/printing/modules_printing.php';
27 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
28 
29 use OAuth\Common\Storage\DoliStorage;
30 use OAuth\Common\Consumer\Credentials;
31 use OAuth\OAuth2\Service\Google;
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 $error = '';
77 
81  public $errors = array();
82 
86  public $db;
87 
88  private $OAUTH_SERVICENAME_GOOGLE = 'Google';
89 
90  const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token';
91  const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search';
92  const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs';
93  const PRINT_URL = 'https://www.google.com/cloudprint/submit';
94  const LANGFILE = 'printgcp';
95 
101  public function __construct($db)
102  {
103  global $conf, $langs, $dolibarr_main_url_root;
104 
105  // Define $urlwithroot
106  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
107  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
108  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
109 
110  $this->db = $db;
111 
112  if (!$conf->oauth->enabled) {
113  $this->conf[] = array(
114  'varname'=>'PRINTGCP_INFO',
115  'info'=>$langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"),
116  'type'=>'info',
117  );
118  } else {
119  $this->google_id = getDolGlobalString('OAUTH_GOOGLE_ID');
120  $this->google_secret = getDolGlobalString('OAUTH_GOOGLE_SECRET');
121  // Token storage
122  $storage = new DoliStorage($this->db, $this->conf);
123  //$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE);
124  // Setup the credentials for the requests
125  $credentials = new Credentials(
126  $this->google_id,
127  $this->google_secret,
128  $urlwithroot.'/core/modules/oauth/google_oauthcallback.php'
129  );
130  $access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken');
131  $serviceFactory = new \OAuth\ServiceFactory();
132  $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
133  $token_ok = true;
134  try {
135  $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
136  } catch (Exception $e) {
137  $this->errors[] = $e->getMessage();
138  $token_ok = false;
139  }
140 
141  $expire = false;
142  // Is token expired or will token expire in the next 30 seconds
143  if ($token_ok) {
144  $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
145  }
146 
147  // Token expired so we refresh it
148  if ($token_ok && $expire) {
149  try {
150  // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
151  $refreshtoken = $token->getRefreshToken();
152  $token = $apiService->refreshAccessToken($token);
153  $token->setRefreshToken($refreshtoken);
154  $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
155  } catch (Exception $e) {
156  $this->errors[] = $e->getMessage();
157  }
158  }
159  if ($this->google_id != '' && $this->google_secret != '') {
160  $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthConfigured', 'type'=>'info');
161  $this->conf[] = array(
162  'varname'=>'PRINTGCP_TOKEN_ACCESS',
163  'info'=>$access,
164  'type'=>'info',
165  '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'),
166  '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') : '')
167  );
168  if ($token_ok) {
169  $expiredat = '';
170 
171  $refreshtoken = $token->getRefreshToken();
172 
173  $endoflife = $token->getEndOfLife();
174 
175  if ($endoflife == $token::EOL_NEVER_EXPIRES) {
176  $expiredat = $langs->trans("Never");
177  } elseif ($endoflife == $token::EOL_UNKNOWN) {
178  $expiredat = $langs->trans("Unknown");
179  } else {
180  $expiredat = dol_print_date($endoflife, "dayhour");
181  }
182 
183  $this->conf[] = array('varname'=>'TOKEN_REFRESH', 'info'=>((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type'=>'info');
184  $this->conf[] = array('varname'=>'TOKEN_EXPIRED', 'info'=>($expire ? 'Yes' : 'No'), 'type'=>'info');
185  $this->conf[] = array('varname'=>'TOKEN_EXPIRE_AT', 'info'=>($expiredat), 'type'=>'info');
186  }
187  /*
188  if ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE)) {
189  $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');
190  $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');
191  } else {
192  $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');
193  }*/
194  } else {
195  $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info');
196  }
197  }
198  // do not display submit button
199  $this->conf[] = array('enabled'=>0, 'type'=>'submit');
200  }
201 
207  public function listAvailablePrinters()
208  {
209  global $conf, $langs;
210  $error = 0;
211  $langs->load('printing');
212 
213  $html = '<tr class="liste_titre">';
214  $html .= '<td>'.$langs->trans('GCP_Name').'</td>';
215  $html .= '<td>'.$langs->trans('GCP_displayName').'</td>';
216  $html .= '<td>'.$langs->trans('GCP_Id').'</td>';
217  $html .= '<td>'.$langs->trans('GCP_OwnerName').'</td>';
218  $html .= '<td>'.$langs->trans('GCP_State').'</td>';
219  $html .= '<td>'.$langs->trans('GCP_connectionStatus').'</td>';
220  $html .= '<td>'.$langs->trans('GCP_Type').'</td>';
221  $html .= '<td class="center">'.$langs->trans("Select").'</td>';
222  $html .= '</tr>'."\n";
223  $list = $this->getlistAvailablePrinters();
224  //$html.= '<td><pre>'.print_r($list,true).'</pre></td>';
225  foreach ($list['available'] as $printer_det) {
226  $html .= '<tr class="oddeven">';
227  $html .= '<td>'.$printer_det['name'].'</td>';
228  $html .= '<td>'.$printer_det['displayName'].'</td>';
229  $html .= '<td>'.$printer_det['id'].'</td>'; // id to identify printer to use
230  $html .= '<td>'.$printer_det['ownerName'].'</td>';
231  $html .= '<td>'.$printer_det['status'].'</td>';
232  $html .= '<td>'.$langs->trans('STATE_'.$printer_det['connectionStatus']).'</td>';
233  $html .= '<td>'.$langs->trans('TYPE_'.$printer_det['type']).'</td>';
234  // Defaut
235  $html .= '<td class="center">';
236  if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) {
237  $html .= img_picto($langs->trans("Default"), 'on');
238  } else {
239  $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>';
240  }
241  $html .= '</td>';
242  $html .= '</tr>'."\n";
243  }
244  $this->resprint = $html;
245  return $error;
246  }
247 
248 
254  public function getlistAvailablePrinters()
255  {
256  $ret = array();
257  // Token storage
258  $storage = new DoliStorage($this->db, $this->conf);
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  // Check if we have auth token
268  $token_ok = true;
269  try {
270  $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
271  } catch (Exception $e) {
272  $this->errors[] = $e->getMessage();
273  $token_ok = false;
274  }
275  $expire = false;
276  // Is token expired or will token expire in the next 30 seconds
277  if ($token_ok) {
278  $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
279  }
280 
281  // Token expired so we refresh it
282  if ($token_ok && $expire) {
283  try {
284  // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
285  $refreshtoken = $token->getRefreshToken();
286  $token = $apiService->refreshAccessToken($token);
287  $token->setRefreshToken($refreshtoken);
288  $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
289  } catch (Exception $e) {
290  $this->errors[] = $e->getMessage();
291  }
292  }
293  // Send a request with api
294  try {
295  $response = $apiService->request(self::PRINTERS_SEARCH_URL);
296  } catch (Exception $e) {
297  $this->errors[] = $e->getMessage();
298  print '<pre>'.print_r($e->getMessage(), true).'</pre>';
299  }
300  //print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
301  $responsedata = json_decode($response, true);
302  $printers = $responsedata['printers'];
303  // Check if we have printers?
304  if (is_array($printers) && count($printers) == 0) {
305  // We dont have printers so return blank array
306  $ret['available'] = array();
307  } else {
308  // We have printers so returns printers as array
309  $ret['available'] = $printers;
310  }
311  return $ret;
312  }
313 
322  public function printFile($file, $module, $subdir = '')
323  {
324  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
325 
326  global $conf, $user;
327  $error = 0;
328 
329  $fileprint = $conf->{$module}->dir_output;
330  if ($subdir != '') {
331  $fileprint .= '/'.$subdir;
332  }
333  $fileprint .= '/'.$file;
334  $mimetype = dol_mimetype($fileprint);
335  $printer_id = '';
336  // select printer uri for module order, propal,...
337  $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);
338  $result = $this->db->query($sql);
339  if ($result) {
340  $obj = $this->db->fetch_object($result);
341  if ($obj) {
342  $printer_id = $obj->printer_id;
343  } else {
344  if (!empty($conf->global->PRINTING_GCP_DEFAULT)) {
345  $printer_id = $conf->global->PRINTING_GCP_DEFAULT;
346  } else {
347  $this->errors[] = 'NoDefaultPrinterDefined';
348  $error++;
349  return $error;
350  }
351  }
352  } else {
353  dol_print_error($this->db);
354  }
355 
356  $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype);
357  $this->error = 'PRINTGCP: '.$ret['errormessage'];
358  if ($ret['status'] != 1) {
359  $error++;
360  }
361  return $error;
362  }
363 
373  public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype)
374  {
375  // Check if printer id
376  if (empty($printerid)) {
377  return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID');
378  }
379  // Open the file which needs to be print
380  $handle = fopen($filepath, "rb");
381  if (!$handle) {
382  return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.');
383  }
384  // Read file content
385  $contents = fread($handle, filesize($filepath));
386  fclose($handle);
387  // Prepare post fields for sending print
388  $post_fields = array(
389  'printerid' => $printerid,
390  'title' => $printjobtitle,
391  'contentTransferEncoding' => 'base64',
392  'content' => base64_encode($contents), // encode file content as base64
393  'contentType' => $contenttype,
394  );
395  // Dolibarr Token storage
396  $storage = new DoliStorage($this->db, $this->conf);
397  // Setup the credentials for the requests
398  $credentials = new Credentials(
399  $this->google_id,
400  $this->google_secret,
401  DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google'
402  );
403  $serviceFactory = new \OAuth\ServiceFactory();
404  $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
405 
406  // Check if we have auth token and refresh it
407  $token_ok = true;
408  try {
409  $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
410  } catch (Exception $e) {
411  $this->errors[] = $e->getMessage();
412  $token_ok = false;
413  }
414  if ($token_ok) {
415  try {
416  // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
417  $refreshtoken = $token->getRefreshToken();
418  $token = $apiService->refreshAccessToken($token);
419  $token->setRefreshToken($refreshtoken);
420  $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
421  } catch (Exception $e) {
422  $this->errors[] = $e->getMessage();
423  }
424  }
425 
426  // Send a request with api
427  $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true);
428  //print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
429  return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']);
430  }
431 
432 
438  public function listJobs()
439  {
440  global $conf, $langs;
441 
442  $error = 0;
443  $html = '';
444  // Token storage
445  $storage = new DoliStorage($this->db, $this->conf);
446  // Setup the credentials for the requests
447  $credentials = new Credentials(
448  $this->google_id,
449  $this->google_secret,
450  DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php'
451  );
452  $serviceFactory = new \OAuth\ServiceFactory();
453  $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
454  // Check if we have auth token
455  $token_ok = true;
456  try {
457  $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
458  } catch (Exception $e) {
459  $this->errors[] = $e->getMessage();
460  $token_ok = false;
461  $error++;
462  }
463  $expire = false;
464  // Is token expired or will token expire in the next 30 seconds
465  if ($token_ok) {
466  $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
467  }
468 
469  // Token expired so we refresh it
470  if ($token_ok && $expire) {
471  try {
472  // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
473  $refreshtoken = $token->getRefreshToken();
474  $token = $apiService->refreshAccessToken($token);
475  $token->setRefreshToken($refreshtoken);
476  $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
477  } catch (Exception $e) {
478  $this->errors[] = $e->getMessage();
479  $error++;
480  }
481  }
482  // Getting Jobs
483  // Send a request with api
484  try {
485  $response = $apiService->request(self::PRINTERS_GET_JOBS);
486  } catch (Exception $e) {
487  $this->errors[] = $e->getMessage();
488  $error++;
489  }
490  $responsedata = json_decode($response, true);
491  //$html .= '<pre>'.print_r($responsedata,true).'</pre>';
492  $html .= '<div class="div-table-responsive">';
493  $html .= '<table width="100%" class="noborder">';
494  $html .= '<tr class="liste_titre">';
495  $html .= '<td>'.$langs->trans("Id").'</td>';
496  $html .= '<td>'.$langs->trans("Date").'</td>';
497  $html .= '<td>'.$langs->trans("Owner").'</td>';
498  $html .= '<td>'.$langs->trans("Printer").'</td>';
499  $html .= '<td>'.$langs->trans("Filename").'</td>';
500  $html .= '<td>'.$langs->trans("Status").'</td>';
501  $html .= '<td>'.$langs->trans("Cancel").'</td>';
502  $html .= '</tr>'."\n";
503 
504  $jobs = $responsedata['jobs'];
505  //$html .= '<pre>'.print_r($jobs['0'],true).'</pre>';
506  if (is_array($jobs)) {
507  foreach ($jobs as $value) {
508  $html .= '<tr class="oddeven">';
509  $html .= '<td>'.$value['id'].'</td>';
510  $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour');
511  $html .= '<td>'.$dates.'</td>';
512  $html .= '<td>'.$value['ownerId'].'</td>';
513  $html .= '<td>'.$value['printerName'].'</td>';
514  $html .= '<td>'.$value['title'].'</td>';
515  $html .= '<td>'.$value['status'].'</td>';
516  $html .= '<td>&nbsp;</td>';
517  $html .= '</tr>';
518  }
519  } else {
520  $html .= '<tr class="oddeven">';
521  $html .= '<td colspan="7" class="opacitymedium">'.$langs->trans("None").'</td>';
522  $html .= '</tr>';
523  }
524  $html .= '</table>';
525  $html .= '</div>';
526 
527  $this->resprint = $html;
528 
529  return $error;
530  }
531 }
Parent class of emailing target selectors modules.
Class to provide printing with Google Cloud Print.
listJobs()
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.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
newToken()
Return the value of token currently saved into session with name 'newtoken'.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition: inc.php:292
$conf db
API class for accounts.
Definition: inc.php:41