From 73f290e89671ead813b474298dc0b8e763cb9b4b Mon Sep 17 00:00:00 2001 From: Nikita Tarasov Date: Sun, 20 May 2018 22:17:29 +0300 Subject: [PATCH] php lint + code standard PSR-2 --- .gitignore | 3 + .php_cs | 37 ++++ .travis.yml | 13 ++ composer.json | 10 ++ grumphp.yml | 9 + includes/class/ApiHandler.php | 59 ++++--- includes/class/PdnsApi.php | 48 +++--- includes/class/Zone.php | 191 ++++++++++++--------- includes/misc.inc.php | 213 +++++++++++++---------- includes/session.inc.php | 102 ++++++----- includes/wefactauth.inc.php | 63 +++---- index.php | 168 +++++++++++------- logs.php | 58 ++++--- users.php | 34 ++-- zones.php | 315 ++++++++++++++++++++-------------- 15 files changed, 794 insertions(+), 529 deletions(-) create mode 100644 .php_cs create mode 100644 .travis.yml create mode 100644 composer.json create mode 100644 grumphp.yml diff --git a/.gitignore b/.gitignore index 62b9b11..c92ff54 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ includes/config.inc.php nsedit.sublime* etc +composer.lock +vendor +.php_cs.cache diff --git a/.php_cs b/.php_cs new file mode 100644 index 0000000..54454a1 --- /dev/null +++ b/.php_cs @@ -0,0 +1,37 @@ +in('.') + ->exclude('jquery-ui'); + +return PhpCsFixer\Config::create() + ->setFinder($finder) + ->setRules([ + '@PSR2' => true, + 'array_syntax' => ['syntax' => 'short'], + 'concat_space' => ['spacing' => 'one'], + 'include' => true, + 'new_with_braces' => true, + 'no_empty_statement' => true, + 'no_extra_consecutive_blank_lines' => true, + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_multiline_whitespace_before_semicolons' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_unused_imports' => true, + 'no_whitespace_in_blank_line' => true, + 'object_operator_without_whitespace' => true, + 'ordered_imports' => true, + 'standardize_not_equals' => true, + 'ternary_operator_spaces' => true, + 'phpdoc_order' => true, + 'phpdoc_types' => true, + 'phpdoc_add_missing_param_annotation' => true, + 'single_quote' => true, + 'standardize_not_equals' => true, + 'ternary_operator_spaces' => true, + 'lowercase_cast' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + ]); diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..6ff6532 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,13 @@ +language: php +php: +- 5.6 +- 7.0 +- 7.1 +- 7.2 +before_script: +- composer self-update +- phpenv config-rm xdebug.ini +- composer install --no-interaction --prefer-dist + +script: +- php vendor/bin/grumphp run diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..8d06db1 --- /dev/null +++ b/composer.json @@ -0,0 +1,10 @@ +{ + "name":"tuxis-ie/nsedit", + "license": "GPL-2.0-only", + "description": "DNS Editor working with PowerDNS's new API", + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.11", + "phpro/grumphp": "^0.14.0", + "jakub-onderka/php-parallel-lint": "^1.0" + } +} diff --git a/grumphp.yml b/grumphp.yml new file mode 100644 index 0000000..0e3eb29 --- /dev/null +++ b/grumphp.yml @@ -0,0 +1,9 @@ +parameters: + git_dir: . + bin_dir: vendor/bin + tasks: + composer: + no_check_lock: true + phplint: + phpcsfixer2: + config: '.php_cs' diff --git a/includes/class/ApiHandler.php b/includes/class/ApiHandler.php index 07b6cdf..ad443a9 100644 --- a/includes/class/ApiHandler.php +++ b/includes/class/ApiHandler.php @@ -1,12 +1,14 @@ headers = Array(); + $this->headers = []; $this->hostname = $apiip; $this->port = $apiport; $this->auth = $apipass; @@ -14,61 +16,66 @@ public function __construct() { $this->sslverify = $apisslverify; $this->curlh = curl_init(); $this->method = 'GET'; - $this->content = FALSE; + $this->content = false; $this->apiurl = ''; } - public function addheader($field, $content) { + public function addheader($field, $content) + { $this->headers[$field] = $content; } - private function authheaders() { + private function authheaders() + { $this->addheader('X-API-Key', $this->auth); } - private function apiurl() { + private function apiurl() + { $tmp = new ApiHandler(); $tmp->url = '/api'; $tmp->go(); - + if ($tmp->json[0]['version'] <= 1) { $this->apiurl = $tmp->json[0]['url']; } else { - throw new Exception("Unsupported API version"); + throw new Exception('Unsupported API version'); } - } - private function curlopts() { + private function curlopts() + { $this->authheaders(); $this->addheader('Accept', 'application/json'); - if(defined('curl_reset')) { + if (defined('curl_reset')) { curl_reset($this->curlh); } else { $this->curlh = curl_init(); } - curl_setopt($this->curlh, CURLOPT_HTTPHEADER, Array()); + curl_setopt($this->curlh, CURLOPT_HTTPHEADER, []); curl_setopt($this->curlh, CURLOPT_RETURNTRANSFER, 1); if (strcasecmp($this->proto, 'https')) { curl_setopt($this->curlh, CURLOPT_SSL_VERIFYPEER, $this->sslverify); } - $setheaders = Array(); + $setheaders = []; foreach ($this->headers as $k => $v) { - array_push($setheaders, join(": ", Array($k, $v))); + array_push($setheaders, join(': ', [$k, $v])); } curl_setopt($this->curlh, CURLOPT_HTTPHEADER, $setheaders); } - private function baseurl() { - return $this->proto.'://'.$this->hostname.':'.$this->port.$this->apiurl; + private function baseurl() + { + return $this->proto . '://' . $this->hostname . ':' . $this->port . $this->apiurl; } - private function go() { + private function go() + { $this->curlopts(); if ($this->content) { @@ -91,31 +98,31 @@ private function go() { break; } - curl_setopt($this->curlh, CURLOPT_URL, $this->baseurl().$this->url); + curl_setopt($this->curlh, CURLOPT_URL, $this->baseurl() . $this->url); $return = curl_exec($this->curlh); $code = curl_getinfo($this->curlh, CURLINFO_HTTP_CODE); $json = json_decode($return, 1); if (isset($json['error'])) { - throw new Exception("API Error $code: ".$json['error']); + throw new Exception("API Error $code: " . $json['error']); } elseif ($code < 200 || $code >= 300) { if ($code == 401) { - throw new Exception("Authentication failed. Have you configured your authmethod correct?"); + throw new Exception('Authentication failed. Have you configured your authmethod correct?'); } - throw new Exception("Curl Error: $code ".curl_error($this->curlh)); + throw new Exception("Curl Error: $code " . curl_error($this->curlh)); } $this->json = $json; } - public function call() { + public function call() + { if (substr($this->url, 0, 1) != '/') { - $this->url = '/'.$this->url; + $this->url = '/' . $this->url; } $this->apiurl(); $this->url = str_replace($this->apiurl, '', $this->url); $this->go(); } } - diff --git a/includes/class/PdnsApi.php b/includes/class/PdnsApi.php index 25a1581..0dcdbd0 100644 --- a/includes/class/PdnsApi.php +++ b/includes/class/PdnsApi.php @@ -1,20 +1,23 @@ http = new ApiHandler(); } - public function listzones($q = FALSE) { + public function listzones($q = false) + { $api = clone $this->http; $api->method = 'GET'; if ($q) { - $api->url = "/servers/localhost/search-data?q=*".$q."*&max=25"; + $api->url = '/servers/localhost/search-data?q=*' . $q . '*&max=25'; $api->call(); - $ret = Array(); - $seen = Array(); + $ret = []; + $seen = []; foreach ($api->json as $result) { if (isset($seen[$result['zone_id']])) { @@ -28,13 +31,14 @@ public function listzones($q = FALSE) { return $ret; } - $api->url = "/servers/localhost/zones"; + $api->url = '/servers/localhost/zones'; $api->call(); return $api->json; } - public function loadzone($zoneid) { + public function loadzone($zoneid) + { $api = clone $this->http; $api->method = 'GET'; $api->url = "/servers/localhost/zones/$zoneid"; @@ -43,7 +47,8 @@ public function loadzone($zoneid) { return $api->json; } - public function exportzone($zoneid) { + public function exportzone($zoneid) + { $api = clone $this->http; $api->method = 'GET'; $api->url = "/servers/localhost/zones/$zoneid/export"; @@ -52,7 +57,8 @@ public function exportzone($zoneid) { return $api->json; } - public function savezone($zone) { + public function savezone($zone) + { $api = clone $this->http; // We have to split up RRSets and Zoneinfo. // First, update the zone @@ -78,14 +84,15 @@ public function savezone($zone) { // Then, update the rrsets if (count($zone['rrsets']) > 0) { $api->method = 'PATCH'; - $api->content = json_encode(Array('rrsets' => $zone['rrsets'])); + $api->content = json_encode(['rrsets' => $zone['rrsets']]); $api->call(); } return $this->loadzone($zone['id']); } - public function deletezone($zoneid) { + public function deletezone($zoneid) + { $api = clone $this->http; $api->method = 'DELETE'; $api->url = "/servers/localhost/zones/$zoneid"; @@ -94,8 +101,9 @@ public function deletezone($zoneid) { return $api->json; } - public function getzonekeys($zoneid) { - $ret = array(); + public function getzonekeys($zoneid) + { + $ret = []; $api = clone $this->http; $api->method = 'GET'; $api->url = "/servers/localhost/zones/$zoneid/cryptokeys"; @@ -103,14 +111,15 @@ public function getzonekeys($zoneid) { $api->call(); foreach ($api->json as $key) { - if (!isset($key['active'])) + if (!isset($key['active'])) { continue; + } - $key['dstxt'] = $zoneid . ' IN DNSKEY '.$key['dnskey']."\n\n"; + $key['dstxt'] = $zoneid . ' IN DNSKEY ' . $key['dnskey'] . "\n\n"; if (isset($key['ds'])) { foreach ($key['ds'] as $ds) { - $key['dstxt'] .= $zoneid . ' IN DS '.$ds."\n"; + $key['dstxt'] .= $zoneid . ' IN DS ' . $ds . "\n"; } unset($key['ds']); } @@ -119,7 +128,4 @@ public function getzonekeys($zoneid) { return $ret; } - } - -?> diff --git a/includes/class/Zone.php b/includes/class/Zone.php index a429550..8df785c 100644 --- a/includes/class/Zone.php +++ b/includes/class/Zone.php @@ -1,7 +1,9 @@ id = ''; $this->name = ''; $this->kind = ''; @@ -12,13 +14,14 @@ public function __construct() { $this->soa_edit_api = ''; $this->keyinfo = ''; $this->account = ''; - $this->zone = FALSE; - $this->nameservers = Array(); - $this->rrsets = Array(); - $this->masters = Array(); + $this->zone = false; + $this->nameservers = []; + $this->rrsets = []; + $this->masters = []; } - public function parse($data) { + public function parse($data) + { $this->setId($data['id']); $this->setName($data['name']); $this->setKind($data['kind']); @@ -26,10 +29,12 @@ public function parse($data) { $this->setAccount($data['account']); $this->setSerial($data['serial']); $this->url = $data['url']; - if (isset($data['soa_edit']) && $data['soa_edit'] != "") + if (isset($data['soa_edit']) && $data['soa_edit'] != '') { $this->setSoaEdit($data['soa_edit']); - if (isset($data['soa_edit_api']) && $data['soa_edit_api'] != "") - $this->setSoaEditApi($data['soa_edit_api'], True); + } + if (isset($data['soa_edit_api']) && $data['soa_edit_api'] != '') { + $this->setSoaEditApi($data['soa_edit_api'], true); + } foreach ($data['masters'] as $master) { $this->addMaster($master); @@ -50,82 +55,96 @@ public function parse($data) { } } - public function importData($data) { + public function importData($data) + { $this->zone = $data; } - public function setKeyinfo($info) { + public function setKeyinfo($info) + { $this->keyinfo = $info; } - public function addNameserver($nameserver) { + public function addNameserver($nameserver) + { foreach ($this->nameservers as $ns) { if ($nameserver == $ns) { - throw new Exception("We already have this as a nameserver"); + throw new Exception('We already have this as a nameserver'); } } array_push($this->nameservers, $nameserver); - } - public function setSerial($serial) { + public function setSerial($serial) + { $this->serial = $serial; } - public function setSoaEdit($soaedit) { + public function setSoaEdit($soaedit) + { $this->soa_edit = $soaedit; } - public function setSoaEditApi($soaeditapi, $overwrite=False) { - if (isset($this->soa_edit_api) and $this->soa_edit_api != "") { - if ($overwrite === False) { - return False; + public function setSoaEditApi($soaeditapi, $overwrite=false) + { + if (isset($this->soa_edit_api) and $this->soa_edit_api != '') { + if ($overwrite === false) { + return false; } } $this->soa_edit_api = $soaeditapi; } - public function setName($name) { + public function setName($name) + { $this->name = $name; } - public function setKind($kind) { + public function setKind($kind) + { $this->kind = $kind; } - public function setAccount($account) { + public function setAccount($account) + { $this->account = $account; } - public function setDnssec($dnssec) { + public function setDnssec($dnssec) + { $this->dnssec = $dnssec; } - public function setId($id) { + public function setId($id) + { $this->id = $id; } - public function addMaster($ip) { + public function addMaster($ip) + { foreach ($this->masters as $master) { if ($ip == $master) { - throw new Exception("We already have this as a master"); + throw new Exception('We already have this as a master'); } } array_push($this->masters, $ip); } - public function eraseMasters() { - $this->masters = Array(); + public function eraseMasters() + { + $this->masters = []; } - public function addRRSet($name, $type, $content, $disabled = FALSE, $ttl = 3600, $setptr = FALSE) { - if ($this->getRRSet($name, $type) !== FALSE) { - throw new Exception("This rrset already exists."); + public function addRRSet($name, $type, $content, $disabled = false, $ttl = 3600, $setptr = false) + { + if ($this->getRRSet($name, $type) !== false) { + throw new Exception('This rrset already exists.'); } $rrset = new RRSet($name, $type, $content, $disabled, $ttl, $setptr); array_push($this->rrsets, $rrset); } - public function addRecord($name, $type, $content, $disabled = FALSE, $ttl = 3600, $setptr = FALSE) { + public function addRecord($name, $type, $content, $disabled = false, $ttl = 3600, $setptr = false) + { $rrset = $this->getRRSet($name, $type); if ($rrset) { @@ -138,7 +157,8 @@ public function addRecord($name, $type, $content, $disabled = FALSE, $ttl = 3600 return $this->getRecord($name, $type, $content); } - public function getRecord($name, $type, $content) { + public function getRecord($name, $type, $content) + { $rrset = $this->getRRSet($name, $type); foreach ($rrset->exportRecords() as $record) { if ($record['content'] == $content) { @@ -150,21 +170,22 @@ public function getRecord($name, $type, $content) { return $record; } } - } - public function getRRSet($name, $type) { + public function getRRSet($name, $type) + { foreach ($this->rrsets as $rrset) { if ($rrset->name == $name and $rrset->type == $type) { return $rrset; } } - return FALSE; + return false; } - public function rrsets2records() { - $ret = Array(); + public function rrsets2records() + { + $ret = []; foreach ($this->rrsets as $rrset) { foreach ($rrset->exportRecords() as $record) { @@ -180,16 +201,17 @@ public function rrsets2records() { return $ret; } - public function export() { - $ret = Array(); + public function export() + { + $ret = []; $ret['account'] = $this->account; $ret['nameservers'] = $this->nameservers; $ret['kind'] = $this->kind; $ret['name'] = $this->name; - if (isset($this->soa_edit) && $this->soa_edit != "") { + if (isset($this->soa_edit) && $this->soa_edit != '') { $ret['soa_edit'] = $this->soa_edit; } - if (isset($this->soa_edit_api) && $this->soa_edit_api != "") { + if (isset($this->soa_edit_api) && $this->soa_edit_api != '') { $ret['soa_edit_api'] = $this->soa_edit_api; } if ($this->zone) { @@ -206,12 +228,13 @@ public function export() { $ret['rrsets'] = $this->exportRRSets(); $ret['serial'] = $this->serial; $ret['url'] = $this->url; - + return $ret; } - private function exportRRSets() { - $ret = Array(); + private function exportRRSets() + { + $ret = []; foreach ($this->rrsets as $rrset) { array_push($ret, $rrset->export()); } @@ -220,36 +243,42 @@ private function exportRRSets() { } } -class RRSet { - public function __construct($name = '', $type = '', $content = '', $disabled = FALSE, $ttl = 3600, $setptr = FALSE) { +class RRSet +{ + public function __construct($name = '', $type = '', $content = '', $disabled = false, $ttl = 3600, $setptr = false) + { $this->name = $name; $this->type = $type; $this->ttl = $ttl; $this->changetype = 'REPLACE'; - $this->records = Array(); - $this->comments = Array(); + $this->records = []; + $this->comments = []; if (isset($content) and $content != '') { $this->addRecord($content, $disabled, $setptr); } } - public function delete() { + public function delete() + { $this->changetype = 'DELETE'; } - public function setTtl($ttl) { + public function setTtl($ttl) + { $this->ttl = $ttl; } - public function setName($name) { + public function setName($name) + { $this->name = $name; } - public function addRecord($content, $disabled = FALSE, $setptr = FALSE) { + public function addRecord($content, $disabled = false, $setptr = false) + { foreach ($this->records as $record) { if ($record->content == $content) { - throw new Exception($this->name."/".$this->type." has duplicate records."); + throw new Exception($this->name . '/' . $this->type . ' has duplicate records.'); } } @@ -257,20 +286,23 @@ public function addRecord($content, $disabled = FALSE, $setptr = FALSE) { array_push($this->records, $record); } - public function deleteRecord($content) { + public function deleteRecord($content) + { foreach ($this->records as $idx => $record) { if ($record->content == $content) { unset($this->records[$idx]); } } } - public function addComment($content, $account, $modified_at = FALSE) { + public function addComment($content, $account, $modified_at = false) + { $comment = new Comment($content, $account, $modified_at); array_push($this->comments, $comment); } - public function export() { - $ret = Array(); + public function export() + { + $ret = []; $ret['comments'] = $this->exportComments(); $ret['name'] = $this->name; $ret['records'] = $this->exportRecords(); @@ -282,11 +314,12 @@ public function export() { return $ret; } - public function exportRecords() { - $ret = Array(); + public function exportRecords() + { + $ret = []; foreach ($this->records as $record) { - if ($this->type != "A" and $this->type != "AAAA") { - $record->setptr = FALSE; + if ($this->type != 'A' and $this->type != 'AAAA') { + $record->setptr = false; } array_push($ret, $record->export()); } @@ -294,45 +327,51 @@ public function exportRecords() { return $ret; } - public function exportComments() { - $ret = Array(); + public function exportComments() + { + $ret = []; foreach ($this->comments as $comment) { array_push($ret, $comment->export()); } - + return $ret; } - } -class Record { - public function __construct($content, $disabled = FALSE, $setptr = FALSE) { +class Record +{ + public function __construct($content, $disabled = false, $setptr = false) + { $this->content = $content; $this->disabled = $disabled; $this->setptr = $setptr; } - public function export() { + public function export() + { $ret; $ret['content'] = $this->content; $ret['disabled'] = ( bool ) $this->disabled; if ($this->setptr) { - $ret['set-ptr'] = ( bool ) TRUE; + $ret['set-ptr'] = ( bool ) true; } return $ret; } } -class Comment { - public function __construct($content, $account, $modified_at) { +class Comment +{ + public function __construct($content, $account, $modified_at) + { $this->content = $content; $this->account = $account; $this->modified_at = $modified_at; } - public function export() { + public function export() + { $ret; $ret['content'] = $this->content; @@ -340,5 +379,3 @@ public function export() { $ret['modified_at'] = $this->modified_at; } } - -?> diff --git a/includes/misc.inc.php b/includes/misc.inc.php index 274b638..6d02342 100644 --- a/includes/misc.inc.php +++ b/includes/misc.inc.php @@ -1,29 +1,29 @@ doc/apiconf.txt'; - $blocklogin = TRUE; + $blocklogin = true; } if (!isset($apiproto) or !preg_match('/^http(s)?$/', $apiproto)) { - $errormsg = "The value for \$apiproto is incorrect in your config. Did you configure it?"; - $blocklogin = TRUE; + $errormsg = 'The value for $apiproto is incorrect in your config. Did you configure it?'; + $blocklogin = true; } if (!isset($apisslverify)) { - $errormsg = "The value for \$apisslverify is incorrect in your config. Did you configure it?"; - $blocklogin = TRUE; + $errormsg = 'The value for $apisslverify is incorrect in your config. Did you configure it?'; + $blocklogin = true; } else { $apisslverify = ( bool ) $apisslverify; } if (!isset($authdb)) { - $errormsg = "You did not configure a value for the setting \$authdb in your config"; - $blocklogin = TRUE; + $errormsg = 'You did not configure a value for the setting $authdb in your config'; + $blocklogin = true; } if (isset($defaults['primaryns'])) { @@ -38,24 +38,22 @@ $logo = 'https://www.tuxis.nl/uploads/images/nsedit.png'; } - /* No need to change stuf below */ -if (function_exists('curl_init') === FALSE) { - $errormsg = "You need PHP Curl to run nsedit"; - $blocklogin = TRUE; +if (function_exists('curl_init') === false) { + $errormsg = 'You need PHP Curl to run nsedit'; + $blocklogin = true; } -if (class_exists('SQLite3') === FALSE) { - $errormsg = "You need PHP SQLite3 to run nsedit"; - $blocklogin = TRUE; -} - -if (function_exists('openssl_random_pseudo_bytes') === FALSE) { - $errormsg = "You need PHP compiled with openssl to run nsedit"; - $blocklogin = TRUE; +if (class_exists('SQLite3') === false) { + $errormsg = 'You need PHP SQLite3 to run nsedit'; + $blocklogin = true; } +if (function_exists('openssl_random_pseudo_bytes') === false) { + $errormsg = 'You need PHP compiled with openssl to run nsedit'; + $blocklogin = true; +} $defaults['defaulttype'] = ucfirst(strtolower($defaults['defaulttype'])); @@ -65,7 +63,7 @@ $createsql = file_get_contents('includes/scheme.sql'); $db->exec($createsql); $salt = bin2hex(openssl_random_pseudo_bytes(16)); - $db->exec("INSERT INTO users (emailaddress, password, isadmin) VALUES ('admin', '".crypt("admin", '$6$'.$salt)."', 1)"); + $db->exec("INSERT INTO users (emailaddress, password, isadmin) VALUES ('admin', '" . crypt('admin', '$6$' . $salt) . "', 1)"); } function string_starts_with($string, $prefix) @@ -84,7 +82,8 @@ function string_ends_with($string, $suffix) return (substr($string, -$length) === $suffix); } -function get_db() { +function get_db() +{ global $authdb, $db; if (!isset($db)) { @@ -95,10 +94,11 @@ function get_db() { return $db; } -function get_all_users() { +function get_all_users() +{ $db = get_db(); $r = $db->query('SELECT id, emailaddress, isadmin FROM users ORDER BY emailaddress'); - $ret = array(); + $ret = []; while ($row = $r->fetchArray(SQLITE3_ASSOC)) { array_push($ret, $row); } @@ -106,7 +106,8 @@ function get_all_users() { return $ret; } -function get_user_info($u) { +function get_user_info($u) +{ $db = get_db(); $q = $db->prepare('SELECT * FROM users WHERE emailaddress = ?'); $q->bindValue(1, $u); @@ -116,11 +117,13 @@ function get_user_info($u) { return $userinfo; } -function user_exists($u) { +function user_exists($u) +{ return (bool) get_user_info($u); } -function do_db_auth($u, $p) { +function do_db_auth($u, $p) +{ $db = get_db(); $q = $db->prepare('SELECT * FROM users WHERE emailaddress = ?'); $q->bindValue(1, $u); @@ -128,19 +131,20 @@ function do_db_auth($u, $p) { $userinfo = $result->fetchArray(SQLITE3_ASSOC); if ($userinfo and $userinfo['password'] and (crypt($p, $userinfo['password']) === $userinfo['password'])) { - return TRUE; + return true; } - return FALSE; + return false; } -function add_user($username, $isadmin = FALSE, $password = '') { +function add_user($username, $isadmin = false, $password = '') +{ if (!$password) { $password = bin2hex(openssl_random_pseudo_bytes(32)); } if (!string_starts_with($password, '$6$')) { $salt = bin2hex(openssl_random_pseudo_bytes(16)); - $password = crypt($password, '$6$'.$salt); + $password = crypt($password, '$6$' . $salt); } $db = get_db(); @@ -158,10 +162,11 @@ function add_user($username, $isadmin = FALSE, $password = '') { return $ret; } -function update_user($id, $isadmin, $password) { +function update_user($id, $isadmin, $password) +{ if ($password && !preg_match('/\$6\$/', $password)) { $salt = bin2hex(openssl_random_pseudo_bytes(16)); - $password = crypt($password, '$6$'.$salt); + $password = crypt($password, '$6$' . $salt); } $db = get_db(); @@ -178,19 +183,20 @@ function update_user($id, $isadmin, $password) { $q->bindValue(1, (int)(bool)$isadmin, SQLITE3_INTEGER); $q->bindValue(2, $password, SQLITE3_TEXT); $q->bindValue(3, $id, SQLITE3_INTEGER); - writelog("Updating password and/or settings for $username. Admin: ".(int)(bool)$isadmin); + writelog("Updating password and/or settings for $username. Admin: " . (int)(bool)$isadmin); } else { $q = $db->prepare('UPDATE users SET isadmin = ? WHERE id = ?'); $q->bindValue(1, (int)(bool)$isadmin, SQLITE3_INTEGER); - $q->bindValue(2, $id, SQLITE3_INTEGER); - writelog("Updating settings for $username. Admin: ".(int)(bool)$isadmin); + $q->bindValue(2, $id, SQLITE3_INTEGER); + writelog("Updating settings for $username. Admin: " . (int)(bool)$isadmin); } $ret = $q->execute(); return $ret; } -function delete_user($id) { +function delete_user($id) +{ $db = get_db(); $q = $db->prepare('SELECT * FROM users WHERE id = ?'); @@ -199,41 +205,43 @@ function delete_user($id) { $userinfo = $result->fetchArray(SQLITE3_ASSOC); $q->close(); - if($userinfo) { + if ($userinfo) { $q = $db->prepare('DELETE FROM users WHERE id = ?'); $q->bindValue(1, $id, SQLITE3_INTEGER); $ret = $q->execute(); - writelog("Deleted user " . $userinfo['emailaddress'] . "."); + writelog('Deleted user ' . $userinfo['emailaddress'] . '.'); return $ret; } else { return false; } } -function valid_user($name) { - return ( bool ) preg_match( "/^[a-z0-9@_.-]+$/i" , $name ); +function valid_user($name) +{ + return ( bool ) preg_match('/^[a-z0-9@_.-]+$/i', $name); } -function jtable_respond($records, $method = 'multiple', $msg = 'Undefined errormessage') { - $jTableResult = array(); +function jtable_respond($records, $method = 'multiple', $msg = 'Undefined errormessage') +{ + $jTableResult = []; if ($method == 'error') { - $jTableResult['Result'] = "ERROR"; + $jTableResult['Result'] = 'ERROR'; $jTableResult['Message'] = $msg; } elseif ($method == 'single') { - $jTableResult['Result'] = "OK"; + $jTableResult['Result'] = 'OK'; $jTableResult['Record'] = $records; } elseif ($method == 'delete') { - $jTableResult['Result'] = "OK"; + $jTableResult['Result'] = 'OK'; } elseif ($method == 'options') { - $jTableResult['Result'] = "OK"; + $jTableResult['Result'] = 'OK'; $jTableResult['Options'] = $records; } else { if (isset($_GET['jtPageSize'])) { $jTableResult['TotalRecordCount'] = count($records); $records = array_slice($records, $_GET['jtStartIndex'], $_GET['jtPageSize']); } - $jTableResult['Result'] = "OK"; + $jTableResult['Result'] = 'OK'; $jTableResult['Records'] = $records; $jTableResult['RecordCount'] = count($records); } @@ -245,10 +253,11 @@ function jtable_respond($records, $method = 'multiple', $msg = 'Undefined errorm exit(0); } -function user_template_list() { +function user_template_list() +{ global $templates; - $templatelist = array(); + $templatelist = []; foreach ($templates as $template) { if (is_adminuser() or (isset($template['owner']) @@ -259,22 +268,25 @@ function user_template_list() { return $templatelist; } -function user_template_names() { - $templatenames = array('None' => 'None'); +function user_template_names() +{ + $templatenames = ['None' => 'None']; foreach (user_template_list() as $template) { $templatenames[$template['name']] = $template['name']; } return $templatenames; } -function getlogs() { +function getlogs() +{ global $logging; - if ($logging !== TRUE) + if ($logging !== true) { return; + } $db = get_db(); $r = $db->query('SELECT * FROM logs ORDER BY timestamp DESC'); - $ret = array(); + $ret = []; while ($row = $r->fetchArray(SQLITE3_ASSOC)) { array_push($ret, $row); } @@ -282,74 +294,82 @@ function getlogs() { return $ret; } -function clearlogs() { +function clearlogs() +{ global $logging; - if ($logging !== TRUE) + if ($logging !== true) { return; + } $db = get_db(); $q = $db->query('DELETE FROM logs;'); - writelog("Logtable truncated."); + writelog('Logtable truncated.'); } -function rotatelogs() { +function rotatelogs() +{ global $logging, $logsdirectory; - if ($logging !== TRUE) - return FALSE; + if ($logging !== true) { + return false; + } - if(!is_dir($logsdirectory) || !is_writable($logsdirectory)) { - writelog("Logs directory cannot be written to."); - return FALSE; + if (!is_dir($logsdirectory) || !is_writable($logsdirectory)) { + writelog('Logs directory cannot be written to.'); + return false; } date_default_timezone_set('UTC'); - $filename = date("Y-m-d-His") . ".json"; - $file = fopen($logsdirectory . "/" . $filename, "x"); + $filename = date('Y-m-d-His') . '.json'; + $file = fopen($logsdirectory . '/' . $filename, 'x'); - if($file === FALSE) { - writelog("Can't create file for log rotation."); - return FALSE; + if ($file === false) { + writelog("Can't create file for log rotation."); + return false; } - if(fwrite($file,json_encode(getlogs())) === FALSE) { + if (fwrite($file, json_encode(getlogs())) === false) { writelog("Can't write to file for log rotation."); fclose($file); - return FALSE; + return false; } else { fclose($file); clearlogs(); return $filename; } - } -function listrotatedlogs() { +function listrotatedlogs() +{ global $logging, $logsdirectory; - if ($logging !== TRUE) - return FALSE; + if ($logging !== true) { + return false; + } - $list = scandir($logsdirectory,SCANDIR_SORT_DESCENDING); + $list = scandir($logsdirectory, SCANDIR_SORT_DESCENDING); - if($list === FALSE) { - writelog("Logs directory cannot read."); - return FALSE; + if ($list === false) { + writelog('Logs directory cannot read.'); + return false; } - $list=array_filter($list, + $list=array_filter( + $list, function ($val) { - return(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}\.json/',$val) == 1); + return(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}\.json/', $val) == 1); } ); return $list; } -function writelog($line, $user=False) { +function writelog($line, $user=false) +{ global $logging; - if ($logging !== TRUE) + if ($logging !== true) { return; + } - if ($user === False) { + if ($user === false) { $user = get_sess_user(); } @@ -375,22 +395,26 @@ function writelog($line, $user=False) { it available on older php versions. Thanks! */ if (!function_exists('hash_pbkdf2')) { - function hash_pbkdf2($algo, $password, $salt, $iterations, $length = 0, $rawOutput = false) { + function hash_pbkdf2($algo, $password, $salt, $iterations, $length = 0, $rawOutput = false) + { // check for hashing algorithm if (!in_array(strtolower($algo), hash_algos())) { trigger_error(sprintf( '%s(): Unknown hashing algorithm: %s', - __FUNCTION__, $algo + __FUNCTION__, + $algo ), E_USER_WARNING); return false; } // check for type of iterations and length - foreach (array(4 => $iterations, 5 => $length) as $index => $value) { + foreach ([4 => $iterations, 5 => $length] as $index => $value) { if (!is_numeric($value)) { trigger_error(sprintf( '%s() expects parameter %d to be long, %s given', - __FUNCTION__, $index, gettype($value) + __FUNCTION__, + $index, + gettype($value) ), E_USER_WARNING); return null; } @@ -401,7 +425,8 @@ function hash_pbkdf2($algo, $password, $salt, $iterations, $length = 0, $rawOutp if ($iterations <= 0) { trigger_error(sprintf( '%s(): Iterations must be a positive integer: %d', - __FUNCTION__, $iterations + __FUNCTION__, + $iterations ), E_USER_WARNING); return false; } @@ -411,7 +436,8 @@ function hash_pbkdf2($algo, $password, $salt, $iterations, $length = 0, $rawOutp if ($length < 0) { trigger_error(sprintf( '%s(): Iterations must be greater than or equal to 0: %d', - __FUNCTION__, $length + __FUNCTION__, + $length ), E_USER_WARNING); return false; } @@ -420,7 +446,8 @@ function hash_pbkdf2($algo, $password, $salt, $iterations, $length = 0, $rawOutp if (strlen($salt) > PHP_INT_MAX - 4) { trigger_error(sprintf( '%s(): Supplied salt is too long, max of INT_MAX - 4 bytes: %d supplied', - __FUNCTION__, strlen($salt) + __FUNCTION__, + strlen($salt) ), E_USER_WARNING); return false; } @@ -454,5 +481,3 @@ function hash_pbkdf2($algo, $password, $salt, $iterations, $length = 0, $rawOutp return $derivedKey; } } - -?> diff --git a/includes/session.inc.php b/includes/session.inc.php index 9b359c3..2248bfb 100644 --- a/includes/session.inc.php +++ b/includes/session.inc.php @@ -1,28 +1,30 @@ $username, 'id' => $userid, 'localauth' => $localauth, 'is_admin' => $is_admin, 'has_csrf_token' => $has_csrf_token, 'is_api' => $is_api, - ); + ]; } -function _check_csrf_token($user) { +function _check_csrf_token($user) +{ global $secret; if (isset($_SERVER['HTTP_X_CSRF_TOKEN']) && $_SERVER['HTTP_X_CSRF_TOKEN']) { @@ -55,7 +57,8 @@ function _check_csrf_token($user) { header("X-CSRF-Token: ${csrf_token}"); } -function enc_secret($message) { +function enc_secret($message) +{ global $secret; if (isset($secret) && $secret) { @@ -81,14 +84,19 @@ function enc_secret($message) { return base64_encode($message); } -function dec_secret($code) { +function dec_secret($code) +{ global $secret; $is_encrypted = (substr($code, 0, 4) === 'enc:'); if (isset($secret) && $secret) { - if (!$is_encrypted) return false; + if (!$is_encrypted) { + return false; + } $msg = explode(':', $code); - if (3 != count($msg)) return false; + if (3 != count($msg)) { + return false; + } $enc_secret = hash_pbkdf2('sha256', 'encryption', $secret, 100, 0, true); $hmac_secret = hash_pbkdf2('sha256', 'encryption_hmac', $secret, 100, 0, true); @@ -98,8 +106,12 @@ function dec_secret($code) { $mac = hash_hmac('sha256', $msg[1], $hmac_secret, true); # compare hashes first: this should prevent any timing leak - if (hash('sha256', $mac, true) !== hash('sha256', $msg[2], true)) return false; - if ($mac !== $msg[2]) return false; + if (hash('sha256', $mac, true) !== hash('sha256', $msg[2], true)) { + return false; + } + if ($mac !== $msg[2]) { + return false; + } $mcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '') or die('missing mcrypt'); $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); @@ -116,31 +128,36 @@ function dec_secret($code) { return $plaintext; } - if ($is_encrypted) return false; + if ($is_encrypted) { + return false; + } return base64_decode($code); } -function _unset_cookie($name) { +function _unset_cookie($name) +{ $is_ssl = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'; setcookie($name, null, -1, null, null, $is_ssl); } -function _store_auto_login($value) { +function _store_auto_login($value) +{ $is_ssl = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'; // set for 30 days setcookie('NSEDIT_AUTOLOGIN', $value, time()+60*60*24*30, null, null, $is_ssl); } -function try_login() { +function try_login() +{ if (isset($_POST['username']) and isset($_POST['password'])) { if (_try_login($_POST['username'], $_POST['password'])) { global $secret; # only store if we have a secret. if ($secret && isset($_POST['autologin']) && $_POST['autologin']) { - _store_auto_login(enc_secret(json_encode(array( + _store_auto_login(enc_secret(json_encode([ 'username' => $_POST['username'], - 'password' => $_POST['password'])))); + 'password' => $_POST['password']]))); } return true; } @@ -148,11 +165,12 @@ function try_login() { return false; } -function _try_login($username, $password) { +function _try_login($username, $password) +{ global $wefactapiurl, $wefactapikey; if (!valid_user($username)) { - writelog("Illegal username at login!", $username); + writelog('Illegal username at login!', $username); return false; } @@ -160,8 +178,8 @@ function _try_login($username, $password) { if (isset($wefactapiurl) && isset($wefactapikey)) { $wefact = do_wefact_auth($username, $password); - if (false === $wefact ) { - writelog("Failed Wefact login!", $username); + if (false === $wefact) { + writelog('Failed Wefact login!', $username); return false; } if (-1 !== $wefact) { @@ -170,13 +188,13 @@ function _try_login($username, $password) { } if ($do_local_auth && !do_db_auth($username, $password)) { - writelog("Failed login!", $username); + writelog('Failed login!', $username); return false; } $user = get_user_info($username); if (!$user) { - writelog("Failed to find user!", $username); + writelog('Failed to find user!', $username); return false; } else { _set_current_user($username, $user['id'], (bool) $do_local_auth, (bool) $user['isadmin']); @@ -198,7 +216,8 @@ function _try_login($username, $password) { } } -function _check_session() { +function _check_session() +{ global $adminapikey, $adminapiips; $is_ssl = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'; @@ -207,13 +226,10 @@ function _check_session() { if (isset($adminapikey) && '' !== $adminapikey && isset($adminapiips) && isset($_POST['adminapikey'])) { if (false !== array_search($_SERVER['REMOTE_ADDR'], $adminapiips) - and $_POST['adminapikey'] === $adminapikey) - { + and $_POST['adminapikey'] === $adminapikey) { # Allow this request, fake that we're logged in as user. return _set_current_user('admin', 1, false, true, true, true); - } - else - { + } else { header('Status: 403 Forbidden'); exit(0); } @@ -251,14 +267,16 @@ function _check_session() { # auto load session if possible _check_session(); -function is_logged_in() { +function is_logged_in() +{ global $current_user; return (bool) $current_user; } # GET/HEAD requests only require a logged in user (they shouldn't trigger any # "writes"); all other requests require the X-CSRF-Token to be present. -function is_csrf_safe() { +function is_csrf_safe() +{ global $current_user; switch ($_SERVER['REQUEST_METHOD']) { @@ -270,32 +288,38 @@ function is_csrf_safe() { } } -function is_apiuser() { +function is_apiuser() +{ global $current_user; return $current_user && (bool) $current_user['is_api']; } -function is_adminuser() { +function is_adminuser() +{ global $current_user; return $current_user && (bool) $current_user['is_admin']; } -function get_sess_user() { +function get_sess_user() +{ global $current_user; return $current_user ? $current_user['username'] : null; } -function get_sess_userid() { +function get_sess_userid() +{ global $current_user; return $current_user ? $current_user['id'] : null; } -function has_local_auth() { +function has_local_auth() +{ global $current_user; return $current_user ? $current_user['localauth'] : null; } -function logout() { +function logout() +{ @session_destroy(); @session_unset(); if (isset($_COOKIE['NSEDIT_AUTOLOGIN'])) { diff --git a/includes/wefactauth.inc.php b/includes/wefactauth.inc.php index 43adc07..0eb62d2 100644 --- a/includes/wefactauth.inc.php +++ b/includes/wefactauth.inc.php @@ -1,79 +1,80 @@ url = $wefactapiurl; $this->api_key = $wefactapikey; } - - public function sendRequest($controller, $action, $params){ - - if(is_array($params)){ - $params['api_key'] = $this->api_key; + + public function sendRequest($controller, $action, $params) + { + if (is_array($params)) { + $params['api_key'] = $this->api_key; $params['controller'] = $controller; $params['action'] = $action; } - + $ch = curl_init(); - curl_setopt($ch,CURLOPT_URL, $this->url); + curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_TIMEOUT,'10'); + curl_setopt($ch, CURLOPT_TIMEOUT, '10'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); $curlResp = curl_exec($ch); $curlError = curl_error($ch); - - if ($curlError != ''){ - $result = array( + + if ($curlError != '') { + $result = [ 'controller' => 'invalid', 'action' => 'invalid', 'status' => 'error', 'date' => date('c'), - 'errors' => array($curlError) - ); - }else{ + 'errors' => [$curlError] + ]; + } else { $result = json_decode($curlResp, true); } - + return $result; } } - -function do_wefact_auth($u, $p) { +function do_wefact_auth($u, $p) +{ $wefact = new WeFactApi(); - $r = $wefact->sendRequest('debtor', 'show', array( - 'DebtorCode' => $u)); + $r = $wefact->sendRequest('debtor', 'show', [ + 'DebtorCode' => $u]); if (isset($r['status']) && $r['status'] == 'success') { - $r = $wefact->sendRequest('debtor', 'checklogin', array( + $r = $wefact->sendRequest('debtor', 'checklogin', [ 'Username' => $u, 'Password' => $p - )); + ]); if (isset($r['status']) && $r['status'] == 'success') { - if (get_user_info($u) == FALSE) { + if (get_user_info($u) == false) { add_user($u); } - return TRUE; + return true; } - return FALSE; + return false; } else { return -1; } diff --git a/index.php b/index.php index b0e6fd4..e2d6f0a 100644 --- a/index.php +++ b/index.php @@ -1,30 +1,30 @@ - + - + @@ -54,7 +56,7 @@ + ?>