forked from Wavyzz/dolibarr
434 lines
17 KiB
PHP
434 lines
17 KiB
PHP
<?php
|
|
/*
|
|
* Copyright (C) 2014-2015 Frederic France <frederic.france@free.fr>
|
|
*
|
|
* This program is free software; you can redistribute it and/or modify
|
|
* it under the terms of the GNU General Public License as published by
|
|
* the Free Software Foundation; either version 3 of the License, or
|
|
* (at your option) any later version.
|
|
*
|
|
* This program is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* GNU General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU General Public License
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
* or see http://www.gnu.org/
|
|
*/
|
|
|
|
/**
|
|
* \file htdocs/core/modules/printing/printgcp.modules.php
|
|
* \ingroup printing
|
|
* \brief File to provide printing with Google Cloud Print
|
|
*/
|
|
|
|
include_once DOL_DOCUMENT_ROOT.'/core/modules/printing/modules_printing.php';
|
|
require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
|
|
use OAuth\Common\Storage\Session;
|
|
use OAuth\Common\Storage\DoliStorage;
|
|
use OAuth\Common\Consumer\Credentials;
|
|
use OAuth\OAuth2\Service\Google;
|
|
|
|
/**
|
|
* Class to provide printing with Google Cloud Print
|
|
*/
|
|
class printing_printgcp extends PrintingDriver
|
|
{
|
|
var $name = 'printgcp';
|
|
var $desc = 'PrintGCPDesc';
|
|
var $picto = 'printer';
|
|
var $active = 'PRINTING_PRINTGCP';
|
|
var $conf = array();
|
|
var $google_id = '';
|
|
var $google_secret = '';
|
|
var $db;
|
|
|
|
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
|
|
*/
|
|
function __construct($db)
|
|
{
|
|
global $conf;
|
|
|
|
$this->db = $db;
|
|
$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('Google');
|
|
// Setup the credentials for the requests
|
|
$credentials = new Credentials(
|
|
$this->google_id,
|
|
$this->google_secret,
|
|
DOL_MAIN_URL_ROOT.'/core/modules/oauth/getgoogleoauthcallback.php'
|
|
);
|
|
$access = ($storage->hasAccessToken('Google')?'HasAccessToken':'NoAccessToken');
|
|
$serviceFactory = new \OAuth\ServiceFactory();
|
|
$apiService = $serviceFactory->createService('Google', $credentials, $storage, array());
|
|
$token_ok=true;
|
|
try {
|
|
$token = $storage->retrieveAccessToken('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('Google', $token);
|
|
} catch (Exception $e) {
|
|
$this->errors[] = $e->getMessage();
|
|
}
|
|
}
|
|
if (!$conf->oauth->enabled) {
|
|
$this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'ModuleAuthNotActive', 'type'=>'info');
|
|
} else {
|
|
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');
|
|
if ($token_ok) {
|
|
$refreshtoken = $token->getRefreshToken();
|
|
$this->conf[] = array('varname'=>'PRINTGCP_TOKEN_REFRESH', 'info'=>((! empty($refreshtoken))?'Yes':'No'), 'type'=>'info');
|
|
$this->conf[] = array('varname'=>'PRINTGCP_TOKEN_EXPIRED', 'info'=>($expire?'Yes':'No'), 'type'=>'info');
|
|
$this->conf[] = array('varname'=>'PRINTGCP_TOKEN_EXPIRE_AT', 'info'=>(date("Y-m-d H:i:s", $token->getEndOfLife())), 'type'=>'info');
|
|
}
|
|
$this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>DOL_MAIN_URL_ROOT.'/core/modules/oauth/getgoogleoauthcallback.php', '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 string html list of printers
|
|
*/
|
|
function listAvailablePrinters()
|
|
{
|
|
global $bc, $conf, $langs;
|
|
$langs->load('printing');
|
|
$var=true;
|
|
|
|
$html = '<tr class="liste_titre">';
|
|
$html.= '<td>'.$langs->trans('GCP_Name').'</td>';
|
|
$html.= '<td>'.$langs->trans('GCP_displayName').'</td>';
|
|
$html.= '<td>'.$langs->trans('GCP_Id').'</td>';
|
|
$html.= '<td>'.$langs->trans('GCP_OwnerName').'</td>';
|
|
$html.= '<td>'.$langs->trans('GCP_State').'</td>';
|
|
$html.= '<td>'.$langs->trans('GCP_connectionStatus').'</td>';
|
|
$html.= '<td>'.$langs->trans('GCP_Type').'</td>';
|
|
$html.= '<td align="center">'.$langs->trans("Select").'</td>';
|
|
$html.= '</tr>'."\n";
|
|
$list = $this->getlist_available_printers();
|
|
//$html.= '<td><pre>'.print_r($list,true).'</pre></td>';
|
|
$var = true;
|
|
foreach ($list['available'] as $printer_det)
|
|
{
|
|
$var=!$var;
|
|
$html.= "<tr ".$bc[$var].">";
|
|
$html.= '<td>'.$printer_det['name'].'</td>';
|
|
$html.= '<td>'.$printer_det['displayName'].'</td>';
|
|
$html.= '<td>'.$printer_det['id'].'</td>'; // id to identify printer to use
|
|
$html.= '<td>'.$printer_det['ownerName'].'</td>';
|
|
$html.= '<td>'.$printer_det['status'].'</td>';
|
|
$html.= '<td>'.$langs->trans('STATE_'.$printer_det['connectionStatus']).'</td>';
|
|
$html.= '<td>'.$langs->trans('TYPE_'.$printer_det['type']).'</td>';
|
|
// Defaut
|
|
$html.= '<td align="center">';
|
|
if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id'])
|
|
{
|
|
$html.= img_picto($langs->trans("Default"),'on');
|
|
}
|
|
else
|
|
$html.= '<a href="'.$_SERVER["PHP_SELF"].'?action=setvalue&mode=test&varname=PRINTING_GCP_DEFAULT&driver=printgcp&value='.urlencode($printer_det['id']).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').'</a>';
|
|
$html.= '</td>';
|
|
$html.= '</tr>'."\n";
|
|
}
|
|
|
|
return $html;
|
|
}
|
|
|
|
|
|
/**
|
|
* Return list of available printers
|
|
*
|
|
* @return array list of printers
|
|
*/
|
|
function getlist_available_printers()
|
|
{
|
|
// 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/getgoogleoauthcallback.php'
|
|
);
|
|
$serviceFactory = new \OAuth\ServiceFactory();
|
|
$apiService = $serviceFactory->createService('Google', $credentials, $storage, array());
|
|
// Check if we have auth token
|
|
$token_ok=true;
|
|
try {
|
|
$token = $storage->retrieveAccessToken('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('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 '<pre>'.print_r($e->getMessage(),true).'</pre>';
|
|
}
|
|
//print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
|
|
$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
|
|
*/
|
|
function print_file($file, $module, $subdir='')
|
|
{
|
|
global $conf, $user, $db;
|
|
|
|
$fileprint=$conf->{$module}->dir_output;
|
|
if ($subdir!='') $fileprint.='/'.$subdir;
|
|
$fileprint.='/'.$file;
|
|
// 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 = $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
|
|
{
|
|
return 'NoDefaultPrinterDefined';
|
|
}
|
|
}
|
|
}
|
|
else dol_print_error($db);
|
|
|
|
$ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, 'application/pdf');
|
|
$this->error = 'PRINTGCP: '.$ret['errormessage'];
|
|
if ($ret['status']==1)
|
|
return 0;
|
|
else
|
|
return -1;
|
|
}
|
|
|
|
/**
|
|
* 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/getoauthcallback.php?service=google'
|
|
);
|
|
$serviceFactory = new \OAuth\ServiceFactory();
|
|
$apiService = $serviceFactory->createService('Google', $credentials, $storage, array());
|
|
|
|
// Check if we have auth token and refresh it
|
|
$token_ok=true;
|
|
try {
|
|
$token = $storage->retrieveAccessToken('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('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 '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
|
|
return array('status' =>$response['success'],'errorcode' =>$response['errorCode'],'errormessage'=>$response['message']);
|
|
}
|
|
|
|
|
|
/**
|
|
* List jobs print
|
|
*
|
|
* @return void
|
|
*/
|
|
function list_jobs()
|
|
{
|
|
global $conf, $db, $bc;
|
|
// 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/getgoogleoauthcallback.php'
|
|
);
|
|
$serviceFactory = new \OAuth\ServiceFactory();
|
|
$apiService = $serviceFactory->createService('Google', $credentials, $storage, array());
|
|
// Check if we have auth token
|
|
$token_ok=true;
|
|
try {
|
|
$token = $storage->retrieveAccessToken('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('Google', $token);
|
|
} catch (Exception $e) {
|
|
$this->errors[] = $e->getMessage();
|
|
}
|
|
}
|
|
// Getting Jobs
|
|
// Send a request with api
|
|
try {
|
|
$response = $apiService->request(self::PRINTERS_GET_JOBS);
|
|
} catch (Exception $e) {
|
|
$this->errors[] = $e->getMessage();
|
|
print '<pre>'.print_r($e->getMessage(),true).'</pre>';
|
|
}
|
|
$responsedata = json_decode($response, true);
|
|
//print '<pre>'.print_r($responsedata,true).'</pre>';
|
|
print '<table width="100%" class="noborder">';
|
|
print '<tr class="liste_titre">';
|
|
print "<td>Id</td>";
|
|
print "<td>Owner</td>";
|
|
print "<td>Printer</td>";
|
|
print "<td>File</td>";
|
|
print "<td>Status</td>";
|
|
print "<td>Cancel</td>";
|
|
print "</tr>\n";
|
|
$var = True;
|
|
$jobs = $responsedata['jobs'];
|
|
//print '<pre>'.print_r($jobs['0'],true).'</pre>';
|
|
foreach ($jobs as $value )
|
|
{
|
|
$var=!$var;
|
|
print "<tr ".$bc[$var].">";
|
|
print '<td>'.$value['id'].'</td>';
|
|
print '<td>'.$value['ownerId'].'</td>';
|
|
print '<td>'.$value['printerName'].'</td>';
|
|
print '<td>'.$value['title'].'</td>';
|
|
print '<td>'.$value['status'].'</td>';
|
|
print '<td> </td>';
|
|
print '</tr>';
|
|
}
|
|
print "</table>";
|
|
}
|
|
|
|
}
|