diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..96503d8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/ctldap.config +/ctldap.sh +/node_modules +/php_api/.idea \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..475da23 --- /dev/null +++ b/README.md @@ -0,0 +1,33 @@ +#LDAP Wrapper for ChurchTools v1.0.0 + +This software acts as an LDAP server for ChurchTools version 3.x + +**This software was tested in a common enviroment, yet no warranties of any kind!** + +#Installation +Node.js is required to run this software. +http://nodejs.org/ + +##Node.js install + +###To install the server on a linux machine with root access, run the install.sh script as root user. It will +- run "npm install" to install required Node.js dependencies for the server +- create a new user "ctldap" to run the server with limited privileges +- create log/error log files for stdout/stderr output and set the required ownership attributes +- create the configuration file with secure random keys and offer to adapt it, asking for reset if it already exists +- (optionally) adapt and create the ctldap.sh file in /etc/init.d and call "update-rc.d ctldap.sh defaults" + +####ctldap.sh remarks: +The file "ctldap.sh" contains a shell script for (re)starting ctldap.sh with Node.js as a background service. +It will attempt to create/remove an iptables NAT rule on start/stop in order to redirect traffic from a standard LDAP port (< 1024) to ldap_port without root. +The script can be used to start/stop the service manually, but will not work correctly without root privileges. +Usage: ctldap.sh {start|stop|status|restart} + +###If you don't have root privileges: +- run `npm install` manually or otherwise trigger the installation of required dependencies +- copy "ctldap.example.config" to "ctldap.config" and adjust the required settings accordingly +- register "ctldap.js" to be run by Node.js, or start the server directly by executing `node ctldap.js` + +##PHP API install +- copy the contents of "php_api" to the root folder of your ChurchTools installation (the composer.* files can be safely ignored) +- copy the line "api_key=" from your "ctldap.config" to your ChuchTools configuration at /sites/[default|subdomain]/churchtools.config \ No newline at end of file diff --git a/ctldap.example.config b/ctldap.example.config new file mode 100644 index 0000000..02a20e1 --- /dev/null +++ b/ctldap.example.config @@ -0,0 +1,33 @@ +; Add debug infos to log +debug=false +; This is required for clients using lowercase DNs, e.g. ownCloud/nextCloud +dn_lower_case=true + +; LDAP admin user, can be a "virtual" root user or a ChurchTools user name (virtual root is recommended!) +ldap_user=root +; The static password to be used for the ldap_user if it is NOT a CT account, or the account password of the chosen user otherwise +; If you did not use install.sh, choose a LONG SECURE RANDOM password from a password generator like KeePass! +ldap_password=XXXXXXXXXXXXXXXXXXXX +; LDAP server port +ldap_port=1389 +; The ctldap.sh service script will try to read this and setup an iptables NAT rule from iptables_port to ldap_port if it is set +iptables_port=389 +; LDAP base DN o=xxx, e.g. churchtools +ldap_base_dn=churchtools + +; The URI pointing to the root of your ChurchTools installation +ct_uri=https://mghh.churchtools.de/ +; This API key is used to authenticate against the PHP API +; IMPORTANT: AFTER using install.sh or choosing a LONG SECURE RANDOM API key from a password generator like KeePass, +; copy this line into your CT configuration at /sites/[default|subdomain]/churchtools.config +api_key=XXXXXXXXXXXXXXXXXXXX +; This controls (in milliseconds) how old the user/group data can be until it is fetched from ChurchTools again +cache_lifetime=10000 + +; To use SSL/TLS, provide file names for x509 certificate and key here +; Use this command to create a private key and a certificate: +; openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 +; Use this command to remove the encryption password: +; openssl rsa -in key.pem -out newkey.pem && mv newkey.pem key.pem +; ldap_cert_filename=cert.pem +; ldap_key_filename=key.pem diff --git a/ctldap.js b/ctldap.js new file mode 100644 index 0000000..9302b7e --- /dev/null +++ b/ctldap.js @@ -0,0 +1,336 @@ +// ChurchTools 3.2 LDAP-Wrapper +// This tool requires a node.js-Server +// (c) 2017 Michael Lux +// License: GNU/GPL v3.0 + +var ldap = require('ldapjs'); +var fs = require('fs'); +var ini = require('ini'); +var rp = require('request-promise'); +var ldapEsc = require('ldap-escape'); +var extend = require('extend'); +var Promise = require("bluebird"); +var path = require('path'); + +var config = ini.parse(fs.readFileSync(path.resolve(__dirname, 'ctldap.config'), 'utf-8')); +if (config.debug) { + console.log("Debug mode enabled, expect lots of output!"); +} + +var fnUserDn = ldapEsc.dn("cn=${cn},ou=users,o=" + config.ldap_base_dn); +var fnGroupDn = ldapEsc.dn("cn=${cn},ou=groups,o=" + config.ldap_base_dn); +var adminDn = fnUserDn({ cn: config.ldap_user }); + +if (config.dn_lower_case) { + var compatTransform = function (s) { + return s.toLowerCase(); + } +} else { + var compatTransform = function (s) { + return s; + } +} + +if (config.ldap_cert_filename && config.ldap_key_filename) { + var ldapCert = fs.readFileSync(config.ldap_cert_filename, {encoding: "utf8"}), + ldapKey = fs.readFileSync(config.ldap_key_filename, {encoding: "utf8"}); + var server = ldap.createServer({ certificate: ldapCert, key: ldapKey }); +} else { + var server = ldap.createServer(); +} + +if (typeof config.cache_lifetime !== 'number') { + config.cache_lifetime = 10000; +} +if (config.ct_uri.slice(-1) !== "/") { + config.ct_uri += "/"; +} + +/** + * Retrieves data from the PHP API via a POST call. + * @param {function} func - The function to call in the API class + * @param {object} [data] - The optional form data to pass along with the POST request + */ +function apiPost(func, data) { + return rp({ + "method": "POST", + "uri": config.ct_uri + "api.php/API/" + func, + "form": extend({ api_key: config.api_key }, data || {}), + "json": true + }).then(function (result) { + if (result.status !== "success") { + throw result.status; + } + return result.data; + }); +} + +var CACHE = {}; +var USERS_KEY = "users", GROUPS_KEY = "groups"; + +/** + * Retrieves data from cache as a Promise or refreshes the data with the provided Promise factory. + * @param {string} key - The cache key + * @param {number} maxAge - The maximum age of the cache entry, if older the data will be refreshed + * @param {function} factory - A function returning a Promise that resolves with the new cache entry or rejects + */ +function getCached(key, maxAge, factory) { + return new Promise(function (resolve, reject) { + var time = new Date().getTime(); + var co = CACHE[key] || { time: -1, entry: null }; + if (time - maxAge < co.time) { + resolve(co.entry); + } else { + // Call the factory() function to retrieve the Promise for the fresh entry + // Either resolve with the new entry (plus cache update), or pass on the rejection + factory().then(function (result) { + co.entry = result; + co.time = new Date().getTime(); + CACHE[key] = co; + resolve(result); + }, reject); + } + }); +} + + +/** + * Retrieves the users for the processed request as a Promise. + * @param {object} req - Request object + * @param {object} res - Response object + * @param {function} next - Next handler function of filter chain + */ +function requestUsers (req, res, next) { + req.usersPromise = getCached(USERS_KEY, config.cache_lifetime, function () { + return apiPost("getUsersData").then(function (results) { + var newCache = results.users.map(function (v) { + var cn = v.cmsuserid; + return { + dn: compatTransform(fnUserDn({ cn: cn })), + attributes: { + cn: cn, + displayname: v.vorname + " " + v.name, + id: String(v.id), + uid: cn, + nsuniqueid: "u" + v.id, + givenname: v.vorname, + street: v.street, + telephoneMobile: v.telefonhandy, + telephoneHome: v.telefonprivat, + postalCode: v.plz, + l: v.ort, + sn: v.name, + email: v.email, + mail: v.email, + objectclass: ['CTPerson'], + memberof: (results.userGroups[v.id] || []).map(function (cn) { + return fnGroupDn({ cn: cn }); + }) + } + }; + }); + // Virtual admin user + if (config.ldap_password !== undefined) { + var cn = config.ldap_user; + newCache.push({ + dn: compatTransform(fnUserDn({ cn: cn })), + attributes: { + cn: cn, + displayname: "LDAP Administrator", + id: 0, + uid: cn, + nsuniqueid: "u0", + givenname: "LDAP Administrator", + } + }); + } + var size = newCache.length; + if (config.debug && size > 0) { + console.log("Updated users: " + size); + } + return newCache; + }); + }); + return next(); +} + +/** + * Retrieves the groups for the processed request as a Promise. + * @param {object} req - Request object + * @param {object} res - Response object + * @param {function} next - Next handler function of filter chain + */ +function requestGroups (req, res, next) { + req.groupsPromise = getCached(GROUPS_KEY, config.cache_lifetime, function () { + return apiPost("getGroupsData").then(function (results) { + var newCache = results.groups.map(function (v) { + var cn = v.bezeichnung; + var groupType = v.gruppentyp; + return { + dn: compatTransform(fnGroupDn({ cn: cn })), + attributes: { + cn: cn, + displayname: v.bezeichnung, + id: v.id, + nsuniqueid: "g" + v.id, + objectclass: ["group", "CTGroup" + groupType.charAt(0).toUpperCase() + groupType.slice(1)], + uniquemember: (results.groupMembers[v.id] || []).map(function (cn) { + return fnUserDn({ cn: cn }); + }) + } + }; + }); + var size = newCache.length; + if (config.debug && size > 0) { + console.log("Updated groups: " + size); + } + return newCache; + }); + }); + return next(); +} + +/** + * Validates root user authentication by comparing the bind DN with the configured admin DN. + * @param {object} req - Request object + * @param {object} res - Response object + * @param {function} next - Next handler function of filter chain + */ +function authorize(req, res, next) { + if (!req.connection.ldap.bindDN.equals(adminDn)) { + console.log("Rejected search without proper binding!"); + return next(new ldap.InsufficientAccessRightsError()); + } + return next(); +} + +/** + * Performs debug logging if debug mode is enabled. + * @param {object} req - Request object + * @param {object} res - Response object + * @param {function} next - Next handler function of filter chain + */ +function searchLogging (req, res, next) { + if (config.debug) { + console.log("SEARCH base object: " + req.dn.toString() + " scope: " + req.scope); + console.log("Filter: " + req.filter.toString()); + } + return next(); +} + +/** + * Evaluetes req.usersPromise and sends matching elements to the client. + * @param {object} req - Request object + * @param {object} res - Response object + * @param {function} next - Next handler function of filter chain + */ +function sendUsers (req, res, next) { + var strDn = req.dn.toString(); + req.usersPromise.then(function (users) { + users.forEach(function (u) { + if ((req.checkAll || strDn === u.dn) && (req.filter.matches(u.attributes))) { + if (config.debug) { + console.log("MatchUser: " + u.dn); + } + res.send(u); + } + }); + return next(); + }).catch(function (error) { + console.log("Error while retrieving users: " + error); + return next(); + }); +} + +/** + * Evaluetes req.groupsPromise and sends matching elements to the client. + * @param {object} req - Request object + * @param {object} res - Response object + * @param {function} next - Next handler function of filter chain + */ +function sendGroups (req, res, next) { + var strDn = req.dn.toString(); + req.groupsPromise.then(function (groups) { + groups.forEach(function (g) { + if ((req.checkAll || strDn === g.dn) && (req.filter.matches(g.attributes))) { + if (config.debug) { + console.log("MatchGroup: " + g.dn); + } + res.send(g); + } + }); + return next(); + }).catch(function (error) { + console.log("Error while retrieving groups: " + error); + return next(); + }); +} + +/** + * Calls the res.end() function to finalize successful chain processing. + * @param {object} req - Request object + * @param {object} res - Response object + * @param {function} next - Next handler function of filter chain + */ +function endSuccess (req, res, next) { + res.end(); + return next(); +} + +// Login bind for user +server.bind("ou=users,o=" + config.ldap_base_dn, function (req, res, next) { + if (req.dn.equals(adminDn)) { + if (config.debug) { + console.log('Admin bind DN: ' + req.dn.toString()); + } + // If ldap_password is undefined, try a default ChurchTools authentication with this user + if (config.ldap_password !== undefined) { + if (req.credentials === config.ldap_password) { + if (config.debug) { + console.log("Authentication success"); + } + return next(); + } else { + console.log("Invalid root password!"); + return next(new ldap.InvalidCredentialsError()); + } + } + } else if (config.debug) { + console.log('Bind user DN: ' + req.dn.toString()); + } + apiPost("authenticate", { + "user": req.dn.rdns[0].cn, + "password": req.credentials + }).then(function () { + if (config.debug) { + console.log("Authentication successful for " + req.dn.toString()); + } + return next(); + }).catch(function (error) { + console.log("Authentication error: " + error); + return next(new ldap.InvalidCredentialsError()); + }); +}, endSuccess); + +// Search implementation for user search +server.search("ou=users,o=" + config.ldap_base_dn, searchLogging, authorize, requestUsers, function (req, res, next) { + req.checkAll = req.scope !== "base"; + return next(); +}, sendUsers, endSuccess); + +// Search implementation for group search +server.search("ou=groups,o=" + config.ldap_base_dn, searchLogging, authorize, requestGroups, function (req, res, next) { + req.checkAll = req.scope !== "base"; + return next(); +}, sendGroups, endSuccess); + +// Search implementation for user and group search +server.search("o=" + config.ldap_base_dn, searchLogging, authorize, requestUsers, requestGroups, function (req, res, next) { + req.checkAll = req.scope === "sub"; + return next(); +}, sendUsers, sendGroups, endSuccess); + +// Start LDAP server +server.listen(parseInt(config.ldap_port), function() { + console.log('ChurchTools-LDAP-Wrapper listening @ %s', server.url); +}); diff --git a/ctldap_raw.sh b/ctldap_raw.sh new file mode 100644 index 0000000..03f62b7 --- /dev/null +++ b/ctldap_raw.sh @@ -0,0 +1,98 @@ +#!/bin/sh + +### BEGIN INIT INFO +# Provides: ctldap +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: ChurchTools 3.2 LDAP-Wrapper +# Description: Init script for the ChurchTools LDAP Wrapper. +### END INIT INFO + +# Author: Michael Lux +# License: GNU/GPL v3.0 + +NAME="ctldap" +DESC="ChurchTools LDAP Wrapper" + +PIDFILE="/var/run/$NAME.pid" +CTLDAP="#CTLDAP#" +PATH=/sbin:/usr/sbin:/bin:/usr/bin + +case "$1" in +start) + echo "Starting $NAME..." + if [ -f $PIDFILE ]; then + echo "Found PID file, try to stop first..." + if echo "$0" | grep -qe "^/"; then + $0 stop + else + DIR=$(dirname "$0") + sh $DIR/$0 stop + fi + fi + su -c "nohup node $CTLDAP/ctldap.js 2>>$CTLDAP/error.log >>$CTLDAP/output.log &" - ctldap + PID=$( ps axf | grep "node $CTLDAP/ctldap.js" | grep -v grep | awk '{print $1}' ) + if [ -z "$PID" ]; then + echo "Fail" + else + echo $PID > $PIDFILE + echo "$DESC started" + DPORT=$( cat $CTLDAP/ctldap.config | grep -oP "(?<=iptables_port=)[1-9][0-9]+" | head -n1 ) + if [ -n "$DPORT" ]; then + echo "Trying to create iptables NAT rules for port redirect..." + TO_PORT=$( cat $CTLDAP/ctldap.config | grep -oP "(?<=ldap_port=)[1-9][0-9]+" | head -n1 ) + iptables -A PREROUTING -t nat -i eth0 -p tcp --dport "$DPORT" -j REDIRECT --to-port "$TO_PORT" + fi + fi +;; + +status) + echo "Checking $NAME..." + if [ -f $PIDFILE ]; then + PID=`cat $PIDFILE` + if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then + echo "$NAME dead but pidfile exists" + else + echo "$NAME running" + fi + else + echo "$NAME not running" + fi +;; + +stop) + echo "Stopping $NAME..." + PID=`cat $PIDFILE` + if [ -f $PIDFILE ]; then + kill -HUP $PID + echo "$DESC stopped" + DPORT=$( cat $CTLDAP/ctldap.config | grep -oP "(?<=iptables_port=)[1-9][0-9]+" | head -n1 ) + if [ -n "$DPORT" ]; then + echo "Trying to remove iptables NAT rules..." + TO_PORT=$( cat $CTLDAP/ctldap.config | grep -oP "(?<=ldap_port=)[1-9][0-9]+" | head -n1 ) + iptables -D PREROUTING -t nat -i eth0 -p tcp --dport "$DPORT" -j REDIRECT --to-port "$TO_PORT" + fi + rm -f $PIDFILE + else + echo "pidfile not found" + fi +;; + +restart|reload|force-reload) + if echo "$0" | grep -qe "^/"; then + $0 stop + $0 start + else + DIR=$(dirname "$0") + sh $DIR/$0 stop + sh $DIR/$0 start + fi + +;; + +*) + echo "Usage: $0 {start|stop|status|restart}" + exit 1 +esac \ No newline at end of file diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..a0c777c --- /dev/null +++ b/install.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +# ChurchTools 3.2 LDAP-Wrapper +# (c) 2017 Michael Lux +# License: GNU/GPL v3.0 + +if [ "$(id -u)" != "0" ]; then + echo "This script must be run as root!" 1>&2 + exit 1 +fi + +CTLDAP=$( dirname "$0" ) +cd "$CTLDAP" +CTLDAP=$( pwd ) +echo "Create init script $CTLDAP/ctldap.sh..." +cat ctldap_raw.sh | sed "s/#CTLDAP#/${CTLDAP//\//\\/}/" > ctldap.sh +echo "" + +echo "Running \"npm_install\" to download required node.js packages..." +npm install +echo "" + +echo "Now creating the \"ctldap\" user..." +useradd ctldap +echo "" + +echo "Init logging files..." +touch output.log +touch error.log +chown ctldap:ctldap *.log +echo "" + +ANSWER="y" +if [ -f "ctldap.config" ]; then + read -n1 -p "Reset configuration file? [y/n]" ANSWER + echo "" +fi +if [ $ANSWER = "y" ]; then + PRNG_CMD="tr -cd '[:alnum:]' < /dev/urandom | fold -w20 | head -n1" + cat ctldap.example.config | \ + sed "s/ldap_password=XXXXXXXXXXXXXXXXXXXX/ldap_password=$(eval ${PRNG_CMD})/" | \ + sed "s/api_key=XXXXXXXXXXXXXXXXXXXX/api_key=$(eval ${PRNG_CMD})/" > test.config +fi + +echo "Trying to open ctldap.config now, modify it according to your needs!" +read -n1 -r -p "Press any key to continue..." +if [[ $(which nano) = /* ]]; then + nano ctldap.config +elif [[ $(which vim) = /* ]]; then + vim ctldap.config +fi +echo "" + +read -n1 -p "Register ctldap.sh for autostart at /etc/init.d? [y/n]" ANSWER +if [ $ANSWER = "y" ]; then + cp -f ctldap.sh /etc/init.d/ + chmod +x /etc/init.d/ctldap.sh + update-rc.d ctldap.sh defaults +fi +echo "" \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..204d941 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "ctldap", + "license": "GPL-3.0", + "description": "LDAP Wrapper for ChurchTools", + "version": "1.0.0", + "private": true, + "dependencies": { + "bluebird": "^3.5.0", + "extend": "^3.0.1", + "ini": "^1.1.0", + "ldap-escape": "^1.1.4", + "ldapjs": "^0.7.0", + "request": "^2.81.0", + "request-promise": "^4.2.1" + }, + "devDependencies": {} +} diff --git a/php_api/api.php b/php_api/api.php new file mode 100644 index 0000000..cf40295 --- /dev/null +++ b/php_api/api.php @@ -0,0 +1,141 @@ +implementsInterface('ICallable')) { + throw new Exception('Class is no module, PATH_INFO: ' . $_SERVER['PATH_INFO'], 400); + } + //check method existence + if(!$reflectClass->hasMethod($method)) { + throw new Exception('Method not found, PATH_INFO: ' . $_SERVER['PATH_INFO'], 400); + } + //create method reflection + $reflectMethod = $reflectClass->getMethod($method); + //parse the method's DocComment + $parser = new AnnotationParser($reflectMethod->getDocComment()); + + //collect parameters according to information from DocComment + $params = array(); + foreach($parser->getParamMeta() as $pName => $pMeta) { + $src = null; + if(isset($pMeta['Source'])) { + $p = explode('.', $pMeta['Source'][0]); + switch(array_shift($p)) { + case 'POST': + $src = $_POST; + break; + case 'GET': + $src = $_GET; + break; + case 'PATH': + $src = $pathInfo; + break; + } + //scan deeper into data structure according to specified indicies + while(count($p) > 0) { + $subIndex = array_shift($p); + if(isset($src[$subIndex])) { + $src = $src[$subIndex]; + } else { + $src = NULL; + break; + } + } + //add parameterized data source to parameter array + if(isset($src)) { + settype($src, $pMeta['type']); + $params[$pName] = $src; + } + } + } + + //clear request data + unset($pathInfo); + $_REQUEST = $_POST = $_GET = array(); + + //check if method is public and static, and number of provided parameters (res. path) + //is greater or equal to the number of required parameters + if(!$reflectMethod->isStatic() || !$reflectMethod->isPublic() + || count($params) < $reflectMethod->getNumberOfRequiredParameters()) { + throw new Exception('Method is not public static or wrong parameter number, ' + . 'PATH_INFO: ' . $_SERVER['PATH_INFO'], 400); + } + + $jsonExpected = strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false; + //wrap method call in output buffer to avoid header problems + ob_start(); + try { + //execute inside transaction + SPDO::ta(function () use ($reflectMethod, $params, $jsonExpected) { + $res = $reflectMethod->invokeArgs(NULL, $params); + if(isset($res)) { + if($jsonExpected || is_bool($res) || is_array($res) || (is_object($res) && $res instanceof stdClass)) { + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(array( + 'status' => 'success', + 'data' => $res + )); + } else { + header('Content-Type: text/html; charset=utf-8'); + echo $res; + } + } + }); + } catch(Exception $e) { + if($jsonExpected || $parser->getReturnType() === 'array') { + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(array( + 'status' => $e->getMessage(), + 'trace' => $e->getTrace() + )); + } else { + header('Content-Type: text/html; charset=utf-8'); + echo $e->getMessage(); + echo '
'; + echo nl2br($e->getTraceAsString()); + } + } + //flush buffered content + ob_end_flush(); +} catch (Exception $ex) { + $httpCodes = array( + 400 => 'Bad Request', + 403 => 'Forbidden', + 404 => 'Not Found' + ); + header('HTTP/1.0 ' . $ex->getCode() . ' ' . $httpCodes[$ex->getCode()]); + header('X-Error: ' . $ex->getMessage()); +} diff --git a/php_api/api_classes/API.php b/php_api/api_classes/API.php new file mode 100644 index 0000000..8947428 --- /dev/null +++ b/php_api/api_classes/API.php @@ -0,0 +1,89 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +use milux\spdo\SPDO; + +class API implements ICallable { + + /** + * Checks if the user can authenticate himself in ChurchTools + * + * @param string $user @Source(POST.user) the user name + * @param string $password @Source(POST.password) The password of the user + * + * @return boolean Authentication error/success + * @throws Exception On authentication error + */ + public static function authenticate($user, $password) { + // include password_compat wrapper if supported + $usePasswordApi = true; + if (!function_exists('password_hash')) { + $hash = '$2y$04$use.any.string.for.itu8yjBBIVvIAXzFyRajcNk82tV0qIVxDK'; + $usePasswordApi = function_exists('crypt') && crypt('password', $hash) === $hash; + } + $hash = SPDO::prepare("SELECT password FROM #_cdb_person WHERE LOWER(cmsuserid) = LOWER(?)") + ->execute($user)->cell(); + $needsRehash = false; + if ($usePasswordApi && password_verify($password, $hash)) { + if (password_needs_rehash($hash, PASSWORD_DEFAULT)) { + $needsRehash = true; + } + } else if (md5(trim($password)) === $hash) { + $needsRehash = true; + } else { + throw new Exception("Authentication failed for $user, password invalid!"); + } + if ($usePasswordApi && $needsRehash) { + $newHash = password_hash($password, PASSWORD_DEFAULT); + SPDO::update('#_cdb_person', array('password' => $newHash), + 'LOWER(cmsuserid) = LOWER(?)', array($user)); + } + return true; + } + + /** + * Returns users and groups of them + * + * @return array Users and groups of them + */ + public static function getUsersData() { + return array( + 'users' => SPDO::query("SELECT id, cmsuserid, vorname, name, email, telefonhandy, telefonprivat, plz, + strasse, ort FROM cdb_person WHERE cmsuserid != ''")->get(), + 'userGroups' => SPDO::query("SELECT g.bezeichnung, gp.person_id" + . " FROM cdb_gruppe g" + . " JOIN cdb_gemeindeperson_gruppe gpg ON g.id = gpg.gruppe_id" + . " JOIN cdb_gemeindeperson gp ON gpg.gemeindeperson_id = gp.id" + . " JOIN cdb_grouptype_memberstatus gtms ON gpg.gruppenteilnehmerstatus_id = gtms.id" + . " WHERE g.groupstatus_id = 1 AND gtms.deleted_yn = 0 AND gtms.request_yn = 0") + ->group(array('person_id'))->get() + ); + } + + /** + * Return groups and their members + * + * @return array Groups and their members + */ + public static function getGroupsData() { + return array( + 'groups' => SPDO::query("SELECT g.id, g.bezeichnung, gt.bezeichnung AS gruppentyp" + . " FROM cdb_gruppe g JOIN cdb_gruppentyp gt ON g.gruppentyp_id = gt.id" + . " WHERE g.groupstatus_id = 1 AND versteckt_yn = 0")->get(), + 'groupMembers' => SPDO::query("SELECT gpg.gruppe_id, p.cmsuserid" + . " FROM cdb_gemeindeperson_gruppe gpg" + . " JOIN cdb_gemeindeperson gp ON gp.id = gpg.gemeindeperson_id" + . " JOIN cdb_person p ON gp.person_id = p.id" + . " JOIN cdb_grouptype_memberstatus gtms ON gpg.gruppenteilnehmerstatus_id = gtms.id" + . " WHERE cmsuserid != '' AND gtms.deleted_yn = 0 AND gtms.request_yn = 0") + ->group(array('gruppe_id'))->get() + ); + } + +} \ No newline at end of file diff --git a/php_api/api_classes/AnnotationParser.php b/php_api/api_classes/AnnotationParser.php new file mode 100644 index 0000000..804c780 --- /dev/null +++ b/php_api/api_classes/AnnotationParser.php @@ -0,0 +1,70 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +class AnnotationParser { + + private $annotations = array(); + private $paramAnnotations = null; + + public function __construct($docComment) { + $token = strtok($docComment, "\n"); + while($token !== false) { + $matches = array(); + if(preg_match('/^\s*\*?\s*@([a-zA-Z]+)\s+(.*)/', $token, $matches) > 0) { + if(!isset($this->annotations[$matches[1]])) { + $this->annotations[$matches[1]] = array(); + } + $this->annotations[$matches[1]][] = $matches[2]; + } + $token = strtok("\n"); + } + } + + public function getAnnotations() { + return $this->annotations; + } + + public function getParamMeta() { + if(!isset($this->paramAnnotations)) { + $this->paramAnnotations = array(); + if(isset($this->annotations['param'])) { + foreach($this->annotations['param'] as $pa) { + $tokens = array(); + //read parameter name and type + if(preg_match('/(\S+)\s+\$(\S+)\s+(.*)/', $pa, $tokens) > 0) { + $paramName = $tokens[2]; + $this->paramAnnotations[$paramName] = array( + 'type' => $tokens[1] + ); + $nas = array(); + //find nested annotations of the form @AnnotationName(content) + preg_match_all('/@([a-zA-Z]+)\((.+?)\)/', $tokens[3], $nas, PREG_SET_ORDER); + foreach($nas as $na) { + if(!isset($this->paramAnnotations[$paramName][$na[1]])) { + $this->paramAnnotations[$paramName][$na[1]] = array(); + } + $this->paramAnnotations[$paramName][$na[1]][] = $na[2]; + } + } + } + } + } + return $this->paramAnnotations; + } + + public function getReturnType() { + if(isset($this->annotations['return'])) { + $typeAndDesc = explode(' ', $this->annotations['return'][0], 2); + if(!empty($typeAndDesc)) { + return $typeAndDesc[0]; + } + } + } + +} diff --git a/php_api/api_classes/CT_SPDOConfig.php b/php_api/api_classes/CT_SPDOConfig.php new file mode 100644 index 0000000..ff4301b --- /dev/null +++ b/php_api/api_classes/CT_SPDOConfig.php @@ -0,0 +1,42 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +use milux\spdo\SPDOConfig; + +class CT_SPDOConfig extends SPDOConfig { + + /** + * @var array The parsed ChurchTools configuration + */ + private $config = array(); + + function __construct($config) { + $this->config = $config; + } + + public function getHost() { + return $this->config['db_server']; + } + + public function getUser() { + return $this->config['db_user']; + } + + public function getPassword() { + return $this->config['db_password']; + } + + public function getSchema() { + return $this->config['db_name']; + } + + public function preProcess($sql) { + return strtr($sql, array('#_' => $this->config['prefix'])); + } +} \ No newline at end of file diff --git a/php_api/api_classes/ICallable.php b/php_api/api_classes/ICallable.php new file mode 100644 index 0000000..c34113d --- /dev/null +++ b/php_api/api_classes/ICallable.php @@ -0,0 +1,10 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +interface ICallable {} \ No newline at end of file diff --git a/php_api/composer.json b/php_api/composer.json new file mode 100644 index 0000000..d58d14e --- /dev/null +++ b/php_api/composer.json @@ -0,0 +1,6 @@ +{ + "require": { + "milux/spdo": "^1.0.0", + "ircmaxell/password-compat": "^1.0" + } +} diff --git a/php_api/composer.lock b/php_api/composer.lock new file mode 100644 index 0000000..062adc1 --- /dev/null +++ b/php_api/composer.lock @@ -0,0 +1,104 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" + ], + "hash": "e95121df8451975a1d77f0ee610e2f0e", + "content-hash": "f3e03dda3ce94a25a7cc4b1d9196ae0a", + "packages": [ + { + "name": "ircmaxell/password-compat", + "version": "v1.0.4", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/password_compat.git", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/password_compat/zipball/5c5cde8822a69545767f7c7f3058cb15ff84614c", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c", + "shasum": "" + }, + "require-dev": { + "phpunit/phpunit": "4.*" + }, + "type": "library", + "autoload": { + "files": [ + "lib/password.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "homepage": "https://github.com/ircmaxell/password_compat", + "keywords": [ + "hashing", + "password" + ], + "time": "2014-11-20 16:49:30" + }, + { + "name": "milux/spdo", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/milux/spdo.git", + "reference": "8a275cfb7f061e87211ea8906e42abdfc05ae723" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/milux/spdo/zipball/8a275cfb7f061e87211ea8906e42abdfc05ae723", + "reference": "8a275cfb7f061e87211ea8906e42abdfc05ae723", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "autoload": { + "psr-0": { + "milux": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPLv3" + ], + "authors": [ + { + "name": "Michael Lux", + "email": "michi.lux@gmail.com", + "role": "Developer" + } + ], + "description": "A static, simple PDO wrapper for easy database operations", + "homepage": "https://github.com/milux/spdo", + "keywords": [ + "database", + "pdo", + "sql" + ], + "time": "2017-05-29 20:48:01" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [] +} diff --git a/php_api/vendor/autoload.php b/php_api/vendor/autoload.php new file mode 100644 index 0000000..0a1c980 --- /dev/null +++ b/php_api/vendor/autoload.php @@ -0,0 +1,7 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see http://www.php-fig.org/psr/psr-0/ + * @see http://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + // PSR-4 + private $prefixLengthsPsr4 = array(); + private $prefixDirsPsr4 = array(); + private $fallbackDirsPsr4 = array(); + + // PSR-0 + private $prefixesPsr0 = array(); + private $fallbackDirsPsr0 = array(); + + private $useIncludePath = false; + private $classMap = array(); + private $classMapAuthoritative = false; + private $missingClasses = array(); + + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', $this->prefixesPsr0); + } + + return array(); + } + + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 base directories + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + } + + /** + * Unregisters this instance as an autoloader. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return bool|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 + if ('\\' == $class[0]) { + $class = substr($class, 1); + } + + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) { + if (0 === strpos($class, $prefix)) { + foreach ($this->prefixDirsPsr4[$prefix] as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + */ +function includeFile($file) +{ + include $file; +} diff --git a/php_api/vendor/composer/LICENSE b/php_api/vendor/composer/LICENSE new file mode 100644 index 0000000..1a28124 --- /dev/null +++ b/php_api/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) 2016 Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/php_api/vendor/composer/autoload_classmap.php b/php_api/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..7a91153 --- /dev/null +++ b/php_api/vendor/composer/autoload_classmap.php @@ -0,0 +1,9 @@ + $vendorDir . '/ircmaxell/password-compat/lib/password.php', +); diff --git a/php_api/vendor/composer/autoload_namespaces.php b/php_api/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..c4a6675 --- /dev/null +++ b/php_api/vendor/composer/autoload_namespaces.php @@ -0,0 +1,10 @@ + array($vendorDir . '/milux/spdo/src'), +); diff --git a/php_api/vendor/composer/autoload_psr4.php b/php_api/vendor/composer/autoload_psr4.php new file mode 100644 index 0000000..b265c64 --- /dev/null +++ b/php_api/vendor/composer/autoload_psr4.php @@ -0,0 +1,9 @@ += 50600 && !defined('HHVM_VERSION'); + if ($useStaticLoader) { + require_once __DIR__ . '/autoload_static.php'; + + call_user_func(\Composer\Autoload\ComposerStaticInitb99c31cbe15c494b4f0f26db1fbcd68a::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + } + + $loader->register(true); + + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInitb99c31cbe15c494b4f0f26db1fbcd68a::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } + foreach ($includeFiles as $fileIdentifier => $file) { + composerRequireb99c31cbe15c494b4f0f26db1fbcd68a($fileIdentifier, $file); + } + + return $loader; + } +} + +function composerRequireb99c31cbe15c494b4f0f26db1fbcd68a($fileIdentifier, $file) +{ + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + require $file; + + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + } +} diff --git a/php_api/vendor/composer/autoload_static.php b/php_api/vendor/composer/autoload_static.php new file mode 100644 index 0000000..8b12a2d --- /dev/null +++ b/php_api/vendor/composer/autoload_static.php @@ -0,0 +1,30 @@ + __DIR__ . '/..' . '/ircmaxell/password-compat/lib/password.php', + ); + + public static $prefixesPsr0 = array ( + 'm' => + array ( + 'milux' => + array ( + 0 => __DIR__ . '/..' . '/milux/spdo/src', + ), + ), + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixesPsr0 = ComposerStaticInitb99c31cbe15c494b4f0f26db1fbcd68a::$prefixesPsr0; + + }, null, ClassLoader::class); + } +} diff --git a/php_api/vendor/composer/installed.json b/php_api/vendor/composer/installed.json new file mode 100644 index 0000000..aa6e519 --- /dev/null +++ b/php_api/vendor/composer/installed.json @@ -0,0 +1,91 @@ +[ + { + "name": "milux/spdo", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/milux/spdo.git", + "reference": "8a275cfb7f061e87211ea8906e42abdfc05ae723" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/milux/spdo/zipball/8a275cfb7f061e87211ea8906e42abdfc05ae723", + "reference": "8a275cfb7f061e87211ea8906e42abdfc05ae723", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2017-05-29 20:48:01", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "milux": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPLv3" + ], + "authors": [ + { + "name": "Michael Lux", + "email": "michi.lux@gmail.com", + "role": "Developer" + } + ], + "description": "A static, simple PDO wrapper for easy database operations", + "homepage": "https://github.com/milux/spdo", + "keywords": [ + "database", + "pdo", + "sql" + ] + }, + { + "name": "ircmaxell/password-compat", + "version": "v1.0.4", + "version_normalized": "1.0.4.0", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/password_compat.git", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/password_compat/zipball/5c5cde8822a69545767f7c7f3058cb15ff84614c", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c", + "shasum": "" + }, + "require-dev": { + "phpunit/phpunit": "4.*" + }, + "time": "2014-11-20 16:49:30", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "lib/password.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "homepage": "https://github.com/ircmaxell/password_compat", + "keywords": [ + "hashing", + "password" + ] + } +] diff --git a/php_api/vendor/ircmaxell/password-compat/LICENSE.md b/php_api/vendor/ircmaxell/password-compat/LICENSE.md new file mode 100644 index 0000000..1efc565 --- /dev/null +++ b/php_api/vendor/ircmaxell/password-compat/LICENSE.md @@ -0,0 +1,7 @@ +Copyright (c) 2012 Anthony Ferrara + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/php_api/vendor/ircmaxell/password-compat/composer.json b/php_api/vendor/ircmaxell/password-compat/composer.json new file mode 100644 index 0000000..822fd1f --- /dev/null +++ b/php_api/vendor/ircmaxell/password-compat/composer.json @@ -0,0 +1,20 @@ +{ + "name": "ircmaxell/password-compat", + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "keywords": ["password", "hashing"], + "homepage": "https://github.com/ircmaxell/password_compat", + "license": "MIT", + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "require-dev": { + "phpunit/phpunit": "4.*" + }, + "autoload": { + "files": ["lib/password.php"] + } +} diff --git a/php_api/vendor/ircmaxell/password-compat/lib/password.php b/php_api/vendor/ircmaxell/password-compat/lib/password.php new file mode 100644 index 0000000..cc6896c --- /dev/null +++ b/php_api/vendor/ircmaxell/password-compat/lib/password.php @@ -0,0 +1,314 @@ + + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @copyright 2012 The Authors + */ + +namespace { + + if (!defined('PASSWORD_BCRYPT')) { + /** + * PHPUnit Process isolation caches constants, but not function declarations. + * So we need to check if the constants are defined separately from + * the functions to enable supporting process isolation in userland + * code. + */ + define('PASSWORD_BCRYPT', 1); + define('PASSWORD_DEFAULT', PASSWORD_BCRYPT); + define('PASSWORD_BCRYPT_DEFAULT_COST', 10); + } + + if (!function_exists('password_hash')) { + + /** + * Hash the password using the specified algorithm + * + * @param string $password The password to hash + * @param int $algo The algorithm to use (Defined by PASSWORD_* constants) + * @param array $options The options for the algorithm to use + * + * @return string|false The hashed password, or false on error. + */ + function password_hash($password, $algo, array $options = array()) { + if (!function_exists('crypt')) { + trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING); + return null; + } + if (is_null($password) || is_int($password)) { + $password = (string) $password; + } + if (!is_string($password)) { + trigger_error("password_hash(): Password must be a string", E_USER_WARNING); + return null; + } + if (!is_int($algo)) { + trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING); + return null; + } + $resultLength = 0; + switch ($algo) { + case PASSWORD_BCRYPT: + $cost = PASSWORD_BCRYPT_DEFAULT_COST; + if (isset($options['cost'])) { + $cost = $options['cost']; + if ($cost < 4 || $cost > 31) { + trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING); + return null; + } + } + // The length of salt to generate + $raw_salt_len = 16; + // The length required in the final serialization + $required_salt_len = 22; + $hash_format = sprintf("$2y$%02d$", $cost); + // The expected length of the final crypt() output + $resultLength = 60; + break; + default: + trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING); + return null; + } + $salt_requires_encoding = false; + if (isset($options['salt'])) { + switch (gettype($options['salt'])) { + case 'NULL': + case 'boolean': + case 'integer': + case 'double': + case 'string': + $salt = (string) $options['salt']; + break; + case 'object': + if (method_exists($options['salt'], '__tostring')) { + $salt = (string) $options['salt']; + break; + } + case 'array': + case 'resource': + default: + trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING); + return null; + } + if (PasswordCompat\binary\_strlen($salt) < $required_salt_len) { + trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", PasswordCompat\binary\_strlen($salt), $required_salt_len), E_USER_WARNING); + return null; + } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) { + $salt_requires_encoding = true; + } + } else { + $buffer = ''; + $buffer_valid = false; + if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) { + $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) { + $buffer = openssl_random_pseudo_bytes($raw_salt_len); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && @is_readable('/dev/urandom')) { + $f = fopen('/dev/urandom', 'r'); + $read = PasswordCompat\binary\_strlen($buffer); + while ($read < $raw_salt_len) { + $buffer .= fread($f, $raw_salt_len - $read); + $read = PasswordCompat\binary\_strlen($buffer); + } + fclose($f); + if ($read >= $raw_salt_len) { + $buffer_valid = true; + } + } + if (!$buffer_valid || PasswordCompat\binary\_strlen($buffer) < $raw_salt_len) { + $bl = PasswordCompat\binary\_strlen($buffer); + for ($i = 0; $i < $raw_salt_len; $i++) { + if ($i < $bl) { + $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255)); + } else { + $buffer .= chr(mt_rand(0, 255)); + } + } + } + $salt = $buffer; + $salt_requires_encoding = true; + } + if ($salt_requires_encoding) { + // encode string with the Base64 variant used by crypt + $base64_digits = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + $bcrypt64_digits = + './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + $base64_string = base64_encode($salt); + $salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits); + } + $salt = PasswordCompat\binary\_substr($salt, 0, $required_salt_len); + + $hash = $hash_format . $salt; + + $ret = crypt($password, $hash); + + if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != $resultLength) { + return false; + } + + return $ret; + } + + /** + * Get information about the password hash. Returns an array of the information + * that was used to generate the password hash. + * + * array( + * 'algo' => 1, + * 'algoName' => 'bcrypt', + * 'options' => array( + * 'cost' => PASSWORD_BCRYPT_DEFAULT_COST, + * ), + * ) + * + * @param string $hash The password hash to extract info from + * + * @return array The array of information about the hash. + */ + function password_get_info($hash) { + $return = array( + 'algo' => 0, + 'algoName' => 'unknown', + 'options' => array(), + ); + if (PasswordCompat\binary\_substr($hash, 0, 4) == '$2y$' && PasswordCompat\binary\_strlen($hash) == 60) { + $return['algo'] = PASSWORD_BCRYPT; + $return['algoName'] = 'bcrypt'; + list($cost) = sscanf($hash, "$2y$%d$"); + $return['options']['cost'] = $cost; + } + return $return; + } + + /** + * Determine if the password hash needs to be rehashed according to the options provided + * + * If the answer is true, after validating the password using password_verify, rehash it. + * + * @param string $hash The hash to test + * @param int $algo The algorithm used for new password hashes + * @param array $options The options array passed to password_hash + * + * @return boolean True if the password needs to be rehashed. + */ + function password_needs_rehash($hash, $algo, array $options = array()) { + $info = password_get_info($hash); + if ($info['algo'] != $algo) { + return true; + } + switch ($algo) { + case PASSWORD_BCRYPT: + $cost = isset($options['cost']) ? $options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST; + if ($cost != $info['options']['cost']) { + return true; + } + break; + } + return false; + } + + /** + * Verify a password against a hash using a timing attack resistant approach + * + * @param string $password The password to verify + * @param string $hash The hash to verify against + * + * @return boolean If the password matches the hash + */ + function password_verify($password, $hash) { + if (!function_exists('crypt')) { + trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING); + return false; + } + $ret = crypt($password, $hash); + if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != PasswordCompat\binary\_strlen($hash) || PasswordCompat\binary\_strlen($ret) <= 13) { + return false; + } + + $status = 0; + for ($i = 0; $i < PasswordCompat\binary\_strlen($ret); $i++) { + $status |= (ord($ret[$i]) ^ ord($hash[$i])); + } + + return $status === 0; + } + } + +} + +namespace PasswordCompat\binary { + + if (!function_exists('PasswordCompat\\binary\\_strlen')) { + + /** + * Count the number of bytes in a string + * + * We cannot simply use strlen() for this, because it might be overwritten by the mbstring extension. + * In this case, strlen() will count the number of *characters* based on the internal encoding. A + * sequence of bytes might be regarded as a single multibyte character. + * + * @param string $binary_string The input string + * + * @internal + * @return int The number of bytes + */ + function _strlen($binary_string) { + if (function_exists('mb_strlen')) { + return mb_strlen($binary_string, '8bit'); + } + return strlen($binary_string); + } + + /** + * Get a substring based on byte limits + * + * @see _strlen() + * + * @param string $binary_string The input string + * @param int $start + * @param int $length + * + * @internal + * @return string The substring + */ + function _substr($binary_string, $start, $length) { + if (function_exists('mb_substr')) { + return mb_substr($binary_string, $start, $length, '8bit'); + } + return substr($binary_string, $start, $length); + } + + /** + * Check if current PHP version is compatible with the library + * + * @return boolean the check result + */ + function check() { + static $pass = NULL; + + if (is_null($pass)) { + if (function_exists('crypt')) { + $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG'; + $test = crypt("password", $hash); + $pass = $test == $hash; + } else { + $pass = false; + } + } + return $pass; + } + + } +} \ No newline at end of file diff --git a/php_api/vendor/ircmaxell/password-compat/version-test.php b/php_api/vendor/ircmaxell/password-compat/version-test.php new file mode 100644 index 0000000..96f60ca --- /dev/null +++ b/php_api/vendor/ircmaxell/password-compat/version-test.php @@ -0,0 +1,6 @@ + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/php_api/vendor/milux/spdo/README.md b/php_api/vendor/milux/spdo/README.md new file mode 100644 index 0000000..fd2d85f --- /dev/null +++ b/php_api/vendor/milux/spdo/README.md @@ -0,0 +1,2 @@ +# spdo +A static, simple PDO wrapper for easy database operations diff --git a/php_api/vendor/milux/spdo/composer.json b/php_api/vendor/milux/spdo/composer.json new file mode 100644 index 0000000..13661d5 --- /dev/null +++ b/php_api/vendor/milux/spdo/composer.json @@ -0,0 +1,23 @@ +{ + "name": "milux/spdo", + "type": "library", + "description": "A static, simple PDO wrapper for easy database operations", + "keywords": ["pdo", "sql", "database"], + "homepage": "https://github.com/milux/spdo", + "license": "GPLv3", + "authors": [ + { + "name": "Michael Lux", + "email": "michi.lux@gmail.com", + "role": "Developer" + } + ], + "require": { + "php": ">=5.3.0" + }, + "autoload": { + "psr-0": { + "milux": "src" + } + } +} \ No newline at end of file diff --git a/php_api/vendor/milux/spdo/src/milux/spdo/SPDO.php b/php_api/vendor/milux/spdo/src/milux/spdo/SPDO.php new file mode 100644 index 0000000..9e524c6 --- /dev/null +++ b/php_api/vendor/milux/spdo/src/milux/spdo/SPDO.php @@ -0,0 +1,223 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +namespace milux\spdo; + +class SPDO { + + const LEVEL_READ_UNCOMMITTED = 'READ UNCOMMITTED'; + const LEVEL_READ_COMMITTED = 'READ COMMITTED'; + const LEVEL_REPEATABLE_READ = 'REPEATABLE READ'; + const LEVEL_SERIALIZABLE = 'SERIALIZABLE'; + + /** + * @var SPDOConnection shared database connection + */ + private static $instance = null; + + /** + * @var SPDOConfig Configuration object + */ + private static $config = null; + + /** + * Set the SPDOConfig instance that is used to get the database connection configuration + * + * @param SPDOConfig $config A configuration object + */ + public static function setConfig(SPDOConfig $config) { + self::$config = $config; + } + + /** + * Get the SPDOConfig instance that is currently in use + * + * @return SPDOConfig The configuration object + */ + public static function getConfig() { + return self::$config; + } + + /** + * Creates/returns the shared DB connection + * + * @return SPDOConnection the new DB connection + * @throws SPDOException + */ + public static function getInstance() { + if (self::$instance === null) { + if (self::$config === null) { + throw new SPDOException('No configuration provided, call setConfigClass() first!'); + } + if (!self::$config instanceof SPDOConfig) { + throw new SPDOException(self::$config . ' is not an instance of SPDOConfig!'); + } + self::$instance = self::$config->newSPDOConnection(); + } + return self::$instance; + } + + /** + * enables the returning of insert ids by insert() and batchInsert() + */ + public static function returnInsertIDs() { + self::getInstance()->returnInsertIDs(); + } + + /** + * Helper to perform some function as transaction. + * + * @param callable $function The function to execute as DB transaction + * @param string $level The explicit transaction isolation level + * + * @return mixed Function return value + * @throws \Exception Re-thrown Exception if transaction fails + */ + public static function ta(callable $function, $level = null) { + return self::getInstance()->ta($function, $level); + } + + /** + * Shortcut for PDO::beginTransaction(); + * + * @param string $level The explicit transaction isolation level + * + * @return bool success of transaction command + */ + public static function begin($level = null) { + return self::getInstance()->begin($level); + } + + /** + * PDO::commit(); + * + * @return bool success of transaction command + */ + public static function commit() { + return self::getInstance()->commit(); + } + + /** + * shortcut for PDO::rollBack(); + * + * @return bool success of transaction command + */ + public static function abort() { + return self::getInstance()->abort(); + } + + /** + * This function automatically inserts/updates data depending on a set of key columns/values. + * If one or more row(s) with certain values in certain columns as specified by $keyColumnMap + * exist in $table, the data of $dataColumnMap is UPDATEd to the values of the latter. + * Otherwise, $keyColumnMap and $dataColumnMap are combined and INSERTed into $table. + * If $dataColumnMap is omitted, this function has a "INSERT-if-not-exists" behaviour. + * + * @param string $table name of the table to update or insert into + * @param array $keyColumnMap column-value-map for key columns to test + * @param array $dataColumnMap [optional] column-value-map for non-key columns + * + * @return int|SPDOStatement the statement of the INSERT/UPDATE query or the insert ID of the new row + */ + public static function save($table, array $keyColumnMap, array $dataColumnMap = array()) { + return self::getInstance()->save($table, $keyColumnMap, $dataColumnMap); + } + + /** + * constructs and performs an UPDATE query on a given table + * + * @param string $table name of the table to update + * @param array $columnValueMap map of column names and values to set + * @param string $whereStmt an optional WHERE statement for the update, parameters MUST be bound with "?" + * @param array $whereParams optional parameters to be passed for the WHERE statement + * + * @return SPDOStatement the result statement of the UPDATE query + * @throws SPDOException + */ + public static function update($table, $columnValueMap, $whereStmt = null, array $whereParams = array()) { + return self::getInstance()->update($table, $columnValueMap, $whereStmt, $whereParams); + } + + /** + * constructs and performs an INSERT query on a given table + * + * @param string $table name of the table to update + * @param array $columnValueMap map of column names (keys) and values to insert + * + * @return int|SPDOStatement the result statement of the INSERT or the insert ID of the new row + */ + public static function insert($table, array $columnValueMap) { + return self::getInstance()->insert($table, $columnValueMap); + } + + /** + * do multiple INSERTS into specified columns
+ * NOTE: non-array entries in parameter 2 ($columnValuesMap) + * are automatically expanded to arrays of suitable length! + * + * @param string $table name of the INSERT target table + * @param array $columnValuesMap map of the form "column => array(values)" or "column => value" + * @param mixed $insertIdName [optional] parameter for PDO::lastInsertId() + * + * @return array|SPDOStatement depending on the state of this SPDOConnection instance, + * an array of insert IDs or the statement object used for the INSERTs is returned + * @throws SPDOException in case of malformed $columnValuesMap + */ + public static function batchInsert($table, array $columnValuesMap, $insertIdName = null) { + return self::getInstance()->batchInsert($table, $columnValuesMap, $insertIdName); + } + + /** + * constructs and performs a DELETE query on a given table + * + * @param string $table name of the table to DELETE from + * @param string $whereClause the WHERE clause of the query + * @param array $whereParams the parameters for the WHERE query + * + * @return SPDOStatement + */ + public static function delete($table, $whereClause = null, array $whereParams = array()) { + return self::getInstance()->delete($table, $whereClause, $whereParams); + } + + /** + * PDO::query() on common PDO object + * + * @param string $sql + * + * @return SPDOStatement query result + */ + public static function query($sql) { + return self::getInstance()->query($sql); + } + + /** + * PDO::exec() on common PDO object + * + * @param string $sql + * + * @return int number of processed lines + */ + public static function exec($sql) { + return self::getInstance()->exec($sql); + } + + /** + * PDO::prepare() on common PDO object + * + * @param string $sql SQL command to prepare + * @param array $driver_options Additional driver options to pass to the DB + * + * @return SPDOStatement prepared statement + */ + public static function prepare($sql, array $driver_options = array()) { + return self::getInstance()->prepare($sql, $driver_options); + } + +} diff --git a/php_api/vendor/milux/spdo/src/milux/spdo/SPDOConfig.php b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOConfig.php new file mode 100644 index 0000000..27b6a65 --- /dev/null +++ b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOConfig.php @@ -0,0 +1,63 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +namespace milux\spdo; + +abstract class SPDOConfig { + + /** + * @return string hostname of the database + */ + public abstract function getHost(); + + /** + * @return string username for login + */ + public abstract function getUser(); + + /** + * @return string password for login + */ + public abstract function getPassword(); + + /** + * @return string selected database schema + */ + public abstract function getSchema(); + + /** + * Pre-processes SQL strings, for example to replace prefix placeholders of table names + * + * @param $sql string unprocessed SQL + * + * @return string processed SQL + */ + public abstract function preProcess($sql); + + /** + * Returns a newly created SPDOConnection + * + * @return SPDOConnection either a SPDOConnection or a subclass with different/extended functionality + */ + public function newSPDOConnection() { + return new SPDOConnection($this); + } + + /** + * Returns a newly created SPDOStatement + * + * @param \PDOStatement $pdoStatement the raw PDOStatement + * + * @return SPDOStatement either a SPDOStatement or a subclass with different/extended functionality + */ + public function newSPDOStatement($pdoStatement) { + return new SPDOStatement($pdoStatement); + } + +} \ No newline at end of file diff --git a/php_api/vendor/milux/spdo/src/milux/spdo/SPDOConnection.php b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOConnection.php new file mode 100644 index 0000000..9be88f5 --- /dev/null +++ b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOConnection.php @@ -0,0 +1,334 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +namespace milux\spdo; + +class SPDOConnection { + + protected static $typeMap = array( + 'boolean' => \PDO::PARAM_BOOL, + 'integer' => \PDO::PARAM_INT, + 'double' => \PDO::PARAM_STR, + 'string' => \PDO::PARAM_STR, + 'NULL' => \PDO::PARAM_NULL + ); + + public static function getTypes(array $values) { + $typeMap = self::$typeMap; + return array_map(function ($v) use($typeMap) { + $type = gettype($v); + return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR; + }, $values); + } + + /** + * @var \PDO the PDO object which is encapsulated by this decorator + */ + protected $pdo = null; + /** + * @var SPDOConfig the configuration object for this connection + */ + protected $configObject = null; + //whether to enable insert id fetching + protected $insertIDs = false; + + /** + * SPDOConnection constructor + * + * @param SPDOConfig $configObject the configuration object for this SPDOConnection + */ + public function __construct(SPDOConfig $configObject) { + $this->configObject = $configObject; + //initialize internal PDO object + $this->pdo = new \PDO( + 'mysql:host=' . $configObject->getHost() . ';dbname=' . $configObject->getSchema(), + $configObject->getUser(), + $configObject->getPassword(), + array( + \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', + \PDO::ATTR_PERSISTENT => true + ) + ); + $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + } + + /** + * enables the returning of insert ids by insert() and batchInsert() + */ + public function returnInsertIDs() { + $this->insertIDs = true; + } + + /** + * Helper to perform some function as transaction. + * + * @param callable $function The function to execute as DB transaction + * @param string $level The explicit transaction isolation level + * + * @return mixed Function return value + * @throws \Exception Re-thrown Exception if transaction fails + */ + public function ta(callable $function, $level = null) { + try { + $this->begin($level); + $result = $function(); + $this->commit(); + return $result; + } catch (\Exception $e) { + $this->abort(); + throw $e; + } + } + + /** + * Shortcut for PDO::beginTransaction(); + * + * @param string $level The explicit transaction isolation level + * + * @return bool success of transaction command + */ + public function begin($level = null) { + $res = $this->pdo->beginTransaction(); + if (isset($level)) { + $this->query('SET TRANSACTION ISOLATION LEVEL ' . $level); + } + return $res; + } + + /** + * PDO::commit(); + * + * @return bool success of transaction command + */ + public function commit() { + return $this->pdo->commit(); + } + + /** + * shortcut for PDO::rollBack(); + * + * @return bool success of transaction command + */ + public function abort() { + return $this->pdo->rollBack(); + } + + /** + * This function automatically inserts/updates data depending on a set of key columns/values. + * If one or more row(s) with certain values in certain columns as specified by $keyColumnMap + * exist in $table, the data of $dataColumnMap is UPDATEd to the values of the latter. + * Otherwise, $keyColumnMap and $dataColumnMap are combined and INSERTed into $table. + * If $dataColumnMap is omitted, this function has a "INSERT-if-not-exists" behaviour. + * + * @param string $table name of the table to update or insert into + * @param array $keyColumnMap column-value-map for key columns to test + * @param array $dataColumnMap [optional] column-value-map for non-key columns + * @return int|null|SPDOStatement + */ + public function save($table, array $keyColumnMap, array $dataColumnMap = array()) { + //assemble WHERE clause from $keyColumnMap + $whereClause = implode(' AND ', array_map(function ($c) { + return $c . ' = ?'; + }, array_keys($keyColumnMap))); + //extract values from keyColumnMap for WHERE parametrization + $whereParams = array_values($keyColumnMap); + //check if row with specified key values exists + $checkValue = $this->prepare('SELECT COUNT(*) FROM ' . $table . ' WHERE ' . $whereClause) + ->execute($whereParams)->cell(); + if ($checkValue === '0') { + //no row(s) found, perform insert with combined map + return $this->insert($table, $dataColumnMap + $keyColumnMap); + } else if(!empty($dataColumnMap)) { + //row(s) found, perform update + return $this->update($table, $dataColumnMap, $whereClause, $whereParams); + } else { + return null; + } + } + + /** + * constructs and performs an UPDATE query on a given table + * + * @param string $table name of the table to update + * @param array $columnValueMap map of column names (keys) and values to set + * @param string $whereStmt an optional WHERE statement for the update, parameters MUST be bound with "?" + * @param array $whereParams optional parameters to be passed for the WHERE statement + * @return SPDOStatement the result statement of the UPDATE query + */ + public function update($table, array $columnValueMap, $whereStmt = null, array $whereParams = array()) { + //assemble set instructions + $setInstructions = array_map(function ($c) { + return $c . ' = ?'; + }, array_keys($columnValueMap)); + //"isolate" parameter values + $params = array_values($columnValueMap); + //assemble UPDATE sql query + $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $setInstructions); + //append WHERE query, if neccessary + if(isset($whereStmt)) { + $sql .= ' WHERE ' . $whereStmt; + //append WHERE parameters to parameter array + $params = array_merge($params, array_values($whereParams)); + } + //prepare, bind values and execute the UPDATE + return $this->prepare($sql)->bindTyped($params)->execute(); + } + + /** + * Constructs and performs an INSERT query on a given table + * + * @param string $table Name of the table to update + * @param array $columnValueMap Map of column names (keys) and values to insert + * @param string $insertIdName The name of the column or DB object that is auto-incremented + * + * @return int|SPDOStatement Depending on the state of this SPDOConnection instance, + * an insert ID or the statement object of the performed INSERT is returned + */ + public function insert($table, array $columnValueMap, $insertIdName = null) { + //prepare, bind values and execute the INSERT + $stmt = $this->prepare('INSERT INTO ' . $table + . ' (' . implode(', ', array_keys($columnValueMap)) . ') ' + . 'VALUES (' . implode(', ', array_fill(0, count($columnValueMap), '?')) . ')') + ->bindTyped($columnValueMap)->execute(); + //return execution result + return $this->insertIDs ? $this->pdo->lastInsertId($insertIdName) : $stmt; + } + + /** + * do multiple INSERTS into specified columns
+ * NOTE: non-array entries in parameter 2 ($columnValuesMap) + * are automatically expanded to arrays of suitable length! + * + * @param string $table name of the INSERT target table + * @param array $columnValuesMap map of the form "column => array(values)" or "column => value" + * @param mixed $insertIdName [optional] parameter for PDO::lastInsertId() + * + * @return array|SPDOStatement depending on the state of this SPDOConnection instance, + * an array of insert IDs or the statement object used for the INSERTs is returned + * @throws SPDOException in case of malformed $columnValuesMap + */ + public function batchInsert($table, array $columnValuesMap, $insertIdName = null) { + //pre-checks of size + $batchSize = 0; + foreach($columnValuesMap as $a) { + if(is_array($a)) { + if($batchSize === 0) { + $batchSize = count($a); + } else { + if($batchSize !== count($a)) { + throw new SPDOException('SPDOConnection::batchInsert() called with arrays of unequal length'); + } + } + } + } + if($batchSize === 0) { + throw new SPDOException('No array was found in $columnValuesMap passed to SPDOConnection::batchInsert()'); + } else { + //expand non-array values to arrays of appropriate size + foreach($columnValuesMap as &$a) { + if(!is_array($a)) { + $a = array_fill(0, $batchSize, $a); + } + } + } + //construct and prepare insert statement + $stmt = $this->prepare('INSERT INTO ' . $table + . ' (' . implode(', ', array_keys($columnValuesMap)) . ') ' + . 'VALUES (' . implode(', ', array_fill(0, count($columnValuesMap), '?')) . ')'); + //bind uses for the closure to vars + $pdoInstance = $this->pdo; + $returnIDs = $this->insertIDs; + //get sample data types by applying reset() an each values-array + $types = self::getTypes(array_map('reset', $columnValuesMap)); + //prepend null to align $type array with bind counter + array_unshift($types, null); + $batchClosure = function () use ($stmt, $pdoInstance, $returnIDs, $insertIdName, $types) { + $bindCounter = 1; + //bind all values + foreach(func_get_args() as $v) { + $stmt->bindValue($bindCounter, $v, $types[$bindCounter]); + $bindCounter++; + } + //execute insert + $stmt->execute(); + //fetch insert id if requested + return $returnIDs ? $pdoInstance->lastInsertId($insertIdName) : null; + }; + //unshift the closure into the columns map + array_unshift($columnValuesMap, $batchClosure); + //use array_map to apply column-value-maps to the batch closure + $insertIDs = call_user_func_array('array_map', $columnValuesMap); + //return insert id array or statement + return $returnIDs ? $insertIDs : $stmt; + } + + /** + * constructs and performs a DELETE query on a given table + * + * @param string $table name of the table to DELETE from + * @param string $whereClause the WHERE clause of the query + * @param array $whereParams the parameters for the WHERE query + * + * @return SPDOStatement + */ + public function delete($table, $whereClause = null, array $whereParams = array()) { + $sql = 'DELETE FROM ' . $table; + if(isset($whereClause)) { + $sql .= ' WHERE ' . $whereClause; + } + return $this->prepare($sql)->execute($whereParams); + } + + /** + * PDO::query() on common PDO object + * + * @param string $sql + * @return SPDOStatement|\PDOStatement + * @throws SPDOException + */ + public function query($sql) { + try { + return new SPDOStatement($this->pdo->query($this->configObject->preProcess($sql))); + } catch(\PDOException $e) { + throw new SPDOException($e); + } + } + + /** + * PDO::exec() on common PDO object + * + * @param string $sql + * @return int number of processed lines + * @throws SPDOException + */ + public function exec($sql) { + try { + return $this->pdo->exec($this->configObject->preProcess($sql)); + } catch(\PDOException $e) { + throw new SPDOException($e); + } + } + + /** + * PDO::prepare() on common PDO object + * + * @param string $sql + * @param array $driver_options + * @return SPDOStatement|\PDOStatement prepared statement + * @throws SPDOException + */ + public function prepare($sql, array $driver_options = array()) { + try { + return new SPDOStatement($this->pdo->prepare($this->configObject->preProcess($sql), $driver_options)); + } catch(\PDOException $e) { + throw new SPDOException($e); + } + } + +} \ No newline at end of file diff --git a/php_api/vendor/milux/spdo/src/milux/spdo/SPDOException.php b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOException.php new file mode 100644 index 0000000..8268b06 --- /dev/null +++ b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOException.php @@ -0,0 +1,34 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +namespace milux\spdo; + +class SPDOException extends \Exception { + + /** + * SPDOException constructor. + * + * @param string|\PDOException $e error message or PDOException + * @param int $code error code + * @param \Exception $previous previous exception + */ + public function __construct($e, $code = 0, $previous = null) { + if($e instanceof \PDOException) { + parent::__construct($e->getMessage(), (int)$e->getCode(), $e); + $this->code = $e->getCode(); + $this->message = $e->getMessage(); + $trace = $e->getTrace(); + $this->file = $trace[1]['file']; + $this->line = $trace[1]['line']; + } else { + parent::__construct($e, $code, $previous); + } + } + +} \ No newline at end of file diff --git a/php_api/vendor/milux/spdo/src/milux/spdo/SPDOStatement.php b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOStatement.php new file mode 100644 index 0000000..51ce600 --- /dev/null +++ b/php_api/vendor/milux/spdo/src/milux/spdo/SPDOStatement.php @@ -0,0 +1,403 @@ + + * @copyright Copyright (c) 2017 Michael Lux + * @license GNU/GPLv3 + */ + +namespace milux\spdo; + +class SPDOStatement { + + /** + * @var \PDOStatement + */ + private $statement; + //nesting level (groups) for advanced data handling + private $nesting = 0; + //data structures for advanced data handling + private $availableColumns = null; + private $data = null; + //marker for call to transform() + private $transformed = false; + //buffer for iterating with cell() + private $line = null; + + public function __construct($statement) { + $this->statement = $statement; + } + + /** + * Helper function to bind an array of values to this statement + * + * @param array $toBind Parameters to bind + * + * @return SPDOStatement + */ + public function bindTyped(array $toBind) { + $bindCount = 1; + foreach(array_combine(SPDOConnection::getTypes($toBind), $toBind) as $t => $v) { + $this->statement->bindValue($bindCount++, $v, $t); + } + return $this; + } + + /** + * modified execute() which returns the underlying PDOStatement object on success, + * thus making the execute command "chainable" + * + * @param mixed $argument [optional] might be an array or + * the first of an arbitrary number of parameters for binding + * + * @return SPDOStatement + * @throws SPDOException + */ + public function execute($argument = null) { + if(isset($this->data)) { + //reset the statement object if necessary + $this->nesting = 0; + $this->availableColumns = null; + $this->data = null; + $this->transformed = false; + $this->line = null; + } + try { + if(!isset($argument)) { + $this->statement->execute(); + } elseif(is_array($argument)) { + $this->statement->execute($argument); + } else { + $this->statement->execute(func_get_args()); + } + return $this; + } catch(\PDOException $e) { + throw new SPDOException($e); + } + } + + /** + * Ensures that data is available for processing + */ + public function init() { + if(!isset($this->data)) { + //fetch data for further processing + $this->data = $this->statement->fetchAll(\PDO::FETCH_ASSOC); + //check for empty result + if(!empty($this->data)) { + //save column names as keys and values of lookup array + $this->availableColumns = array_combine(array_keys($this->data[0]), array_keys($this->data[0])); + } + } + } + + /** + * Helper function to immerse into the nested structure until data dimension after group() + * + * @param callback $callback the callback to apply at the innermost dimension + * @param int $level [optional] the levels to immerse before the callback is applied, + * defaults to the number of previous group operations + * (e.g. the total number of array elements passed to group()) + * @return array modified copy of the internal data structure + */ + public function immerse($callback, $level = null) { + $this->init(); + //check for empty result + if(empty($this->data)) { + return $this->data; + } + if(!isset($level)) { + $level = $this->nesting; + } + //recursive immersion closure + $immerse = function ($data, $callback, $level) use (&$immerse) { + if ($level === 0) { + /** @noinspection PhpParamsInspection */ + return $callback($data); + } else { + foreach($data as &$d) { + $d = $immerse($d, $callback, $level - 1); + } + return $data; + } + }; + return $immerse($this->data, $callback, $level); + } + + /** + * Groups data into subarrays by given column name(s), + * generating nested map (array) structures. + * + * @param array $groups + * + * @return SPDOStatement + * @throws SPDOException + */ + public function group(array $groups) { + $this->init(); + //check for empty result + if(empty($this->data)) { + return $this; + } + if($this->statement->columnCount() <= $this->nesting + count($groups)) { + throw new SPDOException('Cannot do more than ' . ($this->statement->columnCount() - 1) + . ' group operations for ' . $this->statement->columnCount() . ' columns.' + . ' Use getUnique() or immerse() with custom callback retrieve flat structure!'); + } + if($this->transformed) { + throw new SPDOException('Cannot safely group transformed elements, transform() must be called after group!'); + } + $cols = $this->availableColumns; + foreach($groups as $g) { + if(!isset($cols[$g])) { + throw new SPDOException('Grouping column ' . $g . ' not available!'); + } else { + unset($cols[$g]); + } + } + $this->data = $this->immerse(function ($data) use ($groups) { + //recursive closure for grouping + $groupClosure = function($data, array $groups) use (&$groupClosure) { + $group = array_shift($groups); + $result = array(); + foreach($data as $rec) { + if(!isset($rec[$group])) { + throw new SPDOException($group . ': ' . json_encode($rec)); + } + $key = $rec[$group]; + if(!isset($result[$key])) { + $result[$key] = array(); + } + unset($rec[$group]); + $result[$key][] = $rec; + } + //recursion: direcly iterate over the grouped maps with further groups + if(!empty($groups)) { + foreach($result as &$d) { + $d = $groupClosure($d, $groups); + } + } + return $result; + }; + return $groupClosure($data, $groups); + }); + //correct available columns after grouping + $this->availableColumns = $cols; + //increase nesting level + $this->nesting += count($groups); + //return $this for method chaining + return $this; + } + + public function filter($callback) { + $this->init(); + //check for empty result + if(empty($this->data)) { + return $this; + } + $this->data = $this->immerse(function ($data) use ($callback) { + return array_values(array_filter($data, $callback)); + }); + return $this; + } + + /** + * Sets the PHP data type of specified columns + * + * @param array $typeMap map of column names (keys) and types to set (values) + * @return SPDOStatement + * @throws SPDOException + */ + public function cast($typeMap) { + $this->init(); + //check for empty result + if(empty($this->data)) { + return $this; + } + foreach(array_keys($typeMap) as $c) { + if(!isset($this->availableColumns[$c])) { + throw new SPDOException('Casting column ' . $c . ' not available!'); + } + } + $this->data = $this->immerse(function ($data) use ($typeMap) { + foreach($data as &$d) { + foreach($typeMap as $c => $t) { + settype($d[$c], $t); + } + } + return $data; + }); + return $this; + } + + /** + * Applies callbacks to specified columns
+ * ATTENTION: Modifying a column to a non-primitive type and using it for grouping, + * reducing, etc. can cause undefined behaviour! + * + * @param array $callbackMap map of column names (keys) and callbacks to apply (values) + * @return SPDOStatement + * @throws SPDOException + */ + public function mod($callbackMap) { + $this->init(); + //check for empty result + if(empty($this->data)) { + return $this; + } + foreach(array_keys($callbackMap) as $c) { + if(!isset($this->availableColumns[$c])) { + throw new SPDOException('Casting column ' . $c . ' not available!'); + } + } + $this->data = $this->immerse(function ($data) use ($callbackMap) { + foreach($data as &$d) { + foreach($callbackMap as $co => $cb) { + $d[$co] = call_user_func($cb, $d[$co]); + } + } + return $data; + }); + return $this; + } + + /** + * Tranforms the innermost dimension elements (initially maps) + * by tranforming them with the given callback function.
+ * ATTENTION: group(), getObjects() and getUnique(true) cannot be used after this operation! + * + * @param callback $callback callback accepting exactly one element + * @return SPDOStatement + */ + public function transform($callback) { + $this->transformed = true; + $this->data = $this->immerse(function ($data) use ($callback) { + foreach($data as &$d) { + $d = $callback($d); + } + return $data; + }); + return $this; + } + + /** + * get next cell of data set + * + * @param bool $reset setting this parameter to true will reset the array pointers + * (required for first call) + * @return mixed + * @throws SPDOException + */ + public function cell($reset = false) { + if($this->nesting > 0) { + throw new SPDOException('Cannot interate over cells after group()!'); + } + if($this->transformed) { + throw new SPDOException('Cannot safely interate over cells after transform()!'); + } + $this->init(); + if($reset) { + reset($this->data); + } + //iteration logic + if(!isset($this->line) || $reset) { + //if line is not set, use each() over data to get next line + $eachOut = each($this->data); + if($eachOut === false) { + return false; + } else { + $this->line = $eachOut[1]; + reset($this->line); + } + } + $eachIn = each($this->line); + if($eachIn === false) { + //set $this->line to null and do one-step-recursion to get next cell + $this->line = null; + return $this->cell(); + } else { + //return cell + return $eachIn[1]; + } + } + + /** + * Returns the manipulated data as hold in this statement. + * The innermost dimension usually consists of maps (assoc. arrays). + * This is different if transform() was called on this statement with non-array callback return type. + * + * @param bool $reduce whether to reduce one-element-arrays to their value + * @return array manipulated data as hold in this statement object + */ + public function get($reduce = true) { + $this->init(); + if(!$this->transformed && $this->statement->columnCount() === $this->nesting + 1 && $reduce) { + return $this->immerse(function ($data) { + //reduce 1-element-maps to their value + foreach($data as &$cell) { + $cell = reset($cell); + } + return $data; + }); + } else { + return $this->data; + } + } + + public function getUnique($reduce = true) { + if(!$this->transformed && $this->statement->columnCount() === $this->nesting + 1 && $reduce) { + return $this->immerse(function ($data) { + //reduce 1-element-maps inside 1-element-arrays to their value + if(count($data) === 1) { + return reset(reset($data)); + } else { + throw new SPDOException('Unique fetch failed, map with more than one element was found!'); + } + }); + } else { + //reduce 1-element-arrays to their value + return $this->immerse(function ($data) { + if(count($data) === 1) { + return reset($data); + } else { + throw new SPDOException('Unique fetch failed, map with more than one element found!'); + } + }); + } + } + + public function getObjects() { + if($this->transformed) { + throw new SPDOException('Cannot safely cast transformed elements, use transform() call for object casting!'); + } + //simply cast to objects + return $this->immerse(function ($data) { + foreach($data as &$d) { + $d = (object)$d; + } + return $data; + }); + } + + public function getFunc($callback) { + return $this->immerse(function ($data) use ($callback) { + foreach($data as &$d) { + $d = $callback($d); + } + return $data; + }); + } + + /** + * Passes the parameter binding to the underlying statement + * + * @param string $parameter The number/name of the bind parameter + * @param mixed $value The value that is bound + * @param int $data_type The PDO data type + */ + public function bindValue($parameter, $value, $data_type) { + $this->statement->bindValue($parameter, $value, $data_type); + } + +}