<?php


function check_nonce($action) {
	if( !verify_nonce($_REQUEST['_mtnonce'], $action) ) {
		wp_nonce_ays($action);
	}
}

/*
 Use nonce lifetime of 20 minutes.
 2 time slices, 10 minutes long each.
 Older nonces will trigger AYS
 */

if ( !function_exists('verify_nonce') ) :
function verify_nonce($nonce, $action = -1) {
		global $currentuser;
        $uid = (int) $currentuser->id;

        $i = ceil(time() / 600);

        //Allow for expanding range, but only do one check if we can
        if( substr( md5($i . '|' . $action . $uid), -12, 10) == $nonce || substr( md5(($i - 1) . '|' . $action . $uid), -12, 10) == $nonce )
                return true;
        return false;
}
endif;

if ( !function_exists('create_nonce') ) :
function create_nonce($action = -1) {
		global $currentuser;
        $uid = (int) $currentuser->id;

        $i = ceil(time() / 600);

        return substr( md5($i . '|' . $action . $uid), -12, 10);
}
endif;


function wp_nonce_ays($action) {
	if ( preg_match('#([^/]+\.php)$#', $_SERVER["PHP_SELF"], $self_matches) ) {
		$pagenow = $self_matches[1];
	} elseif ( strpos($_SERVER["PHP_SELF"], '?') !== false ) {
		$pagenow = explode('/', $_SERVER["PHP_SELF"]);
		$pagenow = trim($pagenow[(sizeof($pagenow)-1)]);
		$pagenow = explode('?', $pagenow);
		$pagenow = $pagenow[0];
	} else {
		$pagenow = 'index.php';
	}

	$adminurl = clean_url(wp_get_referer());

		$html='The attempted operation is potentially unsafe.</p>';

		if ( $_POST ) {
			$q = http_build_query($_POST);
			$q = explode( ini_get('arg_separator.output'), $q);
			$html .= "\t<form method='post' action='" . htmlentities($pagenow) . "'>\n";
			foreach ( (array) $q as $a ) {
				$v = substr(strstr($a, '='), 1);
				$k = substr($a, 0, -(strlen($v)+1));
				$html .= "\t\t<input type='hidden' name='" . mt_specialchars(urldecode($k),true) . "' value='" . mt_specialchars(urldecode($v),true) . "' />\n";
			}
			$html .= "\t\t<input type='hidden' name='_mtnonce' value='" . create_nonce($action) . "' />\n";
			$html .= "\t\t<div id='message' class='confirm fade'>\n\t\t<p>" . mt_explain_nonce($action) . "</p>\n\t\t<p><a href='$adminurl'>No</a> &nbsp; <input type='submit' value='Yes' /></p>\n\t\t</div>\n\t</form><p>\n";
		} else {
		$html .= "\t<div id='message' class='confirm fade'>\n\t<p>" . mt_explain_nonce($action) . "</p>\n\t<p><a href='$adminurl'>No</a> &nbsp; <a href='" . clean_url(add_query_arg( '_mtnonce', create_nonce($action), $_SERVER['REQUEST_URI'] )) . "'>Yes</a></p>\n\t</div><p>\n";
	}
	mtdie($html, 'Are You Sure?');
}

function mt_explain_nonce($action) {
	global $dbConnection;
	$c = explode('-',$action);
	$i = (int)$c[2];

	$message = array();
	$message['rant']['new'] = 'Are you sure you want to create a new rant?';
	$message['rant']['save'] = 'Are you sure you want to save changes to the rant "%s"?';
	$message['rant']['delete'] = 'Are you sure you want to delete the rant "%s"? This is a destructive action, and cannot be undone!';

	$message['type']['new'] = 'Are you sure you want to create a new type?';
	$message['type']['save'] = 'Are you sure you want to save changes to the type "%s"?';
	$message['type']['delete'] = 'Are you sure you want to delete the type "%s"? This is a destructive action, and cannot be undone!';

	$message['metatype']['new'] = 'Are you sure you want to create a new metatype?';
	$message['metatype']['save'] = 'Are you sure you want to save changes to the metatype "%s"?';
	$message['metatype']['delete'] = 'Are you sure you want to delete the metatype "%s"? This is a destructive action, and cannot be undone!';

	$message['strip']['new'] = 'Are you sure you want to create a new strip?';
	$message['strip']['save'] = 'Are you sure you want to save changes to the strip "%s"?';
	$message['strip']['delete'] = 'Are you sure you want to delete the comic strip "%1$s"? This will break site navigation, which can be fixed by changing other strip numbers. This is a destructive action, and cannot be undone! It is far better to <a href="edit-comic.php?strip_id=%1$s">edit the existing strip</a>.';
	$message['strip']['swap'] = 'Are you sure you want to swap these two strips? This is a destructive action, and cannot be undone!';

	$message['statusbox']['update'] = 'Are you sure you want to update the statusbox information?';
	$message['scratchpad']['new'] = 'Are you sure you want to update the scratchpad information?';
	$message['twitter']['new'] = 'Are you sure you want to update the Twitter feed?';

	$message['extra']['new'] = 'Are you sure you want to upload a new file to /extra?';
	$message['extra']['delete'] = 'Are you sure you want to delete the file from /extra named "%s"?';

	$message['twitteruser']['delete'] = 'Are you sure you want to delete the twitter user "%s"?';

	if( isset( $message[ $c[1] ][ $c[0] ] )) {
		$t = $message[ $c[1] ][ $c[0] ];

		if( false !== strpos( $t, '%' ) ) {

			switch( $c[1] ) {
				case 'rant':	$v = $dbConnection->fetchColumn('SELECT title FROM rant WHERE id = ?', array($i)); break;
				case 'strip':	$v = $dbConnection->fetchColumn('SELECT id FROM strip WHERE id = ?', array($i)); break;
				case 'type':	$v = $dbConnection->fetchColumn('SELECT name FROM strip_t WHERE id = ?', array($i)); break;
				case 'metatype':$v = $dbConnection->fetchColumn('SELECT name FROM meta_t WHERE id = ?', array($i)); break;
				case 'extra':   $temp = extra_file_from_inode($i); $v = $temp->name; break;
				case 'twitteruser': $v = $dbConnection->fetchColumn('SELECT username FROM twitter_user WHERE id = ?', array($i)); break;
				default:		$v = $i;
			}

			return sprintf( $t, mt_specialchars($v,true) );
		}

		return $t;
	}
	return "Are you sure you want to perform the action $action?";
}

function nonce_field($action) {
	echo '<input type="hidden" name="_mtnonce" value="' . create_nonce($action) . '" />';
}

?>
