From ab23338fe9f1b3ed21455867f1c032d7b146ceb8 Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Mon, 2 Mar 2015 16:51:04 +0100 Subject: Initial Commit --- inc/database.inc.php | 128 +++++++++++++++++++++++ inc/message.inc.php | 119 +++++++++++++++++++++ inc/render.inc.php | 221 +++++++++++++++++++++++++++++++++++++++ inc/request.inc.php | 45 ++++++++ inc/rpc.inc.php | 59 +++++++++++ inc/session.inc.php | 99 ++++++++++++++++++ inc/user.inc.php | 176 +++++++++++++++++++++++++++++++ inc/util.inc.php | 289 +++++++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 1136 insertions(+) create mode 100644 inc/database.inc.php create mode 100644 inc/message.inc.php create mode 100644 inc/render.inc.php create mode 100644 inc/request.inc.php create mode 100644 inc/rpc.inc.php create mode 100644 inc/session.inc.php create mode 100644 inc/user.inc.php create mode 100644 inc/util.inc.php (limited to 'inc') diff --git a/inc/database.inc.php b/inc/database.inc.php new file mode 100644 index 0000000..efc330f --- /dev/null +++ b/inc/database.inc.php @@ -0,0 +1,128 @@ + "SET NAMES utf8")); + else + self::$dbh = new PDO(CONFIG_SQL_DSN, CONFIG_SQL_USER, CONFIG_SQL_PASS); + } catch (PDOException $e) { + Util::traceError('Connecting to the local database failed: ' . $e->getMessage()); + } + } + + /** + * If you just need the first row of a query you can use this. + * + * @return array|boolean Associative array representing row, or false if no row matches the query + */ + public static function queryFirst($query, $args = array(), $ignoreError = false) + { + $res = self::simpleQuery($query, $args, $ignoreError); + if ($res === false) + return false; + return $res->fetch(PDO::FETCH_ASSOC); + } + + + /** + * Execute the given query and return the number of rows affected. + * Mostly useful for UPDATEs or INSERTs + * + * @param string $query Query to run + * @param array $args Arguments to query + * @param boolean $ignoreError Ignore query errors and just return false + * @return int|boolean Number of rows affected, or false on error + */ + public static function exec($query, $args = array(), $ignoreError = false) + { + $res = self::simpleQuery($query, $args, $ignoreError); + if ($res === false) + return false; + return $res->rowCount(); + } + + /** + * Get id (promary key) of last row inserted. + * + * @return int the id + */ + public static function lastInsertId() + { + return self::$dbh->lastInsertId(); + } + + /** + * Execute the given query and return the corresponding PDOStatement object + * Note that this will re-use PDOStatements, so if you run the same + * query again with different params, do not rely on the first PDOStatement + * still being valid. If you need to do something fancy, use Database::prepare + * @return \PDOStatement The query result object + */ + public static function simpleQuery($query, $args = array(), $ignoreError = false) + { + self::init(); + try { + if (!isset(self::$statements[$query])) { + self::$statements[$query] = self::$dbh->prepare($query); + } else { + self::$statements[$query]->closeCursor(); + } + if (self::$statements[$query]->execute($args) === false) { + if ($ignoreError) + return false; + Util::traceError("Database Error: \n" . implode("\n", self::$statements[$query]->errorInfo())); + } + return self::$statements[$query]; + } catch (Exception $e) { + if ($ignoreError) + return false; + Util::traceError("Database Error: \n" . $e->getMessage()); + } + } + + /** + * Simply calls PDO::prepare and returns the PDOStatement. + * You must call PDOStatement::execute manually on it. + */ + public static function prepare($query) + { + self:init(); + return self::$dbh->prepare($query); + } + +} diff --git a/inc/message.inc.php b/inc/message.inc.php new file mode 100644 index 0000000..7decc12 --- /dev/null +++ b/inc/message.inc.php @@ -0,0 +1,119 @@ + $type, + 'id' => $id, + 'params' => array_slice($params, 1) + ); + if (self::$flushed) self::renderList(); + } + + /** + * Render all currently queued messages, flushing the queue. + * After calling this, any further calls to add* will be rendered in + * place in the current page output. + */ + public static function renderList() + { + // Non-Ajax + foreach (self::$list as $item) { + $message = $item['id']; // Dictionary::getMessage($item['id']); + foreach ($item['params'] as $index => $text) { + $message = str_replace('{{' . $index . '}}', '' . htmlspecialchars($text) . '', $message); + } + Render::addTemplate('messagebox-' . $item['type'], array('message' => $message)); + self::$alreadyDisplayed[] = $item; + } + self::$list = array(); + self::$flushed = true; + } + + /** + * Get all queued messages, flushing the queue. + * Useful in api/ajax mode. + */ + public static function asString() + { + $return = ''; + foreach (self::$list as $item) { + $message = $item['id']; // Dictionary::getMessage($item['id']); + foreach ($item['params'] as $index => $text) { + $message = str_replace('{{' . $index . '}}', $text, $message); + } + $return .= '[' . $item['type'] . ']: ' . $message . "\n"; + self::$alreadyDisplayed[] = $item; + } + self::$list = array(); + return $return; + } + + /** + * Deserialize any messages from the current HTTP request and + * place them in the message queue. + */ + public static function fromRequest() + { + $messages = is_array($_REQUEST['message']) ? $_REQUEST['message'] : array($_REQUEST['message']); + foreach ($messages as $message) { + $data = explode('|', $message); + if (count($data) < 2 || !preg_match('/^(error|warning|info|success)$/', $data[0])) continue; + self::add($data[0], $data[1], array_slice($data, 1)); + } + } + + /** + * Turn the current message queue into a serialized version, + * suitable for appending to a GET or POST request + */ + public static function toRequest() + { + $parts = array(); + foreach (array_merge(self::$list, self::$alreadyDisplayed) as $item) { + $str = 'message[]=' . urlencode($item['type'] . '|' .$item['id']); + if (!empty($item['params'])) { + $str .= '|' . implode('|', $item['params']); + } + $parts[] = $str; + } + return implode('&', $parts); + } + +} + diff --git a/inc/render.inc.php b/inc/render.inc.php new file mode 100644 index 0000000..0147709 --- /dev/null +++ b/inc/render.inc.php @@ -0,0 +1,221 @@ + + + + ', RENDER_DEFAULT_TITLE, self::$title, ' + + + + + + + ', + self::$header + , + ' + +
+ ', + self::$body + , + '
+ + + ', + self::$footer + , + ' + ' + ; + if ($zip) { + Header('Content-Encoding: gzip'); + ob_implicit_flush(false); + $gzip_contents = ob_get_contents(); + ob_end_clean(); + echo "\x1f\x8b\x08\x00\x00\x00\x00\x00"; + echo substr(gzcompress($gzip_contents, 5), 0, -4); + } + } + + /** + * Set the page title (title-tag) + */ + public static function setTitle($title) + { + self::$title = ' - ' . $title; + } + + /** + * Add raw html data to the header-section of the generated page + */ + public static function addHeader($html) + { + self::$header .= $html . "\n"; + } + + /** + * Add raw html data to the footer-section of the generated page (right before the closing body tag) + */ + public static function addFooter($html) + { + self::$footer .= $html . "\n"; + } + + /** + * Add given js script file from the script directory to the header + * + * @param string $file file name of script + */ + public static function addScriptTop($file) + { + self::addHeader(''); + } + + /** + * Add given js script file from the script directory to the bottom + * + * @param string $file file name of script + */ + public static function addScriptBottom($file) + { + self::addFooter(''); + } + + /** + * Add the given template to the output, using the given params for placeholders in the template + */ + public static function addTemplate($template, $params = false) + { + self::$body .= self::parse($template, $params); + } + + /** + * Add a dialog to the page output. + * + * @param string $title Title of the dialog window + * @param boolean $next URL to next dialog step, or false to hide the next button + * @param string $template template used to fill the dialog body + * @param array $params parameters for rendering the body template + */ + public static function addDialog($title, $next, $template, $params = false) + { + self::addTemplate('dialog-generic', array( + 'title' => $title, + 'next' => $next, + 'body' => self::parse($template, $params) + )); + } + + /** + * Add error message to page + */ + public static function addError($message) + { + self::addTemplate('messagebox-error', array('message' => $message)); + } + + /** + * Parse template with given params and return; do not add to body + * @param string $template name of template, relative to templates/, without .html extension + * @return string Rendered template + */ + public static function parse($template, $params = false) + { + // Load html snippet + $html = self::getTemplate($template); + // Always add token to parameter list + if (is_array($params) || $params === false || is_null($params)) + $params['token'] = Session::get('token'); + // Return rendered html + return self::$mustache->render($html, $params); + } + + /** + * Open the given html tag, optionally adding the passed assoc array of params + */ + public static function openTag($tag, $params = false) + { + array_push(self::$tags, $tag); + if (!is_array($params)) { + self::$body .= '<' . $tag . '>'; + } else { + self::$body .= '<' . $tag; + foreach ($params as $key => $val) { + self::$body .= ' ' . $key . '="' . htmlspecialchars($val) . '"'; + } + self::$body .= '>'; + } + } + + /** + * Close the given tag. Will check if it maches the tag last opened + */ + public static function closeTag($tag) + { + if (empty(self::$tags)) + Util::traceError('Tried to close tag ' . $tag . ' when no open tags exist.'); + $last = array_pop(self::$tags); + if ($last !== $tag) + Util::traceError('Tried to close tag ' . $tag . ' when last opened tag was ' . $last); + self::$body .= ''; + } + + /** + * Private helper: Load the given template and return it + */ + private static function getTemplate($template) + { + if (isset(self::$templateCache[$template])) { + return self::$templateCache[$template]; + } + // Load from disk + $data = @file_get_contents('templates/' . $template . '.html'); + if ($data === false) + $data = 'Non-existent template ' . $template . ' requested!'; + self::$templateCache[$template] = & $data; + return $data; + } + +} diff --git a/inc/request.inc.php b/inc/request.inc.php new file mode 100644 index 0000000..bb212df --- /dev/null +++ b/inc/request.inc.php @@ -0,0 +1,45 @@ + 0, 'usec' => 300000)); + socket_set_option(self::$sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0)); + socket_connect(self::$sock, '127.0.0.1', 1333); + } + + public static function submit($data) + { + self::init(); + if (empty($data)) { + $data = '{}'; + } else { + $data = json_encode($data); + } + $sent = socket_send(self::$sock, $data, strlen($data), 0); + if ($sent != strlen($data)) { + return 'RPC send error'; + } + $reply = self::readReply(); + if ($reply === false) { + return 'RPC receive error'; + } + return $reply; + } + + /** + * Read reply from socket. + * + * @return mixed read reply as astring, or error message + */ + private static function readReply() + { + for ($i = 0; $i < 3; ++$i) { + $bytes = socket_recvfrom(self::$sock, $buf, 90000, 0, $bla1, $bla2); + if ($bytes !== false) + return $buf; + } + return false; + } + +} diff --git a/inc/session.inc.php b/inc/session.inc.php new file mode 100644 index 0000000..b9adfcb --- /dev/null +++ b/inc/session.inc.php @@ -0,0 +1,99 @@ + self::$sid)); + @setcookie('sid', '', time() - 8640000, null, null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true); + self::$sid = false; + self::$uid = false; + } + + public static function save() + { + if (self::$sid === false || self::$uid === false || self::$uid === 0) + return; + $ret = Database::exec('INSERT INTO websession (sid, userid, dateline) ' + . ' VALUES (:sid, :uid, UNIX_TIMESTAMP()) ' + . ' ON DUPLICATE KEY UPDATE userid = VALUES(userid), dateline = VALUES(dateline)', + array('sid' => self::$sid, 'uid' => self::$uid)); + if (!$ret) Util::traceError('Storing session data in dahdähbank failed.'); + $ret = @setcookie('sid', self::$sid, time() + CONFIG_SESSION_TIMEOUT, null, null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true); + if (!$ret) Util::traceError('Error: Could not set Cookie for Client (headers already sent)'); + } +} + diff --git a/inc/user.inc.php b/inc/user.inc.php new file mode 100644 index 0000000..30630d4 --- /dev/null +++ b/inc/user.inc.php @@ -0,0 +1,176 @@ + self::$user['organization'])); + } + return self::$organization; + } + + public static function load() + { + if (self::isLoggedIn()) + return true; + Session::load(); + if (empty($_SERVER['persistent-id'])) { + if (Session::getUid() === false) + return false; + // Try user from local DB + self::$user = Database::queryFirst('SELECT userid, shibid, login, firstname, lastname, email FROM user WHERE userid = :uid LIMIT 1', array('uid' => Session::getUid())); + return self::$user !== false; + } + // Try bwIDM etc. + self::$isShib = true; + if (!isset($_SERVER['sn'])) $_SERVER['sn'] = ''; + if (!isset($_SERVER['givenName'])) $_SERVER['givenName'] = ''; + if (!isset($_SERVER['mail'])) $_SERVER['mail'] = ''; + $shibId = md5($_SERVER['persistent-id']); + self::$user = array( + 'userid' => 0, + 'shibid' => $shibId, + 'login' => NULL, + 'firstname' => $_SERVER['givenName'], + 'lastname' => $_SERVER['sn'], + 'email' => $_SERVER['mail'], + ); + // Figure out whether the user should be considered a tutor + if (isset($_SERVER['affiliation']) && preg_match('/(^|;)employee@/', $_SERVER['affiliation'])) + self::$user['role'] = 'tutor'; + elseif (isset($_SERVER['entitlement']) && strpos(";{$_SERVER['entitlement']};", ';http://bwidm.de/entitlement/bwLehrpool;') !== false) + self::$user['role'] = 'tutor'; + // Try to figure out organization + if (isset($_SERVER['affiliation']) && preg_match('/@([a-zA-Z\-\._]+)(;|$)/', $_SERVER['affiliation'], $out)) + self::$user['organization'] = $out[1]; + // Get matching db entry if any + $user = Database::queryFirst('SELECT userid, login, firstname, lastname, email, fixedname FROM user WHERE shibid = :shibid LIMIT 1', array('shibid' => $shibId)); + if ($user === false) { + // No match in database, user is not signed up + return true; + } + // Already signed up, see if we can fetch missing fields from DB + self::$user['login'] = $user['login']; + self::$isInDb = true; + foreach (array('firstname', 'lastname', 'email') as $key) { + if (empty(self::$user[$key])) + self::$user[$key] = $user[$key]; + } + return true; + } + + public static function deploy($anonymous) + { + if (empty(self::$user['shibid'])) + Util::traceError('NO SHIBID'); + if ($anonymous) { + Database::exec("INSERT INTO user (shibid, login, organizationid, firstname, lastname, email) " + . " VALUES (:shibid, :shibid, :org, '', '', '')", array( + 'shibid' => self::$user['shibid'], + 'org' => self::getOrganizationId() + )); + } else { + Database::exec("INSERT INTO user (shibid, login, organizationid, firstname, lastname, email) " + . " VALUES (:shibid, :shibid, :org, :firstname, :lastname, :email)", array( + 'shibid' => self::$user['shibid'], + 'firstname' => self::$user['firstname'], + 'lastname' => self::$user['lastname'], + 'email' => self::$user['email'], + 'org' => self::getOrganizationId() + )); + } + } + + public static function login($user, $pass) + { + $ret = Database::queryFirst('SELECT userid, password FROM user WHERE login = :user LIMIT 1', array(':user' => $user)); + if ($ret === false) + return false; + if (!Crypto::verify($pass, $ret['passwd'])) + return false; + Session::create(); + Session::setUid($ret['userid']); + Session::set('token', md5(rand() . time() . mt_rand() . $_SERVER['REMOTE_ADDR'] . rand() . $_SERVER['REMOTE_PORT'] . rand() . $_SERVER['HTTP_USER_AGENT'] . microtime(true))); + Session::save(); + return true; + } + + public static function logout() + { + Session::delete(); + Header('Location: ?do=Main&fromlogout'); + exit(0); + } + +} diff --git a/inc/util.inc.php b/inc/util.inc.php new file mode 100644 index 0000000..4378a08 --- /dev/null +++ b/inc/util.inc.php @@ -0,0 +1,289 @@ +$2$3', $string); + $string = preg_replace('#(^|[\n \-\*/\.])_(.+?)_($|[ \-\*/\.\!\?,:])#is', '$1$2$3', $string); + $string = preg_replace('#(^|[\n \-_\*\.])/(.+?)/($|[ \-_\*\.\!\?,:])#is', '$1$2$3', $string); + return nl2br($string); + } + + /** + * Convert given number to human readable file size string. + * Will append Bytes, KiB, etc. depending on magnitude of number. + * + * @param type $bytes numeric value of the filesize to make readable + * @param type $decimals number of decimals to show, -1 for automatic + * @return type human readable string representing the given filesize + */ + public static function readableFileSize($bytes, $decimals = -1) + { + static $sz = array('Byte', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); + $factor = floor((strlen($bytes) - 1) / 3); + if ($factor == 0) { + $decimals = 0; + } elseif ($decimals === -1) { + $decimals = 2 - floor((strlen($bytes) - 1) % 3); + } + return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . $sz[$factor]; + } + + public static function sanitizeFilename($name) + { + return preg_replace('/[^a-zA-Z0-9_\-]+/', '_', $name); + } + + public static function safePath($path, $prefix = '') + { + if (empty($path)) + return false; + $path = trim($path); + if ($path{0} == '/' || preg_match('/[\x00-\x19\?\*]/', $path)) + return false; + if (strpos($path, '..') !== false) + return false; + if (substr($path, 0, 2) !== './') + $path = "./$path"; + if (empty($prefix)) + return $path; + if (substr($prefix, 0, 2) !== './') + $prefix = "./$prefix"; + if (substr($path, 0, strlen($prefix)) !== $prefix) + return false; + return $path; + } + + /** + * Create human readable error description from a $_FILES[<..>]['error'] code + * + * @param int $code the code to turn into an error description + * @return string the error description + */ + public static function uploadErrorString($code) + { + switch ($code) { + case UPLOAD_ERR_INI_SIZE: + $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; + break; + case UPLOAD_ERR_FORM_SIZE: + $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; + break; + case UPLOAD_ERR_PARTIAL: + $message = "The uploaded file was only partially uploaded"; + break; + case UPLOAD_ERR_NO_FILE: + $message = "No file was uploaded"; + break; + case UPLOAD_ERR_NO_TMP_DIR: + $message = "Missing a temporary folder"; + break; + case UPLOAD_ERR_CANT_WRITE: + $message = "Failed to write file to disk"; + break; + case UPLOAD_ERR_EXTENSION: + $message = "File upload stopped by extension"; + break; + + default: + $message = "Unknown upload error"; + break; + } + return $message; + } + + /** + * Is given string a public ipv4 address? + * + * @param string $ip_addr input to check + * @return boolean true iff $ip_addr is a valid public ipv4 address + */ + public static function isPublicIpv4($ip_addr) + { + if (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $ip_addr)) + return false; + + $parts = explode(".", $ip_addr); + foreach ($parts as $part) { + if (!is_numeric($part) || $part > 255 || $part < 0) + return false; + } + + if ($parts[0] == 0 || $parts[0] == 10 || $parts[0] == 127 || ($parts[0] > 223 && $parts[0] < 240)) + return false; + if (($parts[0] == 192 && $parts[1] == 168) || ($parts[0] == 169 && $parts[1] == 254)) + return false; + if ($parts[0] == 172 && $parts[1] > 15 && $parts[1] < 32) + return false; + + return true; + } + + /** + * Check whether $arrax contains all keys given in $keyList + * @param array $array An array + * @param array $keyList A list of strings which must all be valid keys in $array + * @return boolean + */ + public static function hasAllKeys($array, $keyList) + { + if (!is_array($array)) + return false; + foreach ($keyList as $key) { + if (!isset($array[$key])) + return false; + } + return true; + } + + /** + * Send a file to user for download. + * + * @param type $file path of local file + * @param type $name name of file to send to user agent + * @param type $delete delete the file when done? + * @return boolean false: file could not be opened. + * true: error while reading the file + * - on success, the function does not return + */ + public static function sendFile($file, $name, $delete = false) + { + while ((@ob_get_level()) > 0) + @ob_end_clean(); + $fh = @fopen($file, 'rb'); + if ($fh === false) { + Message::addError('error-read', $file); + return false; + } + Header('Content-Type: application/octet-stream', true); + Header('Content-Disposition: attachment; filename=' . str_replace(array(' ', '=', ',', '/', '\\', ':', '?'), '_', iconv('UTF-8', 'ASCII//TRANSLIT', $name))); + Header('Content-Length: ' . @filesize($file)); + while (!feof($fh)) { + $data = fread($fh, 16000); + if ($data === false) { + echo "\r\n\nDOWNLOAD INTERRUPTED!\n"; + if ($delete) + @unlink($file); + return true; + } + echo $data; + @ob_flush(); + @flush(); + } + @fclose($fh); + if ($delete) + @unlink($file); + exit(0); + } + +} -- cgit v1.2.3-55-g7522