From a4736cbf3233e00d4ead05792c2ce0358d4bb8f2 Mon Sep 17 00:00:00 2001 From: Franco Fichtner Date: Sat, 12 Sep 2015 00:52:41 +0200 Subject: [PATCH] www: apply PSR2 style to a few files JavaScript works like a charm, too. --- src/www/carp_status.php | 237 ++++++++++++++++++------------------ src/www/crash_reporter.php | 190 ++++++++++++++--------------- src/www/csrf/csrf-magic.js | 89 ++++++++------ src/www/csrf/csrf-magic.php | 159 +++++++++++++++++------- 4 files changed, 384 insertions(+), 291 deletions(-) diff --git a/src/www/carp_status.php b/src/www/carp_status.php index 56fa7e00f..d7f9ed9d2 100644 --- a/src/www/carp_status.php +++ b/src/www/carp_status.php @@ -31,23 +31,23 @@ require_once("guiconfig.inc"); require_once("pfsense-utils.inc"); require_once("interfaces.inc"); -function interfaces_carp_set_maintenancemode($carp_maintenancemode){ - global $config; - if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) { - unset($config["virtualip_carp_maintenancemode"]); - write_config("Leave CARP maintenance mode"); - } else - if (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) { - $config["virtualip_carp_maintenancemode"] = true; - write_config("Enter CARP maintenance mode"); - } +function interfaces_carp_set_maintenancemode($carp_maintenancemode) +{ + global $config; + if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) { + unset($config["virtualip_carp_maintenancemode"]); + write_config("Leave CARP maintenance mode"); + } elseif (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) { + $config["virtualip_carp_maintenancemode"] = true; + write_config("Enter CARP maintenance mode"); + } - $viparr = &$config['virtualip']['vip']; - foreach ($viparr as $vip) { - if ($vip['mode'] == "carp") { - interface_carp_configure($vip); - } - } + $viparr = &$config['virtualip']['vip']; + foreach ($viparr as $vip) { + if ($vip['mode'] == "carp") { + interface_carp_configure($vip); + } + } } @@ -56,40 +56,40 @@ unset($carp_interface_count_cache); unset($interface_ip_arr_cache); $status = get_carp_status(); -if($_POST['carp_maintenancemode'] <> "") { - interfaces_carp_set_maintenancemode(!isset($config["virtualip_carp_maintenancemode"])); +if ($_POST['carp_maintenancemode'] <> "") { + interfaces_carp_set_maintenancemode(!isset($config["virtualip_carp_maintenancemode"])); } -if($_POST['disablecarp'] <> "") { - if($status == true) { - set_single_sysctl('net.inet.carp.allow', '0'); - if(is_array($config['virtualip']['vip'])) { - $viparr = &$config['virtualip']['vip']; - foreach ($viparr as $vip) { - switch ($vip['mode']) { - case "carp": - interface_vip_bring_down($vip); - sleep(1); - break; - } - } - } - $savemsg = sprintf(gettext("%s IPs have been disabled. Please note that disabling does not survive a reboot."), $carp_counter); - } else { - $savemsg = gettext("CARP has been enabled."); - if(is_array($config['virtualip']['vip'])) { - $viparr = &$config['virtualip']['vip']; - foreach ($viparr as $vip) { - switch ($vip['mode']) { - case "carp": - interface_carp_configure($vip); - sleep(1); - break; - } - } - } - interfaces_carp_setup(); - set_single_sysctl('net.inet.carp.allow', '1'); - } +if ($_POST['disablecarp'] <> "") { + if ($status == true) { + set_single_sysctl('net.inet.carp.allow', '0'); + if (is_array($config['virtualip']['vip'])) { + $viparr = &$config['virtualip']['vip']; + foreach ($viparr as $vip) { + switch ($vip['mode']) { + case "carp": + interface_vip_bring_down($vip); + sleep(1); + break; + } + } + } + $savemsg = sprintf(gettext("%s IPs have been disabled. Please note that disabling does not survive a reboot."), $carp_counter); + } else { + $savemsg = gettext("CARP has been enabled."); + if (is_array($config['virtualip']['vip'])) { + $viparr = &$config['virtualip']['vip']; + foreach ($viparr as $vip) { + switch ($vip['mode']) { + case "carp": + interface_carp_configure($vip); + sleep(1); + break; + } + } + } + interfaces_carp_setup(); + set_single_sysctl('net.inet.carp.allow', '1'); + } } $status = get_carp_status(); @@ -111,39 +111,43 @@ include("head.inc");
- + - " . gettext("Check link status on all interfaces with configured CARP VIPs.")); ?> + " . gettext("Check link status on all interfaces with configured CARP VIPs.")); +} ?>
0) { - if($status == false) { - $carp_enabled = false; - echo ""; - } else { - $carp_enabled = true; - echo ""; - } - if(isset($config["virtualip_carp_maintenancemode"])) { - echo ""; - } else { - echo ""; - } - } - ?> + $carpcount = 0; + if (isset($config['virtualip']['vip'])) { + foreach ($config['virtualip']['vip'] as $carp) { + if ($carp['mode'] == "carp") { + $carpcount++; + break; + } + } + } + if ($carpcount > 0) { + if ($status == false) { + $carp_enabled = false; + echo ""; + } else { + $carp_enabled = true; + echo ""; + } + if (isset($config["virtualip_carp_maintenancemode"])) { + echo ""; + } else { + echo ""; + } + } + ?>
@@ -154,43 +158,43 @@ include("head.inc");

" . gettext("Could not locate any defined CARP interfaces."); + if ($carpcount == 0) { + echo "

" . gettext("Could not locate any defined CARP interfaces."); - } - elseif(is_array($config['virtualip']['vip'])) { - foreach($config['virtualip']['vip'] as $carp) { - if ($carp['mode'] != "carp") - continue; - $ipaddress = $carp['subnet']; - $password = $carp['password']; - $netmask = $carp['subnet_bits']; - $vhid = $carp['vhid']; - $advskew = $carp['advskew']; - $advbase = $carp['advbase']; - $status = get_carp_interface_status("{$carp['interface']}_vip{$carp['vhid']}"); - echo ""; - $align = "style=\"vertical-align:middle\""; - if($carp_enabled == false) { - $icon = ""; - $status = "DISABLED"; - } else { - if($status == "MASTER") { - $icon = ""; - } else if($status == "BACKUP") { - $icon = ""; - } else if($status == "INIT") { - $icon = ""; - } - } - echo "" . convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$vhid}  "; - echo "" . $ipaddress . " "; - echo "{$icon}  " . $status . " "; - echo ""; - } - } - ?> + } elseif (is_array($config['virtualip']['vip'])) { + foreach ($config['virtualip']['vip'] as $carp) { + if ($carp['mode'] != "carp") { + continue; + } + $ipaddress = $carp['subnet']; + $password = $carp['password']; + $netmask = $carp['subnet_bits']; + $vhid = $carp['vhid']; + $advskew = $carp['advskew']; + $advbase = $carp['advbase']; + $status = get_carp_interface_status("{$carp['interface']}_vip{$carp['vhid']}"); + echo ""; + $align = "style=\"vertical-align:middle\""; + if ($carp_enabled == false) { + $icon = ""; + $status = "DISABLED"; + } else { + if ($status == "MASTER") { + $icon = ""; + } elseif ($status == "BACKUP") { + $icon = ""; + } elseif ($status == "INIT") { + $icon = ""; + } + } + echo "" . convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$vhid}  "; + echo "" . $ipaddress . " "; + echo "{$icon}  " . $status . " "; + echo ""; + } + } + ?>
@@ -199,15 +203,16 @@ include("head.inc");

:
- . + .

" . gettext("pfSync nodes") . ":
"; - echo "
";
-							system("/sbin/pfctl -vvss | /usr/bin/grep creator | /usr/bin/cut -d\" \" -f7 | /usr/bin/sort -u");
-							echo "
"; - ?> + echo "
" . gettext("pfSync nodes") . ":
"; + echo "
";
+                            system("/sbin/pfctl -vvss | /usr/bin/grep creator | /usr/bin/cut -d\" \" -f7 | /usr/bin/sort -u");
+                            echo "
"; + ?> diff --git a/src/www/crash_reporter.php b/src/www/crash_reporter.php index 649839a4c..76e5467bc 100644 --- a/src/www/crash_reporter.php +++ b/src/www/crash_reporter.php @@ -33,33 +33,33 @@ require_once("captiveportal.inc"); function upload_crash_report($files, $agent) { - global $g; + global $g; - $post = array(); - $counter = 0; + $post = array(); + $counter = 0; - foreach($files as $filename) { - if (is_link($filename) || $filename == '/var/crash/minfree.gz' || $filename == '/var/crash/bounds.gz') { - continue; - } - $post["file{$counter}"] = curl_file_create($filename, "application/x-gzip", basename($filename)); - $counter++; - } + foreach ($files as $filename) { + if (is_link($filename) || $filename == '/var/crash/minfree.gz' || $filename == '/var/crash/bounds.gz') { + continue; + } + $post["file{$counter}"] = curl_file_create($filename, "application/x-gzip", basename($filename)); + $counter++; + } - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, 'https://crash.opnsense.org/'); - curl_setopt($ch, CURLOPT_HEADER, false); - curl_setopt($ch, CURLOPT_VERBOSE, false); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_USERAGENT, $agent); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $post); - curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data;' ) ); - $response = curl_exec($ch); - curl_close($ch); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, 'https://crash.opnsense.org/'); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_VERBOSE, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_USERAGENT, $agent); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post); + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data;' )); + $response = curl_exec($ch); + curl_close($ch); - return !$response; + return !$response; } $pgtitle = array(gettext('System'), gettext('Crash Reporter')); @@ -67,14 +67,14 @@ include('head.inc'); $last_version = '/usr/local/opnsense/version/opnsense.last'; $crash_report_header = sprintf( - "%s\n%s %s%s %s (%s)\nUUID %s\n", - php_uname('v'), - $g['product_name'], - trim(file_get_contents('/usr/local/opnsense/version/opnsense')), - file_exists($last_version) ? sprintf(' [%s]', trim(file_get_contents($last_version))) : '', - trim(shell_exec('/usr/local/bin/openssl version')), - php_uname('m'), - shell_exec('/sbin/sysctl -b kern.hostuuid') + "%s\n%s %s%s %s (%s)\nUUID %s\n", + php_uname('v'), + $g['product_name'], + trim(file_get_contents('/usr/local/opnsense/version/opnsense')), + file_exists($last_version) ? sprintf(' [%s]', trim(file_get_contents($last_version))) : '', + trim(shell_exec('/usr/local/bin/openssl version')), + php_uname('m'), + shell_exec('/sbin/sysctl -b kern.hostuuid') ); $pkgver = explode('-', trim(file_get_contents('/usr/local/opnsense/version/opnsense'))); @@ -83,53 +83,53 @@ $crash_reports = array(); $has_crashed = false; if (isset($_POST['Submit'])) { - if ($_POST['Submit'] == 'yes') { - if (!is_dir('/var/crash')) { - mkdir('/var/crash', 0750, true); - } - $email = trim($_POST['Email']); - if (!empty($email)) { - $crash_report_header .= "Email {$email}\n"; - } - $desc = trim($_POST['Desc']); - if (!empty($desc)) { - $crash_report_header .= "Description\n\n{$desc}"; - } - file_put_contents('/var/crash/crashreport_header.txt', $crash_report_header); - @rename('/tmp/PHP_errors.log', '/var/crash/PHP_errors.log'); - @copy('/var/run/dmesg.boot', '/var/crash/dmesg.boot'); - exec('/usr/bin/gzip /var/crash/*'); - $files_to_upload = glob('/var/crash/*'); - $resp = upload_crash_report($files_to_upload, $user_agent); - array_map('unlink', $files_to_upload); - } elseif ($_POST['Submit'] == 'no') { - array_map('unlink', glob('/var/crash/*')); - @unlink('/tmp/PHP_errors.log'); - } elseif ($_POST['Submit'] == 'new') { - /* force a crash report generation */ - $has_crashed = true; - } + if ($_POST['Submit'] == 'yes') { + if (!is_dir('/var/crash')) { + mkdir('/var/crash', 0750, true); + } + $email = trim($_POST['Email']); + if (!empty($email)) { + $crash_report_header .= "Email {$email}\n"; + } + $desc = trim($_POST['Desc']); + if (!empty($desc)) { + $crash_report_header .= "Description\n\n{$desc}"; + } + file_put_contents('/var/crash/crashreport_header.txt', $crash_report_header); + @rename('/tmp/PHP_errors.log', '/var/crash/PHP_errors.log'); + @copy('/var/run/dmesg.boot', '/var/crash/dmesg.boot'); + exec('/usr/bin/gzip /var/crash/*'); + $files_to_upload = glob('/var/crash/*'); + $resp = upload_crash_report($files_to_upload, $user_agent); + array_map('unlink', $files_to_upload); + } elseif ($_POST['Submit'] == 'no') { + array_map('unlink', glob('/var/crash/*')); + @unlink('/tmp/PHP_errors.log'); + } elseif ($_POST['Submit'] == 'new') { + /* force a crash report generation */ + $has_crashed = true; + } } else { - /* if there is no user activity probe for a crash report */ - $has_crashed = get_crash_report(true) != ''; + /* if there is no user activity probe for a crash report */ + $has_crashed = get_crash_report(true) != ''; } if ($has_crashed) { - $crash_files = glob("/var/crash/*"); - $crash_reports['System Information'] = trim($crash_report_header); - $php_errors = @file_get_contents('/tmp/PHP_errors.log'); - if (!empty($php_errors)) { - $crash_reports['PHP Errors'] = trim($php_errors); - } - $dmesg_boot = @file_get_contents('/var/run/dmesg.boot'); - if (!empty($dmesg_boot)) { - $crash_reports['dmesg.boot'] = trim($dmesg_boot); - } - foreach ($crash_files as $cf) { - if (!is_link($cf) && $cf != '/var/crash/minfree' && $cf != '/var/crash/bounds' && filesize($cf) < 450000) { - $crash_reports[$cf] = trim(file_get_contents($cf)); - } - } + $crash_files = glob("/var/crash/*"); + $crash_reports['System Information'] = trim($crash_report_header); + $php_errors = @file_get_contents('/tmp/PHP_errors.log'); + if (!empty($php_errors)) { + $crash_reports['PHP Errors'] = trim($php_errors); + } + $dmesg_boot = @file_get_contents('/var/run/dmesg.boot'); + if (!empty($dmesg_boot)) { + $crash_reports['dmesg.boot'] = trim($dmesg_boot); + } + foreach ($crash_files as $cf) { + if (!is_link($cf) && $cf != '/var/crash/minfree' && $cf != '/var/crash/bounds' && filesize($cf) < 450000) { + $crash_reports[$cf] = trim(file_get_contents($cf)); + } + } } ?> @@ -149,29 +149,29 @@ if ($has_crashed) { "; - echo ""; - echo "

" . gettext("Unfortunately we have detected at least one programming bug.") . "

"; - echo "

" . gettext("Would you like to submit this crash report to the developers?") . "

"; - echo "

" . gettext("You can help us further by optionally adding your contact information and a problem description.") . "

"; - echo "

"; - echo "

"; - echo "

" . gettext("Please double-check the following contents to ensure you are comfortable submitting the following information.") . "

"; - foreach ($crash_reports as $report => $content) { - echo "

{$report}:

{$content}

"; - } + echo "
"; + echo ""; + echo "

" . gettext("Unfortunately we have detected at least one programming bug.") . "

"; + echo "

" . gettext("Would you like to submit this crash report to the developers?") . "

"; + echo "

" . gettext("You can help us further by optionally adding your contact information and a problem description.") . "

"; + echo "

"; + echo "

"; + echo "

" . gettext("Please double-check the following contents to ensure you are comfortable submitting the following information.") . "

"; + foreach ($crash_reports as $report => $content) { + echo "

{$report}:

{$content}

"; + } } else { - $message = gettext('Luckily we have not detected a programming bug.'); - if (isset($_POST['Submit'])) { - if ($_POST['Submit'] == 'yes') { - $message = gettext('Thank you for submitting this crash report.'); - } elseif ($_POST['Submit'] == 'no') { - $message = gettext('Please consider submitting a crash report if the error persists.'); - } - } + $message = gettext('Luckily we have not detected a programming bug.'); + if (isset($_POST['Submit'])) { + if ($_POST['Submit'] == 'yes') { + $message = gettext('Thank you for submitting this crash report.'); + } elseif ($_POST['Submit'] == 'no') { + $message = gettext('Please consider submitting a crash report if the error persists.'); + } + } - echo '
'; - echo '

' . $message . '


'; + echo '
'; + echo '

' . $message . '


'; } ?> diff --git a/src/www/csrf/csrf-magic.js b/src/www/csrf/csrf-magic.js index d358b0f06..27e2ec596 100644 --- a/src/www/csrf/csrf-magic.js +++ b/src/www/csrf/csrf-magic.js @@ -8,37 +8,53 @@ // Here are the basic overloaded method definitions // The wrapper must be set BEFORE onreadystatechange is written to, since // a bug in ActiveXObject prevents us from properly testing for it. -CsrfMagic = function(real) { +CsrfMagic = function (real) { // try to make it ourselves, if you didn't pass it - if (!real) try { real = new XMLHttpRequest; } catch (e) {;} - if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {;} - if (!real) try { real = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {;} - if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP.4.0'); } catch (e) {;} - this.csrf = real; + if (!real) { + try { + real = new XMLHttpRequest; } } catch (e) { + ;} + if (!real) { + try { + real = new ActiveXObject('Msxml2.XMLHTTP'); } } catch (e) { + ;} + if (!real) { + try { + real = new ActiveXObject('Microsoft.XMLHTTP'); } } catch (e) { + ;} + if (!real) { + try { + real = new ActiveXObject('Msxml2.XMLHTTP.4.0'); } } catch (e) { + ;} + this.csrf = real; // properties - var csrfMagic = this; - real.onreadystatechange = function() { - csrfMagic._updateProps(); - return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null; - }; + var csrfMagic = this; + real.onreadystatechange = function () { + csrfMagic._updateProps(); + return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null; + }; csrfMagic._updateProps(); } CsrfMagic.prototype = { - open: function(method, url, async, username, password) { - if (method == 'POST') this.csrf_isPost = true; + open: function (method, url, async, username, password) { + if (method == 'POST') { + this.csrf_isPost = true; } // deal with Opera bug, thanks jQuery - if (username) return this.csrf_open(method, url, async, username, password); - else return this.csrf_open(method, url, async); + if (username) { + return this.csrf_open(method, url, async, username, password); } else { + return this.csrf_open(method, url, async); } }, - csrf_open: function(method, url, async, username, password) { - if (username) return this.csrf.open(method, url, async, username, password); - else return this.csrf.open(method, url, async); + csrf_open: function (method, url, async, username, password) { + if (username) { + return this.csrf.open(method, url, async, username, password); } else { + return this.csrf.open(method, url, async); } }, - send: function(data) { - if (!this.csrf_isPost) return this.csrf_send(data); + send: function (data) { + if (!this.csrf_isPost) { + return this.csrf_send(data); } prepend = csrfMagicName + '=' + csrfMagicToken + '&'; if (this.csrf_purportedLength === undefined) { this.csrf_setRequestHeader("Content-length", this.csrf_purportedLength + prepend.length); @@ -47,11 +63,11 @@ CsrfMagic.prototype = { delete this.csrf_isPost; return this.csrf_send(prepend + data); }, - csrf_send: function(data) { + csrf_send: function (data) { return this.csrf.send(data); }, - setRequestHeader: function(header, value) { + setRequestHeader: function (header, value) { // We have to auto-set this at the end, since we don't know how long the // nonce is when added to the data. if (this.csrf_isPost && header == "Content-length") { @@ -60,23 +76,23 @@ CsrfMagic.prototype = { } return this.csrf_setRequestHeader(header, value); }, - csrf_setRequestHeader: function(header, value) { + csrf_setRequestHeader: function (header, value) { return this.csrf.setRequestHeader(header, value); }, - abort: function() { + abort: function () { return this.csrf.abort(); }, - getAllResponseHeaders: function() { + getAllResponseHeaders: function () { return this.csrf.getAllResponseHeaders(); }, - getResponseHeader: function(header) { + getResponseHeader: function (header) { return this.csrf.getResponseHeader(header); } // , } // proprietary -CsrfMagic.prototype._updateProps = function() { +CsrfMagic.prototype._updateProps = function () { this.readyState = this.csrf.readyState; if (this.readyState == 4) { this.responseText = this.csrf.responseText; @@ -85,20 +101,23 @@ CsrfMagic.prototype._updateProps = function() { this.statusText = this.csrf.statusText; } } -CsrfMagic.process = function(base) { +CsrfMagic.process = function (base) { var prepend = csrfMagicName + '=' + csrfMagicToken; - if (base) return prepend + '&' + base; + if (base) { + return prepend + '&' + base; } return prepend; } // callback function for when everything on the page has loaded -CsrfMagic.end = function() { +CsrfMagic.end = function () { // This rewrites forms AGAIN, so in case buffering didn't work this // certainly will. forms = document.getElementsByTagName('form'); for (var i = 0; i < forms.length; i++) { form = forms[i]; - if (form.method.toUpperCase() !== 'POST') continue; - if (form.elements[csrfMagicName]) continue; + if (form.method.toUpperCase() !== 'POST') { + continue; } + if (form.elements[csrfMagicName]) { + continue; } var input = document.createElement('input'); input.setAttribute('name', csrfMagicName); input.setAttribute('value', csrfMagicToken); @@ -132,7 +151,7 @@ if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') { // jQuery didn't implement a new XMLHttpRequest function, so we have // to do this the hard way. jQuery.csrf_ajax = jQuery.ajax; - jQuery.ajax = function( s ) { + jQuery.ajax = function ( s ) { if (s.type && s.type.toUpperCase() == 'POST') { s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s)); if ( s.data && s.processData && typeof s.data != "string" ) { @@ -140,13 +159,13 @@ if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') { } s.data = CsrfMagic.process(s.data); } - return jQuery.csrf_ajax( s ); + return jQuery.csrf_ajax(s); } } if (window.Prototype) { // This works for script.aculo.us too Ajax.csrf_getTransport = Ajax.getTransport; - Ajax.getTransport = function() { + Ajax.getTransport = function () { return new CsrfMagic(Ajax.csrf_getTransport()); } } diff --git a/src/www/csrf/csrf-magic.php b/src/www/csrf/csrf-magic.php index 1742e53cc..1eb97bf6a 100644 --- a/src/www/csrf/csrf-magic.php +++ b/src/www/csrf/csrf-magic.php @@ -137,7 +137,8 @@ $GLOBALS['csrf']['version'] = '1.0.4'; * Rewrites
on the fly to add CSRF tokens to them. This can also * inject our JavaScript library. */ -function csrf_ob_handler($buffer, $flags) { +function csrf_ob_handler($buffer, $flags) +{ // Even though the user told us to rewrite, we should do a quick heuristic // to check if the page is *actually* HTML. We don't begin rewriting until // we hit the first ', ''. + 'var csrfMagicToken = "'.$tokens.'";'. + 'var csrfMagicName = "'.$name.'";'. '', $buffer ); @@ -181,23 +182,32 @@ function csrf_ob_handler($buffer, $flags) { * @param bool $fatal Whether or not to fatally error out if there is a problem. * @return True if check passes or is not necessary, false if failure. */ -function csrf_check($fatal = true) { - if ($_SERVER['REQUEST_METHOD'] !== 'POST') return true; +function csrf_check($fatal = true) +{ + if ($_SERVER['REQUEST_METHOD'] !== 'POST') { + return true; + } csrf_start(); $name = $GLOBALS['csrf']['input-name']; $ok = false; $tokens = ''; do { - if (!isset($_POST[$name])) break; + if (!isset($_POST[$name])) { + break; + } // we don't regenerate a token and check it because some token creation // schemes are volatile. $tokens = $_POST[$name]; - if (!csrf_check_tokens($tokens)) break; + if (!csrf_check_tokens($tokens)) { + break; + } $ok = true; } while (false); if ($fatal && !$ok) { $callback = $GLOBALS['csrf']['callback']; - if (trim($tokens, 'A..Za..z0..9:;,') !== '') $tokens = 'hidden'; + if (trim($tokens, 'A..Za..z0..9:;,') !== '') { + $tokens = 'hidden'; + } $callback($tokens); exit; } @@ -208,7 +218,8 @@ function csrf_check($fatal = true) { * Retrieves a valid token(s) for a particular context. Tokens are separated * by semicolons. */ -function csrf_get_tokens() { +function csrf_get_tokens() +{ $has_cookies = !empty($_COOKIE); // $ip implements a composite key, which is sent if the user hasn't sent @@ -224,15 +235,21 @@ function csrf_get_tokens() { csrf_start(); // These are "strong" algorithms that don't require per se a secret - if (session_id()) return 'sid:' . csrf_hash(session_id()) . $ip; + if (session_id()) { + return 'sid:' . csrf_hash(session_id()) . $ip; + } if ($GLOBALS['csrf']['cookie']) { $val = csrf_generate_secret(); setcookie($GLOBALS['csrf']['cookie'], $val); return 'cookie:' . csrf_hash($val) . $ip; } - if ($GLOBALS['csrf']['key']) return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip; + if ($GLOBALS['csrf']['key']) { + return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip; + } // These further algorithms require a server-side secret - if (!$secret) return 'invalid'; + if (!$secret) { + return 'invalid'; + } if ($GLOBALS['csrf']['user'] !== false) { return 'user:' . csrf_hash($GLOBALS['csrf']['user']); } @@ -242,17 +259,21 @@ function csrf_get_tokens() { return 'invalid'; } -function csrf_flattenpost($data) { +function csrf_flattenpost($data) +{ $ret = array(); - foreach($data as $n => $v) { + foreach ($data as $n => $v) { $ret = array_merge($ret, csrf_flattenpost2(1, $n, $v)); } return $ret; } -function csrf_flattenpost2($level, $key, $data) { - if(!is_array($data)) return array($key => $data); +function csrf_flattenpost2($level, $key, $data) +{ + if (!is_array($data)) { + return array($key => $data); + } $ret = array(); - foreach($data as $n => $v) { + foreach ($data as $n => $v) { $nk = $level >= 1 ? $key."[$n]" : "[$n]"; $ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v)); } @@ -262,12 +283,15 @@ function csrf_flattenpost2($level, $key, $data) { /** * @param $tokens is safe for HTML consumption */ -function csrf_callback($tokens) { +function csrf_callback($tokens) +{ // (yes, $tokens is safe to echo without escaping) header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden'); $data = ''; foreach (csrf_flattenpost($_POST) as $key => $value) { - if ($key == $GLOBALS['csrf']['input-name']) continue; + if ($key == $GLOBALS['csrf']['input-name']) { + continue; + } $data .= ''; } echo "CSRF check failed @@ -283,10 +307,15 @@ function csrf_callback($tokens) { * Checks if a composite token is valid. Outward facing code should use this * instead of csrf_check_token() */ -function csrf_check_tokens($tokens) { - if (is_string($tokens)) $tokens = explode(';', $tokens); +function csrf_check_tokens($tokens) +{ + if (is_string($tokens)) { + $tokens = explode(';', $tokens); + } foreach ($tokens as $token) { - if (csrf_check_token($token)) return true; + if (csrf_check_token($token)) { + return true; + } } return false; } @@ -294,39 +323,64 @@ function csrf_check_tokens($tokens) { /** * Checks if a token is valid. */ -function csrf_check_token($token) { - if (strpos($token, ':') === false) return false; +function csrf_check_token($token) +{ + if (strpos($token, ':') === false) { + return false; + } list($type, $value) = explode(':', $token, 2); - if (strpos($value, ',') === false) return false; + if (strpos($value, ',') === false) { + return false; + } list($x, $time) = explode(',', $token, 2); if ($GLOBALS['csrf']['expires']) { - if (time() > $time + $GLOBALS['csrf']['expires']) return false; + if (time() > $time + $GLOBALS['csrf']['expires']) { + return false; + } } switch ($type) { case 'sid': return $value === csrf_hash(session_id(), $time); case 'cookie': $n = $GLOBALS['csrf']['cookie']; - if (!$n) return false; - if (!isset($_COOKIE[$n])) return false; + if (!$n) { + return false; + } + if (!isset($_COOKIE[$n])) { + return false; + } return $value === csrf_hash($_COOKIE[$n], $time); case 'key': - if (!$GLOBALS['csrf']['key']) return false; + if (!$GLOBALS['csrf']['key']) { + return false; + } return $value === csrf_hash($GLOBALS['csrf']['key'], $time); // We could disable these 'weaker' checks if 'key' was set, but // that doesn't make me feel good then about the cookie-based // implementation. case 'user': - if (!csrf_get_secret()) return false; - if ($GLOBALS['csrf']['user'] === false) return false; + if (!csrf_get_secret()) { + return false; + } + if ($GLOBALS['csrf']['user'] === false) { + return false; + } return $value === csrf_hash($GLOBALS['csrf']['user'], $time); case 'ip': - if (!csrf_get_secret()) return false; + if (!csrf_get_secret()) { + return false; + } // do not allow IP-based checks if the username is set, or if // the browser sent cookies - if ($GLOBALS['csrf']['user'] !== false) return false; - if (!empty($_COOKIE)) return false; - if (!$GLOBALS['csrf']['allow-ip']) return false; + if ($GLOBALS['csrf']['user'] !== false) { + return false; + } + if (!empty($_COOKIE)) { + return false; + } + if (!$GLOBALS['csrf']['allow-ip']) { + return false; + } return $value === csrf_hash($_SERVER['IP_ADDRESS'], $time); } return false; @@ -335,7 +389,8 @@ function csrf_check_token($token) { /** * Sets a configuration value. */ -function csrf_conf($key, $val) { +function csrf_conf($key, $val) +{ if (!isset($GLOBALS['csrf'][$key])) { trigger_error('No such configuration ' . $key, E_USER_WARNING); return; @@ -346,7 +401,8 @@ function csrf_conf($key, $val) { /** * Starts a session if we're allowed to. */ -function csrf_start() { +function csrf_start() +{ if ($GLOBALS['csrf']['auto-session'] && session_status() == PHP_SESSION_NONE) { session_start(); } @@ -355,8 +411,11 @@ function csrf_start() { /** * Retrieves the secret, and generates one if necessary. */ -function csrf_get_secret() { - if ($GLOBALS['csrf']['secret']) return $GLOBALS['csrf']['secret']; +function csrf_get_secret() +{ + if ($GLOBALS['csrf']['secret']) { + return $GLOBALS['csrf']['secret']; + } $dir = dirname(__FILE__); $file = $dir . '/csrf-secret.php'; $secret = ''; @@ -377,7 +436,8 @@ function csrf_get_secret() { /** * Generates a random string as the hash of time, microtime, and mt_rand. */ -function csrf_generate_secret($len = 32) { +function csrf_generate_secret($len = 32) +{ $r = ''; for ($i = 0; $i < 32; $i++) { $r .= chr(mt_rand(0, 255)); @@ -390,14 +450,23 @@ function csrf_generate_secret($len = 32) { * Generates a hash/expiry double. If time isn't set it will be calculated * from the current time. */ -function csrf_hash($value, $time = null) { - if (!$time) $time = time(); +function csrf_hash($value, $time = null) +{ + if (!$time) { + $time = time(); + } return sha1(csrf_get_secret() . $value . $time) . ',' . $time; } // Load user configuration -if (function_exists('csrf_startup')) csrf_startup(); +if (function_exists('csrf_startup')) { + csrf_startup(); +} // Initialize our handler -if ($GLOBALS['csrf']['rewrite']) ob_start('csrf_ob_handler'); +if ($GLOBALS['csrf']['rewrite']) { + ob_start('csrf_ob_handler'); +} // Perform check -if (!$GLOBALS['csrf']['defer']) csrf_check(); +if (!$GLOBALS['csrf']['defer']) { + csrf_check(); +}