~skye/poker/com.php

view raw


<?php

/*
 * common functions, types, etc
 *
 * types first then functions
 */

require 'cfg.php';

/* we always want the session so just start it each time */
session_start();

if(!defined('STDERR')) define('STDERR', fopen('php://stderr', 'wb'));

/* for interpolating constants in strings */
$_ = function ($x) { return $x; };

/* write to stderr */
function eputs($m) {
	fwrite(STDERR, $m . PHP_EOL);
}

/* generate a page with a title $t and body $b */
function page($t, $b): string {
	$title = Cfg::TITLE;
	$version = Cfg::VERSION;
	return <<<HTML
	<!DOCTYPE html>
	<html>
		<head>
			<meta charset="utf-8">
			<title>$t :: $title</title>
			<link
				rel="stylesheet"
				type="text/css"
				href="/css/style.php"
			>
		</head>
		<body>
			<div id="page">
				<div id="head">
					<a href="/">$title</a>
				</div>
				<hr>
				<div id="body">$b</div>
				<div id="foot">version $version</div>
			</div>
		</body>
	</html>
	HTML;
}

/* generate an error page with message $m */
function page_err($m, $goto = "/") {
	/* say "go home" if we go home otherwise "go back" */
	$loc = $goto == "/" ? "home" : "back";

	return page("error! :: $m", <<<HTML
	<h1>error</h1>
	<p>$m</p>
	<p><a href="$goto">go $loc</a></p>
	HTML);
}

/* check if $d has the right keys set & at the right len
 *
 * accepts key/val array $a, where $a is an array of
 * [ "key for $_POST" => [ min_length, max_length ] ]
 *
 * accepts dictionary $d */
function dict_has_vals($a, $d) {
	foreach ($a as $k => $v) {
		if (isset($d[$k])) {
			$x = $d[$k];
			/* len */
			$l = strlen($x);
			/* min */
			$i = $v[0];
			/* max */
			$a = $v[1];

			if (!($l >= $v[0] && $l <= $v[1])) {
				throw new Exception(
					"$k must be between $i and $a chars"
				);
			}
		} else {
			throw new Exception(
				"$k not sent in form"
			);
		}
	}
}

function form_has_post($a)	{ return dict_has_vals($a, $_POST); }
function form_has_get($a)	{ return dict_has_vals($a, $_GET); }
function session_has($a)	{ return dict_has_vals($a, $_SESSION); }


/* checks the session for a user
 * 
 * accepts a database $db */
function whoami($db) {
	try {
		session_has(["id" => [0, 32]]);
	} catch (Exception $e) {
		eputs("invalid session: " . $e->getMessage());
		return null;
	}

	try {
		return $db->get_user_by_id((int)($_SESSION["id"]));
	} catch (Exception $e) {
		eputs("error getting user: " . $e->getMessage());
		return null;
	}
}

?>