--- /tmp/dsg/dolibarr/htdocs/core/modules/printing/github_19.0.3_modules_printing.php +++ /tmp/dsg/dolibarr/htdocs/core/modules/printing/client_modules_printing.php @@ -3 +3 @@ - * Copyright (C) 2014-2023 Frederic France + * Copyright (C) 2014-2018 Frederic France @@ -34,4 +34,4 @@ - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; @@ -39 +39 @@ - /** + /** @@ -44,4 +43,0 @@ - /** - * @var string Name - */ - public $name; @@ -49,4 +45,9 @@ - /** - * @var string Description - */ - public $desc; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } @@ -54,4 +55,10 @@ - /** - * @var string Html string returned for print - */ - public $resprint; + /** + * Return list of printing driver + * + * @param DoliDB $db Database handler + * @param integer $maxfilenamelength Max length of value to show + * @return array List of drivers + */ + public static function listDrivers($db, $maxfilenamelength = 0) + { + global $conf; @@ -59,9 +66,2 @@ - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + $type = 'printing'; + $list = array(); @@ -69,10 +69,5 @@ - /** - * Return list of printing driver - * - * @param DoliDB $db Database handler - * @param integer $maxfilenamelength Max length of value to show - * @return array List of drivers - */ - public static function listDrivers($db, $maxfilenamelength = 0) - { - global $conf; + $moduledir = DOL_DOCUMENT_ROOT."/core/modules/printing/"; + $tmpfiles = dol_dir_list($moduledir, 'all', 0, '\modules.php', '', 'name', SORT_ASC, 0); + foreach ($tmpfiles as $record) { + $list[$record['fullname']] = str_replace('.modules.php', '', $record['name']); + } @@ -80,2 +75,2 @@ - $type = 'printing'; - $list = array(); + return $list; + } @@ -83,34 +78,13 @@ - $listoffiles = array(); - if (!empty($conf->modules_parts['printing'])) { - $dirmodels = array_merge(array('/core/modules/printing/'), (array) $conf->modules_parts['printing']); - } else { - $dirmodels = array('/core/modules/printing/'); - } - foreach ($dirmodels as $dir) { - $tmpfiles = dol_dir_list(dol_buildpath($dir, 0), 'all', 0, '\.modules.php', '', 'name', SORT_ASC, 0); - if (!empty($tmpfiles)) { - $listoffiles = array_merge($listoffiles, $tmpfiles); - } - } - foreach ($listoffiles as $record) { - $list[$record['fullname']] = str_replace('.modules.php', '', $record['name']); - } - return $list; - } - - /** - * Return description of Printing Module - * - * @return string Return translation of key PrintingModuleDescXXX where XXX is module name, or $this->desc if not exists - */ - public function getDesc() - { - global $langs; - $langs->load("printing"); - $transstring = "PrintingModuleDesc".$this->name; - if ($langs->trans($transstring) != $transstring) { - return $langs->trans($transstring); - } else { - return $this->desc; - } - } + /** + * Return description of Printing Module + * + * @return string Return translation of key PrintingModuleDescXXX where XXX is module name, or $this->desc if not exists + */ + public function getDesc() + { + global $langs; + $langs->load("printing"); + $transstring = "PrintingModuleDesc".$this->name; + if ($langs->trans($transstring) != $transstring) return $langs->trans($transstring); + else return $this->desc; + } --- /tmp/dsg/dolibarr/htdocs/core/modules/printing/github_19.0.3_printgcp.modules.php +++ /tmp/dsg/dolibarr/htdocs/core/modules/printing/client_printgcp.modules.php @@ -38,506 +38,485 @@ - /** - * @var string module name - */ - public $name = 'printgcp'; - - /** - * @var string module description - */ - public $desc = 'PrintGCPDesc'; - - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'printer'; - - /** - * @var string module description - */ - public $active = 'PRINTING_PRINTGCP'; - - /** - * @var array module parameters - */ - public $conf = array(); - - /** - * @var string google id - */ - public $google_id = ''; - - /** - * @var string google secret - */ - public $google_secret = ''; - - /** - * @var string Error code (or message) - */ - public $error = ''; - - /** - * @var string[] Error codes (or messages) - */ - public $errors = array(); - - /** - * @var DoliDB Database handler. - */ - public $db; - - private $OAUTH_SERVICENAME_GOOGLE = 'Google'; - - const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token'; - const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search'; - const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs'; - const PRINT_URL = 'https://www.google.com/cloudprint/submit'; - const LANGFILE = 'printgcp'; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $conf, $langs, $dolibarr_main_url_root; - - // Define $urlwithroot - $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - - $this->db = $db; - - if (!$conf->oauth->enabled) { - $this->conf[] = array( - 'varname'=>'PRINTGCP_INFO', - 'info'=>$langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"), - 'type'=>'info', - ); - } else { - $keyforprovider = ''; // @FIXME - - $this->google_id = getDolGlobalString('OAUTH_GOOGLE_ID'); - $this->google_secret = getDolGlobalString('OAUTH_GOOGLE_SECRET'); - // Token storage - $storage = new DoliStorage($this->db, $conf, $keyforprovider); - //$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - $urlwithroot.'/core/modules/oauth/google_oauthcallback.php' - ); - $access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken'); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } - - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - if ($this->google_id != '' && $this->google_secret != '') { - $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthConfigured', 'type'=>'info'); - $this->conf[] = array( - 'varname'=>'PRINTGCP_TOKEN_ACCESS', - 'info'=>$access, - 'type'=>'info', - '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'), - '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') : '') - ); - if ($token_ok) { - $expiredat = ''; - - $refreshtoken = $token->getRefreshToken(); - - $endoflife = $token->getEndOfLife(); - - if ($endoflife == $token::EOL_NEVER_EXPIRES) { - $expiredat = $langs->trans("Never"); - } elseif ($endoflife == $token::EOL_UNKNOWN) { - $expiredat = $langs->trans("Unknown"); - } else { - $expiredat = dol_print_date($endoflife, "dayhour"); - } - - $this->conf[] = array('varname'=>'TOKEN_REFRESH', 'info'=>((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type'=>'info'); - $this->conf[] = array('varname'=>'TOKEN_EXPIRED', 'info'=>($expire ? 'Yes' : 'No'), 'type'=>'info'); - $this->conf[] = array('varname'=>'TOKEN_EXPIRE_AT', 'info'=>($expiredat), 'type'=>'info'); - } - /* - if ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE)) { - $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'); - $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'); - } else { - $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'); - }*/ - } else { - $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info'); - } - } - // do not display submit button - $this->conf[] = array('enabled'=>0, 'type'=>'submit'); - } - - /** - * Return list of available printers - * - * @return int 0 if OK, >0 if KO - */ - public function listAvailablePrinters() - { - global $conf, $langs; - $error = 0; - $langs->load('printing'); - - $html = ''; - $html .= ''.$langs->trans('GCP_Name').''; - $html .= ''.$langs->trans('GCP_displayName').''; - $html .= ''.$langs->trans('GCP_Id').''; - $html .= ''.$langs->trans('GCP_OwnerName').''; - $html .= ''.$langs->trans('GCP_State').''; - $html .= ''.$langs->trans('GCP_connectionStatus').''; - $html .= ''.$langs->trans('GCP_Type').''; - $html .= ''.$langs->trans("Select").''; - $html .= ''."\n"; - $list = $this->getlistAvailablePrinters(); - //$html.= '
'.print_r($list,true).'
'; - foreach ($list['available'] as $printer_det) { - $html .= ''; - $html .= ''.$printer_det['name'].''; - $html .= ''.$printer_det['displayName'].''; - $html .= ''.$printer_det['id'].''; // id to identify printer to use - $html .= ''.$printer_det['ownerName'].''; - $html .= ''.$printer_det['status'].''; - $html .= ''.$langs->trans('STATE_'.$printer_det['connectionStatus']).''; - $html .= ''.$langs->trans('TYPE_'.$printer_det['type']).''; - // Defaut - $html .= ''; - if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) { - $html .= img_picto($langs->trans("Default"), 'on'); - } else { - $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; - } - $html .= ''; - $html .= ''."\n"; - } - $this->resprint = $html; - return $error; - } - - - /** - * Return list of available printers - * - * @return array list of printers - */ - public function getlistAvailablePrinters() - { - global $conf; - $ret = array(); - - $keyforprovider = ''; // @FIXME - - // Token storage - $storage = new DoliStorage($this->db, $conf, $keyforprovider); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } - - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - // Send a request with api - try { - $response = $apiService->request(self::PRINTERS_SEARCH_URL); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - print '
'.print_r($e->getMessage(), true).'
'; - } - //print '
'.print_r($response, true).'
'; - $responsedata = json_decode($response, true); - $printers = $responsedata['printers']; - // Check if we have printers? - if (is_array($printers) && count($printers) == 0) { - // We dont have printers so return blank array - $ret['available'] = array(); - } else { - // We have printers so returns printers as array - $ret['available'] = $printers; - } - return $ret; - } - - /** - * Print selected file - * - * @param string $file file - * @param string $module module - * @param string $subdir subdir for file - * @return int 0 if OK, >0 if KO - */ - public function printFile($file, $module, $subdir = '') - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - global $conf, $user; - $error = 0; - - $fileprint = $conf->{$module}->dir_output; - if ($subdir != '') { - $fileprint .= '/'.$subdir; - } - $fileprint .= '/'.$file; - $mimetype = dol_mimetype($fileprint); - $printer_id = ''; - // select printer uri for module order, propal,... - $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); - $result = $this->db->query($sql); - if ($result) { - $obj = $this->db->fetch_object($result); - if ($obj) { - $printer_id = $obj->printer_id; - } else { - if (getDolGlobalString('PRINTING_GCP_DEFAULT')) { - $printer_id = $conf->global->PRINTING_GCP_DEFAULT; - } else { - $this->errors[] = 'NoDefaultPrinterDefined'; - $error++; - return $error; - } - } - } else { - dol_print_error($this->db); - } - - $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype); - $this->error = 'PRINTGCP: '.$ret['errormessage']; - if ($ret['status'] != 1) { - $error++; - } - return $error; - } - - /** - * Sends document to the printer - * - * @param string $printerid Printer id returned by Google Cloud Print - * @param string $printjobtitle Job Title - * @param string $filepath File Path to be send to Google Cloud Print - * @param string $contenttype File content type by example application/pdf, image/png - * @return array status array - */ - public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype) - { - global $conf; - // Check if printer id - if (empty($printerid)) { - return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID'); - } - // Open the file which needs to be print - $handle = fopen($filepath, "rb"); - if (!$handle) { - return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.'); - } - // Read file content - $contents = fread($handle, filesize($filepath)); - fclose($handle); - // Prepare post fields for sending print - $post_fields = array( - 'printerid' => $printerid, - 'title' => $printjobtitle, - 'contentTransferEncoding' => 'base64', - 'content' => base64_encode($contents), // encode file content as base64 - 'contentType' => $contenttype, - ); - - $keyforprovider = ''; // @FIXME - - // Dolibarr Token storage - $storage = new DoliStorage($this->db, $conf, $keyforprovider); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - - // Check if we have auth token and refresh it - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - if ($token_ok) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - - // Send a request with api - $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true); - //print '
'.print_r($response, true).'
'; - return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']); - } - - - /** - * List jobs print - * - * @return int 0 if OK, >0 if KO - */ - public function listJobs() - { - global $conf, $langs; - - $error = 0; - $html = ''; - - $keyforprovider = ''; // @FIXME - - // Token storage - $storage = new DoliStorage($this->db, $conf, $keyforprovider); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - $error++; - } - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } - - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - } - // Getting Jobs - // Send a request with api - try { - $response = $apiService->request(self::PRINTERS_GET_JOBS); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - $responsedata = json_decode($response, true); - //$html .= '
'.print_r($responsedata,true).'
'; - $html .= '
'; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''."\n"; - - $jobs = $responsedata['jobs']; - //$html .= '
'.print_r($jobs['0'],true).'
'; - if (is_array($jobs)) { - foreach ($jobs as $value) { - $html .= ''; - $html .= ''; - $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour'); - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - } - } else { - $html .= ''; - $html .= ''; - $html .= ''; - } - $html .= '
'.$langs->trans("Id").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Printer").''.$langs->trans("Filename").''.$langs->trans("Status").''.$langs->trans("Cancel").'
'.$value['id'].''.$dates.''.$value['ownerId'].''.$value['printerName'].''.$value['title'].''.$value['status'].' 
'.$langs->trans("None").'
'; - $html .= '
'; - - $this->resprint = $html; - - return $error; - } + public $name = 'printgcp'; + public $desc = 'PrintGCPDesc'; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'printer'; + public $active = 'PRINTING_PRINTGCP'; + public $conf = array(); + public $google_id = ''; + public $google_secret = ''; + + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * @var string[] Error codes (or messages) + */ + public $errors = array(); + + /** + * @var DoliDB Database handler. + */ + public $db; + + private $OAUTH_SERVICENAME_GOOGLE = 'Google'; + + const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token'; + const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search'; + const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs'; + const PRINT_URL = 'https://www.google.com/cloudprint/submit'; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $conf, $langs, $dolibarr_main_url_root; + + // Define $urlwithroot + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + + $this->db = $db; + + if (!$conf->oauth->enabled) { + $this->conf[] = array( + 'varname'=>'PRINTGCP_INFO', + 'info'=>$langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"), + 'type'=>'info', + ); + } else { + $this->google_id = $conf->global->OAUTH_GOOGLE_ID; + $this->google_secret = $conf->global->OAUTH_GOOGLE_SECRET; + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + //$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + $urlwithroot.'/core/modules/oauth/google_oauthcallback.php' + ); + $access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken'); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + //var_dump($this->errors);exit; + + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } + + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + if ($this->google_id != '' && $this->google_secret != '') { + $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthConfigured', 'type'=>'info'); + $this->conf[] = array( + 'varname'=>'PRINTGCP_TOKEN_ACCESS', + 'info'=>$access, + 'type'=>'info', + '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'), + 'delete'=>($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp') : '') + ); + if ($token_ok) { + $expiredat = ''; + + $refreshtoken = $token->getRefreshToken(); + + $endoflife = $token->getEndOfLife(); + + if ($endoflife == $token::EOL_NEVER_EXPIRES) + { + $expiredat = $langs->trans("Never"); + } + elseif ($endoflife == $token::EOL_UNKNOWN) + { + $expiredat = $langs->trans("Unknown"); + } + else + { + $expiredat = dol_print_date($endoflife, "dayhour"); + } + + $this->conf[] = array('varname'=>'TOKEN_REFRESH', 'info'=>((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type'=>'info'); + $this->conf[] = array('varname'=>'TOKEN_EXPIRED', 'info'=>($expire ? 'Yes' : 'No'), 'type'=>'info'); + $this->conf[] = array('varname'=>'TOKEN_EXPIRE_AT', 'info'=>($expiredat), 'type'=>'info'); + } + /* + if ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE)) { + $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'); + $this->conf[] = array('varname'=>'DELETE_TOKEN', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'delete'); + } else { + $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'); + }*/ + } else { + $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info'); + } + } + // do not display submit button + $this->conf[] = array('enabled'=>0, 'type'=>'submit'); + } + + /** + * Return list of available printers + * + * @return int 0 if OK, >0 if KO + */ + public function listAvailablePrinters() + { + global $conf, $langs; + $error = 0; + $langs->load('printing'); + + $html = ''; + $html .= ''.$langs->trans('GCP_Name').''; + $html .= ''.$langs->trans('GCP_displayName').''; + $html .= ''.$langs->trans('GCP_Id').''; + $html .= ''.$langs->trans('GCP_OwnerName').''; + $html .= ''.$langs->trans('GCP_State').''; + $html .= ''.$langs->trans('GCP_connectionStatus').''; + $html .= ''.$langs->trans('GCP_Type').''; + $html .= ''.$langs->trans("Select").''; + $html .= ''."\n"; + $list = $this->getlistAvailablePrinters(); + //$html.= '
'.print_r($list,true).'
'; + foreach ($list['available'] as $printer_det) + { + $html .= ''; + $html .= ''.$printer_det['name'].''; + $html .= ''.$printer_det['displayName'].''; + $html .= ''.$printer_det['id'].''; // id to identify printer to use + $html .= ''.$printer_det['ownerName'].''; + $html .= ''.$printer_det['status'].''; + $html .= ''.$langs->trans('STATE_'.$printer_det['connectionStatus']).''; + $html .= ''.$langs->trans('TYPE_'.$printer_det['type']).''; + // Defaut + $html .= ''; + if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) + { + $html .= img_picto($langs->trans("Default"), 'on'); + } + else + $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; + $html .= ''; + $html .= ''."\n"; + } + $this->resprint = $html; + return $error; + } + + + /** + * Return list of available printers + * + * @return array list of printers + */ + public function getlistAvailablePrinters() + { + $ret = array(); + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + // Check if we have auth token + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } + + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + // Send a request with api + try { + $response = $apiService->request(self::PRINTERS_SEARCH_URL); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + print '
'.print_r($e->getMessage(), true).'
'; + } + //print '
'.print_r($response, true).'
'; + $responsedata = json_decode($response, true); + $printers = $responsedata['printers']; + // Check if we have printers? + if (count($printers) == 0) { + // We dont have printers so return blank array + $ret['available'] = array(); + } else { + // We have printers so returns printers as array + $ret['available'] = $printers; + } + return $ret; + } + + /** + * Print selected file + * + * @param string $file file + * @param string $module module + * @param string $subdir subdir for file + * @return int 0 if OK, >0 if KO + */ + public function printFile($file, $module, $subdir = '') + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + global $conf, $user; + $error = 0; + + $fileprint = $conf->{$module}->dir_output; + if ($subdir != '') { + $fileprint .= '/'.$subdir; + } + $fileprint .= '/'.$file; + $mimetype = dol_mimetype($fileprint); + // select printer uri for module order, propal,... + $sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$module."' AND driver='printgcp' AND userid=".$user->id; + $result = $this->db->query($sql); + if ($result) + { + $obj = $this->db->fetch_object($result); + if ($obj) + { + $printer_id = $obj->printer_id; + } + else + { + if (!empty($conf->global->PRINTING_GCP_DEFAULT)) + { + $printer_id = $conf->global->PRINTING_GCP_DEFAULT; + } + else + { + $this->errors[] = 'NoDefaultPrinterDefined'; + $error++; + return $error; + } + } + } else { + dol_print_error($this->db); + } + + $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype); + $this->error = 'PRINTGCP: '.$ret['errormessage']; + if ($ret['status'] != 1) { + $error++; + } + return $error; + } + + /** + * Sends document to the printer + * + * @param string $printerid Printer id returned by Google Cloud Print + * @param string $printjobtitle Job Title + * @param string $filepath File Path to be send to Google Cloud Print + * @param string $contenttype File content type by example application/pdf, image/png + * @return array status array + */ + public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype) + { + // Check if printer id + if (empty($printerid)) { + return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID'); + } + // Open the file which needs to be print + $handle = fopen($filepath, "rb"); + if (!$handle) { + return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.'); + } + // Read file content + $contents = fread($handle, filesize($filepath)); + fclose($handle); + // Prepare post fields for sending print + $post_fields = array( + 'printerid' => $printerid, + 'title' => $printjobtitle, + 'contentTransferEncoding' => 'base64', + 'content' => base64_encode($contents), // encode file content as base64 + 'contentType' => $contenttype, + ); + // Dolibarr Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + + // Check if we have auth token and refresh it + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + if ($token_ok) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + // Send a request with api + $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true); + //print '
'.print_r($response, true).'
'; + return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']); + } + + + /** + * List jobs print + * + * @return int 0 if OK, >0 if KO + */ + public function listJobs() + { + global $conf, $langs; + + $error = 0; + $html = ''; + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + // Check if we have auth token + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + $error++; + } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } + + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + } + // Getting Jobs + // Send a request with api + try { + $response = $apiService->request(self::PRINTERS_GET_JOBS); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + $responsedata = json_decode($response, true); + //$html .= '
'.print_r($responsedata,true).'
'; + $html .= '
'; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''."\n"; + + $jobs = $responsedata['jobs']; + //$html .= '
'.print_r($jobs['0'],true).'
'; + if (is_array($jobs)) { + foreach ($jobs as $value) { + $html .= ''; + $html .= ''; + $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour'); + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + } + } + else + { + $html .= ''; + $html .= ''; + $html .= ''; + } + $html .= '
'.$langs->trans("Id").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Printer").''.$langs->trans("Filename").''.$langs->trans("Status").''.$langs->trans("Cancel").'
'.$value['id'].''.$dates.''.$value['ownerId'].''.$value['printerName'].''.$value['title'].''.$value['status'].' 
'.$langs->trans("None").'
'; + $html .= '
'; + + $this->resprint = $html; + + return $error; + } --- /tmp/dsg/dolibarr/htdocs/core/modules/printing/github_19.0.3_printipp.modules.php +++ /tmp/dsg/dolibarr/htdocs/core/modules/printing/client_printipp.modules.php @@ -3 +3 @@ - * Copyright (C) 2014-2021 Frederic France + * Copyright (C) 2014-2018 Frederic France @@ -33,323 +33,284 @@ - /** - * @var string module name - */ - public $name = 'printipp'; - - /** - * @var string module description - */ - public $desc = 'PrintIPPDesc'; - - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'printer'; - - /** - * @var string Constant name - */ - public $active = 'PRINTING_PRINTIPP'; - - /** - * @var array array of setup value - */ - public $conf = array(); - - /** - * @var string host - */ - public $host; - - /** - * @var string port - */ - public $port; - - /** - * @var string username - */ - public $userid; - - /** - * @var string login for printer host - */ - public $user; - - /** - * @var string password for printer host - */ - public $password; - - /** - * @var string Error code (or message) - */ - public $error = ''; - - /** - * @var string[] Error codes (or messages) - */ - public $errors = array(); - - /** - * @var DoliDB Database handler. - */ - public $db; - - const LANGFILE = 'printipp'; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $conf; - - $this->db = $db; - $this->host = getDolGlobalString('PRINTIPP_HOST'); - $this->port = getDolGlobalString('PRINTIPP_PORT'); - $this->user = getDolGlobalString('PRINTIPP_USER'); - $this->password = getDolGlobalString('PRINTIPP_PASSWORD'); - $this->conf[] = array('varname'=>'PRINTIPP_HOST', 'required'=>1, 'example'=>'localhost', 'type'=>'text'); - $this->conf[] = array('varname'=>'PRINTIPP_PORT', 'required'=>1, 'example'=>'631', 'type'=>'text'); - $this->conf[] = array('varname'=>'PRINTIPP_USER', 'required'=>0, 'example'=>'', 'type'=>'text', 'moreattributes'=>'autocomplete="off"'); - $this->conf[] = array('varname'=>'PRINTIPP_PASSWORD', 'required'=>0, 'example'=>'', 'type'=>'password', 'moreattributes'=>'autocomplete="off"'); - $this->conf[] = array('enabled'=>1, 'type'=>'submit'); - } - - /** - * Print selected file - * - * @param string $file file - * @param string $module module - * @param string $subdir subdirectory of document like for expedition subdir is sendings - * - * @return int 0 if OK, >0 if KO - */ - public function printFile($file, $module, $subdir = '') - { - global $conf, $user; - $error = 0; - - include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; - - $ipp = new CupsPrintIPP(); - $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose - $ipp->setHost($this->host); - $ipp->setPort($this->port); - $ipp->setJobName($file, true); - $ipp->setUserName($this->userid); - // Set default number of copy - $ipp->setCopies(1); - if (!empty($this->user)) { - $ipp->setAuthentication($this->user, $this->password); - } - - // select printer uri for module order, propal,... - $sql = "SELECT rowid,printer_id,copy FROM ".MAIN_DB_PREFIX."printing WHERE module = '".$this->db->escape($module)."' AND driver = 'printipp' AND userid = ".((int) $user->id); - $result = $this->db->query($sql); - if ($result) { - $obj = $this->db->fetch_object($result); - if ($obj) { - dol_syslog("Found a default printer for user ".$user->id." = ".$obj->printer_id); - $ipp->setPrinterURI($obj->printer_id); - // Set number of copy - $ipp->setCopies($obj->copy); - } else { - if (getDolGlobalString('PRINTIPP_URI_DEFAULT')) { - dol_syslog("Will use default printer conf->global->PRINTIPP_URI_DEFAULT = ".getDolGlobalString('PRINTIPP_URI_DEFAULT')); - $ipp->setPrinterURI(getDolGlobalString('PRINTIPP_URI_DEFAULT')); - } else { - $this->errors[] = 'NoDefaultPrinterDefined'; - $error++; - return $error; - } - } - } else { - dol_print_error($this->db); - } - - $fileprint = $conf->{$module}->dir_output; - if ($subdir != '') { - $fileprint .= '/'.$subdir; - } - $fileprint .= '/'.$file; - $ipp->setData($fileprint); - try { - $ipp->printJob(); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - if ($error == 0) { - $this->errors[] = 'PRINTIPP: Job added'; - } - - return $error; - } - - /** - * Return list of available printers - * - * @return int 0 if OK, >0 if KO - */ - public function listAvailablePrinters() - { - global $conf, $langs; - $error = 0; - - $html = ''; - $html .= ''.$langs->trans('IPP_Uri').''; - $html .= ''.$langs->trans('IPP_Name').''; - $html .= ''.$langs->trans('IPP_State').''; - $html .= ''.$langs->trans('IPP_State_reason').''; - $html .= ''.$langs->trans('IPP_State_reason1').''; - $html .= ''.$langs->trans('IPP_BW').''; - $html .= ''.$langs->trans('IPP_Color').''; - //$html.= ''.$langs->trans('IPP_Device').''; - $html .= ''.$langs->trans('IPP_Media').''; - $html .= ''.$langs->trans('IPP_Supported').''; - $html .= ''.$langs->trans("Select").''; - $html .= "\n"; - $list = $this->getlistAvailablePrinters(); - foreach ($list as $value) { - $printer_det = $this->getPrinterDetail($value); - $html .= ''; - $html .= ''.$value.''; - //$html.= '
'.print_r($printer_det,true).'
'; - $html .= ''.$printer_det->printer_name->_value0.''; - $html .= ''.$langs->trans('STATE_IPP_'.$printer_det->printer_state->_value0).''; - $html .= ''.$langs->trans('STATE_IPP_'.$printer_det->printer_state_reasons->_value0).''; - $html .= ''.(!empty($printer_det->printer_state_reasons->_value1) ? $langs->trans('STATE_IPP_'.$printer_det->printer_state_reasons->_value1) : '').''; - $html .= ''.$langs->trans('IPP_COLOR_'.$printer_det->printer_type->_value2).''; - $html .= ''.$langs->trans('IPP_COLOR_'.$printer_det->printer_type->_value3).''; - //$html.= ''.$printer_det->device_uri->_value0.''; - $html .= ''.$printer_det->media_default->_value0.''; - $html .= ''.$langs->trans('MEDIA_IPP_'.$printer_det->media_type_supported->_value1).''; - // Defaut - $html .= ''; - if ($conf->global->PRINTIPP_URI_DEFAULT == $value) { - $html .= img_picto($langs->trans("Default"), 'on'); - } else { - $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; - } - $html .= ''; - $html .= ''."\n"; - } - $this->resprint = $html; - return $error; - } - - /** - * Return list of available printers - * - * @return array list of printers - */ - public function getlistAvailablePrinters() - { - global $conf, $db; - include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; - $ipp = new CupsPrintIPP(); - $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose - $ipp->setHost($this->host); - $ipp->setPort($this->port); - $ipp->setUserName($this->userid); - if (!empty($this->user)) { - $ipp->setAuthentication($this->user, $this->password); - } - $ipp->getPrinters(); - return $ipp->available_printers; - } - - /** - * Get printer detail - * - * @param string $uri URI - * @return array List of attributes - */ - private function getPrinterDetail($uri) - { - global $conf, $db; - - include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; - $ipp = new CupsPrintIPP(); - $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose - $ipp->setHost($this->host); - $ipp->setPort($this->port); - $ipp->setUserName($this->userid); - if (!empty($this->user)) { - $ipp->setAuthentication($this->user, $this->password); - } - $ipp->setPrinterURI($uri); - $ipp->getPrinterAttributes(); - return $ipp->printer_attributes; - } - - /** - * List jobs print - * - * @param string $module module - * - * @return int 0 if OK, >0 if KO - */ - public function listJobs($module) - { - global $conf; - $error = 0; - $html = ''; - include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; - $ipp = new CupsPrintIPP(); - $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose - $ipp->setHost($this->host); - $ipp->setPort($this->port); - $ipp->setUserName($this->userid); - if (!empty($this->user)) { - $ipp->setAuthentication($this->user, $this->password); - } - // select printer uri for module order, propal,... - $sql = "SELECT rowid,printer_uri,printer_name FROM ".MAIN_DB_PREFIX."printer_ipp WHERE module = '".$this->db->escape($module)."'"; - $result = $this->db->query($sql); - if ($result) { - $obj = $this->db->fetch_object($result); - if ($obj) { - $ipp->setPrinterURI($obj->printer_uri); - } else { - // All printers - $ipp->setPrinterURI("ipp://localhost:631/printers/"); - } - } - // Getting Jobs - try { - $ipp->getJobs(false, 0, 'completed', false); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''."\n"; - $jobs = $ipp->jobs_attributes; - - //$html .= '
'.print_r($jobs,true).'
'; - foreach ($jobs as $value) { - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - } - $html .= "
IdOwnerPrinterFileStatusCancel
'.$value->job_id->_value0.''.$value->job_originating_user_name->_value0.''.$value->printer_uri->_value0.''.$value->job_name->_value0.''.$value->job_state->_value0.''.$value->job_uri->_value0.'
"; - $this->resprint = $html; - return $error; - } + public $name = 'printipp'; + public $desc = 'PrintIPPDesc'; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'printer'; + public $active = 'PRINTING_PRINTIPP'; + public $conf = array(); + public $host; + public $port; + public $userid; /* user login */ + public $user; + public $password; + + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * @var string[] Error codes (or messages) + */ + public $errors = array(); + + /** + * @var DoliDB Database handler. + */ + public $db; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $conf; + + $this->db = $db; + $this->host = $conf->global->PRINTIPP_HOST; + $this->port = $conf->global->PRINTIPP_PORT; + $this->user = $conf->global->PRINTIPP_USER; + $this->password = $conf->global->PRINTIPP_PASSWORD; + $this->conf[] = array('varname'=>'PRINTIPP_HOST', 'required'=>1, 'example'=>'localhost', 'type'=>'text'); + $this->conf[] = array('varname'=>'PRINTIPP_PORT', 'required'=>1, 'example'=>'631', 'type'=>'text'); + $this->conf[] = array('varname'=>'PRINTIPP_USER', 'required'=>0, 'example'=>'', 'type'=>'text', 'moreattributes'=>'autocomplete="off"'); + $this->conf[] = array('varname'=>'PRINTIPP_PASSWORD', 'required'=>0, 'example'=>'', 'type'=>'password', 'moreattributes'=>'autocomplete="off"'); + $this->conf[] = array('enabled'=>1, 'type'=>'submit'); + } + + /** + * Print selected file + * + * @param string $file file + * @param string $module module + * @param string $subdir subdirectory of document like for expedition subdir is sendings + * + * @return int 0 if OK, >0 if KO + */ + public function printFile($file, $module, $subdir = '') + { + global $conf, $user; + $error = 0; + + include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; + + $ipp = new CupsPrintIPP(); + $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose + $ipp->setHost($this->host); + $ipp->setPort($this->port); + $ipp->setJobName($file, true); + $ipp->setUserName($this->userid); + if (!empty($this->user)) $ipp->setAuthentication($this->user, $this->password); + + // select printer uri for module order, propal,... + $sql = "SELECT rowid,printer_id,copy FROM ".MAIN_DB_PREFIX."printing WHERE module = '".$module."' AND driver = 'printipp' AND userid = ".$user->id; + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + if ($obj) + { + dol_syslog("Found a default printer for user ".$user->id." = ".$obj->printer_id); + $ipp->setPrinterURI($obj->printer_id); + } + else + { + if (!empty($conf->global->PRINTIPP_URI_DEFAULT)) + { + dol_syslog("Will use default printer conf->global->PRINTIPP_URI_DEFAULT = ".$conf->global->PRINTIPP_URI_DEFAULT); + $ipp->setPrinterURI($conf->global->PRINTIPP_URI_DEFAULT); + } + else + { + $this->errors[] = 'NoDefaultPrinterDefined'; + $error++; + return $error; + } + } + } else { + dol_print_error($this->db); + } + + // Set number of copy + $ipp->setCopies($obj->copy); + $fileprint = $conf->{$module}->dir_output; + if ($subdir != '') $fileprint .= '/'.$subdir; + $fileprint .= '/'.$file; + $ipp->setData($fileprint); + try { + $ipp->printJob(); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + if ($error == 0) $this->errors[] = 'PRINTIPP: Job added'; + + return $error; + } + + /** + * Return list of available printers + * + * @return int 0 if OK, >0 if KO + */ + public function listAvailablePrinters() + { + global $conf, $langs; + $error = 0; + + $html = ''; + $html .= ''.$langs->trans('IPP_Uri').''; + $html .= ''.$langs->trans('IPP_Name').''; + $html .= ''.$langs->trans('IPP_State').''; + $html .= ''.$langs->trans('IPP_State_reason').''; + $html .= ''.$langs->trans('IPP_State_reason1').''; + $html .= ''.$langs->trans('IPP_BW').''; + $html .= ''.$langs->trans('IPP_Color').''; + //$html.= ''.$langs->trans('IPP_Device').''; + $html .= ''.$langs->trans('IPP_Media').''; + $html .= ''.$langs->trans('IPP_Supported').''; + $html .= ''.$langs->trans("Select").''; + $html .= "\n"; + $list = $this->getlistAvailablePrinters(); + foreach ($list as $value) { + $printer_det = $this->getPrinterDetail($value); + $html .= ''; + $html .= ''.$value.''; + //$html.= '
'.print_r($printer_det,true).'
'; + $html .= ''.$printer_det->printer_name->_value0.''; + $html .= ''.$langs->trans('STATE_IPP_'.$printer_det->printer_state->_value0).''; + $html .= ''.$langs->trans('STATE_IPP_'.$printer_det->printer_state_reasons->_value0).''; + $html .= ''.(!empty($printer_det->printer_state_reasons->_value1) ? $langs->trans('STATE_IPP_'.$printer_det->printer_state_reasons->_value1) : '').''; + $html .= ''.$langs->trans('IPP_COLOR_'.$printer_det->printer_type->_value2).''; + $html .= ''.$langs->trans('IPP_COLOR_'.$printer_det->printer_type->_value3).''; + //$html.= ''.$printer_det->device_uri->_value0.''; + $html .= ''.$printer_det->media_default->_value0.''; + $html .= ''.$langs->trans('MEDIA_IPP_'.$printer_det->media_type_supported->_value1).''; + // Defaut + $html .= ''; + if ($conf->global->PRINTIPP_URI_DEFAULT == $value) { + $html .= img_picto($langs->trans("Default"), 'on'); + } else { + $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; + } + $html .= ''; + $html .= ''."\n"; + } + $this->resprint = $html; + return $error; + } + + /** + * Return list of available printers + * + * @return array list of printers + */ + public function getlistAvailablePrinters() + { + global $conf, $db; + include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; + $ipp = new CupsPrintIPP(); + $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose + $ipp->setHost($this->host); + $ipp->setPort($this->port); + $ipp->setUserName($this->userid); + if (!empty($this->user)) { + $ipp->setAuthentication($this->user, $this->password); + } + $ipp->getPrinters(); + return $ipp->available_printers; + } + + /** + * Get printer detail + * + * @param string $uri URI + * @return array List of attributes + */ + private function getPrinterDetail($uri) + { + global $conf, $db; + + include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; + $ipp = new CupsPrintIPP(); + $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose + $ipp->setHost($this->host); + $ipp->setPort($this->port); + $ipp->setUserName($this->userid); + if (!empty($this->user)) { + $ipp->setAuthentication($this->user, $this->password); + } + $ipp->setPrinterURI($uri); + $ipp->getPrinterAttributes(); + return $ipp->printer_attributes; + } + + /** + * List jobs print + * + * @param string $module module + * + * @return int 0 if OK, >0 if KO + */ + public function listJobs($module) + { + global $conf; + $error = 0; + $html = ''; + include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; + $ipp = new CupsPrintIPP(); + $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log', 'file', 3); // logging very verbose + $ipp->setHost($this->host); + $ipp->setPort($this->port); + $ipp->setUserName($this->userid); + if (!empty($this->user)) { + $ipp->setAuthentication($this->user, $this->password); + } + // select printer uri for module order, propal,... + $sql = 'SELECT rowid,printer_uri,printer_name FROM '.MAIN_DB_PREFIX.'printer_ipp WHERE module="'.$module.'"'; + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + if ($obj) { + $ipp->setPrinterURI($obj->printer_uri); + } else { + // All printers + $ipp->setPrinterURI("ipp://localhost:631/printers/"); + } + } + // Getting Jobs + try { + $ipp->getJobs(false, 0, 'completed', false); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''."\n"; + $jobs = $ipp->jobs_attributes; + + //$html .= '
'.print_r($jobs,true).'
'; + foreach ($jobs as $value) { + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + } + $html .= "
IdOwnerPrinterFileStatusCancel
'.$value->job_id->_value0.''.$value->job_originating_user_name->_value0.''.$value->printer_uri->_value0.''.$value->job_name->_value0.''.$value->job_state->_value0.''.$value->job_uri->_value0.'
"; + $this->resprint = $html; + return $error; + }