-
Notifications
You must be signed in to change notification settings - Fork 0
/
GoogleCloudPrint.php
executable file
·495 lines (431 loc) · 15.3 KB
/
GoogleCloudPrint.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
<?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.
*/
namespace inquid\googlecloudprint;
use Yii;
use Exception;
use yii\base\Component;
use yii\httpclient\Client;
use yii\data\ArrayDataProvider;
use yii\grid\GridView;
use yii\helpers\Html;
use yii\web\Session;
use yii\web\HttpException;
/**
* Class GoogleCloudPrint
* @package app\components\GooglePrinting
*
* @property mixed $accessTokenByRefreshToken
* @property array $printers
* @property mixed $authToken
* @property mixed $defaultPrinter
*/
class GoogleCloudPrint extends Component
{
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";
const AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/auth";
const ACCESSTOKEN_URL = "https://accounts.google.com/o/oauth2/token";
const REFRESHTOKEN_URL = "https://www.googleapis.com/oauth2/v3/token";
const SCOPE_URL = "https://www.googleapis.com/auth/cloudprint";
private $authtoken;
private $session;
public $redirect_uri;
public $refresh_token;
public $client_id;
public $client_secret;
public $grant_type;
//Optional
public $default_printer_id;
/**
* Function __construct
* Set private members varials to blank
*/
public function init()
{
parent::init();
$this->authtoken = "";
$this->session = new Session;
}
/**
* Function setAuthToken
*
* Set auth tokem
* @param string $token token to set
*/
public function setAuthToken()
{
$this->authtoken = $this->getAccessTokenByRefreshToken();
}
/**
* Function setAuthTokenByResponce
* Set auth token by responce
* return auth tokem
*/
public function setAuthTokenByResponce($_access_token){
$this->authtoken = $_access_token;
}
/**
* Function getAuthToken
*
* Get auth tokem
* return auth tokem
*/
public function getAuthToken()
{
return $this->authtoken;
}
public function getRefreshToken($code)
{
$authConfig = array(
'code' => $code,
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->redirect_uri,
"grant_type" => "authorization_code"
);
return $this->getAccessToken(self::ACCESSTOKEN_URL, $authConfig);
}
/**
* Function getAccessTokenByRefreshToken
*
* Gets access token by making http request
*
* @param $url string to post data to
*
* @param $post_fields array fileds
*
* return access tokem
* @return mixed
*/
public function getAccessTokenByRefreshToken()
{
$refreshTokenConfig = array(
'refresh_token' => $this->refresh_token?$this->refresh_token:$this->getRefreshTokenSession(),
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'grant_type' => $this->grant_type
);
$responce = $this->getAccessToken(self::REFRESHTOKEN_URL, $refreshTokenConfig);
if(isset($responce->access_token)) return $responce->access_token;
return "";
}
/**
* Function getAccessToken
*
* Makes Http request call
*
* @param $url string to post data to
* @return mixed
* @internal param array $post_fields fileds array
*
* return http response
*/
public function getAccessToken($url, $config)
{
$client = new Client(['baseUrl' => $url,
'responseConfig' => [
'format' => Client::FORMAT_JSON
],
]);
$response = $client->createRequest()
->setMethod('POST')
->addHeaders(['Content-Type' => 'application/json'])
->setContent(json_encode($config))
->send();
return json_decode($response->content);
}
public function getAuthUrl(){
$redirectConfig = array(
'client_id' => $this->client_id,
'redirect_uri' => $this->redirect_uri,
'response_type' => 'code',
'access_type' => 'offline',
'prompt' => 'consent',
'scope' => self::SCOPE_URL,
);
return self::AUTHORIZATION_URL."?".http_build_query($redirectConfig);
}
/**
* Returns the default printer if set
* @return mixed
*/
public function getDefaultPrinter()
{
if ($this->default_printer_id != null) {
return $this->default_printer_id;
}
return null;
}
/**
* 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)) {
$this->setAuthToken();
}
$client = new Client(['baseUrl' => self::PRINTERS_SEARCH_URL,
'responseConfig' => [
'format' => Client::FORMAT_JSON
],
]);
$request = $client->createRequest();
$request->headers->set('Authorization', 'Bearer ' . $this->authtoken);
$response = $request->send();
$printers = json_decode($response->content);
// Check if we have printers?
if (is_null($printers)) {
// We dont have printers so return balnk array
return [];
} else {
// We have printers so returns printers as array
return $this->parsePrinters($printers);
}
}
public function renderPrinters()
{
$gridColumn = [
[
'label' => 'Id',
'attribute' => 'id',
],
[
'label' => 'Name',
'attribute' => 'name',
],
[
'label' => 'Display Name',
'attribute' => 'displayName',
],
[
'label' => 'Owner Name',
'attribute' => 'ownerName',
],
[
'label' => 'Connection Status',
'attribute' => 'connectionStatus',
'format' => 'html',
'value' => function ($data) {
if ($data['connectionStatus'] == "ONLINE")
return Html::decode('<span style="color: #00aa00">' . $data['connectionStatus'] . '</span>');
return '<span style="color: #aa1700">' . $data['connectionStatus'] . '</span>';
},
]
];
$dataProvider = new ArrayDataProvider([
'allModels' => $this->getPrinters(),
'pagination' => [
'pageSize' => 10,
],
]);
return GridView::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumn
]);
}
/**
* @param $printerid
* @param $printjobtitle
* @param $content string text to be sent
* @param $contenttype string application/html for example
* @return array|Error
* @throws Exception
*/
public function sendPrintToPrinterContent($printerid, $printjobtitle, $content, $contenttype)
{
// Check if we have auth token
if (empty($this->authtoken)) {
$this->setAuthToken();
}
// Check if prtinter id is passed
if($printerid == null || $printerid == ""){
if($this->default_printer_id == null || $this->default_printer_id == ""){
throw new HttpException(404, "GoogleCloudPrint error: Please provide printer ID");
}else
$printerid = $this->default_printer_id;
}
// Prepare post fields for sending print
$post_fields = array(
'printerid' => $printerid,
'title' => $printjobtitle,
'contentTransferEncoding' => 'utf-8',
'content' => $content, // encode file content as base64
'contentType' => $contenttype
);
$client = new Client(['baseUrl' => self::PRINT_URL,
'responseConfig' => [
'format' => Client::FORMAT_JSON
],
]);
$return = $client->createRequest()
->setMethod('POST')
->addHeaders(['Authorization'=> 'Bearer '.$this->authtoken])// 'Content-Type' => 'application/json'
->setData($post_fields)
->send();
$response = json_decode($return->content);
// Has document been successfully sent?
if ($response->success == "1") {
return array('status' => true, 'id' => $response->job->id);
} else {
throw new HttpException(451,'GoogleCloudPrint error: # '. $response->errorCode . ' - ' . $response->message);
return [];
}
}
public function actionPrintView($view, $job = null, $printerId = null)
{
return $this->sendPrintToPrinterContent($printerId, $job, $view, "text/html");
}
/**
* Function sendPrintToPrinter
*
* Sends document to the printer
*
* @param $printerid
* @param $printjobtitle
* @param $filepath
* @param $contenttype
* @return array|Error
* @throws Exception
* @internal param id $Printer $printerid // Printer id returned by Google Cloud Print service
*
* @internal param Title $Job $printjobtitle // Title of the print Job e.g. Fincial reports 2012
*
* @internal param Path $File $filepath // Path to the file to be send to Google Cloud Print
*
* @internal param Type $Content $contenttype // File content type e.g. application/pdf, image/png for pdf and images
*/
public function sendFileToPrinter($printerid, $printjobtitle, $filepath, $contenttype)
{
// Check if we have auth token
if (empty($this->authtoken)) {
$this->setAuthToken();
}
// Check if prtinter id is passed
if($printerid == null || $printerid == ""){
if($this->default_printer_id == null || $this->default_printer_id == ""){
throw new HttpException(404, "GoogleCloudPrint error: Please provide printer ID");
}else
$printerid = $this->default_printer_id;
}
try {
// Open the file which needs to be print
$handle = fopen($filepath, "rb");
} catch (Exception $e) {
throw new HttpException(404, "GoogleCloudPrint error: Could not read the file. Please check file path.");
}
// Read file content
$contents = file_get_contents($filepath);
// 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
);
$client = new Client(['baseUrl' => self::PRINT_URL,
'responseConfig' => [
'format' => Client::FORMAT_JSON
],
]);
$return = $client->createRequest()
->setMethod('POST')
->addHeaders(['Authorization'=> 'Bearer '.$this->authtoken])// 'Content-Type' => 'application/json'
->setData($post_fields)
->send();
$response = json_decode($return->content);
// Has document been successfully sent?
if ($response->success == "1") {
return array('status' => true, 'id' => $response->job->id);
} else {
throw new HttpException(451,'GoogleCloudPrint error: # '. $response->errorCode . ' - ' . $response->message);
return [];
}
}
public function jobStatus($jobid)
{
// Check if we have auth token
if (empty($this->authtoken)) {
$this->setAuthToken();
}
$client = new Client(['baseUrl' => self::JOBS_URL,
'responseConfig' => [
'format' => Client::FORMAT_JSON
],
]);
$request = $client->createRequest();
$request->headers->set('Authorization', 'Bearer ' . $this->authtoken);
$response = $request->send();
$responsedata = json_decode($response->content);
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
*
* @return array
*/
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;
}
public function setRefreshTokenSession($refresh_token=""){
$this->session->set('refresh_token', $refresh_token);
}
public function getRefreshTokenSession(){
return $this->refresh_token?$this->refresh_token:$this->session->get('refresh_token');
}
public function getRedirectUrl(){
return $this->session->get('gcpRedirectUrl');
}
public function removeTokenSession(){
$this->session->remove('refresh_token');
$this->session->remove('gcpRedirectUrl');
}
public function checkRefreshTokenSession($redirectUrl){
if(!$this->getRefreshTokenSession()) {
$this->session->set('gcpRedirectUrl', $redirectUrl);
return Yii::$app->response->redirect($this->redirect_uri)->send();
}
}
}