Merge branch 'rewrite' into 'master'
authortelegnom <max@telegnom.org>
Sat, 2 Dec 2017 14:55:42 +0000 (15:55 +0100)
committertelegnom <max@telegnom.org>
Sat, 2 Dec 2017 14:55:42 +0000 (15:55 +0100)
Rewrite

See merge request ccc-ffm/memberdb!1

106 files changed:
.gitignore
README [deleted file]
README.md [new file with mode: 0644]
UPGRADE.txt [deleted file]
composer.json
config.php.sample [deleted file]
config.sample.php [new file with mode: 0644]
images/activity_indicator.gif [deleted file]
include/autoload.php [new file with mode: 0644]
include/cryptography.php
include/database.php
include/directdebit.php
include/earnings.php
include/events.php
include/expenses.php
include/fees.php
include/finances.php
include/html.php
include/includes.php [new file with mode: 0644]
include/installation.php [deleted file]
include/members.php
include/misc.php
include/payments.php
include/xlsexport.php
index.php [deleted file]
install.sql [new file with mode: 0644]
js/crypto-js/VERSION [deleted file]
js/crypto-js/aes/aes-min.js [deleted file]
js/crypto-js/aes/aes.js [deleted file]
js/crypto-js/aes/aes_modified.js [deleted file]
js/crypto-js/cbc/cbc-min.js [deleted file]
js/crypto-js/cbc/cbc.js [deleted file]
js/crypto-js/crypto-md5/crypto-md5.js [deleted file]
js/crypto-js/crypto-sha1-hmac-pbkdf2-marc4/crypto-sha1-hmac-pbkdf2-marc4.js [deleted file]
js/crypto-js/crypto-sha1-hmac-pbkdf2-ofb-aes/crypto-sha1-hmac-pbkdf2-ofb-aes.js [deleted file]
js/crypto-js/crypto-sha1-hmac-pbkdf2-rabbit/crypto-sha1-hmac-pbkdf2-rabbit.js [deleted file]
js/crypto-js/crypto-sha1-hmac-pbkdf2/crypto-sha1-hmac-pbkdf2.js [deleted file]
js/crypto-js/crypto-sha1/crypto-sha1.js [deleted file]
js/crypto-js/crypto-sha256/crypto-sha256.js [deleted file]
js/crypto-js/crypto/crypto-min.js [deleted file]
js/crypto-js/crypto/crypto.js [deleted file]
js/crypto-js/hmac/hmac-min.js [deleted file]
js/crypto-js/hmac/hmac.js [deleted file]
js/crypto-js/marc4/marc4-min.js [deleted file]
js/crypto-js/marc4/marc4.js [deleted file]
js/crypto-js/md5/md5-min.js [deleted file]
js/crypto-js/md5/md5.js [deleted file]
js/crypto-js/ofb/ofb-min.js [deleted file]
js/crypto-js/ofb/ofb.js [deleted file]
js/crypto-js/pbkdf2/pbkdf2-min.js [deleted file]
js/crypto-js/pbkdf2/pbkdf2.js [deleted file]
js/crypto-js/rabbit/rabbit-min.js [deleted file]
js/crypto-js/rabbit/rabbit.js [deleted file]
js/crypto-js/sha1/sha1-min.js [deleted file]
js/crypto-js/sha1/sha1.js [deleted file]
js/crypto-js/sha256/sha256-min.js [deleted file]
js/crypto-js/sha256/sha256.js [deleted file]
js/date.js [deleted file]
js/dtaus.js [deleted file]
js/jquery-1.4.2.min.js [deleted file]
js/sepa-CORE.js [deleted file]
js/sepa-CORE.xml [deleted file]
js/utils.js [deleted file]
public/assets/css/style.css [new file with mode: 0644]
public/assets/images/activity_indicator.gif [new file with mode: 0644]
public/assets/js/crypto-js/VERSION [new file with mode: 0644]
public/assets/js/crypto-js/aes/aes-min.js [new file with mode: 0755]
public/assets/js/crypto-js/aes/aes.js [new file with mode: 0755]
public/assets/js/crypto-js/aes/aes_modified.js [new file with mode: 0755]
public/assets/js/crypto-js/cbc/cbc-min.js [new file with mode: 0755]
public/assets/js/crypto-js/cbc/cbc.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto-md5/crypto-md5.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto-sha1-hmac-pbkdf2-marc4/crypto-sha1-hmac-pbkdf2-marc4.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto-sha1-hmac-pbkdf2-ofb-aes/crypto-sha1-hmac-pbkdf2-ofb-aes.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto-sha1-hmac-pbkdf2-rabbit/crypto-sha1-hmac-pbkdf2-rabbit.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto-sha1-hmac-pbkdf2/crypto-sha1-hmac-pbkdf2.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto-sha1/crypto-sha1.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto-sha256/crypto-sha256.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto/crypto-min.js [new file with mode: 0755]
public/assets/js/crypto-js/crypto/crypto.js [new file with mode: 0755]
public/assets/js/crypto-js/hmac/hmac-min.js [new file with mode: 0755]
public/assets/js/crypto-js/hmac/hmac.js [new file with mode: 0755]
public/assets/js/crypto-js/marc4/marc4-min.js [new file with mode: 0755]
public/assets/js/crypto-js/marc4/marc4.js [new file with mode: 0755]
public/assets/js/crypto-js/md5/md5-min.js [new file with mode: 0755]
public/assets/js/crypto-js/md5/md5.js [new file with mode: 0755]
public/assets/js/crypto-js/ofb/ofb-min.js [new file with mode: 0755]
public/assets/js/crypto-js/ofb/ofb.js [new file with mode: 0755]
public/assets/js/crypto-js/pbkdf2/pbkdf2-min.js [new file with mode: 0755]
public/assets/js/crypto-js/pbkdf2/pbkdf2.js [new file with mode: 0755]
public/assets/js/crypto-js/rabbit/rabbit-min.js [new file with mode: 0755]
public/assets/js/crypto-js/rabbit/rabbit.js [new file with mode: 0755]
public/assets/js/crypto-js/sha1/sha1-min.js [new file with mode: 0755]
public/assets/js/crypto-js/sha1/sha1.js [new file with mode: 0755]
public/assets/js/crypto-js/sha256/sha256-min.js [new file with mode: 0755]
public/assets/js/crypto-js/sha256/sha256.js [new file with mode: 0755]
public/assets/js/date.js [new file with mode: 0644]
public/assets/js/dtaus.js [new file with mode: 0644]
public/assets/js/jquery-1.4.2.min.js [new file with mode: 0644]
public/assets/js/sepa-CORE.js [new file with mode: 0644]
public/assets/js/sepa-CORE.xml [new file with mode: 0644]
public/assets/js/utils.js [new file with mode: 0644]
public/index.php [new file with mode: 0644]
src/Config/Config.php [new file with mode: 0644]
src/Database/Db.php [new file with mode: 0644]
update.sql [new file with mode: 0644]

index daa40c1..925fcf5 100644 (file)
@@ -1,5 +1,27 @@
-config.php
-.idea
-.vagrant
-vendor/
-composer.lock
+# Generic cache files
+*~
+.~*
+*.tmp
+*.temp
+*.lock
+*.DS_Store
+.*.swp
+*.out
+Thumbs.db
+.project
+.buildpath
+.settings
+_vimrc_local.vim
+
+# PHPstorm files
+/.idea/
+
+# Composer files
+/vendor/
+/composer.lock
+
+# Vagrant
+/.vagrant
+
+# Project files
+/config.php
diff --git a/README b/README
deleted file mode 100644 (file)
index 6a2d8a9..0000000
--- a/README
+++ /dev/null
@@ -1,20 +0,0 @@
-Needs PEAR OLE and PEAR Spreadsheet_Excel_Writer in Subdirectory pear/ like:
-
-pear/
-pear/OLE
-pear/OLE/ChainedBlockStream.php
-pear/OLE/PPS
-pear/OLE/PPS/File.php
-pear/OLE/PPS/Root.php
-pear/OLE/PPS.php
-pear/OLE.php
-pear/Spreadsheet
-pear/Spreadsheet/Excel
-pear/Spreadsheet/Excel/Writer
-pear/Spreadsheet/Excel/Writer/BIFFwriter.php
-pear/Spreadsheet/Excel/Writer/Format.php
-pear/Spreadsheet/Excel/Writer/Parser.php
-pear/Spreadsheet/Excel/Writer/Validator.php
-pear/Spreadsheet/Excel/Writer/Workbook.php
-pear/Spreadsheet/Excel/Writer/Worksheet.php
-pear/Spreadsheet/Excel/Writer.php
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..eaad558
--- /dev/null
+++ b/README.md
@@ -0,0 +1,9 @@
+# MemberDB
+
+## Installation
+* `ìnstall.sql` einspielen
+* `config.sample.php` in `config.php` umbenennen und Zugangsdaten eintragen
+* Docroot auf den `public/` Ordner setzen
+
+## Update
+* `update.sql` einspielen
diff --git a/UPGRADE.txt b/UPGRADE.txt
deleted file mode 100644 (file)
index 91c3b3c..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-
-// Upgrade existing database:
-// ALTER TABLE `memberdb_members` ADD `ddmandatesigdate` datetime NOT NULL AFTER `directdebit`;
-// UPDATE memberdb_members, memberdb_events SET memberdb_members.ddmandatesigdate = memberdb_events.event_date WHERE memberdb_members.id = memberdb_events.member_id AND memberdb_members.ddmandatesigdate = '0000-00-00 00:00:00' AND memberdb_events.event_type = 'joined' AND memberdb_members.directdebit IN (1, 2, 3);
index cd1d457..84f076a 100644 (file)
@@ -1,12 +1,14 @@
 {
-    "repositories": [
-        {
-            "type": "pear",
-            "url": "http://pear.php.net"
-        }
-    ],
+    "name": "ccc-ffm/memberdb",
+    "description": "Frickeling memberdb",
+    "type": "project",
+    "minimum-stability": "RC",
     "require": {
-        "pear-pear/PEAR": "*",
-        "pear-pear/Spreadsheet_Excel_Writer": "*"
+        "pear/spreadsheet_excel_writer": "*"
+    },
+    "autoload": {
+        "psr-4": {
+            "MemberDB\\": "src/"
+        }
     }
-}
\ No newline at end of file
+}
diff --git a/config.php.sample b/config.php.sample
deleted file mode 100644 (file)
index 7b6d51f..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-<?php
-
-define ('IS_INSTALLED', 0);
-define ('DB_USER',      'cccffm');
-define ('DB_PASSWORD',  'geheim');
-define ('DB_NAME',      'cccffm');
-define ('DB_HOST',      'localhost');
-define ('DB_CHARSET',   'utf8');
-define ('DB_PREFIX',    'memberdb_');
-
-define ('FOUNDING_DATE',    strtotime('02.10.2009'));
-define ('DIRECTDEBIT_DATE', strtotime('01.07.2010'));
-
-define ('DIRECTDEBIT_DAY_OF_MONTH', 15);
-
-define ('ACCOUNT_HOLDER', 'CCCFFM e.V.');
-define ('ACCOUNT_NUMBER', '1234567890');
-define ('BANK_CODE',      '0987654321');
-
-define ('CREDITOR_IDENTIFIER', 'DE00ZZZ00000000000');
-define ('IBAN',                'DE89370400440532013000');
-define ('BIC',                 'TESTDEX0XXX');
-# Mandatory until 2014-01-31 (DE), 2016-01-31 (EU)
-define ('USE_BIC', 1);
-
diff --git a/config.sample.php b/config.sample.php
new file mode 100644 (file)
index 0000000..026fbfb
--- /dev/null
@@ -0,0 +1,23 @@
+<?php
+
+return [
+    'database'      => [
+        'user'     => 'memberdb',
+        'password' => 'password',
+        'database' => 'memberdb',
+        'host'     => 'localhost',
+    ],
+    'founding_date' => new DateTime('2009-10-02'),
+    'direct_debit'  => [
+        'date' => new DateTime('2010-07-01'),
+        'day'  => 15,
+    ],
+    'bank'          => [
+        'holder'      => 'CCCFFM e.V.',
+        'number'      => '1234567890',
+        'code'        => '09876543',
+        'creditor_id' => 'DE00ZZZ00000000000',
+        'iban'        => 'DE89370400440532013000',
+        'bic'         => 'TESTDEX0XXX',
+    ],
+];
diff --git a/images/activity_indicator.gif b/images/activity_indicator.gif
deleted file mode 100644 (file)
index 7e8cc1b..0000000
Binary files a/images/activity_indicator.gif and /dev/null differ
diff --git a/include/autoload.php b/include/autoload.php
new file mode 100644 (file)
index 0000000..0cd9d35
--- /dev/null
@@ -0,0 +1,9 @@
+<?php
+
+// Check for autoloader
+if (!is_readable(__DIR__ . '/../vendor/autoload.php')) {
+    die('Please run composer.phar install');
+}
+
+// Include composer autoloader
+$loader = require __DIR__ . '/../vendor/autoload.php';
index 58a6b10..00cbb62 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 
-/* CRYPTOGRAPHY DOCUMENTATION {{{
+/* CRYPTOGRAPHY DOCUMENTATION
 
 Derived from http://clemens.endorphin.org/TKS1-draft.pdf
 
@@ -50,54 +50,42 @@ Derived from http://clemens.endorphin.org/TKS1-draft.pdf
 
 PROBLEM: AES uses a random initialization vector and creates different output for same parameters
 
-}}} */
+*/
 
-
-$SQL_CREATE_CRYPTO = sprintf('
-    CREATE TABLE IF NOT EXISTS `%1$s` (
-      `description` varchar(255) NOT NULL,
-      `masterkey` blob NOT NULL,
-      `salt` blob NOT NULL,
-      `control` blob NOT NULL,
-      `created_at` datetime NOT NULL,
-      `modified_at` datetime NOT NULL
-    ) ENGINE=InnoDB DEFAULT CHARSET=%2$s
-    ', DB_TABLE_CRYPTO, DB_CHARSET);
-
-/* DB functions {{{ */
-function db_get_crypto_keys() {
-    $sql = 'SELECT * FROM %1$s';
-    return db_select_multi(sprintf($sql, DB_TABLE_CRYPTO));
+/* DB functions */
+function db_get_crypto_keys()
+{
+    return db_select_multi('SELECT * FROM `cryptography`');
 }
 
-function db_add_crypto_key($key) {
-    $key['created_at']    = db_unixtime2datetime(time());
-    $key['modified_at']   = db_unixtime2datetime(time());
-    return (db_insert_single(DB_TABLE_CRYPTO, $key));
+function db_add_crypto_key($key)
+{
+    $key['created_at'] = db_unixtime2datetime(time());
+    $key['modified_at'] = db_unixtime2datetime(time());
+    return (db_insert('cryptography', $key));
 }
 
-/* }}} */
-
-function validate_crypto_key($userdata, &$dbdata, &$validation) {/*{{{*/
+function validate_crypto_key($userdata, &$dbdata)
+{
     $fields = array(
-        'description'   => 'string',
-        'masterkey'     => 'string',
-        'salt'          => 'string',
-        'control'       => 'string'
+        'description' => 'string',
+        'masterkey'   => 'string',
+        'salt'        => 'string',
+        'control'     => 'string'
     );
-    $orig = $dbdata;
     foreach ($fields as $name => $type) {
-        if (!isset($userdata[$name])) continue;
+        if (!isset($userdata[$name])) {
+            continue;
+        }
         $dbdata[$name] = $userdata[$name];
     }
     return true;
-}/*}}}*/
-
-
-function action_cryptography() {/*{{{*/
+}
 
+function action_cryptography()
+{
     $log_messages = array();
-    
+
     if (isset($_POST['task'])) {
         switch ($_POST['task']) {
             case 'add':
@@ -107,13 +95,13 @@ function action_cryptography() {/*{{{*/
                     'salt'        => '',
                     'control'     => ''
                 );
-                if (validate_crypto_key($_POST, $key, $log_messages)) {
+                if (validate_crypto_key($_POST, $key)) {
                     if (db_add_crypto_key($key)) {
                         redirect(link_to('cryptography'));
                     }
                     echo db_error();
                 }
-                
+
                 break;
             default:
                 break;
@@ -122,285 +110,295 @@ function action_cryptography() {/*{{{*/
 
     $keys = db_get_crypto_keys();
 
-?>
+    ?>
     <h2>Liste der Schl&uuml;ssel</h2>
     <?php if (isset($keys)) : ?>
-        <table>
-            <tr>
-                <th>Nickname</th>
-            </tr>
+    <table>
+        <tr>
+            <th>Nickname</th>
+        </tr>
         <?php foreach ($keys as $key) : ?>
             <tr>
-                <td><?=html_escape($key['description'])?></td>
+                <td><?php echo html_escape($key['description']) ?></td>
             </tr>
         <?php endforeach ?>
-        </table>
-    <?php else : ?>
-        <p>Bisher gibt's noch keine Schl&uuml;ssel.</p>
-    <?php endif ?>
-<?php
+    </table>
+<?php else : ?>
+    <p>Bisher gibt's noch keine Schl&uuml;ssel.</p>
+<?php endif ?>
+    <?php
 
     form_cryptography($keys, $log_messages);
-}/*}}}*/
-
-
-
-function form_cryptography($keys = array(), $log_messages = array()) {/*{{{*/
-?>
-<?php if (empty($keys)) : ?>
-<div class="clearfix">
-    <noscript>
-        <p class="error">
-            <strong>Achtung:</strong> Ohne JavaScript geht hier gar nichts. Bitte aktivieren!
-        </p>
-    </noscript>
-    <fieldset class="clearfix">
-        <legend>Ersteinrichtung</legend>
-        <?php log_messages($log_messages); ?>
-        <?=html_text_field('Nickname', 'description_visible')?>
-        <?=html_password_field('Passwort', 'password1')?>
-        <?=html_password_field('Passwort (wdh.)', 'password2')?>
-    </fieldset>
-    <input class="submit" type="button" name="btn_initialize" value="Masterkey erzeugen und speichern" onclick="initialize()"/>
-</div>
-<form action="" method="post" id="keyform">
-    <?=html_hidden_field('description')?>
-    <?=html_hidden_field('masterkey')?>
-    <?=html_hidden_field('salt')?>
-    <?=html_hidden_field('control')?>
-    <?=html_hidden_field('task', 'add')?>
-</form>
-
-<?php js_modal_windows() ?>
-
-<script type="text/javascript">
-
-$(document).ready(function(){  
-    $('#password2').keypress( function(event) { if (event.keyCode == '13') { initialize(); } });
-});  
-
-function initialize() {/*{{{*/
-//    var t1 = new Date().getTime()
-
-    var description = $('#description_visible').val();
-    if (description.length < 1) {
-        alert('Bitte einen Nickname angeben.');
-        return;
-    }
-
-    // 1.1 Ask for password1
-    // password should be already entered into the two input fields
-    var password1 = $('#password1').val();
-    var password2 = $('#password2').val();
-    if (password1 != password2) {
-        alert('Die Passwörter sind nicht identisch.');
-        return;
-    }
-    if (password1.length < 8) {
-        alert('Das Passwort ist zu kurz (min. 8 Zeichen).');
-        return;
-    }
-
-    modal_window_show($('#please_wait'));
-    $('#password1').val('');
-    $('#password2').val('');
-
-    setTimeout(function() {
-        // 1.2 Generate random bytes (salt1)
-        var salt1       = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
-
-        // 1.3 Generate random bytes (salt2)
-        var salt2       = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
-
-        // 1.4 Generate random bytes (secret)
-        var secret      = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
-
-        // 1.5 Create masterkey using PBKDF2 with secret, salt2 (1000 iterations)
-        var masterkey   = Crypto.PBKDF2(secret,    salt2, 256, { iterations: 1000, asBytes: true });
-        secret          = ''; // we don't need this anymore
-        salt2           = ''; // we don't need this anymore
-
-        // 1.6 Create userkey using PBKDF2 with password1, salt1 (1000 iterations)
-        var userkey     = Crypto.PBKDF2(password1, salt1, 256, { iterations: 1000, asBytes: true });
-        password1       = ''; // we don't need this anymore
-
-        // 1.7 Encrypt masterkey using AES with userkey
-        var crypted_masterkey = Crypto.AES.encrypt(masterkey, userkey);
-
-        // 1.8 Create sha1 hash of masterkey+userkey+salt
-        var control     = Crypto.SHA1(Crypto.charenc.Binary.bytesToString(masterkey) + Crypto.charenc.Binary.bytesToString(userkey) + salt1);
-
-    /* XXX DEBUG XXX
-        alert(
-            "masterkey: " + Crypto.charenc.Binary.bytesToString(masterkey).length + " " + masterkey + "\n" +
-            "userkey: " + userkey + "\n" + 
-            "control: " + control
-        );
-        return;
-    */
-    //    var t2 = new Date().getTime()
-    //    alert((t2 - t1) / 1000); // benchmark
-
-        // 1.9 Store data: key=1.7 salt=1.2, control=1.8
-        $('#masterkey').val(crypted_masterkey);
-        $('#salt').val(Crypto.util.bytesToHex(Crypto.charenc.Binary.stringToBytes(salt1)));
-        $('#control').val(control);
-        $('#description').val(description);
+}
 
-        $('#keyform').submit();
-    }, 500);
-}/*}}}*/
-</script>
+function form_cryptography($keys = array(), $log_messages = array())
+{
+    ?>
+    <?php if (empty($keys)) : ?>
+    <div class="clearfix">
+        <noscript>
+            <p class="error">
+                <strong>Achtung:</strong> Ohne JavaScript geht hier gar nichts. Bitte aktivieren!
+            </p>
+        </noscript>
+        <fieldset class="clearfix">
+            <legend>Ersteinrichtung</legend>
+            <?php log_messages($log_messages); ?>
+            <?php echo html_text_field('Nickname', 'description_visible') ?>
+            <?php echo html_password_field('Passwort', 'password1') ?>
+            <?php echo html_password_field('Passwort (wdh.)', 'password2') ?>
+        </fieldset>
+        <input class="submit" type="button" name="btn_initialize" value="Masterkey erzeugen und speichern"
+               onclick="initialize()"/>
+    </div>
+    <form action="" method="post" id="keyform">
+        <?php echo html_hidden_field('description') ?>
+        <?php echo html_hidden_field('masterkey') ?>
+        <?php echo html_hidden_field('salt') ?>
+        <?php echo html_hidden_field('control') ?>
+        <?php echo html_hidden_field('task', 'add') ?>
+    </form>
+
+    <?php js_modal_windows() ?>
+
+    <script type="text/javascript">
+
+        $(document).ready(function () {
+            $('#password2').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    initialize();
+                }
+            });
+        });
+
+        function initialize() {
+            // var t1 = new Date().getTime() // Debugging/Benchmarking
+
+            var description = $('#description_visible').val();
+            if (description.length < 1) {
+                alert('Bitte einen Nickname angeben.');
+                return;
+            }
+
+            // 1.1 Ask for password1
+            // password should be already entered into the two input fields
+            var password1 = $('#password1').val();
+            var password2 = $('#password2').val();
+            if (password1 != password2) {
+                alert('Die Passwörter sind nicht identisch.');
+                return;
+            }
+            if (password1.length < 8) {
+                alert('Das Passwort ist zu kurz (min. 8 Zeichen).');
+                return;
+            }
+
+            modal_window_show($('#please_wait'));
+            $('#password1').val('');
+            $('#password2').val('');
+
+            setTimeout(function () {
+                // 1.2 Generate random bytes (salt1)
+                var salt1 = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
+
+                // 1.3 Generate random bytes (salt2)
+                var salt2 = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
+
+                // 1.4 Generate random bytes (secret)
+                var secret = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
+
+                // 1.5 Create masterkey using PBKDF2 with secret, salt2 (1000 iterations)
+                var masterkey = Crypto.PBKDF2(secret, salt2, 256, {iterations: 1000, asBytes: true});
+                secret = ''; // we don't need this anymore
+                salt2 = ''; // we don't need this anymore
+
+                // 1.6 Create userkey using PBKDF2 with password1, salt1 (1000 iterations)
+                var userkey = Crypto.PBKDF2(password1, salt1, 256, {iterations: 1000, asBytes: true});
+                password1 = ''; // we don't need this anymore
+
+                // 1.7 Encrypt masterkey using AES with userkey
+                var crypted_masterkey = Crypto.AES.encrypt(masterkey, userkey);
+
+                // 1.8 Create sha1 hash of masterkey+userkey+salt
+                var control = Crypto.SHA1(Crypto.charenc.Binary.bytesToString(masterkey) + Crypto.charenc.Binary.bytesToString(userkey) + salt1);
+
+                /* XXX DEBUG XXX
+                    alert(
+                        "masterkey: " + Crypto.charenc.Binary.bytesToString(masterkey).length + " " + masterkey + "\n" +
+                        "userkey: " + userkey + "\n" +
+                        "control: " + control
+                    );
+                    return;
+                    var t2 = new Date().getTime()
+                    alert((t2 - t1) / 1000); // benchmark
+                */
+
+                // 1.9 Store data: key=1.7 salt=1.2, control=1.8
+                $('#masterkey').val(crypted_masterkey);
+                $('#salt').val(Crypto.util.bytesToHex(Crypto.charenc.Binary.stringToBytes(salt1)));
+                $('#control').val(control);
+                $('#description').val(description);
+
+                $('#keyform').submit();
+            }, 500);
+        }
+    </script>
 
 <?php else : ?>
 
-<div class="clearfix">
-    <noscript>
-        <p class="error">
-            <strong>Achtung:</strong> Ohne JavaScript geht hier gar nichts. Bitte aktivieren!
-        </p>
-    </noscript>
-    <fieldset class="clearfix">
-        <legend>Passwort hinzuf&uuml;gen</legend>
-        <?php log_messages($log_messages); ?>
-        <?=html_password_field('Exist. Passwort', 'password1')?>
-        <small>Bestehendes Passwort</small>
-        <?=html_text_field('Nickname', 'description_visible')?>
-        <?=html_password_field('Passwort', 'password2')?>
-        <?=html_password_field('Passwort (wdh.)', 'password3')?>
-    </fieldset>
-    <input class="submit" type="button" name="btn_add_new_key" value="Passwort hinzuf&uuml;gen" onclick="add_new_key()"/>
-</div>
-<form action="" method="post" id="keyform">
-    <?=html_hidden_field('description')?>
-    <?=html_hidden_field('masterkey')?>
-    <?=html_hidden_field('salt')?>
-    <?=html_hidden_field('control')?>
-    <?=html_hidden_field('task', 'add')?>
-</form>
-
-<?php js_modal_windows() ?>
-<?php js_get_master_key() ?>
-
-<script type="text/javascript">
-
-$(document).ready(function(){  
-    $('#password3').keypress( function(event) { if (event.keyCode == '13') { add_new_key(); } });
-});  
-
-function add_new_key() {/*{{{*/
-
-    var description = $('#description_visible').val();
-    if (description.length < 1) {
-        alert('Bitte einen Nickname angeben.');
-        return;
-    }
-
-    // 2.1 Check password1 (existing)
-    var password1 = $('#password1').val();
-    if (password1.length < 1) {
-        alert('Bitte ein existierenges Passwort angeben.');
-        return;
-    }
-
-    // 2.2 Check password2 (new one)
-    var password2 = $('#password2').val();
-    var password3 = $('#password3').val();
-    if (password2 != password3) {
-        alert('Die Passwörter sind nicht identisch.');
-        return;
-    }
-    if (password2.length < 8) {
-        alert('Das Passwort ist zu kurz (min. 8 Zeichen).');
-        return;
-    }
-
-    get_master_key(password1, function(masterkey) {
-
-        $('#password1').val('');
-        $('#password2').val('');
-        $('#password3').val('');
-
-        // 2.4 Generate random bytes (salt2)
-        var salt2       = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
-
-        // 2.5 Create userkey2 using PBKDF2 with password2, salt2 (1000 iterations)
-        var userkey2    = Crypto.PBKDF2(password2, salt2, 256, { iterations: 1000, asBytes: true });
-
-        // 2.6 Encrypt masterkey (from 2.3) using AES with userkey2
-        var crypted_masterkey = Crypto.AES.encrypt(masterkey, userkey2);
-
-        // 2.7 Create sha1 hash of masterkey+userkey2+salt2
-        var control     = Crypto.SHA1(Crypto.charenc.Binary.bytesToString(masterkey) + Crypto.charenc.Binary.bytesToString(userkey2) + salt2);
-
-        // 2.8 Store data: key=2.6 salt=2.4, control=2.7
-        $('#masterkey').val(crypted_masterkey);
-        $('#salt').val(Crypto.util.bytesToHex(Crypto.charenc.Binary.stringToBytes(salt2)));
-        $('#control').val(control);
-        $('#description').val(description);
-
-        $('#keyform').submit();
-    }, 10);
-}/*}}}*/
-</script>
-<?php endif ?>
-
+    <div class="clearfix">
+        <noscript>
+            <p class="error">
+                <strong>Achtung:</strong> Ohne JavaScript geht hier gar nichts. Bitte aktivieren!
+            </p>
+        </noscript>
+        <fieldset class="clearfix">
+            <legend>Passwort hinzuf&uuml;gen</legend>
+            <?php log_messages($log_messages); ?>
+            <?php echo html_password_field('Exist. Passwort', 'password1') ?>
+            <small>Bestehendes Passwort</small>
+            <?php echo html_text_field('Nickname', 'description_visible') ?>
+            <?php echo html_password_field('Passwort', 'password2') ?>
+            <?php echo html_password_field('Passwort (wdh.)', 'password3') ?>
+        </fieldset>
+        <input class="submit" type="button" name="btn_add_new_key" value="Passwort hinzuf&uuml;gen"
+               onclick="add_new_key()"/>
+    </div>
+    <form action="" method="post" id="keyform">
+        <?php echo html_hidden_field('description') ?>
+        <?php echo html_hidden_field('masterkey') ?>
+        <?php echo html_hidden_field('salt') ?>
+        <?php echo html_hidden_field('control') ?>
+        <?php echo html_hidden_field('task', 'add') ?>
+    </form>
+
+    <?php js_modal_windows() ?>
+    <?php js_get_master_key() ?>
+
+    <script type="text/javascript">
+
+        $(document).ready(function () {
+            $('#password3').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    add_new_key();
+                }
+            });
+        });
+
+        function add_new_key() {
+            var description = $('#description_visible').val();
+            if (description.length < 1) {
+                alert('Bitte einen Nickname angeben.');
+                return;
+            }
+
+            // 2.1 Check password1 (existing)
+            var password1 = $('#password1').val();
+            if (password1.length < 1) {
+                alert('Bitte ein existierenges Passwort angeben.');
+                return;
+            }
+
+            // 2.2 Check password2 (new one)
+            var password2 = $('#password2').val();
+            var password3 = $('#password3').val();
+            if (password2 != password3) {
+                alert('Die Passwörter sind nicht identisch.');
+                return;
+            }
+            if (password2.length < 8) {
+                alert('Das Passwort ist zu kurz (min. 8 Zeichen).');
+                return;
+            }
+
+            get_master_key(password1, function (masterkey) {
+                $('#password1').val('');
+                $('#password2').val('');
+                $('#password3').val('');
+
+                // 2.4 Generate random bytes (salt2)
+                var salt2 = Crypto.charenc.Binary.bytesToString(Crypto.util.randomBytes(32));
+
+                // 2.5 Create userkey2 using PBKDF2 with password2, salt2 (1000 iterations)
+                var userkey2 = Crypto.PBKDF2(password2, salt2, 256, {iterations: 1000, asBytes: true});
+
+                // 2.6 Encrypt masterkey (from 2.3) using AES with userkey2
+                var crypted_masterkey = Crypto.AES.encrypt(masterkey, userkey2);
+
+                // 2.7 Create sha1 hash of masterkey+userkey2+salt2
+                var control = Crypto.SHA1(Crypto.charenc.Binary.bytesToString(masterkey) + Crypto.charenc.Binary.bytesToString(userkey2) + salt2);
+
+                // 2.8 Store data: key=2.6 salt=2.4, control=2.7
+                $('#masterkey').val(crypted_masterkey);
+                $('#salt').val(Crypto.util.bytesToHex(Crypto.charenc.Binary.stringToBytes(salt2)));
+                $('#control').val(control);
+                $('#description').val(description);
+
+                $('#keyform').submit();
+            }, 10);
+        }
+    </script>
 <?php
-}/*}}}*/
-
-function js_get_master_key($keys = NULL) {/*{{{*/
-    if (!isset($keys)) $keys = db_get_crypto_keys();
-    if (empty($keys)) return;
-?>
-<script type="text/javascript">
-
-var keys = new Array(
-    <?=join(",\n", array_map('json_encode', $keys)) ?>
-);
-
-function get_master_key(password, callback) {/*{{{*/
-
-    modal_window_show($("#please_wait"));
-
-    // 4.2 iterate through valid keys
-    setTimeout(function() { check_master_key(0, password, callback); }, 1000);
-
-}/*}}}*/
-
-function check_master_key(idx, password, callback) {/*{{{*/
+endif;
+}
 
-    if (idx >= keys.length) {
-        modal_window_hide();
-        alert("Falsches Passwort");
-        return;
+function js_get_master_key($keys = null)
+{
+    if (!isset($keys)) {
+        $keys = db_get_crypto_keys();
     }
-
-    var crypted_masterkey   = keys[idx]['masterkey'];
-    var salt                = Crypto.charenc.Binary.bytesToString(Crypto.util.hexToBytes(keys[idx]['salt']));
-    var control1            = keys[idx]['control'];
-
-    // 1 Create userkey using PBKDF2 with password, salt (from database) - (1000 iterations)
-    var userkey             = Crypto.PBKDF2(password, salt, 256, { iterations: 1000, asBytes: true });
-
-    // 2 Decrypt key (from database) using AES with userkey
-    var masterkey           = Crypto.AES.decrypt(crypted_masterkey, userkey);
-    // 3 Create sha1 hash of masterkey+userkey+salt, afterwards compare with control
-    var control2            = Crypto.SHA1(Crypto.charenc.Binary.bytesToString(masterkey) + Crypto.charenc.Binary.bytesToString(userkey) + salt);
-
-    // 4 if equal we have the correct row and the correct master key
-    if (control1 == control2) {
-        modal_window_hide();
-        callback(masterkey);
+    if (empty($keys)) {
         return;
     }
+    ?>
+    <script type="text/javascript">
 
-    // check next key
-    setTimeout( function() { check_master_key(idx + 1, password, callback); }, 10);
+        var keys = new Array(
+            <?php echo join(",\n", array_map('json_encode', $keys)) ?>
+        );
 
-}/*}}}*/
+        function get_master_key(password, callback) {
+            modal_window_show($("#please_wait"));
 
-</script>
-<?php
-}/*}}}*/
+            // 4.2 iterate through valid keys
+            setTimeout(function () {
+                check_master_key(0, password, callback);
+            }, 1000);
 
+        }
+
+        function check_master_key(idx, password, callback) {
+            if (idx >= keys.length) {
+                modal_window_hide();
+                alert("Falsches Passwort");
+                return;
+            }
+
+            var crypted_masterkey = keys[idx]['masterkey'];
+            var salt = Crypto.charenc.Binary.bytesToString(Crypto.util.hexToBytes(keys[idx]['salt']));
+            var control1 = keys[idx]['control'];
+
+            // 1 Create userkey using PBKDF2 with password, salt (from database) - (1000 iterations)
+            var userkey = Crypto.PBKDF2(password, salt, 256, {iterations: 1000, asBytes: true});
+
+            // 2 Decrypt key (from database) using AES with userkey
+            var masterkey = Crypto.AES.decrypt(crypted_masterkey, userkey);
+            // 3 Create sha1 hash of masterkey+userkey+salt, afterwards compare with control
+            var control2 = Crypto.SHA1(Crypto.charenc.Binary.bytesToString(masterkey) + Crypto.charenc.Binary.bytesToString(userkey) + salt);
+
+            // 4 if equal we have the correct row and the correct master key
+            if (control1 == control2) {
+                modal_window_hide();
+                callback(masterkey);
+                return;
+            }
+
+            // check next key
+            setTimeout(function () {
+                check_master_key(idx + 1, password, callback);
+            }, 10);
 
+        }
+    </script>
+    <?php
+}
index 079c356..88ac29c 100644 (file)
 <?php
 
-/* DATABASE TABLE NAMES {{{ */
-define ('DB_TABLE_CRYPTO',      DB_PREFIX . 'crypto');
-define ('DB_TABLE_EVENTS',      DB_PREFIX . 'events');
-define ('DB_TABLE_MEMBERS',     DB_PREFIX . 'members');
-define ('DB_TABLE_EARNINGS',    DB_PREFIX . 'earnings');
-define ('DB_TABLE_EXPENSES',    DB_PREFIX . 'expenses');
-/* }}} */
-
-
-/* COMPATIBILITY functions {{{ */
-if (function_exists('mysql_set_charset') === false) {
-    function mysql_set_charset($charset, $link_identifier = null) {
-        if ($link_identifier == null) return mysql_query('SET NAMES "' . $charset . '"');
-        return mysql_query('SET NAMES "' . $charset . '"', $link_identifier);
+use MemberDB\Config\Config;
+use MemberDB\Database\Db;
+
+function db_connect()
+{
+    $config = Config::getInstance();
+    $success = Db::connect(
+        'mysql:host=' . $config->get('database')['host'] . ';dbname=' . $config->get('database')['database'] . ';charset=utf8',
+        $config->get('database')['user'],
+        $config->get('database')['password']
+    );
+    if (!$success) {
+        echo '<html><body>Konnte keine Verbindung zur Datenbank herstellen.</body></html>';
+        exit();
     }
-}
-/* }}} */
-
-function db_connect() {
-       global $dbh;
-       if (!($dbh = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true))) throw new Exception('<html><body>Konnte keine Verbindung zur Datenbank herstellen.</body></html>');
-       mysql_set_charset(DB_CHARSET, $dbh);
-       if (!mysql_select_db(DB_NAME)) throw new Exception('<html><body>Eine Verbindung zur Datenbank konnte hergestellt werden, aber die angegebene Datenbank konnte nicht ausgewählt werden.</body></html>');
-}
-
-// escape value for usage in mysql query
-function db_escape($value) {
-    global $dbh;
-    return mysql_real_escape_string($value, $dbh);
-}
 
-// escape each value of an array for usage in mysql query
-function db_escape_array($arr) {
-    global $dbh;
-    foreach ($arr as $key => $val) {
-        $arr[$key] = mysql_real_escape_string($val, $dbh);
-    }
-    return $arr;
+    Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+    Db::getPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
 }
 
 // select one row
-function db_select_single($query) {
-    global $dbh;
-    $res = mysql_query($query, $dbh);
-    if (!$res) {
-        echo $query, ' ', db_error();
-        return NULL;
-    }
-    if (mysql_num_rows($res) != 1) return NULL;
-    $row = mysql_fetch_assoc($res);
-    mysql_free_result($res);
-    return $row;
+function db_select_single($query, $bindings = [])
+{
+    return Db::selectOne($query, $bindings);
 }
 
 // select multiple rows
-function db_select_multi($query) {
-    global $dbh;
-    $res = mysql_query($query, $dbh);
-    if (!$res) {
-        echo $query, ' ', db_error();
-        return NULL;
-    }
-    if (mysql_num_rows($res) == 0) return array();
-    $ret = array();
-    while ($row = mysql_fetch_assoc($res)) $ret[] = $row;
-    mysql_free_result($res);
-    return $ret;
+function db_select_multi($query, $bindings = [])
+{
+    return Db::select($query, $bindings);
 }
 
 // insert one row
-function db_insert_single($table, $fields, $ignore = false) {
-    global $dbh;
-    $query = 'INSERT INTO ' . $table;
-    if ($ignore) $query = 'INSERT IGNORE INTO ' . $table;
-    $query .= ' (' . join(',', array_keys($fields)) . ') VALUES (\'' . join('\', \'', db_escape_array($fields)) . '\')';
-    $res = mysql_query($query, $dbh);
-    if (!$res)  echo $query, ' ', db_error();
-       return $res;
+function db_insert($table, $fields, $ignore = false)
+{
+    $query = sprintf('INSERT %s INTO %s', ($ignore ? 'IGNORE' : ''), $table);
+
+    $replacements = [];
+    foreach ($fields as $name => $field) {
+        $replacements[] = ':' . $name;
+    }
+
+    $query .= ' (`' . join('`,`', array_keys($fields)) . '`) VALUES (' . join(',', $replacements) . ')';
+
+    return Db::insert($query, $fields);
 }
 
 // get automatically generated id of last record
-function db_insert_id() {
-    global $dbh;
-    return mysql_insert_id($dbh);
+function db_insert_id($name = 'id')
+{
+    return Db::getPdo()->lastInsertId($name);
 }
 
 // begin transaction
-function db_begin() {
-    global $dbh;
-    return mysql_query('BEGIN');
+function db_begin()
+{
+    return Db::getPdo()->beginTransaction();
 }
 
 // commit transaction
-function db_commit() {
-    global $dbh;
-    return mysql_query('COMMIT');
+function db_commit()
+{
+    return Db::getPdo()->commit();
 }
 
 // rollback transaction
-function db_rollback() {
-    global $dbh;
-    return mysql_query('ROLLBACK');
+function db_rollback()
+{
+    Db::getPdo()->rollBack();
 }
 
 // update multiple rows
-function db_update_multi($table, $fields, $where = '', $special = '') {
-    global $dbh;
-    $query = 'UPDATE ' . $table . ' SET ';
-    $first = true;
-    foreach ($fields as $name => $value) {
-        if (!$first) $query .= ', ';
-        else $first = false;
-        $query .= '`' . $name . '`=\'' . db_escape($value) . '\'';
+function db_update($table, $fields, $where = '', $special = '', $limit = 'LIMIT 1')
+{
+    $query = 'UPDATE `' . $table . '` SET ';
+
+    $params = [];
+    foreach ($fields as $name => $field) {
+        $params[] = '`' . $name . '` = ? ';
     }
-    $query .= $special;
-    if (!empty($where)) $query.= ' WHERE ' . $where;
-    $res = mysql_query($query, $dbh);
-    if (!$res)  echo $query, ' ', db_error();
-       return $res;
-}
+    $query .= implode(',', $params);
 
-// update one rows
-function db_update_single($table, $fields, $where = '', $special = '') {
-    global $dbh;
-    $query = 'UPDATE ' . $table . ' SET ';
-    $first = true;
-    foreach ($fields as $name => $value) {
-        if (!$first) $query .= ', ';
-        else $first = false;
-        $query .= '`' . $name . '`=\'' . db_escape($value) . '\'';
+    $query .= $special . ' ';
+    if (!empty($where)) {
+        $query .= 'WHERE ' . $where . ' ';
     }
-    $query .= $special;
-    if (!empty($where)) $query.= ' WHERE ' . $where;
-       $query .= ' LIMIT 1';
-    $res = mysql_query($query, $dbh);
-    if (!$res)  echo $query, ' ', db_error();
-       return $res;
+
+    $query .= $limit;
+
+    return Db::update($query, array_values($fields));
 }
 
 // delete one row
-function db_delete_single($table, $where) {
-    global $dbh;
-    $query = 'DELETE FROM ' . $table . ' WHERE ' . $where . ' LIMIT 1';
-    $res = mysql_query($query, $dbh);
-    if (!$res) return NULL;
-    return (mysql_affected_rows($dbh));
+function db_delete($table, $where, $bindings = [])
+{
+    $query = sprintf('DELETE FROM `%s` WHERE %s LIMIT 1', $table, $where);
+
+    return Db::delete($query, $bindings);
 }
 
 // get error message
-function db_error() {
-    global $dbh;
-    return mysql_error($dbh);
+function db_error()
+{
+    return Db::getError()[2];
 }
 
-function db_unixtime2date($unixtime) {
+function db_unixtime2date($unixtime)
+{
     return strftime('%Y-%m-%d', $unixtime);
 }
 
-function db_date2unixtime($date) {
+function db_date2unixtime($date)
+{
     return strtotime($date);
 }
 
-function db_unixtime2datetime($unixtime) {
+function db_unixtime2datetime($unixtime)
+{
     return strftime('%Y-%m-%d %H:%M:%S', $unixtime);
 }
-
-function db_datetime2unixtime($datetime) {
-    return strtotime($datetime);
-}
-
index ac907fe..048246b 100644 (file)
@@ -1,34 +1,46 @@
 <?php
 
+use MemberDB\Config\Config;
 
-function action_directdebit() {
+function action_directdebit()
+{
+    $config = Config::getInstance();
+    $bank = $config->get('bank');
 
     $debittype = array(
         1 => 'DTAUS',
         2 => 'FRST',
         3 => 'RCUR'
-    ); 
+    );
 
     $members = db_get_members();
-    if (empty($members)) return;
+    if (empty($members)) {
+        return;
+    }
 
     $debits = array();
     $cash_payments = array();
     foreach ($members as $member) {
-               if (empty($member['directdebit'])) {
-                       // Barzahler
-                       $open = bcsub(fees_sum_for_member($member['id'], time()), bcadd(finance_get_paid_fees_for_member($member['id']), finance_get_paid_fees_for_member($member['id'], true)));
-                       if (bccomp($open, 0) != 1) continue;
-                       $cash_payments[] = array(
-                               'member_id'     => $member['id'],
-                               'member_number' => $member['number'],
-                               'nickname'      => $member['nickname'],
-                               'amount'        => $open
-                       );
-                       continue;
-               }
+        if (empty($member['directdebit'])) {
+            // Barzahler
+            $open = bcsub(fees_sum_for_member($member['id'], time()),
+                bcadd(finance_get_paid_fees_for_member($member['id']),
+                    finance_get_paid_fees_for_member($member['id'], true)));
+            if (bccomp($open, 0) != 1) {
+                continue;
+            }
+            $cash_payments[] = array(
+                'member_id'     => $member['id'],
+                'member_number' => $member['number'],
+                'nickname'      => $member['nickname'],
+                'amount'        => $open
+            );
+            continue;
+        }
         $info = fee_next_directdebit_for_member($member['id'], time());
-        if (empty($info)) continue;
+        if (empty($info)) {
+            continue;
+        }
         $debits[] = array(
             'member_id'        => $member['id'],
             'member_number'    => $member['number'],
@@ -36,7 +48,7 @@ function action_directdebit() {
             'accountholder'    => $member['accountholder'],
             'accountnumber'    => $member['accountnumber'],
             'bankcode'         => $member['bankcode'],
-//          'bankname'         => $member['bankname'],
+            //          'bankname'         => $member['bankname'],
             'amount'           => $info['value'],
             'amountcent'       => '' . (int)round(bcmul($info['value'], 100)),
             'purpose'          => $info['info'],
@@ -47,256 +59,258 @@ function action_directdebit() {
 
     js_modal_windows();
     js_get_master_key();
-
-?>
+    ?>
     <noscript>
         <p class="error">
             <strong>Achtung:</strong> Ohne JavaScript geht hier gar nichts. Bitte aktivieren!
         </p>
     </noscript>
-<?php if (!empty($cash_payments)) : ?>
-<h2>Barzahler</h2>
-<table>
-    <tr>
-        <th>Mitgliedsnummer</th>
-        <th>Nickname</th>
-        <th style="text-align: right;">Betrag</th>
-               <th></th>
-       </tr>
-<?php foreach ($cash_payments as $payment) : ?>
-    <tr>
-        <td><a href="<?=html_escape(link_to('fees', array('member_id'=> $payment['member_id'])))?>"><?=html_escape($payment['member_number'])?></a></td>
-        <td><?=html_escape($payment['nickname'])?></td>
-        <td style="text-align: right;"><?=html_escape(format_money($payment['amount']))?></td>
-               <td>
-                       <form action="<?=link_to('create_earning')?>" method="post" class="clearfix">
-                               <?=html_hidden_field('date', format_date(time()))?>
-                               <?=html_hidden_field('type', 'fee')?>
-                               <?=html_hidden_field('status', 'paid')?>
-                               <?=html_hidden_field('value', format_money($payment['amount']))?>
-                               <?=html_hidden_field('member_id', $payment['member_id'])?>
-                               <?=html_hidden_field('description', '')?>
-                               <?=html_hidden_field('account', 'cash')?>
-                               <input class="submit" type="submit" name="submit" value="Einnahme verbuchen"/>
-                       </form>
-               </td>
-    </tr>
-<?php endforeach ?>
-</table>
+    <?php if (!empty($cash_payments)) : ?>
+    <h2>Barzahler</h2>
+    <table>
+        <tr>
+            <th>Mitgliedsnummer</th>
+            <th>Nickname</th>
+            <th style="text-align: right;">Betrag</th>
+            <th></th>
+        </tr>
+        <?php foreach ($cash_payments as $payment) : ?>
+            <tr>
+                <td><a href="<?php echo html_escape(link_to('fees',
+                        array('member_id' => $payment['member_id']))) ?>"><?php echo html_escape($payment['member_number']) ?></a>
+                </td>
+                <td><?php echo html_escape($payment['nickname']) ?></td>
+                <td style="text-align: right;"><?php echo html_escape(format_money($payment['amount'])) ?></td>
+                <td>
+                    <form action="<?php echo link_to('create_earning') ?>" method="post" class="clearfix">
+                        <?php echo html_hidden_field('date', format_date(time())) ?>
+                        <?php echo html_hidden_field('type', 'fee') ?>
+                        <?php echo html_hidden_field('status', 'paid') ?>
+                        <?php echo html_hidden_field('value', format_money($payment['amount'])) ?>
+                        <?php echo html_hidden_field('member_id', $payment['member_id']) ?>
+                        <?php echo html_hidden_field('description', '') ?>
+                        <?php echo html_hidden_field('account', 'cash') ?>
+                        <input class="submit" type="submit" name="submit" value="Einnahme verbuchen"/>
+                    </form>
+                </td>
+            </tr>
+        <?php endforeach ?>
+    </table>
 <?php endif ?>
 
-<h2>Bankeinzug</h2>
-<table>
-    <tr>
-        <th>Mitgliedsnummer</th>
-        <th>Nickname</th>
-        <th>Verwendungszweck</th>
-        <th>Einzugstyp</th>
-        <th style="text-align: right;">Betrag</th>
-    </tr>
-<?php $total = 0; ?>
-<?php foreach ($debits as $debit) : ?>
-    <tr>
-        <td><a href="<?=html_escape(link_to('fees', array('member_id'=> $debit['member_id'])))?>"><?=html_escape($debit['member_number'])?></a></td>
-        <td><?=html_escape($debit['nickname'])?></td>
-        <td><?=html_escape($debit['purpose'])?></td>
-        <td><?=html_escape($debit['debittype'])?></td>
-        <td style="text-align: right;"><?=html_escape(format_money($debit['amount']))?></td>
-    </tr>
-    <?php $total = bcadd($total, $debit['amount']); ?>
-<?php endforeach ?>
-    <tr class="total">
-        <td>Gesamt</td>
-        <td></td>
-        <td></td>
-        <td></td>
-        <td style="text-align: right;"><?=html_escape(format_money($total))?></td>
-    </tr>
-</table>
-
-<!-- ?=html_hidden_field('directdebittype', 'pain')? -->
-<?=html_list_box('Dateiformat', 'directdebittype', array('dtaus' => 'DTAUS', 'pain' => 'PAIN'), 'pain');?>
-<input class="submit" type="button" name="btn_directdebit" value="Datei erzeugen" onclick="ask_for_password()" id="btn_directdebit"/>
-<br/>
-<br/>
-<form action="<?=link_to('create_earnings')?>" method="post" class="clearfix">
-<?php $count = 0; ?>
-<?php foreach ($debits as $debit) : ?>
-    <?=html_hidden_field(sprintf('earnings[%d][date]',        $count), format_date(time()))?>
-    <?=html_hidden_field(sprintf('earnings[%d][type]',        $count), 'fee')?>
-    <?=html_hidden_field(sprintf('earnings[%d][status]',      $count), 'paid')?>
-    <?=html_hidden_field(sprintf('earnings[%d][value]',       $count), $debit['amount'])?>
-    <?=html_hidden_field(sprintf('earnings[%d][member_id]',   $count), $debit['member_id'])?>
-    <?=html_hidden_field(sprintf('earnings[%d][description]', $count), $debit['purpose'])?>
-    <?php $count++; ?>
-<?php endforeach ?>
-<input class="submit" type="submit" name="btn_create_earnings" value="Einnahmen verbuchen"/>
-</form>
-<hr/>
-<form action="<?=link_to('export_ibanhin')?>" method="POST" class="clearfix">
-<input class="submit" type="submit" name="btn_export_ibanhin" value="IBAN-hin Export"/>
-</form>
-
-<div id="password_popup" class="modal_window">
-    <fieldset>
-        <legend>Passwortabfrage</legend>
-        <?=html_password_field('Passwort', 'password')?>
-        <input class="submit" type="button" name="btn_generate_directdebit" value="Datei erzeugen" onclick="generate_directdebit()"/>
-        <input class="submit" type="button" name="btn_cancel" value="Abbrechen" onclick="cancel_ask_for_password()"/>
-    </fieldset>
-</div>
-<div id="directdebit_popup" class="modal_window">
-    <fieldset>
-        <legend>DTAUS / SEPA PAIN FRST</legend>
+    <h2>Bankeinzug</h2>
+    <table>
+        <tr>
+            <th>Mitgliedsnummer</th>
+            <th>Nickname</th>
+            <th>Verwendungszweck</th>
+            <th>Einzugstyp</th>
+            <th style="text-align: right;">Betrag</th>
+        </tr>
+        <?php $total = 0; ?>
+        <?php foreach ($debits as $debit) : ?>
+            <tr>
+                <td><a href="<?php echo html_escape(link_to('fees',
+                        array('member_id' => $debit['member_id']))) ?>"><?php echo html_escape($debit['member_number']) ?></a>
+                </td>
+                <td><?php echo html_escape($debit['nickname']) ?></td>
+                <td><?php echo html_escape($debit['purpose']) ?></td>
+                <td><?php echo html_escape($debit['debittype']) ?></td>
+                <td style="text-align: right;"><?php echo html_escape(format_money($debit['amount'])) ?></td>
+            </tr>
+            <?php $total = bcadd($total, $debit['amount']); ?>
+        <?php endforeach ?>
+        <tr class="total">
+            <td>Gesamt</td>
+            <td></td>
+            <td></td>
+            <td></td>
+            <td style="text-align: right;"><?php echo html_escape(format_money($total)) ?></td>
+        </tr>
+    </table>
+
+    <?php echo html_list_box('Dateiformat', 'directdebittype', array('dtaus' => 'DTAUS', 'pain' => 'PAIN'), 'pain'); ?>
+    <input class="submit" type="button" name="btn_directdebit" value="Datei erzeugen" onclick="ask_for_password()"
+           id="btn_directdebit"/>
+    <br/>
+    <br/>
+    <form action="<?php echo link_to('create_earnings') ?>" method="post" class="clearfix">
+        <?php $count = 0; ?>
+        <?php foreach ($debits as $debit) : ?>
+            <?php echo html_hidden_field(sprintf('earnings[%d][date]', $count), format_date(time())) ?>
+            <?php echo html_hidden_field(sprintf('earnings[%d][type]', $count), 'fee') ?>
+            <?php echo html_hidden_field(sprintf('earnings[%d][status]', $count), 'paid') ?>
+            <?php echo html_hidden_field(sprintf('earnings[%d][value]', $count), $debit['amount']) ?>
+            <?php echo html_hidden_field(sprintf('earnings[%d][member_id]', $count), $debit['member_id']) ?>
+            <?php echo html_hidden_field(sprintf('earnings[%d][description]', $count), $debit['purpose']) ?>
+            <?php $count++; ?>
+        <?php endforeach ?>
+        <input class="submit" type="submit" name="btn_create_earnings" value="Einnahmen verbuchen"/>
+    </form>
+    <hr/>
+    <form action="<?php echo link_to('export_ibanhin') ?>" method="POST" class="clearfix">
+        <input class="submit" type="submit" name="btn_export_ibanhin" value="IBAN-hin Export"/>
+    </form>
+
+    <div id="password_popup" class="modal_window">
+        <fieldset>
+            <legend>Passwortabfrage</legend>
+            <?php echo html_password_field('Passwort', 'password') ?>
+            <input class="submit" type="button" name="btn_generate_directdebit" value="Datei erzeugen"
+                   onclick="generate_directdebit()"/>
+            <input class="submit" type="button" name="btn_cancel" value="Abbrechen"
+                   onclick="cancel_ask_for_password()"/>
+        </fieldset>
+    </div>
+    <div id="directdebit_popup" class="modal_window">
+        <fieldset>
+            <legend>DTAUS / SEPA PAIN FRST</legend>
             <textarea id="directdebit_content" style="width: 100%" rows="15" readonly="readonly"></textarea>
-        <legend>SEPA PAIN RCUR</legend>
+            <legend>SEPA PAIN RCUR</legend>
             <textarea id="directdebit_content2" style="width: 100%" rows="15" readonly="readonly"></textarea>
-            <input class="submit" type="button" name="btn_directdebit_close" value="Schließen" onclick="directdebit_close()"/>
-    </fieldset>
-</div>
-
-<script type="text/javascript">
-
-var debits = new Array(
-    <?=join(",\n", array_map('json_encode', $debits)) ?>
-);
-
-
-$(document).ready(function(){  
-    $('#password').keypress( function(event) { if (event.keyCode == '13') { generate_directdebit(); } });
-    $('#btn_directdebit').focus();
-});  
-
-
-function ask_for_password() {/*{{{*/
-    modal_window_show($("#password_popup"));
-    $("#password").focus();
-    return;
-}/*}}}*/
-
-function cancel_ask_for_password() {/*{{{*/
-    modal_window_hide();
-    $("#btn_directdebit").focus();
-    return;
-}/*}}}*/
-
-
-function generate_directdebit() {/*{{{*/
-
-    var password = $('#password').val();
-    var directdebitcontent = "";
-    var directdebitcontent2 = "Wird nur bei SEPA verwendet.";
-    $("#password").val('');
-
-    // We pass a closure so that get_master_key may defer execution
-    get_master_key(password, function(masterkey) {
-
-        modal_window_replace($("#directdebit_popup"));
-
-    switch ($('#directdebittype').val()) {
-        case "dtaus":
-           if (!DTAUS.setAccountFileSender('<?=dtaus_string(ACCOUNT_HOLDER)?>', '<?=BANK_CODE?>', '<?=ACCOUNT_NUMBER?>')) {
-               $('#directdebit_content').val(DTAUS.errormsg);
-               return;
-           }
-
-           for (var i = 0; i < debits.length; i++) {
-           
-               if (debits[i]['debittype'] != 'DTAUS' ) {
-                 continue;
-               }
-               
-               var accountholder = debits[i]['accountholder'];
-               var accountnumber = debits[i]['accountnumber'];
-               var bankcode      = debits[i]['bankcode'];
-
-               // Encrypt/Decrypt data using AES with masterkey
-               if (accountholder != "") accountholder = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountholder, masterkey));
-               if (accountnumber != "") accountnumber = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey));
-               if (bankcode      != "") bankcode      = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode,      masterkey));
-
-               accountholder = DTAUS.prepareString(accountholder);
-
-               if (!DTAUS.addExchange(accountholder, bankcode, accountnumber, '', debits[i]['amountcent'], debits[i]['purpose'])) {
-                   $('#directdebit_content').val('Mitglied ' + debits[i]['member_number'] + ' ' + accountholder + '\n' + DTAUS.errormsg);
-                   return;
-               }
-           }
-           directdebitcontent = DTAUS.getFileContent();
-           break;
-           
-       case "pain":
-
-           <?php $bic = (USE_BIC == 1)?'\''.BIC.'\'':'null'; ?>    
-           
-           // datejs.com MAGIC
-           var jetzt = new Date.today();
-           var collectiondate = new Date.parse('<?=DIRECTDEBIT_DAY_OF_MONTH?>');
-           if (jetzt.getDate() > <?=DIRECTDEBIT_DAY_OF_MONTH?>) {
-             collectiondate = collectiondate.add(1).month();
-           }
-
-           if (!SEPACORE.init(collectiondate, '<?=CREDITOR_IDENTIFIER?>', '<?=ACCOUNT_HOLDER?>', '<?=IBAN?>', <?=$bic?>)) {
-               $('#directdebit_content').val(DTAUS.errormsg);
-               return;
-           }
-
-           for (var i = 0; i < debits.length; i++) {
-           
-               if (debits[i]['debittype'] != 'FRST' && debits[i]['debittype'] != 'RCUR' ) {
-                 continue;
-               }
-               
-               var accountholder = debits[i]['accountholder'];
-               var accountnumber = debits[i]['accountnumber'];
-               var bankcode      = debits[i]['bankcode'];
-
-               // Encrypt/Decrypt data using AES with masterkey
-               if (accountholder != "") accountholder = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountholder, masterkey));
-               if (accountnumber != "") accountnumber = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey));
-               if (bankcode      != "") bankcode      = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode,      masterkey));
-               
-               // Mandatsreferenz '/V1/M:n/'; z.B. /V:1/M:2/
-               var mandateref = '/V:1/M:' + debits[i]['member_number'] + '/';
-               var e2eid = '/V:1/E2E:' + parseInt(SEPACORE.creationdate.getTime()/1000) + '/S:' + debits[i]['debittype'][0] + '/I:' + i + '/';
-               if (!SEPACORE.addDDTx(debits[i]['debittype'], accountholder, accountnumber, bankcode, mandateref, debits[i]['ddmandatesigdate'].substring(0, 10), debits[i]['amountcent'], debits[i]['purpose'], e2eid)) {
-                   $('#directdebit_content').val('Mitglied ' + debits[i]['member_number'] + ' ' + accountholder + '\n' + SEPACORE.errormsg);
-                   return;
-               }
-           }
-           
-           directdebitcontent = SEPACORE.getXMLContent('FRST');
-           directdebitcontent2 = SEPACORE.getXMLContent('RCUR');
-            
-           if (SEPACORE.errormsg.lenght > 0) {
-               $('#directdebit_content').val(SEPACORE.errormsg);
-               return;
-           }
-            break;
-        }
-        $('#directdebit_content').val(directdebitcontent);
-        $('#directdebit_content2').val(directdebitcontent2);
-        $('#directdebit_content').focus();
-        $('#directdebit_content').select();
-    });
+            <input class="submit" type="button" name="btn_directdebit_close" value="Schließen"
+                   onclick="directdebit_close()"/>
+        </fieldset>
+    </div>
+
+    <script type="text/javascript">
+        var debits = new Array(
+            <?php echo join(",\n", array_map('json_encode', $debits)) ?>
+        );
 
-}/*}}}*/
+        $(document).ready(function () {
+            $('#password').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    generate_directdebit();
+                }
+            });
+            $('#btn_directdebit').focus();
+        });
+
+        function ask_for_password() {
+            modal_window_show($("#password_popup"));
+            $("#password").focus();
+            return;
+        }
 
-function directdebit_close() {/*{{{*/
-    modal_window_hide();
-    $("#directdebit_content").val('');
-    $("#directdebit_content2").val('');
-}/*}}}*/
+        function cancel_ask_for_password() {
+            modal_window_hide();
+            $("#btn_directdebit").focus();
+            return;
+        }
 
+        function generate_directdebit() {
+            var password = $('#password').val();
+            var directdebitcontent = "";
+            var directdebitcontent2 = "Wird nur bei SEPA verwendet.";
+            $("#password").val('');
+
+            // We pass a closure so that get_master_key may defer execution
+            get_master_key(password, function (masterkey) {
+
+                modal_window_replace($("#directdebit_popup"));
+
+                switch ($('#directdebittype').val()) {
+                    case "dtaus":
+                        if (!DTAUS.setAccountFileSender('<?php echo dtaus_string($bank['holder']); ?>', '<?php echo $bank['code']; ?>', '<?php echo $bank['number']; ?>')) {
+                            $('#directdebit_content').val(DTAUS.errormsg);
+                            return;
+                        }
+
+                        for (var i = 0; i < debits.length; i++) {
+
+                            if (debits[i]['debittype'] != 'DTAUS') {
+                                continue;
+                            }
+
+                            var accountholder = debits[i]['accountholder'];
+                            var accountnumber = debits[i]['accountnumber'];
+                            var bankcode = debits[i]['bankcode'];
+
+                            // Encrypt/Decrypt data using AES with masterkey
+                            if (accountholder != "") accountholder = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountholder, masterkey));
+                            if (accountnumber != "") accountnumber = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey));
+                            if (bankcode != "") bankcode = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode, masterkey));
+
+                            accountholder = DTAUS.prepareString(accountholder);
+
+                            if (!DTAUS.addExchange(accountholder, bankcode, accountnumber, '', debits[i]['amountcent'], debits[i]['purpose'])) {
+                                $('#directdebit_content').val('Mitglied ' + debits[i]['member_number'] + ' ' + accountholder + '\n' + DTAUS.errormsg);
+                                return;
+                            }
+                        }
+                        directdebitcontent = DTAUS.getFileContent();
+                        break;
+
+                    case "pain":
+                        // datejs.com MAGIC
+                        var jetzt = new Date.today();
+                        var collectiondate = new Date.parse('<?php echo $config->get('direct_debit')['day']; ?>');
+                        if (jetzt.getDate() > <?php echo $config->get('direct_debit')['day']; ?>) {
+                            collectiondate = collectiondate.add(1).month();
+                        }
+
+                        if (!SEPACORE.init(collectiondate, '<?php echo $bank['creditor_id']; ?>', '<?php echo $bank['holder']; ?>', '<?php echo $bank['iban']; ?>', '<?php echo $bank['bic']; ?>')) {
+                        $('#directdebit_content').val(DTAUS.errormsg);
+                        return;
+                }
+
+                for (var i = 0; i < debits.length; i++) {
+
+                    if (debits[i]['debittype'] != 'FRST' && debits[i]['debittype'] != 'RCUR') {
+                        continue;
+                    }
+
+                    var accountholder = debits[i]['accountholder'];
+                    var accountnumber = debits[i]['accountnumber'];
+                    var bankcode = debits[i]['bankcode'];
+
+                    // Encrypt/Decrypt data using AES with masterkey
+                    if (accountholder != "") accountholder = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountholder, masterkey));
+                    if (accountnumber != "") accountnumber = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey));
+                    if (bankcode != "") bankcode = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode, masterkey));
+
+                    // Mandatsreferenz '/V1/M:n/'; z.B. /V:1/M:2/
+                    var mandateref = '/V:1/M:' + debits[i]['member_number'] + '/';
+                    var e2eid = '/V:1/E2E:' + parseInt(SEPACORE.creationdate.getTime() / 1000) + '/S:' + debits[i]['debittype'][0] + '/I:' + i + '/';
+                    if (!SEPACORE.addDDTx(debits[i]['debittype'], accountholder, accountnumber, bankcode, mandateref, debits[i]['ddmandatesigdate'].substring(0, 10), debits[i]['amountcent'], debits[i]['purpose'], e2eid)) {
+                        $('#directdebit_content').val('Mitglied ' + debits[i]['member_number'] + ' ' + accountholder + '\n' + SEPACORE.errormsg);
+                        return;
+                    }
+                }
+
+                directdebitcontent = SEPACORE.getXMLContent('FRST');
+                directdebitcontent2 = SEPACORE.getXMLContent('RCUR');
+
+                if (SEPACORE.errormsg.lenght > 0) {
+                    $('#directdebit_content').val(SEPACORE.errormsg);
+                    return;
+                }
+            }
+            $('#directdebit_content').val(directdebitcontent);
+            $('#directdebit_content2').val(directdebitcontent2);
+            $('#directdebit_content').focus();
+            $('#directdebit_content').select();
+        }
 
+        )
+        }
 
-</script>
-<?
+        function directdebit_close() {
+            modal_window_hide();
+            $("#directdebit_content").val('');
+            $("#directdebit_content2").val('');
+        }
+    </script>
+    <?php
 }
 
 // borrowed from PEARs Payment_DTA
-function dtaus_string($string) {
-    if (strlen($string) == 0) return '';
+function dtaus_string($string)
+{
+    if (strlen($string) == 0) {
+        return '';
+    }
     $special_chars = array(
         'á' => 'a',
         'à' => 'a',
@@ -371,7 +385,6 @@ function dtaus_string($string) {
         'Ĥ' => 'H',
         'Ħ' => 'H',
         'ì' => 'i',
-        'ì' => 'i',
         'î' => 'i',
         'ï' => 'i',
         'ĩ' => 'i',
@@ -508,7 +521,6 @@ function dtaus_string($string) {
         'Ž' => 'Z',
     );
 
-
     $result = strtr($string, $special_chars);   // replace known special chars
     $result = strtoupper($result);                  // upper case
     // make sure every special char is replaced by one space, not two or three
@@ -517,4 +529,3 @@ function dtaus_string($string) {
 
     return $result;
 }
-
index 071fe43..6e24806 100644 (file)
@@ -1,82 +1,66 @@
 <?php
 
-$SQL_CREATE_EARNINGS = sprintf('
-    CREATE TABLE IF NOT EXISTS `%1$s` (
-      `id` int(10) unsigned NOT NULL auto_increment,
-      `date` date NOT NULL,
-      `type` enum(\'donation\', \'fee\', \'old_fee\', \'interest\', \'account_transfer\', \'room\', \'catering\') NULL,
-      `status` enum(\'open\',\'paid\') NOT NULL,
-      `account` enum(\'bank\',\'cash\') NOT NULL,
-      `value` DECIMAL(10,2) NULL,
-      `member_id` int(10) unsigned NOT NULL,
-      `description` TEXT NOT NULL,
-      `created_at` datetime NOT NULL,
-      `modified_at` datetime NOT NULL,
-      PRIMARY KEY  (`id`),
-      INDEX `idx_member_id` (`member_id`),
-      INDEX `idx_date` (`date`)
-    ) ENGINE=InnoDB DEFAULT CHARSET=%2$s
-    ', DB_TABLE_EARNINGS, DB_CHARSET);
+use MemberDB\Config\Config;
 
 $EARNING_TYPES = array(
-    'fee'       => 'Mitgliedsbeitrag',
-    'donation'  => 'Spende',
-    'interest'  => 'Zinsen',
-    'room'      => 'Raumeinnahme',
-    'account_transfer'  => 'Umbuchung',
-    'old_fee'   => 'Mitgliedsbeiträge vor dem ' . format_date(DIRECTDEBIT_DATE),
-    'catering' => 'Raum - Getraenke & Snacks'
+    'fee'              => 'Mitgliedsbeitrag',
+    'donation'         => 'Spende',
+    'interest'         => 'Zinsen',
+    'room'             => 'Raumeinnahme',
+    'account_transfer' => 'Umbuchung',
+    'old_fee'          => 'Mitgliedsbeiträge vor dem ' . format_date(Config::getInstance()->get('direct_debit')['date']->getTimestamp()),
+    'catering'         => 'Raum - Getraenke & Snacks'
 );
 
-
-/* DB functions {{{ */
-
-function db_get_earning_with_id($earning_id) {
-    $sql = 'SELECT * FROM %1$s WHERE id=\'%2$d\' LIMIT 1';
-    return db_select_single(sprintf($sql, DB_TABLE_EARNINGS, db_escape($earning_id)));
+// DB functions
+function db_get_earning_with_id($earning_id)
+{
+    return db_select_single('SELECT * FROM `earnings` WHERE id=? LIMIT 1', [$earning_id]);
 }
 
-function db_create_earning($earning) {
+function db_create_earning($earning)
+{
     unset($earning['id']);
-    $earning['date']        = db_unixtime2datetime(ui_date2unixtime($earning['date']));
-    $earning['value']       = ui_money2float($earning['value']);
-    $earning['created_at']  = db_unixtime2datetime(time());
+    $earning['date'] = db_unixtime2datetime(ui_date2unixtime($earning['date']));
+    $earning['value'] = ui_money2float($earning['value']);
+    $earning['created_at'] = db_unixtime2datetime(time());
     $earning['modified_at'] = db_unixtime2datetime(time());
-    return (db_insert_single(DB_TABLE_EARNINGS, $earning));
+    return (db_insert('earnings', $earning));
 }
 
-function db_change_earning($earning) {
+function db_change_earning($earning)
+{
     $id = $earning['id'];
     unset($earning['id']);
-    $earning['date']        = db_unixtime2datetime(ui_date2unixtime($earning['date']));
-    $earning['value']       = ui_money2float($earning['value']);
+    $earning['date'] = db_unixtime2datetime(ui_date2unixtime($earning['date']));
+    $earning['value'] = ui_money2float($earning['value']);
     $earning['modified_at'] = db_unixtime2datetime(time());
-    return db_update_single(DB_TABLE_EARNINGS, $earning, sprintf('id=\'%1$d\'', db_escape($id)));
+    return db_update('earnings', $earning, sprintf("id=%d", (int)$id));
 }
 
-function db_delete_earning($earning) {
-    return db_delete_single(DB_TABLE_EARNINGS, sprintf('id=\'%1$d\'', db_escape($earning['id'])));
+function db_delete_earning($earning)
+{
+    return db_delete('earnings', 'id=?', [$earning['id']]);
 }
 
-/* }}} */
-
-
-function validate_earning($userdata, &$dbdata, &$validation) {/*{{{*/
+function validate_earning($userdata, &$dbdata, &$validation)
+{
     global $EARNING_TYPES, $ACCOUNT_TYPES;
     $fields = array(
-        'id'              => 'number',
-        'date'            => 'date',
-        'type'            => $EARNING_TYPES,
-        'account'         => $ACCOUNT_TYPES,
-        'member_id'       => 'member',
-        'value'           => 'money',
-        'description'     => 'text',
-//      'status'          -  See below...
+        'id'          => 'number',
+        'date'        => 'date',
+        'type'        => $EARNING_TYPES,
+        'account'     => $ACCOUNT_TYPES,
+        'member_id'   => 'member',
+        'value'       => 'money',
+        'description' => 'text',
+        //      'status'          -  See below...
     );
-    $orig = $dbdata;
     $dbdata['status'] = empty($userdata['status']) ? 'open' : 'paid';
     foreach ($fields as $name => $type) {
-        if (!isset($userdata[$name])) continue;
+        if (!isset($userdata[$name])) {
+            continue;
+        }
         $dbdata[$name] = $userdata[$name];
     }
 
@@ -88,13 +72,13 @@ function validate_earning($userdata, &$dbdata, &$validation) {/*{{{*/
     }
 
     return (count($validation) == 0);
-}/*}}}*/
-
+}
 
-function action_create_earning() {/*{{{*/
+function action_create_earning()
+{
     $earning = array();
-    $earning['date']      = format_date(time());
-    $earning['status']    = 'paid';
+    $earning['date'] = format_date(time());
+    $earning['status'] = 'paid';
     $log_messages = array();
     if (isset($_POST['submit'])) {
         unset($_POST['id']);
@@ -106,15 +90,19 @@ function action_create_earning() {/*{{{*/
         }
     }
     form_earning($earning, 'create', $log_messages);
-}/*}}}*/
-
+}
 
-function action_change_earning() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to('finances'));
+function action_change_earning()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to('finances'));
+    }
     $earning = db_get_earning_with_id($_REQUEST['id']);
-    if (!isset($earning)) redirect(link_to('finances'));
+    if (!isset($earning)) {
+        redirect(link_to('finances'));
+    }
     $earning['date'] = format_date(db_date2unixtime($earning['date']));
-    $earning['value']= format_money($earning['value']);
+    $earning['value'] = format_money($earning['value']);
     $log_messages = array();
     if (isset($_POST['submit'])) {
         if (validate_earning($_POST, $earning, $log_messages)) {
@@ -126,15 +114,19 @@ function action_change_earning() {/*{{{*/
     }
 
     form_earning($earning, 'change', $log_messages);
-}/*}}}*/
-
+}
 
-function action_delete_earning() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to('finances'));
+function action_delete_earning()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to('finances'));
+    }
     $earning = db_get_earning_with_id($_REQUEST['id']);
-    if (!isset($earning)) redirect(link_to('finances'));
+    if (!isset($earning)) {
+        redirect(link_to('finances'));
+    }
     $earning['date'] = format_date(db_date2unixtime($earning['date']));
-    $earning['value']= format_money($earning['value']);
+    $earning['value'] = format_money($earning['value']);
     $log_messages = array();
     if (isset($_POST['submit'])) {
         if (db_delete_earning($earning)) {
@@ -143,54 +135,57 @@ function action_delete_earning() {/*{{{*/
         echo db_error();
     }
     form_earning($earning, 'delete', $log_messages);
-}/*}}}*/
-
+}
 
-function form_earning($earning = array(), $task, $log_messages) {/*{{{*/
+function form_earning($earning = array(), $task, $log_messages)
+{
     global $EARNING_TYPES, $ACCOUNT_TYPES;
 
     $readonly = ($task == 'delete');
 
     ?>
-    <form action="<?=link_to($task . '_earning')?>" method="post" class="clearfix" id="earning_form" style="<?php if ($_REQUEST['action'] == 'finances') : ?>float: left<?php else :?>margin-top: 2em<?php endif ?>">
-        <?php if (isset($earning['id'])) : ?><?=html_hidden_field('id', $earning)?><?php endif ?>
+    <form action="<?php echo link_to($task . '_earning') ?>" method="post" class="clearfix" id="earning_form"
+          style="<?php if ($_REQUEST['action'] == 'finances') : ?>float: left<?php else : ?>margin-top: 2em<?php endif ?>">
+        <?php if (isset($earning['id'])) : ?><?php echo html_hidden_field('id', $earning) ?><?php endif ?>
         <fieldset>
-        <?php if     ($task == 'create') : ?>
-            <legend>Neue Einnahme</legend>
-        <?php elseif ($task == 'delete') : ?>
-            <legend>Einnahme l&ouml;schen</legend>
-        <?php elseif ($task == 'change') : ?>
-            <legend>Einnahme &auml;ndern</legend>
-        <?php endif ?>
+            <?php if ($task == 'create') : ?>
+                <legend>Neue Einnahme</legend>
+            <?php elseif ($task == 'delete') : ?>
+                <legend>Einnahme l&ouml;schen</legend>
+            <?php elseif ($task == 'change') : ?>
+                <legend>Einnahme &auml;ndern</legend>
+            <?php endif ?>
             <?php log_messages($log_messages); ?>
-            <?=html_text_field('Datum', 'date', $earning, $readonly)?>
-            <?=html_list_box('Typ', 'type', $EARNING_TYPES, $earning, $readonly)?>
-            <?=html_member_list_box('Mitglied', 'member_id', $earning, $readonly)?>
-            <?=html_money_field('Betrag', 'value', $earning, $readonly)?>
-            <?=html_text_field('Beschreibung', 'description', $earning, $readonly)?>
-            <?=html_list_box('Ziel', 'account', $ACCOUNT_TYPES, $earning, $readonly)?>
-            <?=html_checkbox('Bezahlt', 'status', $earning['status'] == 'paid', 1, $readonly)?>
+            <?php echo html_text_field('Datum', 'date', $earning, $readonly) ?>
+            <?php echo html_list_box('Typ', 'type', $EARNING_TYPES, $earning, $readonly) ?>
+            <?php echo html_member_list_box('Mitglied', 'member_id', $earning, $readonly) ?>
+            <?php echo html_money_field('Betrag', 'value', $earning, $readonly) ?>
+            <?php echo html_text_field('Beschreibung', 'description', $earning, $readonly) ?>
+            <?php echo html_list_box('Ziel', 'account', $ACCOUNT_TYPES, $earning, $readonly) ?>
+            <?php echo html_checkbox('Bezahlt', 'status', $earning['status'] == 'paid', 1, $readonly) ?>
         </fieldset>
-    <?php if ($task == 'delete') : ?>
-        <input class="submit" type="submit" name="submit" value="L&ouml;schen"/>
-    <?php else : ?>
-        <input class="submit" type="submit" name="submit" value="Speichern"/>
-    <?php endif ?>
+        <?php if ($task == 'delete') : ?>
+            <input class="submit" type="submit" name="submit" value="L&ouml;schen"/>
+        <?php else : ?>
+            <input class="submit" type="submit" name="submit" value="Speichern"/>
+        <?php endif ?>
     </form>
     <?php if ($task == 'change') : ?>
-        <br/>
-        <a href="<?=html_escape(link_to('delete_earning', array('id' => $earning['id'])))?>">Einnahme l&ouml;schen</a>
-        <a href="<?=html_escape(link_to('finances'))?>">Neue Einnahme</a>
-    <?php elseif ($task == 'delete') : ?>
-        <br/>
-        <a href="<?=html_escape(link_to('finances'))?>">Neue Einnahme</a>
-    <?php endif ?>
+    <br/>
+    <a href="<?php echo html_escape(link_to('delete_earning', array('id' => $earning['id']))) ?>">Einnahme l&ouml;schen</a>
+    <a href="<?php echo html_escape(link_to('finances')) ?>">Neue Einnahme</a>
+<?php elseif ($task == 'delete') : ?>
+    <br/>
+    <a href="<?php echo html_escape(link_to('finances')) ?>">Neue Einnahme</a>
+<?php endif ?>
     <?php
-}/*}}}*/
-
+}
 
-function action_create_earnings() {/*{{{*/
-    if (empty($_POST['earnings']) || !is_array($_POST['earnings'])) redirect(link_to('finances'));
+function action_create_earnings()
+{
+    if (empty($_POST['earnings']) || !is_array($_POST['earnings'])) {
+        redirect(link_to('finances'));
+    }
     db_begin();
     foreach ($_POST['earnings'] as $post_data) {
         $log_messages = array();
@@ -205,8 +200,7 @@ function action_create_earnings() {/*{{{*/
                 db_rollback();
                 return;
             }
-        }
-        else {
+        } else {
             db_rollback();
             echo '<h2>Verbuchen von Einnahmen</h2><p>Beim Verbuchen der Einnahmen ist ein Fehler aufgetreten:</p>';
             log_messages($log_messages);
@@ -214,14 +208,17 @@ function action_create_earnings() {/*{{{*/
         }
     }
     db_commit();
-    
+
     // SET directdebit from FRST to RCUR
     foreach ($_POST['earnings'] as $post_data) {
         $member['modified_at'] = db_unixtime2datetime(time());
         $member['directdebit'] = 3; // RCUR
-        db_update_single(DB_TABLE_MEMBERS, $member, sprintf('directdebit=\'2\' AND id=\'%1$d\'', db_escape($post_data['member_id'])));
+        db_update(
+            'members',
+            $member,
+            sprintf("directdebit=2 AND id=%d", (int)$post_data['member_id'])
+        );
     }
 
     redirect(link_to('finances'));
-}/*}}}*/
-
+}
index 7a56de6..493483c 100644 (file)
 <?php
 
-$SQL_CREATE_EVENTS = sprintf('
-    CREATE TABLE IF NOT EXISTS `%1$s` (
-      `id` int(10) unsigned NOT NULL auto_increment,
-      `event_date` date NOT NULL,
-      `event_type` enum(\'joined\',\'changed\',\'leaved\') NOT NULL,
-      `member_id` int(10) unsigned NOT NULL,
-      `member_type` enum(\'regular\',\'patron\',\'honorary\') NULL,
-      `fee` DECIMAL(10,2) NULL,
-      `payment_interval` enum(\'monthly\', \'quarterly\', \'halfyearly\', \'yearly\') NULL,
-      `created_at` datetime NOT NULL,
-      `modified_at` datetime NOT NULL,
-      PRIMARY KEY  (`id`),
-      UNIQUE KEY `member_id_event_date` (`member_id`, `event_date`)
-    ) ENGINE=InnoDB DEFAULT CHARSET=%2$s
-    ', DB_TABLE_EVENTS, DB_CHARSET);
-
 $EVENT_TYPES = array(
-    'joined'    => 'Eintritt',
-    'changed'   => 'Änderung',
-    'leaved'    => 'Austritt'
+    'joined'  => 'Eintritt',
+    'changed' => 'Änderung',
+    'leaved'  => 'Austritt'
 );
 
 $PAYMENT_INTERVALS = array(
-    'monthly'   => 'monatlich',
-    'quarterly' => 'vierteljährlich',
-    'halfyearly'=> 'halbjährlich',
-    'yearly'    => 'jährlich'
+    'monthly'    => 'monatlich',
+    'quarterly'  => 'vierteljährlich',
+    'halfyearly' => 'halbjährlich',
+    'yearly'     => 'jährlich'
 );
 
 $MEMBER_TYPES = array(
-    'regular'   => 'Ordentliches Mitglied',
-    'patron'    => 'Fördermitglied',
-    'honorary'  => 'Ehrenmitglied'
+    'regular'  => 'Ordentliches Mitglied',
+    'patron'   => 'Fördermitglied',
+    'honorary' => 'Ehrenmitglied'
 );
 
-/* DB functions {{{ */
-
-function db_create_event($event) {
+// DB functions
+function db_create_event($event)
+{
     unset($event['id']);
-    $event['event_date']    = db_unixtime2datetime(ui_date2unixtime($event['event_date']));
-    $event['fee']                  = ui_money2float($event['fee']);
-    $event['created_at']    = db_unixtime2datetime(time());
-    $event['modified_at']   = db_unixtime2datetime(time());
-    return (db_insert_single(DB_TABLE_EVENTS, $event));
+    $event['event_date'] = db_unixtime2datetime(ui_date2unixtime($event['event_date']));
+    $event['fee'] = ui_money2float($event['fee']);
+    $event['created_at'] = db_unixtime2datetime(time());
+    $event['modified_at'] = db_unixtime2datetime(time());
+    return (db_insert('events', $event));
 }
 
-function db_change_event($event) {
+function db_change_event($event)
+{
     $id = $event['id'];
     unset($event['id']);
     unset($event['member_id']);
-    $event['event_date']    = db_unixtime2datetime(ui_date2unixtime($event['event_date']));
-    $event['fee']                  = ui_money2float($event['fee']);
-    $event['modified_at']   = db_unixtime2datetime(time());
+    $event['event_date'] = db_unixtime2datetime(ui_date2unixtime($event['event_date']));
+    $event['fee'] = ui_money2float($event['fee']);
+    $event['modified_at'] = db_unixtime2datetime(time());
     $special = '';
-    if (!isset($event['fee']             )) { $special .= ',`fee`=NULL';              }
-    if (!isset($event['member_type']     )) { $special .= ',`member_type`=NULL';      }
-    if (!isset($event['payment_interval'])) { $special .= ',`payment_interval`=NULL'; }
-    return db_update_single(DB_TABLE_EVENTS, $event, sprintf('id=\'%1$d\'', db_escape($id)), $special);
+    if (!isset($event['fee'])) {
+        $special .= ',`fee`=NULL';
+    }
+    if (!isset($event['member_type'])) {
+        $special .= ',`member_type`=NULL';
+    }
+    if (!isset($event['payment_interval'])) {
+        $special .= ',`payment_interval`=NULL';
+    }
+    return db_update('events', $event, sprintf("id=%d", (int)$id), $special);
 }
 
-function db_delete_event($event) {
-    return db_delete_single(DB_TABLE_EVENTS, sprintf('id=\'%1$d\'', db_escape($event['id'])));
+function db_delete_event($event)
+{
+    return db_delete('events', 'id=?', [$event['id']]);
 }
 
-function db_get_events_for_member($member_id, $unixtime_start = NULL, $unixtime_end = NULL) {
-       $conditions = array(
-               sprintf('member_id=\'%d\'', db_escape($member_id))
-       );
-       if (isset($unixtime_start)) $conditions[] = sprintf('event_date>=\'%s\'', db_unixtime2date($unixtime_start));
-       if (isset($unixtime_end)  ) $conditions[] = sprintf('event_date<=\'%s\'', db_unixtime2date($unixtime_end));
-       
-    $sql = 'SELECT * FROM %1$s WHERE %2$s ORDER BY event_date ASC';
-    return db_select_multi(sprintf($sql, DB_TABLE_EVENTS, join(' AND ', $conditions)));
-}
+function db_get_events_for_member($member_id, $unixtime_start = null, $unixtime_end = null)
+{
+    // @TODO: Change to prepared statement
+    $conditions = array(
+        sprintf("member_id=%d", (int)$member_id)
+    );
+    if (isset($unixtime_start)) {
+        $conditions[] = sprintf("event_date>='%s'", db_unixtime2date($unixtime_start));
+    }
+    if (isset($unixtime_end)) {
+        $conditions[] = sprintf("event_date<='%s'", db_unixtime2date($unixtime_end));
+    }
 
-function db_get_event_with_member_and_date($member_id, $event_date) {
-    $sql = 'SELECT * FROM %1$s WHERE member_id=\'%2$d\' AND event_date=\'%3$s\' LIMIT 1';
-    return db_select_single(sprintf($sql, DB_TABLE_EVENTS, db_escape($member_id), db_escape($event_date)));
+    $sql = 'SELECT * FROM `events` WHERE %s ORDER BY event_date ASC';
+    return db_select_multi(sprintf($sql, join(' AND ', $conditions)));
 }
 
-function db_get_event_with_id($event_id) {
-    $sql = 'SELECT * FROM %1$s WHERE id=\'%2$d\' LIMIT 1';
-    return db_select_single(sprintf($sql, DB_TABLE_EVENTS, db_escape($event_id)));
+function db_get_event_with_member_and_date($member_id, $event_date)
+{
+    $sql = 'SELECT * FROM `events` WHERE member_id=? AND event_date=? LIMIT 1';
+    return db_select_single($sql, [$member_id, $event_date]);
 }
 
-/* }}} */
-
+function db_get_event_with_id($event_id)
+{
+    $sql = 'SELECT * FROM `events` WHERE id=? LIMIT 1';
+    return db_select_single($sql, [$event_id]);
+}
 
-function validate_event($userdata, &$dbdata, &$validation) {/*{{{*/
+function validate_event($userdata, &$dbdata, &$validation)
+{
     global $EVENT_TYPES, $MEMBER_TYPES, $PAYMENT_INTERVALS;
     $fields = array(
-        'id'              => 'number',
-        'event_date'      => 'date',
-        'fee'             => 'fee',
-        'event_type'      => $EVENT_TYPES,
-        'member_type'     => $MEMBER_TYPES,
-        'payment_interval'=> $PAYMENT_INTERVALS,
+        'id'               => 'number',
+        'event_date'       => 'date',
+        'fee'              => 'fee',
+        'event_type'       => $EVENT_TYPES,
+        'member_type'      => $MEMBER_TYPES,
+        'payment_interval' => $PAYMENT_INTERVALS,
     );
     $orig = $dbdata;
     foreach ($fields as $name => $type) {
-        if (!isset($userdata[$name])) continue;
+        if (!isset($userdata[$name])) {
+            continue;
+        }
         $dbdata[$name] = $userdata[$name];
     }
 
-
-// ids must be equal
-// member_ids must be equal
-// date must be unique for given member
+    // ids must be equal
+    // member_ids must be equal
+    // date must be unique for given member
     if (isset($orig['id'])) {
         if ($dbdata['id'] != $orig['id']) {
             $validation[] = 'Irgendwas anderes ist sehr sehr komisch.';
         }
-               if (empty($dbdata['event_date'])) {
+        if (empty($dbdata['event_date'])) {
             $validation[] = 'Bitte ein Datum für das Ereignis eingeben.';
-               }
-        elseif (!validate_event_date($dbdata['member_id'], $dbdata['event_date'], $dbdata['id'])) {
+        } elseif (!validate_event_date($dbdata['member_id'], $dbdata['event_date'], $dbdata['id'])) {
             $validation[] = 'An dem angegebenen Datum existiert schon ein Ereignis.';
         }
         return (count($validation) == 0);
     }
-       if (empty($dbdata['event_date'])) {
-           $validation[] = 'Bitte ein Datum für das Ereignis eingeben.';
-       }
-    elseif (!validate_event_date($dbdata['member_id'], $dbdata['event_date'])) {
+    if (empty($dbdata['event_date'])) {
+        $validation[] = 'Bitte ein Datum für das Ereignis eingeben.';
+    } elseif (!validate_event_date($dbdata['member_id'], $dbdata['event_date'])) {
         $validation[] = 'An dem angegebenen Datum existiert schon ein Ereignis.';
     }
     return (count($validation) == 0);
-}/*}}}*/
-
-
-
+}
 
-function validate_event_date($member_id, $event_date, $event_id = NULL) {/*{{{*/
+function validate_event_date($member_id, $event_date, $event_id = null)
+{
     $event_date = db_unixtime2date(ui_date2unixtime($event_date));
-    $event      = db_get_event_with_member_and_date($member_id, $event_date);
+    $event = db_get_event_with_member_and_date($member_id, $event_date);
 
     // theres no event with this date
-    if (!isset($event)) return true;
+    if (!isset($event)) {
+        return true;
+    }
 
     // there is a event, but maybe its the one we got passed
-    if (isset($event_id) && $event_id == $event['id']) return true;
+    if (isset($event_id) && $event_id == $event['id']) {
+        return true;
+    }
 
     return false;
-}/*}}}*/
-
+}
 
-function action_list_events($member = NULL) {/*{{{*/
+function action_list_events($member = null)
+{
     global $EVENT_TYPES, $MEMBER_TYPES, $PAYMENT_INTERVALS;
 
     if (!isset($member)) {
-        if (!isset($_REQUEST['member_id'])) redirect(link_to());
+        if (!isset($_REQUEST['member_id'])) {
+            redirect(link_to());
+        }
         $member = db_get_member_with_id($_REQUEST['id']);
-        if (!isset($member)) redirect(link_to());
+        if (!isset($member)) {
+            redirect(link_to());
+        }
     }
 
     $events = db_get_events_for_member($member['id']);
@@ -160,55 +163,65 @@ function action_list_events($member = NULL) {/*{{{*/
     ?>
     <h3 id="events">Ereignisse</h3>
     <?php if (isset($events)) : ?>
-        <table>
-            <tr>
-                <th>Datum</th>
-                <th>Ereignistyp</th>
-                <th>Mitgliedstyp</th>
-                <th>Beitrag</th>
-                <th>Zahlungsintervall</th>
-            </tr>
+    <table>
+        <tr>
+            <th>Datum</th>
+            <th>Ereignistyp</th>
+            <th>Mitgliedstyp</th>
+            <th>Beitrag</th>
+            <th>Zahlungsintervall</th>
+        </tr>
         <?php foreach ($events as $event) : ?>
             <tr>
-                <td><a href="<?=html_escape(link_to('change_event', array('id' => $event['id'])))?>#event_form"><?=html_escape(format_date(db_date2unixtime($event['event_date'])))?></a></td>
-                <td><?=html_escape($EVENT_TYPES[$event['event_type']])?></td>
-                <td><?=html_escape(isset($event['member_type'])? $MEMBER_TYPES[$event['member_type']] : '-')?></td>
-                <td><?=html_escape(isset($event['fee'])? format_money($event['fee']) : '-')?></td>
-                <td><?=html_escape(isset($event['payment_interval'])? $PAYMENT_INTERVALS[$event['payment_interval']] : '-')?></td>
+                <td><a href="<?php echo html_escape(link_to('change_event',
+                        array('id' => $event['id']))) ?>#event_form"><?php echo html_escape(format_date(db_date2unixtime($event['event_date']))) ?></a>
+                </td>
+                <td><?php echo html_escape($EVENT_TYPES[$event['event_type']]) ?></td>
+                <td><?php echo html_escape(isset($event['member_type']) ? $MEMBER_TYPES[$event['member_type']] : '-') ?></td>
+                <td><?php echo html_escape(isset($event['fee']) ? format_money($event['fee']) : '-') ?></td>
+                <td><?php echo html_escape(isset($event['payment_interval']) ? $PAYMENT_INTERVALS[$event['payment_interval']] : '-') ?></td>
             </tr>
         <?php endforeach ?>
-        </table>
-    <?php else : ?>
-        <p>Bisher gibt's noch keine Ereignisse.</p>
-    <?php endif ?>
+    </table>
+<?php else : ?>
+    <p>Bisher gibt's noch keine Ereignisse.</p>
+<?php endif ?>
     <?php
-}/*}}}*/
-
-
+}
 
-function action_create_event($member = NULL) {/*{{{*/
+function action_create_event($member = null)
+{
     if (!isset($member)) {
-        if (!isset($_REQUEST['member_id'])) redirect(link_to());
+        if (!isset($_REQUEST['member_id'])) {
+            redirect(link_to());
+        }
         $member = db_get_member_with_id($_REQUEST['id']);
-        if (!isset($member)) redirect(link_to());
+        if (!isset($member)) {
+            redirect(link_to());
+        }
     }
     $event = array();
-    $event['event_date']    = format_date(time());
-    $event['member_id']     = $member['id'];
+    $event['event_date'] = format_date(time());
+    $event['member_id'] = $member['id'];
     $events = db_get_events_for_member($member['id']);
     if (empty($events)) {
         $event['member_type'] = 'regular';
-    }
-    else {
+    } else {
         $event['event_type'] = 'changed';
     }
     $log_messages = array();
     if (isset($_POST['submit'])) {
         unset($_POST['id']);
         if (validate_event($_POST, $event, $log_messages)) {
-            if (empty($event['fee']             )) unset($event['fee']             );
-            if (empty($event['member_type']     )) unset($event['member_type']     );
-            if (empty($event['payment_interval'])) unset($event['payment_interval']);
+            if (empty($event['fee'])) {
+                unset($event['fee']);
+            }
+            if (empty($event['member_type'])) {
+                unset($event['member_type']);
+            }
+            if (empty($event['payment_interval'])) {
+                unset($event['payment_interval']);
+            }
             if (db_create_event($event)) {
                 redirect(link_to('view_member', array('id' => $event['member_id'])) . '#events');
             }
@@ -216,20 +229,31 @@ function action_create_event($member = NULL) {/*{{{*/
         }
     }
     form_event($event, 'create', $log_messages);
-}/*}}}*/
+}
 
-function action_change_event() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to());
+function action_change_event()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to());
+    }
     $event = db_get_event_with_id($_REQUEST['id']);
-    $event['event_date']    = format_date(db_date2unixtime($event['event_date']));
-    $event['fee']                  = format_money($event['fee']);
-    if (!isset($event)) redirect(link_to());
+    $event['event_date'] = format_date(db_date2unixtime($event['event_date']));
+    $event['fee'] = format_money($event['fee']);
+    if (!isset($event)) {
+        redirect(link_to());
+    }
     $log_messages = array();
     if (isset($_POST['submit'])) {
         if (validate_event($_POST, $event, $log_messages)) {
-            if (empty($event['fee']             )) unset($event['fee']             );
-            if (empty($event['member_type']     )) unset($event['member_type']     );
-            if (empty($event['payment_interval'])) unset($event['payment_interval']);
+            if (empty($event['fee'])) {
+                unset($event['fee']);
+            }
+            if (empty($event['member_type'])) {
+                unset($event['member_type']);
+            }
+            if (empty($event['payment_interval'])) {
+                unset($event['payment_interval']);
+            }
             if (db_change_event($event)) {
                 redirect(link_to('view_member', array('id' => $event['member_id'])) . '#events');
             }
@@ -238,18 +262,25 @@ function action_change_event() {/*{{{*/
     }
 
     $member = db_get_member_with_id($event['member_id']);
-    if (!isset($member)) redirect(link_to());
+    if (!isset($member)) {
+        redirect(link_to());
+    }
     form_member($member, true);
     action_list_events($member);
     form_event($event, 'change', $log_messages);
-}/*}}}*/
+}
 
-function action_delete_event() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to());
+function action_delete_event()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to());
+    }
     $event = db_get_event_with_id($_REQUEST['id']);
-    if (!isset($event)) redirect(link_to());
-    $event['event_date']    = format_date(db_date2unixtime($event['event_date']));
-    $event['fee']                  = format_money($event['fee']);
+    if (!isset($event)) {
+        redirect(link_to());
+    }
+    $event['event_date'] = format_date(db_date2unixtime($event['event_date']));
+    $event['fee'] = format_money($event['fee']);
     $log_messages = array();
     if (isset($_POST['submit'])) {
         if (db_delete_event($event)) {
@@ -258,52 +289,57 @@ function action_delete_event() {/*{{{*/
         echo db_error();
     }
     $member = db_get_member_with_id($event['member_id']);
-    if (!isset($member)) redirect(link_to());
+    if (!isset($member)) {
+        redirect(link_to());
+    }
     form_member($member, true);
     action_list_events($member);
     form_event($event, 'delete', $log_messages);
-}/*}}}*/
-
-
+}
 
-function form_event($event = array(), $task, $log_messages) {/*{{{*/
+function form_event($event = array(), $task, $log_messages)
+{
     global $EVENT_TYPES, $MEMBER_TYPES, $PAYMENT_INTERVALS;
 
     $readonly = ($task == 'delete');
 
     ?>
     <form action="#event_form" method="post" class="clearfix" id="event_form">
-        <?php if (isset($event['id'])) : ?><?=html_hidden_field('id', $event)?><?php endif ?>
-        <?=html_hidden_field('member_id', $event)?>
+        <?php if (isset($event['id'])) : ?><?php echo html_hidden_field('id', $event) ?><?php endif ?>
+        <?php echo html_hidden_field('member_id', $event) ?>
         <fieldset>
-        <?php if     ($task == 'create') : ?>
-            <legend>Neues Ereignis</legend>
-        <?php elseif ($task == 'delete') : ?>
-            <legend>Ereignis l&ouml;schen</legend>
-        <?php elseif ($task == 'change') : ?>
-            <legend>Ereignis &auml;ndern</legend>
-        <?php endif ?>
+            <?php if ($task == 'create') : ?>
+                <legend>Neues Ereignis</legend>
+            <?php elseif ($task == 'delete') : ?>
+                <legend>Ereignis l&ouml;schen</legend>
+            <?php elseif ($task == 'change') : ?>
+                <legend>Ereignis &auml;ndern</legend>
+            <?php endif ?>
             <?php log_messages($log_messages); ?>
-            <?=html_text_field('Datum', 'event_date', $event, $readonly)?>
-            <?=html_list_box('Ereignistyp', 'event_type', $EVENT_TYPES, $event, $readonly)?>
-            <?=html_list_box('Mitgliedstyp', 'member_type', array_merge(array(0 => 'unverändert'), $MEMBER_TYPES), $event, $readonly)?>
-            <?=html_money_field('Beitrag', 'fee', $event, $readonly)?>
+            <?php echo html_text_field('Datum', 'event_date', $event, $readonly) ?>
+            <?php echo html_list_box('Ereignistyp', 'event_type', $EVENT_TYPES, $event, $readonly) ?>
+            <?php echo html_list_box('Mitgliedstyp', 'member_type',
+                array_merge(array(0 => 'unverändert'), $MEMBER_TYPES),
+                $event, $readonly) ?>
+            <?php echo html_money_field('Beitrag', 'fee', $event, $readonly) ?>
             <small>Leer lassen wenn unver&auml;ndert.</small>
-            <?=html_list_box('Zahlungsintervall', 'payment_interval', array_merge(array(0 => 'unverändert'), $PAYMENT_INTERVALS), $event, $readonly)?>
+            <?php echo html_list_box('Zahlungsintervall', 'payment_interval',
+                array_merge(array(0 => 'unverändert'), $PAYMENT_INTERVALS), $event, $readonly) ?>
         </fieldset>
-    <?php if ($task == 'delete') : ?>
-        <input class="submit" type="submit" name="submit" value="L&ouml;schen"/>
-    <?php else : ?>
-        <input class="submit" type="submit" name="submit" value="Speichern"/>
-    <?php endif ?>
+        <?php if ($task == 'delete') : ?>
+            <input class="submit" type="submit" name="submit" value="L&ouml;schen"/>
+        <?php else : ?>
+            <input class="submit" type="submit" name="submit" value="Speichern"/>
+        <?php endif ?>
     </form>
     <?php if ($task == 'change') : ?>
-        <a href="<?=html_escape(link_to('delete_event', array('id' => $event['id'])))?>#event_form">Ereignis l&ouml;schen</a>
-        <a href="<?=html_escape(link_to('view_member', array('id' => $event['member_id'])))?>#event_form">Neues Ereignis</a>
-    <?php elseif ($task == 'delete') : ?>
-        <a href="<?=html_escape(link_to('view_member', array('id' => $event['member_id'])))?>#event_form">Neues Ereignis</a>
-    <?php endif ?>
+    <a href="<?php echo html_escape(link_to('delete_event', array('id' => $event['id']))) ?>#event_form">Ereignis
+        l&ouml;schen</a>
+    <a href="<?php echo html_escape(link_to('view_member', array('id' => $event['member_id']))) ?>#event_form">Neues
+        Ereignis</a>
+<?php elseif ($task == 'delete') : ?>
+    <a href="<?php echo html_escape(link_to('view_member', array('id' => $event['member_id']))) ?>#event_form">Neues
+        Ereignis</a>
+<?php endif ?>
     <?php
-}/*}}}*/
-
-
+}
index f16bb21..e08a06b 100644 (file)
@@ -1,81 +1,64 @@
 <?php
 
-$SQL_CREATE_EXPENSES = sprintf('
-    CREATE TABLE IF NOT EXISTS `%1$s` (
-      `id` int(10) unsigned NOT NULL auto_increment,
-      `date` date NOT NULL,
-      `type` enum(\'invoice\', \'gains_tax\', \'bankcharges\', \'account_transfer\', \'member_fee\', \'catering\') NULL,
-      `status` enum(\'open\',\'paid\') NOT NULL,
-      `account` enum(\'bank\',\'cash\') NOT NULL,
-      `value` DECIMAL(10,2) NULL,
-      `member_id` int(10) unsigned NOT NULL,
-      `description` TEXT NOT NULL,
-      `created_at` datetime NOT NULL,
-      `modified_at` datetime NOT NULL,
-      PRIMARY KEY  (`id`),
-      INDEX `idx_member_id` (`member_id`),
-      INDEX `idx_date` (`date`)
-    ) ENGINE=InnoDB DEFAULT CHARSET=%2$s
-    ', DB_TABLE_EXPENSES, DB_CHARSET);
-
 $EXPENSE_TYPES = array(
-    'invoice'   => 'Rechnung',
-    'gains_tax' => 'Kapitalertragssteuer',
-    'bankcharges' => 'Bankgebühren',
-    'account_transfer'  => 'Umbuchung',
-    'member_fee' => 'Rückbuchung Mitgliedsbeitrag',
-    'catering' => 'Raum - Getraenke & Snacks'
+    'invoice'          => 'Rechnung',
+    'gains_tax'        => 'Kapitalertragssteuer',
+    'bankcharges'      => 'Bankgebühren',
+    'account_transfer' => 'Umbuchung',
+    'member_fee'       => 'Rückbuchung Mitgliedsbeitrag',
+    'catering'         => 'Raum - Getraenke & Snacks'
 );
 
-
-/* DB functions {{{ */
-
-function db_get_expense_with_id($expense_id) {
-    $sql = 'SELECT * FROM %1$s WHERE id=\'%2$d\' LIMIT 1';
-    return db_select_single(sprintf($sql, DB_TABLE_EXPENSES, db_escape($expense_id)));
+// DB functions
+function db_get_expense_with_id($expense_id)
+{
+    $sql = 'SELECT * FROM `expenses` WHERE id=? LIMIT 1';
+    return db_select_single($sql, [$expense_id]);
 }
 
-function db_create_expense($expense) {
+function db_create_expense($expense)
+{
     unset($expense['id']);
-    $expense['date']        = db_unixtime2datetime(ui_date2unixtime($expense['date']));
-    $expense['value']       = ui_money2float($expense['value']);
-    $expense['created_at']  = db_unixtime2datetime(time());
+    $expense['date'] = db_unixtime2datetime(ui_date2unixtime($expense['date']));
+    $expense['value'] = ui_money2float($expense['value']);
+    $expense['created_at'] = db_unixtime2datetime(time());
     $expense['modified_at'] = db_unixtime2datetime(time());
-    return (db_insert_single(DB_TABLE_EXPENSES, $expense));
+    return (db_insert('expenses', $expense));
 }
 
-function db_change_expense($expense) {
+function db_change_expense($expense)
+{
     $id = $expense['id'];
     unset($expense['id']);
-    $expense['date']        = db_unixtime2datetime(ui_date2unixtime($expense['date']));
-    $expense['value']       = ui_money2float($expense['value']);
+    $expense['date'] = db_unixtime2datetime(ui_date2unixtime($expense['date']));
+    $expense['value'] = ui_money2float($expense['value']);
     $expense['modified_at'] = db_unixtime2datetime(time());
-    return db_update_single(DB_TABLE_EXPENSES, $expense, sprintf('id=\'%1$d\'', db_escape($id)));
+    return db_update('expenses', $expense, sprintf('id=%d', (int)$id));
 }
 
-function db_delete_expense($expense) {
-    return db_delete_single(DB_TABLE_EXPENSES, sprintf('id=\'%1$d\'', db_escape($expense['id'])));
+function db_delete_expense($expense)
+{
+    return db_delete('expenses', 'id=?', $expense['id']);
 }
 
-/* }}} */
-
-
-function validate_expense($userdata, &$dbdata, &$validation) {/*{{{*/
+function validate_expense($userdata, &$dbdata, &$validation)
+{
     global $EXPENSE_TYPES, $ACCOUNT_TYPES;
     $fields = array(
-        'id'              => 'number',
-        'date'            => 'date',
-        'type'            => $EXPENSE_TYPES,
-        'account'         => $ACCOUNT_TYPES,
-        'member_id'       => 'member',
-        'value'           => 'money',
-        'description'     => 'text',
-//      'status'          -  See below...
+        'id'          => 'number',
+        'date'        => 'date',
+        'type'        => $EXPENSE_TYPES,
+        'account'     => $ACCOUNT_TYPES,
+        'member_id'   => 'member',
+        'value'       => 'money',
+        'description' => 'text',
+        //'status'     -  See below...
     );
-    $orig = $dbdata;
     $dbdata['status'] = empty($userdata['status']) ? 'open' : 'paid';
     foreach ($fields as $name => $type) {
-        if (!isset($userdata[$name])) continue;
+        if (!isset($userdata[$name])) {
+            continue;
+        }
         $dbdata[$name] = $userdata[$name];
     }
 
@@ -87,13 +70,13 @@ function validate_expense($userdata, &$dbdata, &$validation) {/*{{{*/
     }
 
     return (count($validation) == 0);
-}/*}}}*/
-
+}
 
-function action_create_expense() {/*{{{*/
+function action_create_expense()
+{
     $expense = array();
-    $expense['date']      = format_date(time());
-    $expense['status']    = 'paid';
+    $expense['date'] = format_date(time());
+    $expense['status'] = 'paid';
     $log_messages = array();
     if (isset($_POST['submit'])) {
         unset($_POST['id']);
@@ -105,15 +88,19 @@ function action_create_expense() {/*{{{*/
         }
     }
     form_expense($expense, 'create', $log_messages);
-}/*}}}*/
-
+}
 
-function action_change_expense() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to('finances'));
+function action_change_expense()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to('finances'));
+    }
     $expense = db_get_expense_with_id($_REQUEST['id']);
-    if (!isset($expense)) redirect(link_to('finances'));
+    if (!isset($expense)) {
+        redirect(link_to('finances'));
+    }
     $expense['date'] = format_date(db_date2unixtime($expense['date']));
-    $expense['value']= format_money($expense['value']);
+    $expense['value'] = format_money($expense['value']);
     $log_messages = array();
     if (isset($_POST['submit'])) {
         if (validate_expense($_POST, $expense, $log_messages)) {
@@ -125,15 +112,19 @@ function action_change_expense() {/*{{{*/
     }
 
     form_expense($expense, 'change', $log_messages);
-}/*}}}*/
-
+}
 
-function action_delete_expense() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to('finances'));
+function action_delete_expense()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to('finances'));
+    }
     $expense = db_get_expense_with_id($_REQUEST['id']);
-    if (!isset($expense)) redirect(link_to('finances'));
+    if (!isset($expense)) {
+        redirect(link_to('finances'));
+    }
     $expense['date'] = format_date(db_date2unixtime($expense['date']));
-    $expense['value']= format_money($expense['value']);
+    $expense['value'] = format_money($expense['value']);
     $log_messages = array();
     if (isset($_POST['submit'])) {
         if (db_delete_expense($expense)) {
@@ -142,49 +133,48 @@ function action_delete_expense() {/*{{{*/
         echo db_error();
     }
     form_expense($expense, 'delete', $log_messages);
-}/*}}}*/
-
+}
 
-function form_expense($expense = array(), $task, $log_messages) {/*{{{*/
+function form_expense($expense = array(), $task, $log_messages)
+{
     global $EXPENSE_TYPES, $ACCOUNT_TYPES;
 
     $readonly = ($task == 'delete');
 
     ?>
-    <form action="<?=link_to($task . '_expense')?>" method="post" class="clearfix" id="expense_form" style="<?php if ($_REQUEST['action'] == 'finances') : ?>float: left<?php else :?>margin-top: 2em<?php endif ?>">
-        <?php if (isset($expense['id'])) : ?><?=html_hidden_field('id', $expense)?><?php endif ?>
+    <form action="<?php echo link_to($task . '_expense') ?>" method="post" class="clearfix" id="expense_form"
+          style="<?php if ($_REQUEST['action'] == 'finances') : ?>float: left<?php else : ?>margin-top: 2em<?php endif ?>">
+        <?php if (isset($expense['id'])) : ?><?php echo html_hidden_field('id', $expense) ?><?php endif ?>
         <fieldset>
-        <?php if     ($task == 'create') : ?>
-            <legend>Neue Ausgabe</legend>
-        <?php elseif ($task == 'delete') : ?>
-            <legend>Ausgabe l&ouml;schen</legend>
-        <?php elseif ($task == 'change') : ?>
-            <legend>Ausgabe &auml;ndern</legend>
-        <?php endif ?>
+            <?php if ($task == 'create') : ?>
+                <legend>Neue Ausgabe</legend>
+            <?php elseif ($task == 'delete') : ?>
+                <legend>Ausgabe l&ouml;schen</legend>
+            <?php elseif ($task == 'change') : ?>
+                <legend>Ausgabe &auml;ndern</legend>
+            <?php endif ?>
             <?php log_messages($log_messages); ?>
-            <?=html_text_field('Datum', 'date', $expense, $readonly)?>
-            <?=html_list_box('Typ', 'type', $EXPENSE_TYPES, $expense, $readonly)?>
-            <?=html_member_list_box('Mitglied', 'member_id', $expense, $readonly)?>
-            <?=html_money_field('Betrag', 'value', $expense, $readonly)?>
-            <?=html_text_field('Beschreibung', 'description', $expense, $readonly)?>
-            <?=html_list_box('Quelle', 'account', $ACCOUNT_TYPES, $expense, $readonly)?>
-            <?=html_checkbox('Bezahlt', 'status', $expense['status'] == 'paid', 1, $readonly)?>
+            <?php echo html_text_field('Datum', 'date', $expense, $readonly) ?>
+            <?php echo html_list_box('Typ', 'type', $EXPENSE_TYPES, $expense, $readonly) ?>
+            <?php echo html_member_list_box('Mitglied', 'member_id', $expense, $readonly) ?>
+            <?php echo html_money_field('Betrag', 'value', $expense, $readonly) ?>
+            <?php echo html_text_field('Beschreibung', 'description', $expense, $readonly) ?>
+            <?php echo html_list_box('Quelle', 'account', $ACCOUNT_TYPES, $expense, $readonly) ?>
+            <?php echo html_checkbox('Bezahlt', 'status', $expense['status'] == 'paid', 1, $readonly) ?>
         </fieldset>
-    <?php if ($task == 'delete') : ?>
-        <input class="submit" type="submit" name="submit" value="L&ouml;schen"/>
-    <?php else : ?>
-        <input class="submit" type="submit" name="submit" value="Speichern"/>
-    <?php endif ?>
+        <?php if ($task == 'delete') : ?>
+            <input class="submit" type="submit" name="submit" value="L&ouml;schen"/>
+        <?php else : ?>
+            <input class="submit" type="submit" name="submit" value="Speichern"/>
+        <?php endif ?>
     </form>
     <?php if ($task == 'change') : ?>
-        <br/>
-        <a href="<?=html_escape(link_to('delete_expense', array('id' => $expense['id'])))?>#expense_form">Ausgabe l&ouml;schen</a>
-        <a href="<?=html_escape(link_to('finances'))?>#expense_form">Neue Ausgabe</a>
-    <?php elseif ($task == 'delete') : ?>
-        <br/>
-        <a href="<?=html_escape(link_to('finances'))?>#expense_form">Neue Ausgabe</a>
-    <?php endif ?>
-    <?php
-}/*}}}*/
-
-
+    <br/>
+    <a href="<?php echo html_escape(link_to('delete_expense', array('id' => $expense['id']))) ?>#expense_form">Ausgabe l&ouml;schen</a>
+    <a href="<?php echo html_escape(link_to('finances')) ?>#expense_form">Neue Ausgabe</a>
+<?php elseif ($task == 'delete') : ?>
+    <br/>
+    <a href="<?php echo html_escape(link_to('finances')) ?>#expense_form">Neue Ausgabe</a>
+<?php
+endif;
+}
index c168a66..a9ceffc 100644 (file)
 <?php
 
+use MemberDB\Config\Config;
 
-/* HELPER functions FOR FEES {{{ */
+// HELPER functions FOR FEES
 
 // build an empty structure for holding monthly information
-function _fees_build_month_array($start_date, $end_date, $preset = array()) {
+function _fees_build_month_array($start_date, $end_date, $preset = array())
+{
     $start_info = getdate($start_date);
-    $end_info   = getdate($end_date);
+    $end_info = getdate($end_date);
 
-    if ($start_info['year'] > $end_info['year']) return $preset;
-    if ($start_info['year'] == $end_info['year'] && $start_info['mon'] > $end_info['mon']) return $preset;
+    if ($start_info['year'] > $end_info['year']) {
+        return $preset;
+    }
+    if ($start_info['year'] == $end_info['year'] && $start_info['mon'] > $end_info['mon']) {
+        return $preset;
+    }
 
     $ret = $preset;
     for ($year = $start_info['year']; $year <= $end_info['year']; $year++) {
-        if (!isset($ret[$year])) $ret[$year] = array();
+        if (!isset($ret[$year])) {
+            $ret[$year] = array();
+        }
         for (
-            $month  = (($year == $start_info['year']) ? $start_info['mon'] :  1);
-            $month <= (($year == $end_info['year']  ) ? $end_info['mon']   : 12);
+            $month = (($year == $start_info['year']) ? $start_info['mon'] : 1);
+            $month <= (($year == $end_info['year']) ? $end_info['mon'] : 12);
             $month++
         ) {
-            if (isset($ret[$year][$month])) continue;
+            if (isset($ret[$year][$month])) {
+                continue;
+            }
             $ret[$year][$month] = array(
-                'is_member'         => NULL,
-                'member_type'       => NULL,
-                'fee'               => NULL,
-                'payment_interval'  => NULL
+                'is_member'        => null,
+                'member_type'      => null,
+                'fee'              => null,
+                'payment_interval' => null
             );
         }
     }
     return $ret;
 }
 
-function _fees_apply_event_information(&$info, $events) {
+function _fees_apply_event_information(&$info, $events)
+{
+    $config = Config::getInstance();
     if (!empty($events)) {
 
         foreach ($events as $event) {
 
+            /** @var DateTime $founding_date */
+            $founding_date = $config->get('founding_date');
             $timestamp = db_date2unixtime($event['event_date']);
-            if ($timestamp < FOUNDING_DATE) $timestamp = FOUNDING_DATE;
+            if ($timestamp < $founding_date->getTimestamp()) {
+                $timestamp = $founding_date->getTimestamp();
+            }
             $date_info = getdate($timestamp);
 
-            if (!isset($info[$date_info['year']])) continue;
-            if (!isset($info[$date_info['year']][$date_info['mon']])) continue;
+            if (!isset($info[$date_info['year']])) {
+                continue;
+            }
+            if (!isset($info[$date_info['year']][$date_info['mon']])) {
+                continue;
+            }
 
-            if ($event['fee']              !== NULL)      $info[$date_info['year']][$date_info['mon']]['fee']              = $event['fee'];
-            if ($event['member_type']      !== NULL)      $info[$date_info['year']][$date_info['mon']]['member_type']      = $event['member_type'];
-            if ($event['event_type']       !== 'changed') $info[$date_info['year']][$date_info['mon']]['is_member']        = ($event['event_type'] == 'joined' ? 1 : 0);
-            if ($event['payment_interval'] !== NULL)      $info[$date_info['year']][$date_info['mon']]['payment_interval'] = $event['payment_interval'];
+            if ($event['fee'] !== null) {
+                $info[$date_info['year']][$date_info['mon']]['fee'] = $event['fee'];
+            }
+            if ($event['member_type'] !== null) {
+                $info[$date_info['year']][$date_info['mon']]['member_type'] = $event['member_type'];
+            }
+            if ($event['event_type'] !== 'changed') {
+                $info[$date_info['year']][$date_info['mon']]['is_member'] = ($event['event_type'] == 'joined' ? 1 : 0);
+            }
+            if ($event['payment_interval'] !== null) {
+                $info[$date_info['year']][$date_info['mon']]['payment_interval'] = $event['payment_interval'];
+            }
         }
     }
-    
-    $fee              = 0;
-    $member_type      = NULL;
-    $is_member        = false;
-    $payment_interval = NULL;
+
+    $fee = 0;
+    $member_type = null;
+    $is_member = false;
+    $payment_interval = null;
 
     foreach (array_keys($info) as $year) {
         foreach (array_keys($info[$year]) as $month) {
-            if (!isset($info[$year][$month]['fee'])) $info[$year][$month]['fee'] = $fee;
-            else $fee = $info[$year][$month]['fee'];
+            if (!isset($info[$year][$month]['fee'])) {
+                $info[$year][$month]['fee'] = $fee;
+            } else {
+                $fee = $info[$year][$month]['fee'];
+            }
 
-            if (!isset($info[$year][$month]['member_type'])) $info[$year][$month]['member_type'] = $member_type;
-            else $member_type = $info[$year][$month]['member_type'];
+            if (!isset($info[$year][$month]['member_type'])) {
+                $info[$year][$month]['member_type'] = $member_type;
+            } else {
+                $member_type = $info[$year][$month]['member_type'];
+            }
 
-            if (!isset($info[$year][$month]['is_member'])) $info[$year][$month]['is_member'] = $is_member;
-            else $is_member = $info[$year][$month]['is_member'];
+            if (!isset($info[$year][$month]['is_member'])) {
+                $info[$year][$month]['is_member'] = $is_member;
+            } else {
+                $is_member = $info[$year][$month]['is_member'];
+            }
 
-            if (!isset($info[$year][$month]['payment_interval'])) $info[$year][$month]['payment_interval'] = $payment_interval;
-            else $payment_interval = $info[$year][$month]['payment_interval'];
+            if (!isset($info[$year][$month]['payment_interval'])) {
+                $info[$year][$month]['payment_interval'] = $payment_interval;
+            } else {
+                $payment_interval = $info[$year][$month]['payment_interval'];
+            }
         }
     }
     return;
 }
 
-function fees_get_list_for_member($member_id, $end_date) {
-
+function fees_get_list_for_member($member_id, $end_date)
+{
     static $cache = array();
+    $config = Config::getInstance();
 
     $end_date = mktime(0, 0, 0, date('m', $end_date) + 1, 0, date('Y', $end_date)); // last day of given month
 
-    if (isset($cache[$member_id][$end_date])) return $cache[$member_id][$end_date];
+    if (isset($cache[$member_id][$end_date])) {
+        return $cache[$member_id][$end_date];
+    }
     if (isset($cache[$member_id])) {
         foreach (array_reverse(array_keys($cache[$member_id])) as $cache_date) {
             if ($cache_date <= $end_date) {
-                $ret = _fees_build_month_array($cache_date /* XXX einen Monat später wäre an dieser Stelle richtiger*/, $end_date, $cache[$member_id][$cache_date]);
+                $ret = _fees_build_month_array($cache_date /* XXX einen Monat später wäre an dieser Stelle richtiger*/,
+                    $end_date, $cache[$member_id][$cache_date]);
                 _fees_apply_event_information($ret, db_get_events_for_member($member_id, $cache_date, $end_date));
                 $cache[$member_id][$end_date] = $ret;
                 return $ret;
@@ -91,8 +135,12 @@ function fees_get_list_for_member($member_id, $end_date) {
         }
     }
 
-    $ret = _fees_build_month_array(FOUNDING_DATE, $end_date);
-    if (empty($ret)) return;
+    /** @var DateTime $founding_date */
+    $founding_date = $config->get('founding_date');
+    $ret = _fees_build_month_array($founding_date->getTimestamp(), $end_date);
+    if (empty($ret)) {
+        return null;
+    }
 
     _fees_apply_event_information($ret, db_get_events_for_member($member_id));
 
@@ -100,96 +148,122 @@ function fees_get_list_for_member($member_id, $end_date) {
     return $ret;
 }
 
-function fees_sum_for_member($member_id, $end_date) {
+function fees_sum_for_member($member_id, $end_date)
+{
     $membership_info = fees_get_list_for_member($member_id, $end_date);
-    
+
     $total = '0';
 
     foreach ($membership_info as $year => $months) {
         foreach ($months as $month => $info) {
-            if ($info['is_member']) $total = bcadd($total, $info['fee']);
+            if ($info['is_member']) {
+                $total = bcadd($total, $info['fee']);
+            }
         }
     }
     return $total;
 }
 
-function fees_for_member_at_date($member_id, $end_date) {
+function fees_for_member_at_date($member_id, $end_date)
+{
     $membership_info = fees_get_list_for_member($member_id, $end_date);
-    
+
     $this_year = array_pop($membership_info);
     $this_month = array_pop($this_year);
-    if ($this_month['is_member']) return $this_month['fee'];
-    return NULL;
+    if ($this_month['is_member']) {
+        return $this_month['fee'];
+    }
+    return null;
 }
 
-function fees_info_for_member($member_id, $end_date) {
+function fees_info_for_member($member_id, $end_date)
+{
     $membership_info = fees_get_list_for_member($member_id, $end_date);
-    
+
     $this_year = array_pop($membership_info);
     return array_pop($this_year);
 }
 
-function fees_sum_by_month($end_date) {
+function fees_sum_by_month($end_date)
+{
     $members = db_get_members();
     $fees = array();
-    if (empty($members)) return array();
+    if (empty($members)) {
+        return array();
+    }
     foreach ($members as $member) {
         $membership_info = fees_get_list_for_member($member['id'], $end_date);
         foreach ($membership_info as $year => $months) {
             foreach ($months as $month => $info) {
-                if (!isset($fees[$year][$month])) $fees[$year][$month] = '0';
-                if ($info['is_member']) $fees[$year][$month] = bcadd($fees[$year][$month], $info['fee']);
+                if (!isset($fees[$year][$month])) {
+                    $fees[$year][$month] = '0';
+                }
+                if ($info['is_member']) {
+                    $fees[$year][$month] = bcadd($fees[$year][$month], $info['fee']);
+                }
             }
         }
     }
     return $fees;
 }
-function fees_get_list_for_month($year, $month) {
+
+function fees_get_list_for_month($year, $month)
+{
     $members = db_get_members();
     $fees = array();
     foreach ($members as $member) {
         $membership_info = fees_get_list_for_member($member['id'], mktime(0, 0, 0, $month, 1, $year));
 
-        if (empty($membership_info)) continue;
-        $member['fee']       = $membership_info[$year][$month]['fee'];
+        if (empty($membership_info)) {
+            continue;
+        }
+        $member['fee'] = $membership_info[$year][$month]['fee'];
         $member['is_member'] = $membership_info[$year][$month]['is_member'];
         $fees[] = $member;
     }
     return $fees;
 }
 
-function fee_next_directdebit_for_member($member_id, $max_date = NULL) {
-
+function fee_next_directdebit_for_member($member_id, $max_date = null)
+{
+    $config = Config::getInstance();
     $member = db_get_member_with_id($member_id);
-    if (!$member['directdebit']) return NULL;
+    if (!$member['directdebit']) {
+        return null;
+    }
 
-    $sum_old_fees   = fees_sum_for_member($member_id, DIRECTDEBIT_DATE - 86400);
-    $sum_new_paid   = finance_get_paid_fees_for_member($member_id);
-    $year   = date('Y', DIRECTDEBIT_DATE);
-    $month  = date('n', DIRECTDEBIT_DATE);
-    $day    = 1;
-   
+    /** @var DateTime $direct_debit_date */
+    $direct_debit_date = $config->get('direct_debit')['date'];
+    $sum_old_fees = fees_sum_for_member($member_id, $direct_debit_date->getTimestamp() - 86400);
+    $sum_new_paid = finance_get_paid_fees_for_member($member_id);
+    $year = $direct_debit_date->format('Y');
+    $month = $direct_debit_date->format('n');
+    $day = 1;
 
 
     while (true) {
         $start_date = mktime(0, 0, 0, $month, $day, $year);
-        if (isset($max_date) && $start_date > $max_date) return NULL;
+        if (isset($max_date) && $start_date > $max_date) {
+            return null;
+        }
 
         // check if fee is zero at the moment and skip to next event
         // quit searching if theres no event in future
         $current_fee = fees_for_member_at_date($member_id, $start_date);
         if (empty($current_fee)) {
             $events = db_get_events_for_member($member_id, $start_date + 86400);
-            if (empty($events)) return NULL;
+            if (empty($events)) {
+                return null;
+            }
             $start_date = db_date2unixtime($events[0]['event_date']);
-            $day   = date('j', $start_date);
+            $day = date('j', $start_date);
             $month = date('n', $start_date);
-            $year  = date('Y', $start_date);
+            $year = date('Y', $start_date);
             continue;
         }
 
-        $sum_fees       = fees_sum_for_member($member_id, $start_date);
-        $sum_new_fees   = bcsub($sum_fees, $sum_old_fees);
+        $sum_fees = fees_sum_for_member($member_id, $start_date);
+        $sum_new_fees = bcsub($sum_fees, $sum_old_fees);
         if (bccomp($sum_new_fees, $sum_new_paid) == 1) {
             $info = fees_get_list_for_member($member_id, $start_date);
             $months = 1;
@@ -199,33 +273,43 @@ function fee_next_directdebit_for_member($member_id, $max_date = NULL) {
                 'info'  => '',
             );
             switch ($info[$year][$month]['payment_interval']) {
-                case 'monthly'   : $months = 1;  break;
-                case 'quarterly' : $months = 3;  break;
-                case 'halfyearly': $months = 6;  break;
-                case 'yearly'    : $months = 12; break;
+                case 'monthly'   :
+                    $months = 1;
+                    break;
+                case 'quarterly' :
+                    $months = 3;
+                    break;
+                case 'halfyearly':
+                    $months = 6;
+                    break;
+                case 'yearly'    :
+                    $months = 12;
+                    break;
             }
             if ($months == 1) {
-                $ret['info'] = dtaus_string(sprintf('CCCFFM %d, %s', $member['number'], format_month($start_date))); 
+                $ret['info'] = dtaus_string(sprintf('CCCFFM %d, %s', $member['number'], format_month($start_date)));
                 return $ret;
             }
             $end_date = mktime(0, 0, 0, $month + $months - 1, 1, $year);
             $sum_fee_end = fees_sum_for_member($member_id, $end_date);
             $ret['value'] = bcadd($ret['value'], bcsub($sum_fee_end, $sum_fees));
-            $ret['info'] = dtaus_string(sprintf('CCCFFM %d, %s-%s', $member['number'], format_month($start_date), format_month($end_date)));
+            $ret['info'] = dtaus_string(sprintf('CCCFFM %d, %s-%s', $member['number'], format_month($start_date),
+                format_month($end_date)));
             return $ret;
         }
         $day = 1;
         $month++;
-        if ($month == 13) { $month = 1; $year++; }
+        if ($month == 13) {
+            $month = 1;
+            $year++;
+        }
     }
-    
-    
-}
-/* }}} */
 
+    return null;
+}
 
-function action_fees() {/*{{{*/
-
+function action_fees()
+{
     if (isset($_REQUEST['member_id'])) {
         render_fees_for_member($_REQUEST['member_id']);
         return;
@@ -239,50 +323,58 @@ function action_fees() {/*{{{*/
     render_accrued_fees_by_month();
     render_next_direct_debit();
     render_future_fees();
+}
 
-}/*}}}*/
-
-function render_fees_by_member() {/*{{{*/
+function render_fees_by_member()
+{
     $members = db_get_members();
-?>
-<h2>Mitgliedsbeitr&auml;ge nach Mitglied</h2>
-<table>
-    <tr>
-        <th>Mitgliedsnummer</th>
-        <th>Nickname</th>
-        <th style="text-align: right;">Angefallene Beitr&auml;ge</th>
-        <th style="text-align: right;">Aktueller Beitrag</th>
-        <th style="text-align: right;">Offener Beitrag</th>
-    </tr>
-<?php if (empty($members)) $members = array(); ?>
-<?php foreach ($members as $member) : ?>
-<?php
-    $current_fee  = fees_for_member_at_date($member['id'], time());
-
-    $sum_fees     = fees_sum_for_member($member['id'], time());
-    $sum_old_fees = fees_sum_for_member($member['id'], DIRECTDEBIT_DATE - 86400);
-    $sum_old_paid = finance_get_paid_fees_for_member($member['id'], true);
-    $sum_new_paid = finance_get_paid_fees_for_member($member['id']);
-    $sum_new_fees = bcsub($sum_fees, $sum_old_fees);
-    $open_fees    = bcadd(bcsub($sum_old_fees, $sum_old_paid), max(bcsub($sum_new_fees, $sum_new_paid), 0));
-?>
-    <tr>
-        <td><a href="<?=html_escape(link_to('fees', array('member_id'=> $member['id'])))?>"><?=html_escape($member['number'])?></a></td>
-        <td><?=html_escape($member['nickname'])?></td>
-        <td style="text-align: right;"><?=format_money($sum_fees)?></td>
-        <td style="text-align: right;"><?=isset($current_fee) ? format_money($current_fee) : '-' ?></td>
-        <td style="text-align: right;"><?=$open_fees > 0 ? format_money($open_fees) : '-' ?></td>
-    </tr>
-<?php endforeach ?>
-</table>
-<?php
-}/*}}}*/
+    $config = Config::getInstance();
+    ?>
+    <h2>Mitgliedsbeitr&auml;ge nach Mitglied</h2>
+    <table>
+        <tr>
+            <th>Mitgliedsnummer</th>
+            <th>Nickname</th>
+            <th style="text-align: right;">Angefallene Beitr&auml;ge</th>
+            <th style="text-align: right;">Aktueller Beitrag</th>
+            <th style="text-align: right;">Offener Beitrag</th>
+        </tr>
+        <?php if (empty($members)) {
+            $members = array();
+        } ?>
+        <?php foreach ($members as $member) : ?>
+            <?php
+            $current_fee = fees_for_member_at_date($member['id'], time());
+
+            $sum_fees = fees_sum_for_member($member['id'], time());
+            /** @var DateTime $direct_debit */
+            $direct_debit = $config->get('direct_debit')['date'];
+            $sum_old_fees = fees_sum_for_member($member['id'], $direct_debit->getTimestamp() - 86400);
+            $sum_old_paid = finance_get_paid_fees_for_member($member['id'], true);
+            $sum_new_paid = finance_get_paid_fees_for_member($member['id']);
+            $sum_new_fees = bcsub($sum_fees, $sum_old_fees);
+            $open_fees = bcadd(bcsub($sum_old_fees, $sum_old_paid), max(bcsub($sum_new_fees, $sum_new_paid), 0));
+            ?>
+            <tr>
+                <td><a href="<?php echo html_escape(link_to('fees',
+                        array('member_id' => $member['id']))); ?>"><?php echo html_escape($member['number']); ?></a>
+                </td>
+                <td><?php echo html_escape($member['nickname']); ?></td>
+                <td style="text-align: right;"><?php echo format_money($sum_fees); ?></td>
+                <td style="text-align: right;"><?php echo isset($current_fee) ? format_money($current_fee) : '-'; ?></td>
+                <td style="text-align: right;"><?php echo $open_fees > 0 ? format_money($open_fees) : '-'; ?></td>
+            </tr>
+        <?php endforeach ?>
+    </table>
+    <?php
+}
 
-function render_future_fees() {/*{{{*/
+function render_future_fees()
+{
     $total_paid = finance_get_total_paid_fees();
     $this_year = date('Y');
     $this_month = date('m');
-    $fees = fees_sum_by_month(mktime(0, 0, 0, date('m') + 6,   date('d'),   date('Y')+1));
+    $fees = fees_sum_by_month(mktime(0, 0, 0, date('m') + 6, date('d'), date('Y') + 1));
     $total = 0;
     foreach ($fees as $year => $months) {
         foreach ($months as $month => $fee) {
@@ -291,230 +383,254 @@ function render_future_fees() {/*{{{*/
         }
     }
     $fees = array_reverse($fees, true);
-?>
-<h2>Beitragsprognose nach Monat</h2>
-<table>
-    <tr>
-        <th>Monat</th>
-        <th style="text-align: right;">Mitgliedsbeitr&auml;ge</th>
-        <th style="text-align: right;">kummuliert</th>
-        <th style="text-align: right;">eingenommen</th>
-        <th style="text-align: right;"><strong>offen</strong></th>
-    </tr>
-<?php foreach ($fees as $year => $months) : ?>
-    <?php $months = array_reverse($months, true); ?>
-    <?php foreach ($months as $month => $data) : ?>
-    <tr<?php if ($year == $this_year && $month == $this_month) : ?> class="current"<?php endif?>>
-        <td><a href="<?=html_escape(link_to('fees', array('year' => $year, 'month'=> $month)))?>"><?=html_escape(format_month($year, $month))?></a></td>
-        <td style="text-align: right;"><?=html_escape(format_money($data['fee']))?></td>
-        <td style="text-align: right;"><?=html_escape(format_money($data['total']))?></td>
-        <td style="text-align: right;">
-        <?php if ($year == $this_year && $month == $this_month) : ?>
-            <?=html_escape(format_money($total_paid))?>
-        <?php endif ?>
-        </td>
-        <td style="text-align: right;">
-        <?php if ($year > $this_year || ($year >= $this_year && $month >= $this_month)) : ?>
-            <?=html_escape(format_money(bcsub($data['total'], $total_paid)))?>
-        <?php endif ?>
-        </td>
-    </tr>
-    <?php endforeach ?>
-<?php endforeach ?>
-</table>
-<?php
-}/*}}}*/
+    ?>
+    <h2>Beitragsprognose nach Monat</h2>
+    <table>
+        <tr>
+            <th>Monat</th>
+            <th style="text-align: right;">Mitgliedsbeitr&auml;ge</th>
+            <th style="text-align: right;">kummuliert</th>
+            <th style="text-align: right;">eingenommen</th>
+            <th style="text-align: right;"><strong>offen</strong></th>
+        </tr>
+        <?php foreach ($fees as $year => $months) : ?>
+            <?php $months = array_reverse($months, true); ?>
+            <?php foreach ($months as $month => $data) : ?>
+                <tr<?php if ($year == $this_year && $month == $this_month) : ?> class="current"<?php endif ?>>
+                    <td><a href="<?php echo html_escape(link_to('fees',
+                            array('year' => $year, 'month' => $month))); ?>"><?php echo html_escape(format_month($year,
+                                $month)); ?></a></td>
+                    <td style="text-align: right;"><?php echo html_escape(format_money($data['fee'])); ?></td>
+                    <td style="text-align: right;"><?php echo html_escape(format_money($data['total'])); ?></td>
+                    <td style="text-align: right;">
+                        <?php if ($year == $this_year && $month == $this_month) : ?>
+                            <?php echo html_escape(format_money($total_paid)); ?>
+                        <?php endif ?>
+                    </td>
+                    <td style="text-align: right;">
+                        <?php if ($year > $this_year || ($year >= $this_year && $month >= $this_month)) : ?>
+                            <?php echo html_escape(format_money(bcsub($data['total'], $total_paid))); ?>
+                        <?php endif ?>
+                    </td>
+                </tr>
+            <?php endforeach ?>
+        <?php endforeach ?>
+    </table>
+    <?php
+}
 
-function render_accrued_fees_by_month() {/*{{{*/
+function render_accrued_fees_by_month()
+{
     $fees = fees_sum_by_month(time());
     $fees = array_reverse($fees, true);
-?>
-<h2>Angefallene Mitgliedsbeitr&auml;ge nach Monat</h2>
-<table>
-    <tr>
-        <th>Monat</th>
-        <th style="text-align: right;">Mitgliedsbeitrag</th>
-    </tr>
-<?php foreach ($fees as $year => $months) : ?>
-    <?php $months = array_reverse($months, true); ?>
-    <?php foreach ($months as $month => $fee) : ?>
-    <tr>
-        <td><a href="<?=html_escape(link_to('fees', array('year' => $year, 'month'=> $month)))?>"><?=html_escape(format_month($year, $month))?></a></td>
-        <td style="text-align: right;"><?=html_escape(format_money($fee))?></td>
-    </tr>
-    <?php endforeach ?>
-<?php endforeach ?>
-</table>
-<?php
-}/*}}}*/
+    ?>
+    <h2>Angefallene Mitgliedsbeitr&auml;ge nach Monat</h2>
+    <table>
+        <tr>
+            <th>Monat</th>
+            <th style="text-align: right;">Mitgliedsbeitrag</th>
+        </tr>
+        <?php foreach ($fees as $year => $months) : ?>
+            <?php $months = array_reverse($months, true); ?>
+            <?php foreach ($months as $month => $fee) : ?>
+                <tr>
+                    <td><a href="<?php echo html_escape(link_to('fees',
+                            array('year' => $year, 'month' => $month))); ?>"><?php echo html_escape(format_month($year,
+                                $month)) ?></a></td>
+                    <td style="text-align: right;"><?php echo html_escape(format_money($fee)) ?></td>
+                </tr>
+            <?php endforeach ?>
+        <?php endforeach ?>
+    </table>
+    <?php
+}
 
-function render_accrued_fees_for_month($year, $month) {/*{{{*/
+function render_accrued_fees_for_month($year, $month)
+{
     $fees = fees_get_list_for_month($year, $month);
-?>
-<h2>Angefallene Mitgliedsbeitr&auml;ge f&uuml;r <?=format_month($year, $month)?></h2>
-<table>
-    <tr>
-        <th>Mitgliedsnummer</th>
-        <th>Nickname</th>
-        <th style="text-align: right;">Mitgliedsbeitrag</th>
-    </tr>
-<?php foreach ($fees as $info) : ?>
-    <tr>
-        <td><a href="<?=html_escape(link_to('fees', array('member_id'=> $info['id'])))?>"><?=html_escape($info['number'])?></a></td>
-        <td><?=html_escape($info['nickname'])?></td>
-        <td style="text-align: right;"><?=html_escape($info['is_member'] ? format_money($info['fee']) : '-')?></td>
-    </tr>
-<?php endforeach ?>
-</table>
-<p><a href="<?=html_escape(link_to('fees'))?>">Alle angefallenen Mitgliedsbeitr&auml;ge</a></p>
-<?php
-}/*}}}*/
+    ?>
+    <h2>Angefallene Mitgliedsbeitr&auml;ge f&uuml;r <?php echo format_month($year, $month) ?></h2>
+    <table>
+        <tr>
+            <th>Mitgliedsnummer</th>
+            <th>Nickname</th>
+            <th style="text-align: right;">Mitgliedsbeitrag</th>
+        </tr>
+        <?php foreach ($fees as $info) : ?>
+            <tr>
+                <td><a href="<?php echo html_escape(link_to('fees',
+                        array('member_id' => $info['id']))) ?>"><?php echo html_escape($info['number']) ?></a></td>
+                <td><?php echo html_escape($info['nickname']) ?></td>
+                <td style="text-align: right;"><?php echo html_escape($info['is_member'] ? format_money($info['fee']) : '-') ?></td>
+            </tr>
+        <?php endforeach ?>
+    </table>
+    <p><a href="<?php echo html_escape(link_to('fees')) ?>">Alle angefallenen Mitgliedsbeitr&auml;ge</a></p>
+    <?php
+}
 
-function render_next_direct_debit() {/*{{{*/
+function render_next_direct_debit()
+{
     $members = db_get_members();
-?>
-<h2>Nächste Abbuchungen nach Mitglied</h2>
-<table>
-    <tr>
-        <th>Mitgliedsnummer</th>
-        <th>Nickname</th>
-        <th style="text-align: right;">Verwendungszweck</th>
-        <th style="text-align: right;">Betrag</th>
-    </tr>
-<?php if (empty($members)) $members = array(); ?>
-<?php foreach ($members as $member) : ?>
-    <?php $next_debit = fee_next_directdebit_for_member($member['id']); ?>
-    <tr>
-        <td><a href="<?=html_escape(link_to('fees', array('member_id'=> $member['id'])))?>"><?=html_escape($member['number'])?></a></td>
-        <td><?=html_escape($member['nickname'])?></td>
-<?php if (empty($next_debit)) : ?>
-        <td>-</td>
-        <td style="text-align: right;">-</td>
-<?php else : ?>
-        <td><?=html_escape($next_debit['info'])?></td>
-        <td style="text-align: right;"><?=format_money($next_debit['value'])?></td>
-<?php endif ?>
-    </tr>
-<?php endforeach ?>
-</table>
-<?php
+    ?>
+    <h2>Nächste Abbuchungen nach Mitglied</h2>
+    <table>
+        <tr>
+            <th>Mitgliedsnummer</th>
+            <th>Nickname</th>
+            <th style="text-align: right;">Verwendungszweck</th>
+            <th style="text-align: right;">Betrag</th>
+        </tr>
+        <?php if (empty($members)) {
+            $members = array();
+        } ?>
+        <?php foreach ($members as $member) : ?>
+            <?php $next_debit = fee_next_directdebit_for_member($member['id']); ?>
+            <tr>
+                <td><a href="<?php echo html_escape(link_to('fees',
+                        array('member_id' => $member['id']))) ?>"><?php echo html_escape($member['number']) ?></a></td>
+                <td><?php echo html_escape($member['nickname']) ?></td>
+                <?php if (empty($next_debit)) : ?>
+                    <td>-</td>
+                    <td style="text-align: right;">-</td>
+                <?php else : ?>
+                    <td><?php echo html_escape($next_debit['info']) ?></td>
+                    <td style="text-align: right;"><?php echo format_money($next_debit['value']) ?></td>
+                <?php endif ?>
+            </tr>
+        <?php endforeach ?>
+    </table>
+    <?php
 }
 
-function render_fees_for_member($member_id) {/*{{{*/
+function render_fees_for_member($member_id)
+{
     global $MEMBER_TYPES, $EARNING_TYPES, $EXPENSE_TYPES;
+    $config = Config::getInstance();
+    /** @var DateTime $direct_debit */
+    $direct_debit = $config->get('direct_debit')['date'];
 
-    $member      = db_get_member_with_id($member_id);
-    if (!isset($member)) redirect(link_to('fees'));
+    $member = db_get_member_with_id($member_id);
+    if (!isset($member)) {
+        redirect(link_to('fees'));
+    }
 
     $membership_info = fees_get_list_for_member($member_id, time());
     $membership_info = array_reverse($membership_info, true);
 
-    $paid_fees = finance_list_paid_fees_for_member($member_id, time(), true);
+    $paid_fees = finance_list_paid_fees_for_member($member_id);
 
     $sum_new_paid = finance_get_paid_fees_for_member($member_id);
     $sum_old_paid = finance_get_paid_fees_for_member($member_id, true);
-    $sum_old_fees = fees_sum_for_member($member_id, DIRECTDEBIT_DATE - 86400);
-    $sum_fees     = fees_sum_for_member($member_id, time());
+    $sum_old_fees = fees_sum_for_member($member_id, $direct_debit->getTimestamp() - 86400);
+    $sum_fees = fees_sum_for_member($member_id, time());
     $sum_new_fees = bcsub($sum_fees, $sum_old_fees);
 
     $state = '';
     $new_open = 0;
     $old_open = 0;
-    if (bccomp($sum_new_fees, $sum_new_paid) == 1) $new_open = 1;
-    if (bccomp($sum_old_fees, $sum_old_paid) == 1) $old_open = 1;
+    if (bccomp($sum_new_fees, $sum_new_paid) == 1) {
+        $new_open = 1;
+    }
+    if (bccomp($sum_old_fees, $sum_old_paid) == 1) {
+        $old_open = 1;
+    }
 
     if ($new_open && $old_open) {
         $state = sprintf('Es sind noch %1$s Mitgliedsbeitrag offen, davon %2$s für die Zeit vor dem %3$s und %4$s für danach.',
             format_money(bcadd(bcsub($sum_old_fees, $sum_old_paid), bcsub($sum_new_fees, $sum_new_paid))),
             format_money(bcsub($sum_old_fees, $sum_old_paid)),
-            format_date(DIRECTDEBIT_DATE),
+            format_date($direct_debit->getTimestamp()),
             format_money(bcsub($sum_new_fees, $sum_new_paid))
         );
-    }
-    elseif($new_open) {
-        $state = sprintf('Es sind noch %1$s Mitgliedsbeitrag offen.', format_money(bcsub($sum_new_fees, $sum_new_paid)));
-    }
-    elseif($old_open) {
-        $state = sprintf('Für die Zeit vor dem %1$s sind noch %2$s Mitgliedsbeitrag offen.', format_date(DIRECTDEBIT_DATE), format_money(bcsub($sum_old_fees, $sum_old_paid)));
+    } elseif ($new_open) {
+        $state = sprintf('Es sind noch %1$s Mitgliedsbeitrag offen.',
+            format_money(bcsub($sum_new_fees, $sum_new_paid)));
+    } elseif ($old_open) {
+        $state = sprintf(
+            'Für die Zeit vor dem %1$s sind noch %2$s Mitgliedsbeitrag offen.',
+            format_date($direct_debit->getTimestamp()), format_money(bcsub($sum_old_fees, $sum_old_paid))
+        );
     }
 
     $next_debit = fee_next_directdebit_for_member($member_id);
 
-?>
-<h2>Mitgliedsbeitr&auml;ge von <?=html_escape(!empty($member['nickname']) ? $member['nickname'] : sprintf('Mitglied Nr. %d', $member['number']))?></h2>
-<h3>Mitgliedsdetails</h3>
-<table>
-    <tr>
-        <th>Mitgliedsnummer</th>
-        <th>Nickname</th>
-        <th>Status</th>
-    </tr>
-    <tr>
-        <td><a href="<?=html_escape(link_to('view_member', array('id'=> $member['id'])))?>"><?=html_escape($member['number'])?></a></td>
-        <td><?=html_escape($member['nickname'])?></strong></p></td>
-        <td>
-        <?php if (empty($state)) : ?>
-            Kein Beitragsrückstand
-        <?php else : ?>
-            <?=wordwrap(html_escape($state), 70, '<br/>')?>
-        <?php endif ?>
-</td>
-    </tr>
-</table>
-<div style="float: left">
-<h3>Angefallene Mitgliedsbeitr&auml;ge</h3>
-<table>
-    <tr>
-        <th>Monat</th>
-        <th>Mitgliedsart</th>
-        <th style="text-align: right;">Mitgliedsbeitrag</th>
-    </tr>
-<?php foreach ($membership_info as $year => $months) : ?>
-    <?php $months = array_reverse($months, true); ?>
-    <?php foreach ($months as $month => $info) : ?>
-    <tr>
-        <td><?=html_escape(format_month($year, $month))?></td>
-        <td><?=html_escape($info['is_member'] ? $MEMBER_TYPES[$info['member_type']] : 'Kein Mitglied')?></td>
-        <td style="text-align: right;"><?=html_escape($info['is_member'] ? format_money($info['fee']) : '-')?></td>
-    </tr>
-    <?php endforeach ?>
-<?php endforeach ?>
-</table>
-<p><a href="<?=html_escape(link_to('fees'))?>">Alle angefallenen Mitgliedsbeitr&auml;ge</a></p>
-</div>
-<div style="float: left; margin-left: 1em;">
-<h3>Nächste Abbuchung</h3>
-<table>
-    <tr>
-        <th>Verwendungszweck</th>
-        <th style="text-align: right;">Betrag</th>
-    </tr>
-<?php if (empty($next_debit)) : ?>
-        <td>-</td>
-        <td style="text-align: right;">-</td>
-<?php else : ?>
-        <td><?=html_escape($next_debit['info'])?></td>
-        <td style="text-align: right;"><?=format_money($next_debit['value'])?></td>
-<?php endif ?> 
-</table>
-<h3>Bezahlte Mitgliedsbeitr&auml;ge</h3>
-<table>
-    <tr>
-        <th>Monat</th>
-        <th style="text-align: right;">Typ</th>
-        <th style="text-align: right;">Betrag</th>
-    </tr>
-<?php foreach ($paid_fees as $payment) : ?>
-    <tr>
-        <td><?=html_escape(format_date(db_date2unixtime($payment['date'])))?></td>
-        <td><?=($payment['value'] < 0) ? $EXPENSE_TYPES[$payment['type']]: $EARNING_TYPES[$payment['type']]?></td>
-        <td style="text-align: right;"><?=format_money($payment['value'])?></td>
-    </tr>
-<?php endforeach ?>
-</table>
-</div>
-<br style="clear: left;"/>
-<?php
-}/*}}}*/
-
-
+    ?>
+    <h2>Mitgliedsbeitr&auml;ge
+        von <?php echo html_escape(!empty($member['nickname']) ? $member['nickname'] : sprintf('Mitglied Nr. %d',
+            $member['number'])) ?></h2>
+    <h3>Mitgliedsdetails</h3>
+    <table>
+        <tr>
+            <th>Mitgliedsnummer</th>
+            <th>Nickname</th>
+            <th>Status</th>
+        </tr>
+        <tr>
+            <td><a href="<?php echo html_escape(link_to('view_member',
+                    array('id' => $member['id']))) ?>"><?php echo html_escape($member['number']) ?></a></td>
+            <td><?php echo html_escape($member['nickname']) ?></strong></p></td>
+            <td>
+                <?php if (empty($state)) : ?>
+                    Kein Beitragsrückstand
+                <?php else : ?>
+                    <?php echo wordwrap(html_escape($state), 70, '<br/>') ?>
+                <?php endif ?>
+            </td>
+        </tr>
+    </table>
+    <div style="float: left">
+        <h3>Angefallene Mitgliedsbeitr&auml;ge</h3>
+        <table>
+            <tr>
+                <th>Monat</th>
+                <th>Mitgliedsart</th>
+                <th style="text-align: right;">Mitgliedsbeitrag</th>
+            </tr>
+            <?php foreach ($membership_info as $year => $months) : ?>
+                <?php $months = array_reverse($months, true); ?>
+                <?php foreach ($months as $month => $info) : ?>
+                    <tr>
+                        <td><?php echo html_escape(format_month($year, $month)) ?></td>
+                        <td><?php echo html_escape($info['is_member'] ? $MEMBER_TYPES[$info['member_type']] : 'Kein Mitglied') ?></td>
+                        <td style="text-align: right;"><?php echo html_escape($info['is_member'] ? format_money($info['fee']) : '-') ?></td>
+                    </tr>
+                <?php endforeach ?>
+            <?php endforeach ?>
+        </table>
+        <p><a href="<?php echo html_escape(link_to('fees')) ?>">Alle angefallenen Mitgliedsbeitr&auml;ge</a></p>
+    </div>
+    <div style="float: left; margin-left: 1em;">
+        <h3>Nächste Abbuchung</h3>
+        <table>
+            <tr>
+                <th>Verwendungszweck</th>
+                <th style="text-align: right;">Betrag</th>
+            </tr>
+            <?php if (empty($next_debit)) : ?>
+                <td>-</td>
+                <td style="text-align: right;">-</td>
+            <?php else : ?>
+                <td><?php echo html_escape($next_debit['info']) ?></td>
+                <td style="text-align: right;"><?php echo format_money($next_debit['value']) ?></td>
+            <?php endif ?>
+        </table>
+        <h3>Bezahlte Mitgliedsbeitr&auml;ge</h3>
+        <table>
+            <tr>
+                <th>Monat</th>
+                <th style="text-align: right;">Typ</th>
+                <th style="text-align: right;">Betrag</th>
+            </tr>
+            <?php foreach ($paid_fees as $payment) : ?>
+                <tr>
+                    <td><?php echo html_escape(format_date(db_date2unixtime($payment['date']))) ?></td>
+                    <td><?php echo ($payment['value'] < 0) ? $EXPENSE_TYPES[$payment['type']] : $EARNING_TYPES[$payment['type']] ?></td>
+                    <td style="text-align: right;"><?php echo format_money($payment['value']) ?></td>
+                </tr>
+            <?php endforeach ?>
+        </table>
+    </div>
+    <br style="clear: left;"/>
+    <?php
+}
index 5731292..dadd52b 100644 (file)
@@ -1,64 +1,67 @@
 <?php
 
+use MemberDB\Config\Config;
 
-function finance_get_total_paid_fees() {
-    $paid = db_select_single(sprintf('SELECT SUM(value) as paid_fees FROM %1$s WHERE type IN(\'old_fee\', \'fee\') AND status=\'paid\'',
-        DB_TABLE_EARNINGS
-    ));
-    $refunded = db_select_single(sprintf('SELECT SUM(value) as refunded_fees FROM %1$s WHERE type IN(\'member_fee\') AND status=\'paid\'',
-        DB_TABLE_EXPENSES
-    ));
+function finance_get_total_paid_fees()
+{
+    $paid = db_select_single("SELECT SUM(value) AS paid_fees FROM `earnings` WHERE type IN('old_fee', 'fee') AND `status`='paid'");
+    $refunded = db_select_single("SELECT SUM(value) AS refunded_fees FROM `expenses` WHERE type IN('member_fee') AND `status`='paid'");
 
     return bcsub($paid['paid_fees'], $refunded['refunded_fees']);
 }
 
-
-function finance_get_paid_fees_for_member($member_id, $old_fees = false) {
+function finance_get_paid_fees_for_member($member_id, $old_fees = false)
+{
     // $old_fees: Beiträge die nicht durch Lastschrift eingezogen werden.
     //            Falls zu viel bezahlt, müssen diese auf die per Lastschrift
     //            eingezogenen Beiträge angerechnet werden.
-    $row = db_select_single(sprintf('SELECT SUM(value) as paid_fees FROM %1$s WHERE member_id=\'%2$d\' AND type=\'%3$s\' AND status=\'paid\'',
-        DB_TABLE_EARNINGS,
-        db_escape($member_id),
-        $old_fees ? 'old_fee' : 'fee'
-    ));
+    $row = db_select_single(
+        "SELECT SUM(value) AS paid_fees FROM `earnings` WHERE member_id=? AND type=? AND `status`='paid'",
+        [$member_id, $old_fees ? 'old_fee' : 'fee']
+    );
 
     $paid_fees = $row['paid_fees'];
 
-    if ($old_fees) return $paid_fees;
+    if ($old_fees) {
+        return $paid_fees;
+    }
 
-    $invoiced_fees      = fees_sum_for_member($member_id, DIRECTDEBIT_DATE - 86400);
+    /** @var DateTime $direct_debit */
+    $direct_debit = Config::getInstance()->get('direct_debit')['date'];
+    $invoiced_fees = fees_sum_for_member($member_id, $direct_debit->getTimestamp() - 86400);
     $paid_invoiced_fees = finance_get_paid_fees_for_member($member_id, true);
-    if (bccomp($paid_invoiced_fees, $invoiced_fees) == 1) $paid_fees = bcadd($paid_fees, bcsub($paid_invoiced_fees, $invoiced_fees));
+    if (bccomp($paid_invoiced_fees, $invoiced_fees) == 1) {
+        $paid_fees = bcadd($paid_fees, bcsub($paid_invoiced_fees, $invoiced_fees));
+    }
 
 
-    $refunded = db_select_single(sprintf('SELECT SUM(value) as refunded_fees FROM %1$s WHERE member_id=\'%2$d\' AND type IN(\'member_fee\') AND status=\'paid\'',
-        DB_TABLE_EXPENSES,
-        db_escape($member_id)
-    ));
+    $refunded = db_select_single(
+        "SELECT SUM(value) AS refunded_fees FROM `expenses` WHERE member_id=? AND type IN('member_fee') AND `status`='paid'",
+        [$member_id]
+    );
     return bcsub($paid_fees, $refunded['refunded_fees']);
 }
 
-function finance_list_paid_fees_for_member($member_id) {
-    return db_select_multi(sprintf('
-               (SELECT id, date, type, status, account, value, member_id, description, created_at, modified_at FROM %1$s WHERE member_id=\'%3$d\' AND type IN(\'old_fee\', \'fee\')) UNION
-               (SELECT id, date, type, status, account, value*-1, member_id, description, created_at, modified_at FROM %2$s WHERE member_id=\'%3$d\' AND type IN(\'member_fee\'))
-               ORDER BY `date` DESC',
-        DB_TABLE_EARNINGS,
-        DB_TABLE_EXPENSES,
-        db_escape($member_id)
-    ));
+function finance_list_paid_fees_for_member($member_id)
+{
+    return db_select_multi("
+               (SELECT id, date, type, status, account, value, member_id, description, created_at, modified_at FROM `earnings` WHERE member_id=? AND type IN('old_fee', 'fee'))
+               UNION
+               (SELECT id, date, type, status, account, value*-1, member_id, description, created_at, modified_at FROM `expenses` WHERE member_id=? AND type IN('member_fee'))
+               ORDER BY `date` DESC",
+        [$member_id, $member_id]
+    );
 }
 
-function action_finances() {/*{{{*/
-?>
+function action_finances()
+{
+    ?>
     <h2>Finanzen</h2>
-<?php
+    <?php
     action_create_expense();
     action_create_earning();
     echo '<br style="clear: left;"/>';
     render_open_payments();
     render_finished_payments();
     echo '<a href="' . link_to('export') . '">.xls runterladen</a>';
-}/*}}}*/
-
+}
index 274f680..65b5f80 100644 (file)
 <?php
 
-function html_escape($val) {
+function html_escape($val)
+{
     return htmlentities($val, ENT_COMPAT, 'UTF-8');
 }
 
-function html_hidden_field($name, $value = '', $id = NULL) {
-    if (!isset($id)) $id = $name;
+function html_hidden_field($name, $value = '', $id = null)
+{
+    if (!isset($id)) {
+        $id = $name;
+    }
     if (is_array($value)) {
-        if (isset($value[$name])) $value = $value[$name];
-        else $value = '';
+        if (isset($value[$name])) {
+            $value = $value[$name];
+        } else {
+            $value = '';
+        }
     }
     return sprintf('<input type="hidden" name="%1$s" id="%3$s" value="%2$s"/>', $name, html_escape($value), $id) . "\n";
 }
 
-function html_text_field($label, $name, $value = '', $readonly = false, $id = NULL) {
-    if (!isset($id)) $id = $name;
+function html_text_field($label, $name, $value = '', $readonly = false, $id = null)
+{
+    if (!isset($id)) {
+        $id = $name;
+    }
     if (is_array($value)) {
-        if (isset($value[$name])) $value = $value[$name];
-        else $value = '';
+        if (isset($value[$name])) {
+            $value = $value[$name];
+        } else {
+            $value = '';
+        }
     }
-    if ($readonly) $readonly = ' readonly="readonly"';
-    else $readonly = '';
-    return sprintf('<label for="%4$s">%1$s:</label><input type="text" name="%2$s" id="%4$s" value="%3$s"%5$s/>', html_escape($label), $name, html_escape($value), $id, $readonly) . "\n";
+    if ($readonly) {
+        $readonly = ' readonly="readonly"';
+    } else {
+        $readonly = '';
+    }
+    return sprintf('<label for="%4$s">%1$s:</label><input type="text" name="%2$s" id="%4$s" value="%3$s"%5$s/>',
+            html_escape($label), $name, html_escape($value), $id, $readonly) . "\n";
 }
 
-function html_money_field($label, $name, $value = '', $readonly = false, $id = NULL) {
-    if (!isset($id)) $id = $name;
+function html_money_field($label, $name, $value = '', $readonly = false, $id = null)
+{
+    if (!isset($id)) {
+        $id = $name;
+    }
     if (is_array($value)) {
-        if (isset($value[$name])) $value = $value[$name];
-        else $value = '';
+        if (isset($value[$name])) {
+            $value = $value[$name];
+        } else {
+            $value = '';
+        }
     }
     $value = str_replace(array('.', '€'), array(',', ''), $value);
-    if ($readonly) $readonly = ' readonly="readonly"';
-    else $readonly = '';
-    return sprintf('<label for="%4$s">%1$s:</label><input type="text" name="%2$s" id="%4$s" value="%3$s"%5$s/>', html_escape($label), $name, html_escape($value), $id, $readonly) . "\n";
+    if ($readonly) {
+        $readonly = ' readonly="readonly"';
+    } else {
+        $readonly = '';
+    }
+    return sprintf('<label for="%4$s">%1$s:</label><input type="text" name="%2$s" id="%4$s" value="%3$s"%5$s/>',
+            html_escape($label), $name, html_escape($value), $id, $readonly) . "\n";
 }
 
-function html_password_field($label, $name, $id = NULL) {
-    if (!isset($id)) $id = $name;
-    return sprintf('<label for="%3$s">%1$s:</label><input type="password" name="%2$s" id="%3$s"/>', html_escape($label), $name, $id) . "\n";
+function html_password_field($label, $name, $id = null)
+{
+    if (!isset($id)) {
+        $id = $name;
+    }
+    return sprintf('<label for="%3$s">%1$s:</label><input type="password" name="%2$s" id="%3$s"/>', html_escape($label),
+            $name, $id) . "\n";
 }
 
-function html_checkbox($label, $name, $checked, $value, $readonly = false, $id = NULL) {
-    if (!isset($id)) $id = $name;
+function html_checkbox($label, $name, $checked, $value, $readonly = false, $id = null)
+{
+    if (!isset($id)) {
+        $id = $name;
+    }
     if (is_array($checked)) {
-        if (isset($checked[$name])) $checked = $checked[$name];
-        else $checked = false;
-    }
-    if ($checked) $checked = ' checked="checked"';
-    else $checked = '';
-    if ($readonly) $readonly = ' disabled="disabled"';
-    else $readonly = '';
-    return sprintf('<div class="checkbox"><input type="checkbox" name="%2$s" id="%4$s" value="%3$s"%5$s%6$s/><label for="%4$s">%1$s</label></div>', html_escape($label), $name, html_escape($value), $id, $checked, $readonly) . "\n";
+        if (isset($checked[$name])) {
+            $checked = $checked[$name];
+        } else {
+            $checked = false;
+        }
+    }
+    if ($checked) {
+        $checked = ' checked="checked"';
+    } else {
+        $checked = '';
+    }
+    if ($readonly) {
+        $readonly = ' disabled="disabled"';
+    } else {
+        $readonly = '';
+    }
+    return sprintf('<div class="checkbox"><input type="checkbox" name="%2$s" id="%4$s" value="%3$s"%5$s%6$s/><label for="%4$s">%1$s</label></div>',
+            html_escape($label), $name, html_escape($value), $id, $checked, $readonly) . "\n";
 }
 
-function html_list_box($label, $name, $list, $selected, $readonly = false, $id = NULL, $tag_params = '') {
-    if (!isset($id)) $id = $name;
-    if (!empty($tag_params)) $tag_params = ' ' . $tag_params;
+function html_list_box($label, $name, $list, $selected, $readonly = false, $id = null, $tag_params = '')
+{
+    if (!isset($id)) {
+        $id = $name;
+    }
+    if (!empty($tag_params)) {
+        $tag_params = ' ' . $tag_params;
+    }
     if (is_array($selected)) {
-        if (isset($selected[$name])) $selected = $selected[$name];
-        else $selected = '';
+        if (isset($selected[$name])) {
+            $selected = $selected[$name];
+        } else {
+            $selected = '';
+        }
+    }
+    if ($readonly) {
+        return html_text_field($label, $name, isset($list[$selected]) ? $list[$selected] : '-', true);
     }
-    if ($readonly) return html_text_field($label, $name, isset($list[$selected]) ? $list[$selected] : '-', true);
 
     $ret = sprintf('<label for="%2$s">%1$s:</label>', html_escape($label), $id) . "\n";
     $ret .= sprintf('<select id="%1$s" name="%1$s"%2$s>', html_escape($name), $tag_params);
     foreach ($list as $key => $value) {
-        if ($key == $selected) $ret .= sprintf('<option value="%1$s" selected="selected">%2$s</option>', html_escape($key), str_replace(' ', '&nbsp;', html_escape($value)));
-        else $ret .= sprintf('<option value="%1$s">%2$s</option>', html_escape($key), str_replace(' ', '&nbsp;', html_escape($value)));
+        if ($key == $selected) {
+            $ret .= sprintf('<option value="%1$s" selected="selected">%2$s</option>', html_escape($key),
+                str_replace(' ', '&nbsp;', html_escape($value)));
+        } else {
+            $ret .= sprintf('<option value="%1$s">%2$s</option>', html_escape($key),
+                str_replace(' ', '&nbsp;', html_escape($value)));
+        }
     }
     $ret .= '</select>';
     return $ret;
 }
-
diff --git a/include/includes.php b/include/includes.php
new file mode 100644 (file)
index 0000000..ae4c894
--- /dev/null
@@ -0,0 +1,16 @@
+<?php
+
+require_once(__DIR__ . '/database.php');
+require_once(__DIR__ . '/misc.php');
+require_once(__DIR__ . '/html.php');
+
+require_once(__DIR__ . '/finances.php');
+require_once(__DIR__ . '/fees.php');
+require_once(__DIR__ . '/cryptography.php');
+require_once(__DIR__ . '/earnings.php');
+require_once(__DIR__ . '/events.php');
+require_once(__DIR__ . '/expenses.php');
+require_once(__DIR__ . '/members.php');
+require_once(__DIR__ . '/payments.php');
+require_once(__DIR__ . '/directdebit.php');
+require_once(__DIR__ . '/xlsexport.php');
diff --git a/include/installation.php b/include/installation.php
deleted file mode 100644 (file)
index f57ccae..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-<?php
-
-function install_database() {
-    if (!mysql_query($GLOBALS['SQL_CREATE_MEMBERS']))  echo db_error();
-    if (!mysql_query($GLOBALS['SQL_CREATE_EVENTS']))   echo db_error();
-    if (!mysql_query($GLOBALS['SQL_CREATE_CRYPTO']))   echo db_error();
-    if (!mysql_query($GLOBALS['SQL_CREATE_EARNINGS'])) echo db_error();
-    if (!mysql_query($GLOBALS['SQL_CREATE_EXPENSES'])) echo db_error();
-}
-
-function install_clear_database() {
-    mysql_query('DROP TABLE ' . DB_TABLE_MEMBERS);
-    mysql_query('DROP TABLE ' . DB_TABLE_EVENTS);
-    mysql_query('DROP TABLE ' . DB_TABLE_CRYPTO);
-    mysql_query('DROP TABLE ' . DB_TABLE_EARNINGS);
-    mysql_query('DROP TABLE ' . DB_TABLE_EXPENSES);
-}
-
index a98ff46..e7395c6 100644 (file)
@@ -1,82 +1,53 @@
 <?php
 
-$SQL_CREATE_MEMBERS = sprintf('
-    CREATE TABLE IF NOT EXISTS `%1$s` (
-      `id` int(10) unsigned NOT NULL auto_increment,
-      `number` int(10) unsigned NOT NULL,
-      `firstname` varchar(255) NOT NULL,
-      `lastname` varchar(255) NOT NULL,
-      `nickname` varchar(255) NOT NULL,
-      `accountholder` blob NOT NULL,
-      `accountnumber` blob NOT NULL,
-      `bankcode` blob NOT NULL,
-      `bankname` blob NOT NULL,
-      `directdebit` tinyint(1) NOT NULL,
-      `ddmandatesigdate` datetime NOT NULL,
-      `street` varchar(255) NOT NULL,
-      `housenumber` varchar(255) NOT NULL,
-      `postcode` varchar(255) NOT NULL,
-      `city` varchar(255) NOT NULL,
-      `country` varchar(255) NOT NULL,
-      `email` varchar(255) NOT NULL,
-      `phone` varchar(255) NOT NULL,
-      `fax` varchar(255) NOT NULL,
-      `mobile` varchar(255) NOT NULL,
-      `jabber` varchar(255) NOT NULL,
-      `icq` varchar(255) NOT NULL,
-      `msn` varchar(255) NOT NULL,
-      `aim` varchar(255) NOT NULL,
-      `skype` varchar(255) NOT NULL,
-      `url` varchar(255) NOT NULL,
-      `twitter` varchar(255) NOT NULL,
-      `created_at` datetime NOT NULL,
-      `modified_at` datetime NOT NULL,
-      PRIMARY KEY  (`id`),
-      UNIQUE KEY `number` (`number`)
-    ) ENGINE=InnoDB DEFAULT CHARSET=%2$s
-    ', DB_TABLE_MEMBERS, DB_CHARSET);
-
 $DIRECTDEBIT_STATES = array(
     '' => '- (Barzahler)',
-    1 => 'DTAUS',
-    2 => 'SEPA Ersteinzug',
-    3 => 'SEPA Folgeeinzug'
-); 
-    
-/* DB functions {{{ */
-
-function db_create_member($member) {
+    1  => 'DTAUS',
+    2  => 'SEPA Ersteinzug',
+    3  => 'SEPA Folgeeinzug'
+);
+
+// DB functions
+function db_create_member($member)
+{
     unset($member['id']);
-    $member['created_at']   = db_unixtime2datetime(time());
-    $member['modified_at']  = db_unixtime2datetime(time());
-    if (!db_insert_single(DB_TABLE_MEMBERS, $member)) return false;
+    $member['created_at'] = db_unixtime2datetime(time());
+    $member['modified_at'] = db_unixtime2datetime(time());
+    if (!db_insert('members', $member)) {
+        return false;
+    }
     return db_insert_id();
 }
 
-function db_change_member($member) {
+function db_change_member($member)
+{
     $id = $member['id'];
     unset($member['id']);
-    $member['modified_at']  = db_unixtime2datetime(time());
-    return db_update_single(DB_TABLE_MEMBERS, $member, sprintf('id=\'%1$d\'', db_escape($id)));
+    $member['modified_at'] = db_unixtime2datetime(time());
+    return db_update('members', $member, sprintf('id=%d', (int)$id));
 }
 
-function db_get_members() {
-    $sql = 'SELECT * FROM %1$s ORDER BY number ASC';
-    return db_select_multi(sprintf($sql, DB_TABLE_MEMBERS));
+function db_get_members()
+{
+    return db_select_multi('SELECT * FROM `members` ORDER BY `number` ASC');
 }
 
-function db_get_member_with_id($member_id) {
-    $sql = 'SELECT * FROM %1$s WHERE id=\'%2$d\' LIMIT 1';
-    return db_select_single(sprintf($sql, DB_TABLE_MEMBERS, db_escape($member_id)));
+function db_get_member_with_id($member_id)
+{
+    $sql = 'SELECT * FROM `members` WHERE id=? LIMIT 1';
+    return db_select_single($sql, [$member_id]);
 }
 
-function db_get_next_free_member_number() {/*{{{*/
-    $row = db_select_single(sprintf('SELECT MAX(number) AS number FROM %1$s', DB_TABLE_MEMBERS));
-    if (!isset($row)) return 2;
+function db_get_next_free_member_number()
+{
+    $row = db_select_single('SELECT MAX(number) AS number FROM `members`');
+    if (!isset($row)) {
+        return 2;
+    }
 
     $number = $row['number'] + 1;
     // Some numbers are reserved for honorary members
-    $number = (int) $number;
+    $number = (int)$number;
     switch ($number) {
         case 1:
         case 23:
@@ -87,17 +58,15 @@ function db_get_next_free_member_number() {/*{{{*/
             return $number + 1;
     }
     return $number;
-};/*}}}*/
-
-
-function db_get_member_with_number($member_number) {
-    $sql = 'SELECT * FROM %1$s WHERE number=\'%2$d\' LIMIT 1';
-    return db_select_single(sprintf($sql, DB_TABLE_MEMBERS, db_escape($member_number)));
 }
 
-/* }}} */
+function db_get_member_with_number($member_number)
+{
+    return db_select_single('SELECT * FROM `members` WHERE `number`=? LIMIT 1', [$member_number]);
+}
 
-function validate_member($userdata, &$dbdata, &$validation) {/*{{{*/
+function validate_member($userdata, &$db_data, &$validation)
+{
     $fields = array(
         'id'               => 'number',
         'number'           => 'number',
@@ -127,50 +96,64 @@ function validate_member($userdata, &$dbdata, &$validation) {/*{{{*/
         'url'              => 'string',
         'twitter'          => 'string',
     );
-    $orig = $dbdata;
+    $orig = $db_data;
     foreach ($fields as $name => $type) {
         if ($type == 'bool') {
-            $dbdata[$name] = !empty($userdata[$name]);
+            $db_data[$name] = !empty($userdata[$name]);
+            continue;
+        }
+        if (!isset($userdata[$name])) {
             continue;
         }
-        if (!isset($userdata[$name])) continue;
-        $dbdata[$name] = $userdata[$name];
+        if ($type == 'number') {
+            $userdata[$name] = (int)$userdata[$name];
+        }
+
+        $db_data[$name] = $userdata[$name];
     }
-//      ids must be equal
-//      number must be equal. if changed - check if free and allowed
+    // ids must be equal
+    // number must be equal. if changed - check if free and allowed
     if (isset($orig['id'])) {
-        if ($dbdata['id'] != $orig['id']) {
+        if ($db_data['id'] != $orig['id']) {
             $validation[] = 'Irgendwas ist sehr sehr komisch.';
         }
-        if (!validate_member_number($dbdata['number'], $dbdata['id'])) {
+        if (!validate_member_number($db_data['number'], $db_data['id'])) {
             $validation[] = 'Die Mitgliedsnummer ist schon vergeben.';
         }
         return (count($validation) == 0);
     }
-    if (!validate_member_number($dbdata['number'])) {
+    if (!validate_member_number($db_data['number'])) {
         $validation[] = 'Die Mitgliedsnummer ist schon vergeben.';
     }
     return (count($validation) == 0);
-}/*}}}*/
+}
 
-function validate_member_number($member_number, $member_id = NULL) {/*{{{*/
+function validate_member_number($member_number, $member_id = null)
+{
     $member = db_get_member_with_number($member_number);
 
     // theres no member with this number
-    if (!isset($member)) return true;
+    if (!isset($member)) {
+        return true;
+    }
 
     // there is a member, but maybe its the one we got passed
-    if (isset($member_id) && $member_id == $member['id']) return true;
+    if (isset($member_id) && $member_id == $member['id']) {
+        return true;
+    }
 
     return false;
-}/*}}}*/
+}
 
-function action_export_ibanhin() {/*{{{*/
+function action_export_ibanhin()
+{
     $members = db_get_members();
-    if (empty($members)) return;
+    if (empty($members)) {
+        return;
+    }
     js_modal_windows();
     js_get_master_key();
-?>
+    ?>
     <noscript>
         <p class="error">
             <strong>Achtung:</strong> Ohne JavaScript geht hier gar nichts. Bitte aktivieren!
@@ -178,193 +161,204 @@ function action_export_ibanhin() {/*{{{*/
     </noscript>
 
     <h2>IBAN-hin</h2>
-<input class="submit" type="button" name="btn_ibanhin" value="IBAN-hin erzeugen" onclick="ask_for_password()" id="btn_export_iban_hin"/>
-<br/>
-<br/>
-
-
-<div id="password_popup" class="modal_window">
-    <fieldset>
-        <legend>Passwortabfrage</legend>
-        <?=html_password_field('Passwort', 'password')?>
-        <input class="submit" type="button" name="btn_export_ibanhin" value="IBAN-hin erzeugen" onclick="export_ibanhin()"/>
-        <input class="submit" type="button" name="btn_cancel" value="Abbrechen" onclick="cancel_ask_for_password()"/>
-    </fieldset>
-</div>
-<div id="ibanhin_popup" class="modal_window">
-    <fieldset>
-        <legend>IBAN-hin</legend>
+    <input class="submit" type="button" name="btn_ibanhin" value="IBAN-hin erzeugen" onclick="ask_for_password()"
+           id="btn_export_iban_hin"/>
+    <br/>
+    <br/>
+
+
+    <div id="password_popup" class="modal_window">
+        <fieldset>
+            <legend>Passwortabfrage</legend>
+            <?php echo html_password_field('Passwort', 'password') ?>
+            <input class="submit" type="button" name="btn_export_ibanhin" value="IBAN-hin erzeugen"
+                   onclick="export_ibanhin()"/>
+            <input class="submit" type="button" name="btn_cancel" value="Abbrechen"
+                   onclick="cancel_ask_for_password()"/>
+        </fieldset>
+    </div>
+    <div id="ibanhin_popup" class="modal_window">
+        <fieldset>
+            <legend>IBAN-hin</legend>
             <textarea id="ibanhin_content" style="width: 100%" rows="30" readonly="readonly"></textarea>
             <input class="submit" type="button" name="btn_ibanhin_close" value="Schließen" onclick="ibanhin_close()"/>
-    </fieldset>
-</div>
-
-<script type="text/javascript">
-
-  var members = new Array(<?=join(",\n", array_map('json_encode', $members)) ?>);
-
-
-
-$(document).ready(function(){  
-    $('#password').keypress( function(event) { if (event.keyCode == '13') { export_ibanhin(); } });
-    $('#btn_ibanhin').focus();
-});  
-
-
-function ask_for_password() {/*{{{*/
-    modal_window_show($("#password_popup"));
-    $("#password").focus();
-    return;
-}/*}}}*/
-
-function cancel_ask_for_password() {/*{{{*/
-    modal_window_hide();
-    $("#btn_ibanhin").focus();
-    return;
-}/*}}}*/
-
-
-function export_ibanhin() {/*{{{*/
-    
-    var ibanhin_content = "";
-
-    var password = $('#password').val();
-    $("#password").val('');
-
-    // We pass a closure so that get_master_key may defer execution
-    get_master_key(password, function(masterkey) {
-
-    modal_window_replace($("#ibanhin_popup"));
-
-    for (var i = 0; i < members.length; i++) {
-      if (members[i]['directdebit'] == "1") {
-       var accountnumber = members[i]['accountnumber'];
-       var bankcode      = members[i]['bankcode'];
-       if (accountnumber != "") accountnumber = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey));
-       if (bankcode      != "") bankcode      = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode,      masterkey));
-        if (accountnumber != "" && bankcode != "") {
-          /* ZKA-Spezifikation-IBAN-hin-IBAN-rueck
-             01. Satzart
-             02. Anwender
-             03. Internes Kennzeichen des Anwenders
-             04. BIC-ALT
-             IBAN-ALT
-             05. LK/PZ-ALT
-             06. BLZ-ALT
-             07. KTONR-ALT
-             IBAN-NEU
-             08. LK/PZ-NEU
-             09. BLZ-NEU
-             10. KTONR-NEU
-             11. UMST-KZ
-           */
-          ibanhin_content += '"DE";;"' + members[i]['number'] + '";;;"' + bankcode + '";"' + accountnumber + '";;;;;' + "\n";
-        }
-      }
-    }
+        </fieldset>
+    </div>
 
-    $('#ibanhin_content').val(ibanhin_content);
-    $('#ibanhin_content').focus();
-    $('#ibanhin_content').select();
-    
-    });
+    <script type="text/javascript">
+        var members = new Array(<?php echo join(",\n", array_map('json_encode', $members)) ?>);
 
-}/*}}}*/
+        $(document).ready(function () {
+            $('#password').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    export_ibanhin();
+                }
+            });
+            $('#btn_ibanhin').focus();
+        });
+
+        function ask_for_password() {
+            modal_window_show($("#password_popup"));
+            $("#password").focus();
+            return;
+        }
 
-function ibanhin_close() {/*{{{*/
-    modal_window_hide();
-    $("#ibanhin_content").val('');
-}/*}}}*/
+        function cancel_ask_for_password() {
+            modal_window_hide();
+            $("#btn_ibanhin").focus();
+            return;
+        }
 
+        function export_ibanhin() {
+            var ibanhin_content = "";
+
+            var password = $('#password').val();
+            $("#password").val('');
+
+            // We pass a closure so that get_master_key may defer execution
+            get_master_key(password, function (masterkey) {
+
+                modal_window_replace($("#ibanhin_popup"));
+
+                for (var i = 0; i < members.length; i++) {
+                    if (members[i]['directdebit'] == "1") {
+                        var accountnumber = members[i]['accountnumber'];
+                        var bankcode = members[i]['bankcode'];
+                        if (accountnumber != "") accountnumber = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey));
+                        if (bankcode != "") bankcode = Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode, masterkey));
+                        if (accountnumber != "" && bankcode != "") {
+                            /* ZKA-Spezifikation-IBAN-hin-IBAN-rueck
+                               01. Satzart
+                               02. Anwender
+                               03. Internes Kennzeichen des Anwenders
+                               04. BIC-ALT
+                               IBAN-ALT
+                               05. LK/PZ-ALT
+                               06. BLZ-ALT
+                               07. KTONR-ALT
+                               IBAN-NEU
+                               08. LK/PZ-NEU
+                               09. BLZ-NEU
+                               10. KTONR-NEU
+                               11. UMST-KZ
+                             */
+                            ibanhin_content += '"DE";;"' + members[i]['number'] + '";;;"' + bankcode + '";"' + accountnumber + '";;;;;' + "\n";
+                        }
+                    }
+                }
 
-</script>
+                var iban_hin_content = $('#ibanhin_content');
+                iban_hin_content.val(ibanhin_content);
+                iban_hin_content.focus();
+                iban_hin_content.select();
 
-<?php
+            });
 
-}/*}}}*/
+        }
 
+        function ibanhin_close() {
+            modal_window_hide();
+            $("#ibanhin_content").val('');
+        }
+    </script>
+    <?php
+}
 
-function action_list_members() {/*{{{*/
+function action_list_members()
+{
     $members = db_get_members();
-    $count   = 0;
     $regular = 0;
     $patron = 0;
     $honorary = 0;
     ?>
     <h2>Liste der Mitglieder</h2>
     <?php if (isset($members)) : ?>
-        <table>
-            <tr>
-                <th>Mitgliedsnummer</th>
-                <th>Nickname</th>
-                <th>Vorname</th>
-                <th>Nachname</th>
-            </tr>
+    <table>
+        <tr>
+            <th>Mitgliedsnummer</th>
+            <th>Nickname</th>
+            <th>Vorname</th>
+            <th>Nachname</th>
+        </tr>
         <?php foreach ($members as $member) : ?>
             <?php $membership_info = fees_info_for_member($member['id'], time()); ?>
-           <?php 
-                if (!empty($membership_info['is_member'])) {
-                    switch($membership_info['member_type']) {
-                        case 'regular': $regular++; break;
-                        case 'honorary': $honorary++; break;
-                        case 'patron': $patron++; break;
-                    }
+            <?php
+            if (!empty($membership_info['is_member'])) {
+                switch ($membership_info['member_type']) {
+                    case 'regular':
+                        $regular++;
+                        break;
+                    case 'honorary':
+                        $honorary++;
+                        break;
+                    case 'patron':
+                        $patron++;
+                        break;
                 }
-           ?>
+            }
+            ?>
             <tr <?php if (empty($membership_info['is_member'])) : ?>class="inactive"<?php endif ?>>
-                <td><a href="<?=html_escape(link_to('view_member', array('id'=> $member['id'])))?>"><?=html_escape($member['number'])?></a></td>
-                <td><?=html_escape($member['nickname'])?></td>
-                <td><?=html_escape($member['firstname'])?></td>
-                <td><?=html_escape($member['lastname'])?></td>
+                <td><a href="<?php echo html_escape(link_to('view_member',
+                        array('id' => $member['id']))) ?>"><?php echo html_escape($member['number']) ?></a></td>
+                <td><?php echo html_escape($member['nickname']) ?></td>
+                <td><?php echo html_escape($member['firstname']) ?></td>
+                <td><?php echo html_escape($member['lastname']) ?></td>
             </tr>
         <?php endforeach ?>
-        </table>
-    <?php else : ?>
-        <p>Bisher gibt es noch keine Mitglieder.</p>
-    <?php
-        endif;
-        $count = $regular + $honorary + $patron;
+    </table>
+<?php else : ?>
+    <p>Bisher gibt es noch keine Mitglieder.</p>
+<?php
+endif;
+    $count = $regular + $honorary + $patron;
     ?>
-        <p>Derzeit gibt es <?=$count?> Vereinsmitglieder. Davon:
-            <ul>
-                <li><?=$regular?> ordentliche Mitglieder</li>
-                <li><?=$honorary?> Ehrenmitglieder</li>
-                <li style="font-weight: bold;"><?=$regular+$honorary?> stimmberechtigte Mitglieder</li>
-                <li><?=$patron?> Fördermitglieder</li>
-            </ul>
-        </p>
-        <a href="<?=link_to('create_member')?>">Neues Mitglied</a>
-        <a href="<?=link_to('export_email')?>">E-Mail-Adressen</a>
-        <a href="<?=link_to('export_members')?>">XLS Export</a>
+    <p>Derzeit gibt es <?php echo $count ?> Vereinsmitglieder. Davon:
+    <ul>
+        <li><?php echo $regular ?> ordentliche Mitglieder</li>
+        <li><?php echo $honorary ?> Ehrenmitglieder</li>
+        <li style="font-weight: bold;"><?php echo $regular + $honorary ?> stimmberechtigte Mitglieder</li>
+        <li><?php echo $patron ?> Fördermitglieder</li>
+    </ul>
+    </p>
+    <a href="<?php echo link_to('create_member') ?>">Neues Mitglied</a>
+    <a href="<?php echo link_to('export_email') ?>">E-Mail-Adressen</a>
+    <a href="<?php echo link_to('export_members') ?>">XLS Export</a>
     <?php
-}/*}}}*/
+}
 
-function action_view_member() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to());
+function action_view_member()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to());
+    }
     $member = db_get_member_with_id($_REQUEST['id']);
-    if (!isset($member)) redirect(link_to());
+    if (!isset($member)) {
+        redirect(link_to());
+    }
     form_member($member, true);
     action_list_events($member);
     action_create_event($member);
-}/*}}}*/
+}
 
-function action_create_member() {/*{{{*/
+function action_create_member()
+{
     $member = array();
     $log_messages = array();
     if (isset($_POST['submit'])) {
         unset($_POST['id']);
-        
+
         if (validate_member($_POST, $member, $log_messages)) {
-            if (empty($member['number'])) $member['number'] = db_get_next_free_member_number();
-            
+            if (empty($member['number'])) {
+                $member['number'] = db_get_next_free_member_number();
+            }
+
             if (($member['ddmandatesigdate'] == 'TT.MM.JJJJ') ||
-                ($member['ddmandatesigdate'] == ''))
-            {
-              $member['ddmandatesigdate'] = '0000-00-00 00:00:00';
+                ($member['ddmandatesigdate'] == '')) {
+                $member['ddmandatesigdate'] = '1000-01-01 00:00:00';
             } else {
-              $member['ddmandatesigdate'] = db_unixtime2datetime(ui_date2unixtime($member['ddmandatesigdate']));
+                $member['ddmandatesigdate'] = db_unixtime2datetime(ui_date2unixtime($member['ddmandatesigdate']));
             }
-            
+
             if ($member_id = db_create_member($member)) {
                 redirect(link_to('view_member', array('id' => $member_id)) . '#events');
             }
@@ -372,23 +366,29 @@ function action_create_member() {/*{{{*/
         }
     }
     form_member($member, false, $log_messages);
-}/*}}}*/
+}
 
-function action_change_member() {/*{{{*/
-    if (!isset($_REQUEST['id'])) redirect(link_to());
+function action_change_member()
+{
+    if (!isset($_REQUEST['id'])) {
+        redirect(link_to());
+    }
     $member = db_get_member_with_id($_REQUEST['id']);
-    if (!isset($member)) redirect(link_to());
+    if (!isset($member)) {
+        redirect(link_to());
+    }
     $log_messages = array();
     if (isset($_POST['submit'])) {
         if (validate_member($_POST, $member, $log_messages)) {
-            if (empty($member['number'])) $member['number'] = db_get_next_free_member_number();
-                        
+            if (empty($member['number'])) {
+                $member['number'] = db_get_next_free_member_number();
+            }
+
             if (($member['ddmandatesigdate'] == 'TT.MM.JJJJ') ||
-                ($member['ddmandatesigdate'] == ''))
-            {
-              $member['ddmandatesigdate'] = '0000-00-00 00:00:00';
+                ($member['ddmandatesigdate'] == '')) {
+                $member['ddmandatesigdate'] = '1000-01-01 00:00:00';
             } else {
-              $member['ddmandatesigdate'] = db_unixtime2datetime(ui_date2unixtime($member['ddmandatesigdate']));
+                $member['ddmandatesigdate'] = db_unixtime2datetime(ui_date2unixtime($member['ddmandatesigdate']));
             }
 
             if (db_change_member($member)) {
@@ -398,24 +398,27 @@ function action_change_member() {/*{{{*/
         }
     }
     form_member($member, false, $log_messages);
-}/*}}}*/
-
+}
 
-function action_export_email() {/*{{{*/
+function action_export_email()
+{
     $members = db_get_members();
     $first = true;
     ?>
     <h2>E-Mail-Adressen</h2>
     <?php if (isset($members)) : ?>
-        <?php foreach ($members as $member) : ?><?php $membership_info = fees_info_for_member($member['id'], time()); ?><?php if (!empty($membership_info['is_member'])) : ?><?php if (empty($member['email'])) continue; ?><?php if ($first) : $first = false; else :?>,<?php endif ?> <?=$member['email']?><?php endif ?><?php endforeach ?>
-    <?php else : ?>
-        <p>Bisher gibt's noch keine Mitglieder.</p>
-    <?php endif ?>
+    <?php foreach ($members as $member) : ?><?php $membership_info = fees_info_for_member($member['id'],
+        time()); ?><?php if (!empty($membership_info['is_member'])) : ?><?php if (empty($member['email'])) {
+        continue;
+    } ?><?php if ($first) : $first = false; else : ?>,<?php endif ?><?php echo $member['email'] ?><?php endif ?><?php endforeach ?>
+<?php else : ?>
+    <p>Bisher gibt's noch keine Mitglieder.</p>
+<?php endif ?>
     <?php
-}/*}}}*/
-
+}
 
-function html_member_list_box($label, $name, $selected, $readonly = false, $id = NULL, $tag_params = '') {
+function html_member_list_box($label, $name, $selected, $readonly = false, $id = null, $tag_params = '')
+{
     $list = array(0 => '-');
     $members = db_get_members();
     if (!empty($members)) {
@@ -426,17 +429,18 @@ function html_member_list_box($label, $name, $selected, $readonly = false, $id =
     return html_list_box($label, $name, $list, $selected, $readonly, $id, $tag_params);
 }
 
-function form_member($member = array(), $readonly = false, $log_messages = array()) {/*{{{*/
-    
+function form_member($member = array(), $readonly = false, $log_messages = array())
+{
     global $DIRECTDEBIT_STATES;
-    
+
     $keys = db_get_crypto_keys();
     if (empty($keys)) {
-?>
+        ?>
         <p class="error">
-            <strong>Achtung:</strong> Bitte zuerst <a href="<?=link_to('cryptography')?>">Kryptographie einrichten</a>.
+            <strong>Achtung:</strong> Bitte zuerst <a href="<?php echo link_to('cryptography') ?>">Kryptographie
+                einrichten</a>.
         </p>
-<?php
+        <?php
         return;
     }
 
@@ -450,86 +454,93 @@ function form_member($member = array(), $readonly = false, $log_messages = array
         </p>
     </noscript>
     <?php if (!isset($member['id'])) : ?>
-        <h2>Neues Mitglied</h2>
-    <?php elseif ($readonly) : ?>
-        <h2>Mitgliedsdetails</h2>
-    <?php else : ?>
-        <h2>Mitglied &auml;ndern</h2>
-    <?php endif ?>
+    <h2>Neues Mitglied</h2>
+<?php elseif ($readonly) : ?>
+    <h2>Mitgliedsdetails</h2>
+<?php else : ?>
+    <h2>Mitglied &auml;ndern</h2>
+<?php endif ?>
     <?php log_messages($log_messages); ?>
     <form action="" method="post" class="clearfix">
-        <?php if (isset($member['id']) && !$readonly) : ?><?=html_hidden_field('id', $member)?><?php endif ?>
+        <?php if (isset($member['id']) && !$readonly) : ?><?php echo html_hidden_field('id', $member) ?><?php endif ?>
         <fieldset>
             <legend>Allgemein</legend>
-            <?=html_text_field('Mitgliedsnummer', 'number', $member, $readonly)?>
-            <?php if (!$readonly) : ?><small>Wird automatisch vergeben wenn leer.</small><?php endif ?>
-            <?=html_text_field('Nickname', 'nickname', $member, $readonly)?>
-            <?=html_text_field('E-Mail', 'email', $member, $readonly)?>
+            <?php echo html_text_field('Mitgliedsnummer', 'number', $member, $readonly) ?>
+            <?php if (!$readonly) : ?>
+                <small>Wird automatisch vergeben wenn leer.</small><?php endif ?>
+            <?php echo html_text_field('Nickname', 'nickname', $member, $readonly) ?>
+            <?php echo html_text_field('E-Mail', 'email', $member, $readonly) ?>
         </fieldset>
         <fieldset id="bank_details">
             <legend>Bankverbindung</legend>
-            <?=html_text_field('Kontoinhaber', 'accountholder', $member, true)?>
-            <?=html_text_field('Kontonummer/IBAN', 'accountnumber', $member, true)?>
-            <?=html_text_field('Bankleitzahl/BIC', 'bankcode', $member, true)?>
-            <?=html_text_field('Name der Bank', 'bankname', $member, true)?>
+            <?php echo html_text_field('Kontoinhaber', 'accountholder', $member, true) ?>
+            <?php echo html_text_field('Kontonummer/IBAN', 'accountnumber', $member, true) ?>
+            <?php echo html_text_field('Bankleitzahl/BIC', 'bankcode', $member, true) ?>
+            <?php echo html_text_field('Name der Bank', 'bankname', $member, true) ?>
             <?php if (!isset($member['id'])) : ?>
-                <input class="submit" type="button" name="btn_bank_details" value="Bankverbindung erfassen" onclick="bank_details_ask_pass()" id="btn_bank_details"/>
+                <input class="submit" type="button" name="btn_bank_details" value="Bankverbindung erfassen"
+                       onclick="bank_details_ask_pass()" id="btn_bank_details"/>
             <?php elseif ($readonly) : ?>
-                <input class="submit" type="button" name="btn_bank_details" value="Bankverbindung betrachten" onclick="bank_details_ask_pass()" id="btn_bank_details"/>
+                <input class="submit" type="button" name="btn_bank_details" value="Bankverbindung betrachten"
+                       onclick="bank_details_ask_pass()" id="btn_bank_details"/>
             <?php else : ?>
-                <input class="submit" type="button" name="btn_bank_details" value="Bankverbindung &auml;ndern" onclick="bank_details_ask_pass()" id="btn_bank_details"/>
+                <input class="submit" type="button" name="btn_bank_details" value="Bankverbindung &auml;ndern"
+                       onclick="bank_details_ask_pass()" id="btn_bank_details"/>
             <?php endif ?>
-            <?=html_list_box('Beitragseinzug', 'directdebit', $DIRECTDEBIT_STATES, $member, $readonly)?>
+            <?php echo html_list_box('Beitragseinzug', 'directdebit', $DIRECTDEBIT_STATES, $member, $readonly) ?>
             <?php
-              if ((!isset($member['ddmandatesigdate'])) ||
-                  ($member['ddmandatesigdate'] == '') ||
-                  ($member['ddmandatesigdate'] == '0000-00-00 00:00:00'))
-              {
+            if ((!isset($member['ddmandatesigdate'])) ||
+                ($member['ddmandatesigdate'] == '') ||
+                ($member['ddmandatesigdate'] == '1000-01-01 00:00:00')) {
                 $member['ddmandatesigdate'] = ($readonly) ? '' : html_escape('TT.MM.JJJJ');
-              } else {              
+            } else {
                 $member['ddmandatesigdate'] = html_escape(format_date(db_date2unixtime($member['ddmandatesigdate'])));
-              }
+            }
             ?>
-            <?=html_text_field('Mandatsunterschrift', 'ddmandatesigdate', $member, $readonly)?>
+            <?php echo html_text_field('Mandatsunterschrift', 'ddmandatesigdate', $member, $readonly) ?>
         </fieldset>
         <fieldset style="clear: left;">
             <legend>Anschrift</legend>
-            <?=html_text_field('Vorname', 'firstname', $member, $readonly)?>
-            <?=html_text_field('Nachname', 'lastname', $member, $readonly)?>
-            <?=html_text_field('Straße', 'street', $member, $readonly)?>
-            <?=html_text_field('Hausnummer', 'housenumber', $member, $readonly)?>
-            <?=html_text_field('PLZ', 'postcode', $member, $readonly)?>
-            <?=html_text_field('Ort', 'city', $member, $readonly)?>
-            <?=html_text_field('Land', 'country', $member, $readonly)?>
+            <?php echo html_text_field('Vorname', 'firstname', $member, $readonly) ?>
+            <?php echo html_text_field('Nachname', 'lastname', $member, $readonly) ?>
+            <?php echo html_text_field('Straße', 'street', $member, $readonly) ?>
+            <?php echo html_text_field('Hausnummer', 'housenumber', $member, $readonly) ?>
+            <?php echo html_text_field('PLZ', 'postcode', $member, $readonly) ?>
+            <?php echo html_text_field('Ort', 'city', $member, $readonly) ?>
+            <?php echo html_text_field('Land', 'country', $member, $readonly) ?>
         </fieldset>
         <fieldset>
             <legend>Sonstiges</legend>
-            <?=html_text_field('Telefon', 'phone', $member, $readonly)?>
-            <?=html_text_field('Fax', 'fax', $member, $readonly)?>
-            <?=html_text_field('Handy', 'mobile', $member, $readonly)?>
-            <?=html_text_field('Jabber', 'jabber', $member, $readonly)?>
-            <?=html_text_field('ICQ', 'icq', $member, $readonly)?>
-            <?=html_text_field('MSN', 'msn', $member, $readonly)?>
-            <?=html_text_field('AIM', 'aim', $member, $readonly)?>
-            <?=html_text_field('Skype', 'skype', $member, $readonly)?>
-            <?=html_text_field('Website', 'url', $member, $readonly)?>
-            <?=html_text_field('Twitter', 'twitter', $member, $readonly)?>
+            <?php echo html_text_field('Telefon', 'phone', $member, $readonly) ?>
+            <?php echo html_text_field('Fax', 'fax', $member, $readonly) ?>
+            <?php echo html_text_field('Handy', 'mobile', $member, $readonly) ?>
+            <?php echo html_text_field('Jabber', 'jabber', $member, $readonly) ?>
+            <?php echo html_text_field('ICQ', 'icq', $member, $readonly) ?>
+            <?php echo html_text_field('MSN', 'msn', $member, $readonly) ?>
+            <?php echo html_text_field('AIM', 'aim', $member, $readonly) ?>
+            <?php echo html_text_field('Skype', 'skype', $member, $readonly) ?>
+            <?php echo html_text_field('Website', 'url', $member, $readonly) ?>
+            <?php echo html_text_field('Twitter', 'twitter', $member, $readonly) ?>
         </fieldset>
         <?php if (!$readonly) : ?>
             <input class="submit" type="submit" name="submit" value="Speichern"/>
         <?php else : ?>
             <br style="clear: left;"/>
-            <a href="<?=html_escape(link_to('change_member', array('id' => $member['id'])))?>">Mitglied &auml;ndern</a>
+            <a href="<?php echo html_escape(link_to('change_member', array('id' => $member['id']))) ?>">Mitglied
+                &auml;ndern</a>
         <?php endif ?>
     </form>
     <?php if (!isset($member['id'])) : ?>
-    <input class="submit" type="button" name="btn_import_qrcode1" value="QR-Code importieren" onclick="import_qrcode_ask_pass()" id="btn_import_qrcode1"/>
+    <input class="submit" type="button" name="btn_import_qrcode1" value="QR-Code importieren"
+           onclick="import_qrcode_ask_pass()" id="btn_import_qrcode1"/>
     <div id="password_popup2" class="modal_window">
         <fieldset>
             <legend>Passwortabfrage</legend>
-            <?=html_password_field('Passwort', 'password2')?>
-            <input class="submit" type="button" name="btn_import_qrcode2" value="QR-Code importieren" onclick="import_qrcode()"/>
-        <input class="submit" type="button" name="btn_cancel_import_qrcode" value="Abbrechen" onclick="cancel_import_qrcode()"/>
+            <?php echo html_password_field('Passwort', 'password2') ?>
+            <input class="submit" type="button" name="btn_import_qrcode2" value="QR-Code importieren"
+                   onclick="import_qrcode()"/>
+            <input class="submit" type="button" name="btn_cancel_import_qrcode" value="Abbrechen"
+                   onclick="cancel_import_qrcode()"/>
         </fieldset>
     </div>
     <div id="qrcode_popup" class="modal_window">
@@ -539,198 +550,247 @@ function form_member($member = array(), $readonly = false, $log_messages = array
             <input class="submit" type="button" name="btn_qrcode_close" value="Importieren" onclick="qrcode_close()"/>
         </fieldset>
     </div>
-    <?php endif ?>
-    
+<?php endif ?>
+
     <div id="password_popup" class="modal_window">
         <fieldset>
             <legend>Passwortabfrage</legend>
-            <?=html_password_field('Passwort', 'password1')?>
-            <input class="submit" type="button" name="btn_decrypt_bank_details" value="Bankdaten entschl&uuml;sseln" onclick="decrypt_bank_details()"/>
-        <input class="submit" type="button" name="btn_cancel" value="Abbrechen" onclick="cancel_change_bank_details()"/>
+            <?php echo html_password_field('Passwort', 'password1') ?>
+            <input class="submit" type="button" name="btn_decrypt_bank_details" value="Bankdaten entschl&uuml;sseln"
+                   onclick="decrypt_bank_details()"/>
+            <input class="submit" type="button" name="btn_cancel" value="Abbrechen"
+                   onclick="cancel_change_bank_details()"/>
         </fieldset>
     </div>
     <div id="bank_detail_popup" class="modal_window">
         <fieldset>
             <legend>Bankverbindung</legend>
-            <?=html_text_field('Kontoinhaber', 'tmp_accountholder', $member, $readonly)?>
-            <?=html_text_field('Kontonummer/IBAN', 'tmp_accountnumber', $member, $readonly)?>
-            <?=html_text_field('Bankleitzahl/BIC', 'tmp_bankcode', $member, $readonly)?>
-            <?=html_text_field('Name der Bank', 'tmp_bankname', $member, $readonly)?>
+            <?php echo html_text_field('Kontoinhaber', 'tmp_accountholder', $member, $readonly) ?>
+            <?php echo html_text_field('Kontonummer/IBAN', 'tmp_accountnumber', $member, $readonly) ?>
+            <?php echo html_text_field('Bankleitzahl/BIC', 'tmp_bankcode', $member, $readonly) ?>
+            <?php echo html_text_field('Name der Bank', 'tmp_bankname', $member, $readonly) ?>
             <?php if (!isset($member['id'])) : ?>
-                <input class="submit" type="button" name="btn_bank_details_save" value="&Uuml;bernehmen" onclick="bank_details_save()"/>
-                <input class="submit" type="button" name="btn_bank_details_cancel" value="Abbrechen" onclick="bank_details_cancel()"/>
+                <input class="submit" type="button" name="btn_bank_details_save" value="&Uuml;bernehmen"
+                       onclick="bank_details_save()"/>
+                <input class="submit" type="button" name="btn_bank_details_cancel" value="Abbrechen"
+                       onclick="bank_details_cancel()"/>
             <?php elseif ($readonly) : ?>
-                <input class="submit" type="button" name="btn_bank_details_cancel" value="Zur&uuml;ck" onclick="bank_details_cancel()" id="btn_bank_details_cancel"/>
+                <input class="submit" type="button" name="btn_bank_details_cancel" value="Zur&uuml;ck"
+                       onclick="bank_details_cancel()" id="btn_bank_details_cancel"/>
             <?php else : ?>
-                <input class="submit" type="button" name="btn_bank_details_save" value="&Uuml;bernehmen" onclick="bank_details_save()"/>
-                <input class="submit" type="button" name="btn_bank_details_cancel" value="Abbrechen" onclick="bank_details_cancel()"/>
+                <input class="submit" type="button" name="btn_bank_details_save" value="&Uuml;bernehmen"
+                       onclick="bank_details_save()"/>
+                <input class="submit" type="button" name="btn_bank_details_cancel" value="Abbrechen"
+                       onclick="bank_details_cancel()"/>
             <?php endif ?>
         </fieldset>
     </div>
-<script type="text/javascript">
-
-
-var the_masterkey;
-
-$(document).ready(function(){  
-    $('#accountholder').focus( function() { $("#btn_bank_details").focus(); });
-<?php if ($readonly) : ?>
-    $('#btn_bank_details_cancel').keypress( function(event) { if (event.keyCode == '13') { bank_details_cancel(); } });
-<?php else : ?>
-    $('#tmp_bankname').keypress( function(event) { if (event.keyCode == '13') { bank_details_save(); } });
-<?php endif ?>
-    $('#password1').keypress( function(event) { if (event.keyCode == '13') { decrypt_bank_details(); } });
-    <?php if (!isset($member['id'])) : ?>
-    $('#password2').keypress( function(event) { if (event.keyCode == '13') { import_qrcode(); } });
-<?php endif ?>
-});  
-
-function bank_details_ask_pass() {/*{{{*/
-    modal_window_show($("#password_popup"));
-    $("#password1").focus();
-    return;
-}/*}}}*/
+    <script type="text/javascript">
+        var the_masterkey;
+
+        $(document).ready(function () {
+            $('#accountholder').focus(function () {
+                $("#btn_bank_details").focus();
+            });
+            <?php if ($readonly) : ?>
+            $('#btn_bank_details_cancel').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    bank_details_cancel();
+                }
+            });
+            <?php else : ?>
+            $('#tmp_bankname').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    bank_details_save();
+                }
+            });
+            <?php endif ?>
+            $('#password1').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    decrypt_bank_details();
+                }
+            });
+            <?php if (!isset($member['id'])) : ?>
+            $('#password2').keypress(function (event) {
+                if (event.keyCode == '13') {
+                    import_qrcode();
+                }
+            });
+            <?php endif ?>
+        });
 
+        function bank_details_ask_pass() {
+            modal_window_show($("#password_popup"));
+            $("#password1").focus();
+            return;
+        }
 
-function import_qrcode_ask_pass() {/*{{{*/
-    modal_window_show($("#password_popup2"));
-    $("#password2").focus();
-    return;
-}/*}}}*/
+        function import_qrcode_ask_pass() {
+            modal_window_show($("#password_popup2"));
+            $("#password2").focus();
+            return;
+        }
 
-function cancel_change_bank_details() {/*{{{*/
-    modal_window_hide();
-    $("#btn_bank_details").focus();
-    $("#password1").val('');
-    return;
-}/*}}}*/
+        function cancel_change_bank_details() {
+            modal_window_hide();
+            $("#btn_bank_details").focus();
+            $("#password1").val('');
+            return;
+        }
 
-function cancel_import_qrcode() {/*{{{*/
-    modal_window_hide();
-    $("#password2").val('');
-    return;
-}/*}}}*/
+        function cancel_import_qrcode() {
+            modal_window_hide();
+            $("#password2").val('');
+            return;
+        }
 
-function decrypt_bank_details() {/*{{{*/
+        function decrypt_bank_details() {
+            var password = $('#password1').val();
+            $("#password1").val('');
 
-    var password = $('#password1').val();
-    $("#password1").val('');
+            // We pass a closure so that get_master_key may defer execution
+            get_master_key(password, function (masterkey) {
 
-    // We pass a closure so that get_master_key may defer execution
-    get_master_key(password, function(masterkey) {
+                modal_window_replace($("#bank_detail_popup"));
+                <?php if ($readonly) : ?>
+                $('#btn_bank_details_cancel').focus();
+                <?php else : ?>
+                $('#tmp_accountholder').focus();
+                <?php endif ?>
 
-        modal_window_replace($("#bank_detail_popup"));
-<?php if ($readonly) : ?>
-        $('#btn_bank_details_cancel').focus();
-<?php else : ?>
-        $('#tmp_accountholder').focus();
-<?php endif ?>
+                var accountholder = $('#accountholder').val();
+                var accountnumber = $('#accountnumber').val();
+                var bankcode = $('#bankcode').val();
+                var bankname = $('#bankname').val();
 
-        var accountholder = $('#accountholder').val();
-        var accountnumber = $('#accountnumber').val();
-        var bankcode      = $('#bankcode').val();
-        var bankname      = $('#bankname').val();
-
-        // Encrypt/Decrypt data using AES with masterkey
-        if (accountholder != "") { $('#tmp_accountholder').val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountholder, masterkey))); }
-        if (accountnumber != "") { $('#tmp_accountnumber').val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey))); }
-        if (bankcode      != "") { $('#tmp_bankcode'     ).val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode,      masterkey))); }
-        if (bankname      != "") { $('#tmp_bankname'     ).val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankname,      masterkey))); }
-        the_masterkey = masterkey; // cache masterkey until popup is closed
-    });
-
-}/*}}}*/
-
-function import_qrcode() {/*{{{*/
-
-    var password = $('#password2').val();
-    $("#password2").val('');
-
-    // We pass a closure so that get_master_key may defer execution
-    get_master_key(password, function(masterkey) {
-
-        modal_window_replace($("#qrcode_popup"));
-        the_masterkey = masterkey; // cache masterkey until popup is closed
-    });
-
-}/*}}}*/
-
-function qrcode_close() {/*{{{*/
-
-    modal_window_hide();
-
-    var qrcode_content = $('#qrcode_content').val();
-    $("#qrcode_content").val('');
-    var qrcode = qrcode_content.split(';');
-    if (qrcode.length >= 17) { 
-        $("#nickname").val(qrcode[0]);
-        // XXX birthdate - unused
-        $("#email").val(qrcode[2]);
-        // XXX cccmember - unused
-        $("#firstname").val(qrcode[4]);
-        $("#lastname").val(qrcode[5]);
-        $("#street").val(qrcode[6]);
-        $("#housenumber").val(qrcode[7]);
-        $("#postcode").val(qrcode[8]);
-        $("#city").val(qrcode[9]);
-        $("#country").val(qrcode[10]);
-        // XXX fee unused
-        $("#paymentinterval").val(qrcode[12]);
-        var accountholder = qrcode[13];
-        var accountnumber = qrcode[14];
-        var bankcode = qrcode[15];
-        var bankname = qrcode[16];
-        // XXX amount unused - wurde erst am 4.5. ergänzt, war vorher leer.
-    }
-
-
-    // 4.2 Encrypt/Decrypt data using AES with masterkey
-    if (accountholder != "") { $('#accountholder').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountholder), the_masterkey)); } else { $('#accountholder').val(''); }
-    if (accountnumber != "") { $('#accountnumber').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountnumber), the_masterkey)); } else { $('#accountnumber').val(''); }
-    if (bankcode      != "") { $('#bankcode'     ).val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankcode),      the_masterkey)); } else { $('#bankcode').val(''); }
-    if (bankname      != "") { $('#bankname'     ).val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankname),      the_masterkey)); } else { $('#bankname').val(''); }
-    the_masterkey = '';
-
-}/*}}}*/
+                // Encrypt/Decrypt data using AES with masterkey
+                if (accountholder != "") {
+                    $('#tmp_accountholder').val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountholder, masterkey)));
+                }
+                if (accountnumber != "") {
+                    $('#tmp_accountnumber').val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(accountnumber, masterkey)));
+                }
+                if (bankcode != "") {
+                    $('#tmp_bankcode').val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankcode, masterkey)));
+                }
+                if (bankname != "") {
+                    $('#tmp_bankname').val(Crypto.charenc.UTF8.bytesToString(Crypto.AES.decrypt(bankname, masterkey)));
+                }
+                the_masterkey = masterkey; // cache masterkey until popup is closed
+            });
+        }
 
-function bank_details_save() {/*{{{*/
+        function import_qrcode() {
+            var password = $('#password2').val();
+            $("#password2").val('');
 
-    modal_window_hide();
+            // We pass a closure so that get_master_key may defer execution
+            get_master_key(password, function (masterkey) {
 
-    var accountholder = $('#tmp_accountholder').val();
-    var accountnumber = $('#tmp_accountnumber').val();
-    var bankcode      = $('#tmp_bankcode').val();
-    var bankname      = $('#tmp_bankname').val();
-    $("#tmp_accountholder").val('');
-    $("#tmp_accountnumber").val('');
-    $("#tmp_bankcode").val('');
-    $("#tmp_bankname").val('');
-    
-    accountnumber = accountnumber.replace(/\s+/g, '');
-    bankcode = bankcode.replace(/\s+/g, '');
-    // 4.2 Encrypt/Decrypt data using AES with masterkey
-    if (accountholder != "") { $('#accountholder').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountholder), the_masterkey)); } else { $('#accountholder').val(''); }
-    if (accountnumber != "") { $('#accountnumber').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountnumber), the_masterkey)); } else { $('#accountnumber').val(''); }
-    if (bankcode      != "") { $('#bankcode'     ).val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankcode),      the_masterkey)); } else { $('#bankcode').val(''); }
-    if (bankname      != "") { $('#bankname'     ).val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankname),      the_masterkey)); } else { $('#bankname').val(''); }
-    the_masterkey = '';
+                modal_window_replace($("#qrcode_popup"));
+                the_masterkey = masterkey; // cache masterkey until popup is closed
+            });
+        }
 
-}/*}}}*/
+        function qrcode_close() {
+            modal_window_hide();
+
+            var qrcode_content = $('#qrcode_content').val();
+            $("#qrcode_content").val('');
+            var qrcode = qrcode_content.split(';');
+            if (qrcode.length >= 17) {
+                $("#nickname").val(qrcode[0]);
+                // XXX birthdate - unused
+                $("#email").val(qrcode[2]);
+                // XXX cccmember - unused
+                $("#firstname").val(qrcode[4]);
+                $("#lastname").val(qrcode[5]);
+                $("#street").val(qrcode[6]);
+                $("#housenumber").val(qrcode[7]);
+                $("#postcode").val(qrcode[8]);
+                $("#city").val(qrcode[9]);
+                $("#country").val(qrcode[10]);
+                // XXX fee unused
+                $("#paymentinterval").val(qrcode[12]);
+                var accountholder = qrcode[13];
+                var accountnumber = qrcode[14];
+                var bankcode = qrcode[15];
+                var bankname = qrcode[16];
+                // XXX amount unused - wurde erst am 4.5. ergänzt, war vorher leer.
+            }
 
-function bank_details_cancel() {/*{{{*/
+            // 4.2 Encrypt/Decrypt data using AES with masterkey
+            if (accountholder != "") {
+                $('#accountholder').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountholder), the_masterkey));
+            } else {
+                $('#accountholder').val('');
+            }
+            if (accountnumber != "") {
+                $('#accountnumber').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountnumber), the_masterkey));
+            } else {
+                $('#accountnumber').val('');
+            }
+            if (bankcode != "") {
+                $('#bankcode').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankcode), the_masterkey));
+            } else {
+                $('#bankcode').val('');
+            }
+            if (bankname != "") {
+                $('#bankname').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankname), the_masterkey));
+            } else {
+                $('#bankname').val('');
+            }
+            the_masterkey = '';
+        }
 
-    modal_window_hide();
+        function bank_details_save() {
+            modal_window_hide();
+
+            var accountholder = $('#tmp_accountholder').val();
+            var accountnumber = $('#tmp_accountnumber').val();
+            var bankcode = $('#tmp_bankcode').val();
+            var bankname = $('#tmp_bankname').val();
+            $("#tmp_accountholder").val('');
+            $("#tmp_accountnumber").val('');
+            $("#tmp_bankcode").val('');
+            $("#tmp_bankname").val('');
+
+            accountnumber = accountnumber.replace(/\s+/g, '');
+            bankcode = bankcode.replace(/\s+/g, '');
+            // 4.2 Encrypt/Decrypt data using AES with masterkey
+            if (accountholder != "") {
+                $('#accountholder').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountholder), the_masterkey));
+            } else {
+                $('#accountholder').val('');
+            }
+            if (accountnumber != "") {
+                $('#accountnumber').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(accountnumber), the_masterkey));
+            } else {
+                $('#accountnumber').val('');
+            }
+            if (bankcode != "") {
+                $('#bankcode').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankcode), the_masterkey));
+            } else {
+                $('#bankcode').val('');
+            }
+            if (bankname != "") {
+                $('#bankname').val(Crypto.AES.encrypt(Crypto.charenc.UTF8.stringToBytes(bankname), the_masterkey));
+            } else {
+                $('#bankname').val('');
+            }
+            the_masterkey = '';
+        }
 
-    $("#tmp_accountholder").val('');
-    $("#tmp_accountnumber").val('');
-    $("#tmp_bankcode").val('');
-    $("#tmp_bankname").val('');
+        function bank_details_cancel() {
+            modal_window_hide();
 
-    the_masterkey = '';
-}/*}}}*/
+            $("#tmp_accountholder").val('');
+            $("#tmp_accountnumber").val('');
+            $("#tmp_bankcode").val('');
+            $("#tmp_bankname").val('');
 
-</script>
+            the_masterkey = '';
+        }
+    </script>
     <?php
-}/*}}}*/
-
-
+}
index 9dbed18..3fcc47b 100644 (file)
 <?php
 
-function action_404() {/*{{{*/
+function action_404()
+{
     header('HTTP/1.0 404 Not Found');
     ?>
     <h2>Seite nicht gefunden!</h2>
     <p>Was immer du auch suchst, es ist nicht hier.</p>
     <?php
-}/*}}}*/
+}
 
-function redirect($url) {/*{{{*/
+function redirect($url)
+{
     header('HTTP/1.1 301 Moved Permanently');
     header('Location: ' . $url);
     die();
-}/*}}}*/
+}
 
-function link_to($action = '', $params = array()) {/*{{{*/
-    if (!empty($action)) $params = array_merge(array('action' => $action), $params);
-       $base = str_replace('index.php', '', $_SERVER['SCRIPT_NAME']);
-    if (empty($params)) return $base;
+function link_to($action = '', $params = array())
+{
+    if (!empty($action)) {
+        $params = array_merge(array('action' => $action), $params);
+    }
+    $base = str_replace('index.php', '', $_SERVER['SCRIPT_NAME']);
+    if (empty($params)) {
+        return $base;
+    }
     $query_string = '';
     foreach ($params as $key => $val) {
-        if ($query_string != '') $query_string .= '&';
+        if ($query_string != '') {
+            $query_string .= '&';
+        }
         $query_string .= urlencode($key) . '=' . urlencode($val);
     }
     return $base . '?' . $query_string;
-}/*}}}*/
+}
 
-function log_messages($log_messages) {/*{{{*/
-    if (empty($log_messages)) return;
-?>
+function log_messages($log_messages)
+{
+    if (empty($log_messages)) {
+        return;
+    }
+    ?>
     <ul class="log_messages">
-    <?php foreach ($log_messages as $log_message) : ?>
-        <li><?=html_escape($log_message)?></li>
-    <?php endforeach ?>
+        <?php foreach ($log_messages as $log_message) : ?>
+            <li><?php echo html_escape($log_message) ?></li>
+        <?php endforeach ?>
     </ul>
-<?php
-}/*}}}*/
+    <?php
+}
 
-function format_date($unixtime) {
+function format_date($unixtime)
+{
     return strftime('%d.%m.%Y', $unixtime);
 }
 
-function format_month() {
+function format_month()
+{
     switch (func_num_args()) {
-        case 1: $ts    = func_get_arg(0);
-                $year  = date('Y', $ts);
-                $month = date('n', $ts);
+        case 1:
+            $ts = func_get_arg(0);
+            $year = date('Y', $ts);
+            $month = date('n', $ts);
             break;
-        case 2: $year  = func_get_arg(0);
-                $month = func_get_arg(1);
+        case 2:
+            $year = func_get_arg(0);
+            $month = func_get_arg(1);
             break;
-        default: return NULL;
+        default:
+            return null;
     }
     return sprintf('%02d/%04d', $month, $year);
 }
 
-function format_money($amount) {
+function format_money($amount)
+{
     return number_format($amount, 2, ',', '') . '€';
 }
 
-function ui_date2unixtime($date) {
+function ui_date2unixtime($date)
+{
     return strtotime($date);
 }
-function ui_money2float($amount) {
-    return str_replace(',', '.', $amount);
-}
 
-function paginate($url, $current, $max) {
-?>
-<?php if ($max > 1) : ?>
-<div class="pagination">
-       <?php if ($current != 1) : ?>
-       <div class="prev"><a href="<?=html_escape(sprintf($url, $current - 1))?>">&laquo;</a></div>
-       <?php endif ?>
-       <?php if ($current != $max) : ?>
-       <div class="next"><a href="<?=html_escape(sprintf($url, $current + 1))?>">&raquo;</a></div>
-       <?php endif ?>
-
-       <?php $skipped = false; ?>
-
-       <?php for ($page = 1; $page <= $max; $page++) : ?>
-           <?php if ($page != 1 && $page != $max && ($page < $current - 3 || $page > $current + 3)) { $skipped = true; continue; } ?>
-           <?php if ($skipped) : ?> ... <?php endif ?>
-               <?php if ($page == $current) : ?>
-            <?=html_escape($page)?>
-        <?php else : ?>
-            <a href="<?=html_escape(sprintf($url, $page))?>"><?=html_escape($page)?></a>
-        <?php endif ?>
-        <?php $skipped = false; ?>
-       <?php endfor ?>
-</div>
-<?php endif ?>
-<?
+function ui_money2float($amount)
+{
+    return (float)str_replace(',', '.', $amount);
 }
 
+function paginate($url, $current, $max)
+{
+    ?>
+    <?php if ($max > 1) : ?>
+    <div class="pagination">
+        <?php if ($current != 1) : ?>
+            <div class="prev"><a href="<?php echo html_escape(sprintf($url, $current - 1)) ?>">&laquo;</a></div>
+        <?php endif ?>
+        <?php if ($current != $max) : ?>
+            <div class="next"><a href="<?php echo html_escape(sprintf($url, $current + 1)) ?>">&raquo;</a></div>
+        <?php endif ?>
 
-function js_modal_windows() {/*{{{*/
-?>
-<script type="text/javascript">
-
-$(document).ready(function(){  
-    var window_width = $(window).width();  
-    var window_height = $(window).height();  
-    $('.modal_window').each(function(){  
-        var modal_height = $(this).outerHeight();  
-        var modal_width = $(this).outerWidth();  
-        var top = (window_height-modal_height)/2;  
-        var left = (window_width-modal_width)/2;  
-        $(this).css({'top' : top , 'left' : left});  
-    });  
-});  
-
-var modal_windows = new Array();
-function modal_window_show(modal_window) {
-    var length = modal_windows.length;
-    if (length > 0) modal_windows[length - 1].fadeOut(500);
-    else $("#mask").fadeTo(500, 0.8);
-    modal_windows.push(modal_window);
-    modal_window.fadeIn(500);
-}
-function modal_window_hide() {
-    var length = modal_windows.length;
-    if (length <= 0) return;
-    modal_windows[length - 1].fadeOut(500);
-    if (length == 1) {
-        $("#mask").fadeOut(500);
-    }
-    else {
-        modal_windows[length - 2].fadeIn(500);
-    }
-    modal_windows.pop();
-}
-function modal_window_replace(modal_window) {
-    var length = modal_windows.length;
-    if (length > 0) {
-        modal_windows[length - 1].fadeOut(500);
-        modal_windows.pop();
-    }
-    modal_windows.push(modal_window);
-    modal_window.fadeIn(500);
-}
+        <?php $skipped = false; ?>
 
-</script>
-<div id="mask"></div>  
-<div id="please_wait" class="modal_window" style="text-align:center;">
-    <strong>Bitte warten...</strong><br/>
-    <img src="images/activity_indicator.gif"/>
-</div>
+        <?php for ($page = 1; $page <= $max; $page++) : ?>
+            <?php if ($page != 1 && $page != $max && ($page < $current - 3 || $page > $current + 3)) {
+                $skipped = true;
+                continue;
+            } ?>
+            <?php if ($skipped) : ?> ... <?php endif ?>
+            <?php if ($page == $current) : ?>
+                <?php echo html_escape($page) ?>
+            <?php else : ?>
+                <a href="<?php echo html_escape(sprintf($url, $page)) ?>"><?php echo html_escape($page) ?></a>
+            <?php endif ?>
+            <?php $skipped = false; ?>
+        <?php endfor ?>
+    </div>
 <?php
-}/*}}}*/
-
+endif;
+}
 
+function js_modal_windows()
+{
+    ?>
+    <script type="text/javascript">
+
+        $(document).ready(function () {
+            var window_width = $(window).width();
+            var window_height = $(window).height();
+            $('.modal_window').each(function () {
+                var modal_height = $(this).outerHeight();
+                var modal_width = $(this).outerWidth();
+                var top = (window_height - modal_height) / 2;
+                var left = (window_width - modal_width) / 2;
+                $(this).css({'top': top, 'left': left});
+            });
+        });
+
+        var modal_windows = [];
+
+        function modal_window_show(modal_window) {
+            var length = modal_windows.length;
+            if (length > 0) modal_windows[length - 1].fadeOut(500);
+            else $("#mask").fadeTo(500, 0.8);
+            modal_windows.push(modal_window);
+            modal_window.fadeIn(500);
+        }
+
+        function modal_window_hide() {
+            var length = modal_windows.length;
+            if (length <= 0) return;
+            modal_windows[length - 1].fadeOut(500);
+            if (length == 1) {
+                $("#mask").fadeOut(500);
+            }
+            else {
+                modal_windows[length - 2].fadeIn(500);
+            }
+            modal_windows.pop();
+        }
+
+        function modal_window_replace(modal_window) {
+            var length = modal_windows.length;
+            if (length > 0) {
+                modal_windows[length - 1].fadeOut(500);
+                modal_windows.pop();
+            }
+            modal_windows.push(modal_window);
+            modal_window.fadeIn(500);
+        }
+
+    </script>
+    <div id="mask"></div>
+    <div id="please_wait" class="modal_window" style="text-align:center;">
+        <strong>Bitte warten...</strong><br/>
+        <img src="assets/images/activity_indicator.gif"/>
+    </div>
+    <?php
+}
index f5290f5..81b9041 100644 (file)
 <?php
 
 // NOTE: combination of earnings and expenses
-
 $ACCOUNT_TYPES = array(
     'bank' => 'Konto',
     'cash' => 'Kasse'
 );
 
-/* DB functions {{{ */
-function db_get_payments($offset, $count, $where) {
+// DB functions
+function db_get_payments($offset, $count, $where)
+{
     $limit = '';
-    if (isset($offset) && isset($count)) $limit = sprintf(' LIMIT %1$d,%2$d', (int)$offset, (int)$count);
-    elseif (isset($offset)) $limit = sprintf(' LIMIT %1$d', (int)$count);
-    $sql = 'SELECT t.*, %4$s.nickname AS nickname FROM ((SELECT \'earning\' as ptype, %1$s.* FROM %1$s %3$s) UNION (SELECT \'expense\', %2$s.* FROM %2$s %3$s)) AS t LEFT JOIN %4$s ON t.member_id=%4$s.id ORDER BY `date` DESC, t.id DESC' . $limit;
-    return db_select_multi(sprintf($sql, DB_TABLE_EARNINGS, DB_TABLE_EXPENSES, $where, DB_TABLE_MEMBERS));
+    if (isset($offset) && isset($count)) {
+        $limit = sprintf(' LIMIT %d,%d', (int)$offset, (int)$count);
+    } elseif (isset($offset)) {
+        $limit = sprintf(' LIMIT %d', (int)$count);
+    }
+
+    $sql = "
+          SELECT t.*, `members`.nickname AS nickname FROM (
+              (SELECT 'earning' AS ptype, `earnings`.* FROM `earnings` %1\$s)
+              UNION
+              (SELECT 'expense', `expenses`.* FROM `expenses` %1\$s)
+          ) AS t
+          LEFT JOIN `members` ON t.member_id=`members`.id
+          ORDER BY `date` DESC, t.id DESC" . $limit;
+
+    return db_select_multi(sprintf($sql, $where));
 }
 
-function db_get_finished_payments($offset, $count) {
-    $where = ' WHERE status=\'paid\'';
+function db_get_finished_payments($offset, $count)
+{
+    $where = " WHERE status='paid'";
     $payments = db_get_payments($offset, $count, $where);
 
-    $bank  = 0;
-    $cash  = 0;
+    $bank = 0;
+    $cash = 0;
     $total = 0;
     if ($count != 0) { // XXX TODO hä? - An dieser Stelle gäbe es sinnigere Bedinungen
-        $limit = sprintf(' LIMIT %d,18446744073709551615', (int)($count + $offset)); // SELECT mit Offset aber ohne Limit
-        $sql = 'SELECT SUM(IF(`account`=\'bank\', `value`, 0)) as `bank`, SUM(IF(`account`=\'cash\', `value`, 0)) as `cash`, SUM(`value`) AS `total` 
+        $limit = sprintf(' LIMIT %d,18446744073709551615',
+            (int)($count + $offset)); // SELECT mit Offset aber ohne Limit
+        $sql = "SELECT SUM(IF(`account`='bank', `value`, 0)) AS `bank`, SUM(IF(`account`='cash', `value`, 0)) AS `cash`, SUM(`value`) AS `total` 
                 FROM (
                     SELECT `value`, `account` 
-                    FROM (( SELECT `value`,                 `id`, `date`, `account` FROM %1$s %3$s) 
-                    UNION ( SELECT `value` * -1 AS `value`, `id`, `date`, `account` FROM %2$s %3$s)
+                    FROM (( SELECT `value`,                 `id`, `date`, `account` FROM `earnings` %1\$s) 
+                    UNION ( SELECT `value` * -1 AS `value`, `id`, `date`, `account` FROM `expenses` %1\$s)
                     ) AS t
-                    ORDER BY `date` DESC, t.id DESC' . $limit . '
+                    ORDER BY `date` DESC, t.id DESC" . $limit . '
                 ) AS u';
-        $row = db_select_single(sprintf($sql, DB_TABLE_EARNINGS, DB_TABLE_EXPENSES, $where));
-        $bank  = $row['bank'];
-        $cash  = $row['cash'];
+        $row = db_select_single(sprintf($sql, $where));
+        $bank = $row['bank'];
+        $cash = $row['cash'];
         $total = $row['total'];
     }
     for ($i = count($payments) - 1; $i >= 0; $i--) {
         $value = $payments[$i]['value'];
-        if ($payments[$i]['ptype'] == 'expense') $value = bcmul($value, '-1');
+        if ($payments[$i]['ptype'] == 'expense') {
+            $value = bcmul($value, '-1');
+        }
         switch ($payments[$i]['account']) {
-            case 'bank': $bank = bcadd($bank, $value); break;
-            case 'cash': $cash = bcadd($cash, $value); break;
-            default: break; // TODO XXX die?
+            case 'bank':
+                $bank = bcadd($bank, $value);
+                break;
+            case 'cash':
+                $cash = bcadd($cash, $value);
+                break;
+            default:
+                break; // TODO XXX die?
         }
         $total = bcadd($total, $value);
-        $payments[$i]['bank']   = $bank;
-        $payments[$i]['cash']   = $cash;
-        $payments[$i]['total']  = $total;
+        $payments[$i]['bank'] = $bank;
+        $payments[$i]['cash'] = $cash;
+        $payments[$i]['total'] = $total;
     }
     return $payments;
 }
 
-function db_count_finished_payments() {
-    $where = ' WHERE status=\'paid\'';
-    $sql = 'SELECT count(*) as `count` FROM ((SELECT * FROM %1$s %3$s) UNION (SELECT * FROM %2$s %3$s)) AS t';
-    $row = db_select_single(sprintf($sql, DB_TABLE_EARNINGS, DB_TABLE_EXPENSES, $where));
+function db_count_finished_payments()
+{
+    $where = " WHERE status='paid'";
+    $sql = 'SELECT count(*) AS `count` FROM ((SELECT * FROM `earnings` %1$s) UNION (SELECT * FROM `expenses` %1$s)) AS t';
+    $row = db_select_single(sprintf($sql, $where));
     return $row['count'];
 }
 
-function db_get_open_payments($offset, $count) {
-    return db_get_payments($offset, $count, ' WHERE status=\'open\'');
+function db_get_open_payments($offset, $count)
+{
+    return db_get_payments($offset, $count, " WHERE status='open'");
 }
 
-/* }}} */
-
-function render_finished_payments($count = 100) {/*{{{*/
-    global $EXPENSE_TYPES, $EARNING_TYPES, $ACCOUNT_TYPES;
+function render_finished_payments($count = 100)
+{
+    global $EXPENSE_TYPES, $EARNING_TYPES;
     $page = 1;
-    if (!empty($_REQUEST['page'])) $page = max(1, (int)$_REQUEST['page']);
+    if (!empty($_REQUEST['page'])) {
+        $page = max(1, (int)$_REQUEST['page']);
+    }
     $payments = db_get_finished_payments(($page - 1) * $count, $count);
     $max = db_count_finished_payments();
     ?>
     <h3 id="finished">Abgeschlossene Zahlungen</h3>
     <?php if (isset($payments)) : ?>
-        <table>
-            <tr>
-                <th>Id</th>
-                <th>Datum</th>
-                <th>Typ</th>
-                <th>Mitglied</th>
-                <th>Betrag</th>
-                <th>Beschreibung</th>
-                <th>Konto</th>
-                <th>Kasse</th>
-                <th>Gesamt</th>
-            </tr>
+    <table>
+        <tr>
+            <th>Id</th>
+            <th>Datum</th>
+            <th>Typ</th>
+            <th>Mitglied</th>
+            <th>Betrag</th>
+            <th>Beschreibung</th>
+            <th>Konto</th>
+            <th>Kasse</th>
+            <th>Gesamt</th>
+        </tr>
         <?php foreach ($payments as $payment) : ?>
-            <tr class="<?=$payment['ptype']?>">
-                <td style="text-align: right;"><a href="<?=html_escape(link_to('change_' . $payment['ptype'], array('id' => $payment['id'])))?>"><?=html_escape($payment['id'])?></a></td>
-                <td><?=html_escape(format_date(db_date2unixtime($payment['date'])))?></td>
-                <td><?=html_escape($payment['ptype'] == 'earning'? $EARNING_TYPES[$payment['type']] : $EXPENSE_TYPES[$payment['type']])?></td>
-                <td><?php if ($payment['member_id'] != 0) : ?><a href="<?=html_escape(link_to('view_member', array('id'=> $payment['member_id'])))?>"><?=html_escape($payment['nickname'])?><?php endif ?></a></td>
-                <td style="text-align: right;"><?=html_escape(format_money(($payment['ptype'] == 'earning' ? 1 : -1)  * $payment['value']))?></td>
-                <td><?=html_escape($payment['description'])?></td>
-                <td style="text-align: right;<?php if ($payment['account'] == 'bank') : ?> text-decoration:underline;<?php endif ?>"><?=html_escape(format_money($payment['bank']))?></td>
-                <td style="text-align: right;<?php if ($payment['account'] == 'cash') : ?> text-decoration:underline;<?php endif ?>"><?=html_escape(format_money($payment['cash']))?></td>
-                <td style="text-align: right;"><?=html_escape(format_money($payment['total']))?></td>
+            <tr class="<?php echo $payment['ptype'] ?>">
+                <td style="text-align: right;"><a href="<?php echo html_escape(link_to('change_' . $payment['ptype'],
+                        array('id' => $payment['id']))) ?>"><?php echo html_escape($payment['id']) ?></a></td>
+                <td><?php echo html_escape(format_date(db_date2unixtime($payment['date']))) ?></td>
+                <td><?php echo html_escape($payment['ptype'] == 'earning' ? $EARNING_TYPES[$payment['type']] : $EXPENSE_TYPES[$payment['type']]) ?></td>
+                <td><?php if ($payment['member_id'] != 0) : ?><a href="<?php echo html_escape(link_to('view_member',
+                        array('id' => $payment['member_id']))) ?>"><?php echo html_escape($payment['nickname']) ?><?php endif ?></a>
+                </td>
+                <td style="text-align: right;"><?php echo html_escape(format_money(($payment['ptype'] == 'earning' ? 1 : -1) * $payment['value'])) ?></td>
+                <td><?php echo html_escape($payment['description']) ?></td>
+                <td style="text-align: right;<?php if ($payment['account'] == 'bank') : ?> text-decoration:underline;<?php endif ?>"><?php echo html_escape(format_money($payment['bank'])) ?></td>
+                <td style="text-align: right;<?php if ($payment['account'] == 'cash') : ?> text-decoration:underline;<?php endif ?>"><?php echo html_escape(format_money($payment['cash'])) ?></td>
+                <td style="text-align: right;"><?php echo html_escape(format_money($payment['total'])) ?></td>
             </tr>
         <?php endforeach ?>
-        </table>
-        <?php paginate(link_to('finances') . '&page=%d#finished', $page, ceil($max / $count)); ?>
-    <?php else : ?>
-        <p>Bisher gibt's noch keine abgeschlossenen Zahlungen.</p>
-    <?php endif ?>
+    </table>
+    <?php paginate(link_to('finances') . '&page=%d#finished', $page, ceil($max / $count)); ?>
+<?php else : ?>
+    <p>Bisher gibt's noch keine abgeschlossenen Zahlungen.</p>
+<?php endif ?>
     <?php
+}
 
-}/*}}}*/
-
-function render_open_payments($offset = 0, $count = 25) {/*{{{*/
+function render_open_payments($offset = 0, $count = 25)
+{
     global $EXPENSE_TYPES, $EARNING_TYPES, $ACCOUNT_TYPES;
-    global $EXPENSE_TYPES, $EARNING_TYPES;
     $payments = db_get_open_payments($offset, $count);
     ?>
     <h3>Offene Zahlungen</h3>
     <?php if (isset($payments)) : ?>
-        <table>
-            <tr>
-                <th>Id</th>
-                <th>Datum</th>
-                <th>Typ</th>
-                <th>Mitglied</th>
-                <th>Quelle/Ziel</th>
-                <th>Betrag</th>
-                <th>Beschreibung</th>
-            </tr>
+    <table>
+        <tr>
+            <th>Id</th>
+            <th>Datum</th>
+            <th>Typ</th>
+            <th>Mitglied</th>
+            <th>Quelle/Ziel</th>
+            <th>Betrag</th>
+            <th>Beschreibung</th>
+        </tr>
         <?php foreach ($payments as $payment) : ?>
-            <tr class="<?=$payment['ptype']?>">
-                <td style="text-align: right;"><a href="<?=html_escape(link_to('change_' . $payment['ptype'], array('id' => $payment['id'])))?>"><?=html_escape($payment['id'])?></a></td>
-                <td><?=html_escape(format_date(db_date2unixtime($payment['date'])))?></td>
-                <td><?=html_escape($payment['ptype'] == 'earning'? $EARNING_TYPES[$payment['type']] : $EXPENSE_TYPES[$payment['type']])?></td>
-                <td><?php if ($payment['member_id'] != 0) : ?><a href="<?=html_escape(link_to('view_member', array('id'=> $payment['member_id'])))?>"><?=html_escape($payment['nickname'])?><?php endif ?></a></td>
-                <td><?=html_escape($ACCOUNT_TYPES[$payment['account']])?></td>
-                <td style="text-align: right;"><?=html_escape(format_money(($payment['ptype'] == 'earning'? 1 : -1)  * $payment['value']))?></td>
-                <td><?=html_escape($payment['description'])?></td>
+            <tr class="<?php echo $payment['ptype'] ?>">
+                <td style="text-align: right;"><a href="<?php echo html_escape(link_to('change_' . $payment['ptype'],
+                        array('id' => $payment['id']))) ?>"><?php echo html_escape($payment['id']) ?></a></td>
+                <td><?php echo html_escape(format_date(db_date2unixtime($payment['date']))) ?></td>
+                <td><?php echo html_escape($payment['ptype'] == 'earning' ? $EARNING_TYPES[$payment['type']] : $EXPENSE_TYPES[$payment['type']]) ?></td>
+                <td><?php if ($payment['member_id'] != 0) : ?><a href="<?php echo html_escape(link_to('view_member',
+                        array('id' => $payment['member_id']))) ?>"><?php echo html_escape($payment['nickname']) ?><?php endif ?></a>
+                </td>
+                <td><?php echo html_escape($ACCOUNT_TYPES[$payment['account']]) ?></td>
+                <td style="text-align: right;"><?php echo html_escape(format_money(($payment['ptype'] == 'earning' ? 1 : -1) * $payment['value'])) ?></td>
+                <td><?php echo html_escape($payment['description']) ?></td>
             </tr>
         <?php endforeach ?>
-        </table>
-    <?php else : ?>
-        <p>Bisher gibt's noch keine abgeschlossenen Zahlungen.</p>
-    <?php endif ?>
+    </table>
+<?php else : ?>
+    <p>Bisher gibt's noch keine abgeschlossenen Zahlungen.</p>
+<?php endif ?>
     <?php
-
-}/*}}}*/
-
+}
index 27cbbc7..de3c4fc 100644 (file)
 <?php
 
-function action_export_members() {
-       global $EARNING_TYPES, $EXPENSE_TYPES;
-
+function action_export_members()
+{
     error_reporting(error_reporting() & ~E_DEPRECATED & ~E_STRICT);
-       require_once 'vendor/autoload.php';
-
-       // Creating a workbook
-       $workbook = new Spreadsheet_Excel_Writer();
-       $workbook->setVersion(8);
-
-       // sending HTTP headers
-       $workbook->send('Mitglieder.xls');
-
-       // Creating a worksheet
-
-       $members = db_get_members();
-
-
-       $row = 0;
-       $col = 0;
-
-       $worksheet =& $workbook->addWorksheet('Mitglieder');
-       $worksheet->setInputEncoding('UTF-8');
-       $row = 0;
-       $worksheet->write($row, $col++, 'Mitgliedsnummer');
-       $worksheet->write($row, $col++, 'Nickname');
-       $worksheet->write($row, $col++, 'E-Mail');
-       $worksheet->write($row, $col++, 'Vorname');
-       $worksheet->write($row, $col++, 'Nachname');
-       $worksheet->write($row, $col++, 'Straße');
-       $worksheet->write($row, $col++, 'Hausnummer');
-       $worksheet->write($row, $col++, 'PLZ');
-       $worksheet->write($row, $col++, 'Ort');
-       $worksheet->write($row, $col++, 'Land');
-       $worksheet->write($row, $col++, 'Telefon');
-       $worksheet->write($row, $col++, 'Fax');
-       $worksheet->write($row, $col++, 'Handy');
-       $worksheet->write($row, $col++, 'Jabber');
-       $worksheet->write($row, $col++, 'ICQ');
-       $worksheet->write($row, $col++, 'MSN');
-       $worksheet->write($row, $col++, 'AIM');
-       $worksheet->write($row, $col++, 'Skype');
-       $worksheet->write($row, $col++, 'Website');
-       $worksheet->write($row, $col++, 'Twitter');
-       $worksheet->write($row, $col++, 'Lastschrifteinzug');
-       $worksheet->write($row, $col++, 'Mandatunterschriftsdatum');
-       $worksheet->write($row, $col++, 'Status');
-       $row++;
-       
-       foreach ($members as $member) {
-               $col = 0;
-               $worksheet->write($row, $col++, $member['number']);    
-               $worksheet->write($row, $col++, $member['nickname']);    
-               $worksheet->write($row, $col++, $member['email']);     
-               $worksheet->write($row, $col++, $member['firstname']);    
-               $worksheet->write($row, $col++, $member['lastname']);    
-               $worksheet->write($row, $col++, $member['street']);    
-               $worksheet->write($row, $col++, $member['housenumber']);
-               $worksheet->write($row, $col++, $member['postcode']);      
-               $worksheet->write($row, $col++, $member['city']);         
-               $worksheet->write($row, $col++, $member['country']); 
-               $worksheet->write($row, $col++, $member['phone']);         
-               $worksheet->write($row, $col++, $member['fax']);         
-               $worksheet->write($row, $col++, $member['mobile']);         
-               $worksheet->write($row, $col++, $member['jabber']);         
-               $worksheet->write($row, $col++, $member['icq']);         
-               $worksheet->write($row, $col++, $member['msn']);         
-               $worksheet->write($row, $col++, $member['aim']);         
-               $worksheet->write($row, $col++, $member['skype']);         
-               $worksheet->write($row, $col++, $member['url']);    
-               $worksheet->write($row, $col++, $member['twitter']);
-               $worksheet->write($row, $col++, $member['directdebit']);
-               $worksheet->write($row, $col++, $member['ddmandatesigdate']);
-               $membership_info = fees_info_for_member($member['id'], time());
-               $worksheet->write($row, $col++, $membership_info['is_member']);
-               $col = 0;
-               $row++;
-       }
-
-       // Let's send the file
-       $workbook->close();
-
-       $content = ob_get_contents();
-       ob_end_clean();
-       echo $content;
-       exit();
+
+    // Creating a workbook
+    $workbook = new Spreadsheet_Excel_Writer();
+    $workbook->setVersion(8);
+
+    // sending HTTP headers
+    $workbook->send('Mitglieder.xls');
+
+    // Creating a worksheet
+    $members = db_get_members();
+
+    $row = 0;
+    $col = 0;
+
+    $worksheet = $workbook->addWorksheet('Mitglieder');
+    $worksheet->setInputEncoding('UTF-8');
+    $worksheet->write($row, $col++, 'Mitgliedsnummer');
+    $worksheet->write($row, $col++, 'Nickname');
+    $worksheet->write($row, $col++, 'E-Mail');
+    $worksheet->write($row, $col++, 'Vorname');
+    $worksheet->write($row, $col++, 'Nachname');
+    $worksheet->write($row, $col++, 'Straße');
+    $worksheet->write($row, $col++, 'Hausnummer');
+    $worksheet->write($row, $col++, 'PLZ');
+    $worksheet->write($row, $col++, 'Ort');
+    $worksheet->write($row, $col++, 'Land');
+    $worksheet->write($row, $col++, 'Telefon');
+    $worksheet->write($row, $col++, 'Fax');
+    $worksheet->write($row, $col++, 'Handy');
+    $worksheet->write($row, $col++, 'Jabber');
+    $worksheet->write($row, $col++, 'ICQ');
+    $worksheet->write($row, $col++, 'MSN');
+    $worksheet->write($row, $col++, 'AIM');
+    $worksheet->write($row, $col++, 'Skype');
+    $worksheet->write($row, $col++, 'Website');
+    $worksheet->write($row, $col++, 'Twitter');
+    $worksheet->write($row, $col++, 'Lastschrifteinzug');
+    $worksheet->write($row, $col++, 'Mandatunterschriftsdatum');
+    $worksheet->write($row, $col, 'Status');
+    $row++;
+
+    foreach ($members as $member) {
+        $col = 0;
+        $worksheet->write($row, $col++, $member['number']);
+        $worksheet->write($row, $col++, $member['nickname']);
+        $worksheet->write($row, $col++, $member['email']);
+        $worksheet->write($row, $col++, $member['firstname']);
+        $worksheet->write($row, $col++, $member['lastname']);
+        $worksheet->write($row, $col++, $member['street']);
+        $worksheet->write($row, $col++, $member['housenumber']);
+        $worksheet->write($row, $col++, $member['postcode']);
+        $worksheet->write($row, $col++, $member['city']);
+        $worksheet->write($row, $col++, $member['country']);
+        $worksheet->write($row, $col++, $member['phone']);
+        $worksheet->write($row, $col++, $member['fax']);
+        $worksheet->write($row, $col++, $member['mobile']);
+        $worksheet->write($row, $col++, $member['jabber']);
+        $worksheet->write($row, $col++, $member['icq']);
+        $worksheet->write($row, $col++, $member['msn']);
+        $worksheet->write($row, $col++, $member['aim']);
+        $worksheet->write($row, $col++, $member['skype']);
+        $worksheet->write($row, $col++, $member['url']);
+        $worksheet->write($row, $col++, $member['twitter']);
+        $worksheet->write($row, $col++, $member['directdebit']);
+        $worksheet->write($row, $col++, $member['ddmandatesigdate']);
+        $membership_info = fees_info_for_member($member['id'], time());
+        $worksheet->write($row, $col, $membership_info['is_member']);
+        $row++;
+    }
+
+    // Let's send the file
+    $workbook->close();
+
+    $content = ob_get_contents();
+    ob_end_clean();
+    echo $content;
+    exit();
 }
 
-function action_export_payments() {
-       global $EARNING_TYPES, $EXPENSE_TYPES;
+function action_export_payments()
+{
+    global $EARNING_TYPES, $EXPENSE_TYPES;
 
     error_reporting(error_reporting() & ~E_DEPRECATED & ~E_STRICT);
-       require_once 'vendor/autoload.php';
-
-       // Creating a workbook
-       $workbook = new Spreadsheet_Excel_Writer();
-       $workbook->setVersion(8);
-
-       // sending HTTP headers
-       $workbook->send('Finanzen.xls');
-
-       // Creating a worksheet
-
-       $payments = db_get_finished_payments(0, 1000000000);
-
-
-       $row = 0;
-       $col = 0;
-       $current_year = '';
-
-       foreach ($payments as $payment) {
-               $year = substr($payment['date'], 0, 4);
-               if ($year != $current_year) {
-                       $current_year = $year;
-                       $worksheet =& $workbook->addWorksheet($year);
-                       $worksheet->setInputEncoding('UTF-8');
-                       $row = 0;
-
-                       $worksheet->write($row, $col++, 'Id');
-                       $worksheet->write($row, $col++, 'Datum');
-                       $worksheet->write($row, $col++, 'Kategorie');
-                       $worksheet->write($row, $col++, 'Betrag');
-                       $worksheet->write($row, $col++, 'Beschreibung');
-                       $worksheet->write($row, $col++, 'Mitglied');
-                       $worksheet->write($row, $col++, 'Kontostand');
-                       $worksheet->write($row, $col++, 'Kassenstand');
-                       $worksheet->write($row, $col++, 'Gesamt');
-                       $row++;
-                       $col = 0;
-               }
-               $worksheet->write($row, $col++, $payment['id']);
-               $worksheet->write($row, $col++, $payment['date']);
-               $worksheet->write($row, $col++, $payment['ptype'] == 'earning'? $EARNING_TYPES[$payment['type']] : $EXPENSE_TYPES[$payment['type']]);
-               $worksheet->write($row, $col++, ($payment['ptype'] == 'earning' ? 1 : -1)  * $payment['value']);
-               $worksheet->write($row, $col++, $payment['description']);
-               $worksheet->write($row, $col++, $payment['nickname']);
-               $worksheet->write($row, $col++, $payment['bank']);
-               $worksheet->write($row, $col++, $payment['cash']);
-               $worksheet->write($row, $col++, $payment['total']);
-
-               $col = 0;
-               $row++;
-       }
-
-       // Let's send the file
-       $workbook->close();
-
-       $content = ob_get_contents();
-       ob_end_clean();
-       echo $content;
-       exit();
-}
 
-
-?>
\ No newline at end of file
+    // Creating a workbook
+    $workbook = new Spreadsheet_Excel_Writer();
+    $workbook->setVersion(8);
+
+    // sending HTTP headers
+    $workbook->send('Finanzen.xls');
+
+    // Creating a worksheet
+    $payments = db_get_finished_payments(0, 1000000000);
+
+
+    $row = 0;
+    $col = 0;
+    $current_year = '';
+    foreach ($payments as $payment) {
+        $year = substr($payment['date'], 0, 4);
+        if ($year != $current_year) {
+            $current_year = $year;
+            $worksheet = $workbook->addWorksheet($year);
+            $worksheet->setInputEncoding('UTF-8');
+            $row = 0;
+
+            $worksheet->write($row, $col++, 'Id');
+            $worksheet->write($row, $col++, 'Datum');
+            $worksheet->write($row, $col++, 'Kategorie');
+            $worksheet->write($row, $col++, 'Betrag');
+            $worksheet->write($row, $col++, 'Beschreibung');
+            $worksheet->write($row, $col++, 'Mitglied');
+            $worksheet->write($row, $col++, 'Kontostand');
+            $worksheet->write($row, $col++, 'Kassenstand');
+            $worksheet->write($row, $col, 'Gesamt');
+            $row++;
+            $col = 0;
+        }
+        $worksheet->write($row, $col++, $payment['id']);
+        $worksheet->write($row, $col++, $payment['date']);
+        $worksheet->write($row, $col++,
+            $payment['ptype'] == 'earning' ? $EARNING_TYPES[$payment['type']] : $EXPENSE_TYPES[$payment['type']]);
+        $worksheet->write($row, $col++, ($payment['ptype'] == 'earning' ? 1 : -1) * $payment['value']);
+        $worksheet->write($row, $col++, $payment['description']);
+        $worksheet->write($row, $col++, $payment['nickname']);
+        $worksheet->write($row, $col++, $payment['bank']);
+        $worksheet->write($row, $col++, $payment['cash']);
+        $worksheet->write($row, $col, $payment['total']);
+
+        $col = 0;
+        $row++;
+    }
+
+    // Let's send the file
+    $workbook->close();
+
+    $content = ob_get_contents();
+    ob_end_clean();
+    echo $content;
+    exit();
+}
diff --git a/index.php b/index.php
deleted file mode 100644 (file)
index 707f114..0000000
--- a/index.php
+++ /dev/null
@@ -1,163 +0,0 @@
-<?php
-
-header('Content-type: text/html; charset=utf-8');
-if (function_exists('date_default_timezone_set')) date_default_timezone_set('UTC');
-bcscale(2);
-
-require_once('config.php');
-require_once('include/database.php');
-require_once('include/misc.php');
-require_once('include/installation.php');
-require_once('include/html.php');
-
-require_once('include/finances.php');
-require_once('include/fees.php');
-require_once('include/cryptography.php');
-require_once('include/earnings.php');
-require_once('include/events.php');
-require_once('include/expenses.php');
-require_once('include/members.php');
-require_once('include/payments.php');
-require_once('include/directdebit.php');
-require_once('include/xlsexport.php');
-
-
-try {
-
-    db_connect();
-
-    if (!defined('IS_INSTALLED') || !IS_INSTALLED) install_database();
-
-    $action = 'list_members';
-    if (isset($_REQUEST['action'])) $action = $_REQUEST['action'];
-
-    ob_start();
-
-    switch ($action) {
-        case 'list_members'   : action_list_members();    break;
-        case 'view_member'    : action_view_member();     break;
-        case 'export_email'   : action_export_email();    break;
-        case 'create_member'  : action_create_member();   break;
-        case 'change_member'  : action_change_member();   break;
-        case 'export_ibanhin' : action_export_ibanhin();  break;
-        case 'create_event'   : action_create_event();    break;
-        case 'change_event'   : action_change_event();    break;
-        case 'delete_event'   : action_delete_event();    break;
-        case 'create_earnings': action_create_earnings(); break;
-        case 'create_earning' : action_create_earning();  break;
-        case 'change_earning' : action_change_earning();  break;
-        case 'delete_earning' : action_delete_earning();  break;
-        case 'create_expense' : action_create_expense();  break;
-        case 'change_expense' : action_change_expense();  break;
-        case 'delete_expense' : action_delete_expense();  break;
-        case 'cryptography'   : action_cryptography();    break;
-        case 'fees'           : action_fees();            break;
-        case 'directdebit'    : action_directdebit();     break;
-        case 'finances'       : action_finances();        break;
-        case 'export'         : action_export_payments(); break;
-        case 'export_members' : action_export_members();  break;
-        default: action_404();
-    }
-
-    $content = ob_get_contents();
-    ob_end_clean();
-
-?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" lang="de" xml:lang="de">
-    <head>
-        <title>Mitgliedsverwaltung - Chaos Computer Club Frankfurt am Main</title>
-        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-        <style type="text/css">
-            form  { line-height: 2em; }
-            fieldset { line-height: 2em; border: 1px solid #ccc; margin-bottom: 1em; float:left; border-width: 1px 0 0 0; width: 27em; }
-            /*fieldset { border: 1px solid #ccc; margin-bottom: 1em; float:left; border-width: 1px 0 0 0; } */
-            legend { font-size: 1.4em; }
-            label { clear: left; display: block; width: 10em; float: left; }
-            input, select { display: block; width: 20em; float: left; }
-            form small { clear: left; display: block; text-align: right; margin-right: 1.8em; line-height: 1em; margin-bottom: 1.5em; }
-            fieldset small { clear: left; display: block; text-align: right; margin-right: 1.8em; line-height: 1em; margin-bottom: 1.5em; }
-            .checkbox label { clear: none; margin-left: 0.5em; }
-            .checkbox input { clear: left; width: auto;  }
-            #header { margin: 0; padding: 1px 0; background-color: #464646; }
-            #content { font-size: 1.4em; }
-            .content { margin: 0 auto; width: 960px; }
-            .submit { clear: left; }
-            h1 { color: #fff; }
-            body { margin: 0; padding: 0; font-family:  Arial, Verdana, Tahoma; font-size: 62.5%; color: #333; }
-            html { margin: 0; padding: 0; }
-            table { border-collapse: collapse; margin-bottom: 1em; border: 1px solid #ccc; }
-            th, td { padding: 0.3em 2em 0.3em 0.3em;}
-            tr:hover { background-color: #eee; }
-            tr.earning { background-color: #efe; }
-            tr.expense { background-color: #fee; }
-            tr.earning:hover { background-color: #dfd; }
-            tr.expense:hover { background-color: #fdd; }
-            tr.total { background-color: #eee; font-weight: bold; }
-            tr.current { background-color: #eee; font-weight: bold; }
-            tr.inactive { color: #999; }
-            #earning_form { background-color: #efe; }
-            #expense_form { background-color: #fee; }
-            th { text-align: left; background-color: #eee; font-weight: normal; border-bottom: 1px solid #ccc;  }
-            h1, h2, h3, legend { font-family: Georgia, Sans-Serif, Verdana; font-weight: normal; color: #333;}
-            #header h1 { font-size: 4em; color: #fff; }
-            h2 { font-size: 2.2em; }
-            h3 { font-size: 1.8em; }
-            #pagemenu { background-color: #e0e0e0; border-top: 1px solid #e4f2fd; font-size: 1.4em; }
-            #pagemenu ul { list-style: none; padding: 0px 10px; display:block; margin-top: 6px; }
-            #pagemenu li { line-height:28px; font-weight: bold; display: inline; float: left; margin-left: 5px; }
-            #pagemenu li a { display: block; color: #888; background-color: #eee; padding: 0px 20px; text-decoration: none; }
-            #pagemenu li a:hover { color: #000; background: #fff; }
-            #footer { background-color: #eee; border-top: 1px solid #ddd; height: 50px; margin-top: 3em; }
-            .clearfix:after { content: " "; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }
-            .clearfix { display: inline-block; }
-            html[xmlns] .clearfix { display: block; }
-            * html .clearfix { height: 1%; }
-            .log_messages { color: #cc0000; }
-            p.error { border: 1px solid #900;  padding: 1em; color: #cc0000; background-color: #fff9f9;}
-
-            #content a { text-decoration: none; padding: 0 1px; color: #21759B; border-bottom: 1px solid #ccc; }
-            #content a:hover { color: #D54E21; background: #F5D1C5; border-bottom: 1px solid #D54E21; }
-            .modal_window { position:absolute; display:none; background-color: #fff; padding: 1em; }
-            #mask { position:absolute; top:0px; left:0px; height:100%; width:100%; display:none; background-color: black; }
-
-            .pagination { text-align: center; margin: 10px 0; font-weight: bold; }
-            .pagination .prev { float: left; }
-            .pagination .next { float: right; }
-
-        </style>
-        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
-        <script type="text/javascript" src="js/crypto-js/crypto/crypto-min.js"></script>
-        <script type="text/javascript" src="js/crypto-js/sha1/sha1-min.js"></script>
-        <script type="text/javascript" src="js/crypto-js/hmac/hmac-min.js"></script>
-        <script type="text/javascript" src="js/crypto-js/pbkdf2/pbkdf2-min.js"></script>
-        <script type="text/javascript" src="js/crypto-js/ofb/ofb-min.js"></script>
-        <script type="text/javascript" src="js/crypto-js/aes/aes_modified.js"></script>
-        <script type="text/javascript" src="js/date.js"></script>
-        <script type="text/javascript" src="js/utils.js"></script>
-        <script type="text/javascript" src="js/dtaus.js"></script>
-        <script type="text/javascript" src="js/sepa-CORE.js"></script>
-    </head>
-    <body>
-    <div id="header"><div class="content"><h1>Mitgliedsverwaltung</h1></div></div>
-    <div id="pagemenu">
-        <ul class="content clearfix">
-            <li><a href="<?=link_to()?>">Mitglieder</a></li>
-            <li><a href="<?=link_to('finances')?>">Finanzen</a></li>
-            <li><a href="<?=link_to('fees')?>">Mitgliedsbeitr&auml;ge</a></li>
-            <li><a href="<?=link_to('directdebit')?>">Bankeinzug</a></li>
-            <li><a href="<?=link_to('cryptography')?>">Kryptographie</a></li>
-        </ul>
-    </div>
-    <div id="content" class="content"><?=$content?></div>
-    <div id="footer"></div>
-    </body>
-</html>
-
-<?php
-
-}
-catch (Exception $e) {
-    echo 'Caught exception: ',  $e->getMessage(), "\n";
-}
diff --git a/install.sql b/install.sql
new file mode 100644 (file)
index 0000000..10ed465
--- /dev/null
@@ -0,0 +1,98 @@
+CREATE TABLE IF NOT EXISTS `members` (
+  `id`               INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
+  `number`           INT(10) UNSIGNED NOT NULL,
+  `firstname`        VARCHAR(255)     NOT NULL,
+  `lastname`         VARCHAR(255)     NOT NULL,
+  `nickname`         VARCHAR(255)     NOT NULL,
+  `accountholder`    BLOB             NOT NULL,
+  `accountnumber`    BLOB             NOT NULL,
+  `bankcode`         BLOB             NOT NULL,
+  `bankname`         BLOB             NOT NULL,
+  `directdebit`      TINYINT(1)       NOT NULL,
+  `ddmandatesigdate` DATETIME         NOT NULL,
+  `street`           VARCHAR(255)     NOT NULL,
+  `housenumber`      VARCHAR(255)     NOT NULL,
+  `postcode`         VARCHAR(255)     NOT NULL,
+  `city`             VARCHAR(255)     NOT NULL,
+  `country`          VARCHAR(255)     NOT NULL,
+  `email`            VARCHAR(255)     NOT NULL,
+  `phone`            VARCHAR(255)     NOT NULL,
+  `fax`              VARCHAR(255)     NOT NULL,
+  `mobile`           VARCHAR(255)     NOT NULL,
+  `jabber`           VARCHAR(255)     NOT NULL,
+  `icq`              VARCHAR(255)     NOT NULL,
+  `msn`              VARCHAR(255)     NOT NULL,
+  `aim`              VARCHAR(255)     NOT NULL,
+  `skype`            VARCHAR(255)     NOT NULL,
+  `url`              VARCHAR(255)     NOT NULL,
+  `twitter`          VARCHAR(255)     NOT NULL,
+  `created_at`       DATETIME         NOT NULL,
+  `modified_at`      DATETIME         NOT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `number` (`number`)
+)
+  ENGINE = InnoDB
+  DEFAULT CHARSET = utf8;
+
+CREATE TABLE IF NOT EXISTS `events` (
+  `id`               INT(10) UNSIGNED                                      NOT NULL AUTO_INCREMENT,
+  `event_date`       DATE                                                  NOT NULL,
+  `event_type`       ENUM ('joined', 'changed', 'leaved')                  NOT NULL,
+  `member_id`        INT(10) UNSIGNED                                      NOT NULL,
+  `member_type`      ENUM ('regular', 'patron', 'honorary')                NULL,
+  `fee`              DECIMAL(10, 2)                                        NULL,
+  `payment_interval` ENUM ('monthly', 'quarterly', 'halfyearly', 'yearly') NULL,
+  `created_at`       DATETIME                                              NOT NULL,
+  `modified_at`      DATETIME                                              NOT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `member_id_event_date` (`member_id`, `event_date`)
+)
+  ENGINE = InnoDB
+  DEFAULT CHARSET = utf8;
+
+CREATE TABLE IF NOT EXISTS `cryptography` (
+  `description` VARCHAR(255) NOT NULL,
+  `masterkey`   BLOB         NOT NULL,
+  `salt`        BLOB         NOT NULL,
+  `control`     BLOB         NOT NULL,
+  `created_at`  DATETIME     NOT NULL,
+  `modified_at` DATETIME     NOT NULL
+)
+  ENGINE = InnoDB
+  DEFAULT CHARSET = utf8;
+
+CREATE TABLE IF NOT EXISTS `earnings` (
+  `id`          INT(10) UNSIGNED                                                                        NOT NULL AUTO_INCREMENT,
+  `date`        DATE                                                                                    NOT NULL,
+  `type`        ENUM ('donation', 'fee', 'old_fee', 'interest', 'account_transfer', 'room', 'catering') NULL,
+  `status`      ENUM ('open', 'paid')                                                                   NOT NULL,
+  `account`     ENUM ('bank', 'cash')                                                                   NOT NULL,
+  `value`       DECIMAL(10, 2)                                                                          NULL,
+  `member_id`   INT(10) UNSIGNED                                                                        NOT NULL,
+  `description` TEXT                                                                                    NOT NULL,
+  `created_at`  DATETIME                                                                                NOT NULL,
+  `modified_at` DATETIME                                                                                NOT NULL,
+  PRIMARY KEY (`id`),
+  INDEX `idx_member_id` (`member_id`),
+  INDEX `idx_date` (`date`)
+)
+  ENGINE = InnoDB
+  DEFAULT CHARSET = utf8;
+
+CREATE TABLE IF NOT EXISTS `expenses` (
+  `id`          INT(10) UNSIGNED                                                                           NOT NULL AUTO_INCREMENT,
+  `date`        DATE                                                                                       NOT NULL,
+  `type`        ENUM ('invoice', 'gains_tax', 'bankcharges', 'account_transfer', 'member_fee', 'catering') NULL,
+  `status`      ENUM ('open', 'paid')                                                                      NOT NULL,
+  `account`     ENUM ('bank', 'cash')                                                                      NOT NULL,
+  `value`       DECIMAL(10, 2)                                                                             NULL,
+  `member_id`   INT(10) UNSIGNED                                                                           NOT NULL,
+  `description` TEXT                                                                                       NOT NULL,
+  `created_at`  DATETIME                                                                                   NOT NULL,
+  `modified_at` DATETIME                                                                                   NOT NULL,
+  PRIMARY KEY (`id`),
+  INDEX `idx_member_id` (`member_id`),
+  INDEX `idx_date` (`date`)
+)
+  ENGINE = InnoDB
+  DEFAULT CHARSET = utf8;
diff --git a/js/crypto-js/VERSION b/js/crypto-js/VERSION
deleted file mode 100644 (file)
index 1449f33..0000000
+++ /dev/null
@@ -1 +0,0 @@
-2.0.0 modified
diff --git a/js/crypto-js/aes/aes-min.js b/js/crypto-js/aes/aes-min.js
deleted file mode 100755 (executable)
index 4e2c043..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-/*
- * Crypto-JS v2.0.0
- * http://code.google.com/p/crypto-js/
- * Copyright (c) 2009, Jeff Mott. All rights reserved.
- * http://code.google.com/p/crypto-js/wiki/License
- */
-(function(){var l=Crypto,a=l.util,u=l.charenc,s=u.UTF8,j=u.Binary;var v=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22];for(var n=[],r=0;r<256;r++){n[v[r]]=r}var q=[],p=[],m=[],h=[],g=[],e=[];function f(y,x){for(var w=0,z=0;z<8;z++){if(x&1){w^=y}var A=y&128;y=(y<<1)&255;if(A){y^=27}x>>>=1}return w}for(var r=0;r<256;r++){q[r]=f(r,2);p[r]=f(r,3);m[r]=f(r,9);h[r]=f(r,11);g[r]=f(r,13);e[r]=f(r,14)}var k=[0,1,2,4,8,16,32,64,128,27,54];var c=[[],[],[],[]],d,b,t;var o=l.AES={encrypt:function(A,z,y){var i=s.stringToBytes(A),x=a.randomBytes(o._blocksize*4),w=z.constructor==String?l.PBKDF2(z,x,32,{asBytes:true}):z;mode=y&&y.mode||l.mode.OFB;o._init(w);mode.encrypt(o,i,x);return a.bytesToBase64(x.concat(i))},decrypt:function(z,y,x){var A=a.base64ToBytes(z),w=A.splice(0,o._blocksize*4),i=y.constructor==String?l.PBKDF2(y,w,32,{asBytes:true}):y;mode=x&&x.mode||l.mode.OFB;o._init(i);mode.decrypt(o,A,w);return s.bytesToString(A)},_blocksize:4,_encryptblock:function(w,x){for(var D=0;D<o._blocksize;D++){for(var i=0;i<4;i++){c[D][i]=w[x+i*4+D]}}for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]^=t[i][D]}}for(var C=1;C<b;C++){for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]=v[c[D][i]]}}c[1].push(c[1].shift());c[2].push(c[2].shift());c[2].push(c[2].shift());c[3].unshift(c[3].pop());for(var i=0;i<4;i++){var B=c[0][i],A=c[1][i],z=c[2][i],y=c[3][i];c[0][i]=q[B]^p[A]^z^y;c[1][i]=B^q[A]^p[z]^y;c[2][i]=B^A^q[z]^p[y];c[3][i]=p[B]^A^z^q[y]}for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]^=t[C*4+i][D]}}}for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]=v[c[D][i]]}}c[1].push(c[1].shift());c[2].push(c[2].shift());c[2].push(c[2].shift());c[3].unshift(c[3].pop());for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]^=t[b*4+i][D]}}for(var D=0;D<o._blocksize;D++){for(var i=0;i<4;i++){w[x+i*4+D]=c[D][i]}}},_decryptblock:function(x,w){for(var D=0;D<o._blocksize;D++){for(var i=0;i<4;i++){c[D][i]=x[w+i*4+D]}}for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]^=t[b*4+i][D]}}for(var C=1;C<b;C++){c[1].unshift(c[1].pop());c[2].push(c[2].shift());c[2].push(c[2].shift());c[3].push(c[3].shift());for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]=n[c[D][i]]}}for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]^=t[(b-C)*4+i][D]}}for(var i=0;i<4;i++){var B=c[0][i],A=c[1][i],z=c[2][i],y=c[3][i];c[0][i]=e[B]^h[A]^g[z]^m[y];c[1][i]=m[B]^e[A]^h[z]^g[y];c[2][i]=g[B]^m[A]^e[z]^h[y];c[3][i]=h[B]^g[A]^m[z]^e[y]}}c[1].unshift(c[1].pop());c[2].push(c[2].shift());c[2].push(c[2].shift());c[3].push(c[3].shift());for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]=n[c[D][i]]}}for(var D=0;D<4;D++){for(var i=0;i<4;i++){c[D][i]^=t[i][D]}}for(var D=0;D<o._blocksize;D++){for(var i=0;i<4;i++){x[w+i*4+D]=c[D][i]}}},_init:function(i){d=i.length/4;b=d+6;o._keyexpansion(i)},_keyexpansion:function(w){t=[];for(var x=0;x<d;x++){t[x]=[w[x*4],w[x*4+1],w[x*4+2],w[x*4+3]]}for(var x=d;x<o._blocksize*(b+1);x++){var i=[t[x-1][0],t[x-1][1],t[x-1][2],t[x-1][3]];if(x%d==0){i.push(i.shift());i[0]=v[i[0]];i[1]=v[i[1]];i[2]=v[i[2]];i[3]=v[i[3]];i[0]^=k[x/d]}else{if(d>6&&x%d==4){i[0]=v[i[0]];i[1]=v[i[1]];i[2]=v[i[2]];i[3]=v[i[3]]}}t[x]=[t[x-d][0]^i[0],t[x-d][1]^i[1],t[x-d][2]^i[2],t[x-d][3]^i[3]]}}}})();
\ No newline at end of file
diff --git a/js/crypto-js/aes/aes.js b/js/crypto-js/aes/aes.js
deleted file mode 100755 (executable)
index 214e634..0000000
+++ /dev/null
@@ -1,385 +0,0 @@
-/*!\r
- * Crypto-JS v2.0.0\r
- * http://code.google.com/p/crypto-js/\r
- * Copyright (c) 2009, Jeff Mott. All rights reserved.\r
- * http://code.google.com/p/crypto-js/wiki/License\r
- */\r
-(function(){\r
-\r
-// Shortcuts\r
-var C = Crypto,\r
-    util = C.util,\r
-    charenc = C.charenc,\r
-    UTF8 = charenc.UTF8,\r
-    Binary = charenc.Binary;\r
-\r
-// Precomputed SBOX\r
-var SBOX = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,\r
-             0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,\r
-             0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,\r
-             0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,\r
-             0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,\r
-             0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,\r
-             0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,\r
-             0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,\r
-             0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,\r
-             0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,\r
-             0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,\r
-             0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,\r
-             0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,\r
-             0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,\r
-             0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,\r
-             0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,\r
-             0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,\r
-             0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,\r
-             0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,\r
-             0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,\r
-             0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,\r
-             0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,\r
-             0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,\r
-             0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,\r
-             0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,\r
-             0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,\r
-             0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,\r
-             0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,\r
-             0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,\r
-             0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,\r
-             0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,\r
-             0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 ];\r
-\r
-// Compute inverse SBOX lookup table\r
-for (var INVSBOX = [], i = 0; i < 256; i++) INVSBOX[SBOX[i]] = i;\r
-\r
-// Compute mulitplication in GF(2^8) lookup tables\r
-var MULT2 = [],\r
-    MULT3 = [],\r
-    MULT9 = [],\r
-    MULTB = [],\r
-    MULTD = [],\r
-    MULTE = [];\r
-\r
-function xtime(a, b) {\r
-       for (var result = 0, i = 0; i < 8; i++) {\r
-               if (b & 1) result ^= a;\r
-               var hiBitSet = a & 0x80;\r
-               a = (a << 1) & 0xFF;\r
-               if (hiBitSet) a ^= 0x1b;\r
-               b >>>= 1;\r
-       }\r
-       return result;\r
-}\r
-\r
-for (var i = 0; i < 256; i++) {\r
-       MULT2[i] = xtime(i,2);\r
-       MULT3[i] = xtime(i,3);\r
-       MULT9[i] = xtime(i,9);\r
-       MULTB[i] = xtime(i,0xB);\r
-       MULTD[i] = xtime(i,0xD);\r
-       MULTE[i] = xtime(i,0xE);\r
-}\r
-\r
-// Precomputed RCon lookup\r
-var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\r
-\r
-// Inner state\r
-var state = [[], [], [], []],\r
-    keylength,\r
-    nrounds,\r
-    keyschedule;\r
-\r
-var AES = C.AES = {\r
-\r
-       /**\r
-        * Public API\r
-        */\r
-\r
-       encrypt: function (message, password, options) {\r
-\r
-               var\r
-\r
-                   // Convert to bytes\r
-                   m = UTF8.stringToBytes(message),\r
-\r
-                   // Generate random IV\r
-                   iv = util.randomBytes(AES._blocksize * 4),\r
-\r
-                   // Generate key\r
-                   k = password.constructor == String ?\r
-                       // Derive key from passphrase\r
-                       C.PBKDF2(password, iv, 32, { asBytes: true }) :\r
-                       // else, assume byte array representing cryptographic key\r
-                       password;\r
-\r
-               // Determine mode\r
-               mode = options && options.mode || C.mode.OFB;\r
-\r
-               // Encrypt\r
-               AES._init(k);\r
-               mode.encrypt(AES, m, iv);\r
-\r
-               // Return ciphertext\r
-               return util.bytesToBase64(iv.concat(m));\r
-\r
-       },\r
-\r
-       decrypt: function (ciphertext, password, options) {\r
-\r
-               var\r
-\r
-                   // Convert to bytes\r
-                   c = util.base64ToBytes(ciphertext),\r
-\r
-                   // Separate IV and message\r
-                   iv = c.splice(0, AES._blocksize * 4),\r
-\r
-                   // Generate key\r
-                   k = password.constructor == String ?\r
-                       // Derive key from passphrase\r
-                       C.PBKDF2(password, iv, 32, { asBytes: true }) :\r
-                       // else, assume byte array representing cryptographic key\r
-                       password;\r
-\r
-               // Determine mode\r
-               mode = options && options.mode || C.mode.OFB;\r
-\r
-               // Decrypt\r
-               AES._init(k);\r
-               mode.decrypt(AES, c, iv);\r
-\r
-               // Return plaintext\r
-               return UTF8.bytesToString(c);\r
-\r
-       },\r
-\r
-\r
-       /**\r
-        * Package private methods and properties\r
-        */\r
-\r
-       _blocksize: 4,\r
-\r
-       _encryptblock: function (m, offset) {\r
-\r
-               // Set input\r
-               for (var row = 0; row < AES._blocksize; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] = m[offset + col * 4 + row];\r
-               }\r
-\r
-               // Add round key\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] ^= keyschedule[col][row];\r
-               }\r
-\r
-               for (var round = 1; round < nrounds; round++) {\r
-\r
-                       // Sub bytes\r
-                       for (var row = 0; row < 4; row++) {\r
-                               for (var col = 0; col < 4; col++)\r
-                                       state[row][col] = SBOX[state[row][col]];\r
-                       }\r
-\r
-                       // Shift rows\r
-                       state[1].push(state[1].shift());\r
-                       state[2].push(state[2].shift());\r
-                       state[2].push(state[2].shift());\r
-                       state[3].unshift(state[3].pop());\r
-\r
-                       // Mix columns\r
-                       for (var col = 0; col < 4; col++) {\r
-\r
-                               var s0 = state[0][col],\r
-                                   s1 = state[1][col],\r
-                                   s2 = state[2][col],\r
-                                   s3 = state[3][col];\r
-\r
-                               state[0][col] = MULT2[s0] ^ MULT3[s1] ^ s2 ^ s3;\r
-                               state[1][col] = s0 ^ MULT2[s1] ^ MULT3[s2] ^ s3;\r
-                               state[2][col] = s0 ^ s1 ^ MULT2[s2] ^ MULT3[s3];\r
-                               state[3][col] = MULT3[s0] ^ s1 ^ s2 ^ MULT2[s3];\r
-\r
-                       }\r
-\r
-                       // Add round key\r
-                       for (var row = 0; row < 4; row++) {\r
-                               for (var col = 0; col < 4; col++)\r
-                                       state[row][col] ^= keyschedule[round * 4 + col][row];\r
-                       }\r
-\r
-               }\r
-\r
-               // Sub bytes\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] = SBOX[state[row][col]];\r
-               }\r
-\r
-               // Shift rows\r
-               state[1].push(state[1].shift());\r
-               state[2].push(state[2].shift());\r
-               state[2].push(state[2].shift());\r
-               state[3].unshift(state[3].pop());\r
-\r
-               // Add round key\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] ^= keyschedule[nrounds * 4 + col][row];\r
-               }\r
-\r
-               // Set output\r
-               for (var row = 0; row < AES._blocksize; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               m[offset + col * 4 + row] = state[row][col];\r
-               }\r
-\r
-       },\r
-\r
-       _decryptblock: function (c, offset) {\r
-\r
-               // Set input\r
-               for (var row = 0; row < AES._blocksize; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] = c[offset + col * 4 + row];\r
-               }\r
-\r
-               // Add round key\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] ^= keyschedule[nrounds * 4 + col][row];\r
-               }\r
-\r
-               for (var round = 1; round < nrounds; round++) {\r
-\r
-                       // Inv shift rows\r
-                       state[1].unshift(state[1].pop());\r
-                       state[2].push(state[2].shift());\r
-                       state[2].push(state[2].shift());\r
-                       state[3].push(state[3].shift());\r
-\r
-                       // Inv sub bytes\r
-                       for (var row = 0; row < 4; row++) {\r
-                               for (var col = 0; col < 4; col++)\r
-                                       state[row][col] = INVSBOX[state[row][col]];\r
-                       }\r
-\r
-                       // Add round key\r
-                       for (var row = 0; row < 4; row++) {\r
-                               for (var col = 0; col < 4; col++)\r
-                                       state[row][col] ^= keyschedule[(nrounds - round) * 4 + col][row];\r
-                       }\r
-\r
-                       // Inv mix columns\r
-                       for (var col = 0; col < 4; col++) {\r
-\r
-                               var s0 = state[0][col],\r
-                                   s1 = state[1][col],\r
-                                   s2 = state[2][col],\r
-                                   s3 = state[3][col];\r
-\r
-                               state[0][col] = MULTE[s0] ^ MULTB[s1] ^ MULTD[s2] ^ MULT9[s3];\r
-                               state[1][col] = MULT9[s0] ^ MULTE[s1] ^ MULTB[s2] ^ MULTD[s3];\r
-                               state[2][col] = MULTD[s0] ^ MULT9[s1] ^ MULTE[s2] ^ MULTB[s3];\r
-                               state[3][col] = MULTB[s0] ^ MULTD[s1] ^ MULT9[s2] ^ MULTE[s3];\r
-\r
-                       }\r
-\r
-               }\r
-\r
-               // Inv shift rows\r
-               state[1].unshift(state[1].pop());\r
-               state[2].push(state[2].shift());\r
-               state[2].push(state[2].shift());\r
-               state[3].push(state[3].shift());\r
-\r
-               // Inv sub bytes\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] = INVSBOX[state[row][col]];\r
-               }\r
-\r
-               // Add round key\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] ^= keyschedule[col][row];\r
-               }\r
-\r
-               // Set output\r
-               for (var row = 0; row < AES._blocksize; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               c[offset + col * 4 + row] = state[row][col];\r
-               }\r
-\r
-       },\r
-\r
-\r
-       /**\r
-        * Private methods\r
-        */\r
-\r
-       _init: function (k) {\r
-               keylength = k.length / 4;\r
-               nrounds = keylength + 6;\r
-               AES._keyexpansion(k);\r
-       },\r
-\r
-       // Generate a key schedule\r
-       _keyexpansion: function (k) {\r
-\r
-               keyschedule = [];\r
-\r
-               for (var row = 0; row < keylength; row++) {\r
-                       keyschedule[row] = [\r
-                               k[row * 4],\r
-                               k[row * 4 + 1],\r
-                               k[row * 4 + 2],\r
-                               k[row * 4 + 3]\r
-                       ];\r
-               }\r
-\r
-               for (var row = keylength; row < AES._blocksize * (nrounds + 1); row++) {\r
-\r
-                       var temp = [\r
-                               keyschedule[row - 1][0],\r
-                               keyschedule[row - 1][1],\r
-                               keyschedule[row - 1][2],\r
-                               keyschedule[row - 1][3]\r
-                       ];\r
-\r
-                       if (row % keylength == 0) {\r
-\r
-                               // Rot word\r
-                               temp.push(temp.shift());\r
-\r
-                               // Sub word\r
-                               temp[0] = SBOX[temp[0]];\r
-                               temp[1] = SBOX[temp[1]];\r
-                               temp[2] = SBOX[temp[2]];\r
-                               temp[3] = SBOX[temp[3]];\r
-\r
-                               temp[0] ^= RCON[row / keylength];\r
-\r
-                       } else if (keylength > 6 && row % keylength == 4) {\r
-\r
-                               // Sub word\r
-                               temp[0] = SBOX[temp[0]];\r
-                               temp[1] = SBOX[temp[1]];\r
-                               temp[2] = SBOX[temp[2]];\r
-                               temp[3] = SBOX[temp[3]];\r
-\r
-                       }\r
-\r
-                       keyschedule[row] = [\r
-                               keyschedule[row - keylength][0] ^ temp[0],\r
-                               keyschedule[row - keylength][1] ^ temp[1],\r
-                               keyschedule[row - keylength][2] ^ temp[2],\r
-                               keyschedule[row - keylength][3] ^ temp[3]\r
-                       ];\r
-\r
-               }\r
-\r
-       }\r
-\r
-};\r
-\r
-})();\r
diff --git a/js/crypto-js/aes/aes_modified.js b/js/crypto-js/aes/aes_modified.js
deleted file mode 100755 (executable)
index 872166f..0000000
+++ /dev/null
@@ -1,385 +0,0 @@
-/*!\r
- * Crypto-JS v2.0.0\r
- * http://code.google.com/p/crypto-js/\r
- * Copyright (c) 2009, Jeff Mott. All rights reserved.\r
- * http://code.google.com/p/crypto-js/wiki/License\r
- */\r
-(function(){\r
-\r
-// Shortcuts\r
-var C = Crypto,\r
-    util = C.util,\r
-    charenc = C.charenc,\r
-    UTF8 = charenc.UTF8,\r
-    Binary = charenc.Binary;\r
-\r
-// Precomputed SBOX\r
-var SBOX = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,\r
-             0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,\r
-             0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,\r
-             0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,\r
-             0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,\r
-             0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,\r
-             0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,\r
-             0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,\r
-             0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,\r
-             0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,\r
-             0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,\r
-             0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,\r
-             0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,\r
-             0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,\r
-             0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,\r
-             0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,\r
-             0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,\r
-             0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,\r
-             0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,\r
-             0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,\r
-             0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,\r
-             0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,\r
-             0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,\r
-             0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,\r
-             0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,\r
-             0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,\r
-             0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,\r
-             0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,\r
-             0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,\r
-             0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,\r
-             0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,\r
-             0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 ];\r
-\r
-// Compute inverse SBOX lookup table\r
-for (var INVSBOX = [], i = 0; i < 256; i++) INVSBOX[SBOX[i]] = i;\r
-\r
-// Compute mulitplication in GF(2^8) lookup tables\r
-var MULT2 = [],\r
-    MULT3 = [],\r
-    MULT9 = [],\r
-    MULTB = [],\r
-    MULTD = [],\r
-    MULTE = [];\r
-\r
-function xtime(a, b) {\r
-       for (var result = 0, i = 0; i < 8; i++) {\r
-               if (b & 1) result ^= a;\r
-               var hiBitSet = a & 0x80;\r
-               a = (a << 1) & 0xFF;\r
-               if (hiBitSet) a ^= 0x1b;\r
-               b >>>= 1;\r
-       }\r
-       return result;\r
-}\r
-\r
-for (var i = 0; i < 256; i++) {\r
-       MULT2[i] = xtime(i,2);\r
-       MULT3[i] = xtime(i,3);\r
-       MULT9[i] = xtime(i,9);\r
-       MULTB[i] = xtime(i,0xB);\r
-       MULTD[i] = xtime(i,0xD);\r
-       MULTE[i] = xtime(i,0xE);\r
-}\r
-\r
-// Precomputed RCon lookup\r
-var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\r
-\r
-// Inner state\r
-var state = [[], [], [], []],\r
-    keylength,\r
-    nrounds,\r
-    keyschedule;\r
-\r
-var AES = C.AES = {\r
-\r
-       /**\r
-        * Public API\r
-        */\r
-\r
-       encrypt: function (message, password, options) {\r
-\r
-               var\r
-\r
-                   // Create copy to work on\r
-                   m = message.slice(),\r
-\r
-                   // Generate random IV\r
-                   iv = util.randomBytes(AES._blocksize * 4),\r
-\r
-                   // Generate key\r
-                   k = password.constructor == String ?\r
-                       // Derive key from passphrase\r
-                       C.PBKDF2(password, iv, 32, { asBytes: true }) :\r
-                       // else, assume byte array representing cryptographic key\r
-                       password;\r
-\r
-               // Determine mode\r
-               mode = options && options.mode || C.mode.OFB;\r
-\r
-               // Encrypt\r
-               AES._init(k);\r
-               mode.encrypt(AES, m, iv);\r
-\r
-               // Return ciphertext\r
-               return util.bytesToBase64(iv.concat(m));\r
-\r
-       },\r
-\r
-       decrypt: function (ciphertext, password, options) {\r
-\r
-               var\r
-\r
-                   // Convert to bytes\r
-                   c = util.base64ToBytes(ciphertext),\r
-\r
-                   // Separate IV and message\r
-                   iv = c.splice(0, AES._blocksize * 4),\r
-\r
-                   // Generate key\r
-                   k = password.constructor == String ?\r
-                       // Derive key from passphrase\r
-                       C.PBKDF2(password, iv, 32, { asBytes: true }) :\r
-                       // else, assume byte array representing cryptographic key\r
-                       password;\r
-\r
-               // Determine mode\r
-               mode = options && options.mode || C.mode.OFB;\r
-\r
-               // Decrypt\r
-               AES._init(k);\r
-               mode.decrypt(AES, c, iv);\r
-\r
-               // Return bytes\r
-               return c;\r
-\r
-       },\r
-\r
-\r
-       /**\r
-        * Package private methods and properties\r
-        */\r
-\r
-       _blocksize: 4,\r
-\r
-       _encryptblock: function (m, offset) {\r
-\r
-               // Set input\r
-               for (var row = 0; row < AES._blocksize; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] = m[offset + col * 4 + row];\r
-               }\r
-\r
-               // Add round key\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] ^= keyschedule[col][row];\r
-               }\r
-\r
-               for (var round = 1; round < nrounds; round++) {\r
-\r
-                       // Sub bytes\r
-                       for (var row = 0; row < 4; row++) {\r
-                               for (var col = 0; col < 4; col++)\r
-                                       state[row][col] = SBOX[state[row][col]];\r
-                       }\r
-\r
-                       // Shift rows\r
-                       state[1].push(state[1].shift());\r
-                       state[2].push(state[2].shift());\r
-                       state[2].push(state[2].shift());\r
-                       state[3].unshift(state[3].pop());\r
-\r
-                       // Mix columns\r
-                       for (var col = 0; col < 4; col++) {\r
-\r
-                               var s0 = state[0][col],\r
-                                   s1 = state[1][col],\r
-                                   s2 = state[2][col],\r
-                                   s3 = state[3][col];\r
-\r
-                               state[0][col] = MULT2[s0] ^ MULT3[s1] ^ s2 ^ s3;\r
-                               state[1][col] = s0 ^ MULT2[s1] ^ MULT3[s2] ^ s3;\r
-                               state[2][col] = s0 ^ s1 ^ MULT2[s2] ^ MULT3[s3];\r
-                               state[3][col] = MULT3[s0] ^ s1 ^ s2 ^ MULT2[s3];\r
-\r
-                       }\r
-\r
-                       // Add round key\r
-                       for (var row = 0; row < 4; row++) {\r
-                               for (var col = 0; col < 4; col++)\r
-                                       state[row][col] ^= keyschedule[round * 4 + col][row];\r
-                       }\r
-\r
-               }\r
-\r
-               // Sub bytes\r
-               for (var row = 0; row < 4; row++) {\r
-                       for (var col = 0; col < 4; col++)\r
-                               state[row][col] = SBOX[state[row][col]];\r
-               }\r
-\r
-               // Shift rows\r
-               state[1].push(state[1].shift());\r
-               state[2].push(state[2].shift());\r
-               state[2].push(state[2].shift());\r
-               state[3].unshift(state[3].pop());\r
-\r
-               // Add round key\r
-               for (var row = 0; row < 4; row++) {\r
<