From 16b8d2b5e9f44ad6537488e1666e5590a52e996b Mon Sep 17 00:00:00 2001 From: splitbrain <86426+splitbrain@users.noreply.github.com> Date: Mon, 2 Dec 2024 22:52:29 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=A4=96=20Automatic=20code=20style=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HTTP/DokuHTTPClient.php | 29 ++- HTTP/HTTPClient.php | 440 ++++++++++++++++++----------------- HTTP/HTTPClientException.php | 1 - HTTP/Headers.php | 4 +- admin.php | 2 +- cli.php | 6 +- helper.php | 39 ++-- legacy.php | 16 +- 8 files changed, 274 insertions(+), 263 deletions(-) diff --git a/HTTP/DokuHTTPClient.php b/HTTP/DokuHTTPClient.php index 534eb28..e908b68 100644 --- a/HTTP/DokuHTTPClient.php +++ b/HTTP/DokuHTTPClient.php @@ -1,23 +1,23 @@ */ -class DokuHTTPClient extends HTTPClient { - +class DokuHTTPClient extends HTTPClient +{ /** * Constructor. * * @author Andreas Gohr */ - public function __construct(){ + public function __construct() + { global $conf; // call parent constructor @@ -32,8 +32,8 @@ public function __construct(){ $this->proxy_except = $conf['proxy']['except']; // allow enabling debugging via URL parameter (if debugging allowed) - if($conf['allowdebug']) { - if( + if ($conf['allowdebug']) { + if ( isset($_REQUEST['httpdebug']) || ( isset($_SERVER['HTTP_REFERER']) && @@ -58,20 +58,17 @@ public function __construct(){ * @param string $method * @return bool */ - public function sendRequest($url,$data='',$method='GET'){ - $httpdata = array('url' => $url, - 'data' => $data, - 'method' => $method); - $evt = new \Doku_Event('HTTPCLIENT_REQUEST_SEND',$httpdata); - if($evt->advise_before()){ + public function sendRequest($url, $data = '', $method = 'GET') + { + $httpdata = ['url' => $url, 'data' => $data, 'method' => $method]; + $evt = new Event('HTTPCLIENT_REQUEST_SEND', $httpdata); + if ($evt->advise_before()) { $url = $httpdata['url']; $data = $httpdata['data']; $method = $httpdata['method']; } $evt->advise_after(); unset($evt); - return parent::sendRequest($url,$data,$method); + return parent::sendRequest($url, $data, $method); } - } - diff --git a/HTTP/HTTPClient.php b/HTTP/HTTPClient.php index 2b96978..3c9765c 100644 --- a/HTTP/HTTPClient.php +++ b/HTTP/HTTPClient.php @@ -2,7 +2,7 @@ namespace dokuwiki\plugin\upgrade\HTTP; -if(!defined('HTTP_NL')) define('HTTP_NL',"\r\n"); +if (!defined('HTTP_NL')) define('HTTP_NL', "\r\n"); /** @@ -17,28 +17,29 @@ * @author Andreas Gohr * @author Tobias Sarnowski */ -class HTTPClient { +class HTTPClient +{ //set these if you like public $agent; // User agent - public $http; // HTTP version defaults to 1.0 - public $timeout; // read timeout (seconds) - public $cookies; - public $referer; - public $max_redirect; - public $max_bodysize; + public $http = '1.0'; // HTTP version defaults to 1.0 + public $timeout = 15; // read timeout (seconds) + public $cookies = []; + public $referer = ''; + public $max_redirect = 3; + public $max_bodysize = 0; public $max_bodysize_abort = true; // if set, abort if the response body is bigger than max_bodysize - public $header_regexp; // if set this RE must match against the headers, else abort - public $headers; - public $debug; + public $header_regexp = ''; // if set this RE must match against the headers, else abort + public $headers = []; + public $debug = false; public $start = 0.0; // for timings public $keep_alive = true; // keep alive rocks // don't set these, read on error public $error; - public $redirect_count; + public $redirect_count = 0; // read these after a successful request - public $status; + public $status = 0; public $resp_body; public $resp_headers; @@ -55,7 +56,7 @@ class HTTPClient { public $proxy_except; // regexp of URLs to exclude from proxy // list of kept alive connections - protected static $connections = array(); + protected static $connections = []; // what we use as boundary on multipart/form-data posts protected $boundary = '---DokuWikiHTTPClient--4523452351'; @@ -65,21 +66,11 @@ class HTTPClient { * * @author Andreas Gohr */ - public function __construct(){ - $this->agent = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; '.PHP_OS.')'; - $this->timeout = 15; - $this->cookies = array(); - $this->referer = ''; - $this->max_redirect = 3; - $this->redirect_count = 0; - $this->status = 0; - $this->headers = array(); - $this->http = '1.0'; - $this->debug = false; - $this->max_bodysize = 0; - $this->header_regexp= ''; - if(extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip'; - $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,'. + public function __construct() + { + $this->agent = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; ' . PHP_OS . ')'; + if (extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip'; + $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,' . 'text/html,text/plain,image/png,image/jpeg,image/gif,*/*'; $this->headers['Accept-Language'] = 'en-us'; } @@ -96,10 +87,11 @@ public function __construct(){ * * @author Andreas Gohr */ - public function get($url,$sloppy304=false){ - if(!$this->sendRequest($url)) return false; - if($this->status == 304 && $sloppy304) return $this->resp_body; - if($this->status < 200 || $this->status > 206) return false; + public function get($url, $sloppy304 = false) + { + if (!$this->sendRequest($url)) return false; + if ($this->status == 304 && $sloppy304) return $this->resp_body; + if ($this->status < 200 || $this->status > 206) return false; return $this->resp_body; } @@ -118,14 +110,15 @@ public function get($url,$sloppy304=false){ * * @author Andreas Gohr */ - public function dget($url,$data,$sloppy304=false){ - if(strpos($url,'?')){ + public function dget($url, $data, $sloppy304 = false) + { + if (strpos($url, '?')) { $url .= '&'; - }else{ + } else { $url .= '?'; } $url .= $this->postEncode($data); - return $this->get($url,$sloppy304); + return $this->get($url, $sloppy304); } /** @@ -138,9 +131,10 @@ public function dget($url,$data,$sloppy304=false){ * @return false|string response body, false on error * @author Andreas Gohr */ - public function post($url,$data){ - if(!$this->sendRequest($url,$data,'POST')) return false; - if($this->status < 200 || $this->status > 206) return false; + public function post($url, $data) + { + if (!$this->sendRequest($url, $data, 'POST')) return false; + if ($this->status < 200 || $this->status > 206) return false; return $this->resp_body; } @@ -161,53 +155,56 @@ public function post($url,$data){ * @author Andreas Goetz * @author Andreas Gohr */ - public function sendRequest($url,$data='',$method='GET'){ - $this->start = $this->time(); + public function sendRequest($url, $data = '', $method = 'GET') + { + $this->start = static::time(); $this->error = ''; $this->status = 0; $this->resp_body = ''; - $this->resp_headers = array(); + $this->resp_headers = []; // save unencoded data for recursive call $unencodedData = $data; // don't accept gzip if truncated bodies might occur - if($this->max_bodysize && + if ( + $this->max_bodysize && !$this->max_bodysize_abort && isset($this->headers['Accept-encoding']) && - $this->headers['Accept-encoding'] == 'gzip'){ + $this->headers['Accept-encoding'] == 'gzip' + ) { unset($this->headers['Accept-encoding']); } // parse URL into bits $uri = parse_url($url); $server = $uri['host']; - $path = !empty($uri['path']) ? $uri['path'] : '/'; - $uriPort = !empty($uri['port']) ? $uri['port'] : null; - if(!empty($uri['query'])) $path .= '?'.$uri['query']; - if(isset($uri['user'])) $this->user = $uri['user']; - if(isset($uri['pass'])) $this->pass = $uri['pass']; + $path = empty($uri['path']) ? '/' : $uri['path']; + $uriPort = empty($uri['port']) ? null : $uri['port']; + if (!empty($uri['query'])) $path .= '?' . $uri['query']; + if (isset($uri['user'])) $this->user = $uri['user']; + if (isset($uri['pass'])) $this->pass = $uri['pass']; // proxy setup - if($this->useProxyForUrl($url)){ + if ($this->useProxyForUrl($url)) { $request_url = $url; $server = $this->proxy_host; $port = $this->proxy_port; if (empty($port)) $port = 8080; $use_tls = $this->proxy_ssl; - }else{ + } else { $request_url = $path; $port = $uriPort ?: ($uri['scheme'] == 'https' ? 443 : 80); $use_tls = ($uri['scheme'] == 'https'); } // add SSL stream prefix if needed - needs SSL support in PHP - if($use_tls) { - if(!in_array('ssl', stream_get_transports())) { + if ($use_tls) { + if (!in_array('ssl', stream_get_transports())) { $this->status = -200; $this->error = 'This PHP version does not support SSL - cannot connect to server'; } - $server = 'ssl://'.$server; + $server = 'ssl://' . $server; } // prepare headers @@ -217,8 +214,8 @@ public function sendRequest($url,$data='',$method='GET'){ $headers['User-Agent'] = $this->agent; $headers['Referer'] = $this->referer; - if($method == 'POST'){ - if(is_array($data)){ + if ($method == 'POST') { + if (is_array($data)) { if (empty($headers['Content-Type'])) { $headers['Content-Type'] = null; } @@ -232,24 +229,24 @@ public function sendRequest($url,$data='',$method='GET'){ $data = $this->postEncode($data); } } - }elseif($method == 'GET'){ + } elseif ($method == 'GET') { $data = ''; //no data allowed on GET requests } $contentlength = strlen($data); - if($contentlength) { + if ($contentlength) { $headers['Content-Length'] = $contentlength; } - if($this->user) { - $headers['Authorization'] = 'Basic '.base64_encode($this->user.':'.$this->pass); + if ($this->user) { + $headers['Authorization'] = 'Basic ' . base64_encode($this->user . ':' . $this->pass); } - if($this->proxy_user) { - $headers['Proxy-Authorization'] = 'Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass); + if ($this->proxy_user) { + $headers['Proxy-Authorization'] = 'Basic ' . base64_encode($this->proxy_user . ':' . $this->proxy_pass); } // already connected? - $connectionId = $this->uniqueConnectionId($server,$port); + $connectionId = $this->uniqueConnectionId($server, $port); $this->debug('connection pool', self::$connections); $socket = null; if (isset(self::$connections[$connectionId])) { @@ -259,8 +256,8 @@ public function sendRequest($url,$data='',$method='GET'){ if (is_null($socket) || feof($socket)) { $this->debug('opening connection', $connectionId); // open socket - $socket = @fsockopen($server,$port,$errno, $errstr, $this->timeout); - if (!$socket){ + $socket = @fsockopen($server, $port, $errno, $errstr, $this->timeout); + if (!$socket) { $this->status = -100; $this->error = "Could not connect to $server:$port\n$errstr ($errno)"; return false; @@ -268,11 +265,11 @@ public function sendRequest($url,$data='',$method='GET'){ // try establish a CONNECT tunnel for SSL try { - if($this->ssltunnel($socket, $request_url)){ + if ($this->ssltunnel($socket, $request_url)) { // no keep alive for tunnels $this->keep_alive = false; // tunnel is authed already - if(isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']); + if (isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']); } } catch (HTTPClientException $e) { $this->status = $e->getCode(); @@ -303,66 +300,65 @@ public function sendRequest($url,$data='',$method='GET'){ stream_set_blocking($socket, 0); // build request - $request = "$method $request_url HTTP/".$this->http.HTTP_NL; + $request = "$method $request_url HTTP/" . $this->http . HTTP_NL; $request .= $this->buildHeaders($headers); $request .= $this->getCookies(); $request .= HTTP_NL; $request .= $data; - $this->debug('request',$request); + $this->debug('request', $request); $this->sendData($socket, $request, 'request'); // read headers from socket $r_headers = ''; - do{ + do { $r_line = $this->readLine($socket, 'headers'); $r_headers .= $r_line; - }while($r_line != "\r\n" && $r_line != "\n"); + } while ($r_line != "\r\n" && $r_line != "\n"); - $this->debug('response headers',$r_headers); + $this->debug('response headers', $r_headers); // check if expected body size exceeds allowance - if($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i',$r_headers,$match)){ - if($match[1] > $this->max_bodysize){ + if ($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i', $r_headers, $match)) { + if ($match[1] > $this->max_bodysize) { if ($this->max_bodysize_abort) throw new HTTPClientException('Reported content length exceeds allowed response size'); - else - $this->error = 'Reported content length exceeds allowed response size'; + else $this->error = 'Reported content length exceeds allowed response size'; } } // get Status if (!preg_match('/^HTTP\/(\d\.\d)\s*(\d+).*?\n/s', $r_headers, $m)) - throw new HTTPClientException('Server returned bad answer '.$r_headers); + throw new HTTPClientException('Server returned bad answer ' . $r_headers); $this->status = $m[2]; // handle headers and cookies $this->resp_headers = $this->parseHeaders($r_headers); - if(isset($this->resp_headers['set-cookie'])){ - foreach ((array) $this->resp_headers['set-cookie'] as $cookie){ - list($cookie) = array_pad(explode(';', $cookie, 2), 2, ''); - list($key, $val) = array_pad(explode('=', $cookie, 2), 2, ''); + if (isset($this->resp_headers['set-cookie'])) { + foreach ((array) $this->resp_headers['set-cookie'] as $cookie) { + [$cookie] = array_pad(explode(';', $cookie, 2), 2, ''); + [$key, $val] = array_pad(explode('=', $cookie, 2), 2, ''); $key = trim($key); - if($val == 'deleted'){ - if(isset($this->cookies[$key])){ + if ($val == 'deleted') { + if (isset($this->cookies[$key])) { unset($this->cookies[$key]); } - }elseif($key){ + } elseif ($key) { $this->cookies[$key] = $val; } } } - $this->debug('Object headers',$this->resp_headers); + $this->debug('Object headers', $this->resp_headers); // check server status code to follow redirect - if(in_array($this->status, [301, 302, 303, 307, 308])){ - if (empty($this->resp_headers['location'])){ + if (in_array($this->status, [301, 302, 303, 307, 308])) { + if (empty($this->resp_headers['location'])) { throw new HTTPClientException('Redirect but no Location Header found'); - }elseif($this->redirect_count == $this->max_redirect){ + } elseif ($this->redirect_count == $this->max_redirect) { throw new HTTPClientException('Maximum number of redirects exceeded'); - }else{ + } else { // close the connection because we don't handle content retrieval here // that's the easiest way to clean up the connection fclose($socket); @@ -371,32 +367,32 @@ public function sendRequest($url,$data='',$method='GET'){ $this->redirect_count++; $this->referer = $url; // handle non-RFC-compliant relative redirects - if (!preg_match('/^http/i', $this->resp_headers['location'])){ - if($this->resp_headers['location'][0] != '/'){ - $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort. - dirname($path).'/'.$this->resp_headers['location']; - }else{ - $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort. + if (!preg_match('/^http/i', $this->resp_headers['location'])) { + if ($this->resp_headers['location'][0] != '/') { + $this->resp_headers['location'] = $uri['scheme'] . '://' . $uri['host'] . ':' . $uriPort . + dirname($path) . '/' . $this->resp_headers['location']; + } else { + $this->resp_headers['location'] = $uri['scheme'] . '://' . $uri['host'] . ':' . $uriPort . $this->resp_headers['location']; } } - if($this->status == 307 || $this->status == 308) { + if ($this->status == 307 || $this->status == 308) { // perform redirected request, same method as before (required by RFC) - return $this->sendRequest($this->resp_headers['location'],$unencodedData,$method); - }else{ + return $this->sendRequest($this->resp_headers['location'], $unencodedData, $method); + } else { // perform redirected request, always via GET (required by RFC) - return $this->sendRequest($this->resp_headers['location'],array(),'GET'); + return $this->sendRequest($this->resp_headers['location'], [], 'GET'); } } } // check if headers are as expected - if($this->header_regexp && !preg_match($this->header_regexp,$r_headers)) + if ($this->header_regexp && !preg_match($this->header_regexp, $r_headers)) throw new HTTPClientException('The received headers did not match the given regexp'); //read body (with chunked encoding if needed) $r_body = ''; - if( + if ( ( isset($this->resp_headers['transfer-encoding']) && $this->resp_headers['transfer-encoding'] == 'chunked' @@ -408,7 +404,7 @@ public function sendRequest($url,$data='',$method='GET'){ $abort = false; do { $chunk_size = ''; - while (preg_match('/^[a-zA-Z0-9]?$/',$byte=$this->readData($socket,1,'chunk'))){ + while (preg_match('/^[a-zA-Z0-9]?$/', $byte = $this->readData($socket, 1, 'chunk'))) { // read chunksize until \r $chunk_size .= $byte; if (strlen($chunk_size) > 128) // set an abritrary limit on the size of chunks @@ -417,7 +413,7 @@ public function sendRequest($url,$data='',$method='GET'){ $this->readLine($socket, 'chunk'); // readtrailing \n $chunk_size = hexdec($chunk_size); - if($this->max_bodysize && $chunk_size+strlen($r_body) > $this->max_bodysize){ + if ($this->max_bodysize && $chunk_size + strlen($r_body) > $this->max_bodysize) { if ($this->max_bodysize_abort) throw new HTTPClientException('Allowed response size exceeded'); $this->error = 'Allowed response size exceeded'; @@ -430,7 +426,7 @@ public function sendRequest($url,$data='',$method='GET'){ $this->readData($socket, 2, 'chunk'); // read trailing \r\n } } while ($chunk_size && !$abort); - }elseif(isset($this->resp_headers['content-length']) && !isset($this->resp_headers['transfer-encoding'])){ + } elseif (isset($this->resp_headers['content-length']) && !isset($this->resp_headers['transfer-encoding'])) { /* RFC 2616 * If a message is received with both a Transfer-Encoding header field and a Content-Length * header field, the latter MUST be ignored. @@ -438,22 +434,22 @@ public function sendRequest($url,$data='',$method='GET'){ // read up to the content-length or max_bodysize // for keep alive we need to read the whole message to clean up the socket for the next read - if( + if ( !$this->keep_alive && $this->max_bodysize && $this->max_bodysize < $this->resp_headers['content-length'] ) { $length = $this->max_bodysize + 1; - }else{ + } else { $length = $this->resp_headers['content-length']; } $r_body = $this->readData($socket, $length, 'response (content-length limited)', true); - }elseif( !isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive){ - $r_body = $this->readData($socket, $this->max_bodysize+1, 'response (content-length limited)', true); + } elseif (!isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive) { + $r_body = $this->readData($socket, $this->max_bodysize + 1, 'response (content-length limited)', true); } elseif ((int)$this->status === 204) { // request has no content - } else{ + } else { // read entire socket while (!feof($socket)) { $r_body .= $this->readData($socket, 4096, 'response (unlimited)', true); @@ -461,8 +457,8 @@ public function sendRequest($url,$data='',$method='GET'){ } // recheck body size, we might have read max_bodysize+1 or even the whole body, so we abort late here - if($this->max_bodysize){ - if(strlen($r_body) > $this->max_bodysize){ + if ($this->max_bodysize) { + if (strlen($r_body) > $this->max_bodysize) { if ($this->max_bodysize_abort) { throw new HTTPClientException('Allowed response size exceeded'); } else { @@ -470,7 +466,6 @@ public function sendRequest($url,$data='',$method='GET'){ } } } - } catch (HTTPClientException $err) { $this->error = $err->getMessage(); if ($err->getCode()) @@ -480,27 +475,31 @@ public function sendRequest($url,$data='',$method='GET'){ return false; } - if (!$this->keep_alive || - (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close')) { + if ( + !$this->keep_alive || + (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close') + ) { // close socket fclose($socket); unset(self::$connections[$connectionId]); } // decode gzip if needed - if(isset($this->resp_headers['content-encoding']) && + if ( + isset($this->resp_headers['content-encoding']) && $this->resp_headers['content-encoding'] == 'gzip' && - strlen($r_body) > 10 && substr($r_body,0,3)=="\x1f\x8b\x08"){ + strlen($r_body) > 10 && substr($r_body, 0, 3) == "\x1f\x8b\x08" + ) { $this->resp_body = @gzinflate(substr($r_body, 10)); - if($this->resp_body === false){ + if ($this->resp_body === false) { $this->error = 'Failed to decompress gzip encoded content'; $this->resp_body = $r_body; } - }else{ + } else { $this->resp_body = $r_body; } - $this->debug('response body',$this->resp_body); + $this->debug('response body', $this->resp_body); $this->redirect_count = 0; return true; } @@ -515,32 +514,33 @@ public function sendRequest($url,$data='',$method='GET'){ * @throws HTTPClientException when a tunnel is needed but could not be established * @return bool true if a tunnel was established */ - protected function ssltunnel(&$socket, &$requesturl){ - if(!$this->useProxyForUrl($requesturl)) return false; + protected function ssltunnel(&$socket, &$requesturl) + { + if (!$this->useProxyForUrl($requesturl)) return false; $requestinfo = parse_url($requesturl); - if($requestinfo['scheme'] != 'https') return false; - if(empty($requestinfo['port'])) $requestinfo['port'] = 443; + if ($requestinfo['scheme'] != 'https') return false; + if (empty($requestinfo['port'])) $requestinfo['port'] = 443; // build request - $request = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0".HTTP_NL; - $request .= "Host: {$requestinfo['host']}".HTTP_NL; - if($this->proxy_user) { - $request .= 'Proxy-Authorization: Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass).HTTP_NL; + $request = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0" . HTTP_NL; + $request .= "Host: {$requestinfo['host']}" . HTTP_NL; + if ($this->proxy_user) { + $request .= 'Proxy-Authorization: Basic ' . base64_encode($this->proxy_user . ':' . $this->proxy_pass) . HTTP_NL; } $request .= HTTP_NL; - $this->debug('SSL Tunnel CONNECT',$request); + $this->debug('SSL Tunnel CONNECT', $request); $this->sendData($socket, $request, 'SSL Tunnel CONNECT'); // read headers from socket $r_headers = ''; - do{ + do { $r_line = $this->readLine($socket, 'headers'); $r_headers .= $r_line; - }while($r_line != "\r\n" && $r_line != "\n"); + } while ($r_line != "\r\n" && $r_line != "\n"); - $this->debug('SSL Tunnel Response',$r_headers); - if(preg_match('/^HTTP\/1\.[01] 200/i',$r_headers)){ + $this->debug('SSL Tunnel Response', $r_headers); + if (preg_match('/^HTTP\/1\.[01] 200/i', $r_headers)) { // set correct peer name for verification (enabled since PHP 5.6) stream_context_set_option($socket, 'ssl', 'peer_name', $requestinfo['host']); @@ -554,13 +554,14 @@ protected function ssltunnel(&$socket, &$requesturl){ } if (@stream_socket_enable_crypto($socket, true, $cryptoMethod)) { - $requesturl = $requestinfo['path']. - (!empty($requestinfo['query'])?'?'.$requestinfo['query']:''); + $requesturl = $requestinfo['path'] . + (empty($requestinfo['query']) ? '' : '?' . $requestinfo['query']); return true; } throw new HTTPClientException( - 'Failed to set up crypto for secure connection to '.$requestinfo['host'], -151 + 'Failed to set up crypto for secure connection to ' . $requestinfo['host'], + -151 ); } @@ -577,31 +578,32 @@ protected function ssltunnel(&$socket, &$requesturl){ * * @author Tom N Harris */ - protected function sendData($socket, $data, $message) { + protected function sendData($socket, $data, $message) + { // send request $towrite = strlen($data); $written = 0; - while($written < $towrite){ + while ($written < $towrite) { // check timeout - $time_used = $this->time() - $this->start; - if($time_used > $this->timeout) - throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)',$message, $time_used), -100); - if(feof($socket)) + $time_used = static::time() - $this->start; + if ($time_used > $this->timeout) + throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)', $message, $time_used), -100); + if (feof($socket)) throw new HTTPClientException("Socket disconnected while writing $message"); // select parameters $sel_r = null; - $sel_w = array($socket); + $sel_w = [$socket]; $sel_e = null; // wait for stream ready or timeout (1sec) - if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){ + if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) { usleep(1000); continue; } // write to stream - $nbytes = fwrite($socket, substr($data,$written,4096)); - if($nbytes === false) + $nbytes = fwrite($socket, substr($data, $written, 4096)); + if ($nbytes === false) throw new HTTPClientException("Failed writing to socket while sending $message", -100); $written += $nbytes; } @@ -622,36 +624,43 @@ protected function sendData($socket, $data, $message) { * * @author Tom N Harris */ - protected function readData($socket, $nbytes, $message, $ignore_eof = false) { + protected function readData($socket, $nbytes, $message, $ignore_eof = false) + { $r_data = ''; // Does not return immediately so timeout and eof can be checked if ($nbytes < 0) $nbytes = 0; $to_read = $nbytes; do { - $time_used = $this->time() - $this->start; + $time_used = static::time() - $this->start; if ($time_used > $this->timeout) throw new HTTPClientException( - sprintf('Timeout while reading %s after %d bytes (%.3fs)', $message, - strlen($r_data), $time_used), -100); - if(feof($socket)) { - if(!$ignore_eof) + sprintf( + 'Timeout while reading %s after %d bytes (%.3fs)', + $message, + strlen($r_data), + $time_used + ), + -100 + ); + if (feof($socket)) { + if (!$ignore_eof) throw new HTTPClientException("Premature End of File (socket) while reading $message"); break; } if ($to_read > 0) { // select parameters - $sel_r = array($socket); + $sel_r = [$socket]; $sel_w = null; $sel_e = null; // wait for stream ready or timeout (1sec) - if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){ + if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) { usleep(1000); continue; } $bytes = fread($socket, $to_read); - if($bytes === false) + if ($bytes === false) throw new HTTPClientException("Failed reading from socket while reading $message", -100); $r_data .= $bytes; $to_read -= strlen($bytes); @@ -672,29 +681,31 @@ protected function readData($socket, $nbytes, $message, $ignore_eof = false) { * * @author Tom N Harris */ - protected function readLine($socket, $message) { + protected function readLine($socket, $message) + { $r_data = ''; do { - $time_used = $this->time() - $this->start; + $time_used = static::time() - $this->start; if ($time_used > $this->timeout) throw new HTTPClientException( sprintf('Timeout while reading %s (%.3fs) >%s<', $message, $time_used, $r_data), - -100); - if(feof($socket)) + -100 + ); + if (feof($socket)) throw new HTTPClientException("Premature End of File (socket) while reading $message"); // select parameters - $sel_r = array($socket); + $sel_r = [$socket]; $sel_w = null; $sel_e = null; // wait for stream ready or timeout (1sec) - if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){ + if (@stream_select($sel_r, $sel_w, $sel_e, 1) === false) { usleep(1000); continue; } $r_data = fgets($socket, 1024); - } while (!preg_match('/\n$/',$r_data)); + } while (!preg_match('/\n$/', $r_data)); return $r_data; } @@ -708,11 +719,12 @@ protected function readLine($socket, $message) { * @param string $info * @param mixed $var */ - protected function debug($info,$var=null){ - if(!$this->debug) return; - if(php_sapi_name() == 'cli'){ + protected function debug($info, $var = null) + { + if (!$this->debug) return; + if (PHP_SAPI == 'cli') { $this->debugText($info, $var); - }else{ + } else { $this->debugHtml($info, $var); } } @@ -723,14 +735,15 @@ protected function debug($info,$var=null){ * @param string $info * @param mixed $var */ - protected function debugHtml($info, $var=null){ - print ''.$info.' '.($this->time() - $this->start).'s
'; - if(!is_null($var)){ + protected function debugHtml($info, $var = null) + { + echo '' . $info . ' ' . (static::time() - $this->start) . 's
'; + if (!is_null($var)) { ob_start(); print_r($var); $content = htmlspecialchars(ob_get_contents()); ob_end_clean(); - print '
'.$content.'
'; + echo '
' . $content . '
'; } } @@ -740,10 +753,11 @@ protected function debugHtml($info, $var=null){ * @param string $info * @param mixed $var */ - protected function debugText($info, $var=null){ - print '*'.$info.'* '.($this->time() - $this->start)."s\n"; - if(!is_null($var)) print_r($var); - print "\n-----------------------------------------------\n"; + protected function debugText($info, $var = null) + { + echo '*' . $info . '* ' . (static::time() - $this->start) . "s\n"; + if (!is_null($var)) print_r($var); + echo "\n-----------------------------------------------\n"; } /** @@ -751,8 +765,9 @@ protected function debugText($info, $var=null){ * * @return float */ - protected static function time(){ - list($usec, $sec) = explode(" ", microtime()); + protected static function time() + { + [$usec, $sec] = explode(" ", microtime()); return ((float)$usec + (float)$sec); } @@ -766,23 +781,24 @@ protected static function time(){ * @param string $string * @return array */ - protected function parseHeaders($string){ - $headers = array(); - $lines = explode("\n",$string); + protected function parseHeaders($string) + { + $headers = []; + $lines = explode("\n", $string); array_shift($lines); //skip first line (status) - foreach($lines as $line){ - list($key, $val) = array_pad(explode(':', $line, 2), 2, ''); + foreach ($lines as $line) { + [$key, $val] = array_pad(explode(':', $line, 2), 2, ''); $key = trim($key); $val = trim($val); $key = strtolower($key); - if(!$key) continue; - if(isset($headers[$key])){ - if(is_array($headers[$key])){ + if (!$key) continue; + if (isset($headers[$key])) { + if (is_array($headers[$key])) { $headers[$key][] = $val; - }else{ - $headers[$key] = array($headers[$key],$val); + } else { + $headers[$key] = [$headers[$key], $val]; } - }else{ + } else { $headers[$key] = $val; } } @@ -797,11 +813,12 @@ protected function parseHeaders($string){ * @param array $headers * @return string */ - protected function buildHeaders($headers){ + protected function buildHeaders($headers) + { $string = ''; - foreach($headers as $key => $value){ - if($value === '') continue; - $string .= $key.': '.$value.HTTP_NL; + foreach ($headers as $key => $value) { + if ($value === '') continue; + $string .= $key . ': ' . $value . HTTP_NL; } return $string; } @@ -813,13 +830,14 @@ protected function buildHeaders($headers){ * * @return string */ - protected function getCookies(){ + protected function getCookies() + { $headers = ''; - foreach ($this->cookies as $key => $val){ + foreach ($this->cookies as $key => $val) { $headers .= "$key=$val; "; } $headers = substr($headers, 0, -2); - if ($headers) $headers = "Cookie: $headers".HTTP_NL; + if ($headers) $headers = "Cookie: $headers" . HTTP_NL; return $headers; } @@ -831,8 +849,9 @@ protected function getCookies(){ * @param array $data * @return string */ - protected function postEncode($data){ - return http_build_query($data,'','&'); + protected function postEncode($data) + { + return http_build_query($data, '', '&'); } /** @@ -844,27 +863,28 @@ protected function postEncode($data){ * @param array $data * @return string */ - protected function postMultipartEncode($data){ - $boundary = '--'.$this->boundary; + protected function postMultipartEncode($data) + { + $boundary = '--' . $this->boundary; $out = ''; - foreach($data as $key => $val){ - $out .= $boundary.HTTP_NL; - if(!is_array($val)){ - $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'.HTTP_NL; + foreach ($data as $key => $val) { + $out .= $boundary . HTTP_NL; + if (!is_array($val)) { + $out .= 'Content-Disposition: form-data; name="' . urlencode($key) . '"' . HTTP_NL; $out .= HTTP_NL; // end of headers $out .= $val; $out .= HTTP_NL; - }else{ - $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'; - if($val['filename']) $out .= '; filename="'.urlencode($val['filename']).'"'; + } else { + $out .= 'Content-Disposition: form-data; name="' . urlencode($key) . '"'; + if ($val['filename']) $out .= '; filename="' . urlencode($val['filename']) . '"'; $out .= HTTP_NL; - if($val['mimetype']) $out .= 'Content-Type: '.$val['mimetype'].HTTP_NL; + if ($val['mimetype']) $out .= 'Content-Type: ' . $val['mimetype'] . HTTP_NL; $out .= HTTP_NL; // end of headers $out .= $val['body']; $out .= HTTP_NL; } } - $out .= "$boundary--".HTTP_NL; + $out .= "$boundary--" . HTTP_NL; return $out; } @@ -875,7 +895,8 @@ protected function postMultipartEncode($data){ * @param string $port * @return string unique identifier */ - protected function uniqueConnectionId($server, $port) { + protected function uniqueConnectionId($server, $port) + { return "$server:$port"; } @@ -887,7 +908,8 @@ protected function uniqueConnectionId($server, $port) { * @param string $url * @return bool */ - protected function useProxyForUrl($url) { + protected function useProxyForUrl($url) + { return $this->proxy_host && (!$this->proxy_except || !preg_match('/' . $this->proxy_except . '/i', $url)); } } diff --git a/HTTP/HTTPClientException.php b/HTTP/HTTPClientException.php index 7324934..86a8108 100644 --- a/HTTP/HTTPClientException.php +++ b/HTTP/HTTPClientException.php @@ -6,5 +6,4 @@ class HTTPClientException extends Exception { - } diff --git a/HTTP/Headers.php b/HTTP/Headers.php index 8d1419f..0472b18 100644 --- a/HTTP/Headers.php +++ b/HTTP/Headers.php @@ -14,7 +14,7 @@ class Headers * * @param array $policy */ - static public function contentSecurityPolicy($policy) + public static function contentSecurityPolicy($policy) { foreach ($policy as $key => $values) { // if the value is not an array, we also accept newline terminated strings @@ -28,7 +28,7 @@ static public function contentSecurityPolicy($policy) $cspheader = 'Content-Security-Policy:'; foreach ($policy as $key => $values) { if ($values) { - $cspheader .= " $key " . join(' ', $values) . ';'; + $cspheader .= " $key " . implode(' ', $values) . ';'; } else { $cspheader .= " $key;"; } diff --git a/admin.php b/admin.php index 72089d5..bde7931 100644 --- a/admin.php +++ b/admin.php @@ -9,7 +9,7 @@ require_once __DIR__ . '/vendor/autoload.php'; -class admin_plugin_upgrade extends DokuWiki_Admin_Plugin +class admin_plugin_upgrade extends \dokuwiki\Extension\AdminPlugin { protected $haderrors = false; diff --git a/cli.php b/cli.php index 15b406f..5d3bc6f 100644 --- a/cli.php +++ b/cli.php @@ -1,7 +1,7 @@ */ -class cli_plugin_upgrade extends DokuWiki_CLI_Plugin +class cli_plugin_upgrade extends CLIPlugin { protected $logdefault = 'notice'; protected $helper; @@ -64,7 +64,7 @@ protected function main(Options $options) } /** @inheritDoc */ - public function log($level, $message, array $context = array()) + public function log($level, $message, array $context = []) { // Log messages are HTML formatted, we need to clean them for console $message = strip_tags($message); diff --git a/helper.php b/helper.php index f01cf3c..bd90927 100644 --- a/helper.php +++ b/helper.php @@ -7,11 +7,12 @@ * @author Andreas Gohr */ +use dokuwiki\Extension\Plugin; use dokuwiki\plugin\upgrade\HTTP\DokuHTTPClient; use splitbrain\PHPArchive\FileInfo; use splitbrain\PHPArchive\Tar; -class helper_plugin_upgrade extends DokuWiki_Plugin +class helper_plugin_upgrade extends Plugin { /** @var string download URL for the new DokuWiki release */ public $tgzurl; @@ -24,7 +25,7 @@ class helper_plugin_upgrade extends DokuWiki_Plugin /** @var string URL to the composer.json file of the new DokuWiki release */ protected $composer; /** @var string URL to the plugin.info.txt file of the upgrade plugin */ - public $pluginversion; + public $pluginversion = "https://raw.githubusercontent.com/splitbrain/dokuwiki-plugin-upgrade/master/plugin.info.txt"; /** @var admin_plugin_upgrade|cli_plugin_upgrade */ protected $logger; @@ -40,7 +41,6 @@ public function __construct() $this->tgzdir = $conf['tmpdir'] . '/dokuwiki-upgrade/'; $this->tgzversion = "https://raw.githubusercontent.com/splitbrain/dokuwiki/$branch/VERSION"; $this->composer = "https://raw.githubusercontent.com/splitbrain/dokuwiki/$branch/composer.json"; - $this->pluginversion = "https://raw.githubusercontent.com/splitbrain/dokuwiki-plugin-upgrade/master/plugin.info.txt"; } /** @@ -341,25 +341,23 @@ private function traverseCheckAndCopy($dir, $dryrun) } else { $this->log('info', $this->getLang('tv_upd'), hsc("$dir/$file")); } - } else { + } elseif (io_mkdir_p(dirname($to))) { // check dir - if (io_mkdir_p(dirname($to))) { - // remove existing (avoid case sensitivity problems) - if (file_exists($to) && !@unlink($to)) { - $this->log('error', '' . $this->getLang('tv_nodel') . '', hsc("$dir/$file")); - $ok = false; - } - // copy - if (!copy($from, $to)) { - $this->log('error', '' . $this->getLang('tv_nocopy') . '', hsc("$dir/$file")); - $ok = false; - } else { - $this->log('info', $this->getLang('tv_done'), hsc("$dir/$file")); - } - } else { - $this->log('error', '' . $this->getLang('tv_nodir') . '', hsc("$dir")); + // remove existing (avoid case sensitivity problems) + if (file_exists($to) && !@unlink($to)) { + $this->log('error', '' . $this->getLang('tv_nodel') . '', hsc("$dir/$file")); + $ok = false; + } + // copy + if (!copy($from, $to)) { + $this->log('error', '' . $this->getLang('tv_nocopy') . '', hsc("$dir/$file")); $ok = false; + } else { + $this->log('info', $this->getLang('tv_done'), hsc("$dir/$file")); } + } else { + $this->log('error', '' . $this->getLang('tv_nodir') . '', hsc("$dir")); + $ok = false; } } } @@ -411,9 +409,8 @@ protected function recursiveDelete($dir) * * @param string ...$level , $msg */ - protected function log() + protected function log(...$args) { - $args = func_get_args(); $level = array_shift($args); $msg = array_shift($args); $msg = vsprintf($msg, $args); diff --git a/legacy.php b/legacy.php index e766bd1..dd6159b 100644 --- a/legacy.php +++ b/legacy.php @@ -1,5 +1,7 @@ array_map('trim', explode(' ', $item, 2)), $lines); return array_combine(array_column($lines, 0), array_column($lines, 1)); } @@ -63,7 +63,7 @@ function io_mkdir_p($dir) function getVersionData() { - $version = array(); + $version = []; if (file_exists(DOKU_INC . 'VERSION')) { //official release $version['date'] = trim(file_get_contents(DOKU_INC . 'VERSION')); @@ -80,10 +80,6 @@ function getVersion() class Doku_Event { - public function __construct($name, &$data) - { - } - public function advise_before() { return true; @@ -96,7 +92,7 @@ public function advise_after() trait UpgradePluginTrait { - protected $lang = null; + protected $lang; /** * @return string @@ -122,7 +118,7 @@ public function getLang($key) } } -abstract class DokuWiki_CLI_Plugin extends splitbrain\phpcli\CLI +abstract class DokuWiki_CLI_Plugin extends CLI { use UpgradePluginTrait; }