Formatting
authorBot <bot@myigel.name>
Fri, 1 Dec 2017 00:51:13 +0000 (01:51 +0100)
committerIgor Scheller <igor.scheller@igorshp.de>
Fri, 1 Dec 2017 00:51:13 +0000 (01:51 +0100)
20 files changed:
config.php.sample [deleted file]
config.sample.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/installation.php
include/members.php
include/misc.php
include/payments.php
include/xlsexport.php
index.php
js/dtaus.js
js/sepa-CORE.js
js/utils.js

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..63cce1b
--- /dev/null
@@ -0,0 +1,24 @@
+<?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);
index 58a6b10..311df5b 100644 (file)
@@ -55,49 +55,55 @@ PROBLEM: AES uses a random initialization vector and creates different output fo
 
 $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
+      `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() {
+function db_get_crypto_keys()
+{
     $sql = 'SELECT * FROM %1$s';
     return db_select_multi(sprintf($sql, DB_TABLE_CRYPTO));
 }
 
-function db_add_crypto_key($key) {
-    $key['created_at']    = db_unixtime2datetime(time());
-    $key['modified_at']   = db_unixtime2datetime(time());
+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 validate_crypto_key($userdata, &$dbdata, &$validation) {/*{{{*/
+function validate_crypto_key($userdata, &$dbdata, &$validation)
+{/*{{{*/
     $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':
@@ -113,7 +119,7 @@ function action_cryptography() {/*{{{*/
                     }
                     echo db_error();
                 }
-                
+
                 break;
             default:
                 break;
@@ -122,285 +128,310 @@ 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><?= 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 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() {/*{{{*/
+        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));
+            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);
+        }
 
-        // 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
+        /*}}}*/
+    </script>
 
-        // 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
+<?php else : ?>
 
-        // 1.7 Encrypt masterkey using AES with userkey
-        var crypted_masterkey = Crypto.AES.encrypt(masterkey, userkey);
+    <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);
+        }
 
-        // 1.8 Create sha1 hash of masterkey+userkey+salt
-        var control     = Crypto.SHA1(Crypto.charenc.Binary.bytesToString(masterkey) + Crypto.charenc.Binary.bytesToString(userkey) + salt1);
+        /*}}}*/
+    </script>
+<?php endif ?>
 
-    /* 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);
+    <?php
 }/*}}}*/
-</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;
+function js_get_master_key($keys = null)
+{/*{{{*/
+    if (!isset($keys)) {
+        $keys = db_get_crypto_keys();
     }
-
-    // 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.');
+    if (empty($keys)) {
         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 ?>
+    ?>
+    <script type="text/javascript">
 
-<?php
-}/*}}}*/
+        var keys = new Array(
+            <?=join(",\n", array_map('json_encode', $keys)) ?>
+        );
 
-function js_get_master_key($keys = NULL) {/*{{{*/
-    if (!isset($keys)) $keys = db_get_crypto_keys();
-    if (empty($keys)) return;
-?>
-<script type="text/javascript">
+        function get_master_key(password, callback) {/*{{{*/
 
-var keys = new Array(
-    <?=join(",\n", array_map('json_encode', $keys)) ?>
-);
+            modal_window_show($("#please_wait"));
 
-function get_master_key(password, callback) {/*{{{*/
+            // 4.2 iterate through valid keys
+            setTimeout(function () {
+                check_master_key(0, password, callback);
+            }, 1000);
 
-    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) {/*{{{*/
 
-function check_master_key(idx, password, callback) {/*{{{*/
+            if (idx >= keys.length) {
+                modal_window_hide();
+                alert("Falsches Passwort");
+                return;
+            }
 
-    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'];
 
-    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});
 
-    // 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);
 
-    // 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;
+            }
 
-    // 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);
 
-    // check next key
-    setTimeout( function() { check_master_key(idx + 1, password, callback); }, 10);
+        }
 
-}/*}}}*/
+        /*}}}*/
 
-</script>
-<?php
+    </script>
+    <?php
 }/*}}}*/
-
-
index 079c356..3c5c1ab 100644 (file)
@@ -1,38 +1,48 @@
 <?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');
+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 . '"');
+    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);
     }
 }
 /* }}} */
 
-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>');
+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) {
+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) {
+function db_escape_array($arr)
+{
     global $dbh;
     foreach ($arr as $key => $val) {
         $arr[$key] = mysql_real_escape_string($val, $dbh);
@@ -41,132 +51,172 @@ function db_escape_array($arr) {
 }
 
 // select one row
-function db_select_single($query) {
+function db_select_single($query)
+{
     global $dbh;
     $res = mysql_query($query, $dbh);
     if (!$res) {
         echo $query, ' ', db_error();
-        return NULL;
+        return null;
+    }
+    if (mysql_num_rows($res) != 1) {
+        return null;
     }
-    if (mysql_num_rows($res) != 1) return NULL;
     $row = mysql_fetch_assoc($res);
     mysql_free_result($res);
     return $row;
 }
 
 // select multiple rows
-function db_select_multi($query) {
+function db_select_multi($query)
+{
     global $dbh;
     $res = mysql_query($query, $dbh);
     if (!$res) {
         echo $query, ' ', db_error();
-        return NULL;
+        return null;
+    }
+    if (mysql_num_rows($res) == 0) {
+        return array();
     }
-    if (mysql_num_rows($res) == 0) return array();
     $ret = array();
-    while ($row = mysql_fetch_assoc($res)) $ret[] = $row;
+    while ($row = mysql_fetch_assoc($res)) {
+        $ret[] = $row;
+    }
     mysql_free_result($res);
     return $ret;
 }
 
 // insert one row
-function db_insert_single($table, $fields, $ignore = false) {
+function db_insert_single($table, $fields, $ignore = false)
+{
     global $dbh;
     $query = 'INSERT INTO ' . $table;
-    if ($ignore) $query = 'INSERT IGNORE 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;
+    if (!$res) {
+        echo $query, ' ', db_error();
+    }
+    return $res;
 }
 
 // get automatically generated id of last record
-function db_insert_id() {
+function db_insert_id()
+{
     global $dbh;
     return mysql_insert_id($dbh);
 }
 
 // begin transaction
-function db_begin() {
+function db_begin()
+{
     global $dbh;
     return mysql_query('BEGIN');
 }
 
 // commit transaction
-function db_commit() {
+function db_commit()
+{
     global $dbh;
     return mysql_query('COMMIT');
 }
 
 // rollback transaction
-function db_rollback() {
+function db_rollback()
+{
     global $dbh;
     return mysql_query('ROLLBACK');
 }
 
 // update multiple rows
-function db_update_multi($table, $fields, $where = '', $special = '') {
+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;
+        if (!$first) {
+            $query .= ', ';
+        } else {
+            $first = false;
+        }
         $query .= '`' . $name . '`=\'' . db_escape($value) . '\'';
     }
     $query .= $special;
-    if (!empty($where)) $query.= ' WHERE ' . $where;
+    if (!empty($where)) {
+        $query .= ' WHERE ' . $where;
+    }
     $res = mysql_query($query, $dbh);
-    if (!$res)  echo $query, ' ', db_error();
-       return $res;
+    if (!$res) {
+        echo $query, ' ', db_error();
+    }
+    return $res;
 }
 
 // update one rows
-function db_update_single($table, $fields, $where = '', $special = '') {
+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;
+        if (!$first) {
+            $query .= ', ';
+        } else {
+            $first = false;
+        }
         $query .= '`' . $name . '`=\'' . db_escape($value) . '\'';
     }
     $query .= $special;
-    if (!empty($where)) $query.= ' WHERE ' . $where;
-       $query .= ' LIMIT 1';
+    if (!empty($where)) {
+        $query .= ' WHERE ' . $where;
+    }
+    $query .= ' LIMIT 1';
     $res = mysql_query($query, $dbh);
-    if (!$res)  echo $query, ' ', db_error();
-       return $res;
+    if (!$res) {
+        echo $query, ' ', db_error();
+    }
+    return $res;
 }
 
 // delete one row
-function db_delete_single($table, $where) {
+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;
+    if (!$res) {
+        return null;
+    }
     return (mysql_affected_rows($dbh));
 }
 
 // get error message
-function db_error() {
+function db_error()
+{
     global $dbh;
     return mysql_error($dbh);
 }
 
-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) {
+function db_datetime2unixtime($datetime)
+{
     return strtotime($datetime);
 }
-
index ac907fe..bf07f17 100644 (file)
@@ -1,34 +1,43 @@
 <?php
 
 
-function action_directdebit() {
+function action_directdebit()
+{
 
     $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 +45,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'],
@@ -48,255 +57,277 @@ 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="<?= 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 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="<?= 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>
             <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;
+            <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;
         }
-        $('#directdebit_content').val(directdebitcontent);
-        $('#directdebit_content2').val(directdebitcontent2);
-        $('#directdebit_content').focus();
-        $('#directdebit_content').select();
-    });
 
-}/*}}}*/
+        /*}}}*/
+
+        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;
+                            }
 
-function directdebit_close() {/*{{{*/
-    modal_window_hide();
-    $("#directdebit_content").val('');
-    $("#directdebit_content2").val('');
-}/*}}}*/
+                            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);
 
-</script>
-<?
+                            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();
+            });
+
+        }
+
+        /*}}}*/
+
+        function directdebit_close() {/*{{{*/
+            modal_window_hide();
+            $("#directdebit_content").val('');
+            $("#directdebit_content2").val('');
+        }
+
+        /*}}}*/
+
+
+    </script>
+    <?
 }
 
 // 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',
@@ -517,4 +548,3 @@ function dtaus_string($string) {
 
     return $result;
 }
-
index 071fe43..7f06f28 100644 (file)
@@ -2,16 +2,16 @@
 
 $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,
+      `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,
+      `member_id` INT(10) UNSIGNED NOT NULL,
       `description` TEXT NOT NULL,
-      `created_at` datetime NOT NULL,
-      `modified_at` datetime 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`)
@@ -19,64 +19,71 @@ $SQL_CREATE_EARNINGS = sprintf('
     ', DB_TABLE_EARNINGS, DB_CHARSET);
 
 $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(DIRECTDEBIT_DATE),
+    'catering'         => 'Raum - Getraenke & Snacks'
 );
 
 
 /* DB functions {{{ */
 
-function db_get_earning_with_id($earning_id) {
+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)));
 }
 
-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));
 }
 
-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)));
 }
 
-function db_delete_earning($earning) {
+function db_delete_earning($earning)
+{
     return db_delete_single(DB_TABLE_EARNINGS, sprintf('id=\'%1$d\'', db_escape($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];
     }
 
@@ -91,10 +98,11 @@ function validate_earning($userdata, &$dbdata, &$validation) {/*{{{*/
 }/*}}}*/
 
 
-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']);
@@ -109,12 +117,17 @@ function action_create_earning() {/*{{{*/
 }/*}}}*/
 
 
-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)) {
@@ -129,12 +142,17 @@ function action_change_earning() {/*{{{*/
 }/*}}}*/
 
 
-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)) {
@@ -146,51 +164,56 @@ function action_delete_earning() {/*{{{*/
 }/*}}}*/
 
 
-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="<?= 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 ?>
         <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)?>
+            <?= 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) ?>
         </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="<?= 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 ?>
     <?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 +228,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 +236,14 @@ 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_single(DB_TABLE_MEMBERS, $member,
+            sprintf('directdebit=\'2\' AND id=\'%1$d\'', db_escape($post_data['member_id'])));
     }
 
     redirect(link_to('finances'));
 }/*}}}*/
-
index 7a56de6..44dd3ee 100644 (file)
 
 $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,
+      `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,
+      `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) {
+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());
+    $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));
 }
 
-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'; }
+    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);
 }
 
-function db_delete_event($event) {
+function db_delete_event($event)
+{
     return db_delete_single(DB_TABLE_EVENTS, sprintf('id=\'%1$d\'', db_escape($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));
-       
+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_event_with_member_and_date($member_id, $event_date) {
+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)));
 }
 
-function db_get_event_with_id($event_id) {
+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)));
 }
@@ -88,19 +104,22 @@ function db_get_event_with_id($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];
     }
 
@@ -112,47 +131,53 @@ function validate_event($userdata, &$dbdata, &$validation) {/*{{{*/
         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 +185,66 @@ 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="<?= 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>
             </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');
             }
@@ -218,18 +254,29 @@ 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 +285,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 +312,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'])) : ?><?= html_hidden_field('id', $event) ?><?php endif ?>
+        <?= 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)?>
+            <?= 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) ?>
             <small>Leer lassen wenn unver&auml;ndert.</small>
-            <?=html_list_box('Zahlungsintervall', 'payment_interval', array_merge(array(0 => 'unverändert'), $PAYMENT_INTERVALS), $event, $readonly)?>
+            <?= 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="<?= 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 ?>
     <?php
 }/*}}}*/
-
-
index f16bb21..3e5af93 100644 (file)
@@ -2,16 +2,16 @@
 
 $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,
+      `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,
+      `member_id` INT(10) UNSIGNED NOT NULL,
       `description` TEXT NOT NULL,
-      `created_at` datetime NOT NULL,
-      `modified_at` datetime 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`)
@@ -19,63 +19,70 @@ $SQL_CREATE_EXPENSES = sprintf('
     ', 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) {
+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)));
 }
 
-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));
 }
 
-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)));
 }
 
-function db_delete_expense($expense) {
+function db_delete_expense($expense)
+{
     return db_delete_single(DB_TABLE_EXPENSES, sprintf('id=\'%1$d\'', db_escape($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];
     }
 
@@ -90,10 +97,11 @@ function validate_expense($userdata, &$dbdata, &$validation) {/*{{{*/
 }/*}}}*/
 
 
-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']);
@@ -108,12 +116,17 @@ function action_create_expense() {/*{{{*/
 }/*}}}*/
 
 
-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)) {
@@ -128,12 +141,17 @@ function action_change_expense() {/*{{{*/
 }/*}}}*/
 
 
-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)) {
@@ -145,46 +163,46 @@ function action_delete_expense() {/*{{{*/
 }/*}}}*/
 
 
-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="<?= 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 ?>
         <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)?>
+            <?= 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) ?>
         </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 ?>
+    <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
 }/*}}}*/
-
-
index c168a66..b826a7b 100644 (file)
 /* 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)
+{
     if (!empty($events)) {
 
         foreach ($events as $event) {
 
             $timestamp = db_date2unixtime($event['event_date']);
-            if ($timestamp < FOUNDING_DATE) $timestamp = FOUNDING_DATE;
+            if ($timestamp < FOUNDING_DATE) {
+                $timestamp = FOUNDING_DATE;
+            }
             $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();
 
     $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;
@@ -92,7 +132,9 @@ function fees_get_list_for_member($member_id, $end_date) {
     }
 
     $ret = _fees_build_month_array(FOUNDING_DATE, $end_date);
-    if (empty($ret)) return;
+    if (empty($ret)) {
+        return;
+    }
 
     _fees_apply_event_information($ret, db_get_events_for_member($member_id));
 
@@ -100,96 +142,120 @@ 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)
+{
 
     $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;
-   
+    $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;
 
 
     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,32 +265,46 @@ 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++;
+        }
     }
-    
-    
+
+
 }
+
 /* }}} */
 
 
-function action_fees() {/*{{{*/
+function action_fees()
+{/*{{{*/
 
     if (isset($_REQUEST['member_id'])) {
         render_fees_for_member($_REQUEST['member_id']);
@@ -242,47 +322,52 @@ function action_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
+    ?>
+    <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
 }/*}}}*/
 
-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,120 +376,134 @@ 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="<?= 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
 }/*}}}*/
 
-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="<?= 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
 }/*}}}*/
 
-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 <?= 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
 }/*}}}*/
 
-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="<?= 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
 }
 
-function render_fees_for_member($member_id) {/*{{{*/
+function render_fees_for_member($member_id)
+{/*{{{*/
     global $MEMBER_TYPES, $EARNING_TYPES, $EXPENSE_TYPES;
 
-    $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);
@@ -414,14 +513,18 @@ function render_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_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.',
@@ -430,91 +533,92 @@ function render_fees_for_member($member_id) {/*{{{*/
             format_date(DIRECTDEBIT_DATE),
             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(DIRECTDEBIT_DATE), 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 <?= 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
 }/*}}}*/
-
-
index 5731292..ec1ef79 100644 (file)
@@ -1,7 +1,8 @@
 <?php
 
 
-function finance_get_total_paid_fees() {
+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
     ));
@@ -13,7 +14,8 @@ function finance_get_total_paid_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.
@@ -25,11 +27,15 @@ function finance_get_paid_fees_for_member($member_id, $old_fees = false) {
 
     $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);
+    $invoiced_fees = fees_sum_for_member($member_id, DIRECTDEBIT_DATE - 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\'',
@@ -39,7 +45,8 @@ function finance_get_paid_fees_for_member($member_id, $old_fees = false) {
     return bcsub($paid_fees, $refunded['refunded_fees']);
 }
 
-function finance_list_paid_fees_for_member($member_id) {
+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\'))
@@ -50,10 +57,11 @@ function finance_list_paid_fees_for_member($member_id) {
     ));
 }
 
-function action_finances() {/*{{{*/
-?>
+function action_finances()
+{/*{{{*/
+    ?>
     <h2>Finanzen</h2>
-<?php
+    <?php
     action_create_expense();
     action_create_earning();
     echo '<br style="clear: left;"/>';
@@ -61,4 +69,3 @@ function action_finances() {/*{{{*/
     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;
 }
-
index f57ccae..bb849b5 100644 (file)
@@ -1,18 +1,29 @@
 <?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_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() {
+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..484d18b 100644 (file)
@@ -2,35 +2,35 @@
 
 $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,
+      `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
@@ -38,45 +38,54 @@ $SQL_CREATE_MEMBERS = sprintf('
 
 $DIRECTDEBIT_STATES = array(
     '' => '- (Barzahler)',
-    1 => 'DTAUS',
-    2 => 'SEPA Ersteinzug',
-    3 => 'SEPA Folgeeinzug'
-); 
-    
+    1  => 'DTAUS',
+    2  => 'SEPA Ersteinzug',
+    3  => 'SEPA Folgeeinzug'
+);
+
 /* DB functions {{{ */
 
-function db_create_member($member) {
+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_single(DB_TABLE_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());
+    $member['modified_at'] = db_unixtime2datetime(time());
     return db_update_single(DB_TABLE_MEMBERS, $member, sprintf('id=\'%1$d\'', db_escape($id)));
 }
 
-function db_get_members() {
-    $sql = 'SELECT * FROM %1$s ORDER BY number ASC';
+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_member_with_id($member_id) {
+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_next_free_member_number() {/*{{{*/
+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;
+    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 +96,21 @@ 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';
+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 validate_member($userdata, &$dbdata, &$validation) {/*{{{*/
+function validate_member($userdata, &$dbdata, &$validation)
+{/*{{{*/
     $fields = array(
         'id'               => 'number',
         'number'           => 'number',
@@ -133,7 +146,9 @@ function validate_member($userdata, &$dbdata, &$validation) {/*{{{*/
             $dbdata[$name] = !empty($userdata[$name]);
             continue;
         }
-        if (!isset($userdata[$name])) continue;
+        if (!isset($userdata[$name])) {
+            continue;
+        }
         $dbdata[$name] = $userdata[$name];
     }
 //      ids must be equal
@@ -153,24 +168,32 @@ function validate_member($userdata, &$dbdata, &$validation) {/*{{{*/
     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 +201,222 @@ 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>
+            <?= 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>
+        </fieldset>
+    </div>
 
-<script type="text/javascript">
+    <script type="text/javascript">
 
-  var members = new Array(<?=join(",\n", array_map('json_encode', $members)) ?>);
+        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();
+        });
 
-$(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 ask_for_password() {/*{{{*/
-    modal_window_show($("#password_popup"));
-    $("#password").focus();
-    return;
-}/*}}}*/
+        /*}}}*/
 
-function cancel_ask_for_password() {/*{{{*/
-    modal_window_hide();
-    $("#btn_ibanhin").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";
+                        }
+                    }
+                }
+
+                $('#ibanhin_content').val(ibanhin_content);
+                $('#ibanhin_content').focus();
+                $('#ibanhin_content').select();
 
+            });
 
-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";
         }
-      }
-    }
 
-    $('#ibanhin_content').val(ibanhin_content);
-    $('#ibanhin_content').focus();
-    $('#ibanhin_content').select();
-    
-    });
+        /*}}}*/
 
-}/*}}}*/
+        function ibanhin_close() {/*{{{*/
+            modal_window_hide();
+            $("#ibanhin_content").val('');
+        }
 
-function ibanhin_close() {/*{{{*/
-    modal_window_hide();
-    $("#ibanhin_content").val('');
-}/*}}}*/
+        /*}}}*/
 
 
-</script>
+    </script>
 
-<?php
+    <?php
 
 }/*}}}*/
 
 
-function action_list_members() {/*{{{*/
+function action_list_members()
+{/*{{{*/
     $members = db_get_members();
-    $count   = 0;
+    $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="<?= 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>
             </tr>
         <?php endforeach ?>
-        </table>
-    <?php else : ?>
-        <p>Bisher gibt es noch keine Mitglieder.</p>
+    </table>
+<?php else : ?>
+    <p>Bisher gibt es noch keine Mitglieder.</p>
     <?php
-        endif;
-        $count = $regular + $honorary + $patron;
+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 <?= $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>
     <?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'] = '0000-00-00 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');
             }
@@ -374,21 +426,27 @@ 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'] = '0000-00-00 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)) {
@@ -401,21 +459,26 @@ function action_change_member() {/*{{{*/
 }/*}}}*/
 
 
-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 ?> <?= $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 +489,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="<?= link_to('cryptography') ?>">Kryptographie einrichten</a>.
         </p>
-<?php
+        <?php
         return;
     }
 
@@ -450,86 +514,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) : ?><?= 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)?>
+            <?= 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) ?>
         </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)?>
+            <?= 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 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)?>
+            <?= 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'] == '0000-00-00 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)?>
+            <?= 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)?>
+            <?= 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) ?>
         </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)?>
+            <?= 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) ?>
         </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="<?= 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()"/>
+            <?= 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 +610,279 @@ 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()"/>
+            <?= 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)?>
+            <?= 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 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">
+    <script type="text/javascript">
 
 
-var the_masterkey;
+        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 ?>
-});  
+        $(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 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 cancel_change_bank_details() {/*{{{*/
-    modal_window_hide();
-    $("#btn_bank_details").focus();
-    $("#password1").val('');
-    return;
-}/*}}}*/
+        function import_qrcode_ask_pass() {/*{{{*/
+            modal_window_show($("#password_popup2"));
+            $("#password2").focus();
+            return;
+        }
 
-function cancel_import_qrcode() {/*{{{*/
-    modal_window_hide();
-    $("#password2").val('');
-    return;
-}/*}}}*/
+        /*}}}*/
 
-function decrypt_bank_details() {/*{{{*/
+        function cancel_change_bank_details() {/*{{{*/
+            modal_window_hide();
+            $("#btn_bank_details").focus();
+            $("#password1").val('');
+            return;
+        }
 
-    var password = $('#password1').val();
-    $("#password1").val('');
+        /*}}}*/
 
-    // We pass a closure so that get_master_key may defer execution
-    get_master_key(password, function(masterkey) {
+        function cancel_import_qrcode() {/*{{{*/
+            modal_window_hide();
+            $("#password2").val('');
+            return;
+        }
 
-        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();
+        function decrypt_bank_details() {/*{{{*/
 
-        // 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
-    });
+            var password = $('#password1').val();
+            $("#password1").val('');
 
-}/*}}}*/
+            // We pass a closure so that get_master_key may defer execution
+            get_master_key(password, function (masterkey) {
 
-function import_qrcode() {/*{{{*/
+                modal_window_replace($("#bank_detail_popup"));
+                <?php if ($readonly) : ?>
+                $('#btn_bank_details_cancel').focus();
+                <?php else : ?>
+                $('#tmp_accountholder').focus();
+                <?php endif ?>
 
-    var password = $('#password2').val();
-    $("#password2").val('');
+                var accountholder = $('#accountholder').val();
+                var accountnumber = $('#accountnumber').val();
+                var bankcode = $('#bankcode').val();
+                var bankname = $('#bankname').val();
 
-    // We pass a closure so that get_master_key may defer execution
-    get_master_key(password, function(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
+            });
 
-        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 import_qrcode() {/*{{{*/
 
+            var password = $('#password2').val();
+            $("#password2").val('');
 
-    // 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 = '';
+            // 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 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 = '';
+        }
 
-}/*}}}*/
+        /*}}}*/
+
+        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() {/*{{{*/
 
-    modal_window_hide();
+            // 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('');
+        }
 
-    the_masterkey = '';
-}/*}}}*/
+        /*}}}*/
 
-</script>
-    <?php
-}/*}}}*/
+        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 = '';
+
+        }
+
+        /*}}}*/
+
+        function bank_details_cancel() {/*{{{*/
+
+            modal_window_hide();
+
+            $("#tmp_accountholder").val('');
+            $("#tmp_accountnumber").val('');
+            $("#tmp_bankcode").val('');
+            $("#tmp_bankname").val('');
+
+            the_masterkey = '';
+        }
+
+        /*}}}*/
+
+    </script>
+    <?php
+}/*}}}*/
index 9dbed18..9fe56f4 100644 (file)
@@ -1,6 +1,7 @@
 <?php
 
-function action_404() {/*{{{*/
+function action_404()
+{/*{{{*/
     header('HTTP/1.0 404 Not Found');
     ?>
     <h2>Seite nicht gefunden!</h2>
@@ -8,146 +9,174 @@ function action_404() {/*{{{*/
     <?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><?= 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) {
+
+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>
+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 endfor ?>
-</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) : ?>
+                <?= 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 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);
-}
-
-</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
+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);
+        }
+
+    </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
 }/*}}}*/
 
 
index f5290f5..8864aeb 100644 (file)
@@ -8,24 +8,30 @@ $ACCOUNT_TYPES = array(
 );
 
 /* DB functions {{{ */
-function db_get_payments($offset, $count, $where) {
+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;
+    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));
 }
 
-function db_get_finished_payments($offset, $count) {
+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) 
@@ -34,115 +40,133 @@ function db_get_finished_payments($offset, $count) {
                     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'];
+        $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() {
+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';
+    $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));
     return $row['count'];
 }
 
-function db_get_open_payments($offset, $count) {
+function db_get_open_payments($offset, $count)
+{
     return db_get_payments($offset, $count, ' WHERE status=\'open\'');
 }
 
 /* }}} */
 
-function render_finished_payments($count = 100) {/*{{{*/
+function render_finished_payments($count = 100)
+{/*{{{*/
     global $EXPENSE_TYPES, $EARNING_TYPES, $ACCOUNT_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="<?= $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>
         <?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="<?= $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>
         <?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..3ccfd4b 100644 (file)
 <?php
 
-function action_export_members() {
-       global $EARNING_TYPES, $EXPENSE_TYPES;
+function action_export_members()
+{
+    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('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();
+    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();
 }
 
-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();
+    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
index 707f114..424fa5f 100644 (file)
--- a/index.php
+++ b/index.php
@@ -1,7 +1,9 @@
 <?php
 
 header('Content-type: text/html; charset=utf-8');
-if (function_exists('date_default_timezone_set')) date_default_timezone_set('UTC');
+if (function_exists('date_default_timezone_set')) {
+    date_default_timezone_set('UTC');
+}
 bcscale(2);
 
 require_once('config.php');
@@ -26,105 +28,389 @@ try {
 
     db_connect();
 
-    if (!defined('IS_INSTALLED') || !IS_INSTALLED) install_database();
+    if (!defined('IS_INSTALLED') || !IS_INSTALLED) {
+        install_database();
+    }
 
     $action = 'list_members';
-    if (isset($_REQUEST['action'])) $action = $_REQUEST['action'];
+    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();
+        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">
+    ?>
+    <!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">
+    <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" />
+        <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; }
+            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; }
+            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>
@@ -140,24 +426,25 @@ try {
         <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="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>
+            <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="content" class="content"><?= $content ?></div>
     <div id="footer"></div>
     </body>
-</html>
+    </html>
 
-<?php
+    <?php
 
-}
-catch (Exception $e) {
-    echo 'Caught exception: ',  $e->getMessage(), "\n";
+} catch (Exception $e) {
+    echo 'Caught exception: ', $e->getMessage(), "\n";
 }
index e0d268f..cea8ec4 100644 (file)
-
 // ported from PEARs Payment_DTA
 var DTAUS = {
 
-       account_file_sender: null,
-       timestamp: new Date(),
-       exchanges: [],
-       errormsg: '',
-
-    sum_bank_codes:                    0,
-    sum_account_numbers:       0,
-       sum_amounts:                    0,
-
-       invalid_chars: new RegExp('[^A-Z0-9 \.,&\-\/\+\*\$%]'),
-       invalid_digits: new RegExp('[^0-9]'),
-
-       validString: function(str) {
-               if (str.match(this.invalid_chars)) return false;
-               return true;
-       },      
-
-       prepareString: function(str) {
-               str = str.toUpperCase();
-               str = str_replace('Ö', 'OE', str);
-               str = str_replace('Ä', 'AE', str);
-               str = str_replace('Ü', 'UE', str);
-               str = str_replace('ß', 'SS', str);
-               return str;
-       },
-       
-    setAccountFileSender: function(sender_name, bank_code, account_number, additional_name) {
-               // TODO additional_name wird derzeit einfach verworfen
-
-               this.account_file_sender= null;
-               this.timestamp                  = new Date();
-               this.exchanges                  = [];
-               this.errormsg                   = '';
-
-       this.sum_bank_codes             = 0;
-       this.sum_account_numbers= 0;
-               this.sum_amounts                = 0;
-
-               account_number = '' + account_number;
-        bank_code      = '' + bank_code;
-               if (!additional_name) additional_name = '';
-
-               var errors = [];
-               var res;
-
-        if (sender_name.length    <=  0)                                               errors.push('Kein Absender angegeben.');
-               if (res = sender_name.match(this.invalid_chars))                errors.push('Absender "' + sender_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-        if (bank_code.length      <=  0)                                               errors.push('Keine Absender-BLZ angegeben.');
-        if (bank_code.length       >  8)                                               errors.push('Absender-BLZ "' + bank_code + '" ist zu lang (max 8 Zeichen).');
-               if (res = bank_code.match(this.invalid_digits))                 errors.push('Absender-BLZ "' + bank_code + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-        if (account_number.length <=  0)                                               errors.push('Keine Absender-Kontonummer angegeben.');
-        if (account_number.length  > 10)                                               errors.push('Absender-Kontonummer "' + account_number + '" ist zu lang (max 8 Zeichen).');
-               if (res = account_number.match(this.invalid_digits))    errors.push('Absender-Kontonummer "' + account_number + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-               if (res = additional_name.match(this.invalid_chars))    errors.push('Absender-Zusatz "' + additional_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-               if (errors.length == 0) {
-                       this.account_file_sender = [];
-                       this.account_file_sender['name']            = sender_name.substr(0, 27);
-                       this.account_file_sender['bank_code']       = bank_code;
-                       this.account_file_sender['account_number']  = account_number;
-                       this.account_file_sender['additional_name'] = additional_name.substr(0, 27);
-                       return true;
+    account_file_sender: null,
+    timestamp: new Date(),
+    exchanges: [],
+    errormsg: '',
+
+    sum_bank_codes: 0,
+    sum_account_numbers: 0,
+    sum_amounts: 0,
+
+    invalid_chars: new RegExp('[^A-Z0-9 \.,&\-\/\+\*\$%]'),
+    invalid_digits: new RegExp('[^0-9]'),
+
+    validString: function (str) {
+        if (str.match(this.invalid_chars)) return false;
+        return true;
+    },
+
+    prepareString: function (str) {
+        str = str.toUpperCase();
+        str = str_replace('Ö', 'OE', str);
+        str = str_replace('Ä', 'AE', str);
+        str = str_replace('Ü', 'UE', str);
+        str = str_replace('ß', 'SS', str);
+        return str;
+    },
+
+    setAccountFileSender: function (sender_name, bank_code, account_number, additional_name) {
+        // TODO additional_name wird derzeit einfach verworfen
+
+        this.account_file_sender = null;
+        this.timestamp = new Date();
+        this.exchanges = [];
+        this.errormsg = '';
+
+        this.sum_bank_codes = 0;
+        this.sum_account_numbers = 0;
+        this.sum_amounts = 0;
+
+        account_number = '' + account_number;
+        bank_code = '' + bank_code;
+        if (!additional_name) additional_name = '';
+
+        var errors = [];
+        var res;
+
+        if (sender_name.length <= 0) errors.push('Kein Absender angegeben.');
+        if (res = sender_name.match(this.invalid_chars)) errors.push('Absender "' + sender_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (bank_code.length <= 0) errors.push('Keine Absender-BLZ angegeben.');
+        if (bank_code.length > 8) errors.push('Absender-BLZ "' + bank_code + '" ist zu lang (max 8 Zeichen).');
+        if (res = bank_code.match(this.invalid_digits)) errors.push('Absender-BLZ "' + bank_code + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (account_number.length <= 0) errors.push('Keine Absender-Kontonummer angegeben.');
+        if (account_number.length > 10) errors.push('Absender-Kontonummer "' + account_number + '" ist zu lang (max 8 Zeichen).');
+        if (res = account_number.match(this.invalid_digits)) errors.push('Absender-Kontonummer "' + account_number + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (res = additional_name.match(this.invalid_chars)) errors.push('Absender-Zusatz "' + additional_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (errors.length == 0) {
+            this.account_file_sender = [];
+            this.account_file_sender['name'] = sender_name.substr(0, 27);
+            this.account_file_sender['bank_code'] = bank_code;
+            this.account_file_sender['account_number'] = account_number;
+            this.account_file_sender['additional_name'] = additional_name.substr(0, 27);
+            return true;
+        }
+        this.errormsg = 'Fehler beim setzen des Senders:\n';
+        for (var i = 0; i < errors.length; i++) {
+            this.errormsg += ' - ' + errors[i] + '\n';
+        }
+        return false;
+    },
+    /*
+        NOTE: For debits the receiver is the one who pays[SIC!] the money!
+
+        receiver_name          string, allowed characters: "A-Z0-9 .,&-/+*$%", up to 27 characters
+        bank_code                      up to 8 digits
+        account_number         up to 10 digits
+        additional_name                string, allowed characters: "A-Z0-9 .,&-/+*$%", up to 27 characters
+        amount                         amount in cent
+        purpose                                string, allowed characters: "A-Z0-9 .,&-/+*$%", up to 27 characters
+    */
+    addExchange: function (receiver_name, bank_code, account_number, additional_name, amount, purpose) {
+        // TODO Derzeit wird nur ein Verwendungszweck unterstützt (purpose theoretisch auch ein array sein)
+        // TODO additional_name wird derzeit einfach verworfen
+
+        if (!this.account_file_sender) return;
+
+        account_number = '' + account_number;
+        bank_code = '' + bank_code;
+        if (!additional_name) additional_name = '';
+
+        var errors = [];
+        var res;
+
+        if (receiver_name.length <= 0) errors.push('Kein Empfänger angegeben.');
+        if (res = receiver_name.match(this.invalid_chars)) errors.push('Empfänger "' + receiver_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (bank_code.length <= 0) errors.push('Keine Empfänger-BLZ angegeben.');
+        if (bank_code.length > 8) errors.push('Empfänger-BLZ "' + bank_code + '" ist zu lang (max 8 Zeichen).');
+        if (res = bank_code.match(this.invalid_digits)) errors.push('Empfänger-BLZ "' + bank_code + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (account_number.length <= 0) errors.push('Keine Empfänger-Kontonummer angegeben.');
+        if (account_number.length > 10) errors.push('Empfänger-Kontonummer "' + account_number + '" ist zu lang (max 8 Zeichen).');
+        if (res = account_number.match(this.invalid_digits)) errors.push('Empfänger-Kontonummer "' + account_number + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (res = additional_name.match(this.invalid_chars)) errors.push('Empfänger-Zusatz "' + additional_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
+        if (res = amount.match(this.invalid_digits)) errors.push('Betrag "' + amount + '" enthält ungültige Zeichen. (' + res[0] + ')');
+        if (res = purpose.match(this.invalid_chars)) errors.push('Verwendungszweck "' + purpose + '" enthält ungültige Zeichen. (' + res[0] + ')');
+
+        if (errors.length == 0) {
+            this.sum_amounts += toInt(amount);
+            this.sum_bank_codes += toInt(bank_code);
+            this.sum_account_numbers += toInt(account_number);
+
+            idx = this.exchanges.length;
+            this.exchanges[idx] = [];
+            this.exchanges[idx]['sender_name'] = this.account_file_sender['name'];
+            this.exchanges[idx]['sender_bank_code'] = this.account_file_sender['bank_code']
+            this.exchanges[idx]['sender_account_number'] = this.account_file_sender['account_number'];
+            this.exchanges[idx]['sender_additional_name'] = this.account_file_sender['additional_name']
+            this.exchanges[idx]['receiver_name'] = receiver_name.substr(0, 27);
+            this.exchanges[idx]['receiver_bank_code'] = bank_code;
+            this.exchanges[idx]['receiver_account_number'] = account_number;
+            this.exchanges[idx]['receiver_additional_name'] = additional_name.substr(0, 27);
+            this.exchanges[idx]['amount'] = amount;
+            this.exchanges[idx]['purpose'] = purpose;
+            return true;
+        }
+        this.errormsg = 'Fehler beim Hinzufügen eines Empfängers:\n';
+        for (var i = 0; i < errors.length; i++) {
+            this.errormsg += ' - ' + errors[i] + '\n';
         }
-               this.errormsg = 'Fehler beim setzen des Senders:\n';
-               for (var i = 0; i < errors.length; i++) {
-                       this.errormsg += ' - ' + errors[i]  +'\n';
-               }
-               return false;
+        return false;
     },
-       /*
-               NOTE: For debits the receiver is the one who pays[SIC!] the money!
-
-               receiver_name           string, allowed characters: "A-Z0-9 .,&-/+*$%", up to 27 characters
-               bank_code                       up to 8 digits
-               account_number          up to 10 digits
-               additional_name         string, allowed characters: "A-Z0-9 .,&-/+*$%", up to 27 characters
-               amount                          amount in cent
-               purpose                         string, allowed characters: "A-Z0-9 .,&-/+*$%", up to 27 characters
-       */
-       addExchange: function(receiver_name, bank_code, account_number, additional_name, amount, purpose) {
-               // TODO Derzeit wird nur ein Verwendungszweck unterstützt (purpose theoretisch auch ein array sein)
-               // TODO additional_name wird derzeit einfach verworfen
-
-               if (!this.account_file_sender) return;
-
-               account_number = '' + account_number;
-        bank_code      = '' + bank_code;
-               if (!additional_name) additional_name = '';
-
-               var errors = [];
-               var res;
-
-        if (receiver_name.length  <=  0)                                               errors.push('Kein Empfänger angegeben.');
-               if (res = receiver_name.match(this.invalid_chars))              errors.push('Empfänger "' + receiver_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-        if (bank_code.length      <=  0)                                               errors.push('Keine Empfänger-BLZ angegeben.');
-        if (bank_code.length       >  8)                                               errors.push('Empfänger-BLZ "' + bank_code + '" ist zu lang (max 8 Zeichen).');
-               if (res = bank_code.match(this.invalid_digits))                 errors.push('Empfänger-BLZ "' + bank_code + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-        if (account_number.length <=  0)                                               errors.push('Keine Empfänger-Kontonummer angegeben.');
-        if (account_number.length  > 10)                                               errors.push('Empfänger-Kontonummer "' + account_number + '" ist zu lang (max 8 Zeichen).');
-               if (res = account_number.match(this.invalid_digits))    errors.push('Empfänger-Kontonummer "' + account_number + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-               if (res = additional_name.match(this.invalid_chars))    errors.push('Empfänger-Zusatz "' + additional_name + '" enthält ungültige Zeichen. (' + res[0] + ')');
-               if (res = amount.match(this.invalid_digits))                    errors.push('Betrag "' + amount + '" enthält ungültige Zeichen. (' + res[0] + ')');
-               if (res = purpose.match(this.invalid_chars))                    errors.push('Verwendungszweck "' + purpose + '" enthält ungültige Zeichen. (' + res[0] + ')');
-
-               if (errors.length == 0) {
-                       this.sum_amounts                += toInt(amount);
-                       this.sum_bank_codes             += toInt(bank_code);
-                       this.sum_account_numbers+= toInt(account_number);
-
-                       idx = this.exchanges.length;
-                       this.exchanges[idx] = [];
-                       this.exchanges[idx]['sender_name']                              = this.account_file_sender['name'];
-                       this.exchanges[idx]['sender_bank_code']                 = this.account_file_sender['bank_code']
-                       this.exchanges[idx]['sender_account_number']    = this.account_file_sender['account_number'];
-                       this.exchanges[idx]['sender_additional_name']   = this.account_file_sender['additional_name']
-                       this.exchanges[idx]['receiver_name']            = receiver_name.substr(0, 27);
-                       this.exchanges[idx]['receiver_bank_code']       = bank_code;
-                       this.exchanges[idx]['receiver_account_number']  = account_number;
-                       this.exchanges[idx]['receiver_additional_name'] = additional_name.substr(0, 27);
-                       this.exchanges[idx]['amount']                                   = amount;
-                       this.exchanges[idx]['purpose']                                  = purpose;
-                       return true;
-               }
-               this.errormsg = 'Fehler beim Hinzufügen eines Empfängers:\n';
-               for (var i = 0; i < errors.length; i++) {
-                       this.errormsg += ' - ' + errors[i]  +'\n';
-               }
-               return false;
-       },
-
-       getFileContent: function() {
-               // TODO additional_name wird derzeit einfach verworfen
-
-               var content = '';
-
-               sum_account_numbers = toInt('0');
-               sum_bank_codes          = toInt('0');
-               sum_amounts                     = toInt('0');
+
+    getFileContent: function () {
+        // TODO additional_name wird derzeit einfach verworfen
+
+        var content = '';
+
+        sum_account_numbers = toInt('0');
+        sum_bank_codes = toInt('0');
+        sum_amounts = toInt('0');
 
         // (field numbers according to ebics-zka.de specification)
 
         /**
          * data record A
          */
-               content += str_pad_left('128', 4, '0');                                                                                 // A1   record length (128 Bytes)
+        content += str_pad_left('128', 4, '0');                                                                                        // A1   record length (128 Bytes)
         content += "A";                                                                                                                                        // A2   record type
         content += "LK";                                                                                                                               // A3   file mode (credit "G" or debit "L") and Customer File ("K") / Bank File ("B")
         content += str_pad_left(this.account_file_sender['bank_code'], 8, '0');                        // A4   sender's bank code
-               content += str_pad_right('', 8, '0');                                                                                   // A5   only used if Bank File, otherwise NULL
+        content += str_pad_right('', 8, '0');                                                                                  // A5   only used if Bank File, otherwise NULL
         content += str_pad_right(this.account_file_sender['name'], 27, ' ');                   // A6   sender's name
         content += str_pad_left(this.timestamp.getDate(), 2, '0')                                              // A7   date of file creation
-                                + str_pad_left(this.timestamp.getMonth() + 1, 2, '0')
-                                + this.timestamp.getFullYear().toString().substr(2,2);
-               content += str_pad_right('', 4, ' ');                                                                                   // A8   free (bank internal)
+            + str_pad_left(this.timestamp.getMonth() + 1, 2, '0')
+            + this.timestamp.getFullYear().toString().substr(2, 2);
+        content += str_pad_right('', 4, ' ');                                                                                  // A8   free (bank internal)
         content += str_pad_left(this.account_file_sender['account_number'], 10, '0');  // A9   sender's account number
-               content += str_pad_right('', 10, '0');                                                                                  // A10  sender's reference number (optional)
-               content += str_pad_right('', 15, ' ');                                                                                  // A11a free (reserve)
-               content += str_pad_right('', 8, ' ');                                                                                   // A11b execution date ("DDMMYYYY", optional)
-               content += str_pad_right('', 24, ' ');                                                                                  // A11c free (reserve)
+        content += str_pad_right('', 10, '0');                                                                                 // A10  sender's reference number (optional)
+        content += str_pad_right('', 15, ' ');                                                                                 // A11a free (reserve)
+        content += str_pad_right('', 8, ' ');                                                                                  // A11b execution date ("DDMMYYYY", optional)
+        content += str_pad_right('', 24, ' ');                                                                                 // A11c free (reserve)
         content += '1';                                                                                                                                        // A12  currency (1 = Euro)
 
-               if (content.length != 128) {
-                       alert('Fehlerhafter A-Satz: ' + content.length + ' Zeichen');
-                       return content;
-               }
+        if (content.length != 128) {
+            alert('Fehlerhafter A-Satz: ' + content.length + ' Zeichen');
+            return content;
+        }
 
         /**
          * data record(s) C
          */
-               for (var i = 0; i < this.exchanges.length; i++) {
-                       var exchange = this.exchanges[i];
+        for (var i = 0; i < this.exchanges.length; i++) {
+            var exchange = this.exchanges[i];
 
-                       sum_account_numbers     += toInt(exchange['receiver_account_number']);
-                       sum_bank_codes          += toInt(exchange['receiver_bank_code']);
-                       sum_amounts                     += toInt(exchange['amount']);
+            sum_account_numbers += toInt(exchange['receiver_account_number']);
+            sum_bank_codes += toInt(exchange['receiver_bank_code']);
+            sum_amounts += toInt(exchange['amount']);
 
-                       content += str_pad_left('187', 4, '0');                                                                         // C1   record length (187 Bytes + 29 Bytes for each additional part)
+            content += str_pad_left('187', 4, '0');                                                                            // C1   record length (187 Bytes + 29 Bytes for each additional part)
             content += 'C';                                                                                                                            // C2   record type
-               content += str_pad_left(exchange['sender_bank_code'], 8, '0');                          // C3   first involved bank
-               content += str_pad_left(exchange['receiver_bank_code'], 8, '0');                        // C4   receiver's bank code
-               content += str_pad_left(exchange['receiver_account_number'], 10, '0');          // C5   receiver's account number
+            content += str_pad_left(exchange['sender_bank_code'], 8, '0');                             // C3   first involved bank
+            content += str_pad_left(exchange['receiver_bank_code'], 8, '0');                   // C4   receiver's bank code
+            content += str_pad_left(exchange['receiver_account_number'], 10, '0');             // C5   receiver's account number
             content += str_pad_right('', 13, '0');                                                                             // C6   internal customer number ('0' + 11 chars + '0')
-                       content += '05';                                                                                                                        // C7a  payment mode (text key) (debit '05' / credit '51')
-                       content += str_pad_right('',  3, '0');                                                                          // C7b  additional text key
-                       content += ' ';                                                                                                                         // C8   bank internal
+            content += '05';                                                                                                                   // C7a  payment mode (text key) (debit '05' / credit '51')
+            content += str_pad_right('', 3, '0');                                                                              // C7b  additional text key
+            content += ' ';                                                                                                                            // C8   bank internal
             content += str_pad_right('', 11, '0');                                                                             // C9   free (reserve)
-               content += str_pad_left(exchange['sender_bank_code'], 8, '0');                          // C10  sender's bank code
-               content += str_pad_left(exchange['sender_account_number'], 10, '0');            // C11  sender's account number
-               content += str_pad_left(exchange['amount'], 11, '0');                                           // C12  amount
-                       content += str_pad_right('',  3, ' ');                                                                          // C13  free (reserve)
-               content += str_pad_right(exchange['receiver_name'], 27, ' ');                           // C14a receiver's name
-                       content += str_pad_right('',  8, ' ');                                                                          // C14b delimitation
+            content += str_pad_left(exchange['sender_bank_code'], 8, '0');                             // C10  sender's bank code
+            content += str_pad_left(exchange['sender_account_number'], 10, '0');               // C11  sender's account number
+            content += str_pad_left(exchange['amount'], 11, '0');                                              // C12  amount
+            content += str_pad_right('', 3, ' ');                                                                              // C13  free (reserve)
+            content += str_pad_right(exchange['receiver_name'], 27, ' ');                              // C14a receiver's name
+            content += str_pad_right('', 8, ' ');                                                                              // C14b delimitation
             /* first part/128 chars full */
-               content += str_pad_right(exchange['sender_name'], 27, ' ');                                     // C15  sender's name
-               content += str_pad_right(exchange['purpose'], 27, ' ');                                         // C16  first line of purpose
-               content += '1';                                                                                                                         // C17a currency (1 = Euro)
-                       content += str_pad_right('',  2, ' ');                                                                          // C17b free (reserve)
-            content += str_pad_right('',  2, '0');                                                                             // C18  number of additional parts (00-15)
+            content += str_pad_right(exchange['sender_name'], 27, ' ');                                        // C15  sender's name
+            content += str_pad_right(exchange['purpose'], 27, ' ');                                            // C16  first line of purpose
+            content += '1';                                                                                                                            // C17a currency (1 = Euro)
+            content += str_pad_right('', 2, ' ');                                                                              // C17b free (reserve)
+            content += str_pad_right('', 2, '0');                                                                              // C18  number of additional parts (00-15)
 
             /*
              * End of the constant part (187 chars),
@@ -214,40 +213,40 @@ var DTAUS = {
              */
 
             // no extension, pad to fill the part to 2*128 chars
-            content += str_pad_right('', 256-187, ' ');
-                       if (content.length % 128 != 0) {
-                               alert('Fehlerhafter C-Satz: ' + content.length + ' Zeichen');
-                               return content;
-                       }
-               }
+            content += str_pad_right('', 256 - 187, ' ');
+            if (content.length % 128 != 0) {
+                alert('Fehlerhafter C-Satz: ' + content.length + ' Zeichen');
+                return content;
+            }
+        }
 
         /**
          * data record E
          */
 
-               if (this.sum_amounts         != sum_amounts
-                || this.sum_bank_codes      != sum_bank_codes
-                || this.sum_account_numbers != sum_account_numbers
-               ) {
-                       alert('Fehlerhafte Summe');
-                       return content;
-               }
+        if (this.sum_amounts != sum_amounts
+            || this.sum_bank_codes != sum_bank_codes
+            || this.sum_account_numbers != sum_account_numbers
+        ) {
+            alert('Fehlerhafte Summe');
+            return content;
+        }
 
-               content += str_pad_left('128', 4, '0');                                                                                 // E1   record length (128 bytes)
+        content += str_pad_left('128', 4, '0');                                                                                        // E1   record length (128 bytes)
         content += 'E';                                                                                                                                        // E2   record type
-               content += str_pad_right('',  5, ' ');                                                                                  // E3   free (reserve)
-               content += str_pad_left(this.exchanges.length, 7, '0');                                                 // E4   number of records type C
-               content += str_pad_right('', 13, '0');                                                                                  // E5   free (reserve)
+        content += str_pad_right('', 5, ' ');                                                                                  // E3   free (reserve)
+        content += str_pad_left(this.exchanges.length, 7, '0');                                                        // E4   number of records type C
+        content += str_pad_right('', 13, '0');                                                                                 // E5   free (reserve)
         content += str_pad_left(sum_account_numbers, 17, '0');                                                 // E6   sum of account numbers
-        content += str_pad_left(sum_bank_codes,      17, '0');                                                 // E7   sum of bank codes
-        content += str_pad_left(sum_amounts,         13, '0');                                                 // E8   sum of amounts
-               content += str_pad_right('',  51, ' ');                                                                                 // E9   delimitation
+        content += str_pad_left(sum_bank_codes, 17, '0');                                                      // E7   sum of bank codes
+        content += str_pad_left(sum_amounts, 13, '0');                                                 // E8   sum of amounts
+        content += str_pad_right('', 51, ' ');                                                                                 // E9   delimitation
 
 
-               if (content.length % 128 != 0) {
-                       alert('Fehlerhafter E-Satz');
-                       return content;
-               }
+        if (content.length % 128 != 0) {
+            alert('Fehlerhafter E-Satz');
+            return content;
+        }
 
         return content;
     }
index a2b0e92..095d451 100644 (file)
@@ -1,17 +1,17 @@
 // stolen from https://gist.github.com/panzi/1857360
 
 var XML_CHAR_MAP = {
-  '<': '&lt;',
-  '>': '&gt;',
-  '&': '&amp;',
-  '"': '&quot;',
-  "'": '&apos;'
+    '<': '&lt;',
+    '>': '&gt;',
+    '&': '&amp;',
+    '"': '&quot;',
+    "'": '&apos;'
 };
 
-function escapeXml (s) {
-  return s.replace(/[<>&"']/g, function (ch) {
-    return XML_CHAR_MAP[ch];
-  });
+function escapeXml(s) {
+    return s.replace(/[<>&"']/g, function (ch) {
+        return XML_CHAR_MAP[ch];
+    });
 }
 
 //
@@ -23,253 +23,253 @@ function escapeXml (s) {
 
 var SEPACORE = {
 
-  creditorname: null,
-  creditoridentifier: null,
-  creditoriban: null,
-  creditorbic: null,
-  
-  directdebittxs: { 'FRST': [], 'RCUR': [] },
-  directdebittxssums: { 'FRST': 0, 'RCUR': 0 },
-  
-  creationdate: new Date(),
-  // only one collectiondate for FRST & RCUR is supported
-  collectiondate: null,
-  
-  errormsg: '',
-  
-  init: function(collectiondate, creditoridentifier, creditorname, creditoriban, creditorbic) {
-    
-    var errors = [];
-    var argscntOK = true;
-    
-    if (arguments.length != 4 && arguments.length != 5) {
-      this.errors.push('initSEPACORE mit falscher Parameteranzahl aufgerufen (Soll: 4 oder 5; Ist: ' + arguments.length + ').');
-      argscntOK = false;
-    }
-    
-    if (argscntOK && (creditorname.length == 0 || creditorname.length > 70)) {
-      errors.push('Name des Zahlungsempfängers muss zwischen 1 und 70 Zeichen lang sein (nicht ' + creditorname.length + ').');
-    }
-    this.creditorname = creditorname;
-
-    if (argscntOK && (creditoriban.length < 15 || creditoriban.length > 32)) {
-      errors.push('IBAN des Zahlungsempfängers muss zwischen 15 und 32 Zeichen lang sein (nicht ' + creditoriban.length + ').');
-    }
-    this.creditoriban = creditoriban;
-
-    if (argscntOK && creditorbic != null && creditorbic.length != 8 && creditorbic.length != 11) {
-      errors.push('BIC des Zahlungsempfängers muss 8 oder 11 Zeichen lang oder nicht gesetzt sein (nicht ' + creditorbic.length + ').');
-    }
-    this.creditorbic = creditorbic;
-
-    if (argscntOK && (creditoridentifier.length == 0 || creditoridentifier.length > 35)) {
-      errors.push('Gläubiger-ID für den Zahlungspflichtigen muss zwischen 1 und 35 Zeichen lang sein (nicht ' + creditormndtid.length + ').');
-    }
-    this.creditoridentifier = creditoridentifier;
-    
-    this.collectiondate = collectiondate;
-    
-    
-    this.directdebittxs = { 'FRST': [], 'RCUR': [] };
-    this.directdebittxssums = { 'FRST': 0, 'RCUR': 0 };
-  
-    this.creationdate = new Date(),
-    this.errormsg = '';
-    
-    return true;
-  },
-  
-  addDDTx: function(ddtype, debtorname, debtoriban, debtorbic, debtormndtid, debtormndtdate, amountcent, purpose, e2eid) {
-    
-    var errors = [];
-    var argscntOK = true;
-    
-    if (arguments.length != 9 && arguments.length != 8) {
-      this.errors.push('addDDTx mit falscher Parameteranzahl aufgerufen (Soll: 8 oder 9; Ist: ' + arguments.length + ').');
-      argscntOK = false;
-    }      
-    
-    if (argscntOK && ddtype != 'FRST' && ddtype != 'RCUR') {
-      errors.push('Sequenztyp (ddtype) muss FRST oder RCUR sein.');
-    }
-    
-    if (argscntOK && (debtorname.length == 0 || debtorname.length > 70)) {
-      errors.push('Name des Zahlungspflichtigen muss zwischen 1 und 70 Zeichen lang sein (nicht ' + debtorname.length + ').');
-    }
-
-    if (argscntOK && (debtoriban.length < 15 || debtoriban.length > 32)) {
-      errors.push('IBAN des Zahlungspflichtigen muss zwischen 15 und 32 Zeichen lang sein (nicht ' + debtoriban.length + ').');
-    }
-
-    if (argscntOK && debtorbic != null && debtorbic.length != 8 && debtorbic.length != 11) {
-      errors.push('BIC des Zahlungspflichtigen muss 8 oder 11 Zeichen lang oder nicht gesetzt sein (nicht ' + debtorbic.length + ').');
-    }
-
-    if (argscntOK && (debtormndtid.length == 0 || debtormndtid.length > 35)) {
-      errors.push('Mandatsreferenz für den Zahlungspflichtigen muss zwischen 1 und 35 Zeichen lang sein (nicht ' + debtormndtid.length + ').');
-    }
-    
-    if (argscntOK && debtormndtdate.length != 10) {
-      errors.push('Datum der Mandatsunterschrift muss 10 Zeichen lang sein (nicht ' + debtormndtdate.length + ').');
-    }
-    
-    if (! /^[-]?\d{4}-(0[1-9]|1[0-2])-(0[0-9]|[1-5][0-9]|60)[Z\-]?\d*:?\d*$/.test(debtormndtdate) ) {
-      errors.push('Datum der Mandatsunterschrift ist nicht in Ordnung (' + debtormndtdate + ').');
-    }      
-    
-    if (argscntOK && (isNaN(amountcent) || amountcent < 0)) {
-      errors.push('Betrag muss eine Zahl und darf nicht negativ (' + amountcent + ' cent) sein.');
-    }
-    amountcent = parseInt(amountcent);
-    
-    purpose = purpose || '';
-    if (argscntOK && purpose.length > 140) {
-      errors.push('Verwendungszweck muss zwischen 0 und 140 Zeichen lang sein (nicht ' + purpose.length + ').');
-    }
-    
-    e2eid = e2eid || 'NOTPROVIDED';
-    if (argscntOK && purpose.length > 35) {
-      errors.push('End-to-End ID muss zwischen 0 und 35 Zeichen lang sein (nicht ' + purpose.length + ').');
-    }
-    if (e2eid == '') {
-      e2eid = 'NOTPROVIDED';
-    }
-    
-    if (debtorbic != null) {
-      bicstr = '<DbtrAgt><FinInstnId><BIC>' + escapeXml(debtorbic) + '</BIC></FinInstnId></DbtrAgt>';
-    } else {
-      bicstr = '<!-- no BIC for DbtrAgt supplied -->';
-    }
-    
-    if (purpose != '') {
-      purposestr = '<RmtInf><Ustrd>' + escapeXml(purpose) + '</Ustrd></RmtInf>';
-    } else {
-      purposestr = '<!-- no Ustrd for RmtInf supplied -->';
-    }
-    
-    if (errors.length == 0) {
-      this.directdebittxs[ddtype].push([      
-        '      <DrctDbtTxInf>',
-        '        <PmtId><EndToEndId>' + escapeXml(e2eid) + '</EndToEndId></PmtId>',
-        '        <InstdAmt Ccy="EUR">' + centToEur(amountcent) + '</InstdAmt>',
-        '        <DrctDbtTx><MndtRltdInf>',
-        '          <MndtId>' + escapeXml(debtormndtid) + '</MndtId>',
-        '          <DtOfSgntr>' + escapeXml(debtormndtdate) + '</DtOfSgntr>',
-        '          <AmdmntInd>false</AmdmntInd>',
-        '        </MndtRltdInf></DrctDbtTx>',
-        '        ' + bicstr,
-        '        <Dbtr><Nm>' + escapeXml(debtorname) + '</Nm></Dbtr>',
-        '        <DbtrAcct><Id><IBAN>' + escapeXml(debtoriban) + '</IBAN></Id></DbtrAcct>',
-        '        ' + purposestr,
-        '      </DrctDbtTxInf>'].join('\n'));
-      this.directdebittxssums[ddtype] += amountcent;
-      return true;
-    }
-    
-    this.errormsg = 'Fehler beim Hinzufügen eines Empfängers:\n';
-    for (var i = 0; i < errors.length; i++) {
-      this.errormsg += ' - ' + errors[i]  +'\n';
-    }
-    return false;
-  },
-  
-  getGroupHeaderBlock: function(ddtype) {
-
-    if (ddtype != 'FRST' && ddtype != 'RCUR') {
-      this.errormsg += ' - getGroupHeaderBlock: Sequenztyp (ddtype) muss FRST oder RCUR sein.\n';
-      return;
-    }
-    
-    createdatestr = [
-      this.creationdate.getUTCFullYear(), '-',
-        str_pad_left(this.creationdate.getUTCMonth()+1, 2, '0'), '-',
-        str_pad_left(this.creationdate.getUTCDate(), 2, '0'), 'T',
-        str_pad_left(this.creationdate.getUTCHours(), 2, '0'), ':',
-        str_pad_left(this.creationdate.getUTCMinutes(), 2, '0'), ':',
-        str_pad_left(this.creationdate.getUTCSeconds(), 2, '0'), '.000Z' ].join('');
-
-    return [
-      '    <GrpHdr>',
-      '      <MsgId>/V:1/MSG:' + parseInt(this.creationdate.getTime()/1000) + '/S:' + ddtype[0] + '/</MsgId>',
-      '      <CreDtTm>' + createdatestr + '</CreDtTm>',
-      '      <NbOfTxs>' + this.directdebittxs[ddtype].length + '</NbOfTxs>',
-      '      <InitgPty><Nm>' + escapeXml(this.creditorname) + '</Nm></InitgPty>',
-      '    </GrpHdr>'].join('\n');
-  },
-    
-  getPaymentInformationHeaderBlock: function(ddtype) {
-    
-    if (ddtype != 'FRST' && ddtype != 'RCUR') {
-      this.errormsg += ' - getPaymentInformationHeaderBlock: Sequenztyp (ddtype) muss FRST oder RCUR sein.\n';
-      return;
-    }
-
-    // Localtime or UTC???
-    collectiondatestr = [ this.collectiondate.getFullYear(),
-                          str_pad_left(this.collectiondate.getMonth()+1, 2, '0'),
-                          str_pad_left(this.collectiondate.getDate(), 2, '0')
-                          ].join('-');
-       
-    return [
-      '      <PmtInfId>/V:1/PMT:' + parseInt(this.creationdate.getTime()/1000) + '/S:' + ddtype[0] + '/</PmtInfId>',
-      '      <PmtMtd>DD</PmtMtd>',
-      '      <NbOfTxs>' + this.directdebittxs[ddtype].length + '</NbOfTxs>',
-      '      <CtrlSum>' + centToEur(this.directdebittxssums[ddtype]) + '</CtrlSum>',
-      '      <PmtTpInf><SvcLvl><Cd>SEPA</Cd></SvcLvl>',
-      '        <LclInstrm><Cd>CORE</Cd></LclInstrm>',
-      '        <SeqTp>' + ddtype + '</SeqTp>',
-      '      </PmtTpInf>',
-      '      <ReqdColltnDt>' + collectiondatestr + '</ReqdColltnDt>'
-      ].join('\n');
-  },
-
-  getCreditorBlock: function() {
-    if (this.creditorbic != null) {
-      bicstr = '<CdtrAgt><FinInstnId><BIC>' + escapeXml(this.creditorbic) + '</BIC></FinInstnId></CdtrAgt>';
-    } else {
-      bicstr = '<!-- no BIC for CdtrAgt supplied -->';
-    }
-    return [
-      '      <Cdtr><Nm>' + escapeXml(this.creditorname) + '</Nm> </Cdtr>',
-      '      <CdtrAcct><Id><IBAN>' + escapeXml(this.creditoriban) + '</IBAN></Id></CdtrAcct>',
-      '      ' + bicstr        ,
-      '      <ChrgBr>SLEV</ChrgBr>',
-      '      <CdtrSchmeId><Id><PrvtId><Othr>',
-      '        <Id>' + escapeXml(this.creditoridentifier) + '</Id>',
-      '        <SchmeNm><Prtry>SEPA</Prtry></SchmeNm>',
-      '      </Othr></PrvtId></Id></CdtrSchmeId>'
-      ].join('\n');
-  },
-  
-  getDirectDebitBlock: function(ddtype) {
-    if (ddtype != 'FRST' && ddtype != 'RCUR') {
-      this.errormsg += ' - getDirectDebitBlock: Sequenztyp (ddtype) muss FRST oder RCUR sein.\n';
-      return;
-    }
-    return this.directdebittxs[ddtype].join('\n');
-  },
-
-  getXMLContent: function(ddtype) {
-    if (ddtype != 'FRST' && ddtype != 'RCUR') {
-      this.errormsg += ' - getXMLContent: Sequenztyp (ddtype) muss FRST oder RCUR sein.\n';
-      return;
-    }
-    if (this.directdebittxs[ddtype].length == 0) {
-      return '<!-- Keine ' + ((ddtype=='FRST') ? 'SEPA Ersteinzüge' : 'wiederkehrenden SEPA Einzüge') + ' -->';
-    } else {
-      return [
-        '<?xml version="1.0" encoding="UTF-8"?>',
-        '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.003.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.008.003.02 pain.008.003.02.xsd">',
-        '  <CstmrDrctDbtInitn>',
-        this.getGroupHeaderBlock(ddtype),
-        '    <PmtInf>',
-        this.getPaymentInformationHeaderBlock(ddtype),
-        this.getCreditorBlock(),
-        this.getDirectDebitBlock(ddtype),
-        '    </PmtInf>',
-        '  </CstmrDrctDbtInitn>',
-        '</Document>'].join('\n');
-    }  
-  },
-  
+    creditorname: null,
+    creditoridentifier: null,
+    creditoriban: null,
+    creditorbic: null,
+
+    directdebittxs: {'FRST': [], 'RCUR': []},
+    directdebittxssums: {'FRST': 0, 'RCUR': 0},
+
+    creationdate: new Date(),
+    // only one collectiondate for FRST & RCUR is supported
+    collectiondate: null,
+
+    errormsg: '',
+
+    init: function (collectiondate, creditoridentifier, creditorname, creditoriban, creditorbic) {
+
+        var errors = [];
+        var argscntOK = true;
+
+        if (arguments.length != 4 && arguments.length != 5) {
+            this.errors.push('initSEPACORE mit falscher Parameteranzahl aufgerufen (Soll: 4 oder 5; Ist: ' + arguments.length + ').');
+            argscntOK = false;
+        }
+
+        if (argscntOK && (creditorname.length == 0 || creditorname.length > 70)) {
+            errors.push('Name des Zahlungsempfängers muss zwischen 1 und 70 Zeichen lang sein (nicht ' + creditorname.length + ').');
+        }
+        this.creditorname = creditorname;
+
+        if (argscntOK && (creditoriban.length < 15 || creditoriban.length > 32)) {
+            errors.push('IBAN des Zahlungsempfängers muss zwischen 15 und 32 Zeichen lang sein (nicht ' + creditoriban.length + ').');
+        }
+        this.creditoriban = creditoriban;
+
+        if (argscntOK && creditorbic != null && creditorbic.length != 8 && creditorbic.length != 11) {
+            errors.push('BIC des Zahlungsempfängers muss 8 oder 11 Zeichen lang oder nicht gesetzt sein (nicht ' + creditorbic.length + ').');
+        }
+        this.creditorbic = creditorbic;
+
+        if (argscntOK && (creditoridentifier.length == 0 || creditoridentifier.length > 35)) {
+            errors.push('Gläubiger-ID für den Zahlungspflichtigen muss zwischen 1 und 35 Zeichen lang sein (nicht ' + creditormndtid.length + ').');
+        }
+        this.creditoridentifier = creditoridentifier;
+
+        this.collectiondate = collectiondate;
+
+
+        this.directdebittxs = {'FRST': [], 'RCUR': []};
+        this.directdebittxssums = {'FRST': 0, 'RCUR': 0};
+
+        this.creationdate = new Date(),
+            this.errormsg = '';
+
+        return true;
+    },
+
+    addDDTx: function (ddtype, debtorname, debtoriban, debtorbic, debtormndtid, debtormndtdate, amountcent, purpose, e2eid) {
+
+        var errors = [];
+        var argscntOK = true;
+
+        if (arguments.length != 9 && arguments.length != 8) {
+            this.errors.push('addDDTx mit falscher Parameteranzahl aufgerufen (Soll: 8 oder 9; Ist: ' + arguments.length + ').');
+            argscntOK = false;
+        }
+
+        if (argscntOK && ddtype != 'FRST' && ddtype != 'RCUR') {
+            errors.push('Sequenztyp (ddtype) muss FRST oder RCUR sein.');
+        }
+
+        if (argscntOK && (debtorname.length == 0 || debtorname.length > 70)) {
+            errors.push('Name des Zahlungspflichtigen muss zwischen 1 und 70 Zeichen lang sein (nicht ' + debtorname.length + ').');
+        }
+
+        if (argscntOK && (debtoriban.length < 15 || debtoriban.length > 32)) {
+            errors.push('IBAN des Zahlungspflichtigen muss zwischen 15 und 32 Zeichen lang sein (nicht ' + debtoriban.length + ').');
+        }
+
+        if (argscntOK && debtorbic != null && debtorbic.length != 8 && debtorbic.length != 11) {
+            errors.push('BIC des Zahlungspflichtigen muss 8 oder 11 Zeichen lang oder nicht gesetzt sein (nicht ' + debtorbic.length + ').');
+        }
+
+        if (argscntOK && (debtormndtid.length == 0 || debtormndtid.length > 35)) {
+            errors.push('Mandatsreferenz für den Zahlungspflichtigen muss zwischen 1 und 35 Zeichen lang sein (nicht ' + debtormndtid.length + ').');
+        }
+
+        if (argscntOK && debtormndtdate.length != 10) {
+            errors.push('Datum der Mandatsunterschrift muss 10 Zeichen lang sein (nicht ' + debtormndtdate.length + ').');
+        }
+
+        if (!/^[-]?\d{4}-(0[1-9]|1[0-2])-(0[0-9]|[1-5][0-9]|60)[Z\-]?\d*:?\d*$/.test(debtormndtdate)) {
+            errors.push('Datum der Mandatsunterschrift ist nicht in Ordnung (' + debtormndtdate + ').');
+        }
+
+        if (argscntOK && (isNaN(amountcent) || amountcent < 0)) {
+            errors.push('Betrag muss eine Zahl und darf nicht negativ (' + amountcent + ' cent) sein.');
+        }
+        amountcent = parseInt(amountcent);
+
+        purpose = purpose || '';
+        if (argscntOK && purpose.length > 140) {
+            errors.push('Verwendungszweck muss zwischen 0 und 140 Zeichen lang sein (nicht ' + purpose.length + ').');
+        }
+
+        e2eid = e2eid || 'NOTPROVIDED';
+        if (argscntOK && purpose.length > 35) {
+            errors.push('End-to-End ID muss zwischen 0 und 35 Zeichen lang sein (nicht ' + purpose.length + ').');
+        }
+        if (e2eid == '') {
+            e2eid = 'NOTPROVIDED';
+        }
+
+        if (debtorbic != null) {
+            bicstr = '<DbtrAgt><FinInstnId><BIC>' + escapeXml(debtorbic) + '</BIC></FinInstnId></DbtrAgt>';
+        } else {
+            bicstr = '<!-- no BIC for DbtrAgt supplied -->';
+        }
+
+        if (purpose != '') {
+            purposestr = '<RmtInf><Ustrd>' + escapeXml(purpose) + '</Ustrd></RmtInf>';
+        } else {
+            purposestr = '<!-- no Ustrd for RmtInf supplied -->';
+        }
+
+        if (errors.length == 0) {
+            this.directdebittxs[ddtype].push([
+                '      <DrctDbtTxInf>',
+                '        <PmtId><EndToEndId>' + escapeXml(e2eid) + '</EndToEndId></PmtId>',
+                '        <InstdAmt Ccy="EUR">' + centToEur(amountcent) + '</InstdAmt>',
+                '        <DrctDbtTx><MndtRltdInf>',
+                '          <MndtId>' + escapeXml(debtormndtid) + '</MndtId>',
+                '          <DtOfSgntr>' + escapeXml(debtormndtdate) + '</DtOfSgntr>',
+                '          <AmdmntInd>false</AmdmntInd>',
+                '        </MndtRltdInf></DrctDbtTx>',
+                '        ' + bicstr,
+                '        <Dbtr><Nm>' + escapeXml(debtorname) + '</Nm></Dbtr>',
+                '        <DbtrAcct><Id><IBAN>' + escapeXml(debtoriban) + '</IBAN></Id></DbtrAcct>',
+                '        ' + purposestr,
+                '      </DrctDbtTxInf>'].join('\n'));
+            this.directdebittxssums[ddtype] += amountcent;
+            return true;
+        }
+
+        this.errormsg = 'Fehler beim Hinzufügen eines Empfängers:\n';
+        for (var i = 0; i < errors.length; i++) {
+            this.errormsg += ' - ' + errors[i] + '\n';
+        }
+        return false;
+    },
+
+    getGroupHeaderBlock: function (ddtype) {
+
+        if (ddtype != 'FRST' && ddtype != 'RCUR') {
+            this.errormsg += ' - getGroupHeaderBlock: Sequenztyp (ddtype) muss FRST oder RCUR sein.\n';
+            return;
+        }
+
+        createdatestr = [
+            this.creationdate.getUTCFullYear(), '-',
+            str_pad_left(this.creationdate.getUTCMonth() + 1, 2, '0'), '-',
+            str_pad_left(this.creationdate.getUTCDate(), 2, '0'), 'T',
+            str_pad_left(this.creationdate.getUTCHours(), 2, '0'), ':',
+            str_pad_left(this.creationdate.getUTCMinutes(), 2, '0'), ':',
+            str_pad_left(this.creationdate.getUTCSeconds(), 2, '0'), '.000Z'].join('');
+
+        return [
+            '    <GrpHdr>',
+            '      <MsgId>/V:1/MSG:' + parseInt(this.creationdate.getTime() / 1000) + '/S:' + ddtype[0] + '/</MsgId>',
+            '      <CreDtTm>' + createdatestr + '</CreDtTm>',
+            '      <NbOfTxs>' + this.directdebittxs[ddtype].length + '</NbOfTxs>',
+            '      <InitgPty><Nm>' + escapeXml(this.creditorname) + '</Nm></InitgPty>',
+            '    </GrpHdr>'].join('\n');
+    },
+
+    getPaymentInformationHeaderBlock: function (ddtype) {
+
+        if (ddtype != 'FRST' && ddtype != 'RCUR') {
+            this.errormsg += ' - getPaymentInformationHeaderBlock: Sequenztyp (ddtype) muss FRST oder RCUR sein.\n';
+            return;
+        }
+
+        // Localtime or UTC???
+        collectiondatestr = [this.collectiondate.getFullYear(),
+            str_pad_left(this.collectiondate.getMonth() + 1, 2, '0'),
+            str_pad_left(this.collectiondate.getDate(), 2, '0')
+        ].join('-');
+
+        return [
+            '      <PmtInfId>/V:1/PMT:' + parseInt(this.creationdate.getTime() / 1000) + '/S:' + ddtype[0] + '/</PmtInfId>',
+            '