This commit is contained in:
steven 2025-08-11 22:23:30 +02:00
commit 72a26edcff
22092 changed files with 2101903 additions and 0 deletions

62
scripts/google/Config.php Normal file
View file

@ -0,0 +1,62 @@
<?php
/*
PHP implementation of Google Cloud Print
Author, Yasir Siddiqui
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
$redirectConfig = array(
'client_id' => 'jb-drucker',
'redirect_uri' => 'http://edv.jb-transport.de/oAuthRedirect.php',
'response_type' => 'code',
'scope' => 'https://www.googleapis.com/auth/cloudprint',
);
$authConfig = array(
'code' => '',
'client_id' => 'jb-drucker',
'client_secret' => 'AIzaSyDNft6EngzYmJfCSU3sTy9cRGzJQMudK14',
'redirect_uri' => 'http://edv.jb-transport.de/oAuthRedirect.php',
"grant_type" => "authorization_code"
);
$offlineAccessConfig = array(
'access_type' => 'offline'
);
$refreshTokenConfig = array(
'refresh_token' => "",
'client_id' => $authConfig['client_id'],
'client_secret' => $authConfig['client_secret'],
'grant_type' => "refresh_token"
);
$urlconfig = array(
'authorization_url' => 'https://accounts.google.com/o/oauth2/auth',
'accesstoken_url' => 'https://accounts.google.com/o/oauth2/token',
'refreshtoken_url' => 'https://www.googleapis.com/oauth2/v3/token'
);
?>

View file

@ -0,0 +1,256 @@
<?php
/*
PHP implementation of Google Cloud Print
Author, Yasir Siddiqui
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
require_once 'HttpRequest.Class.php';
class GoogleCloudPrint {
const PRINTERS_SEARCH_URL = "https://www.google.com/cloudprint/search";
const PRINT_URL = "https://www.google.com/cloudprint/submit";
const JOBS_URL = "https://www.google.com/cloudprint/jobs";
private $authtoken;
private $httpRequest;
private $refreshtoken;
/**
* Function __construct
* Set private members varials to blank
*/
public function __construct() {
$this->authtoken = "";
$this->httpRequest = new HttpRequest();
}
/**
* Function setAuthToken
*
* Set auth tokem
* @param string $token token to set
*/
public function setAuthToken($token) {
$this->authtoken = $token;
}
/**
* Function getAuthToken
*
* Get auth tokem
* return auth tokem
*/
public function getAuthToken() {
return $this->authtoken;
}
/**
* Function getAccessTokenByRefreshToken
*
* Gets access token by making http request
*
* @param $url url to post data to
*
* @param $post_fields post fileds array
*
* return access tokem
*/
public function getAccessTokenByRefreshToken($url,$post_fields) {
$responseObj = $this->getAccessToken($url,$post_fields);
return $responseObj->access_token;
}
/**
* Function getAccessToken
*
* Makes Http request call
*
* @param $url url to post data to
*
* @param $post_fields post fileds array
*
* return http response
*/
public function getAccessToken($url,$post_fields) {
$this->httpRequest->setUrl($url);
$this->httpRequest->setPostData($post_fields);
$this->httpRequest->send();
$response = json_decode($this->httpRequest->getResponse());
return $response;
}
/**
* Function getPrinters
*
* Get all the printers added by user on Google Cloud Print.
* Follow this link https://support.google.com/cloudprint/answer/1686197 in order to know how to add printers
* to Google Cloud Print service.
*/
public function getPrinters() {
// Check if we have auth token
if(empty($this->authtoken)) {
// We don't have auth token so throw exception
throw new Exception("Please first login to Google");
}
// Prepare auth headers with auth token
$authheaders = array(
"Authorization: Bearer " .$this->authtoken
);
$this->httpRequest->setUrl(self::PRINTERS_SEARCH_URL);
$this->httpRequest->setHeaders($authheaders);
$this->httpRequest->send();
$responsedata = $this->httpRequest->getResponse();
// Make Http call to get printers added by user to Google Cloud Print
$printers = json_decode($responsedata);
// Check if we have printers?
if(is_null($printers)) {
// We dont have printers so return balnk array
return array();
}
else {
// We have printers so returns printers as array
return $this->parsePrinters($printers);
}
}
/**
* Function sendPrintToPrinter
*
* Sends document to the printer
*
* @param Printer id $printerid // Printer id returned by Google Cloud Print service
*
* @param Job Title $printjobtitle // Title of the print Job e.g. Fincial reports 2012
*
* @param File Path $filepath // Path to the file to be send to Google Cloud Print
*
* @param Content Type $contenttype // File content type e.g. application/pdf, image/png for pdf and images
*/
public function sendPrintToPrinter($printerid,$printjobtitle,$filepath,$contenttype) {
// Check if we have auth token
if(empty($this->authtoken)) {
// We don't have auth token so throw exception
throw new Exception("Please first login to Google by calling loginToGoogle function");
}
// Check if prtinter id is passed
if(empty($printerid)) {
// Printer id is not there so throw exception
throw new Exception("Please provide printer ID");
}
// Open the file which needs to be print
$handle = fopen($filepath, "rb");
if(!$handle)
{
// Can't locate file so throw exception
throw new Exception("Could not read the file. Please check file path.");
}
// 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
);
// Prepare authorization headers
$authheaders = array(
"Authorization: Bearer " . $this->authtoken
);
// Make http call for sending print Job
$this->httpRequest->setUrl(self::PRINT_URL);
$this->httpRequest->setPostData($post_fields);
$this->httpRequest->setHeaders($authheaders);
$this->httpRequest->send();
$response = json_decode($this->httpRequest->getResponse());
// Has document been successfully sent?
if($response->success=="1") {
return array('status' =>true,'errorcode' =>'','errormessage'=>"", 'id' => $response->job->id);
}
else {
return array('status' =>false,'errorcode' =>$response->errorCode,'errormessage'=>$response->message);
}
}
public function jobStatus($jobid)
{
// Prepare auth headers with auth token
$authheaders = array(
"Authorization: Bearer " .$this->authtoken
);
// Make http call for sending print Job
$this->httpRequest->setUrl(self::JOBS_URL);
$this->httpRequest->setHeaders($authheaders);
$this->httpRequest->send();
$responsedata = json_decode($this->httpRequest->getResponse());
foreach ($responsedata->jobs as $job)
if ($job->id == $jobid)
return $job->status;
return 'UNKNOWN';
}
/**
* Function parsePrinters
*
* Parse json response and return printers array
*
* @param $jsonobj // Json response object
*
*/
private function parsePrinters($jsonobj) {
$printers = array();
if (isset($jsonobj->printers)) {
foreach ($jsonobj->printers as $gcpprinter) {
$printers[] = array('id' =>$gcpprinter->id,'name' =>$gcpprinter->name,'displayName' =>$gcpprinter->displayName,
'ownerName' => $gcpprinter->ownerName,'connectionStatus' => $gcpprinter->connectionStatus,
);
}
}
return $printers;
}
}

View file

@ -0,0 +1,112 @@
<?php
/*
Simple Http request class
Author, Yasir Siddiqui
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
class HttpRequest {
public $httpResponse;
public $ch;
/**
* Function __construct
* Set member variables
* @param url $url // Url to send http request to
*/
public function __construct($url = null) {
// Initialize curl
$this->ch = curl_init();
curl_setopt( $this->ch, CURLOPT_FOLLOWLOCATION,true);
curl_setopt( $this->ch, CURLOPT_HEADER,false);
curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt( $this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $this->ch, CURLOPT_HTTPAUTH,CURLAUTH_ANY);
if(isset($url)) {
$this->setUrl($url);
}
}
/**
* Function setUrl
* Set http request url
* @param string $url // http request url
*/
public function setUrl($url) {
curl_setopt( $this->ch, CURLOPT_URL, $url );
}
/**
* Function setPostData
* Set data to be posted to the url
* @param array $params // Key value pairs of data to be posted
*/
public function setPostData( $params ) {
curl_setopt( $this->ch, CURLOPT_POST, true );
curl_setopt ( $this->ch, CURLOPT_POSTFIELDS,$params);
}
/**
* Function setHeaders
* Set http request headers
* @param array $headers // array containing headers
*/
public function setHeaders($headers) {
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
}
/**
* Function send
* Send http request
* return void
*/
public function send() {
// execute curl
$this->httpResponse = curl_exec( $this->ch );
}
/**
* Function getResponse
* return response of last http request sent
* return http response
*/
public function getResponse() {
return $this->httpResponse;
}
/**
* Function __destruct
* class destructor
*/
public function __destruct() {
curl_close($this->ch);
}
}
?>

42
scripts/google/README.md Normal file
View file

@ -0,0 +1,42 @@
Google Cloud Print
======================
PHP class to print documents using Google Cloud Print using OAuth2.
First of all you have to add printers to Google Cloud Print
using your Gmail account and Google Chrome browser. Follow the
instructions on the following link to add printer to Google Cloud Print
https://support.google.com/cloudprint/answer/1686197
Google OAuth Prerequisites
1) Create Google API project and get OAuth credentials.
Create Google OAuth Credentials
1) Create new project and get the corresponding OAuth credentials using Google developer console
https://console.developers.google.com/
2) Select APIS & AUTH > credentials from the left menu.
3) Click Create new Client ID button. A popup will appear. In Authorized redirect URIs text area enter url that should point to oAuthRedirect.php on your server.
4) After submitting this form, we can get the client Id, secret key etc.
Replace client_id, client_secret values in $redirectConfig and $authConfig arrays in Config.php file.
You also need to replace redirect_uri in both $redirectConfig and $authConfig arrays. This URL should
point to oAuthRedirect.php on your server.
## For Online Access hit index.php
Online access requires authorization every time you need to send print to printer once token in Session gets expired.
## For Offline Access (when you want to send prints without user presence) hit offlineAccess.php
Offline access requires authorization only once or unless user has revoked access. You should use offline access when you want to send prints to printer with out the presence of user or send prints to printer using a cron job script.
Once you hit offlineAccess.php you will be redirected to offlineToken.php which will show you your refresh token.
You need to save refresh token to database, file or some cache systems as later on when you will send print to printer in offline mode you need to replace that refrsh token at line # 29 on cron.php

59
scripts/google/cron.php Normal file
View file

@ -0,0 +1,59 @@
<?php
// To add printers to your account follow the following link
// https://support.google.com/cloudprint/answer/1686197
/**
* PHP implementation of Google Cloud Print
*
* 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/>.
*/
require_once 'Config.php';
require_once 'GoogleCloudPrint.php';
// Create object
$gcp = new GoogleCloudPrint();
// Replace token you got in offlineToken.php
$refreshTokenConfig['refresh_token'] = 'YOUR-OFFLINE-ACCESS-TOKEN';
$token = $gcp->getAccessTokenByRefreshToken($urlconfig['refreshtoken_url'],http_build_query($refreshTokenConfig));
$gcp->setAuthToken($token);
$printers = $gcp->getPrinters();
//print_r($printers);
$printerid = "";
if(count($printers)==0) {
echo "Could not get printers";
exit;
}
else {
$printerid = $printers[0]['id']; // Pass id of any printer to be used for print
// Send document to the printer
$resarray = $gcp->sendPrintToPrinter($printerid, "Printing Doc using Google Cloud Printing", "./pdf.pdf", "application/pdf");
if($resarray['status']==true) {
echo "Document has been sent to printer and should print shortly.";
}
else {
echo "An error occured while printing the doc. Error code:".$resarray['errorcode']." Message:".$resarray['errormessage'];
}
}
?>

31
scripts/google/index.php Normal file
View file

@ -0,0 +1,31 @@
<?php
// To add printers to your account follow the following link
// https://support.google.com/cloudprint/answer/1686197
/**
* PHP implementation of Google Cloud Print
*
* 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/>.
*/
session_start();
if (!isset($_SESSION['accessToken'])) {
header('Location: oAuthRedirect.php?op=getauth');
}
else {
header("Location: example.php");
}
?>

View file

@ -0,0 +1,66 @@
<?php
/*
PHP implementation of Google Cloud Print
Author, Yasir Siddiqui
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
require_once 'Config.php';
require_once 'GoogleCloudPrint.php';
if (isset($_GET['op'])) {
if ($_GET['op']=="getauth") {
header("Location: ".$urlconfig['authorization_url']."?".http_build_query($redirectConfig));
exit;
}
else if ($_GET['op']=="offline") {
header("Location: ".$urlconfig['authorization_url']."?".http_build_query(array_merge($redirectConfig,$offlineAccessConfig)));
exit;
}
}
session_start();
// Google redirected back with code in query string.
if(isset($_GET['code']) && !empty($_GET['code'])) {
$code = $_GET['code'];
$authConfig['code'] = $code;
// Create object
$gcp = new GoogleCloudPrint();
$responseObj = $gcp->getAccessToken($urlconfig['accesstoken_url'],$authConfig);
$accessToken = $responseObj->access_token;
// We requested offline access
if (isset($responseObj->refresh_token)) {
header("Location: offlineToken.php?offlinetoken=".$responseObj->refresh_token);
exit;
}
$_SESSION['accessToken'] = $accessToken;
header("Location: example.php");
}
?>

View file

@ -0,0 +1,25 @@
<?php
// To add printers to your account follow the following link
// https://support.google.com/cloudprint/answer/1686197
/**
* PHP implementation of Google Cloud Print
*
* 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/>.
*/
header('Location: oAuthRedirect.php?op=offline');
?>

View file

@ -0,0 +1,27 @@
<!doctype html>
<html lang="en">
<head>
<style>
.disclaimer {
border: dotted 1px #885777;
padding: 1em;
background-color: #FFF0F5;
font-size: 1.5em;
font-style: italic;
color: #885777;
}
</style>
<title>Offline Access Token</title>
</head>
<body>
<?php
if (isset($_GET['offlinetoken'])) {
echo "<p class=\"disclaimer\">Here is your offline access token: ".$_GET['offlinetoken']." <br>You need to save it
to database, file or some cache system so that you can use it later on.<br>
You need to replace this token in cron.php at line # 29 either by querying database
,cache system or from file.";
}
?>
</body>
</html>

52
scripts/google/print.php Normal file
View file

@ -0,0 +1,52 @@
<?php
// To add printers to your account follow the following link
// https://support.google.com/cloudprint/answer/1686197
/**
* PHP implementation of Google Cloud Print
*
* 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/>.
*/
require_once 'GoogleCloudPrint.php';
session_start();
// Create object
$gcp = new GoogleCloudPrint();
$gcp->setAuthToken($_SESSION['accessToken']);
$printers = $gcp->getPrinters();
//print_r($printers);
$printerid = "";
if(count($printers)==0) {
echo "Could not get printers";
exit;
}
else {
$printerid = $printers[0]['id']; // Pass id of any printer to be used for print
// Send document to the printer
$resarray = $gcp->sendPrintToPrinter($printerid, "Printing Doc using Google Cloud Printing", "./pdf.pdf", "application/pdf");
if($resarray['status']==true) {
echo "Document has been sent to printer and should print shortly.";
}
else {
echo "An error occured while printing the doc. Error code:".$resarray['errorcode']." Message:".$resarray['errormessage'];
}
}