Update lib with github.com/mfly/php-ipp

This commit is contained in:
frederic34 2014-12-28 11:29:53 +01:00
parent 3bf63ed0a9
commit 310be3d3b6
5 changed files with 4365 additions and 3903 deletions

View File

@ -1,6 +1,6 @@
<?php <?php
/* vim: set expandtab tabstop=2 shiftwidth=2 foldmethod=marker: */
/* @(#) $Header: /sources/phpprintipp/phpprintipp/php_classes/BasicIPP.php,v 1.6 2010/08/22 15:45:17 harding Exp $ /* @(#) $Header: /sources/phpprintipp/phpprintipp/php_classes/BasicIPP.php,v 1.7 2012/03/01 17:21:04 harding Exp $
* *
* Class BasicIPP - Send Basic IPP requests, Get and parses IPP Responses. * Class BasicIPP - Send Basic IPP requests, Get and parses IPP Responses.
* *
@ -35,103 +35,26 @@
- RFC 3380 - RFC 3380
- RFC 3382 - RFC 3382
*/ */
/*
TODO: beta tests on other servers than Cups
*/
// required and included files
require_once ("http_class.php"); require_once ("http_class.php");
/*
// If you want http backend from http://www.phpclasses.org/browse/package/3.html class ippException extends \Exception
require_once("HTTP/http.php");
include_once("SASL/sasl.php");
include_once("SASL/basic_sasl_client.php");
include_once("SASL/digest_sasl_client.php");
include_once("SASL/ntlm_sasl_client.php");
*/
/**
* Class and Function List:
* Function list:
* - __construct()
* - getErrorFormatted()
* - getErrno()
* - setPort()
* - setUnix()
* - setHost()
* - setTimeout()
* - setPrinterURI()
* - setData()
* - setRawText()
* - unsetRawText()
* - setBinary()
* - setFormFeed()
* - unsetFormFeed()
* - setCharset()
* - setLanguage()
* - setDocumentFormat()
* - setMimeMediaType()
* - setCopies()
* - setDocumentName()
* - setJobName()
* - setUserName()
* - setAuthentification()
* - setAuthentication()
* - setSides()
* - setFidelity()
* - unsetFidelity()
* - setMessage()
* - setPageRanges()
* - setAttribute()
* - unsetAttribute()
* - setLog()
* - printDebug()
* - getDebug()
* - printJob()
* - _sendHttp()
* - _initTags()
* - _setOperationId()
* - _setJobId()
* - _setJobUri()
* - _parseServerOutput()
* - _parseHttpHeaders()
* - _parseIppVersion()
* - _parseStatusCode()
* - _parseRequestID()
* - _interpretInteger()
* - _parseResponse()
* - _stringJob()
* - _buildValues()
* - _giveMeStringLength()
* - _enumBuild()
* - _integerBuild()
* - _rangeOfIntegerBuild()
* - _setJobAttribute()
* - _setOperationAttribute()
* - _setPrinterAttribute()
* - _putDebug()
* - _errorLog()
* Classes list:
* - ippException extends Exception
* - BasicIPP
*/
/***********************
*
* ippException class
*
************************/
class ippException extends Exception
{ {
protected $errno; protected $errno;
public function __construct($msg, $errno = null) public function __construct($msg, $errno = null)
{ {
parent::__construct($msg); parent::__construct($msg);
$this->errno = $errno; $this->errno = $errno;
} }
public function getErrorFormatted() public function getErrorFormatted()
{ {
$return = sprintf("[ipp]: %s -- " . _(" file %s, line %s"), $return = sprintf("[ipp]: %s -- " . _(" file %s, line %s"),
$this->getMessage() , $this->getFile() , $this->getLine()); $this->getMessage() , $this->getFile() , $this->getLine());
return $return; return $return;
} }
public function getErrno() public function getErrno()
{ {
return $this->errno; return $this->errno;
@ -140,12 +63,6 @@ class ippException extends Exception
class BasicIPP class BasicIPP
{ {
//
// variables declaration
//
// setup variables
public $paths = array( public $paths = array(
"root" => "/", "root" => "/",
"admin" => "/admin/", "admin" => "/admin/",
@ -161,7 +78,6 @@ class BasicIPP
public $handle_http_exceptions = 1; public $handle_http_exceptions = 1;
// readables variables // readables variables
public $jobs = array(); public $jobs = array();
public $jobs_uri = array(); public $jobs_uri = array();
public $status = array(); public $status = array();
@ -172,9 +88,11 @@ class BasicIPP
public $job_attributes; // object you can read: last job attributes public $job_attributes; // object you can read: last job attributes
public $jobs_attributes; // object you can read: jobs attributes after getJobs() public $jobs_attributes; // object you can read: jobs attributes after getJobs()
public $available_printers = array(); public $available_printers = array();
public $printer_map = array();
public $printers_uri = array(); public $printers_uri = array();
public $debug = array(); public $debug = array();
public $response; public $response;
public $meta;
// protected variables; // protected variables;
protected $log_level = 2; // max 3: very verbose protected $log_level = 2; // max 3: very verbose
@ -193,6 +111,7 @@ class BasicIPP
protected $stream; protected $stream;
protected $host = "localhost"; protected $host = "localhost";
protected $port = "631"; protected $port = "631";
protected $requesting_user = '';
protected $printer_uri; protected $printer_uri;
protected $timeout = "20"; //20 secs protected $timeout = "20"; //20 secs
protected $errNo; protected $errNo;
@ -200,7 +119,6 @@ class BasicIPP
protected $datatype; protected $datatype;
protected $datahead; protected $datahead;
protected $datatail; protected $datatail;
public $meta;
protected $operation_id; protected $operation_id;
protected $delay; protected $delay;
protected $error_generation; //devel feature protected $error_generation; //devel feature
@ -216,31 +134,25 @@ class BasicIPP
protected $end_collection = false; //RFC3382 protected $end_collection = false; //RFC3382
protected $collection_nbr = array(); //RFC3382 protected $collection_nbr = array(); //RFC3382
protected $unix = false; // true -> use unix sockets instead of http protected $unix = false; // true -> use unix sockets instead of http
protected $output;
// constructor
public function __construct() public function __construct()
{ {
$tz = getenv("date.timezone"); $tz = getenv("date.timezone");
if (!$tz) $tz = @date_default_timezone_get(); if (!$tz)
date_default_timezone_set($tz); {
$this->meta = new stdClass(); $tz = @date_default_timezone_get();
$this->setup = new stdClass();
$this->values = new stdClass();
$this->serveroutput = new stdClass();
$this->error_generation = new stdClass();
$this->_parsing = new stdClass();
self::_initTags();
} }
/***************** date_default_timezone_set($tz);
* $this->meta = new \stdClass();
* PUBLIC FUNCTIONS $this->setup = new \stdClass();
* $this->values = new \stdClass();
*******************/ $this->serveroutput = new \stdClass();
$this->error_generation = new \stdClass();
// $this->_parsing = new \stdClass();
// SETUP self::_initTags();
// }
public function setPort($port = '631') public function setPort($port = '631')
{ {
@ -303,7 +215,12 @@ class BasicIPP
{ {
$output = $this->data; $output = $this->data;
} }
if (substr($output, -1, 1) != chr(0x0c)) if (!isset($this->setup->noFormFeed)) $this->datatail = chr(0x0c); if (substr($output, -1, 1) != chr(0x0c)) {
if (!isset($this->setup->noFormFeed))
{
$this->datatail = chr(0x0c);
}
}
self::_putDebug(_("Forcing data to be interpreted as RAW TEXT") , 2); self::_putDebug(_("Forcing data to be interpreted as RAW TEXT") , 2);
} }
@ -332,7 +249,7 @@ class BasicIPP
$this->setup->noFormFeed = 1; $this->setup->noFormFeed = 1;
} }
public function setCharset($charset = 'us-ascii') public function setCharset($charset = 'utf-8')
{ {
$charset = strtolower($charset); $charset = strtolower($charset);
$this->charset = $charset; $this->charset = $charset;
@ -378,7 +295,12 @@ class BasicIPP
public function setCopies($nbrcopies = 1) public function setCopies($nbrcopies = 1)
{ {
$this->meta->copies = ""; $this->meta->copies = "";
if ($nbrcopies == 1 || !$nbrcopies) return true;
if ($nbrcopies == 1 || !$nbrcopies)
{
return true;
}
$copies = self::_integerBuild($nbrcopies); $copies = self::_integerBuild($nbrcopies);
$this->meta->copies = chr(0x21) // integer type | value-tag $this->meta->copies = chr(0x21) // integer type | value-tag
. chr(0x00) . chr(0x06) // name-length . chr(0x00) . chr(0x06) // name-length
@ -392,7 +314,9 @@ class BasicIPP
public function setDocumentName($document_name = "") public function setDocumentName($document_name = "")
{ {
$this->meta->document_name = ""; $this->meta->document_name = "";
if (!$document_name) return true; if (!$document_name) {
return true;
}
$document_name = substr($document_name, 0, 1023); $document_name = substr($document_name, 0, 1023);
$length = strlen($document_name); $length = strlen($document_name);
$length = chr($length); $length = chr($length);
@ -414,7 +338,9 @@ class BasicIPP
return true; return true;
} }
$postpend = date('-H:i:s-') . $this->_setJobId(); $postpend = date('-H:i:s-') . $this->_setJobId();
if ($absolute) $postpend = ''; if ($absolute) {
$postpend = '';
}
if (isset($this->values->jobname) && $jobname == '(PHP)') if (isset($this->values->jobname) && $jobname == '(PHP)')
{ {
$jobname = $this->values->jobname; $jobname = $this->values->jobname;
@ -434,8 +360,12 @@ class BasicIPP
{ {
$this->requesting_user = $username; $this->requesting_user = $username;
$this->meta->username = ''; $this->meta->username = '';
if (!$username) return true; if (!$username) {
if ($username == 'PHP-SERVER' && isset($this->meta->username)) return TRUE; return true;
}
if ($username == 'PHP-SERVER' && isset($this->meta->username)) {
return TRUE;
}
/* /*
$value_length = 0x00; $value_length = 0x00;
for ($i = 0; $i < strlen($username); $i++) for ($i = 0; $i < strlen($username); $i++)
@ -470,7 +400,11 @@ class BasicIPP
public function setSides($sides = 2) public function setSides($sides = 2)
{ {
$this->meta->sides = ''; $this->meta->sides = '';
if (!$sides) return true; if (!$sides)
{
return true;
}
switch ($sides) switch ($sides)
{ {
case 1: case 1:
@ -484,11 +418,8 @@ class BasicIPP
case "2CE": case "2CE":
$sides = "two-sided-short-edge"; $sides = "two-sided-short-edge";
break; break;
default:
$sides = $sides; // yeah, what ?
break;
} }
$this->meta->sides = chr(0x44) // keyword type | value-tag $this->meta->sides = chr(0x44) // keyword type | value-tag
. chr(0x00) . chr(0x05) // name-length . chr(0x00) . chr(0x05) // name-length
. "sides" // sides | name . "sides" // sides | name
@ -526,7 +457,9 @@ class BasicIPP
public function setMessage($message = '') public function setMessage($message = '')
{ {
$this->meta->message = ''; $this->meta->message = '';
if (!$message) return true; if (!$message) {
return true;
}
$this->meta->message = $this->meta->message =
chr(0x41) // attribute type = textWithoutLanguage chr(0x41) // attribute type = textWithoutLanguage
. chr(0x00) . chr(0x00)
@ -542,7 +475,9 @@ class BasicIPP
// $pages_ranges = string: "1:5 10:25 40:52 ..." // $pages_ranges = string: "1:5 10:25 40:52 ..."
// to unset, specify an empty string. // to unset, specify an empty string.
$this->meta->page_range = ''; $this->meta->page_range = '';
if (!$page_ranges) return true; if (!$page_ranges) {
return true;
}
$page_ranges = trim(str_replace("-", ":", $page_ranges)); $page_ranges = trim(str_replace("-", ":", $page_ranges));
$first = true; $first = true;
#$page_ranges = split(' ', $page_ranges); #$page_ranges = split(' ', $page_ranges);
@ -679,13 +614,21 @@ class BasicIPP
// //
// LOGGING / DEBUGGING // LOGGING / DEBUGGING
// //
/**
* Sets log file destination. Creates the file if has permission.
*
* @param string $log_destination
* @param string $destination_type
* @param int $level
*
* @throws ippException
*/
public function setLog($log_destination, $destination_type = 'file', $level = 2) public function setLog($log_destination, $destination_type = 'file', $level = 2)
{ {
if (!file_exists($log_destination) && is_writable(dirname($log_destination)))
if (is_string($log_destination) && !empty($log_destination))
{ {
$this->log_destination = $log_destination; touch($log_destination);
chmod($log_destination, 0777);
} }
switch ($destination_type) switch ($destination_type)
@ -736,7 +679,6 @@ class BasicIPP
// //
// OPERATIONS // OPERATIONS
// //
public function printJob() public function printJob()
{ {
// this BASIC version of printJob do not parse server // this BASIC version of printJob do not parse server
@ -747,7 +689,9 @@ class BasicIPP
date('Y-m-d H:i:s') date('Y-m-d H:i:s')
) )
); );
if (!$this->_stringJob()) return FALSE; if (!$this->_stringJob()) {
return FALSE;
}
if (is_readable($this->data)) if (is_readable($this->data))
{ {
self::_putDebug(_("Printing a FILE")); self::_putDebug(_("Printing a FILE"));
@ -821,17 +765,9 @@ class BasicIPP
return false; return false;
} }
/******************
*
* PROTECTED FUNCTIONS
*
*******************/
// //
// HTTP OUTPUT // HTTP OUTPUT
// //
protected function _sendHttp($post_values, $uri) protected function _sendHttp($post_values, $uri)
{ {
/* /*
@ -843,8 +779,12 @@ class BasicIPP
$this->serveroutput->headers = array(); $this->serveroutput->headers = array();
$this->serveroutput->body = ""; $this->serveroutput->body = "";
$http = new http_class; $http = new http_class;
if (!$this->unix) $http->host = $this->host; if (!$this->unix) {
else $http->host = "localhost"; $http->host = $this->host;
}
else {
$http->host = "localhost";
}
$http->with_exceptions = $this->with_exceptions; $http->with_exceptions = $this->with_exceptions;
if ($this->debug_http) if ($this->debug_http)
{ {
@ -857,8 +797,12 @@ class BasicIPP
$http->html_debug = 0; $http->html_debug = 0;
} }
$url = "http://" . $this->host; $url = "http://" . $this->host;
if ($this->ssl) $url = "https://" . $this->host; if ($this->ssl) {
if ($this->unix) $url = "unix://" . $this->host; $url = "https://" . $this->host;
}
if ($this->unix) {
$url = "unix://" . $this->host;
}
$http->port = $this->port; $http->port = $this->port;
$http->timeout = $this->http_timeout; $http->timeout = $this->http_timeout;
$http->data_timeout = $this->http_data_timeout; $http->data_timeout = $this->http_data_timeout;
@ -875,11 +819,14 @@ class BasicIPP
"Data" => $post_values["Data"] "Data" => $post_values["Data"]
) )
); );
if (isset($post_values["File"])) $arguments["BodyStream"][] = array( if (isset($post_values["File"])) {
$arguments["BodyStream"][] = array(
"File" => $post_values["File"] "File" => $post_values["File"]
); );
}
if (isset($post_values["FileType"]) if (isset($post_values["FileType"])
&& !strcmp($post_values["FileType"], "TEXT")) && !strcmp($post_values["FileType"], "TEXT")
)
{ {
$arguments["BodyStream"][] = array("Data" => Chr(12)); $arguments["BodyStream"][] = array("Data" => Chr(12));
} }
@ -963,7 +910,9 @@ class BasicIPP
for (;;) for (;;)
{ {
$http->ReadReplyBody($body, 1024); $http->ReadReplyBody($body, 1024);
if (strlen($body) == 0) break; if (strlen($body) == 0) {
break;
}
self::_putDebug(htmlentities($body)); self::_putDebug(htmlentities($body));
$this->serveroutput->body.= $body; $this->serveroutput->body.= $body;
@ -978,7 +927,6 @@ class BasicIPP
// //
// INIT // INIT
// //
protected function _initTags() protected function _initTags()
{ {
$this->tags_types = array( $this->tags_types = array(
@ -1142,7 +1090,6 @@ class BasicIPP
// //
// SETUP // SETUP
// //
protected function _setOperationId() protected function _setOperationId()
{ {
$prepend = ''; $prepend = '';
@ -1156,7 +1103,9 @@ class BasicIPP
$this->meta->jobid+= 1; $this->meta->jobid+= 1;
$prepend = ''; $prepend = '';
$prepend_length = 4 - strlen($this->meta->jobid); $prepend_length = 4 - strlen($this->meta->jobid);
for ($i = 0; $i < $prepend_length; $i++) $prepend.= '0'; for ($i = 0; $i < $prepend_length; $i++) {
$prepend.= '0';
}
return $prepend . $this->meta->jobid; return $prepend . $this->meta->jobid;
} }
@ -1173,11 +1122,12 @@ class BasicIPP
// //
// RESPONSE PARSING // RESPONSE PARSING
// //
protected function _parseServerOutput() protected function _parseServerOutput()
{ {
$this->serveroutput->response = array(); $this->serveroutput->response = array();
if (!self::_parseHttpHeaders()) return FALSE; if (!self::_parseHttpHeaders()) {
return FALSE;
}
$this->_parsing->offset = 0; $this->_parsing->offset = 0;
self::_parseIppVersion(); self::_parseIppVersion();
self::_parseStatusCode(); self::_parseStatusCode();
@ -1480,7 +1430,6 @@ class BasicIPP
* *
ord($value[strlen($value) - $i]) ord($value[strlen($value) - $i])
); );
} }
if ($value_parsed >= 2147483648) if ($value_parsed >= 2147483648)
{ {
@ -1496,11 +1445,14 @@ class BasicIPP
// //
// REQUEST BUILDING // REQUEST BUILDING
// //
protected function _stringJob() protected function _stringJob()
{ {
if (!isset($this->setup->charset)) self::setCharset('us-ascii'); if (!isset($this->setup->charset)) {
if (!isset($this->setup->datatype)) self::setBinary(); self::setCharset();
}
if (!isset($this->setup->datatype)) {
self::setBinary();
}
if (!isset($this->setup->uri)) if (!isset($this->setup->uri))
{ {
$this->getPrinters(); $this->getPrinters();
@ -1521,16 +1473,34 @@ class BasicIPP
return FALSE; return FALSE;
} }
} }
if (!isset($this->setup->copies)) self::setCopies(1); if (!isset($this->setup->copies)) {
if (!isset($this->setup->language)) self::setLanguage('en_us'); self::setCopies(1);
if (!isset($this->setup->mime_media_type)) self::setMimeMediaType(); }
if (!isset($this->setup->jobname)) self::setJobName(); if (!isset($this->setup->language)) {
self::setLanguage('en_us');
}
if (!isset($this->setup->mime_media_type)) {
self::setMimeMediaType();
}
if (!isset($this->setup->jobname)) {
self::setJobName();
}
unset($this->setup->jobname); unset($this->setup->jobname);
if (!isset($this->meta->username)) self::setUserName(); if (!isset($this->meta->username)) {
if (!isset($this->meta->fidelity)) $this->meta->fidelity = ''; self::setUserName();
if (!isset($this->meta->document_name)) $this->meta->document_name = ''; }
if (!isset($this->meta->sides)) $this->meta->sides = ''; if (!isset($this->meta->fidelity)) {
if (!isset($this->meta->page_ranges)) $this->meta->page_ranges = ''; $this->meta->fidelity = '';
}
if (!isset($this->meta->document_name)) {
$this->meta->document_name = '';
}
if (!isset($this->meta->sides)) {
$this->meta->sides = '';
}
if (!isset($this->meta->page_ranges)) {
$this->meta->page_ranges = '';
}
$jobattributes = ''; $jobattributes = '';
$operationattributes = ''; $operationattributes = '';
$printerattributes = ''; $printerattributes = '';
@ -1560,8 +1530,7 @@ class BasicIPP
. $this->meta->copies . $this->meta->copies
. $this->meta->sides . $this->meta->sides
. $this->meta->page_ranges . $this->meta->page_ranges
. $jobattributes . $jobattributes;
;
} }
$this->stringjob.= chr(0x03); // end-of-attributes | end-of-attributes-tag $this->stringjob.= chr(0x03); // end-of-attributes | end-of-attributes-tag
self::_putDebug( self::_putDebug(
@ -1841,8 +1810,12 @@ class BasicIPP
$value-= $int3; $value-= $int3;
$value = $value >> 8; $value = $value >> 8;
$int4 = $value & 0xFF; //64bits $int4 = $value & 0xFF; //64bits
if ($initial_value < 0) $int4 = chr($int4) | chr(0x80); if ($initial_value < 0) {
else $int4 = chr($int4); $int4 = chr($int4) | chr(0x80);
}
else {
$int4 = chr($int4);
}
$value = $int4 . chr($int3) . chr($int2) . chr($int1); $value = $int4 . chr($int3) . chr($int2) . chr($int1);
return $value; return $value;
} }
@ -1851,7 +1824,9 @@ class BasicIPP
{ {
#$integers = split(":", $integers); #$integers = split(":", $integers);
$integers = preg_split("#:#", $integers); $integers = preg_split("#:#", $integers);
for ($i = 0; $i < 2; $i++) $outvalue[$i] = self::_integerBuild($integers[$i]); for ($i = 0; $i < 2; $i++) {
$outvalue[$i] = self::_integerBuild($integers[$i]);
}
return $outvalue[0] . $outvalue[1]; return $outvalue[0] . $outvalue[1];
} }
@ -1865,6 +1840,7 @@ class BasicIPP
$this->job_tags[$attribute]['value'][] = self::_integerBuild($value); $this->job_tags[$attribute]['value'][] = self::_integerBuild($value);
break; break;
case 'boolean':
case 'nameWithoutLanguage': case 'nameWithoutLanguage':
case 'nameWithLanguage': case 'nameWithLanguage':
case 'textWithoutLanguage': case 'textWithoutLanguage':
@ -1885,8 +1861,12 @@ class BasicIPP
break; break;
case 'resolution': case 'resolution':
if (preg_match("#dpi#", $value)) $unit = chr(0x3); if (preg_match("#dpi#", $value)) {
if (preg_match("#dpc#", $value)) $unit = chr(0x4); $unit = chr(0x3);
}
if (preg_match("#dpc#", $value)) {
$unit = chr(0x4);
}
$search = array( $search = array(
"#(dpi|dpc)#", "#(dpi|dpc)#",
'#(x|-)#' '#(x|-)#'
@ -1964,8 +1944,14 @@ class BasicIPP
// //
protected function _putDebug($string, $level = 1) protected function _putDebug($string, $level = 1)
{ {
if ($level === false) return; if ($level === false) {
if ($level < $this->debug_level) return; return;
}
if ($level < $this->debug_level) {
return;
}
$this->debug[$this->debug_count] = substr($string, 0, 1024); $this->debug[$this->debug_count] = substr($string, 0, 1024);
$this->debug_count++; $this->debug_count++;
//$this->debug .= substr($string,0,1024); //$this->debug .= substr($string,0,1024);
@ -1977,24 +1963,20 @@ class BasicIPP
// //
protected function _errorLog($string_to_log, $level) protected function _errorLog($string_to_log, $level)
{ {
if ($level < $this->log_level) return; if ($level > $this->log_level) {
return;
}
$string = sprintf('%s : %s:%s user %s : %s', basename($_SERVER['PHP_SELF']) , $this->host, $this->port, $this->requesting_user, $string_to_log); $string = sprintf('%s : %s:%s user %s : %s', basename($_SERVER['PHP_SELF']) , $this->host, $this->port, $this->requesting_user, $string_to_log);
if ($this->log_type == 0) if ($this->log_type == 0)
{ {
error_log($string); error_log($string);
return; return;
} }
$string = sprintf("%s %s Host %s:%s user %s : %s\n", date('M d H:i:s') , basename($_SERVER['PHP_SELF']) , $this->host, $this->port, $this->requesting_user, $string_to_log); $string = sprintf("%s %s Host %s:%s user %s : %s\n", date('M d H:i:s') , basename($_SERVER['PHP_SELF']) , $this->host, $this->port, $this->requesting_user, $string_to_log);
error_log($string, $this->log_type, $this->log_destination); error_log($string, $this->log_type, $this->log_destination);
return; return;
} }
}
};
/*
* Local variables:
* mode: php
* tab-width: 4
* c-basic-offset: 4
* End:
*/
?>

View File

@ -1,5 +1,5 @@
<?php <?php
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
/* @(#) $Header: /sources/phpprintipp/phpprintipp/php_classes/CupsPrintIPP.php,v 1.1 2008/06/21 00:30:56 harding Exp $ /* @(#) $Header: /sources/phpprintipp/phpprintipp/php_classes/CupsPrintIPP.php,v 1.1 2008/06/21 00:30:56 harding Exp $
* *
* Class PrintIPP - Send extended IPP requests. * Class PrintIPP - Send extended IPP requests.
@ -26,7 +26,6 @@
*/ */
/* /*
This class is intended to implement Internet Printing Protocol on client side. This class is intended to implement Internet Printing Protocol on client side.
References needed to debug / add functionnalities: References needed to debug / add functionnalities:
@ -39,28 +38,25 @@
require_once("ExtendedPrintIPP.php"); require_once("ExtendedPrintIPP.php");
class CupsPrintIPP extends ExtendedPrintIPP { class CupsPrintIPP extends ExtendedPrintIPP
{
// {{{ variables declaration
public $printers_attributes; public $printers_attributes;
public $defaults_attributes; public $defaults_attributes;
// }}} protected $parsed;
protected $output;
// {{{ constructor public function __construct()
public function __construct() { {
parent::__construct(); parent::__construct();
self::_initTags(); self::_initTags();
} }
// }}}
// //
// OPERATIONS // OPERATIONS
// //
public function cupsGetDefaults($attributes=array("all"))
// {{{ cupsGetDefaults ($attributes="all") {
public function cupsGetDefaults($attributes=array("all")) {
//The CUPS-Get-Default operation returns the default printer URI and attributes //The CUPS-Get-Default operation returns the default printer URI and attributes
$this->jobs = array_merge($this->jobs,array("")); $this->jobs = array_merge($this->jobs,array(""));
@ -69,25 +65,35 @@ class CupsPrintIPP extends ExtendedPrintIPP {
unset($this->printer_attributes); unset($this->printer_attributes);
if (!isset($this->setup->charset)) if (!isset($this->setup->charset))
self::setCharset('us-ascii'); {
self::setCharset();
}
if (!isset($this->setup->language)) if (!isset($this->setup->language))
{
self::setLanguage('en'); self::setLanguage('en');
}
self::_setOperationId(); self::_setOperationId();
for($i = 0 ; $i < count($attributes) ; $i++) for($i = 0 ; $i < count($attributes) ; $i++)
{
if ($i == 0) if ($i == 0)
{
$this->meta->attributes = chr(0x44) // Keyword $this->meta->attributes = chr(0x44) // Keyword
. self::_giveMeStringLength('requested-attributes') . self::_giveMeStringLength('requested-attributes')
. 'requested-attributes' . 'requested-attributes'
. self::_giveMeStringLength($attributes[0]) . self::_giveMeStringLength($attributes[0])
. $attributes[0]; . $attributes[0];
}
else else
{
$this->meta->attributes .= chr(0x44) // Keyword $this->meta->attributes .= chr(0x44) // Keyword
. chr(0x0).chr(0x0) // zero-length name . chr(0x0).chr(0x0) // zero-length name
. self::_giveMeStringLength($attributes[$i]) . self::_giveMeStringLength($attributes[$i])
. $attributes[$i]; . $attributes[$i];
}
}
$this->stringjob = chr(0x01) . chr(0x01) // IPP version 1.1 $this->stringjob = chr(0x01) . chr(0x01) // IPP version 1.1
. chr(0x40). chr(0x01) // operation: cups vendor extension: get defaults . chr(0x40). chr(0x01) // operation: cups vendor extension: get defaults
@ -105,45 +111,55 @@ class CupsPrintIPP extends ExtendedPrintIPP {
$post_values = array( "Content-Type" => "application/ipp", $post_values = array( "Content-Type" => "application/ipp",
"Data" => $this->output); "Data" => $this->output);
if (self::_sendHttp ($post_values,'/')) { if (self::_sendHttp ($post_values,'/'))
{
if(self::_parseServerOutput()) if(self::_parseServerOutput())
{
self::_parsePrinterAttributes(); self::_parsePrinterAttributes();
} }
}
$this->attributes = &$this->printer_attributes; $this->attributes = &$this->printer_attributes;
if (isset($this->printer_attributes->printer_type)) { if (isset($this->printer_attributes->printer_type))
{
$printer_type = $this->printer_attributes->printer_type->_value0; $printer_type = $this->printer_attributes->printer_type->_value0;
$table = self::_interpretPrinterType($printer_type); $table = self::_interpretPrinterType($printer_type);
for($i = 0 ; $i < count($table) ; $i++ ) { for($i = 0 ; $i < count($table) ; $i++ )
{
$index = '_value'.$i; $index = '_value'.$i;
$this->printer_attributes->printer_type->$index = $table[$i]; $this->printer_attributes->printer_type->$index = $table[$i];
} }
} }
if (isset($this->serveroutput) && isset($this->serveroutput->status)) { if (isset($this->serveroutput) && isset($this->serveroutput->status))
{
$this->status = array_merge($this->status,array($this->serveroutput->status)); $this->status = array_merge($this->status,array($this->serveroutput->status));
if ($this->serveroutput->status == "successfull-ok") if ($this->serveroutput->status == "successfull-ok")
{
self::_errorLog("getting defaults: ".$this->serveroutput->status,3); self::_errorLog("getting defaults: ".$this->serveroutput->status,3);
}
else else
{
self::_errorLog("getting defaults: ".$this->serveroutput->status,1); self::_errorLog("getting defaults: ".$this->serveroutput->status,1);
}
return $this->serveroutput->status; return $this->serveroutput->status;
}
} else { else
{
$this->status = array_merge($this->status,array("OPERATION FAILED")); $this->status = array_merge($this->status,array("OPERATION FAILED"));
self::_errorLog("getting defaults : OPERATION FAILED",1); self::_errorLog("getting defaults : OPERATION FAILED",1);
} }
return false; return false;
} }
// }}}
// {{{ cupsAcceptJobs ($printer_uri)
public function cupsAcceptJobs($printer_uri) { public function cupsAcceptJobs($printer_uri)
{
//The CUPS-Get-Default operation returns the default printer URI and attributes //The CUPS-Get-Default operation returns the default printer URI and attributes
$this->jobs = array_merge($this->jobs,array("")); $this->jobs = array_merge($this->jobs,array(""));
@ -152,10 +168,14 @@ class CupsPrintIPP extends ExtendedPrintIPP {
unset($this->printer_attributes); unset($this->printer_attributes);
if (!isset($this->setup->charset)) if (!isset($this->setup->charset))
self::setCharset('us-ascii'); {
self::setCharset();
}
if (!isset($this->setup->language)) if (!isset($this->setup->language))
{
self::setLanguage('en'); self::setLanguage('en');
}
self::_setOperationId(); self::_setOperationId();
@ -179,32 +199,41 @@ class CupsPrintIPP extends ExtendedPrintIPP {
$post_values = array( "Content-Type" => "application/ipp", $post_values = array( "Content-Type" => "application/ipp",
"Data" => $this->output); "Data" => $this->output);
if (self::_sendHttp ($post_values,'/admin/')) { if (self::_sendHttp ($post_values,'/admin/'))
{
if(self::_parseServerOutput()) if(self::_parseServerOutput())
{
self::_parseAttributes(); self::_parseAttributes();
} }
}
if (isset($this->serveroutput) && isset($this->serveroutput->status)) { if (isset($this->serveroutput) && isset($this->serveroutput->status))
{
$this->status = array_merge($this->status,array($this->serveroutput->status)); $this->status = array_merge($this->status,array($this->serveroutput->status));
if ($this->serveroutput->status == "successfull-ok") if ($this->serveroutput->status == "successfull-ok")
{
self::_errorLog("getting defaults: ".$this->serveroutput->status,3); self::_errorLog("getting defaults: ".$this->serveroutput->status,3);
}
else else
{
self::_errorLog("getting defaults: ".$this->serveroutput->status,1); self::_errorLog("getting defaults: ".$this->serveroutput->status,1);
}
return $this->serveroutput->status; return $this->serveroutput->status;
}
} else { else
{
$this->status = array_merge($this->status,array("OPERATION FAILED")); $this->status = array_merge($this->status,array("OPERATION FAILED"));
self::_errorLog("getting defaults : OPERATION FAILED",1); self::_errorLog("getting defaults : OPERATION FAILED",1);
} }
return false; return false;
} }
// }}}
// {{{ cupsRejectJobs ($printer_uri,$printer_state_message=false)
public function cupsRejectJobs($printer_uri,$printer_state_message) { public function cupsRejectJobs($printer_uri,$printer_state_message)
{
//The CUPS-Get-Default operation returns the default printer URI and attributes //The CUPS-Get-Default operation returns the default printer URI and attributes
$this->jobs = array_merge($this->jobs,array("")); $this->jobs = array_merge($this->jobs,array(""));
@ -213,21 +242,27 @@ class CupsPrintIPP extends ExtendedPrintIPP {
unset($this->attributes); unset($this->attributes);
if (!isset($this->setup->charset)) if (!isset($this->setup->charset))
self::setCharset('us-ascii'); {
self::setCharset();
}
if (!isset($this->setup->language)) if (!isset($this->setup->language))
{
self::setLanguage('en'); self::setLanguage('en');
}
self::_setOperationId(); self::_setOperationId();
$message = ""; $message = "";
if ($printer_state_message) if ($printer_state_message)
{
$message = chr(0x04) // start printer-attributes $message = chr(0x04) // start printer-attributes
. chr(0x41) // textWithoutLanguage . chr(0x41) // textWithoutLanguage
. self::_giveMeStringLength("printer-state-message") . self::_giveMeStringLength("printer-state-message")
. "printer-state-message" . "printer-state-message"
. self::_giveMeStringLength($printer_state_message) . self::_giveMeStringLength($printer_state_message)
. $printer_state_message; . $printer_state_message;
}
$this->stringjob = chr(0x01) . chr(0x01) // IPP version 1.1 $this->stringjob = chr(0x01) . chr(0x01) // IPP version 1.1
. chr(0x40). chr(0x09) // operation: cups vendor extension: Reject-Jobs . chr(0x40). chr(0x09) // operation: cups vendor extension: Reject-Jobs
@ -250,79 +285,101 @@ class CupsPrintIPP extends ExtendedPrintIPP {
$post_values = array( "Content-Type" => "application/ipp", $post_values = array( "Content-Type" => "application/ipp",
"Data" => $this->output); "Data" => $this->output);
if (self::_sendHttp ($post_values,'/admin/')) { if (self::_sendHttp ($post_values,'/admin/'))
{
if(self::_parseServerOutput()) if(self::_parseServerOutput())
{
self::_parseAttributes(); self::_parseAttributes();
} }
}
if (isset($this->serveroutput) && isset($this->serveroutput->status)) { if (isset($this->serveroutput) && isset($this->serveroutput->status))
{
$this->status = array_merge($this->status,array($this->serveroutput->status)); $this->status = array_merge($this->status,array($this->serveroutput->status));
if ($this->serveroutput->status == "successfull-ok") if ($this->serveroutput->status == "successfull-ok")
{
self::_errorLog("getting defaults: ".$this->serveroutput->status,3); self::_errorLog("getting defaults: ".$this->serveroutput->status,3);
}
else else
{
self::_errorLog("getting defaults: ".$this->serveroutput->status,1); self::_errorLog("getting defaults: ".$this->serveroutput->status,1);
}
return $this->serveroutput->status; return $this->serveroutput->status;
}
} else { else
{
$this->status = array_merge($this->status,array("OPERATION FAILED")); $this->status = array_merge($this->status,array("OPERATION FAILED"));
self::_errorLog("getting defaults : OPERATION FAILED",1); self::_errorLog("getting defaults : OPERATION FAILED",1);
} }
return false; return false;
} }
// }}}
// {{{ getPrinters()
public function getPrinters($printer_location=false,$printer_info=false,$attributes=array()) {
public function getPrinters($printer_location=false,$printer_info=false,$attributes=array())
{
if (count($attributes) == 0) if (count($attributes) == 0)
{
true; true;
$attributes=array('printer-uri-supported','printer-location','printer-info','printer-type','color-supported'); }
$attributes=array('printer-uri-supported', 'printer-location', 'printer-info', 'printer-type', 'color-supported', 'printer-name');
$this->jobs = array_merge($this->jobs,array("")); $this->jobs = array_merge($this->jobs,array(""));
$this->jobs_uri = array_merge($this->jobs_uri,array("")); $this->jobs_uri = array_merge($this->jobs_uri,array(""));
unset ($this->printers_attributes); unset ($this->printers_attributes);
if (!isset($this->setup->charset)) if (!isset($this->setup->charset))
self::setCharset('us-ascii'); {
self::setCharset();
}
if (!isset($this->setup->language)) if (!isset($this->setup->language))
{
self::setLanguage('en-us'); self::setLanguage('en-us');
}
self::_setOperationId(); self::_setOperationId();
$this->meta->attributes=''; $this->meta->attributes='';
if ($printer_location) if ($printer_location)
{
$this->meta->attributes .= chr(0x41) // textWithoutLanguage $this->meta->attributes .= chr(0x41) // textWithoutLanguage
. self::_giveMeStringLength('printer-location') . self::_giveMeStringLength('printer-location')
. 'printer-location' . 'printer-location'
. self::_giveMeStringLength($printer_location) . self::_giveMeStringLength($printer_location)
. $printer_location; . $printer_location;
}
if ($printer_info) if ($printer_info)
{
$this->meta->attributes .= chr(0x41) // textWithoutLanguage $this->meta->attributes .= chr(0x41) // textWithoutLanguage
. self::_giveMeStringLength('printer-info') . self::_giveMeStringLength('printer-info')
. 'printer-info' . 'printer-info'
. self::_giveMeStringLength($printer_info) . self::_giveMeStringLength($printer_info)
. $printer_info; . $printer_info;
}
for($i = 0 ; $i < count($attributes) ; $i++) for($i = 0 ; $i < count($attributes) ; $i++)
{
if ($i == 0) if ($i == 0)
{
$this->meta->attributes .= chr(0x44) // Keyword $this->meta->attributes .= chr(0x44) // Keyword
. self::_giveMeStringLength('requested-attributes') . self::_giveMeStringLength('requested-attributes')
. 'requested-attributes' . 'requested-attributes'
. self::_giveMeStringLength($attributes[0]) . self::_giveMeStringLength($attributes[0])
. $attributes[0]; . $attributes[0];
}
else else
{
$this->meta->attributes .= chr(0x44) // Keyword $this->meta->attributes .= chr(0x44) // Keyword
. chr(0x0).chr(0x0) // zero-length name . chr(0x0).chr(0x0) // zero-length name
. self::_giveMeStringLength($attributes[$i]) . self::_giveMeStringLength($attributes[$i])
. $attributes[$i]; . $attributes[$i];
}
}
$this->stringjob = chr(0x01) . chr(0x01) // IPP version 1.1 $this->stringjob = chr(0x01) . chr(0x01) // IPP version 1.1
. chr(0x40). chr(0x02) // operation: cups vendor extension: get printers . chr(0x40). chr(0x02) // operation: cups vendor extension: get printers
@ -338,51 +395,65 @@ class CupsPrintIPP extends ExtendedPrintIPP {
$post_values = array( "Content-Type" => "application/ipp", $post_values = array( "Content-Type" => "application/ipp",
"Data" => $this->output); "Data" => $this->output);
if (self::_sendHttp ($post_values,'/')) { if (self::_sendHttp ($post_values,'/'))
{
if(self::_parseServerOutput()) if(self::_parseServerOutput())
{
$this->_getAvailablePrinters(); $this->_getAvailablePrinters();
}
} }
if (isset($this->serveroutput) && isset($this->serveroutput->status)) { if (isset($this->serveroutput) && isset($this->serveroutput->status))
{
$this->status = array_merge($this->status,array($this->serveroutput->status)); $this->status = array_merge($this->status,array($this->serveroutput->status));
if ($this->serveroutput->status == "successfull-ok") if ($this->serveroutput->status == "successfull-ok")
{
self::_errorLog("getting printers: ".$this->serveroutput->status,3); self::_errorLog("getting printers: ".$this->serveroutput->status,3);
}
else else
{
self::_errorLog("getting printers: ".$this->serveroutput->status,1); self::_errorLog("getting printers: ".$this->serveroutput->status,1);
}
return $this->serveroutput->status; return $this->serveroutput->status;
}
} else { else
{
$this->status = array_merge($this->status,array("OPERATION FAILED")); $this->status = array_merge($this->status,array("OPERATION FAILED"));
self::_errorLog("getting printers : OPERATION FAILED",1); self::_errorLog("getting printers : OPERATION FAILED",1);
} }
return false; return false;
} }
// }}}
// {{{ cupsGetPrinters ()
public function cupsGetPrinters () { public function cupsGetPrinters ()
{
// alias for getPrinters(); // alias for getPrinters();
self::getPrinters(); self::getPrinters();
} }
// }}}
// {{{ getPrinterAttributes()
public function getPrinterAttributes() { public function getPrinterAttributes()
{
// complete informations from parent with Cups-specific stuff // complete informations from parent with Cups-specific stuff
if(!$result = parent::getPrinterAttributes()) if(!$result = parent::getPrinterAttributes())
{
return FALSE; return FALSE;
}
if(!isset($this->printer_attributes)) if(!isset($this->printer_attributes))
{
return FALSE; return FALSE;
}
if (isset ($this->printer_attributes->printer_type)) { if (isset ($this->printer_attributes->printer_type))
{
$printer_type = $this->printer_attributes->printer_type->_value0; $printer_type = $this->printer_attributes->printer_type->_value0;
$table = self::_interpretPrinterType($printer_type); $table = self::_interpretPrinterType($printer_type);
for($i = 0 ; $i < count($table) ; $i++ ) { for($i = 0 ; $i < count($table) ; $i++ )
{
$index = '_value'.$i; $index = '_value'.$i;
$this->printer_attributes->printer_type->$index = $table[$i]; $this->printer_attributes->printer_type->$index = $table[$i];
} }
@ -390,15 +461,12 @@ class CupsPrintIPP extends ExtendedPrintIPP {
return $result; return $result;
} }
// }}}
// //
// SETUP // SETUP
// //
protected function _initTags ()
// {{{ _initTags () {
protected function _initTags () {
// override parent with specific cups attributes // override parent with specific cups attributes
$operation_tags = array (); $operation_tags = array ();
@ -434,21 +502,19 @@ class CupsPrintIPP extends ExtendedPrintIPP {
); );
$this->job_tags = array_merge ($this->job_tags, $job_tags); $this->job_tags = array_merge ($this->job_tags, $job_tags);
} }
// }}}
//
// REQUEST BUILDING
//
// {{{ _enumBuild ($tag,$value)
protected function _enumBuild ($tag,$value) {
//
// REQUEST BUILDING
//
protected function _enumBuild ($tag,$value)
{
$value_built = parent::_enumBuild($tag,$value); $value_built = parent::_enumBuild($tag,$value);
switch ($tag)
switch ($tag) { {
case "cpi": case "cpi":
switch ($value) { switch ($value)
{
case '10': case '10':
$value_built = chr(10); $value_built = chr(10);
break; break;
@ -463,7 +529,8 @@ class CupsPrintIPP extends ExtendedPrintIPP {
} }
break; break;
case "lpi": case "lpi":
switch ($value) { switch ($value)
{
case '6': case '6':
$value_built = chr(6); $value_built = chr(6);
break; break;
@ -481,37 +548,40 @@ class CupsPrintIPP extends ExtendedPrintIPP {
$prepend .= chr(0); $prepend .= chr(0);
return $prepend.$value_built; return $prepend.$value_built;
} }
// }}}
//
// RESPONSE PARSING
//
// {{{ _getAvailablePrinters ()
private function _getAvailablePrinters () {
//
// RESPONSE PARSING
//
private function _getAvailablePrinters ()
{
$this->available_printers = array(); $this->available_printers = array();
$this->printer_map = array();
$k = 0; $k = 0;
$this->printers_attributes = new stdClass(); $this->printers_attributes = new \stdClass();
for ($i = 0 ; (array_key_exists($i,$this->serveroutput->response)) ; $i ++) for ($i = 0 ; (array_key_exists($i,$this->serveroutput->response)) ; $i ++)
if (($this->serveroutput->response[$i]['attributes']) == "printer-attributes") { {
if (($this->serveroutput->response[$i]['attributes']) == "printer-attributes")
{
$phpname = "_printer".$k; $phpname = "_printer".$k;
$this->printers_attributes->$phpname = new stdClass(); $this->printers_attributes->$phpname = new \stdClass();
for ($j = 0 ; array_key_exists($j,$this->serveroutput->response[$i]) ; $j++) { for ($j = 0 ; array_key_exists($j,$this->serveroutput->response[$i]) ; $j++)
{
$value = $this->serveroutput->response[$i][$j]['value']; $value = $this->serveroutput->response[$i][$j]['value'];
$name = str_replace("-","_",$this->serveroutput->response[$i][$j]['name']); $name = str_replace("-","_",$this->serveroutput->response[$i][$j]['name']);
switch ($name) { switch ($name)
{
case "printer_uri_supported": case "printer_uri_supported":
$this->available_printers = array_merge($this->available_printers,array($value)); $this->available_printers = array_merge($this->available_printers,array($value));
break; break;
case "printer_type": case "printer_type":
$table = self::_interpretPrinterType($value); $table = self::_interpretPrinterType($value);
$this->printers_attributes->$phpname->$name = new stdClass(); $this->printers_attributes->$phpname->$name = new \stdClass();
for($l = 0 ; $l < count($table) ; $l++ ) { for($l = 0 ; $l < count($table) ; $l++ )
{
$index = '_value'.$l; $index = '_value'.$l;
$this->printers_attributes->$phpname->$name->$index = $table[$l]; $this->printers_attributes->$phpname->$name->$index = $table[$l];
} }
@ -519,20 +589,23 @@ class CupsPrintIPP extends ExtendedPrintIPP {
break; break;
case '': case '':
break; break;
case 'printer_name':
$this->printer_map[$value] = $k;
break;
default: default:
$this->printers_attributes->$phpname->$name = $value; $this->printers_attributes->$phpname->$name = $value;
break; break;
} }
} }
$k ++; $k ++;
} }
} }
// }}} }
// {{{ _getEnumVendorExtensions protected function _getEnumVendorExtensions ($value_parsed)
protected function _getEnumVendorExtensions ($value_parsed) { {
switch ($value_parsed) { switch ($value_parsed)
{
case 0x4002: case 0x4002:
$value = 'Get-Availables-Printers'; $value = 'Get-Availables-Printers';
break; break;
@ -542,109 +615,151 @@ class CupsPrintIPP extends ExtendedPrintIPP {
} }
if (isset($value)) if (isset($value))
{
return ($value); return ($value);
}
return sprintf('Unknown: 0x%x',$value_parsed); return sprintf('Unknown: 0x%x',$value_parsed);
} }
// }}}
// {{{ _interpretPrinterType($type)
private function _interpretPrinterType($value) { private function _interpretPrinterType($value)
{
$value_parsed = 0; $value_parsed = 0;
for ($i = strlen($value) ; $i > 0 ; $i --) for ($i = strlen($value) ; $i > 0 ; $i --)
{
$value_parsed += pow(256,($i - 1)) * ord($value[strlen($value) - $i]); $value_parsed += pow(256,($i - 1)) * ord($value[strlen($value) - $i]);
}
$type[0] = $type[1] = $type[2] = $type[3] = $type[4] = $type[5] = ''; $type[0] = $type[1] = $type[2] = $type[3] = $type[4] = $type[5] = '';
$type[6] = $type[7] = $type[8] = $type[9] = $type[10] = ''; $type[6] = $type[7] = $type[8] = $type[9] = $type[10] = '';
$type[11] = $type[12] = $type[13] = $type[14] = $type[15] = ''; $type[11] = $type[12] = $type[13] = $type[14] = $type[15] = '';
$type[16] = $type[17] = $type[18] = $type[19] = ''; $type[16] = $type[17] = $type[18] = $type[19] = '';
if ($value_parsed %2 == 1) { if ($value_parsed %2 == 1)
{
$type[0] = 'printer-class'; $type[0] = 'printer-class';
$value_parsed -= 1; $value_parsed -= 1;
} }
if ($value_parsed %4 == 2 ) {
if ($value_parsed %4 == 2 )
{
$type[1] = 'remote-destination'; $type[1] = 'remote-destination';
$value_parsed -= 2; $value_parsed -= 2;
} }
if ($value_parsed %8 == 4 ) {
if ($value_parsed %8 == 4 )
{
$type[2] = 'print-black'; $type[2] = 'print-black';
$value_parsed -= 4; $value_parsed -= 4;
} }
if ($value_parsed %16 == 8 ) {
if ($value_parsed %16 == 8 )
{
$type[3] = 'print-color'; $type[3] = 'print-color';
$value_parsed -= 8; $value_parsed -= 8;
} }
if ($value_parsed %32 == 16) {
if ($value_parsed %32 == 16)
{
$type[4] = 'hardware-print-on-both-sides'; $type[4] = 'hardware-print-on-both-sides';
$value_parsed -= 16; $value_parsed -= 16;
} }
if ($value_parsed %64 == 32) {
if ($value_parsed %64 == 32)
{
$type[5] = 'hardware-staple-output'; $type[5] = 'hardware-staple-output';
$value_parsed -= 32; $value_parsed -= 32;
} }
if ($value_parsed %128 == 64) {
if ($value_parsed %128 == 64)
{
$type[6] = 'hardware-fast-copies'; $type[6] = 'hardware-fast-copies';
$value_parsed -= 64; $value_parsed -= 64;
} }
if ($value_parsed %256 == 128) {
if ($value_parsed %256 == 128)
{
$type[7] = 'hardware-fast-copy-collation'; $type[7] = 'hardware-fast-copy-collation';
$value_parsed -= 128; $value_parsed -= 128;
} }
if ($value_parsed %512 == 256) {
if ($value_parsed %512 == 256)
{
$type[8] = 'punch-output'; $type[8] = 'punch-output';
$value_parsed -= 256; $value_parsed -= 256;
} }
if ($value_parsed %1024 == 512) {
if ($value_parsed %1024 == 512)
{
$type[9] = 'cover-output'; $type[9] = 'cover-output';
$value_parsed -= 512; $value_parsed -= 512;
} }
if ($value_parsed %2048 == 1024) {
if ($value_parsed %2048 == 1024)
{
$type[10] = 'bind-output'; $type[10] = 'bind-output';
$value_parsed -= 1024; $value_parsed -= 1024;
} }
if ($value_parsed %4096 == 2048) {
if ($value_parsed %4096 == 2048)
{
$type[11] = 'sort-output'; $type[11] = 'sort-output';
$value_parsed -= 2048; $value_parsed -= 2048;
} }
if ($value_parsed %8192 == 4096) {
if ($value_parsed %8192 == 4096)
{
$type[12] = 'handle-media-up-to-US-Legal-A4'; $type[12] = 'handle-media-up-to-US-Legal-A4';
$value_parsed -= 4096; $value_parsed -= 4096;
} }
if ($value_parsed %16384 == 8192) {
if ($value_parsed %16384 == 8192)
{
$type[13] = 'handle-media-between-US-Legal-A4-and-ISO_C-A2'; $type[13] = 'handle-media-between-US-Legal-A4-and-ISO_C-A2';
$value_parsed -= 8192; $value_parsed -= 8192;
} }
if ($value_parsed %32768 == 16384) {
if ($value_parsed %32768 == 16384)
{
$type[14] = 'handle-media-larger-than-ISO_C-A2'; $type[14] = 'handle-media-larger-than-ISO_C-A2';
$value_parsed -= 16384; $value_parsed -= 16384;
} }
if ($value_parsed %65536 == 32768) {
if ($value_parsed %65536 == 32768)
{
$type[15] = 'handle-user-defined-media-sizes'; $type[15] = 'handle-user-defined-media-sizes';
$value_parsed -= 32768; $value_parsed -= 32768;
} }
if ($value_parsed %131072 == 65536) {
if ($value_parsed %131072 == 65536)
{
$type[16] = 'implicit-server-generated-class'; $type[16] = 'implicit-server-generated-class';
$value_parsed -= 65536; $value_parsed -= 65536;
} }
if ($value_parsed %262144 == 131072) {
if ($value_parsed %262144 == 131072)
{
$type[17] = 'network-default-printer'; $type[17] = 'network-default-printer';
$value_parsed -= 131072; $value_parsed -= 131072;
} }
if ($value_parsed %524288 == 262144) {
if ($value_parsed %524288 == 262144)
{
$type[18] = 'fax-device'; $type[18] = 'fax-device';
$value_parsed -= 262144; $value_parsed -= 262144;
} }
return $type; return $type;
} }
// }}}
// {{{ _interpretEnum()
protected function _interpretEnum($attribute_name,$value) {
protected function _interpretEnum($attribute_name,$value)
{
$value_parsed = self::_interpretInteger($value); $value_parsed = self::_interpretInteger($value);
switch ($attribute_name) { switch ($attribute_name)
{
case 'cpi': case 'cpi':
case 'lpi': case 'lpi':
$value = $value_parsed; $value = $value_parsed;
@ -654,18 +769,6 @@ class CupsPrintIPP extends ExtendedPrintIPP {
break; break;
} }
return $value; return $value;
} }
// }}} }
};
/*
* Local variables:
* mode: php
* tab-width: 4
* c-basic-offset: 4
* End:
*/
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,7 @@
*/ */
/** /**
* This class is intended to implement a subset of Hyper Text Transfer Protocol * This class is intended to implement a subset of Hyper Text Transfer Protocol
* (HTTP/1.1) on client side  (currently: POST operation), with file streaming * (HTTP/1.1) on client side (currently: POST operation), with file streaming
* capability. * capability.
* *
* It can perform Basic and Digest authentication. * It can perform Basic and Digest authentication.
@ -67,16 +67,19 @@
class httpException extends Exception class httpException extends Exception
{ {
protected $errno; protected $errno;
public function __construct ($msg, $errno = null) public function __construct ($msg, $errno = null)
{ {
parent::__construct ($msg); parent::__construct ($msg);
$this->errno = $errno; $this->errno = $errno;
} }
public function getErrorFormatted () public function getErrorFormatted ()
{ {
return sprintf ("[http_class]: %s -- "._(" file %s, line %s"), return sprintf ("[http_class]: %s -- "._(" file %s, line %s"),
$this->getMessage (), $this->getFile (), $this->getLine ()); $this->getMessage (), $this->getFile (), $this->getLine ());
} }
public function getErrno () public function getErrno ()
{ {
return $this->errno; return $this->errno;
@ -98,7 +101,9 @@ function error2string($value)
E_USER_WARNING => 'E_USER_WARNING', E_USER_WARNING => 'E_USER_WARNING',
E_USER_NOTICE => 'E_USER_NOTICE' E_USER_NOTICE => 'E_USER_NOTICE'
); );
if(defined('E_STRICT')) $level_names[E_STRICT]='E_STRICT'; if(defined('E_STRICT')) {
$level_names[E_STRICT]='E_STRICT';
}
$levels=array(); $levels=array();
if(($value&E_ALL)==E_ALL) if(($value&E_ALL)==E_ALL)
{ {
@ -106,7 +111,12 @@ function error2string($value)
$value&=~E_ALL; $value&=~E_ALL;
} }
foreach($level_names as $level=>$name) foreach($level_names as $level=>$name)
if(($value&$level)==$level) $levels[]=$name; {
if(($value&$level)==$level)
{
$levels[]=$name;
}
}
return implode(' | ',$levels); return implode(' | ',$levels);
} }
@ -160,14 +170,13 @@ class http_class
public function GetRequestArguments ($url, &$arguments) public function GetRequestArguments ($url, &$arguments)
{ {
$this->arguments = array (); $this->arguments = array ();
$arguments["URL"] = $this->arguments["URL"] = $url; $this->arguments["URL"] = $arguments["URL"] = $url;
$arguments["RequestMethod"] = $this->arguments["RequestMethod"] = "POST"; $this->arguments["RequestMethod"] = $arguments["RequestMethod"] = "POST";
$this->headers["Content-Length"] = 0; $this->headers["Content-Length"] = 0;
$this->headers["Content-Type"] = "application/octet-stream"; $this->headers["Content-Type"] = "application/octet-stream";
$this->headers["Host"] = $this->host; $this->headers["Host"] = $this->host;
$this->headers["User-Agent"] = $this->user_agent; $this->headers["User-Agent"] = $this->user_agent;
//$this->headers["Expect"] = "100-continue"; //$this->headers["Expect"] = "100-continue";
} }
public function Open ($arguments) public function Open ($arguments)
@ -214,9 +223,13 @@ class http_class
return $this->_HttpError ($error, E_USER_WARNING); return $this->_HttpError ($error, E_USER_WARNING);
} }
if (strstr ($url, ":")) // we got an ipv6 address if (strstr ($url, ":")) // we got an ipv6 address
{
if (!strstr ($url, "[")) // it is not escaped if (!strstr ($url, "[")) // it is not escaped
{
$url = sprintf ("[%s]", $url); $url = sprintf ("[%s]", $url);
} }
}
}
$this->connection = @fsockopen ($transport_type.$url, $port, $errno, $errstr, $this->timeout); $this->connection = @fsockopen ($transport_type.$url, $port, $errno, $errstr, $this->timeout);
$error = $error =
sprintf (_('Unable to connect to "%s%s port %s": %s'), $transport_type, sprintf (_('Unable to connect to "%s%s port %s": %s'), $transport_type,
@ -269,14 +282,11 @@ class http_class
$authtype[0]); $authtype[0]);
return $this->_HttpError ($error, E_USER_WARNING); return $this->_HttpError ($error, E_USER_WARNING);
break; break;
} }
self::Close (); self::Close ();
self::Open ($arguments); self::Open ($arguments);
$error =
sprintf (_ $error = sprintf(_('Streaming request failed to %s after a try to authenticate'), $arguments['RequestURI']);
('Streaming request failed to %s after a try to authenticate'),
$url);
$result = self::_StreamRequest ($arguments); $result = self::_StreamRequest ($arguments);
if (!$result[0]) if (!$result[0])
{ {
@ -300,7 +310,9 @@ class http_class
public function Close () public function Close ()
{ {
if (!$this->connected) if (!$this->connected)
{
return; return;
}
fclose ($this->connection); fclose ($this->connection);
} }
@ -313,7 +325,7 @@ class http_class
private function _HttpError ($msg, $level, $errno = null) private function _HttpError ($msg, $level, $errno = null)
{ {
$trace = ''; $trace = '';
$backtrace = debug_backtrace; $backtrace = debug_backtrace();
foreach ($backtrace as $trace) foreach ($backtrace as $trace)
{ {
$trace .= sprintf ("in [file: '%s'][function: '%s'][line: %s];\n", $trace['file'], $trace['function'],$trace['line']); $trace .= sprintf ("in [file: '%s'][function: '%s'][line: %s];\n", $trace['file'], $trace['function'],$trace['line']);
@ -348,7 +360,7 @@ class http_class
$this->reply_body = ""; $this->reply_body = "";
if (!$this->connected) if (!$this->connected)
{ {
return _HttpError (_("not connected"), E_USER_WARNING); return $this->_HttpError (_("not connected"), E_USER_WARNING);
} }
$this->arguments = $arguments; $this->arguments = $arguments;
$content_length = 0; $content_length = 0;
@ -369,39 +381,28 @@ class http_class
else else
{ {
$length = 0; $length = 0;
return return $this->_HttpError (sprintf (_("%s: file is not readable"), $value), E_USER_WARNING);
_HttpError (sprintf (_("%s: file is not readable"), $value),
E_USER_WARNING);
} }
} }
else else
{ {
$length = 0; $length = 0;
return return $this->_HttpError (sprintf(_("%s: not a valid argument for content"), $type), E_USER_WARNING);
_HttpError (sprintf
(_("%s: not a valid argument for content"), $type),
E_USER_WARNING);
} }
$content_length += $length; $content_length += $length;
} }
$this->request_body = sprintf (_("%s Bytes"), $content_length); $this->request_body = sprintf (_("%s Bytes"), $content_length);
$this->headers["Content-Length"] = $content_length; $this->headers["Content-Length"] = $content_length;
$this->arguments["Headers"] = $this->arguments["Headers"] = array_merge ($this->headers, $this->arguments["Headers"]);
array_merge ($this->headers, $this->arguments["Headers"]);
if ($this->arguments["RequestMethod"] != "POST") if ($this->arguments["RequestMethod"] != "POST")
{ {
return return $this->_HttpError (sprintf(_("%s: method not implemented"), $arguments["RequestMethod"]), E_USER_WARNING);
_HttpError (sprintf
(_("%s: method not implemented"),
$arguments["RequestMethod"]), E_USER_WARNING);
} }
$string = $string = sprintf ("POST %s HTTP/1.1\r\n", $this->arguments["RequestURI"]);
sprintf ("POST %s HTTP/1.1\r\n", $this->arguments["RequestURI"]);
$this->request_headers[$string] = ''; $this->request_headers[$string] = '';
if (!$this->_streamString ($string)) if (!$this->_streamString ($string))
{ {
return _HttpError (_("Error while puts POST operation"), return $this->_HttpError (_("Error while puts POST operation"), E_USER_WARNING);
E_USER_WARNING);
} }
foreach ($this->arguments["Headers"] as $header => $value) foreach ($this->arguments["Headers"] as $header => $value)
{ {
@ -409,15 +410,13 @@ class http_class
$this->request_headers[$header] = $value; $this->request_headers[$header] = $value;
if (!$this->_streamString ($string)) if (!$this->_streamString ($string))
{ {
return _HttpError (_("Error while puts HTTP headers"), return $this->_HttpError (_("Error while puts HTTP headers"), E_USER_WARNING);
E_USER_WARNING);
} }
} }
$string = "\r\n"; $string = "\r\n";
if (!$this->_streamString ($string)) if (!$this->_streamString ($string))
{ {
return _HttpError (_("Error while ends HTTP headers"), return $this->_HttpError (_("Error while ends HTTP headers"), E_USER_WARNING);
E_USER_WARNING);
} }
foreach ($this->arguments["BodyStream"] as $argument) foreach ($this->arguments["BodyStream"] as $argument)
{ {
@ -431,8 +430,7 @@ class http_class
$string = substr ($value, $streamed_length, $this->window_size); $string = substr ($value, $streamed_length, $this->window_size);
if (!$this->_streamString ($string)) if (!$this->_streamString ($string))
{ {
return _HttpError (_("error while sending body data"), return $this->_HttpError (_("error while sending body data"), E_USER_WARNING);
E_USER_WARNING);
} }
$streamed_length += $this->window_size; $streamed_length += $this->window_size;
} }
@ -444,16 +442,13 @@ class http_class
$file = fopen ($value, 'rb'); $file = fopen ($value, 'rb');
while (!feof ($file)) while (!feof ($file))
{ {
if (gettype ($block = @fread ($file, $this->window_size)) != if (gettype ($block = @fread ($file, $this->window_size)) != "string")
"string")
{ {
return _HttpError (_("cannot read file to upload"), return $this->_HttpError (_("cannot read file to upload"), E_USER_WARNING);
E_USER_WARNING);
} }
if (!$this->_streamString ($block)) if (!$this->_streamString ($block))
{ {
return _HttpError (_("error while sending body data"), return $this->_HttpError (_("error while sending body data"), E_USER_WARNING);
E_USER_WARNING);
} }
} }
} }
@ -476,7 +471,9 @@ class http_class
{ {
$line = fgets ($this->connection, 1024); $line = fgets ($this->connection, 1024);
if (strlen (trim($line)) == 0) if (strlen (trim($line)) == 0)
break; // \r\n => end of headers {
break;
} // \r\n => end of headers
if (preg_match ('#^[[:space:]]#', $line)) if (preg_match ('#^[[:space:]]#', $line))
{ {
$headers[-1] .= sprintf(' %s', trim ($line)); $headers[-1] .= sprintf(' %s', trim ($line));
@ -553,7 +550,7 @@ class http_class
break; break;
default: default:
return _HttpError( return $this->_HttpError(
sprintf (_("digest Authorization: algorithm '%s' not implemented"), sprintf (_("digest Authorization: algorithm '%s' not implemented"),
$algorithm), $algorithm),
E_USER_WARNING); E_USER_WARNING);
@ -568,7 +565,9 @@ class http_class
#$qop = split (" ", $qop); #$qop = split (" ", $qop);
$qop = preg_split ("# #", $qop); $qop = preg_split ("# #", $qop);
if (in_array ("auth", $qop)) if (in_array ("auth", $qop))
{
$qop = "auth"; $qop = "auth";
}
else else
{ {
self::_HttpError( self::_HttpError(
@ -591,25 +590,23 @@ class http_class
$username, $fields["realm"], $fields['nonce'], $username, $fields["realm"], $fields['nonce'],
$this->arguments["RequestURI"], $response); $this->arguments["RequestURI"], $response);
if (isset ($algorithm)) if (isset ($algorithm))
{
$auth_scheme .= sprintf (', algorithm="%s"', $algorithm); $auth_scheme .= sprintf (', algorithm="%s"', $algorithm);
}
if (isset ($qop)) if (isset ($qop))
{
$auth_scheme .= sprintf (', cnonce="%s"', $cnonce); $auth_scheme .= sprintf (', cnonce="%s"', $cnonce);
}
if (array_key_exists ("opaque", $fields)) if (array_key_exists ("opaque", $fields))
{
$auth_scheme .= sprintf (', opaque="%s"', $fields['opaque']); $auth_scheme .= sprintf (', opaque="%s"', $fields['opaque']);
}
if (isset ($qop)) if (isset ($qop))
{
$auth_scheme .= sprintf (', qop="%s"', $qop); $auth_scheme .= sprintf (', qop="%s"', $qop);
}
$auth_scheme .= sprintf (', nc=%s', $nc); $auth_scheme .= sprintf (', nc=%s', $nc);
$this->nc++; $this->nc++;
return $auth_scheme; return $auth_scheme;
} }
}
};
/*
* Local variables:
* mode: php
* tab-width: 2
* c-basic-offset: 2
* End:
*/
?>