Changeset 136


Ignore:
Timestamp:
Jun 3, 2006 7:47:48 PM (18 years ago)
Author:
scdev
Message:

Q - Merged branches/2.0singleton into trunk. Completed updating classes to use singleton methods. Implemented tests. Fixed some bugs. Changed some interfaces.

Location:
trunk
Files:
1 added
73 edited

Legend:

Unmodified
Added
Removed
  • trunk/bin/file_importer.php

    r111 r136  
    77
    88require realpath(dirname(__FILE__) . '/..') . '/config/cli_config.inc.php';
     9
     10$app =& App::getInstance();
     11$db =& DB::getInstance();
     12   
    913
    1014// Test arguments.
     
    3135            preg_match('/BALANCE:\s*\$([\.\d]+)/', $file_text, $amt);
    3236            $file_date = date('Y-m-d', strtotime(preg_replace('|[^_]*_|', '', basename($file))));
    33 //             DB::query("
     37//             $db->query("
    3438//                 INSERT INTO invoice_tbl (
    3539//                     client_id,
     
    4347//                     added_datetime
    4448//                 ) VALUES (
    45 //                     '" . DB::escapeString(0) . "',
    46 //                     '" . DB::escapeString('hosting') . "',
    47 //                     '" . DB::escapeString($file_date) . "',
    48 //                     '" . DB::escapeString($amt[1]) . "',
    49 //                     '" . DB::escapeString('Paid') . "',
    50 //                     '" . DB::escapeString('') . "',
    51 //                     '" . DB::escapeString($file_text) . "',
    52 //                     '" . DB::escapeString($file_date) . "',
     49//                     '" . $db->escapeString(0) . "',
     50//                     '" . $db->escapeString('hosting') . "',
     51//                     '" . $db->escapeString($file_date) . "',
     52//                     '" . $db->escapeString($amt[1]) . "',
     53//                     '" . $db->escapeString('Paid') . "',
     54//                     '" . $db->escapeString('') . "',
     55//                     '" . $db->escapeString($file_text) . "',
     56//                     '" . $db->escapeString($file_date) . "',
    5357//                     NOW()
    5458//                 )
     
    5660
    5761        } else {
    58             App::logMsg('Could not open file: ' . $file, LOG_INFO, __FILE__, __LINE__);
     62            $app->logMsg('Could not open file: ' . $file, LOG_INFO, __FILE__, __LINE__);
    5963        }
    6064    }
    61     App::logMsg('Proccessing complete: ' . $file_count . ' files total.', LOG_INFO, __FILE__, __LINE__);
     65    $app->logMsg('Proccessing complete: ' . $file_count . ' files total.', LOG_INFO, __FILE__, __LINE__);
    6266} else {
    63     App::logMsg('No files available in that directory.', LOG_INFO, __FILE__, __LINE__);
     67    $app->logMsg('No files available in that directory.', LOG_INFO, __FILE__, __LINE__);
    6468}
    6569
  • trunk/bin/module_maker/_config.inc.php

    r19 r136  
    3030
    3131$app =& App::getInstance('module_maker');
    32 
    3332$app->setParam(array(
    3433    'site_name' => 'Module Maker',
     
    4342    'log_screen_priority' => LOG_DEBUG,
    4443));
    45 
    4644require_once 'global/db_auth.inc.php';
    4745
     46// Start application-based functionality: database, session, environment, ini setup, etc.
     47// Most configuration parameters must be set before starting the App.
    4848$app->start();
    4949
     50// Global DB object. Automatically preconfigured by $app->start().
     51$db =& DB::getInstance();
     52
     53
    5054?>
  • trunk/bin/module_maker/form_template.cli.php

    r121 r136  
    1717
    1818// Get DB tables.
    19 $qid = DB::query("SHOW TABLES");
     19$qid = $db->query("SHOW TABLES");
    2020while (list($row) = mysql_fetch_row($qid)) {
    2121    $tables[] = $row;
     
    2424// Make sure requested table is in database.
    2525if (!in_array($db_tbl, $tables)) {
    26     die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, App::getParam('db_name'), join("\n", $tables)));
     26    die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name'), join("\n", $tables)));
    2727}
    2828
    2929// Get DB table column info.
    30 $qid = DB::query("DESCRIBE " . DB::escapeString($db_tbl));
     30$qid = $db->query("DESCRIBE " . $db->escapeString($db_tbl));
    3131while ($row = mysql_fetch_row($qid)) {
    3232    $cols[] = $row;
     
    6565<label for="$field"<\x3fphp \$fv->err('$field') \x3f>><\x3fphp echo _("$title"); \x3f></label>
    6666<select name="$field" id="$field" class="sc-small"><\x3fphp printSelectForm('<##>_tbl', "CONCAT(<##>_id, '&mdash;', <##>)", '$field', \$frm['$field'], true, 'ORDER BY $field ASC'); \x3f></select>
    67     <span class="commanditem commandtext"><a href="<\x3fphp echo App::oHREF('<##>.php?op=add&boomerang=true'); \x3f>" onClick="javascript:return confirm('<\x3fphp echo _("Notice: You are about to leave this form page and any changes you may have made without saving will be lost."); \x3f>')"><\x3fphp echo _("Add <##>") \x3f></a></span>
     67    <span class="commanditem commandtext"><a href="<\x3fphp echo \$app->oHREF('<##>.php?op=add&boomerang=true'); \x3f>" onClick="javascript:return confirm('<\x3fphp echo _("Notice: You are about to leave this form page and any changes you may have made without saving will be lost."); \x3f>')"><\x3fphp echo _("Add <##>") \x3f></a></span>
    6868    <\x3fphp if ('' != \$frm['<##>_id']) { \x3f>
    69     <span class="commanditem commandtext"><a href="<\x3fphp echo App::oHREF('<##>.php?op=edit&boomerang=true&<##>_id=' . \$frm['<##>_id']); \x3f>" onClick="javascript:return confirm('<\x3fphp echo _("Notice: You are about to leave this form page and any changes you may have made without saving will be lost."); \x3f>')"><\x3fphp echo sprintf(_("Edit <##> <em>%s</em>"), \$frm['<##>']) \x3f></a></span>
     69    <span class="commanditem commandtext"><a href="<\x3fphp echo \$app->oHREF('<##>.php?op=edit&boomerang=true&<##>_id=' . \$frm['<##>_id']); \x3f>" onClick="javascript:return confirm('<\x3fphp echo _("Notice: You are about to leave this form page and any changes you may have made without saving will be lost."); \x3f>')"><\x3fphp echo sprintf(_("Edit <##> <em>%s</em>"), \$frm['<##>']) \x3f></a></span>
    7070    <\x3fphp } \x3f>
    7171E_O_F;
  • trunk/bin/module_maker/list_template.cli.php

    r121 r136  
    3030
    3131// Get DB tables.
    32 $qid = DB::query("SHOW TABLES");
     32$qid = $db->query("SHOW TABLES");
    3333while (list($row) = mysql_fetch_row($qid)) {
    3434    $tables[] = $row;
     
    3737// Make sure requested table is in database.
    3838if (!in_array($db_tbl, $tables)) {
    39     die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, App::getParam('db_name'), join("\n", $tables)));
     39    die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name'), join("\n", $tables)));
    4040}
    4141
    4242// Get DB table column info.
    43 $qid = DB::query("DESCRIBE " . DB::escapeString($db_tbl));
     43$qid = $db->query("DESCRIBE " . $db->escapeString($db_tbl));
    4444while ($row = mysql_fetch_row($qid)) {
    4545    $cols[] = $row;
     
    8080            $listrows[] = "<\x3fphp echo strlen(\$list[\$i]['$field'])<50 \x3f oTxt(\$list[\$i]['$field'], true) : oTxt(trim(substr(\$list[\$i]['$field'], 0, 50)) . '...'); \x3f>";
    8181        } else if (preg_match('/.*(begin|start).*date.*/i', $field)) {
    82             $listrows[] = "<\x3fphp echo '0000-00-00' == \$list[\$i]['$field'] ? '' : date(App::getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
     82            $listrows[] = "<\x3fphp echo '0000-00-00' == \$list[\$i]['$field'] ? '' : date(\$app->getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
    8383        } else if (preg_match('/.*(end|expire).*date.*/i', $field)) {
    84             $listrows[] = "<\x3fphp echo '9999-12-31' == \$list[\$i]['$field'] ? '' : date(App::getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
     84            $listrows[] = "<\x3fphp echo '9999-12-31' == \$list[\$i]['$field'] ? '' : date(\$app->getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
    8585        } else if (preg_match('/datetime/i', $type)) {
    86             $listrows[] = "<\x3fphp echo '0000-00-00 00:00:00' == \$list[\$i]['$field'] ? '' : date(App::getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
     86            $listrows[] = "<\x3fphp echo '0000-00-00 00:00:00' == \$list[\$i]['$field'] ? '' : date(\$app->getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
    8787        } else if (preg_match('/date/i', $type)) {
    88             $listrows[] = "<\x3fphp echo '0000-00-00' == \$list[\$i]['$field'] ? '' : date(App::getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
     88            $listrows[] = "<\x3fphp echo '0000-00-00' == \$list[\$i]['$field'] ? '' : date(\$app->getParam('date_format'), strtotime(\$list[\$i]['$field'])); \x3f>";
    8989        } else if (preg_match('/(amount|_rate)/i', $field)) {
    9090            $listrows[] = "<\x3fphp printf('$%01.2f', \$list[\$i]['$field']); \x3f>";
     
    110110<div id="commandbox">
    111111<form action="<\x3fphp echo \$_SERVER['PHP_SELF']; \x3f>" method="get">
    112 <\x3fphp App::printHiddenSession(false); \x3f>
    113     <span class="sc-nowrap commandtext"><a href="<\x3fphp echo App::oHREF(\$_SERVER['PHP_SELF'] . '?op=add'); \x3f>"><\x3fphp echo _("Add <##>"); \x3f></a></span>
     112<\x3fphp \$app->printHiddenSession(false); \x3f>
     113    <span class="sc-nowrap commandtext"><a href="<\x3fphp echo \$app->oHREF(\$_SERVER['PHP_SELF'] . '?op=add'); \x3f>"><\x3fphp echo _("Add <##>"); \x3f></a></span>
    114114    <br />
    115115
     
    149149    <\x3fphp for (\$i = 0; \$i <= \$page->last_item - \$page->first_item && \$page->total_items > 0; \$i++) { \x3f>
    150150    <tr>
    151         <td class="sc-nowrap"><a title="<\x3fphp printf(_("Edit %s"), oTxt(\$list[\$i]['<##>'])) \x3f>" href="<\x3fphp echo App::oHREF(\$_SERVER['PHP_SELF'] . '?op=edit&$primary_key=' . \$list[\$i]['$primary_key']); \x3f>"><img src="/admin/_widgets/edit.gif" alt="Edit" width="14" height="18" border="0"></a> &nbsp;</td>
    152         <td class="sc-nowrap"><a title="<\x3fphp printf(_("Versions of %s"), oTxt(\$list[\$i]['<##>'])) \x3f>" href="<\x3fphp echo App::oHREF("/admin/versions.php?record_table=$db_tbl&record_key=$primary_key&boomerang=true&record_val=" . \$list[\$i]['$primary_key']); \x3f>"><img src="/admin/_widgets/subcategory.gif" alt="" width="18" height="14" border="0" /></a> &nbsp;</td>
     151        <td class="sc-nowrap"><a title="<\x3fphp printf(_("Edit %s"), oTxt(\$list[\$i]['<##>'])) \x3f>" href="<\x3fphp echo \$app->oHREF(\$_SERVER['PHP_SELF'] . '?op=edit&$primary_key=' . \$list[\$i]['$primary_key']); \x3f>"><img src="/admin/_widgets/edit.gif" alt="Edit" width="14" height="18" border="0"></a> &nbsp;</td>
     152        <td class="sc-nowrap"><a title="<\x3fphp printf(_("Versions of %s"), oTxt(\$list[\$i]['<##>'])) \x3f>" href="<\x3fphp echo \$app->oHREF("/admin/versions.php?record_table=$db_tbl&record_key=$primary_key&boomerang=true&record_val=" . \$list[\$i]['$primary_key']); \x3f>"><img src="/admin/_widgets/subcategory.gif" alt="" width="18" height="14" border="0" /></a> &nbsp;</td>
    153153
    154154E_O_F;
     
    164164
    165165echo isset($op) ? '' : <<<E_O_F
    166         <td class="sc-nowrap" align="right"><a title="<\x3fphp printf(_("Delete %s"), oTxt(\$list[\$i]['<##>'])) \x3f>" href="<\x3fphp echo App::oHREF(\$_SERVER['PHP_SELF'] . "?op=del&$primary_key=" . \$list[\$i]['$primary_key']); \x3f>" onClick="javascript:return confirm('<\x3fphp printf(_("Are you sure you want to delete the record %s? This action is permanent and cannot be undone."), oTxt(\$list[\$i]['<##>'])) \x3f>')"><img src="/admin/_widgets/delete.gif" alt="Delete" width="16" height="17" border="0"></a> &nbsp;</td>
     166        <td class="sc-nowrap" align="right"><a title="<\x3fphp printf(_("Delete %s"), oTxt(\$list[\$i]['<##>'])) \x3f>" href="<\x3fphp echo \$app->oHREF(\$_SERVER['PHP_SELF'] . "?op=del&$primary_key=" . \$list[\$i]['$primary_key']); \x3f>" onClick="javascript:return confirm('<\x3fphp printf(_("Are you sure you want to delete the record %s? This action is permanent and cannot be undone."), oTxt(\$list[\$i]['<##>'])) \x3f>')"><img src="/admin/_widgets/delete.gif" alt="Delete" width="16" height="17" border="0"></a> &nbsp;</td>
    167167    </tr>
    168168    <\x3fphp } \x3f>
  • trunk/bin/module_maker/module.cli.php

    r119 r136  
    129129
    130130// Get DB tables.
    131 $qid = DB::query("SHOW TABLES");
     131$qid = $db->query("SHOW TABLES");
    132132while (list($row) = mysql_fetch_row($qid)) {
    133133    $tables[] = $row;
     
    136136// Make sure requested table is in database.
    137137if (!in_array($db_tbl, $tables)) {
    138     die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, App::getParam('db_name'), join("\n", $tables)));
     138    die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name'), join("\n", $tables)));
    139139}
    140140
    141141// Ensure requested table contains columns.
    142142// Get DB table column info.
    143 $qid = DB::query("DESCRIBE " . DB::escapeString($db_tbl));
     143$qid = $db->query("DESCRIBE " . $db->escapeString($db_tbl));
    144144while ($row = mysql_fetch_row($qid)) {
    145145    $cols[] = $row;
     
    266266        // If file upload errors, redirect to edit operation for the inserted record.
    267267        if (\$upload->anyErrors() || false === \$new_file) {
    268             App::dieURL(\$_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . \$%PRIMARY_KEY%);
     268            \$app->dieURL(\$_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . \$%PRIMARY_KEY%);
    269269        }
    270270E_O_F;
     
    300300
    301301$search['date'] = '/%DATE%/';
    302 $replace['date'] = date(App::getParam('date_format'));
     302$replace['date'] = date($app->getParam('date_format'));
    303303
    304304$search['name_plural'] = '/%NAME_PLURAL%/';
  • trunk/bin/module_maker/skel/adm_form.ihtml

    r51 r136  
    22
    33%ADMIN_FORM_TAG_INIT%
    4 <?php App::printHiddenSession(); ?>
     4<?php $app->printHiddenSession(); ?>
    55<input type="hidden" name="op" value="<?php echo $frm['new_op']; ?>" />
    66<input type="hidden" name="%PRIMARY_KEY%" value="<?php echo $frm['%PRIMARY_KEY%']; ?>" />
  • trunk/bin/module_maker/skel/adm_list.ihtml

    r124 r136  
    44<div id="commandbox">
    55<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
    6 <?php App::printHiddenSession(false); ?>
    7     <span class="sc-nowrap commandtext"><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=add'); ?>"><?php echo _("Add %ITEM_TITLE%"); ?></a></span>
     6<?php $app->printHiddenSession(false); ?>
     7    <span class="sc-nowrap commandtext"><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=add'); ?>"><?php echo _("Add %ITEM_TITLE%"); ?></a></span>
    88    <br />
    99
     
    1717
    1818<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    19 <?php App::printHiddenSession(); ?>
     19<?php $app->printHiddenSession(); ?>
    2020<?php include 'list_info.ihtml'; ?>
    2121<table class="list">
     
    2828    <?php for ($i = 0; $i <= $page->last_item - $page->first_item && $page->total_items > 0; $i++) { ?>
    2929    <tr>
    30         <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Edit %s"), oTxt($list[$i]['<##>'])) ?>" href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . $list[$i]['%PRIMARY_KEY%']); ?>"><img src="/admin/_widgets/edit.gif" alt="Edit" width="14" height="18" border="0"></a> &nbsp;</td>
    31         <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Versions of %s"), oTxt($list[$i]['<##>'])) ?>" href="<?php echo App::oHREF('/admin/versions.php?record_table=%DB_TBL%&record_key=%PRIMARY_KEY%&boomerang=true&record_val=' . $list[$i]['%PRIMARY_KEY%']); ?>"><img src="/admin/_widgets/subcategory.gif" alt="" width="18" height="14" border="0" /></a> &nbsp;</td>
     30        <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Edit %s"), oTxt($list[$i]['<##>'])) ?>" href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . $list[$i]['%PRIMARY_KEY%']); ?>"><img src="/admin/_widgets/edit.gif" alt="Edit" width="14" height="18" border="0"></a> &nbsp;</td>
     31        <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Versions of %s"), oTxt($list[$i]['<##>'])) ?>" href="<?php echo $app->oHREF('/admin/versions.php?record_table=%DB_TBL%&record_key=%PRIMARY_KEY%&boomerang=true&record_val=' . $list[$i]['%PRIMARY_KEY%']); ?>"><img src="/admin/_widgets/subcategory.gif" alt="" width="18" height="14" border="0" /></a> &nbsp;</td>
    3232%ADM_LIST_ROWS%
    33         <td class="sc-padleft sc-nowrap" align="right"><a title="<?php printf(_("Delete %s"), oTxt($list[$i]['<##>'])) ?>" href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . "?op=del&%PRIMARY_KEY%=" . $list[$i]['%PRIMARY_KEY%']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to delete the record %s? This action is permanent and cannot be undone."), oTxt($list[$i]['<##>'])) ?>')"><img src="/admin/_widgets/delete.gif" alt="Delete" width="16" height="17" border="0"></a> &nbsp;</td>
     33        <td class="sc-padleft sc-nowrap" align="right"><a title="<?php printf(_("Delete %s"), oTxt($list[$i]['<##>'])) ?>" href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . "?op=del&%PRIMARY_KEY%=" . $list[$i]['%PRIMARY_KEY%']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to delete the record %s? This action is permanent and cannot be undone."), oTxt($list[$i]['<##>'])) ?>')"><img src="/admin/_widgets/delete.gif" alt="Delete" width="16" height="17" border="0"></a> &nbsp;</td>
    3434    </tr>
    3535    <?php } ?>
  • trunk/bin/module_maker/skel/admin.php

    r111 r136  
    1111$auth->requireLogin();
    1212// $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%);
    13 App::sslOn();
     13$app->sslOn();
    1414
    1515require_once 'codebase/lib/PageNumbers.inc.php';
     
    3333$fv = new FormValidator();
    3434
     35$cache =& SessionCache::getInstance();
     36
    3537%SORT_ORDER%
    3638
     
    4143
    4244// Search limiters retain their values between page requests.
    43 App::carryQuery('search_query');
    44 App::carryQuery('filter_<##>');
     45$app->carryQuery('search_query');
     46$app->carryQuery('filter_<##>');
    4547%ADMIN_UPLOAD_CONFIG%
    4648/******************************************************************************
     
    5153// allows us to remember which page we came from so we can go back there.
    5254if (getFormData('boomerang', false) && isset($_SERVER['HTTP_REFERER'])) {
    53     App::setBoomerangURL($_SERVER['HTTP_REFERER'], '%NAME_PLURAL%');
     55    $app->setBoomerangURL($_SERVER['HTTP_REFERER'], '%NAME_PLURAL%');
    5456}
    5557
    5658if (getFormData('break_list_cache', false)) {
    5759    // Break the cache because we are changing the list data.
    58     SessionCache::breakCache($_SERVER['PHP_SELF']);
     60    $cache->delete($_SERVER['PHP_SELF']);
    5961}
    6062
     
    8183//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_DELETE);
    8284    deleteRecord(getFormData('%PRIMARY_KEY%'));%ADMIN_UPLOAD_DEL%
    83     if (App::validBoomerangURL('%NAME_PLURAL%')) {
     85    if ($app->validBoomerangURL('%NAME_PLURAL%')) {
    8486        // Display boomerang page.
    85         App::dieBoomerangURL('%NAME_PLURAL%');
     87        $app->dieBoomerangURL('%NAME_PLURAL%');
    8688    }
    8789    // Display default page.
    88     App::dieURL($_SERVER['PHP_SELF']);
     90    $app->dieURL($_SERVER['PHP_SELF']);
    8991    break;
    9092
     
    9294//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_ADD);
    9395    if (getFormdata('cancel', false)) {
    94         if (App::validBoomerangURL('%NAME_PLURAL%')) {
     96        if ($app->validBoomerangURL('%NAME_PLURAL%')) {
    9597            // Display boomerang page.
    96             App::dieBoomerangURL('%NAME_PLURAL%');
     98            $app->dieBoomerangURL('%NAME_PLURAL%');
    9799        }
    98100        // Display default page.
    99         App::dieURL($_SERVER['PHP_SELF']);
     101        $app->dieURL($_SERVER['PHP_SELF']);
    100102    }
    101103    validateInput();
     
    109111        if (getFormdata('repeat', false)) {
    110112            // Display function again.
    111             App::dieURL($_SERVER['PHP_SELF'] . '?op=add');
    112         } else if (App::validBoomerangURL('%NAME_PLURAL%')) {
     113            $app->dieURL($_SERVER['PHP_SELF'] . '?op=add');
     114        } else if ($app->validBoomerangURL('%NAME_PLURAL%')) {
    113115            // Display boomerang page.
    114             App::dieBoomerangURL('%NAME_PLURAL%');
     116            $app->dieBoomerangURL('%NAME_PLURAL%');
    115117        }
    116118        // Display default page.
    117         App::dieURL($_SERVER['PHP_SELF']);
     119        $app->dieURL($_SERVER['PHP_SELF']);
    118120    }
    119121    break;
     
    122124//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_EDIT);
    123125    if (getFormdata('reset', false)) {
    124         App::raiseMsg(_("Saved values have been reloaded."), MSG_NOTICE, __FILE__, __LINE__);
    125         App::dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . getFormData('%PRIMARY_KEY%'));
     126        $app->raiseMsg(_("Saved values have been reloaded."), MSG_NOTICE, __FILE__, __LINE__);
     127        $app->dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . getFormData('%PRIMARY_KEY%'));
    126128    }
    127129    if (getFormdata('cancel', false)) {
     
    129131        $lock->select('%DB_TBL%', '%PRIMARY_KEY%', getFormData('%PRIMARY_KEY%'));
    130132        $lock->remove();
    131         if (App::validBoomerangURL('%NAME_PLURAL%')) {
     133        if ($app->validBoomerangURL('%NAME_PLURAL%')) {
    132134            // Display boomerang page.
    133             App::dieBoomerangURL('%NAME_PLURAL%');
     135            $app->dieBoomerangURL('%NAME_PLURAL%');
    134136        }
    135137        // Display default page.
    136         App::dieURL($_SERVER['PHP_SELF']);
     138        $app->dieURL($_SERVER['PHP_SELF']);
    137139    }
    138140    validateInput();
     
    146148        if (getFormdata('repeat', false)) {
    147149            // Display edit function with next available ID.
    148             $qid = DB::query("SELECT %PRIMARY_KEY% FROM %DB_TBL% WHERE %PRIMARY_KEY% > '" . DB::escapeString(getFormData('%PRIMARY_KEY%')) . "' ORDER BY %PRIMARY_KEY% ASC LIMIT 1");
     150            $qid = $db->query("SELECT %PRIMARY_KEY% FROM %DB_TBL% WHERE %PRIMARY_KEY% > '" . $db->escapeString(getFormData('%PRIMARY_KEY%')) . "' ORDER BY %PRIMARY_KEY% ASC LIMIT 1");
    149151            if (list($next_id) = mysql_fetch_row($qid)) {
    150                 App::dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . $next_id);
     152                $app->dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . $next_id);
    151153            } else {
    152                 App::raiseMsg(_("Cannot edit next, the end of the list was reached"), MSG_NOTICE, __FILE__, __LINE__);
     154                $app->raiseMsg(_("Cannot edit next, the end of the list was reached"), MSG_NOTICE, __FILE__, __LINE__);
    153155            }
    154         } else if (App::validBoomerangURL('%NAME_PLURAL%')) {
     156        } else if ($app->validBoomerangURL('%NAME_PLURAL%')) {
    155157            // Display boomerang page.
    156             App::dieBoomerangURL('%NAME_PLURAL%');
     158            $app->dieBoomerangURL('%NAME_PLURAL%');
    157159        }
    158160        // Display default page.
    159         App::dieURL($_SERVER['PHP_SELF']);
     161        $app->dieURL($_SERVER['PHP_SELF']);
    160162    }
    161163    break;
     
    164166//     $auth->requireAccessClearance(ZONE_ADMIN_PROGRAMS_FUNC_REORDER);
    165167    updateRank(getFormData('rank'));
    166     App::dieURL($_SERVER['PHP_SELF']);
     168    $app->dieURL($_SERVER['PHP_SELF']);
    167169    break;
    168170
     
    207209{
    208210    global $lock;
    209 
     211    $db =& DB::getInstance();
     212   
    210213    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
    211214    if ($lock->isLocked() && !$lock->isMine()) {
     
    214217
    215218    // Get the information for the form.
    216     $qid = DB::query("
     219    $qid = $db->query("
    217220        SELECT *
    218221        FROM %DB_TBL%
    219         WHERE %PRIMARY_KEY% = '" . DB::escapeString($id) . "'
     222        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
    220223    ");
    221224    if (!$frm = mysql_fetch_assoc($qid)) {
    222         App::logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
    223         App::raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
    224         App::dieBoomerangURL();
     225        $app->logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
     226        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
     227        $app->dieBoomerangURL();
    225228    }
    226229
     
    246249{
    247250    global $lock;
    248 
     251    $db =& DB::getInstance();
     252    $cache =& SessionCache::getInstance();
     253   
    249254    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
    250255    if ($lock->isLocked() && !$lock->isMine()) {
     
    253258
    254259    // Break the cache because we are changing the list data.
    255     SessionCache::breakCache($_SERVER['PHP_SELF']);
     260    $cache->delete($_SERVER['PHP_SELF']);
    256261
    257262    // Get the information for this object.
    258     $qid = DB::query("
     263    $qid = $db->query("
    259264        SELECT <##>
    260265        FROM %DB_TBL%
    261         WHERE %PRIMARY_KEY% = '" . DB::escapeString($id) . "'
     266        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
    262267    ");
    263268    if (! list($name) = mysql_fetch_row($qid)) {
    264         App::logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
    265         App::raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
    266         App::dieBoomerangURL();
     269        $app->logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
     270        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
     271        $app->dieBoomerangURL();
    267272    }
    268273
    269274    // Delete the record.
    270     DB::query("DELETE FROM %DB_TBL% WHERE %PRIMARY_KEY% = '" . DB::escapeString($id) . "'");
    271 
    272     App::raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
     275    $db->query("DELETE FROM %DB_TBL% WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'");
     276
     277    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
    273278
    274279    // Unlock record.
     
    279284{
    280285    global $auth;
    281 
     286    $db =& DB::getInstance();
     287    $cache =& SessionCache::getInstance();
     288   
    282289    // Break the cache because we are changing the list data.
    283     SessionCache::breakCache($_SERVER['PHP_SELF']);
     290    $cache->delete($_SERVER['PHP_SELF']);
    284291
    285292%INSERT%
    286     $last_insert_id = mysql_insert_id(DB::getDBH());
     293    $last_insert_id = mysql_insert_id($db->getDBH());
    287294
    288295    // Create version.
     
    290297    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $last_insert_id, $frm['<##>']);
    291298
    292     App::raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been added."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
     299    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been added."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
    293300
    294301    return $last_insert_id;
     
    297304function updateRecord($frm)
    298305{
    299     global $auth, $lock;
    300 
     306    global $auth, $lock;
     307    $app =& App::getInstance();
     308    $cache =& SessionCache::getInstance();
     309   
    301310    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%']);
    302311    if ($lock->isLocked() && !$lock->isMine()) {
     
    305314
    306315    // Break the cache because we are changing the list data.
    307     SessionCache::breakCache($_SERVER['PHP_SELF']);
     316    $cache->delete($_SERVER['PHP_SELF']);
    308317
    309318%UPDATE%
     
    313322    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%'], $frm['<##>']);
    314323
    315     App::raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been updated."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
     324    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been updated."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
    316325
    317326    // Unlock record.
     
    323332    global $page;
    324333    global $so;
    325 
     334    $db =& DB::getInstance();
     335    $prefs =& Prefs::getInstance();
     336    $cache =& SessionCache::getInstance();
     337   
    326338    $where_clause = '';
    327339
     
    336348    if (getFormData('filter_<##>', false)) {
    337349        // Limit by filter.
    338         $where_clause .= (empty($where_clause) ? 'WHERE' : 'AND') . " <##> = '" . DB::escapeString(getFormData('filter_<##>')) . "'";
     350        $where_clause .= (empty($where_clause) ? 'WHERE' : 'AND') . " <##> = '" . $db->escapeString(getFormData('filter_<##>')) . "'";
    339351    }
    340352
    341353    // Count the total number of records so we can do something about the page numbers.
    342     $qid = DB::query("
     354    $qid = $db->query("
    343355        SELECT COUNT(*)
    344356        FROM %DB_TBL%
     
    371383    // without knowing the hash.
    372384    $cache_hash = md5($sql . '|' . $page->total_items);
    373     if (Prefs::getValue('cache_hash', $_SERVER['PHP_SELF']) != $cache_hash) {
    374         SessionCache::breakCache($_SERVER['PHP_SELF']);
    375         Prefs::setValue('cache_hash', $cache_hash, $_SERVER['PHP_SELF']);
    376     }
    377 
    378     if (SessionCache::isCached($_SERVER['PHP_SELF'])) {
     385    if ($prefs->get('cache_hash', $_SERVER['PHP_SELF']) != $cache_hash) {
     386        $cache->delete($_SERVER['PHP_SELF']);
     387        $prefs->set('cache_hash', $cache_hash, $_SERVER['PHP_SELF']);
     388    }
     389
     390    if ($cache->exists($_SERVER['PHP_SELF'])) {
    379391        // Get the cached results.
    380         $list = SessionCache::getCache($_SERVER['PHP_SELF']);
     392        $list = $cache->get($_SERVER['PHP_SELF']);
    381393    } else {
    382394        // If the list is not already cached, query now.
    383         $qid = DB::query($sql);
     395        $qid = $db->query($sql);
    384396        // Fill an array with the items for this page.
    385397        while ($row = mysql_fetch_assoc($qid)) {
     
    389401        if (isset($list) && !empty($list)) {
    390402            // Cache the results.
    391             SessionCache::putCache($list, $_SERVER['PHP_SELF']);
     403            $cache->set($list, $_SERVER['PHP_SELF']);
    392404        }
    393405    }
     
    398410function updateRank($ranks)
    399411{
     412    $db =& DB::getInstance();
     413    $cache =& SessionCache::getInstance();
     414   
    400415    if (!is_array($ranks)) {
    401         App::logMsg('Saving rank failed, data posted is not an array: ' . $ranks, LOG_ERR, __FILE__, __LINE__);
     416        $app->logMsg('Saving rank failed, data posted is not an array: ' . $ranks, LOG_ERR, __FILE__, __LINE__);
    402417        return false;
    403418    }
    404419
    405420    // Break the cache because we are changing the list data.
    406     SessionCache::breakCache($_SERVER['PHP_SELF']);
     421    $cache->delete($_SERVER['PHP_SELF']);
    407422
    408423    // Count the ranks with invalid numbers
     
    416431            $unspecified_counter++;
    417432        }
    418         DB::query("
     433        $db->query("
    419434            UPDATE %DB_TBL% SET
    420                 rank = '" . DB::escapeString($new_rank) . "'
    421             WHERE %PRIMARY_KEY% = '" . DB::escapeString($id) . "'
     435                rank = '" . $db->escapeString($new_rank) . "'
     436            WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
    422437        ");
    423438    }
    424439
    425     App::raiseMsg(_("Records have been reordered with the new rank."), MSG_SUCCESS, __FILE__, __LINE__);
     440    $app->raiseMsg(_("Records have been reordered with the new rank."), MSG_SUCCESS, __FILE__, __LINE__);
    426441    if ($unspecified_counter > 0) {
    427         App::raiseMsg(sprintf(_("%s items with unspecified ranks were automatically assigned a rank of 10000."), $unspecified_counter), MSG_NOTICE, __FILE__, __LINE__);
     442        $app->raiseMsg(sprintf(_("%s items with unspecified ranks were automatically assigned a rank of 10000."), $unspecified_counter), MSG_NOTICE, __FILE__, __LINE__);
    428443    }
    429444}
  • trunk/bin/module_maker/skel/public.ihtml

    r1 r136  
    11<p><?php echo nl2br(fancyTxt(oTxt($item['content'], true))); ?></p>
    2 <p><em><?php echo sprintf(_("Published %s"), date(App::getParam('date_format'), strtotime($item['<##>']))); ?></em></p>
     2<p><em><?php echo sprintf(_("Published %s"), date($app->getParam('date_format'), strtotime($item['<##>']))); ?></em></p>
    33
    44<!--
  • trunk/bin/module_maker/skel/public.php

    r111 r136  
    3434
    3535    // Get requested record.
    36     $qid = DB::query("
     36    $qid = $db->query("
    3737        SELECT * FROM %DB_TBL%
    38         WHERE %PRIMARY_KEY% = '" . DB::escapeString(getFormData('%PRIMARY_KEY%')) . "'
     38        WHERE %PRIMARY_KEY% = '" . $db->escapeString(getFormData('%PRIMARY_KEY%')) . "'
    3939        AND publish = 'true'
    4040        <##>AND (publish_date <= CURDATE() OR publish_date = '0000-00-00')
     
    4242    ");
    4343    if (!$item = mysql_fetch_assoc($qid)) {
    44         App::raiseMsg(_("Sorry that %ITEM_TITLE% could not be found"), MSG_WARNING, __FILE__, __LINE__);
    45         App::dieBoomerangURL();
     44        $app->raiseMsg(_("Sorry that %ITEM_TITLE% could not be found"), MSG_WARNING, __FILE__, __LINE__);
     45        $app->dieBoomerangURL();
    4646    }
    4747
    4848    // Update the hit counter for this record.
    49     DB::query("
     49    $db->query("
    5050        UPDATE %DB_TBL%
    5151        SET hit_count = hit_count + 1
    52         WHERE %PRIMARY_KEY% = '" . DB::escapeString(getFormData('%PRIMARY_KEY%')) . "'
     52        WHERE %PRIMARY_KEY% = '" . $db->escapeString(getFormData('%PRIMARY_KEY%')) . "'
    5353    ");
    5454
     
    6161    // Get the DEFAULT list.
    6262    $%NAME_SINGULAR%_list = array();
    63     $qid = DB::query("
     63    $qid = $db->query("
    6464        SELECT *
    6565        FROM %DB_TBL%
     
    7979    // Get the FEATURED list.
    8080    $featured_list = array();
    81     $qid = DB::query("
     81    $qid = $db->query("
    8282        SELECT *
    8383        FROM %DB_TBL%
     
    9292    // Get the POPULAR list.
    9393    $popular_list = array();
    94     $qid = DB::query("
     94    $qid = $db->query("
    9595        SELECT *
    9696        FROM %DB_TBL%
     
    104104    // Get the RECENT list.
    105105    $recent_list = array();
    106     $qid = DB::query("
     106    $qid = $db->query("
    107107        SELECT *
    108108        FROM %DB_TBL%
  • trunk/bin/module_maker/skel/public_list.ihtml

    r42 r136  
    55        ?>
    66        <?php if (strlen(trim($%NAME_SINGULAR%_list[$i]['content'])) > 0) { // Link only if content is available. ?>
    7             <h4><a href="<?php echo App::oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $%NAME_SINGULAR%_list[$i]['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($%NAME_SINGULAR%_list[$i]['title'])); ?></a></h4>
     7            <h4><a href="<?php echo $app->oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $%NAME_SINGULAR%_list[$i]['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($%NAME_SINGULAR%_list[$i]['title'])); ?></a></h4>
    88        <?php } else { ?>
    99            <h4><?php echo fancyTxt(oTxt($%NAME_SINGULAR%_list[$i]['title'])); ?></h4>
    1010        <?php } ?>
    1111        <p>
    12         <em><?php echo date(App::getParam('date_format'), strtotime($%NAME_SINGULAR%_list[$i]['<##>'])); ?></em> &mdash; <?php echo nl2br(fancyTxt(oTxt($%NAME_SINGULAR%_list[$i]['summary'], true))); ?>
     12        <em><?php echo date($app->getParam('date_format'), strtotime($%NAME_SINGULAR%_list[$i]['<##>'])); ?></em> &mdash; <?php echo nl2br(fancyTxt(oTxt($%NAME_SINGULAR%_list[$i]['summary'], true))); ?>
    1313
    1414        <?php if (strlen(trim($%NAME_SINGULAR%_list[$i]['content'])) > 0) { // Link only if content is available. ?>
    15             <br /><a href="<?php echo App::oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $%NAME_SINGULAR%_list[$i]['%PRIMARY_KEY%']); ?>"><?php echo _("Read more"); ?></a>
     15            <br /><a href="<?php echo $app->oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $%NAME_SINGULAR%_list[$i]['%PRIMARY_KEY%']); ?>"><?php echo _("Read more"); ?></a>
    1616        <?php } ?>
    1717        </p>
     
    3232    <?php
    3333    foreach ($featured_list as $item) {
    34         ?><h4><a href="<?php echo App::oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $item['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($item['title'])); ?></a></h4><?php
     34        ?><h4><a href="<?php echo $app->oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $item['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($item['title'])); ?></a></h4><?php
    3535    }
    3636}
     
    4444    <?php
    4545    foreach ($popular_list as $item) {
    46         ?><h4><a href="<?php echo App::oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $item['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($item['title'])); ?></a> </h4><?php
     46        ?><h4><a href="<?php echo $app->oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $item['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($item['title'])); ?></a> </h4><?php
    4747    }
    4848}
     
    5656    <?php
    5757    foreach ($recent_list as $item) {
    58         ?><h4><a href="<?php echo App::oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $item['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($item['title'])); ?></a> </h4><?php
     58        ?><h4><a href="<?php echo $app->oHREF('/%PUBLIC_SCRIPT%?%PRIMARY_KEY%=' . $item['%PRIMARY_KEY%']); ?>"><?php echo fancyTxt(oTxt($item['title'])); ?></a> </h4><?php
    5959    }
    6060}
  • trunk/bin/module_maker/sql.cli.php

    r111 r136  
    3030
    3131// Get DB tables.
    32 $qid = DB::query("SHOW TABLES");
     32$qid = $db->query("SHOW TABLES");
    3333while (list($row) = mysql_fetch_row($qid)) {
    3434    $tables[] = $row;
     
    3737// Make sure requested table is in database.
    3838if (!in_array($db_tbl, $tables)) {
    39     die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, App::getParam('db_name'), join("\n", $tables)));
     39    die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name'), join("\n", $tables)));
    4040}
    4141
     
    4646
    4747// Get DB table column info.
    48 $qid = DB::query("DESCRIBE " . DB::escapeString($db_tbl));
     48$qid = $db->query("DESCRIBE " . $db->escapeString($db_tbl));
    4949while ($row = mysql_fetch_row($qid)) {
    5050    $cols[] = $row;
     
    7676        } else if ('added_by_user_id' == $field || 'modified_by_user_id' == $field) {
    7777            // Toggle types.
    78             $c[$field] = "'\" . DB::escapeString(\$auth->getVal('user_id')) . \"'";
     78            $c[$field] = "'\" . \$db->escapeString(\$auth->getVal('user_id')) . \"'";
    7979        } else if ('added_datetime' == $field || 'modified_datetime' == $field) {
    8080            // DB record insertion datetime.
     
    8282        } else {
    8383            // Default. Just insert data.
    84             $c[$field] = "'\" . DB::escapeString(\$frm['$field']) . \"'";
     84            $c[$field] = "'\" . \$db->escapeString(\$frm['$field']) . \"'";
    8585        }
    8686    }
     
    107107echo <<<E_O_F
    108108    // Insert record data.
    109     DB::query("
     109    \$db->query("
    110110        INSERT INTO $db_tbl (
    111111            $db_keys
     
    133133echo <<<E_O_F
    134134    // Update record data.
    135     DB::query("
     135    \$db->query("
    136136        UPDATE $db_tbl SET$key_eq_val
    137         WHERE $primary_key = '" . DB::escapeString(\$frm['$primary_key']) . "'
     137        WHERE $primary_key = '" . \$db->escapeString(\$frm['$primary_key']) . "'
    138138    ");
    139139E_O_F;
     
    148148$delim = 'WHERE';
    149149if (!empty($primary_key)) {
    150     $where_clause = "            $delim $primary_key = '\" . DB::escapeString(\$frm['$primary_key']) . \"'\n";
     150    $where_clause = "            $delim $primary_key = '\" . \$db->escapeString(\$frm['$primary_key']) . \"'\n";
    151151    $delim = 'AND';
    152152}
     
    155155        continue;
    156156    }
    157     $where_clause .= "            $delim $k = '\" . DB::escapeString(\$frm['$k']) . \"'\n";
     157    $where_clause .= "            $delim $k = '\" . \$db->escapeString(\$frm['$k']) . \"'\n";
    158158    $delim = 'AND';
    159159}
    160160echo <<<E_O_F
    161161        // Delete record data.
    162         DB::query("
     162        \$db->query("
    163163            DELETE FROM $db_tbl
    164164$where_clause        ");
     
    183183if (!isset($op) || 'search' == $op) {
    184184$search_skip_columns = array('added_datetime', 'added_by_user_id', 'modified_datetime', 'modified_by_user_id', 'publish', 'featured');
    185 $search_columns = $db_tbl . '.' . join(" LIKE '%\" . DB::escapeString(\$qry_words[\$i]) . \"%'\n                    OR $db_tbl.", array_diff(array_keys($c), $search_skip_columns));
     185$search_columns = $db_tbl . '.' . join(" LIKE '%\" . \$db->escapeString(\$qry_words[\$i]) . \"%'\n                    OR $db_tbl.", array_diff(array_keys($c), $search_skip_columns));
    186186echo <<<E_O_F
    187187            \$where_clause .= (empty(\$where_clause) ? 'WHERE' : 'AND') . "
    188188                (
    189                     $search_columns LIKE '%" . DB::escapeString(\$qry_words[\$i]) . "%'
     189                    $search_columns LIKE '%" . \$db->escapeString(\$qry_words[\$i]) . "%'
    190190                )
    191191            ";
  • trunk/bin/module_maker/validation.cli.php

    r111 r136  
    1717
    1818// Get DB tables.
    19 $qid = DB::query("SHOW TABLES");
     19$qid = $db->query("SHOW TABLES");
    2020while (list($row) = mysql_fetch_row($qid)) {
    2121    $tables[] = $row;
     
    2424// Make sure requested table is in database.
    2525if (!in_array($db_tbl, $tables)) {
    26     die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, App::getParam('db_name'), join("\n", $tables)));
     26    die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name'), join("\n", $tables)));
    2727}
    2828
    2929// Get DB table column info.
    30 $qid = DB::query("DESCRIBE " . DB::escapeString($db_tbl));
     30$qid = $db->query("DESCRIBE " . $db->escapeString($db_tbl));
    3131while ($row = mysql_fetch_row($qid)) {
    3232    $cols[] = $row;
     
    277277// natsort($o);
    278278
     279// Remove last empty element.
     280if ('' == end($o)) {
     281    array_pop($o);
     282}
     283
    279284echo "function validateInput()
    280285{
    281286    global \$fv;
    282287
    283     ";
    284 echo join("\n    ", $o);
    285 echo "
     288    " . join("\n    ", $o) . "
    286289}";
    287290?>
  • trunk/docs/coding_standards.txt

    r121 r136  
    183183        ?>
    184184        <div align="right" class="sc-tiny">
    185         [&nbsp;<a href="<?php echo App::oHREF('contact.php') ?>">Contact us</a>&nbsp;]
     185        [&nbsp;<a href="<?php echo $app->oHREF('contact.php') ?>">Contact us</a>&nbsp;]
    186186        </div>
    187187        <?php
     
    214214    function getSetEnumFieldValues()
    215215    {
    216         $qid = DB::query("SHOW COLUMNS FROM $db_table LIKE '$db_col'",false);
     216        $db =& DB::getInstance();
     217       
     218        $qid = $db->query("SHOW COLUMNS FROM $db_table LIKE '$db_col'",false);
    217219
    218220        $row = mysql_fetch_row($qid);
  • trunk/docs/example_config.inc.php

    r101 r136  
    7070// DB credentials for command line scripts stored in a file with read rights
    7171// given only to the user who will be executing the scripts: -rw-------
    72 // This file includes App:: method calls so must be included after App.
     72// This file includes $app-> method calls so must be included after App.
    7373require_once 'global/db_auth.inc.php';
    7474
     75// Start application-based functionality: database, session, environment, ini setup, etc.
    7576// Most configuration parameters must be set before starting the App.
    7677$app->start();
     78
     79// Global DB object. Automatically preconfigured by $app->start().
     80$db =& DB::getInstance();
    7781
    7882// User authentication.
  • trunk/docs/example_script_template.php

    r21 r136  
    1111
    1212$auth->requireLogin();
    13 App::sslOn();
     13$app->sslOn();
    1414
    1515require_once 'codebase/lib/FormValidator.inc.php';
  • trunk/docs/file_layout.txt

    r42 r136  
    5555        RecordVersion.inc.php (db record versioning system)
    5656        ScriptTimer.inc.php (timer for scripts)
    57         SessionCache.inc.php (class for accessing a cache in a users session, stores any variables for quick retreival)
     57        Cache.inc.php (class for accessing a cache in a users session, stores any variables for quick retreival)
    5858        SortOrder.inc.php (class dealing with sorting of columns in database generated lists)
    5959        SpellCheck.inc.php
  • trunk/docs/revision_history.txt

    r124 r136  
    3131    - RecordLock
    3232    - RecordVersion
    33     - SessionCache
     33    - Cache
    3434    - Upload
    3535
     
    5656    - app object can be accessed globally without reference to object name by calling methods statically, e.g. App:logMsg()
    5757    - seperate application and codebase parameters from site configuration variables.
    58       Use $app->getParam('var') or App::getParam('var') to get app params.
     58      Use $app->getParam('var') or $app->getParam('var') to get app params.
    5959      F or site configurations do whatever you want (I'm using $cfg['node']['features'] format for configurations)
    6060
     
    6868
    6969DB object:
    70     - Self contained class for DB functions. db::query is the only necessary function. Maintains connections and state independent of App.
     70    - Self contained class for DB functions. $db->query is the only necessary function. Maintains connections and state independent of App.
    7171
    7272Full test suite for all codebase libraries. Run from the command line: "codebase/tests/run_tests.sh;"
  • trunk/lib/App.inc.php

    r124 r136  
    77 *
    88 * @author  Quinn Comendant <quinn@strangecode.com>
    9  * @version 2.0
     9 * @version 2.1
    1010 */
    1111
     
    2222class App {
    2323
    24     // Name of this application.
    25     var $app = '_app_';
    26 
    27     // If App::start has run successfully.
     24    // Namespace of this application instance.
     25    var $_ns;
     26
     27    // If $app->start has run successfully.
    2828    var $running = false;
    2929
     
    3434    var $_carry_queries = array();
    3535
    36     // Hash of global application parameters.
     36    // Dictionary of global application parameters.
    3737    var $_params = array();
    3838
     
    4545        'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here.
    4646
    47         // The location the user will go if the system doesn't knew where else to send them.
     47        // The location the user will go if the system doesn't know where else to send them.
    4848        'redirect_home_url' => '/',
    4949
    50         // SSL URL used when redirecting with App::sslOn().
     50        // SSL URL used when redirecting with $app->sslOn().
    5151        'ssl_domain' => null,
    5252        'ssl_enabled' => false,
     
    8686        'db_create_tables' => true,
    8787
    88         // The level of error reporting. Don't set this to 0 to suppress messages, instead use display_errors to control display.
     88        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
    8989        'error_reporting' => E_ALL,
    9090
     
    9999
    100100        // General application log.
    101         'log_filename' => 'app_error_log',
     101        'log_filename' => 'app_log',
    102102
    103103        // Logging priority can be any of the following, or false to deactivate:
     
    122122
    123123        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
     124        // Existing password hashes rely on the same key/salt being used to compare encryptions.
     125        // Don't change this unless you know existing hashes or signatures will not be affected!
    124126        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
    125127    );
     
    128130     * This method enforces the singleton pattern for this class. Only one application is running at a time.
    129131     *
    130      * @return  object  Reference to the global SessionCache object.
     132     * $param   string  $namespace  Name of this application.
     133     * @return  object  Reference to the global Cache object.
    131134     * @access  public
    132135     * @static
    133136     */
    134     function &getInstance($app=null)
     137    function &getInstance($namespace='')
    135138    {
    136139        static $instance = null;
    137140
    138141        if ($instance === null) {
    139             $instance = new App($app);
     142            $instance = new App($namespace);
    140143        }
    141144
     
    146149     * Constructor.
    147150     */
    148     function App($app=null)
    149     {
    150         if (isset($app)) {
    151             $this->app .= $app;
    152         }
     151    function App($namespace='')
     152    {
     153        // Set namespace of application instance.
     154        $this->_ns = '_app_' . $namespace;
    153155
    154156        // Initialize default parameters.
     
    164166    function setParam($param=null)
    165167    {
    166         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    167             $_this =& App::getInstance();
    168         }
    169 
    170168        if (isset($param) && is_array($param)) {
    171169            // Merge new parameters with old overriding only those passed.
    172             $_this->_params = array_merge($_this->_params, $param);
     170            $this->_params = array_merge($this->_params, $param);
    173171        }
    174172    }
     
    181179     * @return  mixed               Parameter value, or null if not existing.
    182180     */
    183     function &getParam($param=null)
    184     {
    185         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    186             $_this =& App::getInstance();
    187         }
    188 
     181    function getParam($param=null)
     182    {
    189183        if ($param === null) {
    190             return $_this->_params;
    191         } else if (isset($_this->_params[$param])) {
    192             return $_this->_params[$param];
     184            return $this->_params;
     185        } else if (isset($this->_params[$param])) {
     186            return $this->_params[$param];
    193187        } else {
    194188            trigger_error(sprintf('Parameter is not set: %s', $param), E_USER_NOTICE);
     
    239233            }
    240234
    241             // The only instance of the DB object.
     235            // There will ever only be one instance of the DB object, and here is where it is instantiated.
    242236            require_once dirname(__FILE__) . '/DB.inc.php';
    243 
    244237            $this->db =& DB::getInstance();
    245 
    246238            $this->db->setParam(array(
    247239                'db_server' => $this->getParam('db_server'),
     
    270262        if (true === $this->getParam('enable_session')) {
    271263
    272             // Set the session ID to one provided in GET/POST. This is necessary for linking
    273             // between domains and keeping the same session.
    274             if ($ses = getFormData($this->getParam('session_name'), false)) {
    275                 session_id($ses);
    276             }
    277 
    278264            if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) {
    279265                // Database session handling.
     
    295281            session_start();
    296282
    297             if (!isset($_SESSION[$this->app])) {
     283            if (!isset($_SESSION[$this->_ns])) {
    298284                // Access session data using: $_SESSION['...'].
    299285                // Initialize here _after_ session has started.
    300                 $_SESSION[$this->app] = array(
     286                $_SESSION[$this->_ns] = array(
    301287                    'messages' => array(),
    302288                    'boomerang' => array('url'),
     
    324310        // Character set. This should also be printed in the html header template.
    325311        header('Content-type: text/html; charset=' . $this->getParam('character_set'));
     312       
     313        // Set the version of the codebase we're using.
     314        $codebase_version_file = dirname(__FILE__) . '/../docs/version.txt';
     315        if (is_readable($codebase_version_file)) {
     316            $codebase_version = trim(file_get_contents($codebase_version_file));
     317            header('X-Codebase-Version: ' . $codebase_version);
     318            define('CODEBASE_VERSION', $codebase_version);
     319        }
    326320
    327321        $this->running = true;
     
    360354    function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
    361355    {
    362         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    363             $_this =& App::getInstance();
    364         }
    365 
    366356        $message = trim($message);
    367357
    368         if (!$_this->running || '' == $message) {
    369             $_this->logMsg(sprintf('Canceled method call %s, application not running or message is an empty string.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     358        if (!$this->running || '' == $message) {
     359            $this->logMsg(sprintf('Canceled method call %s, application not running or message is an empty string.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    370360            return false;
    371361        }
     
    373363        // Save message in session under unique key to avoid duplicate messages.
    374364        $msg_id = md5($type . $message . $file . $line);
    375         $_SESSION[$_this->app]['messages'][$msg_id] = array(
     365        $_SESSION[$this->_ns]['messages'][$msg_id] = array(
    376366            'type'    => $type,
    377367            'message' => $message,
    378368            'file'    => $file,
    379369            'line'    => $line,
    380             'count'   => (isset($_SESSION[$_this->app]['messages'][$msg_id]['count']) ? (1 + $_SESSION[$_this->app]['messages'][$msg_id]['count']) : 1)
     370            'count'   => (isset($_SESSION[$this->_ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION[$this->_ns]['messages'][$msg_id]['count']) : 1)
    381371        );
    382372
    383373        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
    384             $_this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_DEBUG, __FILE__, __LINE__);
     374            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__);
    385375        }
    386376    }
     
    396386    function getRaisedMessages()
    397387    {
    398         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    399             $_this =& App::getInstance();
    400         }
    401 
    402         if (!$_this->running) {
    403             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
    404             return false;
    405         }
    406        
    407         $output = array();
    408         while (isset($_SESSION[$_this->app]['messages']) && $message = array_shift($_SESSION[$_this->app]['messages'])) {
    409             $output[] = $message;
    410         }
    411         return $output;
     388        if (!$this->running) {
     389            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
     390            return false;
     391        }
     392
     393        return isset($_SESSION[$this->_ns]['messages']) ? $_SESSION[$this->_ns]['messages'] : array();
    412394    }
    413395   
     
    421403    function clearRaisedMessages()
    422404    {
    423         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    424             $_this =& App::getInstance();
    425         }
    426 
    427         if (!$_this->running) {
    428             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     405        if (!$this->running) {
     406            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    429407            return false;
    430408        }
    431409       
    432         $_SESSION[$_this->app]['messages'] = array();
     410        $_SESSION[$this->_ns]['messages'] = array();
    433411    }
    434412
     
    442420    function printRaisedMessages()
    443421    {
    444         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    445             $_this =& App::getInstance();
    446         }
    447 
    448         if (!$_this->running) {
    449             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
    450             return false;
    451         }
    452 
    453         while (isset($_SESSION[$_this->app]['messages']) && $message = array_shift($_SESSION[$_this->app]['messages'])) {
     422        if (!$this->running) {
     423            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
     424            return false;
     425        }
     426       
     427        $messages = $this->getRaisedMessages();
     428        foreach ($messages as $m) {
    454429            ?><div class="sc-msg"><?php
    455             if (error_reporting() > 0 && $_this->getParam('display_errors')) {
    456                 echo "\n<!-- [" . $message['file'] . ' : ' . $message['line'] . '] -->';
    457             }
    458             switch ($message['type']) {
     430            if (error_reporting() > 0 && $this->getParam('display_errors') && isset($m['file']) && isset($m['line'])) {
     431                echo "\n<!-- [" . $m['file'] . ' : ' . $m['line'] . '] -->';
     432            }
     433            switch ($m['type']) {
    459434            case MSG_ERR:
    460                 echo '<div class="sc-msg-error">' . $message['message'] . '</div>';
     435                echo '<div class="sc-msg-error">' . $m['message'] . '</div>';
    461436                break;
    462437
    463438            case MSG_WARNING:
    464                 echo '<div class="sc-msg-warning">' . $message['message'] . '</div>';
     439                echo '<div class="sc-msg-warning">' . $m['message'] . '</div>';
    465440                break;
    466441
    467442            case MSG_SUCCESS:
    468                 echo '<div class="sc-msg-success">' . $message['message'] . '</div>';
     443                echo '<div class="sc-msg-success">' . $m['message'] . '</div>';
    469444                break;
    470445
    471446            case MSG_NOTICE:
    472447            default:
    473                 echo '<div class="sc-msg-notice">' . $message['message'] . '</div>';
     448                echo '<div class="sc-msg-notice">' . $m['message'] . '</div>';
    474449                break;
    475450
     
    477452            ?></div><?php
    478453        }
     454        $this->clearRaisedMessages();
    479455    }
    480456
     
    501477        static $previous_events = array();
    502478
    503         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    504             $_this =& App::getInstance();
    505         }
    506 
    507479        // If priority is not specified, assume the worst.
    508         if (!$_this->logPriorityToString($priority)) {
    509             $_this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
     480        if (!$this->logPriorityToString($priority)) {
     481            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
    510482            $priority = LOG_EMERG;
    511483        }
    512484
    513485        // If log file is not specified, don't log to a file.
    514         if (!$_this->getParam('log_directory') || !$_this->getParam('log_filename') || !is_dir($_this->getParam('log_directory')) || !is_writable($_this->getParam('log_directory'))) {
    515             $_this->setParam(array('log_file_priority' => false));
    516             // We must use trigger_error to report this problem rather than calling App::logMsg, which might lead to an infinite loop.
    517             trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $_this->getParam('log_directory')), E_USER_NOTICE);
     486        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
     487            $this->setParam(array('log_file_priority' => false));
     488            // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop.
     489            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
    518490        }
    519491
     
    531503            $previous_events[$msg_id]++;
    532504            if ($previous_events[$msg_id] == 2) {
    533                 $_this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
     505                $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
    534506            }
    535507            return false;
     
    543515            'remote ip' => getRemoteAddr(),
    544516            'pid'       => (substr(PHP_OS, 0, 3) != 'WIN' ? posix_getpid() : ''),
    545             'type'      => $_this->logPriorityToString($priority),
     517            'type'      => $this->logPriorityToString($priority),
    546518            'file:line' => "$file : $line",
    547519            'url'       => (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''),
     
    550522
    551523        // FILE ACTION
    552         if ($_this->getParam('log_file_priority') && $priority <= $_this->getParam('log_file_priority')) {
     524        if ($this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
    553525            $event_str = '[' . join('] [', $event) . ']';
    554             error_log($event_str . "\n", 3, $_this->getParam('log_directory') . '/' . $_this->getParam('log_filename'));
     526            error_log($event_str . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
    555527        }
    556528
    557529        // EMAIL ACTION
    558         if ($_this->getParam('log_email_priority') && $priority <= $_this->getParam('log_email_priority')) {
     530        if ($this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) {
    559531            $subject = sprintf('[%s %s] %s', getenv('HTTP_HOST'), $event['type'], $message);
    560532            $email_msg = sprintf("A %s log event occured on %s\n\n", $event['type'], getenv('HTTP_HOST'));
     
    563535                $email_msg .= sprintf("%-11s%s\n", $k, $v);
    564536            }
    565             mail($_this->getParam('log_to_email_address'), $subject, $email_msg, $headers, '-f codebase@strangecode.com');
     537            mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers, '-f codebase@strangecode.com');
    566538        }
    567539
    568540        // SMS ACTION
    569         if ($_this->getParam('log_sms_priority') && $priority <= $_this->getParam('log_sms_priority')) {
     541        if ($this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority')) {
    570542            $subject = sprintf('[%s %s]', getenv('HTTP_HOST'), $priority);
    571543            $sms_msg = sprintf('%s [%s:%s]', $event['message'], basename($file), $line);
    572544            $headers = "From: codebase@strangecode.com";
    573             mail($_this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers, '-f codebase@strangecode.com');
     545            mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers, '-f codebase@strangecode.com');
    574546        }
    575547
    576548        // SCREEN ACTION
    577         if ($_this->getParam('log_screen_priority') && $priority <= $_this->getParam('log_screen_priority')) {
     549        if ($this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
    578550            echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n";
    579551        }
     
    610582    /**
    611583     * Sets which query arguments will be carried persistently between requests.
    612      * Values in the _carry_queries array will be copied to URLs (via App::url()) and
     584     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
    613585     * to hidden input values (via printHiddenSession()).
    614586     *
     
    620592    function carryQuery($query_key)
    621593    {
    622         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    623             $_this =& App::getInstance();
    624         }
    625 
    626594        // If not already set, and there is a non-empty value provided in the request...
    627         if (!isset($_this->_carry_queries[$query_key]) && getFormData($query_key, false)) {
     595        if (!isset($this->_carry_queries[$query_key]) && getFormData($query_key, false)) {
    628596            // Copy the value of the specified query argument into the _carry_queries array.
    629             $_this->_carry_queries[$query_key] = getFormData($query_key);
     597            $this->_carry_queries[$query_key] = getFormData($query_key);
    630598        }
    631599    }
     
    652620    function url($url, $carry_args=null, $always_include_sid=false)
    653621    {
    654         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    655             $_this =& App::getInstance();
    656         }
    657 
    658         if (!$_this->running) {
    659             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     622        if (!$this->running) {
     623            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    660624            return false;
    661625        }
     
    691655        if ($do_carry_queries) {
    692656            // Join the global _carry_queries and local one_time_carry_queries.
    693             $query_args = urlEncodeArray(array_merge($_this->_carry_queries, $one_time_carry_queries));
     657            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
    694658            foreach ($query_args as $key=>$val) {
    695659                // Check value is set and value does not already exist in the url.
     
    715679                    (
    716680                        !isset($_COOKIE[session_name()])
    717                         || !$_this->getParam('session_use_cookies')
     681                        || !$this->getParam('session_use_cookies')
    718682                    )
    719                     && $_this->getParam('enable_session')
     683                    && $this->getParam('enable_session')
    720684                    && isMyDomain($url)
    721685                    &&
     
    738702
    739703    /**
    740      * Returns a HTML-friendly URL processed with App::url and & replaced with &amp;
     704     * Returns a HTML-friendly URL processed with $app->url and & replaced with &amp;
    741705     *
    742706     * @access  public
    743707     * @param   string  $url    Input URL to parse.
    744      * @return  string          URL with App::url() and htmlentities() applied.
     708     * @return  string          URL with $app->url() and htmlentities() applied.
    745709     * @author  Quinn Comendant <quinn@strangecode.com>
    746710     * @since   09 Dec 2005 17:58:45
     
    748712    function oHREF($url, $carry_args=null, $always_include_sid=false)
    749713    {
    750         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    751             $_this =& App::getInstance();
    752         }
    753 
    754         $url = $_this->url($url, $carry_args, $always_include_sid);
     714        $url = $this->url($url, $carry_args, $always_include_sid);
    755715
    756716        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
     
    772732    function printHiddenSession($carry_args=null)
    773733    {
    774         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    775             $_this =& App::getInstance();
    776         }
    777 
    778         if (!$_this->running) {
    779             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     734        if (!$this->running) {
     735            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    780736            return false;
    781737        }
     
    808764            // Join the global _carry_queries and local one_time_carry_queries.
    809765            // urlencode is not used here, not for form data!
    810             $query_args = array_merge($_this->_carry_queries, $one_time_carry_queries);
     766            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
    811767            foreach ($query_args as $key=>$val) {
    812                 echo '<input type="hidden" name="' . $key . '" value="' . $val . '" />';
     768                printf('<input type="hidden" name="%s" value="%s" />', $key, $val);
    813769            }
    814770        }
     
    816772        // Include the SID if cookies are disabled.
    817773        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
    818             echo '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />';
     774            printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id());
    819775        }
    820776    }
     
    829785     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
    830786     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
    831      *                                          -array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
     787     *                                          -array('key1' => 'value', key2' => 'value')  <-- to set keys to default values if not present in form data.
    832788     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
    833789     * @param   bool    $always_include_sid     Force session id to be added to Location header.
     
    835791    function dieURL($url, $carry_args=null, $always_include_sid=false)
    836792    {
    837         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    838             $_this =& App::getInstance();
    839         }
    840 
    841         if (!$_this->running) {
    842             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     793        if (!$this->running) {
     794            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    843795            return false;
    844796        }
     
    846798        if ('' == $url) {
    847799            // If URL is not specified, use the redirect_home_url.
    848             $url = $_this->getParam('redirect_home_url');
     800            $url = $this->getParam('redirect_home_url');
    849801        }
    850802
     
    856808        }
    857809
    858         $url = $_this->url($url, $carry_args, $always_include_sid);
     810        $url = $this->url($url, $carry_args, $always_include_sid);
    859811
    860812        header(sprintf('Location: %s', $url));
    861         $_this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
     813        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
    862814
    863815        // End this application.
    864816        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
    865         $_this->stop();
     817        $this->stop();
    866818        die;
    867819    }
    868820
    869821    /*
    870     * Redirects a user by calling App::dieURL(). It will use:
     822    * Redirects a user by calling $app->dieURL(). It will use:
    871823    * 1. the stored boomerang URL, it it exists
    872824    * 2. a specified $default_url, it it exists
     
    876828    * @access   public
    877829    * @param    string  $id             Identifier for this script.
    878     * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see App::oHREF()).
     830    * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see $app->oHREF()).
    879831    * @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
    880832    * @return   bool                    False if the session is not running. No return otherwise.
     
    884836    function dieBoomerangURL($id=null, $carry_args=null, $default_url=null)
    885837    {
    886         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    887             $_this =& App::getInstance();
    888         }
    889 
    890         if (!$_this->running) {
    891             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     838        if (!$this->running) {
     839            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    892840            return false;
    893841        }
    894842
    895843        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
    896         if ($_this->validBoomerangURL($id, true)) {
    897             if (isset($id) && isset($_SESSION[$_this->app]['boomerang']['url'][$id])) {
    898                 $url = $_SESSION[$_this->app]['boomerang']['url'][$id];
    899                 $_this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     844        if ($this->validBoomerangURL($id, true)) {
     845            if (isset($id) && isset($_SESSION[$this->_ns]['boomerang']['url'][$id])) {
     846                $url = $_SESSION[$this->_ns]['boomerang']['url'][$id];
     847                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    900848            } else {
    901                 $url = end($_SESSION[$_this->app]['boomerang']['url']);
    902                 $_this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     849                $url = end($_SESSION[$this->_ns]['boomerang']['url']);
     850                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    903851            }
    904852            // Delete stored boomerang.
    905             $_this->deleteBoomerangURL($id);
     853            $this->deleteBoomerangURL($id);
    906854        } else if (isset($default_url)) {
    907855            $url = $default_url;
     
    909857            // Ensure that the redirecting page is not also the referrer.
    910858            $url = getenv('HTTP_REFERER');
    911             $_this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     859            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    912860        } else {
    913861            // If URL is not specified, use the redirect_home_url.
    914             $url = $_this->getParam('redirect_home_url');
    915             $_this->logMsg(sprintf('dieBoomerangURL(%s) not found, using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     862            $url = $this->getParam('redirect_home_url');
     863            $this->logMsg(sprintf('dieBoomerangURL(%s) not found, using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    916864        }
    917865
    918866        // A redirection will never happen immediately twice.
    919867        // Set the time so ensure this doesn't happen.
    920         $_SESSION[$_this->app]['boomerang']['time'] = time();
    921         $_this->dieURL($url, $carry_args);
    922     }
    923 
    924     /**
    925      * Set the URL to return to when App::dieBoomerangURL() is called.
     868        $_SESSION[$this->_ns]['boomerang']['time'] = time();
     869        $this->dieURL($url, $carry_args);
     870    }
     871
     872    /**
     873     * Set the URL to return to when $app->dieBoomerangURL() is called.
    926874     *
    927875     * @param string  $url  A fully validated URL.
     
    931879    function setBoomerangURL($url=null, $id=null)
    932880    {
    933         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    934             $_this =& App::getInstance();
    935         }
    936 
    937         if (!$_this->running) {
    938             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     881        if (!$this->running) {
     882            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    939883            return false;
    940884        }
    941885        // A redirection will never happen immediately after setting the boomerangURL.
    942         // Set the time so ensure this doesn't happen. See App::validBoomerangURL for more.
     886        // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more.
    943887
    944888        if ('' != $url && is_string($url)) {
     
    946890            $url = preg_replace('/boomerang=[\w]+/', '', $url);
    947891
    948             if (isset($_SESSION[$_this->app]['boomerang']['url']) && is_array($_SESSION[$_this->app]['boomerang']['url']) && !empty($_SESSION[$_this->app]['boomerang']['url'])) {
     892            if (isset($_SESSION[$this->_ns]['boomerang']['url']) && is_array($_SESSION[$this->_ns]['boomerang']['url']) && !empty($_SESSION[$this->_ns]['boomerang']['url'])) {
    949893                // If the URL currently exists in the boomerang array, delete.
    950                 while ($existing_key = array_search($url, $_SESSION[$_this->app]['boomerang']['url'])) {
    951                     unset($_SESSION[$_this->app]['boomerang']['url'][$existing_key]);
     894                while ($existing_key = array_search($url, $_SESSION[$this->_ns]['boomerang']['url'])) {
     895                    unset($_SESSION[$this->_ns]['boomerang']['url'][$existing_key]);
    952896                }
    953897            }
    954898
    955899            if (isset($id)) {
    956                 $_SESSION[$_this->app]['boomerang']['url'][$id] = $url;
     900                $_SESSION[$this->_ns]['boomerang']['url'][$id] = $url;
    957901            } else {
    958                 $_SESSION[$_this->app]['boomerang']['url'][] = $url;
    959             }
    960             $_this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     902                $_SESSION[$this->_ns]['boomerang']['url'][] = $url;
     903            }
     904            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    961905            return true;
    962906        } else {
    963             $_this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
     907            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
    964908            return false;
    965909        }
     
    973917    function getBoomerangURL($id=null)
    974918    {
    975         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    976             $_this =& App::getInstance();
    977         }
    978 
    979         if (!$_this->running) {
    980             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
     919        if (!$this->running) {
     920            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
    981921            return false;
    982922        }
    983923
    984924        if (isset($id)) {
    985             if (isset($_SESSION[$_this->app]['boomerang']['url'][$id])) {
    986                 return $_SESSION[$_this->app]['boomerang']['url'][$id];
     925            if (isset($_SESSION[$this->_ns]['boomerang']['url'][$id])) {
     926                return $_SESSION[$this->_ns]['boomerang']['url'][$id];
    987927            } else {
    988928                return '';
    989929            }
    990         } else if (is_array($_SESSION[$_this->app]['boomerang']['url'])) {
    991             return end($_SESSION[$_this->app]['boomerang']['url']);
     930        } else if (is_array($_SESSION[$this->_ns]['boomerang']['url'])) {
     931            return end($_SESSION[$this->_ns]['boomerang']['url']);
    992932        } else {
    993933            return false;
     
    1002942    function deleteBoomerangURL($id=null)
    1003943    {
    1004         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    1005             $_this =& App::getInstance();
    1006         }
    1007 
    1008         if (!$_this->running) {
    1009             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
    1010             return false;
    1011         }
    1012 
    1013         $_this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $_this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
    1014 
    1015         if (isset($id) && isset($_SESSION[$_this->app]['boomerang']['url'][$id])) {
    1016             unset($_SESSION[$_this->app]['boomerang']['url'][$id]);
    1017         } else if (is_array($_SESSION[$_this->app]['boomerang']['url'])) {
    1018             array_pop($_SESSION[$_this->app]['boomerang']['url']);
     944        if (!$this->running) {
     945            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
     946            return false;
     947        }
     948
     949        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
     950
     951        if (isset($id) && isset($_SESSION[$this->_ns]['boomerang']['url'][$id])) {
     952            unset($_SESSION[$this->_ns]['boomerang']['url'][$id]);
     953        } else if (is_array($_SESSION[$this->_ns]['boomerang']['url'])) {
     954            array_pop($_SESSION[$this->_ns]['boomerang']['url']);
    1019955        }
    1020956    }
     
    1028964    function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
    1029965    {
    1030         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    1031             $_this =& App::getInstance();
    1032         }
    1033 
    1034         if (!$_this->running) {
    1035             $_this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_DEBUG, __FILE__, __LINE__);
    1036             return false;
    1037         }
    1038 
    1039         if (!isset($_SESSION[$_this->app]['boomerang']['url'])) {
    1040             $_this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__);
     966        if (!$this->running) {
     967            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
     968            return false;
     969        }
     970
     971        if (!isset($_SESSION[$this->_ns]['boomerang']['url'])) {
     972            $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__);
    1041973            return false;
    1042974        }
     
    1045977        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
    1046978        // or a boomerang being set.
    1047         $boomerang_time = isset($_SESSION[$_this->app]['boomerang']['time']) ? $_SESSION[$_this->app]['boomerang']['time'] : 0;
     979        $boomerang_time = isset($_SESSION[$this->_ns]['boomerang']['time']) ? $_SESSION[$this->_ns]['boomerang']['time'] : 0;
    1048980
    1049981        $url = '';
    1050         if (isset($id) && isset($_SESSION[$_this->app]['boomerang']['url'][$id])) {
    1051             $url = $_SESSION[$_this->app]['boomerang']['url'][$id];
     982        if (isset($id) && isset($_SESSION[$this->_ns]['boomerang']['url'][$id])) {
     983            $url = $_SESSION[$this->_ns]['boomerang']['url'][$id];
    1052984        } else if (!isset($id) || $use_nonspecificboomerang) {
    1053985            // Use non specific boomerang if available.
    1054             $url = end($_SESSION[$_this->app]['boomerang']['url']);
    1055         }
    1056 
    1057         $_this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     986            $url = end($_SESSION[$this->_ns]['boomerang']['url']);
     987        }
     988
     989        $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    1058990
    1059991        if ('' == $url) {
    1060             $_this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
     992            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
    1061993            return false;
    1062994        }
    1063995        if ($url == absoluteMe()) {
    1064996            // The URL we are directing to is the current page.
    1065             $_this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     997            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    1066998            return false;
    1067999        }
    10681000        if ($boomerang_time >= (time() - 2)) {
    10691001            // Last boomerang direction was more than 2 seconds ago.
    1070             $_this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__);
    1071             return false;
    1072         }
    1073 
    1074         $_this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
     1002            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__);
     1003            return false;
     1004        }
     1005
     1006        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    10751007        return true;
    10761008    }
     
    10821014    function sslOn()
    10831015    {
    1084         if (!isset($_this) || !is_a($_this, 'App') && !is_subclass_of($_this, 'App')) {
    1085             $_this =& App::getInstance();
    1086         }
    1087 
    10881016        if (function_exists('apache_get_modules')) {
    10891017            $modules = apache_get_modules();
     
    10931021        }
    10941022
    1095         if ('' == getenv('HTTPS') && $_this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
    1096             $_this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $_this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
     1023        if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
     1024            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
    10971025            // Always append session because some browsers do not send cookie when crossing to SSL URL.
    1098             $_this->dieURL('https://' . $_this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
     1026            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
    10991027        }
    11001028    }
     
    11071035    function sslOff()
    11081036    {
    1109         if (!isset($this) || !is_a($this, 'App') && !is_subclass_of($this, 'App')) {
    1110             $this =& App::getInstance();
    1111         }
    1112 
    11131037        if ('' != getenv('HTTPS')) {
    11141038            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
  • trunk/lib/Auth_File.inc.php

    r103 r136  
    11<?php
    22/**
    3  * The Auth_File:: class provides a htpasswd file implementation for
     3 * Auth_File.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * The Auth_File class provides a htpasswd file implementation for
    47 * authentication.
    58 *
     
    2427
    2528class Auth_File {
    26 
    27     var $_auth = '';
    28     var $_sess = '_auth_';
     29   
     30    // Namespace of this auth object.
     31    var $_ns;
     32   
     33    // Parameters to be specified by setParam().
    2934    var $_params = array();
    3035    var $_default_params = array(
     
    6166     * @param optional array $params  A hash containing parameters.
    6267     */
    63     function Auth_File($auth_name=null)
    64     {
    65         if (isset($auth_name)) {
    66             $this->_auth = $auth_name;
    67             $this->_sess .= $auth_name;
    68         }
     68    function Auth_File($namespace='null')
     69    {
     70        $this->_ns = '_auth_' . $namespace;
    6971
    7072        // Initialize default parameters.
     
    9597    function getParam($param)
    9698    {
     99        $app =& App::getInstance();
     100   
    97101        if (isset($this->_params[$param])) {
    98102            return $this->_params[$param];
    99103        } else {
    100             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     104            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    101105            return null;
    102106        }
     
    110114    function clearAuth()
    111115    {
    112         $_SESSION[$this->_sess] = array('authenticated' => false);
     116        $_SESSION[$this->_ns] = array('authenticated' => false);
    113117    }
    114118
     
    123127    function setVal($key, $val)
    124128    {
    125         if (!isset($_SESSION[$this->_sess]['user_data'])) {
    126             $_SESSION[$this->_sess]['user_data'] = array();
    127         }
    128         $_SESSION[$this->_sess]['user_data'][$key] = $val;
     129        if (!isset($_SESSION[$this->_ns]['user_data'])) {
     130            $_SESSION[$this->_ns]['user_data'] = array();
     131        }
     132        $_SESSION[$this->_ns]['user_data'][$key] = $val;
    129133    }
    130134
     
    139143    function getVal($key, $default='')
    140144    {
    141         if (isset($_SESSION[$this->_sess][$key])) {
    142             return $_SESSION[$this->_sess][$key];
    143         } else if (isset($_SESSION[$this->_sess]['user_data'][$key])) {
    144             return $_SESSION[$this->_sess]['user_data'][$key];
     145        if (isset($_SESSION[$this->_ns][$key])) {
     146            return $_SESSION[$this->_ns][$key];
     147        } else if (isset($_SESSION[$this->_ns]['user_data'][$key])) {
     148            return $_SESSION[$this->_ns]['user_data'][$key];
    145149        } else {
    146150            return $default;
     
    160164    function authenticate($username, $password)
    161165    {
     166        $app =& App::getInstance();
     167   
    162168        if ('' == trim($password)) {
    163             App::logMsg(_("No password provided for authentication."), LOG_INFO, __FILE__, __LINE__);
     169            $app->logMsg(_("No password provided for authentication."), LOG_INFO, __FILE__, __LINE__);
    164170            return false;
    165171        }
     
    169175
    170176        if (!isset($this->_users[$username])) {
    171             App::logMsg(_("User ID provided does not exist."), LOG_INFO, __FILE__, __LINE__);
     177            $app->logMsg(_("User ID provided does not exist."), LOG_INFO, __FILE__, __LINE__);
    172178            return false;
    173179        }
    174180
    175181        if ($this->_encrypt($password, $this->_users[$username]) != $this->_users[$username]) {
    176             App::logMsg(sprintf('Authentication failed for user %s', $username), LOG_INFO, __FILE__, __LINE__);
     182            $app->logMsg(sprintf('Authentication failed for user %s', $username), LOG_INFO, __FILE__, __LINE__);
    177183            return false;
    178184        }
     
    203209        }
    204210       
    205         $_SESSION[$this->_sess] = array(
     211        $_SESSION[$this->_ns] = array(
    206212            'authenticated' => true,
    207213            'username' => $username,
     
    227233    function isLoggedIn()
    228234    {
     235        $app =& App::getInstance();
     236   
    229237        // Some users will access from networks with a changing IP number (i.e. behind a proxy server). These users must be allowed entry by adding their IP to the list of trusted_networks.
    230238        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
    231239            $user_in_trusted_network = true;
    232             App::logMsg(sprintf('User %s accessing from trusted network %s', $_SESSION[$this->_sess]['username'], $trusted_net), LOG_DEBUG, __FILE__, __LINE__);
     240            $app->logMsg(sprintf('User %s accessing from trusted network %s', $_SESSION[$this->_ns]['username'], $trusted_net), LOG_DEBUG, __FILE__, __LINE__);
    233241        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
    234242            $user_in_trusted_network = true;
    235             App::logMsg(sprintf('User %s accessing from trusted network proxy.aol.com', $_SESSION[$this->_sess]['username']), LOG_DEBUG, __FILE__, __LINE__);
     243            $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com', $_SESSION[$this->_ns]['username']), LOG_DEBUG, __FILE__, __LINE__);
    236244        } else {
    237245            $user_in_trusted_network = false;
     
    239247
    240248        // Test login with information stored in session. Skip IP matching for users from trusted networks.
    241         if (isset($_SESSION[$this->_sess])
    242             && true === $_SESSION[$this->_sess]['authenticated']
    243             && !empty($_SESSION[$this->_sess]['username'])
    244             && strtotime($_SESSION[$this->_sess]['login_datetime']) > time() - $this->_params['login_timeout']
    245             && strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - $this->_params['idle_timeout']
    246             && ($_SESSION[$this->_sess]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
     249        if (isset($_SESSION[$this->_ns])
     250            && true === $_SESSION[$this->_ns]['authenticated']
     251            && !empty($_SESSION[$this->_ns]['username'])
     252            && strtotime($_SESSION[$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
     253            && strtotime($_SESSION[$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
     254            && ($_SESSION[$this->_ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
    247255        ) {
    248256            // User is authenticated!
    249             $_SESSION[$this->_sess]['last_access_datetime'] = date('Y-m-d H:i:s');
     257            $_SESSION[$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
    250258            return true;
    251         } else if (isset($_SESSION[$this->_sess]) && true === $_SESSION[$this->_sess]['authenticated']) {
    252             if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - 43200) {
     259        } else if (isset($_SESSION[$this->_ns]) && true === $_SESSION[$this->_ns]['authenticated']) {
     260            if (strtotime($_SESSION[$this->_ns]['last_access_datetime']) > time() - 43200) {
    253261                // Only raise message if last session is less than 12 hours old.
    254                 App::raiseMsg(_("Your session has closed. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
     262                $app->raiseMsg(_("Your session has closed. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
    255263            }
    256264
    257265            // Log the reason for login expiration.
    258266            $expire_reasons = array();
    259             if (empty($_SESSION[$this->_sess]['username'])) {
     267            if (empty($_SESSION[$this->_ns]['username'])) {
    260268                $expire_reasons[] = 'username not found';
    261269            }
    262             if (strtotime($_SESSION[$this->_sess]['login_datetime']) <= time() - $this->_params['login_timeout']) {
     270            if (strtotime($_SESSION[$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
    263271                $expire_reasons[] = 'login_timeout expired';
    264272            }
    265             if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
     273            if (strtotime($_SESSION[$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
    266274                $expire_reasons[] = 'idle_timeout expired';
    267275            }
    268             if ($_SESSION[$this->_sess]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
    269                 $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION[$this->_sess]['remote_ip'], getRemoteAddr());
    270             }
    271             App::logMsg(sprintf('User %s session expired: %s', $_SESSION[$this->_sess]['username'], join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
     276            if ($_SESSION[$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
     277                $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION[$this->_ns]['remote_ip'], getRemoteAddr());
     278            }
     279            $app->logMsg(sprintf('User %s session expired: %s', $_SESSION[$this->_ns]['username'], join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
    272280        }
    273281
     
    287295    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
    288296    {
     297        $app =& App::getInstance();
     298   
    289299        if (!$this->isLoggedIn()) {
    290300            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
    291             App::raiseMsg($message, $type, $file, $line);
     301            $app->raiseMsg($message, $type, $file, $line);
    292302
    293303            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
    294             App::setBoomerangURL(absoluteMe(), 'login');
    295             App::dieURL($this->_params['login_url']);
     304            $app->setBoomerangURL(absoluteMe(), 'login');
     305            $app->dieURL($this->_params['login_url']);
    296306        }
    297307    }
     
    308318    function _loadHTPasswdFile()
    309319    {
     320        $app =& App::getInstance();
     321   
    310322        static $users = null;
    311323       
    312324        if (!file_exists($this->_params['htpasswd_file'])) {
    313             App::logMsg(sprintf('htpasswd file missing or not specified: %s', $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
     325            $app->logMsg(sprintf('htpasswd file missing or not specified: %s', $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
    314326            return false;
    315327        }
     
    317329        if (!isset($users)) {
    318330            if (false === ($users = file($this->_params['htpasswd_file']))) {
    319                 App::logMsg(sprintf(_("Could not read htpasswd file: %s"), $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
     331                $app->logMsg(sprintf(_("Could not read htpasswd file: %s"), $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
    320332                return false;
    321333            }
  • trunk/lib/Auth_SQL.inc.php

    r124 r136  
    11<?php
    22/**
    3  * The Auth_SQL:: class provides a SQL implementation for authentication.
     3 * The Auth_SQL class provides a SQL implementation for authentication.
    44 *
    55 * @author  Quinn Comendant <quinn@strangecode.com>
     
    88
    99// Available encryption types for class Auth_SQL.
    10 define('AUTH_ENCRYPT_MD5', 1);
     10define('AUTH_ENCRYPT_PLAINTEXT', 1);
    1111define('AUTH_ENCRYPT_CRYPT', 2);
    1212define('AUTH_ENCRYPT_SHA1', 3);
    13 define('AUTH_ENCRYPT_PLAINTEXT', 4);
     13define('AUTH_ENCRYPT_SHA1_HARDENED', 4);
     14define('AUTH_ENCRYPT_MD5', 5);
     15define('AUTH_ENCRYPT_MD5_HARDENED', 6);
    1416
    1517require_once dirname(__FILE__) . '/Email.inc.php';
    1618
    1719class Auth_SQL {
    18 
    19     var $_auth = '';
    20     var $_sess = '_auth_';
     20       
     21    // Namespace of this auth object.
     22    var $_ns;
     23   
     24    // Static var for test.
    2125    var $_authentication_tested;
     26
     27    // Paramters to be configured by setParam.
    2228    var $_params = array();
    23 
    24     // Default param values.
    2529    var $_default_params = array(
    2630
     
    4145
    4246        // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
    43         'encryption_type' => AUTH_ENCRYPT_SHA1,
     47        // Hardened password hashes rely on the same key/salt being used to compare encryptions.
     48        // Be aware that when using one of the hardened types the App signing_key or $more_salt below cannot change!
     49        'encryption_type' => AUTH_ENCRYPT_MD5,
    4450
    4551        // The URL to the login script.
     
    9096     * @param optional array $params  A hash containing parameters.
    9197     */
    92     function Auth_SQL($auth_name=null)
    93     {
    94         if (isset($auth_name)) {
    95             $this->_auth = $auth_name;
    96             $this->_sess .= $auth_name;
    97         }
     98    function Auth_SQL($namespace='')
     99    {
     100        $app =& App::getInstance();
     101       
     102        $this->_ns = '_auth_' . $namespace;
    98103
    99104        // Initialize default parameters.
     
    101106
    102107        // Get create tables config from global context.
    103         if (!is_null(App::getParam('db_create_tables'))) {
    104             $this->setParam(array('create_table' => App::getParam('db_create_tables')));
     108        if (!is_null($app->getParam('db_create_tables'))) {
     109            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
    105110        }
    106111    }
     
    115120    function initDB($recreate_db=false)
    116121    {
     122        $app =& App::getInstance();
     123        $db =& DB::getInstance();
     124   
     125   
    117126        static $_db_tested = false;
    118127
     
    121130            // User table.
    122131            if ($recreate_db) {
    123                 DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
    124                 App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
     132                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
     133                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
    125134            }
    126135
    127136            // The minimal columns for a table compatable with the Auth_SQL class.
    128             DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
     137            $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
    129138                " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL auto_increment,
    130139                " . $this->getParam('db_username_column') . " varchar(255) NOT NULL default '',
     
    152161            )");
    153162
    154             if (!DB::columnExists($this->getParam('db_table'), array(
     163            if (!$db->columnExists($this->getParam('db_table'), array(
    155164                $this->getParam('db_primary_key'),
    156165                $this->getParam('db_username_column'),
     
    173182                'modified_datetime',
    174183            ), false, false)) {
    175                 App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
     184                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
    176185                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
    177186            }
     
    180189            if ($this->getParam('abuse_detection')) {
    181190                if ($recreate_db) {
    182                     DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
    183                     App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_DEBUG, __FILE__, __LINE__);
     191                    $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
     192                    $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_DEBUG, __FILE__, __LINE__);
    184193                }
    185                 DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_login_table') . " (
     194                $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_login_table') . " (
    186195                    " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL default '0',
    187196                    login_datetime datetime NOT NULL default '0000-00-00 00:00:00',
     
    192201                )");
    193202
    194                 if (!DB::columnExists($this->getParam('db_login_table'), array(
     203                if (!$db->columnExists($this->getParam('db_login_table'), array(
    195204                    $this->getParam('db_primary_key'),
    196205                    'login_datetime',
    197206                    'remote_ip_binary',
    198207                ), false, false)) {
    199                     App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
     208                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
    200209                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), E_USER_ERROR);
    201210                }
     
    228237    function getParam($param)
    229238    {
     239        $app =& App::getInstance();
     240   
    230241        if (isset($this->_params[$param])) {
    231242            return $this->_params[$param];
    232243        } else {
    233             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     244            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    234245            return null;
    235246        }
     
    243254    function clearAuth()
    244255    {
     256        $db =& DB::getInstance();
     257   
    245258        $this->initDB();
    246259
    247         DB::query("
     260        $db->query("
    248261            UPDATE " . $this->_params['db_table'] . " SET
    249262            seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)),
     
    251264            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
    252265        ");
    253         $_SESSION[$this->_sess] = array('authenticated' => false);
     266        $_SESSION[$this->_ns] = array('authenticated' => false);
    254267    }
    255268
     
    263276    function setVal($key, $val)
    264277    {
    265         if (!isset($_SESSION[$this->_sess]['user_data'])) {
    266             $_SESSION[$this->_sess]['user_data'] = array();
    267         }
    268         $_SESSION[$this->_sess]['user_data'][$key] = $val;
     278        if (!isset($_SESSION[$this->_ns]['user_data'])) {
     279            $_SESSION[$this->_ns]['user_data'] = array();
     280        }
     281        $_SESSION[$this->_ns]['user_data'][$key] = $val;
    269282    }
    270283
     
    279292    function getVal($key, $default='')
    280293    {
    281         if (isset($_SESSION[$this->_sess][$key])) {
    282             return $_SESSION[$this->_sess][$key];
    283         } else if (isset($_SESSION[$this->_sess]['user_data'][$key])) {
    284             return $_SESSION[$this->_sess]['user_data'][$key];
     294        if (isset($_SESSION[$this->_ns][$key])) {
     295            return $_SESSION[$this->_ns][$key];
     296        } else if (isset($_SESSION[$this->_ns]['user_data'][$key])) {
     297            return $_SESSION[$this->_ns]['user_data'][$key];
    285298        } else {
    286299            return $default;
     
    298311    function authenticate($username, $password)
    299312    {
     313        $app =& App::getInstance();
     314        $db =& DB::getInstance();
     315
    300316        $this->initDB();
    301317
     
    303319        case AUTH_ENCRYPT_CRYPT :
    304320            // Query DB for user matching credentials. Compare cyphertext with salted-encrypted password.
    305             $qid = DB::query("
     321            $qid = $db->query("
    306322                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
    307323                FROM " . $this->_params['db_table'] . "
    308                 WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
    309                 AND BINARY userpass = ENCRYPT('" . DB::escapeString($password) . "', LEFT(userpass, 2)))
     324                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
     325                AND BINARY userpass = ENCRYPT('" . $db->escapeString($password) . "', LEFT(userpass, 2)))
    310326            ");
    311327            break;
     
    315331        default :
    316332            // Query DB for user matching credentials. Directly compare cyphertext with result from encryptPassword().
    317             $qid = DB::query("
     333            $qid = $db->query("
    318334                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
    319335                FROM " . $this->_params['db_table'] . "
    320                 WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
    321                 AND BINARY userpass = '" . DB::escapeString($this->encryptPassword($password)) . "'
     336                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
     337                AND BINARY userpass = '" . $db->escapeString($this->encryptPassword($password)) . "'
    322338            ");
    323339            break;
     
    326342        // Return user data if found.
    327343        if ($user_data = mysql_fetch_assoc($qid)) {
    328             App::logMsg(sprintf('Authentication successful for %s %s (%s)', $this->_auth, $user_data['user_id'], $username), LOG_INFO, __FILE__, __LINE__);
     344            $app->logMsg(sprintf('Authentication successful for user %s (%s)', $user_data['user_id'], $username), LOG_INFO, __FILE__, __LINE__);
    329345            return $user_data;
    330346        } else {
    331             App::logMsg(sprintf('Authentication failed for %s %s (encrypted attempted password: %s)', $this->_auth, $username, $this->encryptPassword($password)), LOG_NOTICE, __FILE__, __LINE__);
     347            $app->logMsg(sprintf('Authentication failed for user %s (encrypted attempted password: %s)', $username, $this->encryptPassword($password)), LOG_NOTICE, __FILE__, __LINE__);
    332348            return false;
    333349        }
     
    344360    function login($username, $password)
    345361    {
     362        $app =& App::getInstance();
     363        $db =& DB::getInstance();
     364   
    346365        $this->initDB();
    347366
     
    354373
    355374        // Register authenticated session.
    356         $_SESSION[$this->_sess] = array(
     375        $_SESSION[$this->_ns] = array(
    357376            'authenticated'         => true,
    358377            'user_id'               => $user_data['user_id'],
    359             'auth_name'             => $this->_auth,
    360378            'username'              => $username,
    361379            'login_datetime'        => date('Y-m-d H:i:s'),
     
    372390            if (!empty($user_data['blocked'])) {
    373391
    374                 App::logMsg(sprintf('%s %s (%s) login failed due to blocked account: %s', ucfirst($this->_auth), $this->getVal('user_id'), $this->getVal('username'), $this->getVal('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
     392                $app->logMsg(sprintf('User %s (%s) login failed due to blocked account: %s', $this->getVal('user_id'), $this->getVal('username'), $this->getVal('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
    375393
    376394                switch ($user_data['blocked_reason']) {
    377395                    case 'account abuse' :
    378                         App::raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
     396                        $app->raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
    379397                        break;
    380398                    default :
    381                         App::raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
     399                        $app->raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
    382400                        break;
    383401                }
     
    395413        **/
    396414        if ($this->getParam('abuse_detection') && !$this->getVal('login_abuse_exempt')) {
    397             $qid = DB::query("
     415            $qid = $db->query("
    398416                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
    399417                FROM " . $this->_params['db_login_table'] . "
     
    406424                    // Warn the user with a password reset.
    407425                    $this->resetPassword(null, _("This is a security precaution. We have detected this account has been accessed from multiple computers simultaneously. It is against policy to share login information with others. If further account abuse is detected this account will be blocked."));
    408                     App::raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
    409                     App::logMsg(sprintf('Account abuse detected for %s %s (%s) from IP %s', $this->_auth, $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
     426                    $app->raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
     427                    $app->logMsg(sprintf('Account abuse detected for user %s (%s) from IP %s', $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
    410428                } else {
    411429                    // Block the account with the reason of account abuse.
    412430                    $this->blockAccount(null, 'account abuse');
    413                     App::raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
    414                     App::logMsg(sprintf('Account blocked for %s %s (%s) from IP %s', $this->_auth, $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
     431                    $app->raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
     432                    $app->logMsg(sprintf('Account blocked for user %s (%s) from IP %s', $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
    415433                }
    416434                // Increment user's warning level.
    417                 DB::query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
     435                $db->query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
    418436                // Reset the login counter for this user.
    419                 DB::query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
     437                $db->query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
    420438                // No login: reset password because of account abuse!
    421439                $this->clearAuth();
     
    424442
    425443            // Update the login counter table with this login access. Convert IP to binary.
    426             DB::query("
     444            $db->query("
    427445                INSERT INTO " . $this->_params['db_login_table'] . " (
    428446                    " . $this->_params['db_primary_key'] . ",
     
    438456
    439457        // Update user table with this login.
    440         DB::query("
     458        $db->query("
    441459            UPDATE " . $this->_params['db_table'] . " SET
    442460                last_login_datetime = '" . $this->getVal('login_datetime') . "',
     
    462480    function isLoggedIn($user_id=null)
    463481    {
     482        $app =& App::getInstance();
     483        $db =& DB::getInstance();
     484   
    464485        $this->initDB();
    465486
    466487        if (isset($user_id)) {
    467488            // Check the login status of a specific user.
    468             $qid = DB::query("
     489            $qid = $db->query("
    469490                SELECT 1 FROM " . $this->_params['db_table'] . "
    470                 WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     491                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    471492                AND DATE_ADD(last_login_datetime, INTERVAL '" . $this->_params['login_timeout'] . "' SECOND) > NOW()
    472493                AND DATE_ADD(last_access_datetime, INTERVAL '" . $this->_params['idle_timeout'] . "' SECOND) > NOW()
     
    476497
    477498        // User login test need only be run once per script execution. We cache the result in the session.
    478         if ($this->_authentication_tested && isset($_SESSION[$this->_sess]['authenticated'])) {
    479             return $_SESSION[$this->_sess]['authenticated'];
     499        if ($this->_authentication_tested && isset($_SESSION[$this->_ns]['authenticated'])) {
     500            return $_SESSION[$this->_ns]['authenticated'];
    480501        }
    481502
     
    486507        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
    487508            $user_in_trusted_network = true;
    488             App::logMsg(sprintf('%s%s accessing from trusted network %s',
    489                 ucfirst($this->_auth),
     509            $app->logMsg(sprintf('User %s accessing from trusted network %s',
    490510                ($this->getVal('user_id') ? ' ' . $this->getVal('user_id') . ' (' .  $this->getVal('username') . ')' : ''),
    491511                $trusted_net
     
    493513        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
    494514            $user_in_trusted_network = true;
    495             App::logMsg(sprintf('%s%s accessing from trusted network proxy.aol.com',
    496                 ucfirst($this->_auth),
     515            $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com',
    497516                ($this->getVal('user_id') ? ' ' . $this->getVal('user_id') . ' (' .  $this->getVal('username') . ')' : '')
    498517            ), LOG_DEBUG, __FILE__, __LINE__);
     
    502521
    503522        // Test login with information stored in session. Skip IP matching for users from trusted networks.
    504         if (isset($_SESSION[$this->_sess])
    505             && true === $_SESSION[$this->_sess]['authenticated']
    506             && !empty($_SESSION[$this->_sess]['username'])
    507             && strtotime($_SESSION[$this->_sess]['login_datetime']) > time() - $this->_params['login_timeout']
    508             && strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - $this->_params['idle_timeout']
    509             && ($_SESSION[$this->_sess]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
     523        if (isset($_SESSION[$this->_ns])
     524            && true === $_SESSION[$this->_ns]['authenticated']
     525            && !empty($_SESSION[$this->_ns]['username'])
     526            && strtotime($_SESSION[$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
     527            && strtotime($_SESSION[$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
     528            && ($_SESSION[$this->_ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
    510529        ) {
    511530            // User is authenticated!
    512             $_SESSION[$this->_sess]['last_access_datetime'] = date('Y-m-d H:i:s');
     531            $_SESSION[$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
    513532
    514533            // Update the DB with the last_access_datetime and increment the seconds_online.
    515             DB::query("
     534            $db->query("
    516535                UPDATE " . $this->_params['db_table'] . " SET
    517536                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
     
    519538                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
    520539            ");
    521             if (mysql_affected_rows(DB::getDBH()) > 0) {
     540            if (mysql_affected_rows($db->getDBH()) > 0) {
    522541                // User record still exists in DB. Do this to ensure user was not delete from DB between accesses. Notice "+ 1" in SQL above to ensure record is modified.
    523542                return true;
    524543            } else {
    525                 App::logMsg(sprintf('User update failed. Record not found for %s %s (%s).', $this->_auth, $this->getVal('user_id'), $this->getVal('username')), LOG_NOTICE, __FILE__, __LINE__);
    526             }
    527         } else if (isset($_SESSION[$this->_sess]) && true === $_SESSION[$this->_sess]['authenticated']) {
     544                $app->logMsg(sprintf('User update failed. Record not found for user %s (%s).', $this->getVal('user_id'), $this->getVal('username')), LOG_NOTICE, __FILE__, __LINE__);
     545            }
     546        } else if (isset($_SESSION[$this->_ns]) && true === $_SESSION[$this->_ns]['authenticated']) {
    528547            // User is authenticated, but login has expired.
    529             if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - 43200) {
     548            if (strtotime($_SESSION[$this->_ns]['last_access_datetime']) > time() - 43200) {
    530549                // Only raise message if last session is less than 12 hours old.
    531                 App::raiseMsg(sprintf(_("Your %s session has closed. You need to log-in again."), strtolower($this->_auth)), MSG_NOTICE, __FILE__, __LINE__);
     550                $app->raiseMsg(_("Your session has expired. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
    532551            }
    533552
    534553            // Log the reason for login expiration.
    535554            $expire_reasons = array();
    536             if (empty($_SESSION[$this->_sess]['username'])) {
     555            if (empty($_SESSION[$this->_ns]['username'])) {
    537556                $expire_reasons[] = 'username not found';
    538557            }
    539             if (strtotime($_SESSION[$this->_sess]['login_datetime']) <= time() - $this->_params['login_timeout']) {
     558            if (strtotime($_SESSION[$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
    540559                $expire_reasons[] = 'login_timeout expired';
    541560            }
    542             if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
     561            if (strtotime($_SESSION[$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
    543562                $expire_reasons[] = 'idle_timeout expired';
    544563            }
    545             if ($_SESSION[$this->_sess]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
    546                 $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION[$this->_sess]['remote_ip'], getRemoteAddr());
    547             }
    548             App::logMsg(sprintf('%s %s (%s) session expired: %s', ucfirst($this->_auth), $this->getVal('user_id'), $this->getVal('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
     564            if ($_SESSION[$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
     565                $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION[$this->_ns]['remote_ip'], getRemoteAddr());
     566            }
     567            $app->logMsg(sprintf('User %s (%s) session expired: %s', $this->getVal('user_id'), $this->getVal('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
    549568        }
    550569
     
    566585    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
    567586    {
     587        $app =& App::getInstance();
     588   
    568589        if (!$this->isLoggedIn()) {
    569590            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
    570             App::raiseMsg($message, $type, $file, $line);
     591            $app->raiseMsg($message, $type, $file, $line);
    571592
    572593            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
    573             App::setBoomerangURL(absoluteMe(), 'login');
    574             App::dieURL($this->_params['login_url']);
     594            $app->setBoomerangURL(absoluteMe(), 'login');
     595            $app->dieURL($this->_params['login_url']);
    575596        }
    576597    }
     
    584605    function blockAccount($user_id=null, $reason='')
    585606    {
     607        $app =& App::getInstance();
     608        $db =& DB::getInstance();
     609   
    586610        $this->initDB();
    587611
    588612        if ($this->getParam('blocking')) {
    589             if (strlen(DB::escapeString($reason)) > 255) {
     613            if (strlen($db->escapeString($reason)) > 255) {
    590614                // blocked_reason field is varchar(255).
    591                 App::logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
     615                $app->logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
    592616            }
    593617
    594618            // Get user_id if specified.
    595619            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
    596             DB::query("
     620            $db->query("
    597621                UPDATE " . $this->_params['db_table'] . " SET
    598622                blocked = 'true',
    599                 blocked_reason = '" . DB::escapeString($reason) . "'
    600                 WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     623                blocked_reason = '" . $db->escapeString($reason) . "'
     624                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    601625            ");
    602626        }
     
    608632    function unblockAccount($user_id=null)
    609633    {
     634        $db =& DB::getInstance();
     635   
    610636        $this->initDB();
    611 
     637   
    612638        if ($this->getParam('blocking')) {
    613639            // Get user_id if specified.
    614640            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
    615             DB::query("
     641            $db->query("
    616642                UPDATE " . $this->_params['db_table'] . " SET
    617643                blocked = '',
    618644                blocked_reason = ''
    619                 WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     645                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    620646            ");
    621647        }
     
    630656    function usernameExists($username)
    631657    {
     658        $db =& DB::getInstance();
     659   
    632660        $this->initDB();
    633661
    634         $qid = DB::query("
     662        $qid = $db->query("
    635663            SELECT 1
    636664            FROM " . $this->_params['db_table'] . "
    637             WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
     665            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
    638666        ");
    639667        return (mysql_num_rows($qid) > 0);
     
    648676    function getUsername($user_id)
    649677    {
     678        $db =& DB::getInstance();
     679   
    650680        $this->initDB();
    651681
    652         $qid = DB::query("
     682        $qid = $db->query("
    653683            SELECT " . $this->_params['db_username_column'] . "
    654684            FROM " . $this->_params['db_table'] . "
    655             WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     685            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    656686        ");
    657687        if (list($username) = mysql_fetch_row($qid)) {
     
    698728    function encryptPassword($password, $salt=null)
    699729    {
     730        $app =& App::getInstance();
     731       
     732        // Existing password hashes rely on the same key/salt being used to compare encryptions.
     733        // Don't change this unless you know existing hashes or signatures will not be affected!
     734        $more_salt = 'B36D18E5-3FE4-4D58-8150-F26642852B81';
     735       
    700736        switch ($this->_params['encryption_type']) {
    701737        case AUTH_ENCRYPT_PLAINTEXT :
     
    709745
    710746        case AUTH_ENCRYPT_SHA1 :
    711             return sha1(App::getParam('signing_key') . sha1($password));
     747            return sha1($password);
    712748            break;
    713749
     750        case AUTH_ENCRYPT_SHA1_HARDENED :
     751            $hash = sha1($app->getParam('signing_key') . $password . $more_salt);
     752            // Increase key strength by 12 bits.
     753            for ($i=0; $i < 4096; $i++) {
     754                $hash = sha1($hash);
     755            }
     756            return $hash;
     757            break;
     758
    714759        case AUTH_ENCRYPT_MD5 :
     760            return md5($password);
     761            break;
     762
     763        case AUTH_ENCRYPT_MD5_HARDENED :
     764            // Include salt to improve hash
     765            $hash = md5($app->getParam('signing_key') . $password . $more_salt);
     766            // Increase key strength by 12 bits.
     767            for ($i=0; $i < 4096; $i++) {
     768                $hash = md5($hash);
     769            }
     770            return $hash;
     771            break;
    715772        default :
    716             return md5(App::getParam('signing_key') . md5($password));
     773            $app->logMsg(sprintf('Authentication encrypt type specified is unrecognized: %s', $this->_params['encryption_type']), LOG_NOTICE, __FILE__, __LINE__);
     774            return false;
    717775            break;
    718776        }
     
    724782    function setPassword($user_id=null, $password)
    725783    {
     784        $app =& App::getInstance();
     785        $db =& DB::getInstance();
     786   
    726787        $this->initDB();
    727788
     
    730791
    731792        // Issue the password change query.
    732         DB::query("
     793        $db->query("
    733794            UPDATE " . $this->_params['db_table'] . "
    734             SET userpass = '" . DB::escapeString($this->encryptPassword($password)) . "'
    735             WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     795            SET userpass = '" . $db->escapeString($this->encryptPassword($password)) . "'
     796            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    736797        ");
    737798       
    738         if (mysql_affected_rows(DB::getDBH()) != 1) {
    739             App::logMsg(sprintf('setPassword failed to update password for user %s', $user_id), LOG_NOTICE, __FILE__, __LINE__);
     799        if (mysql_affected_rows($db->getDBH()) != 1) {
     800            $app->logMsg(sprintf('setPassword failed to update password for user %s', $user_id), LOG_NOTICE, __FILE__, __LINE__);
    740801        }
    741802    }
     
    750811    function resetPassword($user_id=null, $reason='')
    751812    {
     813        $app =& App::getInstance();
     814        $db =& DB::getInstance();
     815   
    752816        $this->initDB();
    753817
     
    756820
    757821        // Reset password of a specific user.
    758         $qid = DB::query("
     822        $qid = $db->query("
    759823            SELECT * FROM " . $this->_params['db_table'] . "
    760             WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     824            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    761825        ");
    762826        if (!$user_data = mysql_fetch_assoc($qid)) {
    763             App::logMsg(sprintf('Reset password failed. %s %s not found.', ucfirst($this->_auth), $user_id), LOG_NOTICE, __FILE__, __LINE__);
     827            $app->logMsg(sprintf('Reset password failed. User %s not found.', $user_id), LOG_NOTICE, __FILE__, __LINE__);
    764828            return false;
    765829        }
     
    773837        // Make sure user has an email on record before continuing.
    774838        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
    775             App::logMsg(sprintf('Password reset but notification failed, no email address for %s %s (%s).', $this->_auth, $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
     839            $app->logMsg(sprintf('Password reset but notification failed, no email address for user %s (%s).', $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
    776840        } else {
    777841            // Body for email.
     
    794858            $email = new Email(array(
    795859                'to' => $user_data['email'],
    796                 'from' => sprintf('%s <%s>', App::getParam('site_name'), App::getParam('site_email')),
    797                 'subject' => sprintf('%s password change', App::getParam('site_name'))
     860                'from' => sprintf('%s <%s>', $app->getParam('site_name'), $app->getParam('site_email')),
     861                'subject' => sprintf('%s password change', $app->getParam('site_name'))
    798862            ));
    799863            $email->setString($email_body);
    800864            $email->replace(array(
    801                 'site_name' => App::getParam('site_name'),
    802                 'site_url' => App::getParam('site_url'),
     865                'site_name' => $app->getParam('site_name'),
     866                'site_url' => $app->getParam('site_url'),
    803867                'name' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
    804868                'username' => $user_data[$this->_params['db_username_column']],
     
    846910    function requireAccessClearance($security_zone, $message='')
    847911    {
     912        $app =& App::getInstance();
     913   
    848914        return true;
    849915        $zone_members = preg_split('/,\s*/', $security_zone);
     
    853919        if (!in_array($this->getVal('priv'), $zone_members) || !$this->getVal('priv')) {
    854920            $message = empty($message) ? _("You have insufficient privileges to view that page.") : $message;
    855             App::raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
    856             App::dieBoomerangURL();
     921            $app->raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
     922            $app->dieBoomerangURL();
    857923        }
    858924    }
  • trunk/lib/AuthorizeNet.inc.php

    r42 r136  
    11<?php
     2/**
     3 * AuthorizeNet.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * The AuthorizeNet class provides an abstract interface for communicating
     7 * with authorize.net's AIM interface. Supports Auth.Net v3.1
     8 *
     9 * @author  Quinn Comendant <quinn@strangecode.com>
     10 * @version 1.0
     11 * @date 2004-04-06
     12 */
     13 
    214// Example usage
    315// require_once 'codebase/lib/AuthorizeNet.inc.php';
     
    1426//     'x_Exp_Date' => '042008',
    1527//     'x_Invoice_Num' => '100',
    16 //     'x_Address' => '10 rue LevouvŽ',
     28//     'x_Address' => '10 rue Levouvé',
    1729//     'x_City' => 'SomeCity',
    1830//     'x_State' => 'CA',
     
    2739// }
    2840
    29 /**
    30  * The AuthorizeNet class provides an abstract interface for communicating
    31  * with authorize.net's AIM interface. Supports Auth.Net v3.1
    32  *
    33  * @author  Quinn Comendant <quinn@strangecode.com>
    34  * @version 1.0
    35  * @date 2004-04-06
    36  */
    37 
    38 require_once dirname(__FILE__) . '/Utilities.inc.php';
    39 
    40 class AuthorizeNet
    41 {
     41class AuthorizeNet {
     42
    4243    var $post_url = ''; // The URL to post data to.
    4344    var $md5_hash_value = ','; // A custom value for the response delimination character.
     
    132133    function setParam($params)
    133134    {
     135        $app =& App::getInstance();
     136   
    134137        if (isset($params) && is_array($params)) {
    135138            // Merge new parameters with old overriding only those passed.
    136139            $this->_params = array_merge($this->_params, $params);
    137140        } else {
    138             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     141            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    139142        }
    140143    }
     
    149152    function getParam($param)
    150153    {
     154        $app =& App::getInstance();
     155   
    151156        if (isset($this->_params[$param])) {
    152157            return $this->_params[$param];
    153158        } else {
    154             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     159            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    155160            return null;
    156161        }
     
    167172    function process()
    168173    {
     174        $app =& App::getInstance();
     175   
    169176        if (empty($this->_params['x_login'])) {
    170177            $this->_results['x_response_reason_text'] = _("Transaction gateway temporarily not available. Please try again later.");
    171             App::logMsg(sprintf('x_login not specified.', null), LOG_ERROR, __FILE__, __LINE__);
     178            $app->logMsg(sprintf('x_login not specified.', null), LOG_ERROR, __FILE__, __LINE__);
    172179            return false;
    173180        }
    174181        if (empty($this->_params['x_card_num'])) {
    175182            $this->_results['x_response_reason_text'] = _("Transaction gateway temporarily not available. Please try again later.");
    176             App::logMsg(sprintf('x_card_num not specified.', null), LOG_ERROR, __FILE__, __LINE__);
     183            $app->logMsg(sprintf('x_card_num not specified.', null), LOG_ERROR, __FILE__, __LINE__);
    177184            return false;
    178185        }
  • trunk/lib/CSS.inc.php

    r92 r136  
    2828    function setParam($params)
    2929    {
     30        $app =& App::getInstance();
     31   
    3032        if (isset($params) && is_array($params)) {
    3133            // Merge new parameters with old overriding only those passed.
    3234            $this->_params = array_merge($this->_params, $params);
    3335        } else {
    34             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     36            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    3537        }
    3638    }
     
    4547    function getParam($param)
    4648    {
     49        $app =& App::getInstance();
     50   
    4751        if (isset($this->_params[$param])) {
    4852            return $this->_params[$param];
    4953        } else {
    50             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     54            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    5155            return null;
    5256        }
     
    5862     * @access  public
    5963     * @param   string  $file   Include path to css files.
    60      * @param   mixed   $apps   App name string or array of app names.
     64     * @param   mixed   $realms   Realm name string or array of realm names.
    6165     * @return  bool    True on success, false on failure.
    6266     */
    63     function setFile($file, $apps='')
     67    function setFile($file, $realms='')
    6468    {
    65         if (!is_array($apps)) {
    66             $apps = array($apps);
     69        $app =& App::getInstance();
     70   
     71        if (!is_array($realms)) {
     72            $realms = array($realms);
    6773        }
    6874
    6975        if ($fp = fopen($file, 'r', true)) {
    70             foreach ($apps as $app) {
    71                 $app = '' == $app ? 'default' : $app;
    72                 $this->_css_files[$app][] = $file;
     76            foreach ($realms as $realm) {
     77                $realm = '' == $realm ? 'default' : $realm;
     78                $this->_css_files[$realm][] = $file;
    7379            }
    7480            fclose($fp);
    7581            return true;
    7682        } else {
    77             App::logMsg(sprintf('CSS file non-existent: %s', $file), LOG_ERR, __FILE__, __LINE__);
     83            $app->logMsg(sprintf('CSS file non-existent: %s', $file), LOG_ERR, __FILE__, __LINE__);
    7884            return false;
    7985        }
     
    8793     * @return  bool    False if no files have been set.
    8894     */
    89     function headers($app='')
     95    function headers($realm='')
    9096    {
    91         $app = '' == $app ? 'default' : $app;
     97        $app =& App::getInstance();
     98   
     99        $realm = '' == $realm ? 'default' : $realm;
    92100
    93         if (empty($this->_css_files[$app])) {
    94             App::logMsg(sprintf('CSS::headers called without specifying any files.', null), LOG_WARNING, __FILE__, __LINE__);
     101        if (empty($this->_css_files[$realm])) {
     102            $app->logMsg(sprintf('CSS::headers called without specifying any files.', null), LOG_WARNING, __FILE__, __LINE__);
    95103            return false;
    96104        }
     
    98106        // Get time of latest modified file, including this class file.
    99107        $files_mtime = array();
    100         foreach (array_merge($this->_css_files[$app], array(__FILE__)) as $file) {
     108        foreach (array_merge($this->_css_files[$realm], array(__FILE__)) as $file) {
    101109            $files_mtime[] = statIncludePath($file, 'mtime');
    102110        }
     
    122130     * @return  bool    False if no files have been set.
    123131     */
    124     function output($app='')
     132    function output($realm='')
    125133    {
    126         $app = '' == $app ? 'default' : $app;
     134        $realm = '' == $realm ? 'default' : $realm;
    127135
    128         if (empty($this->_css_files[$app])) {
    129             App::logMsg(sprintf('CSS::output called without specifying any files.', null), LOG_WARNING, __FILE__, __LINE__);
     136        if (empty($this->_css_files[$realm])) {
     137            $app->logMsg(sprintf('CSS::output called without specifying any files.', null), LOG_WARNING, __FILE__, __LINE__);
    130138            return false;
    131139        }
    132140
    133         foreach ($this->_css_files[$app] as $file) {
     141        foreach ($this->_css_files[$realm] as $file) {
    134142            include $file;
    135143        }
  • trunk/lib/Captcha.inc.php

    r121 r136  
    118118    function Captcha()
    119119    {
    120         $this->secret_key = App::getParam('signing_key');
     120        $app =& App::getInstance();
     121   
     122        $this->secret_key = $app->getParam('signing_key');
    121123        $this->random_number = $this->_getRandomNumber();
    122124    }
     
    133135    function getAsciiNumber($num=null)
    134136    {
     137        $app =& App::getInstance();
     138   
    135139        if (!isset($num)) {
    136140            $num = $this->random_number;
     
    138142
    139143        if (preg_match('/[^\d]/', $num)) {
    140             App::logMsg(sprintf('Bad number: %s', $num), LOG_ERR, __FILE__, __LINE__);
     144            $app->logMsg(sprintf('Bad number: %s', $num), LOG_ERR, __FILE__, __LINE__);
    141145            return false;
    142146        }
  • trunk/lib/DB.inc.php

    r119 r136  
    44 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
    55 *
    6  * DB abstraction layer.
     6 * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies.
    77 *
    88 * @author  Quinn Comendant <quinn@strangecode.com>
    9  * @version 1.0.1
     9 * @version 2.1
    1010 */
    1111
    1212class DB {
    1313
    14     // If DB::connect has successfully opened a db connection.
     14    // If $db->connect has successfully opened a db connection.
    1515    var $_connected = false;
    1616
    17     // Database handler.
     17    // Database handle.
    1818    var $dbh;
    1919
     
    3030        'db_pass' => null,
    3131
    32         // Debugging.
    33         'db_always_debug' => false, // TRUE = display all SQL queries.
    34         'db_debug' => false, // TRUE = display db errors.
    35         'db_die_on_failure' => false, // TRUE = script stops on db error.
     32        // Display all SQL queries.
     33        'db_always_debug' => false,
     34
     35        // Display db errors.
     36        'db_debug' => false,
     37       
     38        // Script stops on db error.
     39        'db_die_on_failure' => false,
    3640    );
    3741
     
    4953     * This method enforces the singleton pattern for this class.
    5054     *
    51      * @return  object  Reference to the global SessionCache object.
     55     * @return  object  Reference to the global DB object.
    5256     * @access  public
    5357     * @static
     
    6569
    6670    /**
    67      * Constructor.
    68      */
    69     function DB()
    70     {
    71         // Initialize default params.
     71     * Set (or overwrite existing) parameters by passing an array of new parameters.
     72     *
     73     * @access public
     74     *
     75     * @param  array    $params     Array of parameters (key => val pairs).
     76     */
     77    function setParam($params)
     78    {
     79        $app =& App::getInstance();
     80   
    7281        if (isset($params) && is_array($params)) {
    7382            // Merge new parameters with old overriding only those passed.
    7483            $this->_params = array_merge($this->_params, $params);
    75         }
    76     }
    77 
    78     /**
    79      * Set (or overwrite existing) parameters by passing an array of new parameters.
     84        } else {
     85            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     86        }
     87    }
     88
     89    /**
     90     * Return the value of a parameter, if it exists.
    8091     *
    8192     * @access public
    82      *
    83      * @param  array    $params     Array of parameters (key => val pairs).
    84      */
    85     function setParam($params)
    86     {
    87         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    88             $_this =& DB::getInstance();
    89         }
    90 
    91         if (isset($params) && is_array($params)) {
    92             // Merge new parameters with old overriding only those passed.
    93             $_this->_params = array_merge($_this->_params, $params);
     93     * @param string $param        Which parameter to return.
     94     * @return mixed               Configured parameter value.
     95     */
     96    function getParam($param)
     97    {
     98        $app =& App::getInstance();
     99   
     100        if (isset($this->_params[$param])) {
     101            return $this->_params[$param];
    94102        } else {
    95             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    96         }
    97     }
    98 
    99     /**
    100      * Return the value of a parameter.
    101      *
    102      * @access  public
    103      *
    104      * @param   string  $param      The key of the parameter to return.
    105      *
    106      * @return  mixed               Parameter value.
    107      */
    108     function getParam($param)
    109     {
    110         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    111             $_this =& DB::getInstance();
    112         }
    113 
    114         if (isset($_this->_params[$param])) {
    115             return $_this->_params[$param];
    116         } else {
    117             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     103            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    118104            return null;
    119105        }
     
    129115    function connect()
    130116    {
    131         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    132             $_this =& DB::getInstance();
    133         }
    134 
    135         if (!$_this->getParam('db_name') || !$_this->getParam('db_user') || !$_this->getParam('db_pass')) {
    136             App::logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
     117        $app =& App::getInstance();
     118   
     119        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
     120            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
    137121            return false;
    138122        }
    139123
    140124        // Connect to database. Always create a new link to the server.
    141         if ($_this->dbh = mysql_connect($_this->getParam('db_server'), $_this->getParam('db_user'), $_this->getParam('db_pass'), true)) {
     125        if ($this->dbh = mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
    142126            // Select database
    143             mysql_select_db($_this->getParam('db_name'), $_this->dbh);
     127            mysql_select_db($this->getParam('db_name'), $this->dbh);
    144128        }
    145129
    146130        // Test for connection errors.
    147         if (!$_this->dbh || mysql_error($_this->dbh)) {
    148             $mysql_error_msg = $_this->dbh ? 'Codebase MySQL error: (' . mysql_errno($_this->dbh) . ') ' . mysql_error($_this->dbh) : 'Codebase MySQL error: Could not connect to server.';
    149             App::logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
     131        if (!$this->dbh || mysql_error($this->dbh)) {
     132            $mysql_error_msg = $this->dbh ? 'Codebase MySQL error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : 'Codebase MySQL error: Could not connect to server.';
     133            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
    150134
    151135            // Print helpful or pretty error?
    152             if ($_this->getParam('db_debug')) {
     136            if ($this->getParam('db_debug')) {
    153137                echo $mysql_error_msg . "\n";
    154             } else {
    155                 echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
    156138            }
    157139
    158140            // Die or continue without connection?
    159             if ($_this->getParam('db_die_on_failure')) {
     141            if ($this->getParam('db_die_on_failure')) {
    160142                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
    161143                die;
     
    166148
    167149        // DB connection success!
    168         $_this->_connected = true;
     150        $this->_connected = true;
    169151
    170152        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
    171         $_this->query("/*!40101 SET NAMES '" . $_this->mysql_character_sets[strtolower(App::getParam('character_set'))] . "' */");
     153        $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[strtolower($app->getParam('character_set'))] . "' */");
    172154
    173155        return true;
     
    183165    function close()
    184166    {
    185         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    186             $_this =& DB::getInstance();
    187         }
    188 
    189         if (!$_this->_connected) {
    190             return false;
    191         }
    192 
    193         mysql_close($_this->dbh);
     167        if (!$this->_connected) {
     168            return false;
     169        }
     170
     171        return mysql_close($this->dbh);
    194172    }
    195173
     
    204182    function getDBH()
    205183    {
    206         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    207             $_this =& DB::getInstance();
    208         }
    209 
    210         if (!$_this->_connected) {
    211             return false;
    212         }
    213 
    214         return $_this->dbh;
     184        if (!$this->_connected) {
     185            return false;
     186        }
     187
     188        return $this->dbh;
    215189    }
    216190
     
    224198    function isConnected()
    225199    {
    226         return $this->_connected;
     200        return (true === $this->_connected);
    227201    }
    228202   
     
    238212    function escapeString($string)
    239213    {
    240         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    241             $_this =& DB::getInstance();
    242         }
    243         return mysql_real_escape_string($string, $_this->dbh);
     214        if (!$this->_connected) {
     215            return false;
     216        }
     217
     218        return mysql_real_escape_string($string, $this->dbh);
    244219    }
    245220
     
    253228     */
    254229    function query($query, $debug=false)
    255     {
     230    {   
    256231        static $_query_count = 0;
    257 
    258         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    259             $_this =& DB::getInstance();
    260         }
    261 
    262         if (!$_this->_connected) {
     232        $app =& App::getInstance();
     233
     234        if (!$this->_connected) {
    263235           return false;
    264236        }
     
    266238        $_query_count++;
    267239        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
    268         if ($_this->getParam('db_always_debug') || $debug) {
     240        if ($this->getParam('db_always_debug') || $debug) {
    269241            echo "<!-- ----------------- Query $_query_count ---------------------\n$debugqry\n-->\n";
    270242        }
    271243
    272244        // Execute!
    273         $qid = mysql_query($query, $_this->dbh);
     245        $qid = mysql_query($query, $this->dbh);
    274246
    275247        // Error checking.
    276         if (!$qid || mysql_error($_this->dbh)) {
    277             if ($_this->getParam('db_debug')) {
    278                 echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($_this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
     248        if (!$qid || mysql_error($this->dbh)) {
     249            if ($this->getParam('db_debug')) {
     250                echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
    279251            } else {
    280252                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
    281253            }
    282             App::logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($_this->dbh), mysql_error($_this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
    283             if ($_this->getParam('db_die_on_failure')) {
     254            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
     255            if ($this->getParam('db_die_on_failure')) {
    284256                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
    285257                die;
     
    302274    function tableExists($table, $use_cached_results=true)
    303275    {
    304         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    305             $_this =& DB::getInstance();
    306         }
    307 
    308         if (!$_this->_connected) {
    309             return false;
    310         }
    311 
    312         if (!isset($_this->existing_tables) || !$use_cached_results) {
    313             $_this->existing_tables = array();
    314             $qid = $_this->query("SHOW TABLES");
     276        $app =& App::getInstance();
     277   
     278        if (!$this->_connected) {
     279            return false;
     280        }
     281
     282        if (!isset($this->existing_tables) || !$use_cached_results) {
     283            $this->existing_tables = array();
     284            $qid = $this->query("SHOW TABLES");
    315285            while (list($row) = mysql_fetch_row($qid)) {
    316                 $_this->existing_tables[] = $row;
    317             }
    318         }
    319         if (in_array($table, $_this->existing_tables)) {
     286                $this->existing_tables[] = $row;
     287            }
     288        }
     289        if (in_array($table, $this->existing_tables)) {
    320290            return true;
    321291        } else {
    322             App::logMsg(sprintf('nonexistent DB table: %s.%s', $_this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
     292            $app->logMsg(sprintf('nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
    323293            return false;
    324294        }
     
    336306    function columnExists($table, $columns, $strict=true, $use_cached_results=true)
    337307    {
    338         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    339             $_this =& DB::getInstance();
    340         }
    341 
    342         if (!$_this->_connected) {
     308        if (!$this->_connected) {
    343309            return false;
    344310        }
    345311
    346312        // Ensure the table exists.
    347         if (!$_this->tableExists($table, $use_cached_results)) {
     313        if (!$this->tableExists($table, $use_cached_results)) {
    348314            return false;
    349315        }
     
    354320        }
    355321
    356         if (!isset($_this->table_columns[$table]) || !$use_cached_results) {
     322        if (!isset($this->table_columns[$table]) || !$use_cached_results) {
    357323            // Populate and cache array of current columns for this table.
    358             $_this->table_columns[$table] = array();
    359             $qid = $_this->query("DESCRIBE $table");
     324            $this->table_columns[$table] = array();
     325            $qid = $this->query("DESCRIBE $table");
    360326            while ($row = mysql_fetch_row($qid)) {
    361                 $_this->table_columns[$table][] = $row[0];
     327                $this->table_columns[$table][] = $row[0];
    362328            }
    363329        }
     
    366332            // Do an exact comparison of table schemas.
    367333            sort($columns);
    368             sort($_this->table_columns[$table]);
    369             return $_this->table_columns[$table] == $columns;
     334            sort($this->table_columns[$table]);
     335            return $this->table_columns[$table] == $columns;
    370336        } else {
    371337            // Only check that the specified columns are available in the table.
    372             $match_columns = array_intersect($_this->table_columns[$table], $columns);
     338            $match_columns = array_intersect($this->table_columns[$table], $columns);
    373339            sort($columns);
    374340            sort($match_columns);
  • trunk/lib/DBSessionHandler.inc.php

    r110 r136  
    33 * DBSessionHandler.inc.php
    44 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information.
     5 *
    56 * @author  Quinn Comendant <quinn@strangecode.com>
    6  * @version 1.3
     7 * @version 2.1
    78 * @since   1999
    89 */
     
    1314
    1415    var $_params = array(
    15         'db_server' => 'localhost',
    16         'db_name' => '',
    17         'db_user' => '',
    18         'db_pass' => '',
    1916        'db_table' => 'session_tbl',
    2017        'create_table' => true, // Automatically create table and verify columns. Better set to false after site launch.
     
    3027     * @since   18 Jul 2005 11:02:50
    3128     */
    32     function DBSessionHandler($db=null, $params=array())
     29    function DBSessionHandler($db, $params=array())
    3330    {
     31        $app =& App::getInstance();
     32   
    3433        $this->_params = array_merge($this->_params, $params);
    3534
    36         if (isset($db)) {
    37             if (is_a($db, 'DB')) {
    38                 if ($db->isConnected()) {
    39                     // Use existing db connection.
    40                     $this->db =& $db;
    41                 } else {
    42                     App::logMsg(sprintf('Provided DB object is not connected. %s', mysql_error($db->dbh)), LOG_ERR, __FILE__, __LINE__);
     35        if (!method_exists($db, 'isConnected')) {
     36            $app->logMsg(sprintf('Provided object (%s) is not a valid DB object.', get_class($db)), LOG_ERR, __FILE__, __LINE__);
     37        } else {
     38            if (!$db->isConnected()) {
     39                $app->logMsg('Provided DB object is not connected.', LOG_ERR, __FILE__, __LINE__);
     40            } else {
     41                // OK! We have a valid, connected DB object.
     42                $this->db =& $db;
     43
     44                // Get create tables config from global context.
     45                if (!is_null($app->getParam('db_create_tables'))) {
     46                    $this->_params['create_table'] = $app->getParam('db_create_tables');
    4347                }
    44             } else {
    45                 App::logMsg(sprintf('Provided DB object is not valid. %s', gettype($db)), LOG_ERR, __FILE__, __LINE__);
     48
     49                // Ensure db table is fit.
     50                $this->initDB();
     51
     52                ini_set('session.save_handler', 'user');
     53                session_set_save_handler(
     54                    array(&$this, 'dbSessionOpen'),
     55                    array(&$this, 'dbSessionClose'),
     56                    array(&$this, 'dbSessionRead'),
     57                    array(&$this, 'dbSessionWrite'),
     58                    array(&$this, 'dbSessionDestroy'),
     59                    array(&$this, 'dbSessionGarbage')
     60                );
    4661            }
    47         } else {
    48             // Create our own new db connection.
    49             require_once dirname(__FILE__) . '/DB.inc.php';
    50 
    51             $this->db =& new DB();
    52             $this->db->setParam(array(
    53                 'db_server' => $this->_params['db_server'],
    54                 'db_name' => $this->_params['db_name'],
    55                 'db_user' => $this->_params['db_user'],
    56                 'db_pass' => $this->_params['db_pass'],
    57                 'db_always_debug' => $this->_params['db_always_debug'],
    58                 'db_debug' => $this->_params['db_debug'],
    59                 'db_die_on_failure' => $this->_params['db_die_on_failure'],
    60             ));
    61 
    62             // Connect to database.
    63             $this->db->connect();
    6462        }
    65 
    66         if (!isset($this) || !is_a($this->db, 'DB') || !$this->db->isConnected()) {
    67             trigger_error('Invalid DB object or unable to connect to database.', E_USER_ERROR);
    68         }
    69 
    70         // Get create tables config from global context.
    71         if (!is_null(App::getParam('db_create_tables'))) {
    72             $this->_params['create_table'] = App::getParam('db_create_tables');
    73         }
    74 
    75         // Ensure db table is fit.
    76         $this->initDB();
    77 
    78         ini_set('session.save_handler', 'user');
    79         session_set_save_handler(
    80             array(&$this, 'dbSessionOpen'),
    81             array(&$this, 'dbSessionClose'),
    82             array(&$this, 'dbSessionRead'),
    83             array(&$this, 'dbSessionWrite'),
    84             array(&$this, 'dbSessionDestroy'),
    85             array(&$this, 'dbSessionGarbage')
    86         );
    8763    }
    8864
     
    9672    function initDB($recreate_db=false)
    9773    {
     74        $app =& App::getInstance();
     75   
    9876        static $_db_tested = false;
    9977
    10078        if ($recreate_db || !$_db_tested && $this->_params['create_table']) {
    10179            if ($recreate_db) {
    102                 $this->db->query("DROP TABLE IF EXISTS " . $this->_params['db_table']);
    103                 App::logMsg(sprintf('Dropping and recreating table %s.', $this->_params['db_table']), LOG_DEBUG, __FILE__, __LINE__);
     80                $this->db->query("DROP TABLE IF EXISTS " . $this->db->escapeString($this->_params['db_table']));
     81                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->_params['db_table']), LOG_DEBUG, __FILE__, __LINE__);
    10482            }
    105             $this->db->query("CREATE TABLE IF NOT EXISTS " . $this->_params['db_table'] . " (
     83            $this->db->query("CREATE TABLE IF NOT EXISTS " . $this->db->escapeString($this->_params['db_table']) . " (
    10684                session_id char(32) NOT NULL default '',
    10785                session_data mediumtext NOT NULL,
     
    11290
    11391            if (!$this->db->columnExists($this->_params['db_table'], array('session_id', 'session_data', 'last_access'))) {
    114                 App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->_params['db_table']), LOG_ALERT, __FILE__, __LINE__);
     92                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->_params['db_table']), LOG_ALERT, __FILE__, __LINE__);
    11593                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->_params['db_table']), E_USER_ERROR);
    11694            }
     
    132110    {
    133111        // Select the data belonging to session $session_id from the session table
    134         $qid = $this->db->query("SELECT session_data FROM " . $this->_params['db_table'] . " WHERE session_id = '" . $this->db->escapeString($session_id) . "'");
     112        $qid = $this->db->query("SELECT session_data FROM " . $this->db->escapeString($this->_params['db_table']) . " WHERE session_id = '" . $this->db->escapeString($session_id) . "'");
    135113
    136114        // Return the session data that was found
     
    147125    {
    148126        // Write the serialized session data ($session_data) to the session table
    149         $this->db->query("REPLACE INTO " . $this->_params['db_table'] . "(session_id, session_data, last_access) VALUES ('" . $this->db->escapeString($session_id) . "', '" . $this->db->escapeString($session_data) . "', null)");
     127        $this->db->query("REPLACE INTO " . $this->db->escapeString($this->_params['db_table']) . "(session_id, session_data, last_access) VALUES ('" . $this->db->escapeString($session_id) . "', '" . $this->db->escapeString($session_data) . "', null)");
    150128
    151129        return true;
     
    155133    {
    156134        // Delete from the table all data for the session $session_id
    157         $this->db->query("DELETE FROM " . $this->_params['db_table'] . " WHERE session_id = '" . $this->db->escapeString($session_id) . "'");
     135        $this->db->query("DELETE FROM " . $this->db->escapeString($this->_params['db_table']) . " WHERE session_id = '" . $this->db->escapeString($session_id) . "'");
    158136
    159137        return true;
     
    163141    {
    164142        // Delete old values from the session table
    165         $qid = $this->db->query("DELETE FROM " . $this->_params['db_table'] . " WHERE UNIX_TIMESTAMP(last_access) < " . (time() - $max_lifetime));
     143        $qid = $this->db->query("DELETE FROM " . $this->db->escapeString($this->_params['db_table']) . " WHERE UNIX_TIMESTAMP(last_access) < " . (time() - $max_lifetime));
    166144
    167145        return true;
  • trunk/lib/Email.inc.php

    r119 r136  
    88 * @author  Quinn Comendant <quinn@strangecode.com>
    99 * @version 1.0
    10 -------------------------------------------------------------------------------------
     10 *
     11 
    1112// Example.
    1213$email = new Email(array(
    1314    'to' => array($frm['email'], 'q@lovemachine.local'),
    14     'from' => sprintf('%s <%s>', App::getParam('site_name'), App::getParam('site_email')),
     15    'from' => sprintf('%s <%s>', $app->getParam('site_name'), $app->getParam('site_email')),
    1516    'subject' => 'Your account has been activated',
    1617));
     
    1819// $email->setString('Or you can pass your message body as a string, also with {VARIABLES}.');
    1920$email->replace(array(
    20     'site_name' => App::getParam('site_name'),
    21     'site_url' => App::getParam('site_url'),
     21    'site_name' => $app->getParam('site_name'),
     22    'site_url' => $app->getParam('site_url'),
    2223    'username' => $frm['username'],
    2324    'password' => $frm['password1'],
    2425));
    2526if ($email->send()) {
    26     App::raiseMsg(sprintf(_("A confirmation email has been sent to %s."), $frm['email']), MSG_SUCCESS, __FILE__, __LINE__);
     27    $app->raiseMsg(sprintf(_("A confirmation email has been sent to %s."), $frm['email']), MSG_SUCCESS, __FILE__, __LINE__);
    2728} else {
    28     App::logMsg(sprintf('Error sending confirmation email to address %s', $frm['email']), LOG_NOTICE, __FILE__, __LINE__);
     29    $app->logMsg(sprintf('Error sending confirmation email to address %s', $frm['email']), LOG_NOTICE, __FILE__, __LINE__);
    2930}
    30 -------------------------------------------------------------------------------------
     31
     32 *
    3133 */
    3234class Email {
     
    8890    function setParam($params)
    8991    {
     92        $app =& App::getInstance();
     93   
    9094        if (isset($params) && is_array($params)) {
    9195            // Enforce valid email addresses.
     
    100104            $this->_params = array_merge($this->_params, $params);
    101105        } else {
    102             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     106            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    103107        }
    104108    }
     
    113117    function getParam($param)
    114118    {
     119        $app =& App::getInstance();
     120   
    115121        if (isset($this->_params[$param])) {
    116122            return $this->_params[$param];
    117123        } else {
    118             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
     124            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    119125            return null;
    120126        }
     
    131137    function setTemplate($template)
    132138    {
     139        $app =& App::getInstance();
     140   
    133141        // Load file, using include_path.
    134142        if (!$this->_template = file_get_contents($template, true)) {
    135             App::logMsg(sprintf('Email template file does not exist: %s', $template), LOG_ERR, __FILE__, __LINE__);
     143            $app->logMsg(sprintf('Email template file does not exist: %s', $template), LOG_ERR, __FILE__, __LINE__);
    136144            $this->_template = null;
    137145            $this->_template_replaced = null;
     
    153161    function setString($string)
    154162    {
     163        $app =& App::getInstance();
     164   
    155165        // Load file, using include_path.
    156166        if ('' == trim($string)) {
    157             App::logMsg(sprintf('Empty string provided.', null), LOG_ERR, __FILE__, __LINE__);
     167            $app->logMsg(sprintf('Empty string provided.', null), LOG_ERR, __FILE__, __LINE__);
    158168            $this->_template_replaced = null;
    159169            return false;
     
    176186    function replace($replacements)
    177187    {
     188        $app =& App::getInstance();
     189   
    178190        // Ensure template exists.
    179191        if (!isset($this->_template)) {
    180             App::logMsg(sprintf('Cannot replace variables, no template defined.', null), LOG_ERR, __FILE__, __LINE__);
     192            $app->logMsg(sprintf('Cannot replace variables, no template defined.', null), LOG_ERR, __FILE__, __LINE__);
    181193            return false;
    182194        }
     
    184196        // Ensure replacements argument is an array.
    185197        if (!is_array($replacements)) {
    186             App::logMsg(sprintf('Cannot replace variables, invalid replacements.', null), LOG_ERR, __FILE__, __LINE__);
     198            $app->logMsg(sprintf('Cannot replace variables, invalid replacements.', null), LOG_ERR, __FILE__, __LINE__);
    187199            return false;
    188200        }
     
    211223    function send($to=null, $from=null, $subject=null, $headers=null)
    212224    {
     225        $app =& App::getInstance();
     226   
    213227        // Use arguments if provided.
    214228        if (isset($to)) {
     
    227241        // Ensure required values exist.
    228242        if (!isset($this->_params['subject'])) {
    229             App::logMsg(sprintf('Cannot send email to %s. SUBJECT not defined.', $this->_params['to']), LOG_ERR, __FILE__, __LINE__);
     243            $app->logMsg(sprintf('Cannot send email to %s. SUBJECT not defined.', $this->_params['to']), LOG_ERR, __FILE__, __LINE__);
    230244            return false;
    231245        } else if (!isset($this->_template)) {
    232             App::logMsg(sprintf('Cannot send email: "%s". Template not set.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
     246            $app->logMsg(sprintf('Cannot send email: "%s". Template not set.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
    233247            return false;
    234248        } else if (!isset($this->_params['to'])) {
    235             App::logMsg(sprintf('Cannot send email: "%s". TO not defined.', $this->_params['subject']), LOG_NOTICE, __FILE__, __LINE__);
     249            $app->logMsg(sprintf('Cannot send email: "%s". TO not defined.', $this->_params['subject']), LOG_NOTICE, __FILE__, __LINE__);
    236250            return false;
    237251        } else if (!isset($this->_params['from'])) {
    238             App::logMsg(sprintf('Cannot send email: "%s". FROM not defined.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
     252            $app->logMsg(sprintf('Cannot send email: "%s". FROM not defined.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
    239253            return false;
    240254        }
     
    245259        // Ensure all placeholders have been replaced. Find anything with {...} characters.
    246260        if (preg_match('/({[^}]+})/', $final_body, $unreplaced_match)) {
    247             App::logMsg(sprintf('Cannot send email. Variables left unreplaced in template: %s', (isset($unreplaced_match[1]) ? $unreplaced_match[1] : '')), LOG_ERR, __FILE__, __LINE__);
     261            $app->logMsg(sprintf('Cannot send email. Variables left unreplaced in template: %s', (isset($unreplaced_match[1]) ? $unreplaced_match[1] : '')), LOG_ERR, __FILE__, __LINE__);
    248262            return false;
    249263        }
     
    273287        $full_mail_content = join("\n", array($final_to, $this->_params['subject'], $final_body, $final_headers, $envelope_sender_header));
    274288        if (preg_match("/(Content-Type:|MIME-Version:|Content-Transfer-Encoding:|[\n\r]Bcc:|[\n\r]Cc:)/i", $full_mail_content)) {
    275             App::logMsg(sprintf('Mail header injection attack in content: %s', $full_mail_content), LOG_WARNING, __FILE__, __LINE__);
     289            $app->logMsg(sprintf('Mail header injection attack in content: %s', $full_mail_content), LOG_WARNING, __FILE__, __LINE__);
    276290            sleep(3);
    277291            return false;
     
    280294        // Ensure message was successfully accepted for delivery.
    281295        if (mail($final_to, $this->_params['subject'], $final_body, $final_headers, $envelope_sender_header)) {
    282             App::logMsg(sprintf('Email successfully sent to %s', $final_to), LOG_DEBUG, __FILE__, __LINE__);
     296            $app->logMsg(sprintf('Email successfully sent to %s', $final_to), LOG_DEBUG, __FILE__, __LINE__);
    283297            return true;
    284298        } else {
    285             App::logMsg(sprintf('Email failure with parameters: %s, %s, %s, %s', $final_to, $this->_params['subject'], str_replace("\r\n", '\r\n', $final_headers), $envelope_sender_header), LOG_NOTICE, __FILE__, __LINE__);
     299            $app->logMsg(sprintf('Email failure with parameters: %s, %s, %s, %s', $final_to, $this->_params['subject'], str_replace("\r\n", '\r\n', $final_headers), $envelope_sender_header), LOG_NOTICE, __FILE__, __LINE__);
    286300            return false;
    287301        }
     
    305319    function validEmail($email)
    306320    {
     321        $app =& App::getInstance();
     322   
    307323        // If an array, check values recursively.
    308324        if (is_array($email)) {
     
    318334                return true;
    319335            } else {
    320                 App::logMsg(sprintf('Invalid email: %s', $email), LOG_INFO, __FILE__, __LINE__);
     336                $app->logMsg(sprintf('Invalid email: %s', $email), LOG_INFO, __FILE__, __LINE__);
    321337                return false;
    322338            }
  • trunk/lib/FormValidator.inc.php

    r121 r136  
    44 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
    55 *
    6  * The FormValidator:: class provides a method for validating input from
     6 * The FormValidator class provides a method for validating input from
    77 * http requests and displaying errors.
    88 *
     
    1010 * @version   1.8
    1111 *
    12  * Examples of use:
    13  *
    14  * require_once 'codebase/lib/FormValidator.inc.php';
    15  * $fv = new FormValidator();
    16  *
    17  * $fv->isEmpty('location_name', _("<strong>Location name</strong> cannot be blank."));
    18  * $fv->checkRegex('cc_exp', '/^\d{4}$|^$/', true, _("CC exp date must be in MMYY format."));
    19  * $fv->isInteger('client_id', _("<strong>Client id</strong> must be an integer."));
    20  * $fv->numericRange('client_id', -32768, 32767, _("<strong>Client id</strong> must be a number between -32768 and 32767."));
    21  * $fv->stringLength('zip', 0, 255, _("<strong>Zip</strong> must contain less than 256 characters."));
    22  * $fv->validateEmail('invoice_email');
    23  * $fv->validatePhone('phone1');
     12 * Example of use:
     13---------------------------------------------------------------------
     14// The object that validates form input.
     15require_once 'codebase/lib/FormValidator.inc.php';
     16$fv = new FormValidator();
     17
     18$fv->isEmpty('field_name', sprintf(_("%s cannot be blank."), _("Field name")));
     19$fv->stringLength('field_name', 0, 255, sprintf(_("%s must be %f-to-%f characters in length."), _("Field name"), 0, 255));
     20$fv->isInteger('field_name', sprintf(_("%s must be an integer."), _("Field name")));
     21$fv->checkRegex('field_name', '/^\d{4}$|^$/', true, sprintf(_("%s must be in MMYY format."), _("Field name")));
     22$fv->numericRange('field_name', 0, 65535, sprintf(_("%s must be a number between %f and %f."), _("Field name"), 0, 65535));
     23$fv->validatePhone('field_name');
     24$fv->validateEmail('field_name');
     25$fv->validateStrDate('field_name', sprintf(_("%s must be a valid date in YYYY-MM-DD format."), _("Field name")));
     26if (is_null($var)) {
     27    $fv->addError('field_name', sprintf(_("%s is invalid."), _("Field name")));
     28}
     29if ($fv->anyErrors()) {
     30    // Errors!
     31}
     32---------------------------------------------------------------------
    2433 */
    25 class FormValidator
    26 {
     34class FormValidator {
    2735
    2836    // Array filling with error messages.
     
    103111    function printErrorMessages()
    104112    {
     113        $app =& App::getInstance();
    105114        if ($this->anyErrors()) {
    106115            ?><div class="sc-msg"><?php
    107116            $errors = $this->getErrorList();
    108             foreach ($errors as $err) {
    109                 if (!empty($err['message']) && is_string($err['message'])) {
    110                     if (error_reporting() > 0 && isset($err['file']) && isset($err['line'])) {
    111                         echo "\n<!-- [" . $err['file'] . ' : ' . $err['line'] . '] -->';
     117            foreach ($errors as $e) {
     118                if ('' != $e['message'] && is_string($e['message'])) {
     119                    if (error_reporting() > 0 && $app->getParam('display_errors') && isset($e['file']) && isset($e['line'])) {
     120                        echo "\n<!-- [" . $e['file'] . ' : ' . $e['line'] . '] -->';
    112121                    }
    113                     switch ($err['type']) {
     122                    switch ($e['type']) {
    114123                    case MSG_ERR:
    115                         echo '<div class="sc-msg-error">' . $err['message'] . '</div>';
     124                        echo '<div class="sc-msg-error">' . $e['message'] . '</div>';
    116125                        break;
    117126
    118127                    case MSG_WARNING:
    119                         echo '<div class="sc-msg-warning">' . $err['message'] . '</div>';
     128                        echo '<div class="sc-msg-warning">' . $e['message'] . '</div>';
    120129                        break;
    121130
    122131                    case MSG_SUCCESS:
    123                         echo '<div class="sc-msg-success">' . $err['message'] . '</div>';
     132                        echo '<div class="sc-msg-success">' . $e['message'] . '</div>';
    124133                        break;
    125134
    126135                    case MSG_NOTICE:
    127136                    default:
    128                         echo '<div class="sc-msg-notice">' . $err['message'] . '</div>';
     137                        echo '<div class="sc-msg-notice">' . $e['message'] . '</div>';
    129138                        break;
    130139                    }
     
    389398    function validateEmail($form_name)
    390399    {
     400        $app =& App::getInstance();
     401   
    391402        $email = getFormData($form_name);
    392403        if ('' == trim($email)) {
     
    400411        if (!preg_match($e->getParam('regex'), $email, $e_parts)) {
    401412            $this->addError($form_name, sprintf(_("<strong>%s</strong> is not a valid email address."), oTxt($email)));
    402             App::logMsg(sprintf('The email address %s is not valid.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
     413            $app->logMsg(sprintf('The email address %s is not valid.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
    403414            return false;
    404415        }
     
    412423        if (strlen($local) > 64 || strlen($domain) > 191) {
    413424            $this->addError($form_name, sprintf(_("<strong>Email address</strong> must contain less than 256 characters."), oTxt($email)));
    414             App::logMsg(sprintf('The email address %s must contain less than 256 characters.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
     425            $app->logMsg(sprintf('The email address %s must contain less than 256 characters.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
    415426            return false;
    416427        }
     
    420431        if ((ip2long($domain) == '-1' || ip2long($domain) === false) && function_exists('checkdnsrr') && !checkdnsrr($domain . '.', 'MX') && gethostbyname($domain) == $domain) {
    421432            $this->addError($form_name, sprintf(_("<strong>%s</strong> is not a valid email domain name"), oTxt($domain)));
    422             App::logMsg(sprintf('The email address %s contains an invalid email domain name (%s).', getFormData($form_name), $domain), LOG_INFO, __FILE__, __LINE__);
     433            $app->logMsg(sprintf('The email address %s contains an invalid email domain name (%s).', getFormData($form_name), $domain), LOG_INFO, __FILE__, __LINE__);
    423434            return false;
    424435        }
     
    454465    function validateStrDate($form_name, $msg='')
    455466    {
     467        $app =& App::getInstance();
     468   
    456469        if (($timestamp = strtotime(getFormData($form_name, '0'))) === -1) {
    457470            $this->addError($form_name, $msg);
    458             App::logMsg(sprintf('The string date %s is not valid.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
     471            $app->logMsg(sprintf('The string date %s is not valid.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
    459472            return false;
    460473        } else {
     
    530543        for ($i=0; $i<$num; $i++) {
    531544            // Get each digit.
    532             $digit = substr($cc_num,$i,1);
     545            $digit = substr($cc_num, $i, 1);
    533546
    534547            //  If it's an odd digit, double it.
     
    539552            //  If the result is two digits, add them.
    540553            if (strlen($digit) == 2) {
    541                 $digit = substr($digit,0,1) + substr($digit,1,1);
     554                $digit = substr($digit, 0, 1) + substr($digit, 1, 1);
    542555            }
    543556
     
    556569
    557570    /**
    558      * Check whether uploaded file is valid.
     571     * Check whether a file was selected for uploading. If file is missing, it's an error.
    559572     *
    560573     * @param  string $form_name the name of the incoming form variable
     
    565578    function validateFile($form_name, $msg='')
    566579    {
    567         if (isset($_FILES[$form_name]['tmp_name']) && '' == trim($_FILES[$form_name]['tmp_name'])) {
     580        if (!isset($_FILES[$form_name]['tmp_name']) || '' == trim($_FILES[$form_name]['tmp_name'])) {
    568581            $this->addError($form_name, $msg);
    569582            return false;
  • trunk/lib/Google_API.inc.php

    r42 r136  
    11<?php
    22/**
     3 * Google_API.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
    36 * Interface to the Google API using SOAP/Client.php.
    47 *
     
    2528require_once 'SOAP/Client.php';
    2629
    27 
    28 /**
    29 * PHP Interface to the Google API
    30 *
    31 * @author  Sebastian Bergmann <sb@sebastian-bergmann.de>
    32 * @access  public
    33 */
    34 class Google_API
    35 {
     30class Google_API {
    3631
    3732    /**
  • trunk/lib/Hierarchy.inc.php

    r111 r136  
    22/**
    33 * Hierarchy.inc.php
    4  * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
    5  */
    6 
    7 /**
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
    86 * Objective: This class provides the tools to organize pieces of data into a
    97 * hierarchy of nodes. Any form of data (article, product, image) can be
     
    9795    function toStringID($child_type=null, $child_id=null)
    9896    {
    99         if (!isset($child_type) || !isset($child_id)) {
    100             if ($this->node_init) {
    101                 $child_type =& $this->child_type;
    102                 $child_id =& $this->child_id;
    103             } else {
    104                 App::logMsg(_("toStringID failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     97            $app =& App::getInstance();
     98   
     99            if (!isset($child_type) || !isset($child_id)) {
     100            if ($this->node_init) {
     101                $child_type =& $this->child_type;
     102                $child_id =& $this->child_id;
     103            } else {
     104                $app->logMsg(_("toStringID failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    105105                return false;
    106106            }
     
    129129    function toArrayID(&$node)
    130130    {
    131         if (preg_match('/^([[:alnum:]]+)__-?([[:digit:]]+)$/', $node, $node_parts)) {
     131            $app =& App::getInstance();
     132   
     133            if (preg_match('/^([[:alnum:]]+)__-?([[:digit:]]+)$/', $node, $node_parts)) {
    132134            return array('node_type' => $node_parts[1], 'node_id' => $node_parts[2]);
    133135        } else {
    134             App::logMsg(_("Cannot parse node identifier, not formated correctly."), LOG_ERR, __FILE__, __LINE__);
     136            $app->logMsg(_("Cannot parse node identifier, not formated correctly."), LOG_ERR, __FILE__, __LINE__);
    135137            return false;
    136138        }
     
    147149    function insertNode($parents, $child_type=null, $child_id=null, $relationship_type=null, $title='')
    148150    {
     151        $app =& App::getInstance();
     152        $db =& DB::getInstance();
     153   
    149154        if (!isset($child_type) || !isset($child_id)) {
    150155            if ($this->node_init) {
     
    152157                $child_id =& $this->child_id;
    153158            } else {
    154                 App::logMsg(_("insertNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     159                $app->logMsg(_("insertNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    155160                return false;
    156161            }
     
    159164        // Make sure this is not empty and an array, even if it has only one value.
    160165        if ('' == $parents) {
    161             App::raiseMsg(sprintf(_("Cannot add node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), MSG_ERR, __FILE__, __LINE__);
    162             App::logMsg(sprintf(_("Cannot add node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), LOG_ERR, __FILE__, __LINE__);
     166            $app->raiseMsg(sprintf(_("Cannot add node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), MSG_ERR, __FILE__, __LINE__);
     167            $app->logMsg(sprintf(_("Cannot add node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), LOG_ERR, __FILE__, __LINE__);
    163168            return false;
    164169        } else if (!is_array($parents)) {
     
    174179            $parent = $this->toArrayID($parent_string);
    175180            if ($this->nodeExists($child_type, $child_id, $parent['node_type'], $parent['node_id'], $relationship_type)) {
    176                 App::raiseMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to parent <strong>%s %s</strong>. It already exists there"), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
    177                 App::logMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to parent <strong>%s %s</strong>. It already exists there"), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
     181                $app->raiseMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to parent <strong>%s %s</strong>. It already exists there"), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
     182                $app->logMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to parent <strong>%s %s</strong>. It already exists there"), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
    178183                return false;
    179184            }
    180185            if (!$this->nodeExists($parent['node_type'], $parent['node_id'])) {
    181                 App::raiseMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
    182                 App::logMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
     186                $app->raiseMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
     187                $app->logMsg(sprintf(_("Cannot add node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
    183188                return false;
    184189            }
     
    188193        foreach ($parents as $parent_string) {
    189194            $parent = $this->toArrayID($parent_string);
    190             DB::query("
     195            $db->query("
    191196                INSERT INTO node_tbl (
    192197                    parent_type,
     
    197202                    title
    198203                ) VALUES (
    199                     '" . DB::escapeString($parent['node_type']) . "',
    200                     '" . DB::escapeString($parent['node_id']) . "',
    201                     '" . DB::escapeString($child_type) . "',
    202                     '" . DB::escapeString($child_id) . "',
    203                     " . (is_null($relationship_type) ? "NULL" : "'" . DB::escapeString($relationship_type) . "'") . ",
    204                     '" . DB::escapeString($title) . "'
     204                    '" . $db->escapeString($parent['node_type']) . "',
     205                    '" . $db->escapeString($parent['node_id']) . "',
     206                    '" . $db->escapeString($child_type) . "',
     207                    '" . $db->escapeString($child_id) . "',
     208                    " . (is_null($relationship_type) ? "NULL" : "'" . $db->escapeString($relationship_type) . "'") . ",
     209                    '" . $db->escapeString($title) . "'
    205210                )
    206211            ");
    207             App::logMsg(sprintf('insertNode: Added node %s %s with parent %s %s.', $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_DEBUG, __FILE__, __LINE__);
     212            $app->logMsg(sprintf('insertNode: Added node %s %s with parent %s %s.', $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_DEBUG, __FILE__, __LINE__);
    208213        }
    209214        return true;
     
    223228    function deleteNode($child_type=null, $child_id=null)
    224229    {
     230        $app =& App::getInstance();
     231        $db =& DB::getInstance();
     232   
    225233        if (!isset($child_type) || !isset($child_id)) {
    226234            if ($this->node_init) {
     
    228236                $child_id =& $this->child_id;
    229237            } else {
    230                 App::logMsg(_("deleteNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     238                $app->logMsg(_("deleteNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    231239                return false;
    232240            }
     
    243251        }
    244252
    245         DB::query("
     253        $db->query("
    246254            DELETE FROM node_tbl
    247             WHERE child_type = '" . DB::escapeString($child_type) . "'
    248             AND child_id = '" . DB::escapeString($child_id) . "'
     255            WHERE child_type = '" . $db->escapeString($child_type) . "'
     256            AND child_id = '" . $db->escapeString($child_id) . "'
    249257        ");
    250         App::logMsg(sprintf('deleteNode: Deleted node %s %s.', $child_type, $child_id), LOG_DEBUG, __FILE__, __LINE__);
     258        $app->logMsg(sprintf('deleteNode: Deleted node %s %s.', $child_type, $child_id), LOG_DEBUG, __FILE__, __LINE__);
    251259
    252260        return true;
     
    270278    function moveNode($new_parents=null, $child_type=null, $child_id=null, $relationship_type=null, $title='')
    271279    {
    272         if (!isset($child_type) || !isset($child_id)) {
    273             if ($this->node_init) {
    274                 $child_type =& $this->child_type;
    275                 $child_id =& $this->child_id;
    276             } else {
    277                 App::logMsg(_("moveNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     280            $app =& App::getInstance();
     281            $db =& DB::getInstance();
     282
     283            if (!isset($child_type) || !isset($child_id)) {
     284            if ($this->node_init) {
     285                $child_type =& $this->child_type;
     286                $child_id =& $this->child_id;
     287            } else {
     288                $app->logMsg(_("moveNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    278289                return false;
    279290            }
     
    282293        // Make sure this is not empty and an array, even if it has only one value.
    283294        if (empty($new_parents)) {
    284             App::raiseMsg(sprintf(_("Cannot move node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), MSG_ERR, __FILE__, __LINE__);
    285             App::logMsg(sprintf(_("Cannot move node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), LOG_ERR, __FILE__, __LINE__);
     295            $app->raiseMsg(sprintf(_("Cannot move node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), MSG_ERR, __FILE__, __LINE__);
     296            $app->logMsg(sprintf(_("Cannot move node <strong>%s %s</strong>, no parent was specified."), $child_type, $child_id), LOG_ERR, __FILE__, __LINE__);
    286297            return false;
    287298        } else if (!is_array($new_parents)) {
     
    296307            $parent = $this->toArrayID($parent_string);
    297308            if (!$this->nodeExists($parent['node_type'], $parent['node_id'])) {
    298                 App::raiseMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
    299                 App::logMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
     309                $app->raiseMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
     310                $app->logMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to nonexistent parent <strong>%s %s</strong>."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
    300311                return false;
    301312            }
    302313            if ($this->isAncestor($child_type, $child_id, $parent['node_type'], $parent['node_id'])) {
    303                 App::raiseMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to parent <strong>%s %s</strong> because a node cannot have itself as a parent."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
    304                 App::logMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to parent <strong>%s %s</strong> because a node cannot have itself as a parent."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
     314                $app->raiseMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to parent <strong>%s %s</strong> because a node cannot have itself as a parent."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), MSG_ERR, __FILE__, __LINE__);
     315                $app->logMsg(sprintf(_("Cannot move node <strong>%s %s</strong> to parent <strong>%s %s</strong> because a node cannot have itself as a parent."), $child_type, $child_id, $parent['node_type'], $parent['node_id']), LOG_ERR, __FILE__, __LINE__);
    305316                return false;
    306317            }
     
    309320        if (empty($title)) {
    310321            // Select the title of the node we are moving, so we can add it again with the same info.
    311             $qid = DB::query("
     322            $qid = $db->query("
    312323                SELECT title FROM node_tbl
    313                 WHERE child_type = '" . DB::escapeString($child_type) . "'
    314                 AND child_id = '" . DB::escapeString($child_id) . "'
    315                 AND relationship_type " . (is_null($relationship_type) ? "IS NULL" : "= '" . DB::escapeString($relationship_type) . "'") . "
     324                WHERE child_type = '" . $db->escapeString($child_type) . "'
     325                AND child_id = '" . $db->escapeString($child_id) . "'
     326                AND relationship_type " . (is_null($relationship_type) ? "IS NULL" : "= '" . $db->escapeString($relationship_type) . "'") . "
    316327            ");
    317328            list($title) = mysql_fetch_row($qid);
     
    319330
    320331        // Delete the nodes with the old parents.
    321         DB::query("
     332        $db->query("
    322333            DELETE FROM node_tbl
    323             WHERE child_type = '" . DB::escapeString($child_type) . "'
    324             AND child_id = '" . DB::escapeString($child_id) . "'
    325             AND relationship_type " . (is_null($relationship_type) ? "IS NULL" : "= '" . DB::escapeString($relationship_type) . "'") . "
     334            WHERE child_type = '" . $db->escapeString($child_type) . "'
     335            AND child_id = '" . $db->escapeString($child_id) . "'
     336            AND relationship_type " . (is_null($relationship_type) ? "IS NULL" : "= '" . $db->escapeString($relationship_type) . "'") . "
    326337        ");
    327         App::logMsg(sprintf('moveNode: Deleted node %s %s.', $child_type, $child_id), LOG_DEBUG, __FILE__, __LINE__);
     338        $app->logMsg(sprintf('moveNode: Deleted node %s %s.', $child_type, $child_id), LOG_DEBUG, __FILE__, __LINE__);
    328339
    329340        // Insert new nodes with the new parents.
     
    344355    function getParents($child_type=null, $child_id=null, $type_constraint=null, $order='')
    345356    {
     357        $app =& App::getInstance();
     358        $db =& DB::getInstance();
     359   
    346360        if (!isset($child_type) || !isset($child_id)) {
    347361            if ($this->node_init) {
     
    349363                $child_id =& $this->child_id;
    350364            } else {
    351                 App::logMsg(_("getParents failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     365                $app->logMsg(_("getParents failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    352366                return false;
    353367            }
     
    359373                $type_constraint = array($type_constraint);
    360374            }
    361             $in_clause = "AND parent_type IN ('" . join("','", array_map(array('DB', 'escapeString'), $type_constraint)) . "')";
    362         }
    363 
    364         $qid = DB::query("
     375            $in_clause = "AND parent_type IN ('" . join("','", array_map(array($db, 'escapeString'), $type_constraint)) . "')";
     376        }
     377
     378        $qid = $db->query("
    365379            SELECT parent_type, parent_id
    366380            FROM node_tbl
    367             WHERE child_type = '" . DB::escapeString($child_type) . "'
    368             AND child_id = '" . DB::escapeString($child_id) . "'
     381            WHERE child_type = '" . $db->escapeString($child_type) . "'
     382            AND child_id = '" . $db->escapeString($child_id) . "'
    369383            $in_clause
    370             " . DB::escapeString($order) . "
     384            " . $db->escapeString($order) . "
    371385        ");
    372386
     
    392406    function getNode($child_type=null, $child_id=null)
    393407    {
     408        $app =& App::getInstance();
     409        $db =& DB::getInstance();
     410   
    394411        if (!isset($child_type) || !isset($child_id)) {
    395412            if ($this->node_init) {
     
    397414                $child_id =& $this->child_id;
    398415            } else {
    399                 App::logMsg(_("getNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    400                 return false;
    401             }
    402         }
    403 
    404         $qid = DB::query("
     416                $app->logMsg(_("getNode failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     417                return false;
     418            }
     419        }
     420
     421        $qid = $db->query("
    405422            SELECT child_type, child_id, title, subnode_quantity
    406423            FROM node_tbl
    407             WHERE child_type = '" . DB::escapeString($child_type) . "'
    408             AND child_id = '" . DB::escapeString($child_id) . "'
     424            WHERE child_type = '" . $db->escapeString($child_type) . "'
     425            AND child_id = '" . $db->escapeString($child_id) . "'
    409426        ");
    410427
     
    433450    function getChildren($child_type=null, $child_id=null, $type_constraint=null, $order='')
    434451    {
     452        $app =& App::getInstance();
     453        $db =& DB::getInstance();
     454   
    435455        if (!isset($child_type) || !isset($child_id)) {
    436456            if ($this->node_init) {
     
    438458                $child_id =& $this->child_id;
    439459            } else {
    440                 App::logMsg(_("getChildren failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     460                $app->logMsg(_("getChildren failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    441461                return false;
    442462            }
     
    448468                $type_constraint = array($type_constraint);
    449469            }
    450             $in_clause = "AND child_type IN ('" . join("','", array_map(array('DB', 'escapeString'), $type_constraint)) . "')";
    451         }
    452 
    453         $qid = DB::query("
     470            $in_clause = "AND child_type IN ('" . join("','", array_map(array($db, 'escapeString'), $type_constraint)) . "')";
     471        }
     472
     473        $qid = $db->query("
    454474            SELECT *
    455475            FROM node_tbl
    456             WHERE parent_type = '" . DB::escapeString($child_type) . "'
    457             AND parent_id = '" . DB::escapeString($child_id) . "'
     476            WHERE parent_type = '" . $db->escapeString($child_type) . "'
     477            AND parent_id = '" . $db->escapeString($child_id) . "'
    458478            $in_clause
    459             " . DB::escapeString($order) . "
     479            " . $db->escapeString($order) . "
    460480        ");
    461481
     
    482502    function getNumberChildren($child_type=null, $child_id=null, $type_constraint=null)
    483503    {
     504        $app =& App::getInstance();
     505        $db =& DB::getInstance();
     506
    484507        if (!isset($child_type) || !isset($child_id)) {
    485508            if ($this->node_init) {
     
    487510                $child_id =& $this->child_id;
    488511            } else {
    489                 App::logMsg(_("getNumberChildren failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     512                $app->logMsg(_("getNumberChildren failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    490513                return false;
    491514            }
     
    497520                $type_constraint = array($type_constraint);
    498521            }
    499             $in_clause = "AND child_type IN ('" . join("','", array_map(array('DB', 'escapeString'), $type_constraint)) . "')";
    500         }
    501 
    502         $qid = DB::query("
     522            $in_clause = "AND child_type IN ('" . join("','", array_map(array($db, 'escapeString'), $type_constraint)) . "')";
     523        }
     524
     525        $qid = $db->query("
    503526            SELECT COUNT(*)
    504527            FROM node_tbl
    505             WHERE parent_type = '" . DB::escapeString($child_type) . "'
    506             AND parent_id = '" . DB::escapeString($child_id) . "'
     528            WHERE parent_type = '" . $db->escapeString($child_type) . "'
     529            AND parent_id = '" . $db->escapeString($child_id) . "'
    507530            $in_clause
    508531        ");
     
    520543    function isLeaf($child_type=null, $child_id=null)
    521544    {
     545        $app =& App::getInstance();
     546   
    522547        if (!isset($child_type) || !isset($child_id)) {
    523548            if ($this->node_init) {
     
    525550                $child_id =& $this->child_id;
    526551            } else {
    527                 App::logMsg(_("isLeaf failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     552                $app->logMsg(_("isLeaf failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    528553                return false;
    529554            }
     
    579604    function getAllAncestors($child_type, $child_id, $go_linear=false, $_return_flag=true)
    580605    {
     606        $db =& DB::getInstance();
     607   
    581608        static $output = array();
    582609        static $return_flag;
    583610
    584         $qid = DB::query("
     611        $qid = $db->query("
    585612            SELECT parent_type, parent_id, child_type, child_id, title, subnode_quantity
    586613            FROM node_tbl
    587             WHERE child_type = '" . DB::escapeString($child_type) . "'
    588             AND child_id = '" . DB::escapeString($child_id) . "'
     614            WHERE child_type = '" . $db->escapeString($child_type) . "'
     615            AND child_id = '" . $db->escapeString($child_id) . "'
    589616        ");
    590617        while ($row = mysql_fetch_assoc($qid)) {
     
    631658    function nodeExists($child_type=null, $child_id=null, $parent_type=null, $parent_id=null, $relationship_type=null)
    632659    {
     660        $app =& App::getInstance();
     661        $db =& DB::getInstance();
     662   
    633663        if (!isset($child_type) || !isset($child_id)) {
    634664            if ($this->node_init) {
     
    636666                $child_id =& $this->child_id;
    637667            } else {
    638                 App::logMsg(_("nodeExists failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     668                $app->logMsg(_("nodeExists failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    639669                return false;
    640670            }
     
    642672
    643673        if (isset($parent_type) && isset($parent_id)) {
    644             $qid = DB::query("
     674            $qid = $db->query("
    645675                SELECT 1 FROM node_tbl
    646                 WHERE parent_type = '" . DB::escapeString($parent_type) . "'
    647                 AND parent_id = '" . DB::escapeString($parent_id) . "'
    648                 AND child_type = '" . DB::escapeString($child_type) . "'
    649                 AND child_id = '" . DB::escapeString($child_id) . "'
    650                 AND relationship_type " . (is_null($relationship_type) ? "IS NULL" : "= '" . DB::escapeString($relationship_type) . "'") . "
     676                WHERE parent_type = '" . $db->escapeString($parent_type) . "'
     677                AND parent_id = '" . $db->escapeString($parent_id) . "'
     678                AND child_type = '" . $db->escapeString($child_type) . "'
     679                AND child_id = '" . $db->escapeString($child_id) . "'
     680                AND relationship_type " . (is_null($relationship_type) ? "IS NULL" : "= '" . $db->escapeString($relationship_type) . "'") . "
    651681            ");
    652682        } else {
    653             $qid = DB::query("
     683            $qid = $db->query("
    654684                SELECT 1 FROM node_tbl
    655                 WHERE child_type = '" . DB::escapeString($child_type) . "'
    656                 AND child_id = '" . DB::escapeString($child_id) . "'
     685                WHERE child_type = '" . $db->escapeString($child_type) . "'
     686                AND child_id = '" . $db->escapeString($child_id) . "'
    657687            ");
    658688        }
     
    680710    function &getNodeList($preselected=null, $child_type=null, $child_id=null, $type_constraint=null, $include_curr=false, $order='', $_indent=0, $_return_flag=true)
    681711    {
     712        $app =& App::getInstance();
     713   
    682714        static $output = array();
    683715        static $is_a_leaf = array();
     
    688720                $child_id =& $this->child_id;
    689721            } else {
    690                 App::logMsg(_("getNodeList failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
     722                $app->logMsg(_("getNodeList failed. Arguments not specified properly."), LOG_ERR, __FILE__, __LINE__);
    691723                return false;
    692724            }
     
    709741                // Preventing circular references.
    710742                if ($my_children[$i]['child_type'] == $child_type && $my_children[$i]['child_id'] == $child_id && !($_return_flag && $include_curr)) {
    711                     App::logMsg(sprintf(_("Circular reference detected: %s has itself as a parent."), $this->toStringID($my_children[$i]['child_type'], $my_children[$i]['child_id'])), LOG_ERR, __FILE__, __LINE__);
     743                    $app->logMsg(sprintf(_("Circular reference detected: %s has itself as a parent."), $this->toStringID($my_children[$i]['child_type'], $my_children[$i]['child_id'])), LOG_ERR, __FILE__, __LINE__);
    712744                    continue;
    713745                }
     
    751783    function rebuildSubnodeQty($type_constraint=null)
    752784    {
     785        $db =& DB::getInstance();
     786   
    753787        // Reset all the category counters to zero.
    754         DB::query("UPDATE node_tbl SET subnode_quantity = 0");
     788        $db->query("UPDATE node_tbl SET subnode_quantity = 0");
    755789
    756790        // Get all the nodes.
    757         $qid = DB::query("SELECT DISTINCT child_type, child_id FROM node_tbl");
     791        $qid = $db->query("SELECT DISTINCT child_type, child_id FROM node_tbl");
    758792
    759793        // For each node count the number of children...
     
    773807    function setSubnodeQtyToParents($child_type, $child_id, $num_children)
    774808    {
    775         DB::query("
     809        $db =& DB::getInstance();
     810   
     811        $db->query("
    776812            UPDATE node_tbl
    777             SET subnode_quantity = subnode_quantity + '" . DB::escapeString($num_children) . "'
    778             WHERE child_type = '" . DB::escapeString($child_type) . "'
    779             AND child_id = '" . DB::escapeString($child_id) . "'
     813            SET subnode_quantity = subnode_quantity + '" . $db->escapeString($num_children) . "'
     814            WHERE child_type = '" . $db->escapeString($child_type) . "'
     815            AND child_id = '" . $db->escapeString($child_id) . "'
    780816        ",false);
    781         $qid = DB::query("
     817        $qid = $db->query("
    782818            SELECT parent_type, parent_id
    783819            FROM node_tbl
    784             WHERE child_type = '" . DB::escapeString($child_type) . "'
    785             AND child_id = '" . DB::escapeString($child_id) . "'
     820            WHERE child_type = '" . $db->escapeString($child_type) . "'
     821            AND child_id = '" . $db->escapeString($child_id) . "'
    786822        ",false);
    787823        while ((list($parent_type, $parent_id) = mysql_fetch_row($qid)) && $parent_id > 0) {
  • trunk/lib/Image.inc.php

    r121 r136  
    22/**
    33 * Image.inc.php
    4  * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information.
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
    56 * @author  Quinn Comendant <quinn@strangecode.com>
    67 * @version 1.1
  • trunk/lib/ImageThumb.inc.php

    r121 r136  
    22/**
    33 * ImageThumb.inc.php
    4  * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
    55 *
    66 * @author   Quinn Comendant <quinn@strangecode.com>
     
    9595    function setParam($params)
    9696    {
     97        $app =& App::getInstance();
     98
    9799        if (isset($params) && is_array($params)) {
    98100
     
    102104                // Must be directory.
    103105                if (!is_dir($params['source_dir'])) {
    104                     App::logMsg(sprintf('Source directory invalid: %s', $params['source_dir']), LOG_ERR, __FILE__, __LINE__);
     106                    $app->logMsg(sprintf('Source directory invalid: %s', $params['source_dir']), LOG_ERR, __FILE__, __LINE__);
    105107                    trigger_error(sprintf('Source directory invalid: %s', $params['source_dir']), E_USER_ERROR);
    106108                }
    107109                // Must be readable.
    108110                if (!is_readable($params['source_dir'])) {
    109                     App::logMsg(sprintf('Source directory not readable: %s', $params['source_dir']), LOG_ERR, __FILE__, __LINE__);
     111                    $app->logMsg(sprintf('Source directory not readable: %s', $params['source_dir']), LOG_ERR, __FILE__, __LINE__);
    110112                    trigger_error(sprintf('Source directory not readable: %s', $params['source_dir']), E_USER_ERROR);
    111113                }
     
    115117            $this->_params = array_merge($this->_params, $params);
    116118        } else {
    117             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     119            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    118120        }
    119121    }
     
    128130    function getParam($param)
    129131    {
     132        $app =& App::getInstance();
     133   
    130134        if (isset($this->_params[$param])) {
    131135            return $this->_params[$param];
    132136        } else {
    133             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     137            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    134138            return null;
    135139        }
     
    144148    function setSpec($spec, $index=null)
    145149    {
     150        $app =& App::getInstance();
     151
    146152        // A little sanity checking.
    147153        if (!isset($spec['dest_dir']) || '' == $spec['dest_dir']) {
    148             App::logMsg('setSpec error: dest_dir not specified.', LOG_ERR, __FILE__, __LINE__);
     154            $app->logMsg('setSpec error: dest_dir not specified.', LOG_ERR, __FILE__, __LINE__);
    149155        }
    150156        if (isset($spec['dest_file_type'])) {
     
    152158            case IMG_JPG :
    153159                if (imagetypes() & IMG_JPG == 0) {
    154                     App::logMsg(sprintf('IMG_JPG is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
     160                    $app->logMsg(sprintf('IMG_JPG is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
    155161                }
    156162                $spec['dest_file_extention'] = 'jpg';
     
    158164            case IMG_PNG :
    159165                if (imagetypes() & IMG_PNG == 0) {
    160                     App::logMsg(sprintf('IMG_PNG is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
     166                    $app->logMsg(sprintf('IMG_PNG is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
    161167                }
    162168                $spec['dest_file_extention'] = 'png';
     
    164170            case IMG_GIF :
    165171                if (imagetypes() & IMG_GIF == 0) {
    166                     App::logMsg(sprintf('IMG_GIF is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
     172                    $app->logMsg(sprintf('IMG_GIF is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
    167173                }
    168174                $spec['dest_file_extention'] = 'gif';
     
    170176            case IMG_WBMP :
    171177                if (imagetypes() & IMG_WBMP == 0) {
    172                     App::logMsg(sprintf('IMG_WBMP is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
     178                    $app->logMsg(sprintf('IMG_WBMP is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
    173179                }
    174180                $spec['dest_file_extention'] = 'wbmp';
    175181                break;
    176182            default :
    177                 App::logMsg(sprintf('Invalid dest_file_type: %s', $spec['dest_file_type']), LOG_ERR, __FILE__, __LINE__);
     183                $app->logMsg(sprintf('Invalid dest_file_type: %s', $spec['dest_file_type']), LOG_ERR, __FILE__, __LINE__);
    178184                break;
    179185            }
    180186        }
    181187        if (!isset($spec['width']) || !is_int($spec['width'])) {
    182             App::logMsg('setSpec error: width not specified.', LOG_ERR, __FILE__, __LINE__);
     188            $app->logMsg('setSpec error: width not specified.', LOG_ERR, __FILE__, __LINE__);
    183189        }
    184190        if (!isset($spec['height']) || !is_int($spec['height'])) {
    185             App::logMsg('setSpec error: height not specified.', LOG_ERR, __FILE__, __LINE__);
     191            $app->logMsg('setSpec error: height not specified.', LOG_ERR, __FILE__, __LINE__);
    186192        }
    187193        if (isset($spec['quality']) && IMG_JPG != $spec['dest_file_type']) {
    188             App::logMsg('The "quality" specification is not used unless IMG_JPG is the dest_file_type.', LOG_INFO, __FILE__, __LINE__);
     194            $app->logMsg('The "quality" specification is not used unless IMG_JPG is the dest_file_type.', LOG_INFO, __FILE__, __LINE__);
    189195        }
    190196        if (isset($spec['progressive']) && IMG_JPG != $spec['dest_file_type']) {
    191             App::logMsg('The "progressive" specification is not used unless IMG_JPG is the dest_file_type.', LOG_INFO, __FILE__, __LINE__);
     197            $app->logMsg('The "progressive" specification is not used unless IMG_JPG is the dest_file_type.', LOG_INFO, __FILE__, __LINE__);
    192198        }
    193199       
     
    213219    function processAll($runtime_specs=null)
    214220    {
     221        $app =& App::getInstance();
     222
    215223        // Ensure we have a source.
    216224        if ('' == $this->getParam('source_dir')) {
    217             App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     225            $app->logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    218226            return false;
    219227        }
     
    237245            return 0 === $return_val;
    238246        } else {
    239             App::logMsg(sprintf('No images found to thumbnail in directory %s.', $this->getParam('source_dir')), LOG_NOTICE, __FILE__, __LINE__);
     247            $app->logMsg(sprintf('No images found to thumbnail in directory %s.', $this->getParam('source_dir')), LOG_NOTICE, __FILE__, __LINE__);
    240248            return false;
    241249        }
     
    252260    function processFile($file_name, $runtime_specs=null)
    253261    {
     262        $app =& App::getInstance();
     263
    254264        // Source file determinted by provided file_name.
    255265        $source_file = realpath(sprintf('%s/%s', $this->getParam('source_dir'), $file_name));
     
    260270                $this->setSpec($runtime_specs, 0);
    261271            } else {
    262                 App::logMsg(sprintf('Image specifications not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     272                $app->logMsg(sprintf('Image specifications not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    263273                return false;               
    264274            }
     
    267277        // Ensure we have a source.
    268278        if ('' == $this->getParam('source_dir')) {
    269             App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     279            $app->logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    270280            return false;
    271281        }
     
    274284        if (!file_exists($source_file)) {
    275285            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s was not found."), $file_name), MSG_ERR, __FILE__, __LINE__);
    276             App::logMsg(sprintf('Source image not found: %s', $source_file), LOG_ALERT, __FILE__, __LINE__);
     286            $app->logMsg(sprintf('Source image not found: %s', $source_file), LOG_ALERT, __FILE__, __LINE__);
    277287            return false;
    278288        }
     
    281291        if (!is_readable($source_file)) {
    282292            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s is not readable."), $file_name), MSG_ERR, __FILE__, __LINE__);
    283             App::logMsg(sprintf('Source image not readable: %s', $source_file), LOG_ALERT, __FILE__, __LINE__);
     293            $app->logMsg(sprintf('Source image not readable: %s', $source_file), LOG_ALERT, __FILE__, __LINE__);
    284294            return false;
    285295        }
     
    288298        if (filesize($source_file) <= 0) {
    289299            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s is zero bytes."), $file_name), MSG_ERR, __FILE__, __LINE__);
    290             App::logMsg(sprintf('Source image is zero bytes: %s', $source_file), LOG_ALERT, __FILE__, __LINE__);
     300            $app->logMsg(sprintf('Source image is zero bytes: %s', $source_file), LOG_ALERT, __FILE__, __LINE__);
    291301            return false;
    292302        }
     
    295305        if (!$this->_validFileExtension($file_name)) {
    296306            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s not a valid type. It must have one of the following file name extensions: %s"), $file_name, join(', ', $this->getParam('valid_file_extensions'))), MSG_ERR, __FILE__, __LINE__);
    297             App::logMsg(sprintf('Image resizing failed: source image not of valid type: %s', $source_file), LOG_ERR, __FILE__, __LINE__);
     307            $app->logMsg(sprintf('Image resizing failed: source image not of valid type: %s', $source_file), LOG_ERR, __FILE__, __LINE__);
    298308            return false;
    299309        }
     
    324334                $file_size = filesize($dest_file);
    325335                if (false !== $file_size && $file_size < $spec['keep_filesize']) {
    326                     App::logMsg(sprintf('Skipping thumbnail %s. File already exists and file size is less than %s bytes.', $spec['dest_dir'] . '/' . $file_name, $spec['keep_filesize']), LOG_DEBUG, __FILE__, __LINE__);
     336                    $app->logMsg(sprintf('Skipping thumbnail %s. File already exists and file size is less than %s bytes.', $spec['dest_dir'] . '/' . $file_name, $spec['keep_filesize']), LOG_DEBUG, __FILE__, __LINE__);
    327337                    continue;
    328338                }
     
    333343            if ($image_size['0'] <= $spec['width'] && $image_size['1'] <= $spec['height'] && !$spec['allow_upscaling']) {
    334344                $spec['scaling_type'] = IMAGETHUMB_NO_SCALE;
    335                 App::logMsg(sprintf('Image %s smaller than specified %s thumbnail size. Keeping original size.', $file_name, $spec['dest_dir']), LOG_DEBUG, __FILE__, __LINE__);
     345                $app->logMsg(sprintf('Image %s smaller than specified %s thumbnail size. Keeping original size.', $file_name, $spec['dest_dir']), LOG_DEBUG, __FILE__, __LINE__);
    336346            }
    337347
     
    339349            if (IMAGETHUMB_METHOD_NETPBM === $this->getParam('resize_method') && file_exists($this->getParam('anytopnm_binary')) && file_exists($this->getParam('pnmscale_binary')) && file_exists($this->getParam('cjpeg_binary'))) {
    340350                // Resize using Netpbm binaries.
    341                 App::logMsg(sprintf('Resizing with Netpbm...', null), LOG_DEBUG, __FILE__, __LINE__);
     351                $app->logMsg(sprintf('Resizing with Netpbm...', null), LOG_DEBUG, __FILE__, __LINE__);
    342352                $return_val += $this->_resizeWithNetpbm($source_file, $dest_file, $spec);
    343353            } else if (IMAGETHUMB_METHOD_GD === $this->getParam('resize_method') && extension_loaded('gd')) {
    344354                // Resize with GD.
    345                 App::logMsg(sprintf('Resizing with GD...', null), LOG_DEBUG, __FILE__, __LINE__);
     355                $app->logMsg(sprintf('Resizing with GD...', null), LOG_DEBUG, __FILE__, __LINE__);
    346356                $return_val += $this->_resizeWithGD($source_file, $dest_file, $spec);
    347357            } else {
    348                 App::logMsg(sprintf('Image thumbnailing failed. Neither Netpbm or GD is available.', null), LOG_DEBUG, __FILE__, __LINE__);
     358                $app->logMsg(sprintf('Image thumbnailing failed. Neither Netpbm or GD is available.', null), LOG_DEBUG, __FILE__, __LINE__);
    349359                return false;
    350360            }
     
    370380    function _resizeWithNetpbm($source_file, $dest_file, $spec)
    371381    {
     382        $app =& App::getInstance();
     383
    372384        // Define pnmscale arguments.
    373385        switch ($spec['scaling_type']) {
     
    405417            escapeshellcmd($file_name)
    406418        );
    407         App::logMsg(sprintf('ImageThumb Netpbm command: %s', $command), LOG_DEBUG, __FILE__, __LINE__);
     419        $app->logMsg(sprintf('ImageThumb Netpbm command: %s', $command), LOG_DEBUG, __FILE__, __LINE__);
    408420       
    409421        // Execute!
     
    414426            // Make the thumbnail writable so the user can delete it over ftp without being 'apache'.
    415427            chmod($dest_file, $this->getParam('dest_file_perms'));
    416             App::logMsg(sprintf('Successfully resized image %s', $spec['dest_dir'] . '/' . basename($dest_file), $return_val), LOG_DEBUG, __FILE__, __LINE__);
     428            $app->logMsg(sprintf('Successfully resized image %s', $spec['dest_dir'] . '/' . basename($dest_file), $return_val), LOG_DEBUG, __FILE__, __LINE__);
    417429        } else {
    418430            // An error occurred.
    419             App::logMsg(sprintf('Image %s failed resizing with return value: %s%s', $spec['dest_dir'] . '/' . basename($dest_file), $return_val, empty($output) ? '' : ' (' . getDump($output) . ')'), LOG_ERR, __FILE__, __LINE__);
     431            $app->logMsg(sprintf('Image %s failed resizing with return value: %s%s', $spec['dest_dir'] . '/' . basename($dest_file), $return_val, empty($output) ? '' : ' (' . getDump($output) . ')'), LOG_ERR, __FILE__, __LINE__);
    420432        }
    421433
     
    438450    function _resizeWithGD($source_file, $dest_file, $spec)
    439451    {
     452        $app =& App::getInstance();
     453
    440454        // Get original file dimensions and type.
    441455        list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_file);
     
    487501            $source_image_resource = imagecreatefromwbmp($source_file);
    488502        default :
    489             App::logMsg(sprintf('Source image type %s not supported.', $source_image_type), LOG_WARNING, __FILE__, __LINE__);
     503            $app->logMsg(sprintf('Source image type %s not supported.', $source_image_type), LOG_WARNING, __FILE__, __LINE__);
    490504            return 1;
    491505            break;
    492506        }
    493507        if (!$source_image_resource) {
    494             App::logMsg(sprintf('Error creating %s image in memory from %s', $source_image_type, $source_file), LOG_WARNING, __FILE__, __LINE__);
     508            $app->logMsg(sprintf('Error creating %s image in memory from %s', $source_image_type, $source_file), LOG_WARNING, __FILE__, __LINE__);
    495509            return 1;
    496510        }
     
    501515        // Resample!
    502516        if (!imagecopyresampled($dest_image_resource, $source_image_resource, 0, 0, 0, 0, $dest_image_width, $dest_image_height, $source_image_width, $source_image_height)) {
    503             App::logMsg(sprintf('Error resampling image %s', $source_file), LOG_WARNING, __FILE__, __LINE__);
     517            $app->logMsg(sprintf('Error resampling image %s', $source_file), LOG_WARNING, __FILE__, __LINE__);
    504518            return 1;
    505519        }
     
    528542            break;
    529543        default :
    530             App::logMsg(sprintf('Destination image type %s not supported for image %s.', $spec['dest_file_type'], $dest_file), LOG_WARNING, __FILE__, __LINE__);
     544            $app->logMsg(sprintf('Destination image type %s not supported for image %s.', $spec['dest_file_type'], $dest_file), LOG_WARNING, __FILE__, __LINE__);
    531545            return 1;
    532546            break;
     
    537551            // Make the thumbnail writable so the user can delete it over ftp without being 'apache'.
    538552            chmod($dest_file, $this->getParam('dest_file_perms'));
    539             App::logMsg(sprintf('Successfully resized image %s', $dest_file), LOG_DEBUG, __FILE__, __LINE__);
     553            $app->logMsg(sprintf('Successfully resized image %s', $dest_file), LOG_DEBUG, __FILE__, __LINE__);
    540554            return 0;
    541555        } else {
    542556            // An error occurred.
    543             App::logMsg(sprintf('Image %s failed resizing.', $dest_file), LOG_ERR, __FILE__, __LINE__);
     557            $app->logMsg(sprintf('Image %s failed resizing.', $dest_file), LOG_ERR, __FILE__, __LINE__);
    544558            return 1;
    545559        }
     
    555569    function deleteThumbs($file_name)
    556570    {
     571        $app =& App::getInstance();
     572
    557573        // Ensure we have a source.
    558574        if ('' == $this->getParam('source_dir')) {
    559             App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     575            $app->logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    560576            return false;
    561577        }
     
    567583                if (!unlink($dest_file)) {
    568584                    $return_val++;
    569                     App::logMsg(sprintf(_("Delete thumbs failed: %s"), $dest_file), LOG_WARNING, __FILE__, __LINE__);
     585                    $app->logMsg(sprintf(_("Delete thumbs failed: %s"), $dest_file), LOG_WARNING, __FILE__, __LINE__);
    570586                }
    571587            }
     
    584600    function deleteOriginal($file_name)
    585601    {
     602        $app =& App::getInstance();
     603
    586604        // Ensure we have a source.
    587605        if ('' == $this->getParam('source_dir')) {
    588             App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     606            $app->logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    589607            return false;
    590608        }
     
    592610        $source_file = realpath(sprintf('%s/%s', $this->getParam('source_dir'), $file_name));
    593611        if (!unlink($source_file)) {
    594             App::logMsg(sprintf(_("Delete original failed: %s"), $source_file), LOG_WARNING, __FILE__, __LINE__);
     612            $app->logMsg(sprintf(_("Delete original failed: %s"), $source_file), LOG_WARNING, __FILE__, __LINE__);
    595613            return false;
    596614        }
     
    608626    function exists($file_name)
    609627    {
     628        $app =& App::getInstance();
     629
    610630        // Ensure we have a source.
    611631        if ('' == $this->getParam('source_dir')) {
    612             App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     632            $app->logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    613633            return false;
    614634        }
     
    639659    function _createDestDirs()
    640660    {
     661        $app =& App::getInstance();
     662
    641663        static $already_checked = false;
    642664
     
    644666            // Ensure we have a source.
    645667            if ('' == $this->getParam('source_dir')) {
    646                 App::logMsg(sprintf('Source directory not set before creating destination directories.'), LOG_ERR, __FILE__, __LINE__);
     668                $app->logMsg(sprintf('Source directory not set before creating destination directories.'), LOG_ERR, __FILE__, __LINE__);
    647669                return false;
    648670            }
     
    654676                    if (!mkdir($this->getParam('source_dir') . '/' . $spec['dest_dir'], $this->getParam('dest_dir_perms'))) {
    655677                        $return_val++;
    656                         App::logMsg(sprintf('mkdir failure: %s', $this->getParam('source_dir') . '/' . $spec['dest_dir']), LOG_ERR, __FILE__, __LINE__);
     678                        $app->logMsg(sprintf('mkdir failure: %s', $this->getParam('source_dir') . '/' . $spec['dest_dir']), LOG_ERR, __FILE__, __LINE__);
    657679                    }
    658680                }
     
    667689
    668690    /**
    669      * An alias for App::raiseMsg that only sends messages configured by display_messages.
     691     * An alias for $app->raiseMsg that only sends messages configured by display_messages.
    670692     *
    671693     * @access public
     
    679701    function _raiseMsg($message, $type, $file, $line)
    680702    {
     703        $app =& App::getInstance();
     704
    681705        if ($this->getParam('display_messages') === true || (is_int($this->getParam('display_messages')) && $this->getParam('display_messages') & $type > 0)) {
    682             App::raiseMsg($message, $type, $file, $line);
     706            $app->raiseMsg($message, $type, $file, $line);
    683707        }
    684708    }
  • trunk/lib/MCVE.inc.php

    r116 r136  
    11<?php
    22/**
    3  * The MCVE:: class provides functions for communicating with a MCVE server.
     3 * MCVE.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * The MCVE class provides functions for communicating with a MCVE server.
    47 *
    58 * @author  Quinn Comendant <quinn@strangecode.com>
     
    2225    function MCVE($username, $password)
    2326    {
     27        $app =& App::getInstance();
     28
    2429        // Ensure PHP was compiled with the MCVE functions.
    2530        if (!extension_loaded('mcve')) {
     
    2732        }
    2833        if ('' == $username || '' == $password) {
    29             App::logMsg(sprintf('Empty username or password provided.', null), LOG_ERR, __FILE__, __LINE__);
     34            $app->logMsg(sprintf('Empty username or password provided.', null), LOG_ERR, __FILE__, __LINE__);
    3035        }
    3136        $this->username = $username;
     
    3540    function _connect()
    3641    {
     42        $app =& App::getInstance();
     43
    3744        if ($this->connected) {
    3845            return true;
     
    4956        case 'ip' :
    5057            if (!MCVE_SetIP($this->conn, $this->host, $this->ip_port)) {
    51                 App::logMsg('Could not set method to IP.', LOG_ERR, __FILE__, __LINE__);
     58                $app->logMsg('Could not set method to IP.', LOG_ERR, __FILE__, __LINE__);
    5259                return false;
    5360            }
     
    5562        case 'ssl' :
    5663            if (!MCVE_SetSSL($this->conn, $this->host, $this->ssl_port)) {
    57                 App::logMsg('Could not set method to IP.', LOG_ERR, __FILE__, __LINE__);
     64                $app->logMsg('Could not set method to IP.', LOG_ERR, __FILE__, __LINE__);
    5865                return false;
    5966            }
     
    6168        case 'dropfile' :
    6269            if (!MCVE_SetDropFile($this->conn, '/var/mcve/trans')) {
    63                 App::logMsg('Could not set method to IP.', LOG_ERR, __FILE__, __LINE__);
     70                $app->logMsg('Could not set method to IP.', LOG_ERR, __FILE__, __LINE__);
    6471                return false;
    6572            }
    6673            break;
    6774        default :
    68             App::logMsg('Connection method not defined.', LOG_ERR, __FILE__, __LINE__);
     75            $app->logMsg('Connection method not defined.', LOG_ERR, __FILE__, __LINE__);
    6976            return false;
    7077        }
     
    7582        // non-blocking, but future versions of php_mcve will default to blocking.
    7683        if (!MCVE_SetBlocking($this->conn, $this->blocking)) {
    77             App::logMsg('Could not set blocking mode.', LOG_ERR, __FILE__, __LINE__);
     84            $app->logMsg('Could not set blocking mode.', LOG_ERR, __FILE__, __LINE__);
    7885            return false;
    7986        }
     
    8188        // Maximum of 30s per transaction allowed. Timeout occurs on server-end, not client-end
    8289        if (!MCVE_SetTimeout($this->conn, $this->timeout)) {
    83             App::logMsg('Could not set timeout.', LOG_ERR, __FILE__, __LINE__);
     90            $app->logMsg('Could not set timeout.', LOG_ERR, __FILE__, __LINE__);
    8491            return false;
    8592        }
     
    8895        if (!MCVE_Connect($this->conn)) {
    8996            $error = MCVE_ConnectionError($this->conn);
    90             App::logMsg("Connection failed: $error. Are you sure the MCVE engine is running?", LOG_ERR, __FILE__, __LINE__);
     97            $app->logMsg("Connection failed: $error. Are you sure the MCVE engine is running?", LOG_ERR, __FILE__, __LINE__);
    9198            return false;
    9299        }
     
    117124    function sendTrans($tid, $type='', $hide_msg=false)
    118125    {
     126        $app =& App::getInstance();
     127
    119128        // Finalize structuring of  to MCVE and ready it to be sent
    120129        if (!MCVE_TransSend($this->conn, $tid)) {
    121             App::logMsg('Transaction improperly structured, possibly not enough info.', LOG_ERR, __FILE__, __LINE__);
     130            $app->logMsg('Transaction improperly structured, possibly not enough info.', LOG_ERR, __FILE__, __LINE__);
    122131            return false;
    123132        }
     
    139148        // Check to see if transaction was successful or not using a strict success/fail function
    140149        if ($ret_status == MCVE_FAIL) {
    141             App::raiseMsg(sprintf('MCVE %s failure: %s %s', $type, $ret_text, ('' == $verbiage ? '' : '(' . trim($verbiage) . ')')), MSG_WARNING, __FILE__, __LINE__);
     150            $app->raiseMsg(sprintf('MCVE %s failure: %s %s', $type, $ret_text, ('' == $verbiage ? '' : '(' . trim($verbiage) . ')')), MSG_WARNING, __FILE__, __LINE__);
    142151            return false;
    143152        } else if ($ret_status == MCVE_SUCCESS) {
    144153            if (!$hide_msg) {
    145                 App::raiseMsg(sprintf(_("MCVE %s success: %s %s"), $type, $ret_text, ('' == $verbiage ? '' : '(' . trim($verbiage) . ')')), MSG_SUCCESS, __FILE__, __LINE__);
     154                $app->raiseMsg(sprintf(_("MCVE %s success: %s %s"), $type, $ret_text, ('' == $verbiage ? '' : '(' . trim($verbiage) . ')')), MSG_SUCCESS, __FILE__, __LINE__);
    146155            }
    147             App::logMsg(sprintf(_("MCVE success details. Auth: %s; Batch: %s; Item: %s; TTID: %s; AVS: %s; CV: %s."),
     156            $app->logMsg(sprintf(_("MCVE success details. Auth: %s; Batch: %s; Item: %s; TTID: %s; AVS: %s; CV: %s."),
    148157                MCVE_TransactionAuth($this->conn, $tid),
    149158                MCVE_TransactionBatch($this->conn, $tid),
     
    155164            return true;
    156165        } else {
    157             App::logMsg(sprintf('Transaction failed. Unknown return code: %s', $ret_status), LOG_ERR, __FILE__, __LINE__);
     166            $app->logMsg(sprintf('Transaction failed. Unknown return code: %s', $ret_status), LOG_ERR, __FILE__, __LINE__);
    158167            return false;
    159168        }
  • trunk/lib/Nav.inc.php

    r44 r136  
    11<?php
    22/**
    3  * The Nav:: class provides a system for working with navigation elements.
     3 * Nav.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * The Nav class provides a system for working with navigation elements.
    47 * Currently it supports storing page titles and URLs for printing breadcrumbs
    58 * and titles, as well as setting page features such as hiding the page title on
     
    201204    function getBreadcrumbs($page_id=null)
    202205    {
     206        $app =& App::getInstance();
     207
    203208        $page_id = $this->_calculatePageID($page_id);
    204209
     
    219224                    } else if ($crumb_count > $this->getFeature('chop_breadcrumb_links')) {
    220225                        // A normal linked crumb.
    221                         $breadcrumbs .= oTxt($pathmark, true) . '<a href="' . App::oHREF($page['url']) . '">' . sprintf($this->last_crumb_format, oTxt($page['title'], true)) . '</a>';
     226                        $breadcrumbs .= oTxt($pathmark, true) . '<a href="' . $app->oHREF($page['url']) . '">' . sprintf($this->last_crumb_format, oTxt($page['title'], true)) . '</a>';
    222227                    }
    223228                } else {
     
    227232                    } else {
    228233                        // A normal linked crumb.
    229                         $breadcrumbs .= oTxt($pathmark, true) . '<a href="' . App::oHREF($page['url']) . '">' . oTxt($page['title'], true) . '</a>';
     234                        $breadcrumbs .= oTxt($pathmark, true) . '<a href="' . $app->oHREF($page['url']) . '">' . oTxt($page['title'], true) . '</a>';
    230235                    }
    231236                }
  • trunk/lib/PEdit.inc.php

    r124 r136  
    11<?php
    22/**
    3  * PEdit:: provides a mechanism to store text in php variables
     3 * PEdit.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * PEdit provides a mechanism to store text in php variables
    47 * which will be printed to the client browser under normal
    58 * circumstances, but an authenticated user can 'edit' the document--
     
    1114 * To use, include this file, initialize variables,
    1215 * and call printing/editing functions where you want data and forms to
    13  * show up. Below is an example of use:
     16 * show up.
     17 *
     18 * @author  Quinn Comendant <quinn@strangecode.com>
     19 * @concept Beau Smith <beau@beausmith.com>
     20 * @version 2.0
     21 *
     22 * Example of use:
    1423 
    1524 // Initialize PEdit object.
     
    3746 $pedit->formEnd();
    3847
    39  * @author  Quinn Comendant <quinn@strangecode.com>
    40  * @concept Beau Smith <beau@beausmith.com>
    41  * @version 2.0
    4248 */
    4349class PEdit {
     
    95101    function setParam($params)
    96102    {
     103        $app =& App::getInstance();
     104
    97105        if (isset($params) && is_array($params)) {
    98106            // Merge new parameters with old overriding only those passed.
    99107            $this->_params = array_merge($this->_params, $params);
    100108        } else {
    101             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_WARNING, __FILE__, __LINE__);
     109            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_WARNING, __FILE__, __LINE__);
    102110        }
    103111    }
     
    112120    function getParam($param)
    113121    {
     122        $app =& App::getInstance();
     123   
    114124        if (isset($this->_params[$param])) {
    115125            return $this->_params[$param];
    116126        } else {
    117             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
     127            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    118128            return null;
    119129        }
     
    129139    function start($initialize_data_file=false)
    130140    {
     141        $app =& App::getInstance();
     142
    131143        if (!is_dir($this->getParam('data_dir'))) {
    132144            trigger_error(sprintf('PEdit data directory not found: %s', $this->getParam('data_dir')), E_USER_WARNING);
     
    143155        case 'Save' :
    144156            if ($this->_writeData()) {
    145                 App::dieURL($_SERVER['PHP_SELF']);
     157                $app->dieURL($_SERVER['PHP_SELF']);
    146158            }
    147159            break;
    148160        case 'Restore' :
    149161            if ($this->_restoreVersion(getFormData('version'))) {
    150                 App::dieURL($_SERVER['PHP_SELF']);
     162                $app->dieURL($_SERVER['PHP_SELF']);
    151163            }
    152164            break;
    153165        case 'View' :
    154166            $this->_data_file = sprintf('%s%s__%s.xml', $this->getParam('data_dir'), $_SERVER['PHP_SELF'], getFormData('version'));
    155             App::raiseMsg(sprintf(_("This is <em><strong>only a preview</strong></em> of version %s."), getFormData('version')), MSG_NOTICE, __FILE__, __LINE__);
     167            $app->raiseMsg(sprintf(_("This is <em><strong>only a preview</strong></em> of version %s."), getFormData('version')), MSG_NOTICE, __FILE__, __LINE__);
    156168            break;
    157169        }
     
    176188    function set($name, $options=array())
    177189    {
     190        $app =& App::getInstance();
     191
    178192        $name = preg_replace('/\s/', '_', $name);
    179193        if (!isset($this->_data[$name])) {
    180194            $this->_data[$name] = array_merge(array('content' => ''), $options);
    181195        } else {
    182             App::logMsg(sprintf('Duplicate set data: %s', $name), LOG_NOTICE, __FILE__, __LINE__);
     196            $app->logMsg(sprintf('Duplicate set data: %s', $name), LOG_NOTICE, __FILE__, __LINE__);
    183197        }
    184198    }
     
    208222    function formBegin()
    209223    {
     224        $app =& App::getInstance();
     225
    210226        if (!$this->_authorized || empty($this->_data)) {
    211227            return false;
     
    216232        <input type="hidden" name="file_hash" value="<?php echo $this->_fileHash(); ?>" />
    217233        <?php
    218         App::printHiddenSession();
     234        $app->printHiddenSession();
    219235        switch ($this->op) {
    220236        case 'Edit' :
     
    345361    function printVersions()
    346362    {
     363        $app =& App::getInstance();
     364
    347365        if ($this->_authorized && $this->op == 'Versions') {
    348366            // Print versions and commands to view/restore.
     
    362380                    ?>
    363381                    <tr>
    364                         <td><?php echo date(App::getParam('date_format'), $v['unixtime']); ?></td>
    365                         <td><?php echo date(App::getParam('time_format'), $v['unixtime']); ?></td>
     382                        <td><?php echo date($app->getParam('date_format'), $v['unixtime']); ?></td>
     383                        <td><?php echo date($app->getParam('time_format'), $v['unixtime']); ?></td>
    366384                        <td><?php echo humanFileSize($v['filesize']); ?></td>
    367                         <td class="sc-nowrap"><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=View&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("View"); ?></a> <?php echo _("or"); ?> <a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=Restore&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("Restore"); ?></a></td>
     385                        <td class="sc-nowrap"><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=View&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("View"); ?></a> <?php echo _("or"); ?> <a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=Restore&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("Restore"); ?></a></td>
    368386                    </tr>
    369387                    <?php
     
    386404    function _fileHash()
    387405    {
    388         return md5(App::getParam('signing_key') . $_SERVER['PHP_SELF']);
     406        $app =& App::getInstance();
     407
     408        return md5($app->getParam('signing_key') . $_SERVER['PHP_SELF']);
    389409    }
    390410
     
    399419    function _loadDataFile()
    400420    {
     421        $app =& App::getInstance();
     422
    401423        if (!file_exists($this->_data_file)) {
    402424            if (!$this->_initializeDataFile()) {
    403                 App::logMsg(sprintf('Initializing content file failed: %s', $this->_data_file), LOG_WARNING, __FILE__, __LINE__);
     425                $app->logMsg(sprintf('Initializing content file failed: %s', $this->_data_file), LOG_WARNING, __FILE__, __LINE__);
    404426                return false;
    405427            }
     
    408430        $status = $this->xml_unserializer->unserialize($xml_file_contents, false);   
    409431        if (PEAR::isError($status)) {
    410             App::logMsg(sprintf('XML_Unserialize error: %s', $status->getMessage()), LOG_WARNING, __FILE__, __LINE__);
     432            $app->logMsg(sprintf('XML_Unserialize error: %s', $status->getMessage()), LOG_WARNING, __FILE__, __LINE__);
    411433            return false;
    412434        }
     
    436458    function _initializeDataFile()
    437459    {
    438         App::logMsg(sprintf('Initializing data file: %s', $this->_data_file), LOG_INFO, __FILE__, __LINE__);
     460        $app =& App::getInstance();
     461
     462        $app->logMsg(sprintf('Initializing data file: %s', $this->_data_file), LOG_INFO, __FILE__, __LINE__);
    439463        $xml_file_contents = $this->xml_serializer->serialize($this->_data);
    440464        return $this->_filePutContents($this->_data_file, $xml_file_contents);
     
    450474    function _writeData()
    451475    {
     476        $app =& App::getInstance();
     477
    452478        if (!$this->_authorized) {
    453479            return false;
     
    455481        if ($this->_fileHash() != getFormData('file_hash')) {
    456482            // Posted data is NOT for this file!
    457             App::logMsg(sprintf('File_hash does not match current file.', null), LOG_WARNING, __FILE__, __LINE__);
     483            $app->logMsg(sprintf('File_hash does not match current file.', null), LOG_WARNING, __FILE__, __LINE__);
    458484            return false;
    459485        }
     
    466492            $this->_deleteOldVersions();
    467493            if (!$this->_createVersion()) {
    468                 App::logMsg(sprintf('Failed creating new version of file.', null), LOG_NOTICE, __FILE__, __LINE__);
     494                $app->logMsg(sprintf('Failed creating new version of file.', null), LOG_NOTICE, __FILE__, __LINE__);
    469495                return false;
    470496            }
     
    496522    function _filePutContents($filename, $content)
    497523    {
     524        $app =& App::getInstance();
     525
    498526        // Ensure requested filename is within the pedit data dir.
    499527        if (strpos($filename, $this->getParam('data_dir')) === false) {
    500             App::logMsg(sprintf('Failed writing file outside pedit _data_dir: %s', $filename), LOG_ERR, __FILE__, __LINE__);
     528            $app->logMsg(sprintf('Failed writing file outside pedit _data_dir: %s', $filename), LOG_ERR, __FILE__, __LINE__);
    501529            return false;
    502530        }
     
    510538            if (!is_dir($curr_path)) {
    511539                if (!mkdir($curr_path)) {
    512                     App::logMsg(sprintf('Failed mkdir: %s', $curr_path), LOG_ERR, __FILE__, __LINE__);
     540                    $app->logMsg(sprintf('Failed mkdir: %s', $curr_path), LOG_ERR, __FILE__, __LINE__);
    513541                    return false;
    514542                }
     
    522550                flock($fp, LOCK_UN);
    523551            } else {
    524                 App::logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
     552                $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
    525553                return false;
    526554            }
    527555            fclose($fp);
    528556            // Success!
    529             App::logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
     557            $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
    530558            return true;
    531559        } else {
    532             App::logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
     560            $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
    533561            return false;
    534562        }
     
    544572    function _createVersion()
    545573    {
     574        $app =& App::getInstance();
     575
    546576        if (!$this->_authorized) {
    547577            return false;
     
    549579        if ($this->_fileHash() != getFormData('file_hash')) {
    550580            // Posted data is NOT for this file!
    551             App::logMsg(sprintf('File_hash does not match current file.', null), LOG_ERR, __FILE__, __LINE__);
     581            $app->logMsg(sprintf('File_hash does not match current file.', null), LOG_ERR, __FILE__, __LINE__);
    552582            return false;
    553583        }
     
    555585        // Ensure current data file exists.
    556586        if (!file_exists($this->_data_file)) {
    557             App::logMsg(sprintf('Data file does not yet exist: %s', $this->_data_file), LOG_NOTICE, __FILE__, __LINE__);
     587            $app->logMsg(sprintf('Data file does not yet exist: %s', $this->_data_file), LOG_NOTICE, __FILE__, __LINE__);
    558588            return false;
    559589        }
     
    563593        $version_file = sprintf('%s__%s.xml', preg_replace('/\.xml$/', '', $this->_data_file), time());
    564594        if (!copy($this->_data_file, $version_file)) {
    565             App::logMsg(sprintf('Failed copying new version: %s -> %s', $this->_data_file, $version_file), LOG_ERR, __FILE__, __LINE__);
     595            $app->logMsg(sprintf('Failed copying new version: %s -> %s', $this->_data_file, $version_file), LOG_ERR, __FILE__, __LINE__);
    566596            return false;
    567597        }
     
    580610    function _deleteOldVersions()
    581611    {
     612        $app =& App::getInstance();
     613
    582614        $version_files = $this->_getVersions();
    583615        if (is_array($version_files) && sizeof($version_files) > $this->getParam('versions_min_qty')) {
     
    590622                $del_file = dirname($this->_data_file) . '/' . $oldest['filename'];
    591623                if (!unlink($del_file)) {
    592                     App::logMsg(sprintf('Failed deleting version: %s', $del_file), LOG_ERR, __FILE__, __LINE__);
     624                    $app->logMsg(sprintf('Failed deleting version: %s', $del_file), LOG_ERR, __FILE__, __LINE__);
    593625                }
    594626                $oldest = array_pop($version_files);
     
    637669    function _restoreVersion($version)
    638670    {
     671        $app =& App::getInstance();
     672
    639673        if (!$this->_authorized) {
    640674            return false;
     
    646680        // Ensure specified version exists.
    647681        if (!file_exists($version_file)) {
    648             App::logMsg(sprintf('Cannot restore non-existant file: %s', $version_file), LOG_NOTICE, __FILE__, __LINE__);
     682            $app->logMsg(sprintf('Cannot restore non-existant file: %s', $version_file), LOG_NOTICE, __FILE__, __LINE__);
    649683            return false;
    650684        }
     
    652686        // Make certain a version is created.
    653687        if (!$this->_createVersion()) {
    654             App::logMsg(sprintf('Failed creating new version of file.', null), LOG_ERR, __FILE__, __LINE__);
     688            $app->logMsg(sprintf('Failed creating new version of file.', null), LOG_ERR, __FILE__, __LINE__);
    655689            return false;
    656690        }
     
    658692        // Do the actual copy.
    659693        if (!copy($version_file, $this->_data_file)) {
    660             App::logMsg(sprintf('Failed copying old version: %s -> %s', $version_file, $this->_data_file), LOG_ERR, __FILE__, __LINE__);
     694            $app->logMsg(sprintf('Failed copying old version: %s -> %s', $version_file, $this->_data_file), LOG_ERR, __FILE__, __LINE__);
    661695            return false;
    662696        }
    663697
    664698        // Success!
    665         App::raiseMsg(sprintf(_("Page has been restored to version %s."), $version), MSG_SUCCESS, __FILE__, __LINE__);
     699        $app->raiseMsg(sprintf(_("Page has been restored to version %s."), $version), MSG_SUCCESS, __FILE__, __LINE__);
    666700        return true;
    667701    }
  • trunk/lib/PageNumbers.inc.php

    r111 r136  
    44 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
    55 *
    6  * The PageNumbers:: class provides a common abstracted interface to the
     6 * The PageNumbers class provides a common abstracted interface to the
    77 * multiple pages features. It sets the various numbers needed to display items
    88 * on a page, and includes functions for working with these numbers.
     
    7272    function setPerPage($per_page, $default=25, $save_value=true)
    7373    {
    74         // (1) By provided argument, if valid.
     74        $prefs =& Prefs::getInstance();
     75   
     76        // (1) By provided argument, if valid.
    7577        // (2) By saved preference, if available.
    7678        // (3) Set to default value if provided and valid.
     
    7981            $this->_per_page = $per_page;
    8082            if ($save_value) {
    81                 Prefs::setValue('items_per_page', $this->_per_page, $_SERVER['PHP_SELF']);
    82             }
    83         } else if ($save_value && Prefs::exists('items_per_page', $_SERVER['PHP_SELF'])) {
    84             $this->_per_page = (int)Prefs::getValue('items_per_page', $_SERVER['PHP_SELF']);
     83                $prefs->set('items_per_page', $this->_per_page, $_SERVER['PHP_SELF']);
     84            }
     85        } else if ($save_value && $prefs->exists('items_per_page', $_SERVER['PHP_SELF'])) {
     86            $this->_per_page = (int)$prefs->get('items_per_page', $_SERVER['PHP_SELF']);
    8587        } else if (is_numeric($default) && $default > 0) {
    8688            $this->_per_page = $default;
     
    9496    function setPageNumber($page_number, $save_value=true)
    9597    {
    96         // (1) By provided argument, if valid.
     98        $prefs =& Prefs::getInstance();
     99   
     100    // (1) By provided argument, if valid.
    97101        // (2) By saved preference, if available.
    98102        // (3) Don't change from what was provided at class instantiation.
     
    105109            }
    106110            if ($save_value) {
    107                 Prefs::setValue('page_number', $this->current_page, $_SERVER['PHP_SELF']);
    108             }
    109         } else if ($save_value && Prefs::exists('page_number', $_SERVER['PHP_SELF'])) {
    110             $this->current_page = (int)Prefs::getValue('page_number', $_SERVER['PHP_SELF']);
     111                $prefs->set('page_number', $this->current_page, $_SERVER['PHP_SELF']);
     112            }
     113        } else if ($save_value && $prefs->exists('page_number', $_SERVER['PHP_SELF'])) {
     114            $this->current_page = (int)$prefs->get('page_number', $_SERVER['PHP_SELF']);
    111115        }
    112116        $this->set_page_number_initialized = true;
     
    137141    function calculate()
    138142    {
     143        $app =& App::getInstance();
     144
    139145        if (!$this->set_per_page_initialized) {
    140             App::logMsg(sprintf('set_per_page not initialized'), LOG_ERR, __FILE__, __LINE__);
     146            $app->logMsg(sprintf('set_per_page not initialized'), LOG_ERR, __FILE__, __LINE__);
    141147        }
    142148        if (!$this->set_page_number_initialized) {
    143             App::logMsg(sprintf('set_page_number not initialized'), LOG_ERR, __FILE__, __LINE__);
     149            $app->logMsg(sprintf('set_page_number not initialized'), LOG_ERR, __FILE__, __LINE__);
    144150        }
    145151        if (!$this->set_total_items_initialized) {
    146             App::logMsg(sprintf('set_total_items not initialized'), LOG_ERR, __FILE__, __LINE__);
     152            $app->logMsg(sprintf('set_total_items not initialized'), LOG_ERR, __FILE__, __LINE__);
    147153        }
    148154
     
    189195    function getLimitSQL()
    190196    {
     197        $app =& App::getInstance();
     198        $db =& DB::getInstance();
     199
    191200        if (is_numeric($this->first_item) && is_numeric($this->_per_page)) {
    192             return ' LIMIT ' . DB::escapeString($this->first_item) . ', ' . DB::escapeString($this->_per_page) . ' ';
    193         } else {
    194             App::logMsg(sprintf('Could not find SQL to LIMIT by %s %s.', $this->first_item, $this->_per_page), LOG_WARNING, __FILE__, __LINE__);
     201            return ' LIMIT ' . $db->escapeString($this->first_item) . ', ' . $db->escapeString($this->_per_page) . ' ';
     202        } else {
     203            $app->logMsg(sprintf('Could not find SQL to LIMIT by %s %s.', $this->first_item, $this->_per_page), LOG_WARNING, __FILE__, __LINE__);
    195204            return '';
    196205        }
     
    204213    function printPerPageLinks($query_key='per_page')
    205214    {
     215        $app =& App::getInstance();
     216
    206217        $sp = '';
    207218        for ($i=0; $i<sizeof($this->per_page_options); $i++) {
     
    209220                printf('%s<a href="%s">%s</a>',
    210221                    $sp,
    211                     App::oHREF($_SERVER['PHP_SELF'] . '?' . $query_key . '=' . $this->per_page_options[$i]),
     222                    $app->oHREF($_SERVER['PHP_SELF'] . '?' . $query_key . '=' . $this->per_page_options[$i]),
    212223                    $this->per_page_options[$i]
    213224                );
     
    220231
    221232    /**
    222      * Outputs an App::oHREF compatible url that goes to the page $page_number.
     233     * Outputs an $app->oHREF compatible url that goes to the page $page_number.
    223234     * Depends on $this->base_url to build the url onto. This is used in the
    224235     * page_number.ihtml template.
     
    232243    function getPageNumURL($page_number, $carry_args=null)
    233244    {
    234         return App::oHREF($this->url_base . $page_number, $carry_args);
     245        $app =& App::getInstance();
     246
     247        return $app->oHREF($this->url_base . $page_number, $carry_args);
    235248    }
    236249    function printPageNumURL($page_number, $carry_args=null)
  • trunk/lib/PageSequence.inc.php

    r42 r136  
    44 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
    55 *
    6  * The PageSequence:: class provides an interface to simplify the creation of a multi-step form.
     6 * The PageSequence class provides an interface to simplify the creation of a multi-step form.
    77 *
    88 * @requires  This class requires Prefs.inc.php
     
    133133    function setCurrent($step_id)
    134134    {
     135        $app =& App::getInstance();
     136
    135137        if (false !== ($pos = $this->getPosition($step_id))) {
    136138            // Specified step exists (even if numeric).
     
    138140        } else {
    139141            // Step with specified key does not exist.
    140             App::logMsg(sprintf(_("Step %s not defined in sequence %s"), $step_id, $this->sequence_title), LOG_INFO, __FILE__, __LINE__);
     142            $app->logMsg(sprintf(_("Step %s not defined in sequence %s"), $step_id, $this->sequence_title), LOG_INFO, __FILE__, __LINE__);
    141143            return false;
    142144        }
     
    257259    function printEditLink($step_id=null)
    258260    {
     261        $app =& App::getInstance();
     262
    259263        $pos = isset($step_id) ? $this->getPosition($step_id) : $this->getPosition();
    260264        if ($_SESSION[$this->seq]['steps'][$pos]['editable']) {
    261             printf('[<a href="%s">%s</a>]', App::oHREF($_SERVER['PHP_SELF'] . '?step=' . $pos . '&boomerang=confirmation'), _("edit"));
     265            printf('[<a href="%s">%s</a>]', $app->oHREF($_SERVER['PHP_SELF'] . '?step=' . $pos . '&boomerang=confirmation'), _("edit"));
    262266        }
    263267    }
     
    320324    function _auto_timeout()
    321325    {
     326        $app =& App::getInstance();
     327
    322328        if (isset($_SESSION[$this->seq]['last_access_time'])
    323329        && $_SESSION[$this->seq]['last_access_time'] < time() - $this->idle_timeout) {
    324330            // Session has expired, flush all vars to start over.
    325331            $this->startOver();
    326             App::dieURL($this->start_url);
     332            $app->dieURL($this->start_url);
    327333        } else {
    328334            // Set timer.
  • trunk/lib/PayPal.inc.php

    r42 r136  
    11<?php
    22/**
    3  * The PayPal:: class provides functions for creating PayPal buttons and for
     3 * PayPal.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * The PayPal class provides functions for creating PayPal buttons and for
    47 * receiving PayPal's Instant Payment Notification (IPN) service.
    58 *
     
    7477    function setButtonDefaults($type, $options)
    7578    {
     79        $app =& App::getInstance();
     80
    7681        if (!is_array($options) || empty($options)) {
    77             App::logMsg(sprintf('Invalid options: %s', getDump($options)), LOG_WARNING, __FILE__, __LINE__);
     82            $app->logMsg(sprintf('Invalid options: %s', getDump($options)), LOG_WARNING, __FILE__, __LINE__);
    7883            return false;
    7984        }
     
    8287            $this->_default_button_options['_global'] = array_merge($this->_default_button_options['_global'], $options);
    8388        } else if (!isset($this->_default_button_options[$type])) {
    84             App::logMsg(sprintf('Invalid button type: %s', $type), LOG_WARNING, __FILE__, __LINE__);
     89            $app->logMsg(sprintf('Invalid button type: %s', $type), LOG_WARNING, __FILE__, __LINE__);
    8590            return false;
    8691        }
     
    104109    function newButton($type, $name, $options=null)
    105110    {
     111        $app =& App::getInstance();
     112
    106113        if (!isset($this->_default_button_options[$type])) {
    107             App::logMsg(sprintf('Invalid button type: %s', $type), LOG_WARNING, __FILE__, __LINE__);
     114            $app->logMsg(sprintf('Invalid button type: %s', $type), LOG_WARNING, __FILE__, __LINE__);
    108115            return false;
    109116        }
    110117
    111118        if (!is_array($options) || empty($options)) {
    112             App::logMsg(sprintf('Invalid options: %s', getDump($options)), LOG_WARNING, __FILE__, __LINE__);
     119            $app->logMsg(sprintf('Invalid options: %s', getDump($options)), LOG_WARNING, __FILE__, __LINE__);
    113120            return false;
    114121        }
    115122
    116123        if (isset($this->_buttons[$name])) {
    117             App::logMsg(sprintf('Overwriting existing button name: %s', getDump($this->_buttons[$name])), LOG_DEBUG, __FILE__, __LINE__);
     124            $app->logMsg(sprintf('Overwriting existing button name: %s', getDump($this->_buttons[$name])), LOG_DEBUG, __FILE__, __LINE__);
    118125        }
    119126
     
    137144    function getLink($name)
    138145    {
     146        $app =& App::getInstance();
     147
    139148        if (!isset($this->_buttons[$name])) {
    140             App::logMsg(sprintf('Button does not exist: %s', $name), LOG_WARNING, __FILE__, __LINE__);
     149            $app->logMsg(sprintf('Button does not exist: %s', $name), LOG_WARNING, __FILE__, __LINE__);
    141150            return false;
    142151        }
     
    207216    function setParam($params)
    208217    {
     218        $app =& App::getInstance();
     219
    209220        if (isset($params) && is_array($params)) {
    210221            // Merge new parameters with old overriding only those passed.
    211222            $this->_params = array_merge($this->_params, $params);
    212223        } else {
    213             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     224            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    214225        }
    215226    }
     
    224235    function getParam($param)
    225236    {
     237        $app =& App::getInstance();
     238   
    226239        if (isset($this->_params[$param])) {
    227240            return $this->_params[$param];
    228241        } else {
    229             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     242            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    230243            return null;
    231244        }
     
    259272    function processIPN()
    260273    {
     274        $app =& App::getInstance();
     275
    261276        if (getPost('test_ipn') == '1' || $this->getParam('test_mode')) {
    262             App::logMsg(sprintf('Processing PayPal IPN in test mode: %s', getDump(getFormData())), LOG_DEBUG, __FILE__, __LINE__);
     277            $app->logMsg(sprintf('Processing PayPal IPN in test mode: %s', getDump(getFormData())), LOG_DEBUG, __FILE__, __LINE__);
    263278            $url = parse_url('https://www.sandbox.paypal.com/cgi-bin/webscr');
    264279        } else {
    265             App::logMsg(sprintf('Processing PayPal IPN: %s', getDump(getFormData())), LOG_DEBUG, __FILE__, __LINE__);
     280            $app->logMsg(sprintf('Processing PayPal IPN: %s', getDump(getFormData())), LOG_DEBUG, __FILE__, __LINE__);
    266281            $url = parse_url($this->getParam('paypal_url'));
    267282        }
     
    287302
    288303        if (!$fp) {
    289             App::logMsg(sprintf('Connection to PayPal URL %s failed with error: %s (%s)', $ssl . $url['host'], $errstr, $errnum), LOG_WARNING, __FILE__, __LINE__);
     304            $app->logMsg(sprintf('Connection to PayPal URL %s failed with error: %s (%s)', $ssl . $url['host'], $errstr, $errnum), LOG_WARNING, __FILE__, __LINE__);
    290305            return false;
    291306        } else {
     
    304319            fclose($fp);
    305320
    306             App::logMsg(sprintf('IPN response received: %s', $this->_ipn_response), LOG_NOTICE, __FILE__, __LINE__);
     321            $app->logMsg(sprintf('IPN response received: %s', $this->_ipn_response), LOG_NOTICE, __FILE__, __LINE__);
    307322            return true;
    308323        }
     
    318333    function verifiedIPN()
    319334    {
     335        $app =& App::getInstance();
     336
    320337        if (!isset($this->_ipn_response)) {
    321             App::logMsg(sprintf('Cannot verify IPN, response not received.', null), LOG_WARNING, __FILE__, __LINE__);
     338            $app->logMsg(sprintf('Cannot verify IPN, response not received.', null), LOG_WARNING, __FILE__, __LINE__);
    322339            return false;
    323340        }
    324341
    325342        if (empty($this->_ipn_response)) {
    326             App::logMsg(sprintf('Cannot verify IPN, response empty.', null), LOG_WARNING, __FILE__, __LINE__);
     343            $app->logMsg(sprintf('Cannot verify IPN, response empty.', null), LOG_WARNING, __FILE__, __LINE__);
    327344            return false;
    328345        }
    329346
    330347        if (preg_match('/VERIFIED/', $this->_ipn_response)) {
    331             App::logMsg(sprintf('IPN verified!', null), LOG_DEBUG, __FILE__, __LINE__);
     348            $app->logMsg(sprintf('IPN verified!', null), LOG_DEBUG, __FILE__, __LINE__);
    332349            return true;
    333350        } else if (preg_match('/INVALID/', $this->_ipn_response)) {
    334             App::logMsg(sprintf('IPN invalid.', null), LOG_DEBUG, __FILE__, __LINE__);
    335             return false;
    336         } else {
    337             App::logMsg(sprintf('IPN unknown.', null), LOG_WARNING, __FILE__, __LINE__);
     351            $app->logMsg(sprintf('IPN invalid.', null), LOG_DEBUG, __FILE__, __LINE__);
     352            return false;
     353        } else {
     354            $app->logMsg(sprintf('IPN unknown.', null), LOG_WARNING, __FILE__, __LINE__);
    338355            return false;
    339356        }
  • trunk/lib/Prefs.inc.php

    r42 r136  
    11<?php
    22/**
    3  * Prefs:: provides an API for saving arbitrary values in a user's session.
    4  * Database save routines to come.
     3 * Prefs.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
    55 *
    6  * @inspiration  Horde 2.0's Prefs class. This one is much simpler, but
    7  *               the API for the methods that exist are sort of like Horde's
    8  *               in case we want to be more like it in the future.
     6 * Prefs provides an API for saving arbitrary values in a user's session.
     7 *
    98 * @author  Quinn Comendant <quinn@strangecode.com>
    10  * @version 1.1
     9 * @version 2.1
    1110 */
    1211class Prefs {
    1312
    14     /**
    15      * Where these preferences can be used. To differentiate between preferences
    16      * for a specific script, application, or global.
    17      * @var string $scope
    18      */
    19     var $scope = 'global';
    20 
    21     /**
    22      * Indicator whether we save in the database or not.
    23      * @var boolean $_perpetual
    24      */
    25     var $_perpetual = false;
    26 
    27     /**
    28      * Hash containing connection parameters.
    29      * @var array $params
    30      */
    31     var $params = array();
    32 
     13    // Namespace of this instance of Prefs.
     14    var $_ns;
    3315
    3416    /**
    3517     * Prefs constructor.
    3618     */
    37     function Prefs($dbh=false, $params=array())
     19    function Prefs($namespace='')
    3820    {
    39         $this->params = $params;
    40         $_perpetual = false; // Until database routines are completed.
     21        $this->_ns = '_prefs_' . $namespace;
     22       
     23        // Initialized the prefs array.
     24        if (!isset($_SESSION[$this->_ns])) {
     25            $_SESSION[$this->_ns] = array();
     26        }
    4127    }
    4228
     
    4531     * is not set already.
    4632     *
    47      * @param  string $pref      The name of the preference to modify.
     33     * @param  string $key       The name of the preference to modify.
    4834     * @param  string $val       The new value for this preference.
    49      * @param  string $scope     The scope for this preference.
    50      *
    51      * @return boolean  True if the value was successfully set.
    5235     */
    53     function setDefault($pref, $val, $scope=null)
     36    function setDefault($key, $val)
    5437    {
    55         if (!isset($scope)) {
    56             $scope =& $this->scope;
    57         }
    58 
    59         // No empty values allowed.
    60         if ('' == $pref || '' == $val || '' == $scope) {
    61             return false;
    62         }
    63 
    64         // Initialized the prefs array.
    65         if (!isset($_SESSION['_prefs'])) {
    66             $_SESSION['_prefs'] = array();
    67         }
    68 
    69         // In case boolean or null values are passed as a string.
    70         if ($val == 'true') {
    71             $val = true;
    72         } else if ($val == 'false') {
    73             $val = false;
    74         } else if ($val == 'null') {
    75             $val = null;
    76         }
    77 
    7838        // Set it only if not set already.
    79         if (!isset($_SESSION['_prefs'][$scope][$pref])) {
    80             $_SESSION['_prefs'][$scope][$pref] = $val;
    81             return true;
     39        if (!isset($_SESSION[$this->_ns][$key])) {
     40            $_SESSION[$this->_ns][$key] = $val;
    8241        }
    8342    }
     
    8645     * Sets the given preferences to the specific value,
    8746     *
    88      * @param  string $pref      The name of the preference to modify.
     47     * @param  string $key       The name of the preference to modify.
    8948     * @param  string $val       The new value for this preference.
    90      * @param  string $scope     The scope for this preference.
    91      *
    92      * @return boolean  True if the value was successfully set.
    9349     */
    94     function setValue($pref, $val, $scope=null)
     50    function set($key, $val)
    9551    {
    96         if (!isset($scope)) {
    97             $scope =& $this->scope;
    98         }
    99 
    100         // No empty values allowed.
    101         if ('' == $pref || '' == $val || '' == $scope) {
    102             return false;
    103         }
    104 
    105         // Initialized the prefs array.
    106         if (!isset($_SESSION['_prefs'])) {
    107             $_SESSION['_prefs'] = array();
    108         }
    109 
    110         // In case boolean or null values are passed as a string.
    111         if ($val == 'true') {
    112             $val = true;
    113         } else if ($val == 'false') {
    114             $val = false;
    115         } else if ($val == 'null') {
    116             $val = null;
    117         }
    118 
    119         $_SESSION['_prefs'][$scope][$pref] = $val;
    120         return true;
     52        $_SESSION[$this->_ns][$key] = $val;
    12153    }
    12254
     
    12456     * Returns the value of the requested preference.
    12557     *
    126      * @param string $pref      The name of the preference to retrieve.
    127      * @param string $scope     The scope for this preference.
     58     * @param string $key       The name of the preference to retrieve.
    12859     *
    12960     * @return string           The value of the preference.
    13061     */
    131     function getValue($pref, $scope=null)
     62    function get($key)
    13263    {
    133         if (!isset($scope)) {
    134             $scope =& $this->scope;
    135         }
    136 
    137         return (isset($_SESSION['_prefs'][$scope][$pref])) ? $_SESSION['_prefs'][$scope][$pref] : null;
     64        return (isset($_SESSION[$this->_ns][$key])) ? $_SESSION[$this->_ns][$key] : null;
    13865    }
    13966
     
    14168     * To see if a preference has been set.
    14269     *
    143      * @param string $pref      The name of the preference to check.
    144      * @param string $scope     The scope for this preference.
     70     * @param string $key       The name of the preference to check.
    14571     *
    14672     * @return boolean          True if the preference isset and not empty
    14773     *                          false otherwise.
    14874     */
    149     function exists($pref, $scope=null)
     75    function exists($key)
    15076    {
    151         if (!isset($scope)) {
    152             $scope =& $this->scope;
    153         }
    154 
    155         return isset($_SESSION['_prefs'][$scope][$pref]);
     77        return isset($_SESSION[$this->_ns][$key]);
    15678    }
    15779
     
    15981     * Clear a set preference value.
    16082     *
    161      * @param string $pref      The name of the preference to check.
    162      * @param string $scope     The scope for this preference.
     83     * @param string $key       The name of the preference to check.
    16384     */
    164     function clearValue($pref, $scope=null)
     85    function delete($key)
    16586    {
    166         if (!isset($scope)) {
    167             $scope =& $this->scope;
     87        if (isset($_SESSION[$this->_ns][$key])) {
     88            unset($_SESSION[$this->_ns][$key]);
    16889        }
    169 
    170         if (isset($_SESSION['_prefs'][$scope][$pref])) {
    171             unset($_SESSION['_prefs'][$scope][$pref]);
    172         }
    173     }
    174 
    175     /**
    176      * Retrieves the requested set of preferences from the user's database
    177      * entry.
    178      *
    179      * @param optional array $prefs  An array listing the preferences to
    180      *                     retrieve. If not specified, retrieve all of the
    181      *                     preferences listed in the $prefs hash.
    182      *
    183      * @return mixed       True on success or a PEAR_Error object on failure.
    184      */
    185     function retrieve()
    186     {
    187         // Check that we don't have the preferences loaded yet.
    188         if ($_SESSION['_prefs']['loaded'] == true || !$_perpetual) {
    189             return true;
    190         }
    191 
    192         // FIXME: Database query goes here....
    193         return false;
    194 
    195         $_SESSION['_prefs']['loaded'] = true;
    196     }
    197 
    198     /**
    199      * Stores preferences to SQL server.
    200      *
    201      * @param array $prefs (optional) An array listing the preferences to be
    202      *                     stored.  If not specified, store all of the
    203      *                     preferences listed in the $prefs hash.
    204      *
    205      * @return mixed       True on success or a PEAR_Error object on failure.
    206      */
    207     function store($prefs=array())
    208     {
    209         // If we are not storing prefs in perpetually.
    210         if (!$_perpetual) {
    211             return true;
    212         }
    213 
    214         /*
    215          * If a list of preferences to store hasn't been provided in
    216          * $prefs, assume all preferences are desired.
    217          */
    218         if (empty($prefs)) {
    219             $prefs =& $_SESSION['_prefs'];
    220         } else if ($_SESSION['_prefs']['loaded'] == true) {
    221             $prefs = array_merge($_SESSION['_prefs'], $prefs);
    222         }
    223 
    224         if (!is_array($prefs) || empty($prefs)) {
    225             App::raiseMsg(_("No preferences are available."), MSG_ERR, __FILE__, __LINE__);
    226             App::dieBoomerangURL();
    227         }
    228 
    229         // FIXME: Database query goes here....
    230         return false;
    231 
    23290    }
    23391
     
    23593     * Perform cleanup operations.
    23694     */
    237     function cleanup()
     95    function clear()
    23896    {
    239         $_SESSION['_prefs'] = array();
     97        $_SESSION[$this->_ns] = array();
    24098    }
    24199}
    242100
    243101
    244 
    245 
    246102?>
  • trunk/lib/RecordLock.inc.php

    r111 r136  
    11<?php
    22/**
    3  * The RecordLock:: class provides a system for locking abstract DB rows.
     3 * RecordLock.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * The RecordLock class provides a system for locking abstract DB rows.
    47 *
    58 * @author  Quinn Comendant <quinn@strangecode.com>
    6  * @version 2.0
     9 * @version 2.1
    710 */
    811class RecordLock {
     
    3235    function &getInstance($auth_object)
    3336    {
    34         static $instances = array();
    35 
    36         if (!isset($instances[$auth_object->getVal('auth_name')])) {
    37             $instances[$auth_object->getVal('auth_name')] = new RecordLock($auth_object);
    38         }
    39 
    40         return $instances[$auth_object->getVal('auth_name')];
     37        static $instance = null;
     38
     39        if ($instance === null) {
     40            $instance = new RecordLock($auth_object);
     41        }
     42
     43        return $instance;
    4144    }
    4245
     
    4447     * Constructor. Pass an Auth object on which to perform user lookups.
    4548     *
    46      * @param mixed  $auth_object  An Auth_SQL object.
     49     * @param mixed  $auth_object  An Auth_SQL or Auth_FILE object.
    4750     */
    4851    function RecordLock($auth_object)
    4952    {
    50         if (!is_a($auth_object, 'Auth_SQL')) {
    51             trigger_error('Constructor not provided a valid Auth_SQL object.', E_USER_ERROR);
     53        $app =& App::getInstance();
     54
     55        if (!method_exists($auth_object, 'getVal') || !method_exists($auth_object, 'getUsername')) {
     56            trigger_error('Constructor not provided a valid Auth_* object.', E_USER_ERROR);
    5257        }
    5358
     
    5560
    5661        // Get create tables config from global context.
    57         if (!is_null(App::getParam('db_create_tables'))) {
    58             $this->setParam(array('create_table' => App::getParam('db_create_tables')));
     62        if (!is_null($app->getParam('db_create_tables'))) {
     63            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
    5964        }
    6065    }
     
    6974    function initDB($recreate_db=false)
    7075    {
     76        $app =& App::getInstance();
     77        $db =& DB::getInstance();
     78
    7179        static $_db_tested = false;
    7280
    7381        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
    7482            if ($recreate_db) {
    75                 DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
    76                 App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
     83                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
     84                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
    7785            }
    78             DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
     86            $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
    7987                lock_id int NOT NULL auto_increment,
    8088                record_table varchar(255) NOT NULL default '',
     
    9098            )");
    9199
    92             if (!DB::columnExists($this->getParam('db_table'), array(
     100            if (!$db->columnExists($this->getParam('db_table'), array(
    93101                'lock_id',
    94102                'record_table',
     
    99107                'lock_datetime',
    100108            ), false, false)) {
    101                 App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
     109                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
    102110                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
    103111            }
     
    120128
    121129    /**
    122      * Return the value of a param setting.
    123      *
    124      * @access  public
    125      * @param   string  $params Which param to return.
    126      * @return  mixed   Configured param value.
     130     * Return the value of a parameter, if it exists.
     131     *
     132     * @access public
     133     * @param string $param        Which parameter to return.
     134     * @return mixed               Configured parameter value.
    127135     */
    128136    function getParam($param)
    129137    {
     138        $app =& App::getInstance();
     139   
    130140        if (isset($this->_params[$param])) {
    131141            return $this->_params[$param];
    132142        } else {
    133             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     143            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    134144            return null;
    135145        }
     
    147157    function select($record_table_or_lock_id, $record_key=null, $record_val=null)
    148158    {
     159        $app =& App::getInstance();
     160        $db =& DB::getInstance();
     161
    149162        $this->initDB();
    150163
     
    154167        if (is_numeric($record_table_or_lock_id) && !isset($record_key) && !isset($record_val)) {
    155168            // Get lock data by lock_id.
    156             $qid = DB::query("
     169            $qid = $db->query("
    157170                SELECT * FROM " . $this->getParam('db_table') . "
    158                 WHERE lock_id = '" . DB::escapeString($record_table_or_lock_id) . "'
     171                WHERE lock_id = '" . $db->escapeString($record_table_or_lock_id) . "'
    159172            ");
    160173        } else {
    161174            // Get lock data by record specs
    162             $qid = DB::query("
     175            $qid = $db->query("
    163176                SELECT * FROM " . $this->getParam('db_table') . "
    164                 WHERE record_table = '" . DB::escapeString($record_table_or_lock_id) . "'
    165                 AND record_key = '" . DB::escapeString($record_key) . "'
    166                 AND record_val = '" . DB::escapeString($record_val) . "'
     177                WHERE record_table = '" . $db->escapeString($record_table_or_lock_id) . "'
     178                AND record_key = '" . $db->escapeString($record_key) . "'
     179                AND record_val = '" . $db->escapeString($record_val) . "'
    167180            ");
    168181        }
    169182        if ($this->data = mysql_fetch_assoc($qid)) {
    170             App::logMsg(sprintf('Selecting %slocked record: %s %s %s', ($this->data['set_by_admin_id'] == $this->_auth->getVal('user_id') ? 'self-' : ''), $record_table_or_lock_id, $record_key, $record_val), LOG_DEBUG, __FILE__, __LINE__);
     183            $app->logMsg(sprintf('Selecting %slocked record: %s %s %s', ($this->data['set_by_admin_id'] == $this->_auth->getVal('user_id') ? 'self-' : ''), $record_table_or_lock_id, $record_key, $record_val), LOG_DEBUG, __FILE__, __LINE__);
    171184            /// FIX ME: What if admin set lock, but public user is current lock user?
    172185            $this->data['editor'] = $this->_auth->getUsername($this->data['set_by_admin_id']);
    173186            return true;
    174187        } else {
    175             App::logMsg(sprintf('No locked record: %s %s %s', $record_table_or_lock_id, $record_key, $record_val), LOG_DEBUG, __FILE__, __LINE__);
     188            $app->logMsg(sprintf('No locked record: %s %s %s', $record_table_or_lock_id, $record_key, $record_val), LOG_DEBUG, __FILE__, __LINE__);
    176189            return false;
    177190        }
     
    196209    function isMine()
    197210    {
     211        $db =& DB::getInstance();
     212   
    198213        $this->initDB();
    199214
    200215        if (isset($this->data['lock_id'])) {
    201             $qid = DB::query("SELECT * FROM " . $this->getParam('db_table') . " WHERE lock_id = '" . DB::escapeString($this->data['lock_id']) . "'");
     216            $qid = $db->query("SELECT * FROM " . $this->getParam('db_table') . " WHERE lock_id = '" . $db->escapeString($this->data['lock_id']) . "'");
    202217            if ($lock = mysql_fetch_assoc($qid)) {
    203218                return ($lock['set_by_admin_id'] == $this->_auth->getVal('user_id'));
     
    222237    function set($record_table, $record_key, $record_val, $title='')
    223238    {
     239        $db =& DB::getInstance();
     240   
    224241        $this->initDB();
    225242
     
    228245
    229246        // Remove previous locks if exist. Is this better than using a REPLACE INTO?
    230         DB::query("
     247        $db->query("
    231248            DELETE FROM " . $this->getParam('db_table') . "
    232             WHERE record_table = '" . DB::escapeString($record_table) . "'
    233             AND record_key = '" . DB::escapeString($record_key) . "'
    234             AND record_val = '" . DB::escapeString($record_val) . "'
     249            WHERE record_table = '" . $db->escapeString($record_table) . "'
     250            AND record_key = '" . $db->escapeString($record_key) . "'
     251            AND record_val = '" . $db->escapeString($record_val) . "'
    235252        ");
    236253
    237254        // Set new lock.
    238         DB::query("
     255        $db->query("
    239256            INSERT INTO " . $this->getParam('db_table') . " (
    240257                record_table,
     
    245262                lock_datetime
    246263            ) VALUES (
    247                 '" . DB::escapeString($record_table) . "',
    248                 '" . DB::escapeString($record_key) . "',
    249                 '" . DB::escapeString($record_val) . "',
    250                 '" . DB::escapeString($title) . "',
    251                 '" . DB::escapeString($this->_auth->getVal('user_id')) . "',
     264                '" . $db->escapeString($record_table) . "',
     265                '" . $db->escapeString($record_key) . "',
     266                '" . $db->escapeString($record_val) . "',
     267                '" . $db->escapeString($title) . "',
     268                '" . $db->escapeString($this->_auth->getVal('user_id')) . "',
    252269                NOW()
    253270            )
    254271        ");
    255         $lock_id = mysql_insert_id(DB::getDBH());
     272        $lock_id = mysql_insert_id($db->getDBH());
    256273
    257274        // Must register this locked record as the current.
     
    266283    function remove()
    267284    {
     285        $app =& App::getInstance();
     286        $db =& DB::getInstance();
     287
    268288        $this->initDB();
    269289
     
    272292
    273293        // Delete a specific lock.
    274         DB::query("
     294        $db->query("
    275295            DELETE FROM " . $this->getParam('db_table') . "
    276             WHERE lock_id = '" . DB::escapeString($this->data['lock_id']) . "'
     296            WHERE lock_id = '" . $db->escapeString($this->data['lock_id']) . "'
    277297        ");
    278298
    279         App::logMsg(sprintf('Removing lock: %s', $this->data['lock_id']), LOG_DEBUG, __FILE__, __LINE__);
     299        $app->logMsg(sprintf('Removing lock: %s', $this->data['lock_id']), LOG_DEBUG, __FILE__, __LINE__);
    280300    }
    281301
     
    285305    function removeAll($user_id=null)
    286306    {
     307        $app =& App::getInstance();
     308        $db =& DB::getInstance();
     309
    287310        $this->initDB();
    288311
     
    292315        if (isset($user_id)) {
    293316            // Delete specific user's locks.
    294             DB::query("DELETE FROM " . $this->getParam('db_table') . " WHERE set_by_admin_id = '" . DB::escapeString($user_id) . "'");
    295             App::logMsg(sprintf('Record locks owned by %s %s have been deleted', $this->_auth->getVal('auth_name'), $this->_auth->getUsername($user_id)), LOG_DEBUG, __FILE__, __LINE__);
     317            $db->query("DELETE FROM " . $this->getParam('db_table') . " WHERE set_by_admin_id = '" . $db->escapeString($user_id) . "'");
     318            $app->logMsg(sprintf('Record locks owned by %s %s have been deleted', $this->_auth->getVal('auth_name'), $this->_auth->getUsername($user_id)), LOG_DEBUG, __FILE__, __LINE__);
    296319        } else {
    297320            // Delete ALL locks.
    298             DB::query("DELETE FROM " . $this->getParam('db_table') . "");
    299             App::logMsg(sprintf('All record locks deleted by %s %s', $this->_auth->getVal('auth_name'), $this->_auth->getVal('username')), LOG_DEBUG, __FILE__, __LINE__);
     321            $db->query("DELETE FROM " . $this->getParam('db_table') . "");
     322            $app->logMsg(sprintf('All record locks deleted by %s %s', $this->_auth->getVal('auth_name'), $this->_auth->getVal('username')), LOG_DEBUG, __FILE__, __LINE__);
    300323        }
    301324    }
     
    306329    function _auto_timeout()
    307330    {
     331        $db =& DB::getInstance();
     332   
    308333        static $_timeout_run = false;
    309334
     
    312337        if (!$_timeout_run) {
    313338            // Delete all old locks.
    314             DB::query("
     339            $db->query("
    315340                DELETE FROM " . $this->getParam('db_table') . "
    316341                WHERE DATE_ADD(lock_datetime, INTERVAL '" . $this->getParam('auto_timeout') . "' SECOND) < NOW()
     
    325350    function dieErrorPage()
    326351    {
    327         App::dieURL(sprintf('%s?lock_id=%s&boomerang=%s', $this->getParam('error_url'), $this->data['lock_id'], urlencode(absoluteMe())));
     352        $app =& App::getInstance();
     353
     354        $app->dieURL(sprintf('%s?lock_id=%s&boomerang=%s', $this->getParam('error_url'), $this->data['lock_id'], urlencode(absoluteMe())));
    328355    }
    329356
     
    333360    function printErrorHTML()
    334361    {
     362        $app =& App::getInstance();
     363
    335364        ?>
    336365        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    337         <?php App::printHiddenSession() ?>
     366        <?php $app->printHiddenSession() ?>
    338367        <input type="hidden" name="lock_id" value="<?php echo $this->getID(); ?>" />
    339368
  • trunk/lib/RecordVersion.inc.php

    r111 r136  
    11<?php
    22/**
    3  * The RecordVersion:: class provides a system for saving, reviewing, and
     3 * RecordVersion.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
     6 * The RecordVersion class provides a system for saving, reviewing, and
    47 * restoring versions of a record of any DB table. All the data in the record is
    58 * serialized, compressed, and saved in a blob in the version_tbl. Restoring a
     
    1417 * @version 2.1
    1518 */
    16 
    1719class RecordVersion {
    1820
     
    3335     * This method enforces the singleton pattern for this class.
    3436     *
    35      * @return  object  Reference to the global RecordVersion object.
     37     * @return  object  Reference to the global RecordLock object.
    3638     * @access  public
    3739     * @static
     
    3941    function &getInstance($auth_object)
    4042    {
    41         static $instances = array();
    42 
    43         if (!isset($instances[$auth_object->getVal('auth_name')])) {
    44             $instances[$auth_object->getVal('auth_name')] = new RecordVersion($auth_object);
    45         }
    46 
    47         return $instances[$auth_object->getVal('auth_name')];
     43        static $instance = null;
     44
     45        if ($instance === null) {
     46            $instance = new RecordVersion($auth_object);
     47        }
     48
     49        return $instance;
    4850    }
    4951
     
    5557    function RecordVersion($auth_object)
    5658    {
    57         if (!is_a($auth_object, 'Auth_SQL')) {
    58             trigger_error('Constructor not provided a valid Auth_SQL object.', E_USER_ERROR);
     59        $app =& App::getInstance();
     60
     61        if (!method_exists($auth_object, 'getVal') || !method_exists($auth_object, 'getUsername')) {
     62            trigger_error('Constructor not provided a valid Auth_* object.', E_USER_ERROR);
    5963        }
    6064
     
    6266
    6367        // Get create tables config from global context.
    64         if (!is_null(App::getParam('db_create_tables'))) {
    65             $this->setParam(array('create_table' => App::getParam('db_create_tables')));
     68        if (!is_null($app->getParam('db_create_tables'))) {
     69            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
    6670        }
    6771    }
     
    7680    function initDB($recreate_db=false)
    7781    {
     82        $app =& App::getInstance();
     83        $db =& DB::getInstance();
     84
    7885        static $_db_tested = false;
    7986
    8087        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
    8188            if ($recreate_db) {
    82                 DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
    83                 App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
     89                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
     90                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
    8491            }
    85             DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
     92            $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
    8693                version_id int NOT NULL auto_increment,
    8794                record_table varchar(255) NOT NULL default '',
     
    99106            )");
    100107
    101             if (!DB::columnExists($this->getParam('db_table'), array(
     108            if (!$db->columnExists($this->getParam('db_table'), array(
    102109                'version_id',
    103110                'record_table',
     
    110117                'version_datetime',
    111118            ), false, false)) {
    112                 App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
     119                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
    113120                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
    114121            }
     
    131138
    132139    /**
    133      * Return the value of a param setting.
    134      *
    135      * @access  public
    136      * @param   string  $params Which param to return.
    137      * @return  mixed   Configured param value.
     140     * Return the value of a parameter, if it exists.
     141     *
     142     * @access public
     143     * @param string $param        Which parameter to return.
     144     * @return mixed               Configured parameter value.
    138145     */
    139146    function getParam($param)
    140147    {
     148        $app =& App::getInstance();
     149   
    141150        if (isset($this->_params[$param])) {
    142151            return $this->_params[$param];
    143152        } else {
    144             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     153            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    145154            return null;
    146155        }
     
    159168    function create($record_table, $record_key, $record_val, $title='', $notes='')
    160169    {
     170        $app =& App::getInstance();
     171        $db =& DB::getInstance();
     172
    161173        $this->initDB();
    162174
    163175        // Get current record.
    164176        if (!$record = $this->getCurrent($record_table, $record_key, $record_val)) {
    165             App::logMsg(sprintf('Could not create %s version, record not found: %s, %s, %s.', $title, $record_table, $record_key, $record_val), LOG_ERR, __FILE__, __LINE__);
     177            $app->logMsg(sprintf('Could not create %s version, record not found: %s, %s, %s.', $title, $record_table, $record_key, $record_val), LOG_ERR, __FILE__, __LINE__);
    166178            return false;
    167179        }
     
    171183
    172184        // Save as new version.
    173         DB::query("
     185        $db->query("
    174186            INSERT INTO " . $this->getParam('db_table') . " (
    175187                record_table,
     
    182194                version_datetime
    183195            ) VALUES (
    184                 '" . DB::escapeString($record_table) . "',
    185                 '" . DB::escapeString($record_key) . "',
    186                 '" . DB::escapeString($record_val) . "',
    187                 '" . DB::escapeString(gzcompress(serialize($record), 9)) . "',
    188                 '" . DB::escapeString($title) . "',
    189                 '" . DB::escapeString($notes) . "',
    190                 '" . DB::escapeString($this->_auth->getVal('user_id')) . "',
     196                '" . $db->escapeString($record_table) . "',
     197                '" . $db->escapeString($record_key) . "',
     198                '" . $db->escapeString($record_val) . "',
     199                '" . $db->escapeString(gzcompress(serialize($record), 9)) . "',
     200                '" . $db->escapeString($title) . "',
     201                '" . $db->escapeString($notes) . "',
     202                '" . $db->escapeString($this->_auth->getVal('user_id')) . "',
    191203                NOW()
    192204            )
    193205        ");
    194206
    195         return mysql_insert_id(DB::getDBH());
     207        return mysql_insert_id($db->getDBH());
    196208    }
    197209
     
    205217    function restore($version_id)
    206218    {
     219        $app =& App::getInstance();
     220        $db =& DB::getInstance();
     221
    207222        $this->initDB();
    208223
    209224        // Get version data.
    210         $qid = DB::query("
     225        $qid = $db->query("
    211226            SELECT * FROM " . $this->getParam('db_table') . "
    212             WHERE version_id = '" . DB::escapeString($version_id) . "'
     227            WHERE version_id = '" . $db->escapeString($version_id) . "'
    213228        ");
    214229        if (!$record = mysql_fetch_assoc($qid)) {
    215             App::raiseMsg(sprintf(_("Version ID %s%s not found."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_WARNING, __FILE__, __LINE__);
    216             App::logMsg(sprintf(_("Version ID %s%s not found."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), LOG_WARNING, __FILE__, __LINE__);
     230            $app->raiseMsg(sprintf(_("Version ID %s%s not found."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_WARNING, __FILE__, __LINE__);
     231            $app->logMsg(sprintf(_("Version ID %s%s not found."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), LOG_WARNING, __FILE__, __LINE__);
    217232            return false;
    218233        }
     
    220235
    221236        // Ensure saved db columns match current table schema.
    222         if (!DB::columnExists($record['record_table'], array_keys($data), $this->getParam('db_schema_strict'))) {
    223             App::raiseMsg(sprintf(_("Version ID %s%s is not compatible with the current database table."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_ERR, __FILE__, __LINE__);
    224             App::logMsg(sprintf(_("Version ID %s%s restoration failed, DB schema does not match for table %s."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')'), $record['record_table']), LOG_ALERT, __FILE__, __LINE__);
     237        if (!$db->columnExists($record['record_table'], array_keys($data), $this->getParam('db_schema_strict'))) {
     238            $app->raiseMsg(sprintf(_("Version ID %s%s is not compatible with the current database table."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_ERR, __FILE__, __LINE__);
     239            $app->logMsg(sprintf(_("Version ID %s%s restoration failed, DB schema does not match for table %s."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')'), $record['record_table']), LOG_ALERT, __FILE__, __LINE__);
    225240            return false;
    226241        }
    227242
    228243        // SQLize the keys of the specified versioned record.
    229         $replace_keys = join(",\n", array_map(array('DB', 'escapeString'), array_keys($data)));
     244        $replace_keys = join(",\n", array_map(array($db, 'escapeString'), array_keys($data)));
    230245
    231246        // SQLize the keys of the values of the specified versioned record. (These are more complex because we need to account for SQL null values.)
     
    233248        $comma = '';
    234249        foreach ($data as $v) {
    235             $replace_values .= is_null($v) ? "$comma\nNULL" : "$comma\n'" . DB::escapeString($v) . "'";
     250            $replace_values .= is_null($v) ? "$comma\nNULL" : "$comma\n'" . $db->escapeString($v) . "'";
    236251            $comma = ',';
    237252        }
    238253
    239254        // Replace current record with specified versioned record.
    240         DB::query("
     255        $db->query("
    241256            REPLACE INTO " . $record['record_table'] . " (
    242257                $replace_keys
     
    263278    function deleteOld($record_table, $record_key, $record_val)
    264279    {
     280        $db =& DB::getInstance();
     281   
    265282        $this->initDB();
    266283
    267284        // Get total number of versions for this record.
    268         $qid = DB::query("
     285        $qid = $db->query("
    269286            SELECT COUNT(*) FROM " . $this->getParam('db_table') . "
    270             WHERE record_table = '" . DB::escapeString($record_table) . "'
    271             AND record_key = '" . DB::escapeString($record_key) . "'
    272             AND record_val = '" . DB::escapeString($record_val) . "'
     287            WHERE record_table = '" . $db->escapeString($record_table) . "'
     288            AND record_key = '" . $db->escapeString($record_key) . "'
     289            AND record_val = '" . $db->escapeString($record_val) . "'
    273290        ");
    274291        list($v_count) = mysql_fetch_row($qid);
     
    278295                // To prevent a record bomb, limit max number of versions to max_qty.
    279296                // First query for oldest records, selecting enough to bring total number down to min_qty.
    280                 $qid = DB::query("
     297                $qid = $db->query("
    281298                    SELECT version_id FROM " . $this->getParam('db_table') . "
    282                     WHERE record_table = '" . DB::escapeString($record_table) . "'
    283                     AND record_key = '" . DB::escapeString($record_key) . "'
    284                     AND record_val = '" . DB::escapeString($record_val) . "'
     299                    WHERE record_table = '" . $db->escapeString($record_table) . "'
     300                    AND record_key = '" . $db->escapeString($record_key) . "'
     301                    AND record_val = '" . $db->escapeString($record_val) . "'
    285302                    ORDER BY version_datetime ASC
    286303                    LIMIT " . ($v_count - $this->getParam('min_qty')) . "
     
    289306                    $old_versions[] = $old_id;
    290307                }
    291                 DB::query("
     308                $db->query("
    292309                    DELETE FROM " . $this->getParam('db_table') . "
    293310                    WHERE version_id IN ('" . join("','", $old_versions) . "')
     
    295312            } else {
    296313                // Delete versions older than min_days, while still keeping min_qty.
    297                 $qid = DB::query("
     314                $qid = $db->query("
    298315                    SELECT version_id FROM " . $this->getParam('db_table') . "
    299                     WHERE record_table = '" . DB::escapeString($record_table) . "'
    300                     AND record_key = '" . DB::escapeString($record_key) . "'
    301                     AND record_val = '" . DB::escapeString($record_val) . "'
     316                    WHERE record_table = '" . $db->escapeString($record_table) . "'
     317                    AND record_key = '" . $db->escapeString($record_key) . "'
     318                    AND record_val = '" . $db->escapeString($record_val) . "'
    302319                    AND DATE_ADD(version_datetime, INTERVAL '" . $this->getParam('min_days') . "' DAY) < NOW()
    303320                    ORDER BY version_datetime ASC
     
    308325                }
    309326                if (sizeof($old_versions) > 0) {
    310                     DB::query("
     327                    $db->query("
    311328                        DELETE FROM " . $this->getParam('db_table') . "
    312329                        WHERE version_id IN ('" . join("','", $old_versions) . "')
     
    328345    function getList($record_table, $record_key, $record_val)
    329346    {
     347        $db =& DB::getInstance();
     348   
    330349        $this->initDB();
    331350
    332351        // Get versions of this record.
    333         $qid = DB::query("
     352        $qid = $db->query("
    334353            SELECT version_id, saved_by_admin_id, version_datetime, version_title
    335354            FROM " . $this->getParam('db_table') . "
    336             WHERE record_table = '" . DB::escapeString($record_table) . "'
    337             AND record_key = '" . DB::escapeString($record_key) . "'
    338             AND record_val = '" . DB::escapeString($record_val) . "'
     355            WHERE record_table = '" . $db->escapeString($record_table) . "'
     356            AND record_key = '" . $db->escapeString($record_key) . "'
     357            AND record_val = '" . $db->escapeString($record_val) . "'
    339358            ORDER BY version_datetime DESC
    340359        ");
     
    357376    function getVerson($version_id)
    358377    {
     378        $db =& DB::getInstance();
     379   
    359380        $this->initDB();
    360381
    361382        // Get version data.
    362         $qid = DB::query("
     383        $qid = $db->query("
    363384            SELECT * FROM " . $this->getParam('db_table') . "
    364             WHERE version_id = '" . DB::escapeString($version_id) . "'
     385            WHERE version_id = '" . $db->escapeString($version_id) . "'
    365386        ");
    366387        return mysql_fetch_assoc($qid);
     
    376397    function getData($version_id)
    377398    {
     399        $db =& DB::getInstance();
     400   
    378401        $this->initDB();
    379402
    380403        // Get version data.
    381         $qid = DB::query("
     404        $qid = $db->query("
    382405            SELECT * FROM " . $this->getParam('db_table') . "
    383             WHERE version_id = '" . DB::escapeString($version_id) . "'
     406            WHERE version_id = '" . $db->escapeString($version_id) . "'
    384407        ");
    385408        $record = mysql_fetch_assoc($qid);
     
    400423    function getCurrent($record_table, $record_key, $record_val)
    401424    {
    402         $this->initDB();
    403 
    404         $qid = DB::query("
    405             SELECT * FROM " . DB::escapeString($record_table) . "
    406             WHERE " . DB::escapeString($record_key) . " = '" . DB::escapeString($record_val) . "'
     425        $db =& DB::getInstance();
     426   
     427        $this->initDB();
     428
     429        $qid = $db->query("
     430            SELECT * FROM " . $db->escapeString($record_table) . "
     431            WHERE " . $db->escapeString($record_key) . " = '" . $db->escapeString($record_val) . "'
    407432        ");
    408433        if ($record = mysql_fetch_assoc($qid)) {
  • trunk/lib/ScriptTimer.inc.php

    r92 r136  
    11<?php
    22/**
    3  * ScriptTimer.inc.php 
    4  * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
     3 * ScriptTimer.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
    55 */
    6  
    76class ScriptTimer {
    87
  • trunk/lib/SessionCache.inc.php

    r119 r136  
    11<?php
    22/**
    3  * SessionCache.inc.php
     3 * Cache.inc.php
     4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
     5 *
    46 * Provides an API for storing a limited amount of data
    57 * intended to have a short lifetime in a user's session.
    68 *
    7  * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information.
    89 * @author  Quinn Comendant <quinn@strangecode.com>
    9  * @version 1.2
     10 * @version 2.1
    1011 * @since   2001
    1112 */
    12 class SessionCache
    13 {
     13 
     14// Flags.
     15define('CACHE_IGNORE_SIZE', 1);
     16
     17class Cache {
     18
    1419    var $_params = array(
    1520        'enabled' => true,
     
    2227     * This method enforces the singleton pattern for this class.
    2328     *
    24      * @return  object  Reference to the global SessionCache object.
     29     * @return  object  Reference to the global Cache object.
    2530     * @access  public
    2631     * @static
    2732     */
    28     function &getInstance() {
     33    function &getInstance()
     34    {
    2935        static $instance = null;
    3036
    3137        if ($instance === null) {
    32             $instance = new SessionCache();
     38            $instance = new Cache();
    3339        }
    3440
     
    4450    function setParam($params)
    4551    {
    46         if (!isset($_this) || !is_a($_this, 'SessionCache') && !is_subclass_of($_this, 'SessionCache')) {
    47             $_this =& SessionCache::getInstance();
    48         }
     52        $app =& App::getInstance();
    4953
    5054        if (isset($params) && is_array($params)) {
    5155            // Merge new parameters with old overriding only those passed.
    52             $_this->_params = array_merge($_this->_params, $params);
    53         } else {
    54             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     56            $this->_params = array_merge($this->_params, $params);
     57        } else {
     58            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    5559        }
    5660    }
     
    6569    function getParam($param)
    6670    {
    67         if (!isset($_this) || !is_a($_this, 'SessionCache') && !is_subclass_of($_this, 'SessionCache')) {
    68             $_this =& SessionCache::getInstance();
    69         }
    70 
    71         if (isset($_this->_params[$param])) {
    72             return $_this->_params[$param];
    73         } else {
    74             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     71        $app =& App::getInstance();
     72   
     73        if (isset($this->_params[$param])) {
     74            return $this->_params[$param];
     75        } else {
     76            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    7577            return null;
    7678        }
     
    7880
    7981    /**
    80      * Stores a new variable in the session cache. The $var_id is is md5'ed
     82     * Stores a new variable in the session cache. The $key is is md5'ed
    8183     * because if a variable id is a very large integer, the array_shift function
    82      * will reset the key to the next largest int key. Weird behaviour I can't
     84     * will reset the key to the next largest int key. Weird behavior I can't
    8385     * understand. $session_cache[32341234123] will become $session_cache[0]
    8486     * for example. Usage warning: if the variable is too big to fit, or is
    8587     * old and discarded, you must provide alternative ways of accessing the data.
    8688     *
     89     * @param str   $key        An identifier for the cached object.
    8790     * @param mixed $var          The var to store in the session cache.
    88      * @param str   $var_id       An identifyer for the cached object.
    89      * @param bool  $force_it_in  If we have something really big that we
    90      *                            still want to cache, setting this true
    91      *                            allows this.
    92      *
    93      * @return string        The $var_id, or false if the object was too big to cache.
    94      */
    95     function putCache($var, $var_id, $force_it_in=false)
    96     {
    97         if (!isset($_this) || !is_a($_this, 'SessionCache') && !is_subclass_of($_this, 'SessionCache')) {
    98             $_this =& SessionCache::getInstance();
    99         }
    100 
    101         if (!$_this->getParam('enabled')) {
    102             App::logMsg(sprintf('SessionCache not enabled, not saving data.', null), LOG_DEBUG, __FILE__, __LINE__);
    103             return false;
    104         }
    105 
    106         $var_id = md5($var_id);
     91     * @param bool  $flags      If we have something really big that we
     92     *                            still want to cache, setting this to
     93     *                            CACHE_IGNORE_SIZE allows this.
     94     *
     95     * @return bool               True on success, false otherwise.
     96     */
     97    function set($key, $var, $flags=0)
     98    {
     99        $app =& App::getInstance();
     100
     101        if (!$this->getParam('enabled')) {
     102            $app->logMsg(sprintf('Cache not enabled, not saving data.', null), LOG_DEBUG, __FILE__, __LINE__);
     103            return false;
     104        }
     105
     106        $key = md5($key);
    107107        $serialized_var = serialize($var);
    108108        $serialized_var_len = strlen($serialized_var);
    109109
    110         if ($serialized_var_len >= $_this->getParam('soft_limit') && !$force_it_in) {
    111             App::logMsg(sprintf('Serialized variable (%s bytes) more than soft_limit (%s bytes).', $serialized_var_len, $_this->getParam('soft_limit')), LOG_NOTICE, __FILE__, __LINE__);
    112             return false;
    113         }
    114 
    115         if ($serialized_var_len >= $_this->getParam('hard_limit')) {
    116             App::logMsg(sprintf('Serialized variable (%s bytes) more than hard_limit (%s bytes).', $serialized_var_len, $_this->getParam('hard_limit')), LOG_NOTICE, __FILE__, __LINE__);
     110        if ($flags & CACHE_IGNORE_SIZE > 0 && $serialized_var_len >= $this->getParam('soft_limit')) {
     111            $app->logMsg(sprintf('Serialized variable (%s bytes) more than soft_limit (%s bytes).', $serialized_var_len, $this->getParam('soft_limit')), LOG_NOTICE, __FILE__, __LINE__);
     112            return false;
     113        }
     114
     115        if ($serialized_var_len >= $this->getParam('hard_limit')) {
     116            $app->logMsg(sprintf('Serialized variable (%s bytes) more than hard_limit (%s bytes).', $serialized_var_len, $this->getParam('hard_limit')), LOG_NOTICE, __FILE__, __LINE__);
    117117            return false;
    118118        }
     
    121121            $_SESSION['_session_cache'] = array();
    122122        } else {
    123             unset($_SESSION['_session_cache'][$var_id]);
     123            unset($_SESSION['_session_cache'][$key]);
    124124            // Continue to prune the cache if it's length is too long for the new variable to fit, but keep at least MIN_ITEMS at least.
    125             while (strlen(serialize($_SESSION['_session_cache'])) + $serialized_var_len >= $_this->getParam('soft_limit')
    126             && sizeof($_SESSION['_session_cache']) >= $_this->getParam('min_items')) {
     125            while (strlen(serialize($_SESSION['_session_cache'])) + $serialized_var_len >= $this->getParam('soft_limit')
     126            && sizeof($_SESSION['_session_cache']) >= $this->getParam('min_items')) {
    127127                array_shift($_SESSION['_session_cache']);
    128128            }
    129129        }
    130         $_SESSION['_session_cache'][$var_id] =& $serialized_var;
     130        $_SESSION['_session_cache'][$key] =& $serialized_var;
    131131
    132132        if ($serialized_var_len >= 1024000) {
    133             App::logMsg(sprintf('Successfully cached oversized variable (%s bytes).', $serialized_var_len), LOG_DEBUG, __FILE__, __LINE__);
    134         }
    135 
    136         return $var_id;
     133            $app->logMsg(sprintf('Successfully cached oversized variable (%s bytes).', $serialized_var_len), LOG_DEBUG, __FILE__, __LINE__);
     134        }
     135
     136        return true;
    137137    }
    138138
     
    143143     * first.
    144144     *
    145      * @param string $var_id  The identifyer for the datum to retrieve.
     145     * @param string $key  The key for the datum to retrieve.
    146146     *
    147147     * @return mixed          The requested datum, or false on failure.
    148148     */
    149     function getCache($var_id)
    150     {
    151         if (!isset($_this) || !is_a($_this, 'SessionCache') && !is_subclass_of($_this, 'SessionCache')) {
    152             $_this =& SessionCache::getInstance();
    153         }
    154 
    155         if (!$_this->getParam('enabled')) {
    156             return false;
    157         }
    158 
    159         $var_id = md5($var_id);
    160         if (isset($_SESSION['_session_cache'][$var_id])) {
     149    function get($key)
     150    {
     151        if (!$this->getParam('enabled')) {
     152            return false;
     153        }
     154
     155        $key = md5($key);
     156        if (isset($_SESSION['_session_cache'][$key])) {
    161157            // Move the accessed cached datum to the top of the stack. Maybe somebody knows a better way to do this?
    162             $tmp =& $_SESSION['_session_cache'][$var_id];
    163             unset($_SESSION['_session_cache'][$var_id]);
    164             $_SESSION['_session_cache'][$var_id] =& $tmp;
     158            $tmp =& $_SESSION['_session_cache'][$key];
     159            unset($_SESSION['_session_cache'][$key]);
     160            $_SESSION['_session_cache'][$key] =& $tmp;
    165161            // Return the unserialized datum.
    166             return unserialize($_SESSION['_session_cache'][$var_id]);
     162            return unserialize($_SESSION['_session_cache'][$key]);
    167163        } else {
    168164            return false;
     
    173169     * Tells you if the object is cached.
    174170     *
    175      * @param string $var_id  The ID of the object to check.
     171     * @param string $key  The key of the object to check.
    176172     *
    177173     * @return bool           The return from isset().
    178174     */
    179     function isCached($var_id)
    180     {
    181         if (!isset($_this) || !is_a($_this, 'SessionCache') && !is_subclass_of($_this, 'SessionCache')) {
    182             $_this =& SessionCache::getInstance();
    183         }
    184 
    185         if (!$_this->getParam('enabled')) {
    186             return false;
    187         }
    188 
    189         $var_id = md5($var_id);
    190         return isset($_SESSION['_session_cache'][$var_id]);
     175    function exists($key)
     176    {
     177        if (!$this->getParam('enabled')) {
     178            return false;
     179        }
     180
     181        $key = md5($key);
     182        return isset($_SESSION['_session_cache'][$key]);
    191183    }
    192184
     
    194186     * Tells you if the object is cached.
    195187     *
    196      * @param string $var_id  The ID of the object to check.
     188     * @param string $key  The key of the object to check.
    197189     *
    198190     * @return bool           The return from isset().
    199191     */
    200     function breakCache($var_id)
    201     {
    202         $var_id = md5($var_id);
    203         if (isset($_SESSION['_session_cache'][$var_id])) {
    204             unset($_SESSION['_session_cache'][$var_id]);
    205         }
    206     }
    207 
    208 // END SessionCache
     192    function delete($key)
     193    {
     194        $key = md5($key);
     195        if (isset($_SESSION['_session_cache'][$key])) {
     196            unset($_SESSION['_session_cache'][$key]);
     197        }
     198    }
     199
     200// END Cache
    209201}
    210202
  • trunk/lib/SortOrder.inc.php

    r119 r136  
    6969    function setDefault($default_sort = '', $default_order = '')
    7070    {
     71        $prefs =& Prefs::getInstance();
     72
    7173        // Which column to sort by?
    7274        // (1) By GET or POST specification, if available.
     
    7678        if (!empty($new_sort_by)) {
    7779            $this->sort_by = $new_sort_by;
    78             Prefs::setValue('sort_by', $this->sort_by, $_SERVER['PHP_SELF']);
    79         } else if (Prefs::exists('sort_by', $_SERVER['PHP_SELF'])) {
    80             $this->sort_by = Prefs::getValue('sort_by', $_SERVER['PHP_SELF']);
     80            $prefs->set('sort_by', $this->sort_by, $_SERVER['PHP_SELF']);
     81        } else if ($prefs->exists('sort_by', $_SERVER['PHP_SELF'])) {
     82            $this->sort_by = $prefs->get('sort_by', $_SERVER['PHP_SELF']);
    8183        } else {
    8284            $this->sort_by = $default_sort;
     
    9092        if (!empty($new_order)) {
    9193            $this->order = $new_order;
    92             Prefs::setValue('sort_order', $this->order, $_SERVER['PHP_SELF']);
    93         } else if (Prefs::exists('sort_order', $_SERVER['PHP_SELF'])) {
    94             $this->order = Prefs::getValue('sort_order', $_SERVER['PHP_SELF']);
     94            $prefs->set('sort_order', $this->order, $_SERVER['PHP_SELF']);
     95        } else if ($prefs->exists('sort_order', $_SERVER['PHP_SELF'])) {
     96            $this->order = $prefs->get('sort_order', $_SERVER['PHP_SELF']);
    9597        } else {
    9698            $this->order = $default_order;
     
    109111    function set($sort = null, $order = null)
    110112    {
     113        $prefs =& Prefs::getInstance();
     114
    111115        // Set new sort value.
    112116        if (isset($sort)) {
    113117            $this->sort_by = $sort;
    114             Prefs::setValue('sort_by', $this->sort_by, $_SERVER['PHP_SELF']);
     118            $prefs->set('sort_by', $this->sort_by, $_SERVER['PHP_SELF']);
    115119        }
    116120
     
    118122        if (isset($order)) {
    119123            $this->order = $order;
    120             Prefs::setValue('sort_order', $this->order, $_SERVER['PHP_SELF']);
     124            $prefs->set('sort_order', $this->order, $_SERVER['PHP_SELF']);
    121125        }
    122126    }
     
    128132    function getSortOrderSQL()
    129133    {
     134        $app =& App::getInstance();
     135        $db =& DB::getInstance();
     136
    130137        if (!isset($this->_columns[strtolower($this->sort_by)])) {
    131138            $this->sort_by = $this->default_sort;
     
    137144
    138145        if (!empty($this->_columns[strtolower($this->sort_by)][strtolower($this->order)])) {
    139             return sprintf(' ORDER BY %s ', DB::escapeString($this->_columns[strtolower($this->sort_by)][strtolower($this->order)]));
     146            return sprintf(' ORDER BY %s ', $db->escapeString($this->_columns[strtolower($this->sort_by)][strtolower($this->order)]));
    140147        } else {
    141             App::logMsg(sprintf('Could not find SQL to sort by %s %s.', $this->sort_by, $this->order), LOG_WARNING, __FILE__, __LINE__);
     148            $app->logMsg(sprintf('Could not find SQL to sort by %s %s.', $this->sort_by, $this->order), LOG_WARNING, __FILE__, __LINE__);
    142149            return '';
    143150        }
     
    155162    function printSortHeader($col, $col_name, $default_order='ASC')
    156163    {
     164        $app =& App::getInstance();
     165
    157166        if ($this->sort_by == $col) {
    158167            if (strtolower($this->order) == 'desc') {
    159                 ?><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=ASC'); ?>" title="<?php echo _("Change to ascending sort order"); ?>"><?php echo $this->desc_widget; ?></a><?php echo $col_name; ?><?php
     168                ?><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=ASC'); ?>" title="<?php echo _("Change to ascending sort order"); ?>"><?php echo $this->desc_widget; ?></a><?php echo $col_name; ?><?php
    160169            } else {
    161                 ?><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=DESC'); ?>" title="<?php echo _("Change to descending sort order"); ?>"><?php echo $this->asc_widget; ?></a><?php echo $col_name; ?><?php
     170                ?><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=DESC'); ?>" title="<?php echo _("Change to descending sort order"); ?>"><?php echo $this->asc_widget; ?></a><?php echo $col_name; ?><?php
    162171            }
    163172        } else {
    164             ?><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=' . $default_order); ?>" title="<?php echo sprintf(_("Sort by %s"), $col_name); ?>"><?php echo $col_name; ?></a><?php
     173            ?><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?sort=' . $col . '&order=' . $default_order); ?>" title="<?php echo sprintf(_("Sort by %s"), $col_name); ?>"><?php echo $col_name; ?></a><?php
    165174        }
    166175    }
  • trunk/lib/SpellCheck.inc.php

    r42 r136  
    6262    function SpellCheck($params)
    6363    {
     64        $app =& App::getInstance();
     65
    6466        if (!is_array($params) || empty($params)) {
    6567            trigger_error('SpellCheck parameters not set properly', E_USER_ERROR);
     
    7577        if ('' != $this->getParam('personal_wordlist')) {
    7678            if (!is_writable(dirname($this->getParam('personal_wordlist'))) || !is_writable($this->getParam('personal_wordlist'))) {
    77                 App::logMsg(sprintf('Personal wordlist file not writable: %s', $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
     79                $app->logMsg(sprintf('Personal wordlist file not writable: %s', $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
    7880            } else {
    7981                pspell_config_personal($this->_pspell_cfg_handle, $this->getParam('personal_wordlist'));
    8082                $this->_use_personal_wordlist = true;
    81                 App::logMsg(sprintf('Using personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
     83                $app->logMsg(sprintf('Using personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
    8284            }
    8385        }
     
    9496    function setParam($params)
    9597    {
     98        $app =& App::getInstance();
     99
    96100        if (isset($params) && is_array($params)) {
    97101            // Merge new parameters with old overriding only those passed.
    98102            $this->_params = array_merge($this->_params, $params);
    99103        } else {
    100             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     104            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    101105        }
    102106    }
     
    111115    function getParam($param)
    112116    {
     117        $app =& App::getInstance();
     118   
    113119        if (isset($this->_params[$param])) {
    114120            return $this->_params[$param];
    115121        } else {
    116             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     122            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    117123            return null;
    118124        }
     
    184190    function add($word)
    185191    {
     192        $app =& App::getInstance();
     193
    186194        if ($this->_use_personal_wordlist) {
    187195            if (pspell_add_to_personal($this->_pspell_handle, $word)) {
    188                 App::logMsg(sprintf('Added "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
     196                $app->logMsg(sprintf('Added "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
    189197                return true;
    190198            } else {
    191                 App::logMsg(sprintf('Failed adding "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
     199                $app->logMsg(sprintf('Failed adding "%s" to personal wordlist: %s', $word, $this->getParam('personal_wordlist')), LOG_WARNING, __FILE__, __LINE__);
    192200                return false;
    193201            }
     
    207215    function save()
    208216    {
     217        $app =& App::getInstance();
     218
    209219        if ($this->_use_personal_wordlist) {
    210220            if (pspell_save_wordlist($this->_pspell_handle)) {
    211                 App::logMsg(sprintf('Saved personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
     221                $app->logMsg(sprintf('Saved personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_DEBUG, __FILE__, __LINE__);
    212222                return true;
    213223            } else {
    214                 App::logMsg(sprintf('Failed saving personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_ERR, __FILE__, __LINE__);
     224                $app->logMsg(sprintf('Failed saving personal wordlist: %s', $this->getParam('personal_wordlist')), LOG_ERR, __FILE__, __LINE__);
    215225                return false;
    216226            }
  • trunk/lib/TemplateGlue.inc.php

    r111 r136  
    6666function getSetEnumFieldValues($db_table, $db_col)
    6767{
    68     $qid = DB::query("SHOW COLUMNS FROM " . DB::escapeString($db_table) . " LIKE '" . DB::escapeString($db_col) . "'",false);
     68    $app =& App::getInstance();
     69    $db =& DB::getInstance();
     70   
     71    $qid = $db->query("SHOW COLUMNS FROM " . $db->escapeString($db_table) . " LIKE '" . $db->escapeString($db_col) . "'",false);
    6972
    7073    $row = mysql_fetch_row($qid);
     
    7275        return $enum[1];
    7376    } else {
    74         App::logMsg(sprintf('No set or enum fields found.', null), LOG_ERR, __FILE__, __LINE__);
     77        $app->logMsg(sprintf('No set or enum fields found.', null), LOG_ERR, __FILE__, __LINE__);
    7578        return false;
    7679    }
     
    294297function printSelectForm($db_table, $key_column, $val_column, $preselected, $blank=false, $extra_clause='')
    295298{
     299    $db =& DB::getInstance();
     300   
    296301    // Sometimes preselected comes as a comma list.
    297302    if (!is_array($preselected)) {
     
    314319        }
    315320    }
    316     $qid = DB::query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
     321    $qid = $db->query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
    317322    while ($row = mysql_fetch_assoc($qid)) {
    318323        $selected = in_array($row[$val_column], $preselected) ? ' selected="selected"' : '';
     
    335340function printDBCheckboxes($db_table, $key_column, $val_column, $preselected, $columns=1, $extra_clause='', $vert_columns=false)
    336341{
     342    $db =& DB::getInstance();
     343   
    337344    // Sometimes preselected comes as a comma list.
    338345    if (!is_array($preselected)) {
     
    348355    }
    349356
    350     $qid = DB::query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
     357    $qid = $db->query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
    351358    while ($row = mysql_fetch_assoc($qid)) {
    352359        $values[] = $row;
  • trunk/lib/Upload.inc.php

    r121 r136  
    5656    function setParam($params)
    5757    {
     58        $app =& App::getInstance();
     59
    5860        if (isset($params) && is_array($params)) {
    5961
     
    6365                // Must be directory.
    6466                if (!is_dir($params['upload_path'])) {
    65                     App::logMsg(sprintf('Attempting to auto-create upload directory: %s', $params['upload_path']), LOG_NOTICE, __FILE__, __LINE__);
     67                    $app->logMsg(sprintf('Attempting to auto-create upload directory: %s', $params['upload_path']), LOG_NOTICE, __FILE__, __LINE__);
    6668                    mkdir($params['upload_path'], $this->getParam('dest_dir_perms'));
    6769                    if (!is_dir($params['upload_path'])) {
    68                         App::logMsg(sprintf('Upload directory invalid: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
     70                        $app->logMsg(sprintf('Upload directory invalid: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
    6971                        trigger_error(sprintf('Upload directory invalid: %s', $params['upload_path']), E_USER_ERROR);
    7072                    }
     
    7274                // Must be writable.
    7375                if (!is_writable($params['upload_path'])) {
    74                     App::logMsg(sprintf('Upload directory not writable: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
     76                    $app->logMsg(sprintf('Upload directory not writable: %s', $params['upload_path']), LOG_ERR, __FILE__, __LINE__);
    7577                    trigger_error(sprintf('Upload directory not writable: %s', $params['upload_path']), E_USER_ERROR);
    7678                }
     
    8082            $this->_params = array_merge($this->_params, $params);
    8183        } else {
    82             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     84            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    8385        }
    8486    }
     
    9395    function getParam($param)
    9496    {
     97        $app =& App::getInstance();
     98   
    9599        if (isset($this->_params[$param])) {
    96100            return $this->_params[$param];
    97101        } else {
    98             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     102            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    99103            return null;
    100104        }
     
    117121    function process($form_name, $custom_file_name=null)
    118122    {
     123        $app =& App::getInstance();
     124
    119125        // Ensure we have a upload directory.
    120126        if (!$this->getParam('upload_path')) {
    121             App::logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     127            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    122128            $this->_raiseMsg(_("There was a problem with the file upload. Please try again later."), MSG_ERR, __FILE__, __LINE__);
    123129            return false;
     
    126132        // Ensure the file form element specified actually exists.
    127133        if (!isset($_FILES[$form_name])) {
    128             App::logMsg(sprintf(_("Form element %s does not exist."), $form_name), LOG_ERR, __FILE__, __LINE__);
     134            $app->logMsg(sprintf(_("Form element %s does not exist."), $form_name), LOG_ERR, __FILE__, __LINE__);
    129135            $this->_raiseMsg(_("There was a problem with the file upload. Please try again later."), MSG_ERR, __FILE__, __LINE__);
    130136            return false;
     
    167173                    $file_name = $custom_file_name;
    168174                    $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
    169                     App::logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
     175                    $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
    170176                } else {
    171177                    // Invalid custom file name provided. Use uploaded file name.
    172178                    $file_name = $files['name'][$i];
    173                     App::logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
     179                    $app->logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
    174180                }
    175181            } else {
     
    179185                    $file_name = $custom_file_name[$i];
    180186                    $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), $files['name'][$i], $file_name), MSG_NOTICE, __FILE__, __LINE__);
    181                     App::logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
     187                    $app->logMsg(sprintf('Using custom file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
    182188                } else {
    183189                    // Invalid custom file name provided. Use uploaded file name.
    184190                    $file_name = $files['name'][$i];
    185                     App::logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
     191                    $app->logMsg(sprintf('Using uploaded file name: %s', $file_name), LOG_DEBUG, __FILE__, __LINE__);
    186192                }
    187193            }
     
    190196            if (UPLOAD_ERR_INI_SIZE === $files['error'][$i]) {
    191197                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it exceeds the maximum allowed upload file size of %s."), $file_name, ini_get('upload_max_filesize')), MSG_ERR, __FILE__, __LINE__);
    192                 App::logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_INI_SIZE (currently %s)."), $files['error'][$i], $file_name, ini_get('upload_max_filesize')), LOG_ERR, __FILE__, __LINE__);
     198                $app->logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_INI_SIZE (currently %s)."), $files['error'][$i], $file_name, ini_get('upload_max_filesize')), LOG_ERR, __FILE__, __LINE__);
    193199                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_INI_SIZE);
    194200                continue;
     
    196202            if (UPLOAD_ERR_FORM_SIZE === $files['error'][$i]) {
    197203                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it exceeds the maximum allowed upload file size of %s."), $file_name, $_POST['MAX_FILE_SIZE']), MSG_ERR, __FILE__, __LINE__);
    198                 App::logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_FORM_SIZE (currently %s)."), $files['error'][$i], $file_name, $_POST['MAX_FILE_SIZE']), LOG_ERR, __FILE__, __LINE__);
     204                $app->logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_FORM_SIZE (currently %s)."), $files['error'][$i], $file_name, $_POST['MAX_FILE_SIZE']), LOG_ERR, __FILE__, __LINE__);
    199205                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_FORM_SIZE);
    200206                continue;
     
    202208            if (UPLOAD_ERR_PARTIAL === $files['error'][$i]) {
    203209                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it was only partially uploaded."), $file_name), MSG_ERR, __FILE__, __LINE__);
    204                 App::logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_PARTIAL."), $files['error'][$i], $file_name), LOG_ERR, __FILE__, __LINE__);
     210                $app->logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_PARTIAL."), $files['error'][$i], $file_name), LOG_ERR, __FILE__, __LINE__);
    205211                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_PARTIAL);
    206212                continue;
     
    208214            if (UPLOAD_ERR_NO_FILE === $files['error'][$i]) {
    209215                $this->_raiseMsg(sprintf(_("The file %s failed uploading: no file was uploaded."), $file_name), MSG_ERR, __FILE__, __LINE__);
    210                 App::logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_NO_FILE."), $files['error'][$i], $file_name), LOG_ERR, __FILE__, __LINE__);
     216                $app->logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_NO_FILE."), $files['error'][$i], $file_name), LOG_ERR, __FILE__, __LINE__);
    211217                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_NO_FILE);
    212218                continue;
     
    214220            if (UPLOAD_ERR_NO_TMP_DIR === $files['error'][$i]) {
    215221                $this->_raiseMsg(sprintf(_("The file %s failed uploading: temporary upload directory missing."), $file_name), MSG_ERR, __FILE__, __LINE__);
    216                 App::logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_NO_TMP_DIR."), $files['error'][$i], $file_name), LOG_ERR, __FILE__, __LINE__);
     222                $app->logMsg(sprintf(_("The file %s failed uploading with PHP error %s UPLOAD_ERR_NO_TMP_DIR."), $files['error'][$i], $file_name), LOG_ERR, __FILE__, __LINE__);
    217223                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_ERR_NO_TMP_DIR);
    218224                continue;
     
    222228            if (!is_uploaded_file($files['tmp_name'][$i])) {
    223229                $this->_raiseMsg(sprintf(_("The file %s failed uploading."), $file_name), MSG_ERR, __FILE__, __LINE__);
    224                 App::logMsg(sprintf(_("The file %s failed is_uploaded_file."), $file_name), LOG_ERR, __FILE__, __LINE__);
     230                $app->logMsg(sprintf(_("The file %s failed is_uploaded_file."), $file_name), LOG_ERR, __FILE__, __LINE__);
    225231                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_NOT_UPLOADED_FILE);
    226232                continue;
     
    230236            if ($files['size'][$i] <= 0) {
    231237                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it contains zero bytes."), $file_name), MSG_ERR, __FILE__, __LINE__);
    232                 App::logMsg(sprintf(_("The uploaded file %s contains zero bytes."), $file_name), LOG_ERR, __FILE__, __LINE__);
     238                $app->logMsg(sprintf(_("The uploaded file %s contains zero bytes."), $file_name), LOG_ERR, __FILE__, __LINE__);
    233239                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_EMPTY_FILE);
    234240                continue;
     
    238244            if (!in_array(strtolower($this->getFilenameExtension($file_name)), $this->getParam('valid_file_extensions'))) {
    239245                $this->_raiseMsg(sprintf(_("The file %s failed uploading: it is an unrecognized type. Files must have one of the following file name extensions: %s."), $file_name, join(', ', $this->getParam('valid_file_extensions'))), MSG_ERR, __FILE__, __LINE__);
    240                 App::logMsg(sprintf(_("The uploaded file %s has an unrecognized file name extension."), $file_name), LOG_WARNING, __FILE__, __LINE__);
     246                $app->logMsg(sprintf(_("The uploaded file %s has an unrecognized file name extension."), $file_name), LOG_WARNING, __FILE__, __LINE__);
    241247                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_INVALID_EXTENSION);
    242248                continue;
     
    246252            if (!$this->getParam('allow_overwriting') && $this->exists($file_name)) {
    247253                $this->_raiseMsg(sprintf(_("The file %s failed uploading: a file with that name already exists."), $file_name), MSG_ERR, __FILE__, __LINE__);
    248                 App::logMsg(sprintf(_("The uploaded file %s doesn't have a unique filename."), $file_name), LOG_WARNING, __FILE__, __LINE__);
     254                $app->logMsg(sprintf(_("The uploaded file %s doesn't have a unique filename."), $file_name), LOG_WARNING, __FILE__, __LINE__);
    249255                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_NOT_UNIQUE);
    250256                continue;
     
    269275            if (move_uploaded_file($files['tmp_name'][$i], $file_path_name)) {
    270276                chmod($file_path_name, $this->getParam('dest_file_perms'));
    271                 App::logMsg(sprintf('File uploaded: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
     277                $app->logMsg(sprintf('File uploaded: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
    272278                $this->_raiseMsg(sprintf(_("The file %s uploaded successfully."), $file_name), MSG_SUCCESS, __FILE__, __LINE__);
    273279                if (!isset($custom_file_name) && $files['name'][$i] != $file_name) {
     
    284290            } else {
    285291                $this->_raiseMsg(sprintf(_("The file %s failed uploading."), $file_name), MSG_ERR, __FILE__, __LINE__);
    286                 App::logMsg(sprintf(_("Moving file failed: %s -> %s"), $files['tmp_name'][$i], $file_path_name), LOG_ALERT, __FILE__, __LINE__);
     292                $app->logMsg(sprintf(_("Moving file failed: %s -> %s"), $files['tmp_name'][$i], $file_path_name), LOG_ALERT, __FILE__, __LINE__);
    287293                $this->errors[] = array('filename' => $file_name, 'errortype' => UPLOAD_USER_ERR_MOVE_FAILED);
    288294            }
     
    290296            // Check file extension with browsers interpretation of file type.
    291297            if (isset($this->mime_extension_map[$file_extension]) && $files['type'][$i] != $this->mime_extension_map[$file_extension]) {
    292                 App::logMsg(sprintf('File extension (%s) does not match mime type (%s).', $file_extension, $files['type'][$i]), LOG_NOTICE, __FILE__, __LINE__);
     298                $app->logMsg(sprintf('File extension (%s) does not match mime type (%s).', $file_extension, $files['type'][$i]), LOG_NOTICE, __FILE__, __LINE__);
    293299            }
    294300        }
     
    307313    function deleteFile($file_name)
    308314    {
     315        $app =& App::getInstance();
     316
    309317        // Ensure we have a upload directory.
    310318        if (!$this->getParam('upload_path')) {
    311             App::logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     319            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    312320            return false;
    313321        }
     
    316324
    317325        if (!is_file($file_path_name)) {
    318             App::logMsg(sprintf(_("Error deleting nonexistent file: %s"), $file_path_name), LOG_ERR, __FILE__, __LINE__);
     326            $app->logMsg(sprintf(_("Error deleting nonexistent file: %s"), $file_path_name), LOG_ERR, __FILE__, __LINE__);
    319327            return false;
    320328        } else if (unlink($file_path_name)) {
    321             App::logMsg(sprintf('Deleted file: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
     329            $app->logMsg(sprintf('Deleted file: %s', $file_path_name), LOG_INFO, __FILE__, __LINE__);
    322330        } else {
    323331            $this->_raiseMsg(sprintf(_("The file %s could not be deleted."), $file_name), MSG_ERR, __FILE__, __LINE__);
    324             App::logMsg(sprintf(_("Failed deleting file: %s"), $file_path_name), LOG_ERR, __FILE__, __LINE__);
     332            $app->logMsg(sprintf(_("Failed deleting file: %s"), $file_path_name), LOG_ERR, __FILE__, __LINE__);
    325333            return false;
    326334        }
     
    337345    function moveFile($old_name, $new_name)
    338346    {
     347        $app =& App::getInstance();
     348
    339349        // Ensure we have an upload directory.
    340350        if (!$this->getParam('upload_path')) {
    341             App::logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     351            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    342352            return false;
    343353        }
     
    348358            if (rename($old_file_path_name, $new_file_path_name)) {
    349359                $this->_raiseMsg(sprintf(_("The file %s has been renamed to %s."), basename($old_file_path_name), basename($new_file_path_name)), MSG_NOTICE, __FILE__, __LINE__);
    350                 App::logMsg(sprintf('File renamed from %s to %s', $old_file_path_name, $new_file_path_name), LOG_DEBUG, __FILE__, __LINE__);
     360                $app->logMsg(sprintf('File renamed from %s to %s', $old_file_path_name, $new_file_path_name), LOG_DEBUG, __FILE__, __LINE__);
    351361            } else {
    352362                $this->_raiseMsg(sprintf(_("Error renaming file to %s"), $new_file_path_name), MSG_WARNING, __FILE__, __LINE__);
    353                 App::logMsg(sprintf(_("Error renaming file to %s"), $new_file_path_name), LOG_WARNING, __FILE__, __LINE__);
     363                $app->logMsg(sprintf(_("Error renaming file to %s"), $new_file_path_name), LOG_WARNING, __FILE__, __LINE__);
    354364                return false;
    355365            }
    356366        } else {
    357367            $this->_raiseMsg(sprintf(_("Couldn't rename nonexistent file %s."), $old_name), MSG_WARNING, __FILE__, __LINE__);
    358             App::logMsg(sprintf(_("Error renaming nonexistent file: %s"), $old_file_path_name), LOG_WARNING, __FILE__, __LINE__);
     368            $app->logMsg(sprintf(_("Error renaming nonexistent file: %s"), $old_file_path_name), LOG_WARNING, __FILE__, __LINE__);
    359369            return false;
    360370        }
     
    370380    function exists($file_name)
    371381    {
     382        $app =& App::getInstance();
     383
    372384        // Ensure we have a upload directory.
    373385        if (!$this->getParam('upload_path')) {
    374             App::logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
     386            $app->logMsg(sprintf('Upload directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
    375387            return false;
    376388        }
     
    453465
    454466    /**
    455      * An alias for App::raiseMsg that only sends messages configured by display_messages.
     467     * An alias for $app->raiseMsg that only sends messages configured by display_messages.
    456468     *
    457469     * @access public
     
    465477    function _raiseMsg($message, $type, $file, $line)
    466478    {
     479        $app =& App::getInstance();
     480
    467481        if ($this->getParam('display_messages') === true || (is_int($this->getParam('display_messages')) && $this->getParam('display_messages') & $type > 0)) {
    468             App::raiseMsg($message, $type, $file, $line);
     482            $app->raiseMsg($message, $type, $file, $line);
    469483        }
    470484    }
  • trunk/lib/Utilities.inc.php

    r111 r136  
    7474function oTxt($txt, $preserve_html=false)
    7575{
     76    $app =& App::getInstance();
     77
    7678    $search = array();
    7779    $replace = array();
     
    100102    $replace['ampersand']       = '&amp;';
    101103
    102     return preg_replace($search, $replace, htmlentities($txt, ENT_QUOTES, App::getParam('character_set')));
     104    return preg_replace($search, $replace, htmlentities($txt, ENT_QUOTES, $app->getParam('character_set')));
    103105}
    104106
     
    474476function escapedList($in)
    475477{
     478    $db =& DB::getInstance();
     479   
    476480    if (is_array($in) && !empty($in)) {
    477         return "'" . join("', '", array_map(array('DB', 'escapeString'), $in)) . "'";
    478     } else {
    479         return DB::escapeString($in);
     481        return "'" . join("', '", array_map(array($db, 'escapeString'), $in)) . "'";
     482    } else {
     483        return $db->escapeString($in);
    480484    }
    481485}
     
    596600function addSignature($val, $seed_key=null)
    597601{
     602    $app =& App::getInstance();
     603   
    598604    if ('' == $val) {
    599         App::logMsg(sprintf('Adding signature to empty string.', null), LOG_NOTICE, __FILE__, __LINE__);
     605        $app->logMsg(sprintf('Adding signature to empty string.', null), LOG_NOTICE, __FILE__, __LINE__);
    600606    }
    601607
    602608    if (!isset($seed_key)) {
    603         $seed_key = App::getParam('signing_key');
     609        $seed_key = $app->getParam('signing_key');
    604610    }
    605611
     
    662668function mailmanAddMember($email, $list, $send_welcome_message=false)
    663669{
    664    $add_members = '/var/mailman/bin/add_members';
     670    $app =& App::getInstance();
     671   
     672    $add_members = '/var/mailman/bin/add_members';
    665673    if (is_executable($add_members) && is_readable($add_members)) {
    666674        $welcome_msg = $send_welcome_message ? 'y' : 'n';
    667675        exec(sprintf('/bin/echo %s | /usr/bin/sudo %s -r - --welcome-msg=%s --admin-notify=n %s', escapeshellarg($email), escapeshellarg($add_members), $welcome_msg, escapeshellarg($list)), $stdout, $return_code);
    668676        if (0 == $return_code) {
    669             App::logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
     677            $app->logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
    670678            return true;
    671679        } else {
    672             App::logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
     680            $app->logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
    673681            return false;
    674682        }
    675683    } else {
    676         App::logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
     684        $app->logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
    677685        return false;
    678686    }
     
    691699function mailmanRemoveMember($email, $list, $send_user_ack=false)
    692700{
     701    $app =& App::getInstance();
     702   
    693703    $remove_members = '/var/mailman/bin/remove_members';
    694704    if (is_executable($remove_members) && is_readable($remove_members)) {
     
    696706        exec(sprintf('/usr/bin/sudo %s %s --noadminack %s %s', escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code);
    697707        if (0 == $return_code) {
    698             App::logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
     708            $app->logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
    699709            return true;
    700710        } else {
    701             App::logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
     711            $app->logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
    702712            return false;
    703713        }
    704714    } else {
    705         App::logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
     715        $app->logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
    706716        return false;
    707717    }
  • trunk/services/admins.php

    r111 r136  
    88
    99$auth->requireLogin();
    10 App::sslOn();
     10$app->sslOn();
    1111
    1212require_once 'codebase/lib/PageNumbers.inc.php';
    13 require_once 'codebase/lib/SessionCache.inc.php';
     13require_once 'codebase/lib/Cache.inc.php';
    1414require_once 'codebase/lib/FormValidator.inc.php';
    1515require_once 'codebase/lib/SortOrder.inc.php';
     
    2929// The object to validate form input.
    3030$fv = new FormValidator();
     31
     32$cache =& Cache::getInstance();
    3133
    3234// Instantiate a sorting object with the default sort and order. Add SQL for each column.
     
    5456
    5557// Search limiters retain their values between page requests.
    56 App::carryQuery('search_query');
     58$app->carryQuery('search_query');
    5759
    5860
     
    6466// allows us to remember which page we came from so we can go back there.
    6567if (getFormData('boomerang', false) && isset($_SERVER['HTTP_REFERER'])) {
    66     App::setBoomerangURL($_SERVER['HTTP_REFERER'], 'admins');
     68    $app->setBoomerangURL($_SERVER['HTTP_REFERER'], 'admins');
    6769}
    6870
    6971if (getFormData('break_list_cache', false)) {
    7072    // Break the cache because we are changing the list data.
    71     SessionCache::breakCache($_SERVER['PHP_SELF']);
     73    $cache->delete($_SERVER['PHP_SELF']);
    7274}
    7375
     
    9193case 'del' :
    9294    deleteRecord(getFormData('admin_id'));
    93     if (App::validBoomerangURL('admins')) {
     95    if ($app->validBoomerangURL('admins')) {
    9496        // Display boomerang page.
    95         App::dieBoomerangURL('admins');
     97        $app->dieBoomerangURL('admins');
    9698    }
    9799    // Display default page.
    98     App::dieURL($_SERVER['PHP_SELF']);
     100    $app->dieURL($_SERVER['PHP_SELF']);
    99101    break;
    100102
    101103case 'insert' :
    102104    if (getFormdata('cancel', false)) {
    103         if (App::validBoomerangURL('admins')) {
     105        if ($app->validBoomerangURL('admins')) {
    104106            // Display boomerang page.
    105             App::dieBoomerangURL('admins');
     107            $app->dieBoomerangURL('admins');
    106108        }
    107109        // Display default page.
    108         App::dieURL($_SERVER['PHP_SELF']);
     110        $app->dieURL($_SERVER['PHP_SELF']);
    109111    }
    110112    validateInput();
     
    118120        if (getFormdata('repeat', false)) {
    119121            // Display function again.
    120             App::dieURL($_SERVER['PHP_SELF'] . '?op=add');
    121         } else if (App::validBoomerangURL('admins')) {
     122            $app->dieURL($_SERVER['PHP_SELF'] . '?op=add');
     123        } else if ($app->validBoomerangURL('admins')) {
    122124            // Display boomerang page.
    123             App::dieBoomerangURL('admins');
     125            $app->dieBoomerangURL('admins');
    124126        }
    125127        // Display default page.
    126         App::dieURL($_SERVER['PHP_SELF']);
     128        $app->dieURL($_SERVER['PHP_SELF']);
    127129    }
    128130    break;
     
    130132case 'update' :
    131133    if (getFormdata('reset', false)) {
    132         App::raiseMsg(_("Saved values have been reloaded."), MSG_NOTICE, __FILE__, __LINE__);
    133         App::dieURL($_SERVER['PHP_SELF'] . '?op=edit&admin_id=' . getFormData('admin_id'));
     134        $app->raiseMsg(_("Saved values have been reloaded."), MSG_NOTICE, __FILE__, __LINE__);
     135        $app->dieURL($_SERVER['PHP_SELF'] . '?op=edit&admin_id=' . getFormData('admin_id'));
    134136    }
    135137    if (getFormdata('cancel', false)) {
     
    137139        $lock->select('admin_tbl', 'admin_id', getFormData('admin_id'));
    138140        $lock->remove();
    139         if (App::validBoomerangURL('admins')) {
     141        if ($app->validBoomerangURL('admins')) {
    140142            // Display boomerang page.
    141             App::dieBoomerangURL('admins');
     143            $app->dieBoomerangURL('admins');
    142144        }
    143145        // Display default page.
    144         App::dieURL($_SERVER['PHP_SELF']);
     146        $app->dieURL($_SERVER['PHP_SELF']);
    145147    }
    146148    validateInput();
     
    154156        if (getFormdata('repeat', false)) {
    155157            // Display edit function with next available ID.
    156             $qid = DB::query("SELECT admin_id FROM admin_tbl WHERE admin_id > '" . DB::escapeString(getFormData('admin_id')) . "' ORDER BY admin_id ASC LIMIT 1");
     158            $qid = $db->query("SELECT admin_id FROM admin_tbl WHERE admin_id > '" . $db->escapeString(getFormData('admin_id')) . "' ORDER BY admin_id ASC LIMIT 1");
    157159            if (list($next_id) = mysql_fetch_row($qid)) {
    158                 App::dieURL($_SERVER['PHP_SELF'] . '?op=edit&admin_id=' . $next_id);
     160                $app->dieURL($_SERVER['PHP_SELF'] . '?op=edit&admin_id=' . $next_id);
    159161            } else {
    160                 App::raiseMsg(_("Cannot edit next, the end of the list was reached"), MSG_NOTICE, __FILE__, __LINE__);
     162                $app->raiseMsg(_("Cannot edit next, the end of the list was reached"), MSG_NOTICE, __FILE__, __LINE__);
    161163            }
    162         } else if (App::validBoomerangURL('admins')) {
     164        } else if ($app->validBoomerangURL('admins')) {
    163165            // Display boomerang page.
    164             App::dieBoomerangURL('admins');
     166            $app->dieBoomerangURL('admins');
    165167        }
    166168        // Display default page.
    167         App::dieURL($_SERVER['PHP_SELF']);
     169        $app->dieURL($_SERVER['PHP_SELF']);
    168170    }
    169171    break;
     
    258260{
    259261    global $lock;
    260 
     262    $app =& App::getInstance();
     263    $db =& DB::getInstance();
     264   
    261265    $lock->select('admin_tbl', 'admin_id', $id);
    262266    if ($lock->isLocked() && !$lock->isMine()) {
     
    265269
    266270    // Get the information for the form.
    267     $qid = DB::query("
     271    $qid = $db->query("
    268272        SELECT *
    269273        FROM admin_tbl
    270         WHERE admin_id = '" . DB::escapeString($id) . "'
     274        WHERE admin_id = '" . $db->escapeString($id) . "'
    271275    ");
    272276    if (!$frm = mysql_fetch_assoc($qid)) {
    273         App::logMsg('Could not find record with admin_id: ' . $id, LOG_WARNING, __FILE__, __LINE__);
    274         App::raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
    275         App::dieBoomerangURL();
     277        $app->logMsg('Could not find record with admin_id: ' . $id, LOG_WARNING, __FILE__, __LINE__);
     278        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
     279        $app->dieBoomerangURL();
    276280    }
    277281
     
    313317{
    314318    global $auth, $lock;
    315 
     319    $app =& App::getInstance();
     320    $db =& DB::getInstance();
     321    $cache =& Cache::getInstance();
     322   
    316323    $lock->select('admin_tbl', 'admin_id', $id);
    317324    if ($lock->isLocked() && !$lock->isMine()) {
     
    320327
    321328    // Break the cache because we are changing the list data.
    322     SessionCache::breakCache($_SERVER['PHP_SELF']);
     329    $cache->delete($_SERVER['PHP_SELF']);
    323330
    324331    // Get the information for this object.
    325     $qid = DB::query("
     332    $qid = $db->query("
    326333        SELECT username, user_type from admin_tbl
    327         WHERE admin_id = '" . DB::escapeString($id) . "'
     334        WHERE admin_id = '" . $db->escapeString($id) . "'
    328335    ");
    329336    if (! list($name, $user_type) = mysql_fetch_row($qid)) {
    330         App::logMsg('Could not find record with admin_id: ' . $id, LOG_WARNING, __FILE__, __LINE__);
    331         App::raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
    332         App::dieBoomerangURL();
     337        $app->logMsg('Could not find record with admin_id: ' . $id, LOG_WARNING, __FILE__, __LINE__);
     338        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
     339        $app->dieBoomerangURL();
    333340    }
    334341
    335342    // Get the information for this object.
    336     $qid = DB::query("SELECT COUNT(*) from admin_tbl");
     343    $qid = $db->query("SELECT COUNT(*) from admin_tbl");
    337344    list($num_admins) = mysql_fetch_row($qid);
    338345    if ('root' == $user_type && 'root' != $auth->getVal('user_type')) {
    339346        // Only root users can delete root users!
    340         App::raiseMsg(_("You do not have clearance to delete a root administrator."), MSG_NOTICE, __FILE__, __LINE__);
     347        $app->raiseMsg(_("You do not have clearance to delete a root administrator."), MSG_NOTICE, __FILE__, __LINE__);
    341348    } else if ($num_admins <= 1) {
    342349        // There must always be at least one admnistrator!
    343         App::raiseMsg(_("You cannot delete the only administrator in the database. There must be at least one to log in and create other users."), MSG_NOTICE, __FILE__, __LINE__);
     350        $app->raiseMsg(_("You cannot delete the only administrator in the database. There must be at least one to log in and create other users."), MSG_NOTICE, __FILE__, __LINE__);
    344351    } else if ($auth->getVal('user_id') == $id) {
    345352        // Do not delete yourself!
    346         App::raiseMsg(_("You cannot delete yourself."), MSG_NOTICE, __FILE__, __LINE__);
     353        $app->raiseMsg(_("You cannot delete yourself."), MSG_NOTICE, __FILE__, __LINE__);
    347354    } else {
    348355        // Delete the record.
    349         DB::query("DELETE FROM admin_tbl WHERE admin_id = '" . DB::escapeString($id) . "'");
    350         App::raiseMsg(sprintf(_("The admin <strong>%s</strong> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
     356        $db->query("DELETE FROM admin_tbl WHERE admin_id = '" . $db->escapeString($id) . "'");
     357        $app->raiseMsg(sprintf(_("The admin <strong>%s</strong> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
    351358    }
    352359
     
    358365{
    359366    global $auth;
    360 
     367    $app =& App::getInstance();
     368    $db =& DB::getInstance();
     369    $cache =& Cache::getInstance();
     370   
    361371    // Break the cache because we are changing the list data.
    362     SessionCache::breakCache($_SERVER['PHP_SELF']);
     372    $cache->delete($_SERVER['PHP_SELF']);
    363373
    364374    // Insert record data.
    365     DB::query("
     375    $db->query("
    366376        INSERT INTO admin_tbl (
    367377            username,
     
    373383            added_datetime
    374384        ) VALUES (
    375             '" . DB::escapeString($frm['username']) . "',
    376             '" . DB::escapeString($frm['first_name']) . "',
    377             '" . DB::escapeString($frm['last_name']) . "',
    378             '" . DB::escapeString($frm['email']) . "',
    379             '" . DB::escapeString($frm['user_type']) . "',
    380             '" . DB::escapeString($auth->getVal('user_id')) . "',
     385            '" . $db->escapeString($frm['username']) . "',
     386            '" . $db->escapeString($frm['first_name']) . "',
     387            '" . $db->escapeString($frm['last_name']) . "',
     388            '" . $db->escapeString($frm['email']) . "',
     389            '" . $db->escapeString($frm['user_type']) . "',
     390            '" . $db->escapeString($auth->getVal('user_id')) . "',
    381391            NOW()
    382392        )
    383393    ");
    384     $last_insert_id = mysql_insert_id(DB::getDBH());
     394    $last_insert_id = mysql_insert_id($db->getDBH());
    385395
    386396    // Set admin password.
     
    391401    $version->create('admin_tbl', 'admin_id', $last_insert_id, $frm['username']);
    392402
    393     App::raiseMsg(sprintf(_("The Admin <strong>%s</strong> has been added."), $frm['username']), MSG_SUCCESS, __FILE__, __LINE__);
     403    $app->raiseMsg(sprintf(_("The Admin <strong>%s</strong> has been added."), $frm['username']), MSG_SUCCESS, __FILE__, __LINE__);
    394404
    395405    return $last_insert_id;
     
    399409{
    400410    global $auth, $lock;
    401 
     411    $app =& App::getInstance();
     412    $db =& DB::getInstance();
     413    $cache =& Cache::getInstance();
     414   
    402415    $lock->select('admin_tbl', 'admin_id', $frm['admin_id']);
    403416    if ($lock->isLocked() && !$lock->isMine()) {
     
    406419
    407420    // Break the cache because we are changing the list data.
    408     SessionCache::breakCache($_SERVER['PHP_SELF']);
     421    $cache->delete($_SERVER['PHP_SELF']);
    409422
    410423    // If the userpass is left blank or with the filler **** characters, we don't want to update it.
     
    415428
    416429    // Update record data.
    417     DB::query("
     430    $db->query("
    418431        UPDATE admin_tbl SET
    419             username = '" . DB::escapeString($frm['username']) . "',
    420             first_name = '" . DB::escapeString($frm['first_name']) . "',
    421             last_name = '" . DB::escapeString($frm['last_name']) . "',
    422             email = '" . DB::escapeString($frm['email']) . "',
    423             user_type = '" . DB::escapeString($frm['user_type']) . "',
    424             modified_by_user_id = '" . DB::escapeString($auth->getVal('user_id')) . "',
     432            username = '" . $db->escapeString($frm['username']) . "',
     433            first_name = '" . $db->escapeString($frm['first_name']) . "',
     434            last_name = '" . $db->escapeString($frm['last_name']) . "',
     435            email = '" . $db->escapeString($frm['email']) . "',
     436            user_type = '" . $db->escapeString($frm['user_type']) . "',
     437            modified_by_user_id = '" . $db->escapeString($auth->getVal('user_id')) . "',
    425438            modified_datetime = NOW()
    426         WHERE admin_id = '" . DB::escapeString($frm['admin_id']) . "'
     439        WHERE admin_id = '" . $db->escapeString($frm['admin_id']) . "'
    427440    ");
    428441
     
    431444    $version->create('admin_tbl', 'admin_id', $frm['admin_id'], $frm['username']);
    432445
    433     App::raiseMsg(sprintf(_("The Admin <strong>%s</strong> has been updated."), $frm['username']), MSG_SUCCESS, __FILE__, __LINE__);
     446    $app->raiseMsg(sprintf(_("The Admin <strong>%s</strong> has been updated."), $frm['username']), MSG_SUCCESS, __FILE__, __LINE__);
    434447
    435448    // Unlock record.
     
    441454    global $page;
    442455    global $so;
    443 
     456    $db =& DB::getInstance();
     457    $prefs =& Prefs::getInstance();
     458    $cache =& Cache::getInstance();
     459   
    444460    $where_clause = '';
    445461
     
    450466            $where_clause .= (empty($where_clause) ? 'WHERE' : 'AND') . "
    451467                (
    452                     admin_tbl.username LIKE '%" . DB::escapeString($qry_words[$i]) . "%'
    453                     OR admin_tbl.first_name LIKE '%" . DB::escapeString($qry_words[$i]) . "%'
    454                     OR admin_tbl.last_name LIKE '%" . DB::escapeString($qry_words[$i]) . "%'
    455                     OR admin_tbl.email LIKE '%" . DB::escapeString($qry_words[$i]) . "%'
     468                    admin_tbl.username LIKE '%" . $db->escapeString($qry_words[$i]) . "%'
     469                    OR admin_tbl.first_name LIKE '%" . $db->escapeString($qry_words[$i]) . "%'
     470                    OR admin_tbl.last_name LIKE '%" . $db->escapeString($qry_words[$i]) . "%'
     471                    OR admin_tbl.email LIKE '%" . $db->escapeString($qry_words[$i]) . "%'
    456472                )
    457473            ";
     
    460476
    461477    // Count the total number of records so we can do something about the page numbers.
    462     $qid = DB::query("
     478    $qid = $db->query("
    463479        SELECT COUNT(*)
    464480        FROM admin_tbl
     
    491507    // without knowing the hash.
    492508    $cache_hash = md5($sql . '|' . $page->total_items);
    493     if (Prefs::getValue('cache_hash', $_SERVER['PHP_SELF']) != $cache_hash) {
    494         SessionCache::breakCache($_SERVER['PHP_SELF']);
    495         Prefs::setValue('cache_hash', $cache_hash, $_SERVER['PHP_SELF']);
    496     }
    497 
    498     if (SessionCache::isCached($_SERVER['PHP_SELF']) && false) {
     509    if ($prefs->get('cache_hash', $_SERVER['PHP_SELF']) != $cache_hash) {
     510        $cache->delete($_SERVER['PHP_SELF']);
     511        $prefs->set('cache_hash', $cache_hash, $_SERVER['PHP_SELF']);
     512    }
     513
     514    if ($cache->exists($_SERVER['PHP_SELF']) && false) {
    499515        // Get the cached results.
    500         $list = SessionCache::getCache($_SERVER['PHP_SELF']);
     516        $list = $cache->get($_SERVER['PHP_SELF']);
    501517    } else {
    502518        // If the list is not already cached, query now.
    503         $qid = DB::query($sql);
     519        $qid = $db->query($sql);
    504520        // Fill an array with the items for this page.
    505521        while ($row = mysql_fetch_assoc($qid)) {
     
    509525        if (isset($list) && !empty($list)) {
    510526            // Cache the results.
    511             SessionCache::putCache($list, $_SERVER['PHP_SELF']);
     527            $cache->set($list, $_SERVER['PHP_SELF']);
    512528        }
    513529    }
  • trunk/services/lock.php

    r53 r136  
    99
    1010$auth->requireLogin();
    11 App::sslOn();
     11$app->sslOn();
    1212
    1313if (getFormData('boomerang', false)) {
    1414    // We remember which page we came from so we can go back there.
    1515    $boom_url = strpos(getFormData('boomerang'), '/') !== false ? getFormData('boomerang') : $_SERVER['HTTP_REFERER'];
    16     App::setBoomerangURL($boom_url, 'lock');
     16    $app->setBoomerangURL($boom_url, 'lock');
    1717    if (isset($_SERVER['HTTP_REFERER'])) {
    18         App::setBoomerangURL($_SERVER['HTTP_REFERER'], 'cancel-lock');
     18        $app->setBoomerangURL($_SERVER['HTTP_REFERER'], 'cancel-lock');
    1919    }
    2020}
     
    2626
    2727if (!$lock->isLocked()) {
    28     App::logMsg('Lock not found with lock_id: ' . getFormData('lock_id') . ', from referrer: ' . $_SERVER['HTTP_REFERER'], LOG_WARNING, __FILE__, __LINE__);
    29     App::dieBoomerangURL('lock');
     28    $app->logMsg('Lock not found with lock_id: ' . getFormData('lock_id') . ', from referrer: ' . $_SERVER['HTTP_REFERER'], LOG_WARNING, __FILE__, __LINE__);
     29    $app->dieBoomerangURL('lock');
    3030}
    3131
     
    3333if (getFormData('unlock', false)) {
    3434    $lock->remove();
    35     App::raiseMsg(sprintf(_("The record <strong>%s</strong> has been unlocked, and can now be modified."), $lock->getTitle('title')), MSG_NOTICE, __FILE__, __LINE__);
    36     App::dieBoomerangURL('lock');
     35    $app->raiseMsg(sprintf(_("The record <strong>%s</strong> has been unlocked, and can now be modified."), $lock->getTitle('title')), MSG_NOTICE, __FILE__, __LINE__);
     36    $app->dieBoomerangURL('lock');
    3737} else if (getFormData('cancel', false)) {
    3838    // Since the boomerang URL will go back to the locked record, and the record was not unlocked, we must delete the boomerang URL otherwise we'll come back here.
    39     App::deleteBoomerangURL('lock');
    40     App::dieBoomerangURL('cancel-lock');
     39    $app->deleteBoomerangURL('lock');
     40    $app->dieBoomerangURL('cancel-lock');
    4141}
    4242
  • trunk/services/login.php

    r103 r136  
    88// allows us to remember which page we came from so we can go back there.
    99if (getFormData('boomerang', false) && isset($_SERVER['HTTP_REFERER'])) {
    10     App::setBoomerangURL($_SERVER['HTTP_REFERER'], 'login');
     10    $app->setBoomerangURL($_SERVER['HTTP_REFERER'], 'login');
    1111}
    12 App::sslOn();
     12$app->sslOn();
    1313
    1414$frm['username'] = getFormdata('username');
     
    1919
    2020    if ($auth->login($frm['username'], $frm['password'])) {
    21         App::raiseMsg(_("You are now logged in."), MSG_SUCCESS, __FILE__, __LINE__);
    22         App::dieBoomerangURL('login');
    23         App::logMsg(sprintf('%s %s successfully logged-in.', $auth->getVal('auth_name'), $frm['username']), LOG_INFO, __FILE__, __LINE__);
     21        $app->raiseMsg(_("You are now logged in."), MSG_SUCCESS, __FILE__, __LINE__);
     22        $app->dieBoomerangURL('login');
     23        $app->logMsg(sprintf('%s %s successfully logged-in.', $auth->getVal('auth_name'), $frm['username']), LOG_INFO, __FILE__, __LINE__);
    2424    } else {
    25         App::raiseMsg(_("Login failed, please try again."), MSG_NOTICE, __FILE__, __LINE__);
    26         App::logMsg(sprintf('%s %s failed login using (MD5ed) password: %s', ucfirst($auth->getVal('auth_name')), $frm['username'], md5($frm['password'])), LOG_NOTICE, __FILE__, __LINE__);
     25        $app->raiseMsg(_("Login failed, please try again."), MSG_NOTICE, __FILE__, __LINE__);
     26        $app->logMsg(sprintf('%s %s failed login using (MD5ed) password: %s', ucfirst($auth->getVal('auth_name')), $frm['username'], md5($frm['password'])), LOG_NOTICE, __FILE__, __LINE__);
    2727    }
    2828}
  • trunk/services/logout.php

    r108 r136  
    55 */
    66
    7 if (is_a($auth, 'Auth_SQL')) {
     7if (isset($auth) && method_exists($auth, 'getVal')) {
    88    // Delete the current user's record locks.
    99    require_once 'codebase/lib/RecordLock.inc.php';
     
    1515$auth->clearAuth();
    1616
    17 App::raiseMsg(sprintf(_("Your session has been logged-out."), null), MSG_SUCCESS, __FILE__, __LINE__);
    18 App::dieURL(App::getParam('redirect_home_url'));
     17$app->raiseMsg(sprintf(_("Your session has been logged-out."), null), MSG_SUCCESS, __FILE__, __LINE__);
     18$app->dieURL($app->getParam('redirect_home_url'));
    1919
    2020?>
  • trunk/services/logs.php

    r42 r136  
    99$auth->requireLogin();
    1010// $auth->requireAccessClearance(ZONE_ADMIN_APPLOG);
    11 App::sslOn();
     11$app->sslOn();
    1212
    1313require_once 'codebase/lib/PageNumbers.inc.php';
     
    3939
    4040// Set the defaults and catch incoming settings.
    41 Prefs::setDefault('log_file', App::getParam('log_filename'), 'logs_module');
    42 Prefs::setValue('log_file', getFormData('log'), 'logs_module');
     41$prefs =& Prefs::getInstance();
     42$prefs->setDefault('log_file', $app->getParam('log_filename'), 'logs_module');
     43$prefs->set('log_file', getFormData('log'), 'logs_module');
    4344
    4445// Titles and navigation header.
    45 $nav->addPage(sprintf(_("Viewing log: <em>%s</em>"), Prefs::getValue('log_file', 'logs_module')), '/admin/logs.php');
     46$nav->addPage(sprintf(_("Viewing log: <em>%s</em>"), $prefs->get('log_file', 'logs_module')), '/admin/logs.php');
    4647
    4748/******************************************************************************
     
    5657case 'delete' :
    5758//     $auth->requireAccessClearance(ZONE_ADMIN_APPLOG_FUNC_RESET);
    58     deleteLog(Prefs::getValue('log_file', 'logs_module'));
    59     Prefs::setValue('log_file', App::getParam('log_filename'), 'logs_module');
    60     if (App::validBoomerangURL('app_log')) {
     59    deleteLog($prefs->get('log_file', 'logs_module'));
     60    $prefs->set('log_file', $app->getParam('log_filename'), 'logs_module');
     61    if ($app->validBoomerangURL('app_log')) {
    6162        // Display boomerang page.
    62         App::dieBoomerangURL('app_log');
     63        $app->dieBoomerangURL('app_log');
    6364    }
    6465    // Display default page.
    65     App::dieURL($_SERVER['PHP_SELF']);
     66    $app->dieURL($_SERVER['PHP_SELF']);
    6667    break;
    6768
    6869case 'clear' :
    6970//     $auth->requireAccessClearance(ZONE_ADMIN_APPLOG_FUNC_RESET);
    70     clearLog(Prefs::getValue('log_file', 'logs_module'));
    71     if (App::validBoomerangURL('app_log')) {
     71    clearLog($prefs->get('log_file', 'logs_module'));
     72    if ($app->validBoomerangURL('app_log')) {
    7273        // Display boomerang page.
    73         App::dieBoomerangURL('app_log');
     74        $app->dieBoomerangURL('app_log');
    7475    }
    7576    // Display default page.
    76     App::dieURL($_SERVER['PHP_SELF']);
     77    $app->dieURL($_SERVER['PHP_SELF']);
    7778    break;
    7879
    7980case 'archive' :
    8081//     $auth->requireAccessClearance(ZONE_ADMIN_APPLOG_FUNC_RESET);
    81     if (archiveLog(Prefs::getValue('log_file', 'logs_module'))) {
     82    if (archiveLog($prefs->get('log_file', 'logs_module'))) {
    8283        // Now flush current log.
    83         App::dieURL($_SERVER['PHP_SELF'] . '?op=clear');
    84     }
    85     if (App::validBoomerangURL('app_log')) {
     84        $app->dieURL($_SERVER['PHP_SELF'] . '?op=clear');
     85    }
     86    if ($app->validBoomerangURL('app_log')) {
    8687        // Display boomerang page.
    87         App::dieBoomerangURL('app_log');
     88        $app->dieBoomerangURL('app_log');
    8889    }
    8990    // Display default page.
    90     App::dieURL($_SERVER['PHP_SELF']);
     91    $app->dieURL($_SERVER['PHP_SELF']);
    9192    break;
    9293
     
    9798case 'download' :
    9899    header('Content-Type: application/octet-stream');
    99     header(sprintf('Content-Disposition: attachment; filename=%s.txt', Prefs::getValue('log_file', 'logs_module')));
    100     printLog(Prefs::getValue('log_file', 'logs_module'));
     100    header(sprintf('Content-Disposition: attachment; filename=%s.txt', $prefs->get('log_file', 'logs_module')));
     101    printLog($prefs->get('log_file', 'logs_module'));
    101102    die;
    102103    break;
    103104
    104105default :
    105     $list =& getLog(Prefs::getValue('log_file', 'logs_module'), getFormData('search_query'));
     106    $list =& getLog($prefs->get('log_file', 'logs_module'), getFormData('search_query'));
    106107    $main_template = 'log_list.ihtml';
    107108    break;
     
    125126include 'header.ihtml';
    126127if ('output' == $main_template) {
    127     printLog(Prefs::getValue('log_file', 'logs_module'));
     128    printLog($prefs->get('log_file', 'logs_module'));
    128129} else {
    129130    include 'codebase/services/templates/' . $main_template;
     
    138139function deleteLog($log_file)
    139140{
    140     if (!file_exists(App::getParam('log_directory') . '/' . $log_file)) {
    141         App::raiseMsg(sprintf(_("Log file %s does not exist."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
    142         App::logMsg(sprintf('Cannot delete nonexistent log file %s', App::getParam('log_directory') . '/' . $log_file), LOG_INFO, __FILE__, __LINE__);
    143         return false;
    144     }
    145 
    146     if (!is_writable(App::getParam('log_directory') . '/' . $log_file) && !is_writable(App::getParam('log_directory'))) {
    147         App::raiseMsg(sprintf(_("Log file %s could not be deleted."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
    148         App::logMsg(sprintf('Cannot delete log file %s, not writable.', App::getParam('log_directory') . '/' . $log_file), LOG_INFO, __FILE__, __LINE__);
    149         return false;
    150     }
    151 
    152     if (unlink(App::getParam('log_directory') . '/' . $log_file)) {
    153         App::raiseMsg(sprintf(_("Log file %s has been deleted."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
    154         App::logMsg(sprintf('Log file %s has been deleted', $log_file), LOG_INFO, __FILE__, __LINE__);
     141    $app =& App::getInstance();
     142
     143    if (!file_exists($app->getParam('log_directory') . '/' . $log_file)) {
     144        $app->raiseMsg(sprintf(_("Log file %s does not exist."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
     145        $app->logMsg(sprintf('Cannot delete nonexistent log file %s', $app->getParam('log_directory') . '/' . $log_file), LOG_INFO, __FILE__, __LINE__);
     146        return false;
     147    }
     148
     149    if (!is_writable($app->getParam('log_directory') . '/' . $log_file) && !is_writable($app->getParam('log_directory'))) {
     150        $app->raiseMsg(sprintf(_("Log file %s could not be deleted."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
     151        $app->logMsg(sprintf('Cannot delete log file %s, not writable.', $app->getParam('log_directory') . '/' . $log_file), LOG_INFO, __FILE__, __LINE__);
     152        return false;
     153    }
     154
     155    if (unlink($app->getParam('log_directory') . '/' . $log_file)) {
     156        $app->raiseMsg(sprintf(_("Log file %s has been deleted."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
     157        $app->logMsg(sprintf('Log file %s has been deleted', $log_file), LOG_INFO, __FILE__, __LINE__);
    155158        return true;
    156159    } else {
    157         App::raiseMsg(sprintf(_("Log file %s could not be deleted."), $log_file), MSG_WARNING, __FILE__, __LINE__);
    158         App::logMsg(sprintf('unlink failed on log file %s', App::getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
     160        $app->raiseMsg(sprintf(_("Log file %s could not be deleted."), $log_file), MSG_WARNING, __FILE__, __LINE__);
     161        $app->logMsg(sprintf('unlink failed on log file %s', $app->getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
    159162        return false;
    160163    }
     
    163166function clearLog($log_file)
    164167{
    165     if (!$fp = fopen(App::getParam('log_directory') . '/' . $log_file, 'r+')) {
    166         App::raiseMsg(sprintf(_("Log file %s could not be opened."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
    167         App::logMsg(sprintf('fopen failed on log file %s', App::getParam('log_directory') . '/' . $log_file), LOG_INFO, __FILE__, __LINE__);
     168    $app =& App::getInstance();
     169
     170    if (!$fp = fopen($app->getParam('log_directory') . '/' . $log_file, 'r+')) {
     171        $app->raiseMsg(sprintf(_("Log file %s could not be opened."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
     172        $app->logMsg(sprintf('fopen failed on log file %s', $app->getParam('log_directory') . '/' . $log_file), LOG_INFO, __FILE__, __LINE__);
    168173        return false;
    169174    }
     
    174179    fclose($fp);
    175180    if (!$ftruncate_return) {
    176         App::raiseMsg(sprintf(_("Log file %s could not be cleared."), $log_file), MSG_WARNING, __FILE__, __LINE__);
    177         App::logMsg(sprintf('ftruncate failed on log file %s', App::getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
     181        $app->raiseMsg(sprintf(_("Log file %s could not be cleared."), $log_file), MSG_WARNING, __FILE__, __LINE__);
     182        $app->logMsg(sprintf('ftruncate failed on log file %s', $app->getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
    178183        return false;
    179184    } else {
    180         App::raiseMsg(sprintf(_("Log file %s has been cleared."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
    181         App::logMsg(sprintf('Log file %s has been cleared', $log_file), LOG_INFO, __FILE__, __LINE__);
     185        $app->raiseMsg(sprintf(_("Log file %s has been cleared."), $log_file), MSG_NOTICE, __FILE__, __LINE__);
     186        $app->logMsg(sprintf('Log file %s has been cleared', $log_file), LOG_INFO, __FILE__, __LINE__);
    182187        return true;
    183188    }
     
    186191function archiveLog($log_file)
    187192{
     193    $app =& App::getInstance();
     194
    188195    $old_file_name = $log_file;
    189196    $new_file_name = $log_file . '__' . date('Y-m-d');
    190     If (!is_writable(App::getParam('log_directory') . '')) {
    191         App::raiseMsg(sprintf('Cannot archive log, log directory not writable: %s', App::getParam('log_directory')), MSG_WARNING, __FILE__, __LINE__);
    192         App::logMsg(sprintf('Cannot archive log, log directory not writable: %s', App::getParam('log_directory')), LOG_WARNING, __FILE__, __LINE__);
    193         return false;
    194     }
    195     If (!copy(App::getParam('log_directory') . '/' . $old_file_name, App::getParam('log_directory') . '/' . $new_file_name)) {
    196         App::raiseMsg(sprintf(_("Cannot archive log, copying old log file failed."), null), MSG_WARNING, __FILE__, __LINE__);
    197         App::logMsg(sprintf('Cannot archive log, copying old log file failed.', null), LOG_WARNING, __FILE__, __LINE__);
    198         return false;
    199     }
    200 
    201     App::raiseMsg(sprintf(_("Log file %s has been archived to %s."), $old_file_name, $new_file_name), MSG_NOTICE, __FILE__, __LINE__);
    202     App::logMsg(sprintf('Log file %s has been archived to %s.', $old_file_name, $new_file_name), LOG_NOTICE, __FILE__, __LINE__);
     197    If (!is_writable($app->getParam('log_directory') . '')) {
     198        $app->raiseMsg(sprintf('Cannot archive log, log directory not writable: %s', $app->getParam('log_directory')), MSG_WARNING, __FILE__, __LINE__);
     199        $app->logMsg(sprintf('Cannot archive log, log directory not writable: %s', $app->getParam('log_directory')), LOG_WARNING, __FILE__, __LINE__);
     200        return false;
     201    }
     202    If (!copy($app->getParam('log_directory') . '/' . $old_file_name, $app->getParam('log_directory') . '/' . $new_file_name)) {
     203        $app->raiseMsg(sprintf(_("Cannot archive log, copying old log file failed."), null), MSG_WARNING, __FILE__, __LINE__);
     204        $app->logMsg(sprintf('Cannot archive log, copying old log file failed.', null), LOG_WARNING, __FILE__, __LINE__);
     205        return false;
     206    }
     207
     208    $app->raiseMsg(sprintf(_("Log file %s has been archived to %s."), $old_file_name, $new_file_name), MSG_NOTICE, __FILE__, __LINE__);
     209    $app->logMsg(sprintf('Log file %s has been archived to %s.', $old_file_name, $new_file_name), LOG_NOTICE, __FILE__, __LINE__);
    203210    return true;
    204211}
     
    206213function printLog($log_file)
    207214{
    208     if (!is_file(App::getParam('log_directory') . '/' . $log_file)) {
    209         App::raiseMsg(sprintf(_("Log file %s not found."), $log_file), MSG_WARNING, __FILE__, __LINE__);
    210         App::logMsg(sprintf('Log file %s not found.', App::getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
    211         return false;
    212     }
    213 
    214     readfile(App::getParam('log_directory') . '/' . $log_file);
     215    $app =& App::getInstance();
     216
     217    if (!is_file($app->getParam('log_directory') . '/' . $log_file)) {
     218        $app->raiseMsg(sprintf(_("Log file %s not found."), $log_file), MSG_WARNING, __FILE__, __LINE__);
     219        $app->logMsg(sprintf('Log file %s not found.', $app->getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
     220        return false;
     221    }
     222
     223    readfile($app->getParam('log_directory') . '/' . $log_file);
    215224}
    216225
    217226function &getLog($log_file, $search_query='')
    218227{
    219     if (!is_file(App::getParam('log_directory') . '/' . $log_file)) {
    220         App::raiseMsg(sprintf(_("Log file %s not found."), $log_file), MSG_WARNING, __FILE__, __LINE__);
    221         App::logMsg(sprintf('Log file %s not found.', App::getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
    222         return false;
    223     }
    224     $log = file(App::getParam('log_directory') . '/' . $log_file);
     228    $app =& App::getInstance();
     229
     230    if (!is_file($app->getParam('log_directory') . '/' . $log_file)) {
     231        $app->raiseMsg(sprintf(_("Log file %s not found."), $log_file), MSG_WARNING, __FILE__, __LINE__);
     232        $app->logMsg(sprintf('Log file %s not found.', $app->getParam('log_directory') . '/' . $log_file), LOG_WARNING, __FILE__, __LINE__);
     233        return false;
     234    }
     235    $log = file($app->getParam('log_directory') . '/' . $log_file);
    225236
    226237    if ('' != trim($search_query)) {
     
    237248{
    238249    global $valid_file_extensions;
     250    $app =& App::getInstance();
    239251
    240252    // Get a list of all files in the log directory.
    241     $dir_handle = opendir(App::getParam('log_directory'));
     253    $dir_handle = opendir($app->getParam('log_directory'));
    242254    $list = array();
    243255    while ($dir_handle && ($file = readdir($dir_handle)) !== false) {
    244         if (!preg_match('/^\./', $file) && is_file(App::getParam('log_directory') . '/' . $file) && in_array(strtolower(Upload::getFilenameExtension($file)), $valid_file_extensions)) {
     256        if (!preg_match('/^\./', $file) && is_file($app->getParam('log_directory') . '/' . $file) && in_array(strtolower(Upload::getFilenameExtension($file)), $valid_file_extensions)) {
    245257            $list[] = array(
    246258                'filename' => $file,
    247                 'filesize' => filesize(App::getParam('log_directory') . '/' . $file),
    248                 'modified' => filemtime(App::getParam('log_directory') . '/' . $file),
     259                'filesize' => filesize($app->getParam('log_directory') . '/' . $file),
     260                'modified' => filemtime($app->getParam('log_directory') . '/' . $file),
    249261            );
    250262        }
  • trunk/services/password.php

    r42 r136  
    2727if (getFormData('boomerang', false) && isset($_SERVER['HTTP_REFERER'])) {
    2828    // We remember which page we came from so we can go back there.
    29     App::setBoomerangURL($_SERVER['HTTP_REFERER'], 'admin_password');
     29    $app->setBoomerangURL($_SERVER['HTTP_REFERER'], 'admin_password');
    3030}
    31 App::sslOn();
     31$app->sslOn();
    3232
    3333switch (getFormData('op')) {
     
    5050    if (!$fv->anyErrors() && false === $auth->authenticate($auth->getVal('username'), $frm['oldpassword'])) {
    5151        $fv->addError('oldpassword', _("Your <strong>Old password</strong> failed authentication."));
    52         App::logMsg(sprintf(_("Password change failed for %s, using (md5ed) password: %s"), $auth->getVal('username'), md5($frm['oldpassword'])), LOG_NOTICE, __FILE__, __LINE__);
     52        $app->logMsg(sprintf(_("Password change failed for %s, using (md5ed) password: %s"), $auth->getVal('username'), md5($frm['oldpassword'])), LOG_NOTICE, __FILE__, __LINE__);
    5353    }
    5454
    5555    if (!$fv->anyErrors()) {
    5656        $auth->setPassword(null, $frm['newpassword']);
    57         App::logMsg(sprintf(_("Password change successful for %s"), $auth->getVal('username')), LOG_INFO, __FILE__, __LINE__);
    58         App::raiseMsg(sprintf(_("Password change successful for %s"), $auth->getVal('username')), MSG_SUCCESS, __FILE__, __LINE__);
    59         App::dieBoomerangURL('admin_password');
     57        $app->logMsg(sprintf(_("Password change successful for %s"), $auth->getVal('username')), LOG_INFO, __FILE__, __LINE__);
     58        $app->raiseMsg(sprintf(_("Password change successful for %s"), $auth->getVal('username')), MSG_SUCCESS, __FILE__, __LINE__);
     59        $app->dieBoomerangURL('admin_password');
    6060    }
    6161    break;
  • trunk/services/templates/admin_form.ihtml

    r121 r136  
    22
    33<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    4 <?php App::printHiddenSession(); ?>
     4<?php $app->printHiddenSession(); ?>
    55<input type="hidden" name="op" value="<?php echo $frm['new_op']; ?>" />
    66<input type="hidden" name="admin_id" value="<?php echo $frm['admin_id']; ?>" />
  • trunk/services/templates/admin_list.ihtml

    r124 r136  
    22<?php $fv->printErrorMessages(); ?>
    33<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    4 <?php App::printHiddenSession(false); ?>
     4<?php $app->printHiddenSession(false); ?>
    55<div id="commandbox">
    6     <span class="sc-nowrap commandtext"><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=add'); ?>"><?php echo _("Add administrator"); ?></a></span>
     6    <span class="sc-nowrap commandtext"><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=add'); ?>"><?php echo _("Add administrator"); ?></a></span>
    77    <br />
    88
     
    3131    <?php for ($i = 0; $i <= $page->last_item - $page->first_item && $page->total_items > 0; $i++) { ?>
    3232    <tr>
    33         <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Edit %s"), oTxt($list[$i]['username'])) ?>" href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=edit&admin_id=' . $list[$i]['admin_id']); ?>"><img src="/admin/_widgets/edit.gif" alt="Edit" width="14" height="18" border="0"></a> &nbsp;</td>
    34         <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Versions of %s"), oTxt($list[$i]['username'])) ?>" href="<?php echo App::oHREF('/admin/versions.php?record_table=admin_tbl&record_key=admin_id&boomerang=true&record_val=' . $list[$i]['admin_id']); ?>"><img src="/admin/_widgets/subcategory.gif" alt="" width="18" height="14" border="0" /></a> &nbsp;</td>
     33        <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Edit %s"), oTxt($list[$i]['username'])) ?>" href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=edit&admin_id=' . $list[$i]['admin_id']); ?>"><img src="/admin/_widgets/edit.gif" alt="Edit" width="14" height="18" border="0"></a> &nbsp;</td>
     34        <td class="sc-padleft sc-nowrap"><a title="<?php printf(_("Versions of %s"), oTxt($list[$i]['username'])) ?>" href="<?php echo $app->oHREF('/admin/versions.php?record_table=admin_tbl&record_key=admin_id&boomerang=true&record_val=' . $list[$i]['admin_id']); ?>"><img src="/admin/_widgets/subcategory.gif" alt="" width="18" height="14" border="0" /></a> &nbsp;</td>
    3535        <td class="sc-nowrap"><?php echo oTxt($list[$i]['admin_id'], true); ?> &nbsp;</td>
    3636        <td class="sc-nowrap"><?php echo oTxt($list[$i]['username'], true); ?> &nbsp;</td>
     
    4040        <td class="sc-nowrap"><?php
    4141            if ($auth->isLoggedIn($list[$i]['admin_id'])) {
    42                 ?><strong><?php echo date(App::getParam('date_format'), strtotime($list[$i]['last_login_datetime'])) ?></strong><?php
     42                ?><strong><?php echo date($app->getParam('date_format'), strtotime($list[$i]['last_login_datetime'])) ?></strong><?php
    4343            } else {
    44                 echo '0000-00-00 00:00:00' == $list[$i]['last_login_datetime'] ? '' : date(App::getParam('date_format'), strtotime($list[$i]['last_login_datetime']));
     44                echo '0000-00-00 00:00:00' == $list[$i]['last_login_datetime'] ? '' : date($app->getParam('date_format'), strtotime($list[$i]['last_login_datetime']));
    4545            }
    4646        ?> &nbsp;</td>
    4747        <td class="sc-nowrap"><?php echo gethostbyaddr($list[$i]['last_login_ip']); ?> &nbsp;</td>
    48         <td class="sc-nowrap"><?php echo '0000-00-00 00:00:00' == $list[$i]['added_datetime'] ? '' : date(App::getParam('date_format'), strtotime($list[$i]['added_datetime'])); ?> &nbsp;</td>
     48        <td class="sc-nowrap"><?php echo '0000-00-00 00:00:00' == $list[$i]['added_datetime'] ? '' : date($app->getParam('date_format'), strtotime($list[$i]['added_datetime'])); ?> &nbsp;</td>
    4949        <td class="sc-nowrap"><?php echo oTxt($list[$i]['added_admin_username'], true); ?> &nbsp;</td>
    50         <td class="sc-nowrap"><?php echo '0000-00-00 00:00:00' == $list[$i]['modified_datetime'] ? '' : date(App::getParam('date_format'), strtotime($list[$i]['modified_datetime'])); ?> &nbsp;</td>
    51         <td class="sc-padleft sc-nowrap" align="right"><a title="<?php printf(_("Delete %s"), oTxt($list[$i]['username'])) ?>" href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . "?op=del&admin_id=" . $list[$i]['admin_id']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to delete the record %s? This action is permanent and cannot be undone."), oTxt($list[$i]['username'])) ?>')"><img src="/admin/_widgets/delete.gif" alt="Delete" width="16" height="17" border="0"></a> &nbsp;</td>
     50        <td class="sc-nowrap"><?php echo '0000-00-00 00:00:00' == $list[$i]['modified_datetime'] ? '' : date($app->getParam('date_format'), strtotime($list[$i]['modified_datetime'])); ?> &nbsp;</td>
     51        <td class="sc-padleft sc-nowrap" align="right"><a title="<?php printf(_("Delete %s"), oTxt($list[$i]['username'])) ?>" href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . "?op=del&admin_id=" . $list[$i]['admin_id']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to delete the record %s? This action is permanent and cannot be undone."), oTxt($list[$i]['username'])) ?>')"><img src="/admin/_widgets/delete.gif" alt="Delete" width="16" height="17" border="0"></a> &nbsp;</td>
    5252    </tr>
    5353    <?php } ?>
  • trunk/services/templates/list_info.ihtml

    r121 r136  
    55    <span class="sc-nowrap commanditem commandtext">
    66        <?php printf(_("Listing <strong>%s-%s</strong> of <strong>%s</strong> results on <strong>%s</strong> pages"), (0==$page->total_items ? 0 : $page->first_item+1), (0==$page->total_items ? 0 : $page->last_item+1), $page->total_items, $page->total_pages) ?>
    7         &nbsp;&nbsp; <a href="<?php echo App::oHREF($_SERVER['PHP_SELF'], false); ?>"><?php echo _("List all"); ?></a>
     7        &nbsp;&nbsp; <a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'], false); ?>"><?php echo _("List all"); ?></a>
    88        &nbsp;&nbsp; <?php echo _("Per page"); ?>:&nbsp;<?php $page->printPerPageLinks() ?>
    99    </span>
  • trunk/services/templates/lock.ihtml

    r42 r136  
    55?>
    66<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    7     <?php App::printHiddenSession() ?>
     7    <?php $app->printHiddenSession() ?>
    88    <input type="hidden" name="lock_id" value="<?php echo $lock->getID(); ?>" />
    99
  • trunk/services/templates/log_list.ihtml

    r121 r136  
    11<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    2 <?php App::printHiddenSession(false); ?>
     2<?php $app->printHiddenSession(false); ?>
    33
    44<div id="commandbox">
     
    1010        <tr class="commandtext">
    1111            <td>
    12                 <?php if ($l['filename'] == Prefs::getValue('log_file', 'logs_module')) { ?>
     12                <?php if ($l['filename'] == $prefs->get('log_file', 'logs_module')) { ?>
    1313                    <span class="commanditem"><strong><?php echo sprintf(_("%s"), $l['filename']); ?></strong></span>
    1414                <?php } else { ?>
    15                     <span class="commanditem"><a href="<?php echo App::oHREF('/admin/logs.php?log=' . $l['filename']); ?>"><strong><?php echo sprintf(_("%s"), $l['filename']); ?></strong></a></span>
     15                    <span class="commanditem"><a href="<?php echo $app->oHREF('/admin/logs.php?log=' . $l['filename']); ?>"><strong><?php echo sprintf(_("%s"), $l['filename']); ?></strong></a></span>
    1616                <?php } ?>
    1717            </td>
    1818            <td>
    19                 <span class="commanditem"><em><?php echo sprintf(_("%01.1f KB, last modified %s"), ($l['filesize']/1024), date(App::getParam('date_format'), $l['modified'])); ?></em></span>
     19                <span class="commanditem"><em><?php echo sprintf(_("%01.1f KB, last modified %s"), ($l['filesize']/1024), date($app->getParam('date_format'), $l['modified'])); ?></em></span>
    2020            </td>
    2121            <td>
    22                 <?php if (!preg_match($no_download_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo App::oHREF('/admin/logs.php?op=download&log=' . $l['filename']); ?>"><?php echo _("Download"); ?></a></span><?php } ?>
    23                 <?php if (!preg_match($no_archive_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo App::oHREF('/admin/logs.php?op=archive&log=' . $l['filename']); ?>"><?php echo _("Archive"); ?></a></span><?php } ?>
    24                 <?php if (!preg_match($no_clear_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo App::oHREF('/admin/logs.php?op=clear&log=' . $l['filename']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to clear the log file %s? This will empty this file of its contents. This action is not reversible."), $l['filename'])?>')"><?php echo _("Clear"); ?></a></span><?php } ?>
    25                 <?php if (!preg_match($no_delete_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo App::oHREF('/admin/logs.php?op=delete&log=' . $l['filename']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to delete the log file %s? This will remove this log file permanently. This action is not reversible."), $l['filename'])?>')"><?php echo _("Delete"); ?></a></span><?php } ?>
     22                <?php if (!preg_match($no_download_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo $app->oHREF('/admin/logs.php?op=download&log=' . $l['filename']); ?>"><?php echo _("Download"); ?></a></span><?php } ?>
     23                <?php if (!preg_match($no_archive_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo $app->oHREF('/admin/logs.php?op=archive&log=' . $l['filename']); ?>"><?php echo _("Archive"); ?></a></span><?php } ?>
     24                <?php if (!preg_match($no_clear_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo $app->oHREF('/admin/logs.php?op=clear&log=' . $l['filename']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to clear the log file %s? This will empty this file of its contents. This action is not reversible."), $l['filename'])?>')"><?php echo _("Clear"); ?></a></span><?php } ?>
     25                <?php if (!preg_match($no_delete_files, $l['filename'])) { ?><span class="commanditem"><a href="<?php echo $app->oHREF('/admin/logs.php?op=delete&log=' . $l['filename']); ?>" onClick="javascript:return confirm('<?php printf(_("Are you sure you want to delete the log file %s? This will remove this log file permanently. This action is not reversible."), $l['filename'])?>')"><?php echo _("Delete"); ?></a></span><?php } ?>
    2626            </td>
    2727        </tr><?php
  • trunk/services/templates/login_form.ihtml

    r121 r136  
    11<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    2 <?php App::printHiddenSession() ?>
     2<?php $app->printHiddenSession() ?>
    33<table>
    44    <tr>
  • trunk/services/templates/password.ihtml

    r121 r136  
    22
    33<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    4 <?php App::printHiddenSession() ?>
     4<?php $app->printHiddenSession() ?>
    55<input type="hidden" name="op" value="update_password" />
    66<table>
  • trunk/services/templates/versions_diff.ihtml

    r124 r136  
    11<div id="commandbox">
    22<?php if (!getFormData('current', false)) { ?>
    3     <span class="sc-nowrap commandtext"><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=restore', array('version_id', 'version_title')); ?>"><?php echo _("Restore this saved version"); ?></a></span>
     3    <span class="sc-nowrap commandtext"><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=restore', array('version_id', 'version_title')); ?>"><?php echo _("Restore this saved version"); ?></a></span>
    44<?php } else { ?>
    55    <span class="sc-nowrap commandtext">&nbsp;</span>
  • trunk/services/templates/versions_list.ihtml

    r124 r136  
    11<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    2 <?php App::printHiddenSession() ?>
     2<?php $app->printHiddenSession() ?>
    33<input type="submit" name="op" value="<?php echo _("Cancel"); ?>" />
    44<table class="list" border="0" cellspacing="0" cellpadding="4">
     
    1414<tr>
    1515    <?php if ($first) { ?>
    16     <td class="sc-padleft sc-nowrap">[<a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=view&current=true&version_id=' . $v['version_id']); ?>">view</a>]</td>
     16    <td class="sc-padleft sc-nowrap">[<a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=view&current=true&version_id=' . $v['version_id']); ?>">view</a>]</td>
    1717    <td class="sc-padleft sc-nowrap" colspan="2">(<?php echo _("Current record"); ?>)</td>
    1818    <?php } else { ?>
    19     <td class="sc-padleft sc-nowrap">[<a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=view&version_id=' . $v['version_id']); ?>">view</a>]</td>
    20     <td class="sc-padleft sc-nowrap">[<a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=diff&version_id=' . $v['version_id']); ?>">diff</a>]</td>
    21     <td class="sc-padleft sc-nowrap">[<a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=restore&version_id=' . $v['version_id']); ?>">restore</a>]</td>
     19    <td class="sc-padleft sc-nowrap">[<a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=view&version_id=' . $v['version_id']); ?>">view</a>]</td>
     20    <td class="sc-padleft sc-nowrap">[<a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=diff&version_id=' . $v['version_id']); ?>">diff</a>]</td>
     21    <td class="sc-padleft sc-nowrap">[<a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=restore&version_id=' . $v['version_id']); ?>">restore</a>]</td>
    2222    <?php } ?>
    2323    <td class="sc-padleft sc-nowrap"><?php echo $v['version_id']; ?></td>
  • trunk/services/templates/versions_view.ihtml

    r121 r136  
    11<div id="commandbox">
    22<?php if (!getFormData('current', false)) { ?>
    3     <span class="sc-nowrap commandtext"><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=restore', array('version_id', 'version_title')); ?>"><?php echo _("Restore this saved version"); ?></a></span>
     3    <span class="sc-nowrap commandtext"><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=restore', array('version_id', 'version_title')); ?>"><?php echo _("Restore this saved version"); ?></a></span>
    44<?php } else { ?>
    55    <span class="sc-nowrap commandtext">&nbsp;</span>
  • trunk/services/versions.php

    r42 r136  
    88
    99$auth->requireLogin();
    10 App::sslOn();
     10$app->sslOn();
    1111
    1212require_once 'codebase/lib/RecordVersion.inc.php';
     
    2020
    2121// Query arguments to retain their values between page requests.
    22 App::carryQuery('record_table');
    23 App::carryQuery('record_key');
    24 App::carryQuery('record_val');
    25 App::carryQuery('version_title');
     22$app->carryQuery('record_table');
     23$app->carryQuery('record_key');
     24$app->carryQuery('record_val');
     25$app->carryQuery('version_title');
    2626
    2727// Titles and navigation header.
     
    3939
    4040if ('' == $version_id && ('' == $record_table || '' == $record_key || '' == $record_val)) {
    41     App::raiseMsg(_("Record not specified for versioning."), MSG_WARNING, __FILE__, __LINE__);
    42     App::logMsg('Record not specified for versioning.', LOG_WARNING, __FILE__, __LINE__);
    43     App::dieBoomerangURL();
     41    $app->raiseMsg(_("Record not specified for versioning."), MSG_WARNING, __FILE__, __LINE__);
     42    $app->logMsg('Record not specified for versioning.', LOG_WARNING, __FILE__, __LINE__);
     43    $app->dieBoomerangURL();
    4444}
    4545
    4646if (getFormData('boomerang', false) && isset($_SERVER['HTTP_REFERER'])) {
    4747    // We remember which page we came from so we can go back there.
    48     App::setBoomerangURL($_SERVER['HTTP_REFERER'], 'versions');
     48    $app->setBoomerangURL($_SERVER['HTTP_REFERER'], 'versions');
    4949}
    5050
     
    5353
    5454case _("Cancel") :
    55     App::dieBoomerangURL('versions', false);
     55    $app->dieBoomerangURL('versions', false);
    5656    break;
    5757
     
    6868    $current = $version->getCurrent($record_table, $record_key, $record_val);
    6969    if (serialize($data) == serialize($current)) {
    70         App::raiseMsg(sprintf(_("Version <strong>%s</strong> is identical to the current record"), $version_id), MSG_NOTICE, __FILE__, __LINE__);
     70        $app->raiseMsg(sprintf(_("Version <strong>%s</strong> is identical to the current record"), $version_id), MSG_NOTICE, __FILE__, __LINE__);
    7171    }
    7272    $nav->addPage(sprintf(_("Difference between version %s (%s) and current record."), $version_id, $versionrecord['version_datetime']));
     
    8686        // Create version of this restored record as the "current" version.
    8787        $version->create($record_table, $record_key, $record_val, $v['version_title']);
    88         App::raiseMsg(sprintf(_("The record <strong>%s</strong> has been replaced with <strong>%s</strong> version <strong>%s</strong> from <strong>%s</strong>."), getFormData('version_title'), $v['version_title'], $version_id, $v['version_datetime']), MSG_SUCCESS, __FILE__, __LINE__);
    89         App::dieBoomerangURL('versions', array('break_list_cache'=>'true', false));
     88        $app->raiseMsg(sprintf(_("The record <strong>%s</strong> has been replaced with <strong>%s</strong> version <strong>%s</strong> from <strong>%s</strong>."), getFormData('version_title'), $v['version_title'], $version_id, $v['version_datetime']), MSG_SUCCESS, __FILE__, __LINE__);
     89        $app->dieBoomerangURL('versions', array('break_list_cache'=>'true', false));
    9090    } else {
    91         App::raiseMsg(_("Version restoration failed."), MSG_ERR, __FILE__, __LINE__);
    92         App::dieURL($_SERVER['PHP_SELF']);
     91        $app->raiseMsg(_("Version restoration failed."), MSG_ERR, __FILE__, __LINE__);
     92        $app->dieURL($_SERVER['PHP_SELF']);
    9393    }
    9494    break;
     
    101101        $main_template = 'versions_list.ihtml';
    102102    } else {
    103         App::raiseMsg(sprintf(_("No saved versions available for this record"), null), MSG_NOTICE, __FILE__, __LINE__);
    104         App::dieBoomerangURL('versions');
     103        $app->raiseMsg(sprintf(_("No saved versions available for this record"), null), MSG_NOTICE, __FILE__, __LINE__);
     104        $app->dieBoomerangURL('versions');
    105105    }
    106106}
  • trunk/tests/AppTest.php

    r42 r136  
    3232    function test_getinstance()
    3333    {
    34         $thisapp =& App::getinstance();
     34        $thisapp =& App::getInstance();
    3535        $this->assertTrue(serialize($thisapp) == serialize($this->App), 'Objects do not match across instantiations.');
    3636    }
     
    7171    function test_dbquery()
    7272    {
    73         $qid = DB::query("SELECT 2 + 2");
     73        $db =& DB::getInstance();
     74   
     75        $qid = $db->query("SELECT 2 + 2");
    7476        list($result) = mysql_fetch_row($qid);
    7577        $this->assertEquals('4', $result);
     
    7880    function test_raisemsg()
    7981    {
     82        $app =& App::getInstance();
    8083        $expected = 'My message';
    81         App::raiseMsg($expected, MSG_NOTICE, __FILE__, __LINE__);
    82         $msg = current($_SESSION[$this->App->app]['messages']);
     84        $app->raiseMsg($expected, MSG_NOTICE, __FILE__, __LINE__);
     85        $msg = current($_SESSION[$this->App->_ns]['messages']);
    8386        $this->assertEquals($expected, $msg['message']);
    8487    }
     
    8790    {
    8891        ob_start();
    89         App::printraisedmessages();
     92        $app =& App::getInstance();
     93        $app->printraisedmessages();
    9094        $result = ob_get_clean();
    9195        $this->assertContains('My message', $result, 'Raised message not found in output.');
     
    9498    function test_logmsg()
    9599    {
     100        $app =& App::getInstance();
    96101        $file = $this->App->getParam('log_directory') . '/' . $this->App->getParam('log_filename');
    97         App::logMsg('Test log message', LOG_DEBUG, __FILE__, __LINE__);
     102        $app->logMsg('Test log message', LOG_DEBUG, __FILE__, __LINE__);
    98103        if ($result = file($file)) {
    99104            $result = end($result);
     
    106111    function test_ohref()
    107112    {
     113        $app =& App::getInstance();
    108114        $_GET['arg1'] = 'A';
    109         $result = App::ohref('/some/url.php', array('arg1'), true);
     115        $result = $app->ohref('/some/url.php', array('arg1'), true);
    110116        $this->assertContains(session_name(), $result, 'SSID not found in URL.');
    111117        $this->assertContains('arg1=A', $result, 'Argument not passed through.');
     
    114120    function test_printhiddensession()
    115121    {
     122        $app =& App::getInstance();
    116123        ob_start();
    117         App::printhiddensession();
     124        $app->printhiddensession();
    118125        $result = ob_get_clean();
    119126        $this->assertContains(session_name(), $result);
     
    122129//     function test_dieurl()
    123130//     {
    124 //         App::dieURL('/die/to/this/url.php');
     131//         $app =& App::getInstance();
     132//         $app->dieURL('/die/to/this/url.php');
    125133//     }
    126134//
  • trunk/tests/Auth_FileTest.php

    r42 r136  
    2323        require dirname(__FILE__) . '/_config.inc.php';
    2424        require_once '../lib/Auth_File.inc.php';
    25         $this->Auth_File =& new Auth_File(array('htpasswd_file' => dirname(__FILE__) . '/_test_htpasswd'));
     25        $this->Auth_File =& new Auth_File('test_auth');
     26        $this->Auth_File->setParam(array('htpasswd_file' => dirname(__FILE__) . '/_test_htpasswd'));
    2627    }
    2728
     
    4445        $result = $this->Auth_File->login('testuser', 'testpass');
    4546        $this->assertTrue($result, 'testuser login failed.');
    46         $this->assertTrue($_SESSION['_auth']['authenticated'], 'testuser authentication not found in session.');
     47        $this->assertTrue($_SESSION[$this->Auth_File->_ns]['authenticated'], 'testuser authentication not found in session.');
    4748    }
    4849
     
    5152        $result = $this->Auth_File->login('testuser', 'testpass');
    5253        $this->Auth_File->clearauth();
    53         $this->assertFalse($_SESSION['_auth']['authenticated'], 'testuser authentication not false in session.');
     54        $this->assertFalse($_SESSION[$this->Auth_File->_ns]['authenticated'], 'testuser authentication not false in session.');
    5455    }
    5556
  • trunk/tests/Auth_SQLTest.php

    r42 r136  
    2121    function setUp()
    2222    {
    23         require dirname(__FILE__) . '/_config.inc.php';
     23        require dirname(__FILE__) . '/_config.inc.php';
    2424        require_once '../lib/Auth_SQL.inc.php';
    2525        $this->Auth_SQL =& new Auth_SQL('testauth');
     
    2929            'db_login_table'    => 'test_login_tbl',
    3030            'login_url'         => '/login.php',
    31             'blocking'          => true
     31            'blocking'          => true,
     32            'encryption_type' => AUTH_ENCRYPT_MD5_HARDENED,
    3233        ));
    3334
     
    3637
    3738        // Insert test data.
    38         DB::query("
     39        $db =& DB::getInstance();
     40        $db->query("
    3941            INSERT INTO test_user_tbl (
    4042                username,
     
    4648            ) VALUES (
    4749                'testuser',
    48                 md5('testpass'),
     50                '" . $this->Auth_SQL->encryptPassword('testpass') . "',
    4951                'John',
    5052                'Doe',
     
    5860    function tearDown()
    5961    {
    60         unset($this->Auth_SQL);
    61         DB::query("DROP TABLE IF EXISTS test_user_tbl");
    62         DB::query("DROP TABLE IF EXISTS test_login_tbl");
     62        $db =& DB::getInstance();
     63   
     64        unset($this->Auth_SQL);
     65        $db->query("DROP TABLE IF EXISTS test_user_tbl");
     66        $db->query("DROP TABLE IF EXISTS test_login_tbl");
    6367    }
    6468
     
    6670    {
    6771        $this->Auth_SQL->setval('testuserkey', 'testuserval');
    68         $this->assertEquals('testuserval', $_SESSION[$this->Auth_SQL->_sess]['user_data']['testuserkey']);
     72        $this->assertEquals('testuserval', $_SESSION[$this->Auth_SQL->_ns]['user_data']['testuserkey']);
    6973    }
    7074
    7175    function test_getval()
    7276    {
    73         $_SESSION[$this->Auth_SQL->_sess]['user_data']['testuserkey'] = 'testuserval';
     77        $_SESSION[$this->Auth_SQL->_ns]['user_data']['testuserkey'] = 'testuserval';
    7478        $val = $this->Auth_SQL->getVal('testuserkey');
    7579        $this->assertEquals('testuserval', $val);
     
    107111        $this->assertTrue($true, 'User login failed, but should have succeeded.');
    108112
    109         echo "Testing wrong password...\n";
     113        // Testing wrong password.
    110114        $false = $this->Auth_SQL->authenticate('testuser', 'wrongpass');
    111115
     
    122126        $after_logged_in = $this->Auth_SQL->isloggedin();
    123127        $this->assertFalse($after_logged_in, '3. User is still logged in but should not be.');
    124 
    125         echo "Testing wrong password...\n";
     128       
     129        // Testing wrong password.
    126130        $login2 = $this->Auth_SQL->login('testuser', 'wrongpass');
    127131        $this->assertFalse($login2, '4. User login succeeded, but should have failed.');
     
    140144    function test_blockaccount()
    141145    {
     146        $db =& DB::getInstance();
     147   
    142148        $this->Auth_SQL->login('testuser', 'testpass');
    143149        $this->Auth_SQL->blockaccount(null, 'blocktestuser');
    144         $qid = DB::query("
     150        $qid = $db->query("
    145151            SELECT blocked_reason
    146152            FROM test_user_tbl
     
    152158    function test_unblockaccount()
    153159    {
    154         DB::query("
     160        $db =& DB::getInstance();
     161   
     162        $db->query("
    155163            UPDATE test_user_tbl SET blocked_reason = 'blocktestuser'
    156164        ");
    157165        $this->Auth_SQL->unblockaccount();
    158166
    159         $qid = DB::query("
     167        $qid = $db->query("
    160168            SELECT blocked_reason
    161169            FROM test_user_tbl
     
    185193    function test_encryptpassword()
    186194    {
     195        $this->Auth_SQL->setParam(array('encryption_type' => AUTH_ENCRYPT_MD5));
    187196        $result = $this->Auth_SQL->encryptpassword('123');
    188197        $this->assertEquals('202cb962ac59075b964b07152d234b70', $result);
     198
     199        $this->Auth_SQL->setParam(array('encryption_type' => AUTH_ENCRYPT_MD5_HARDENED));
     200        $result = $this->Auth_SQL->encryptpassword('123');
     201        $this->assertEquals('c55e4ac608a8768ecd758fab971b0646', $result);
     202
     203        $this->Auth_SQL->setParam(array('encryption_type' => AUTH_ENCRYPT_SHA1));
     204        $result = $this->Auth_SQL->encryptpassword('123');
     205        $this->assertEquals('40bd001563085fc35165329ea1ff5c5ecbdbbeef', $result);
     206
     207        $this->Auth_SQL->setParam(array('encryption_type' => AUTH_ENCRYPT_SHA1_HARDENED));
     208        $result = $this->Auth_SQL->encryptpassword('123');
     209        $this->assertEquals('33d90af96a5928ac93cbd41fc436e8c55d2768c2', $result);
     210
     211        $this->Auth_SQL->setParam(array('encryption_type' => AUTH_ENCRYPT_PLAINTEXT));
     212        $result = $this->Auth_SQL->encryptpassword('123');
     213        $this->assertEquals('123', $result);
     214
     215        $this->Auth_SQL->setParam(array('encryption_type' => AUTH_ENCRYPT_CRYPT));
     216        $result = $this->Auth_SQL->encryptpassword('123', 'saltstring');
     217        $this->assertEquals('saEZ6MlWYV9nQ', $result);
    189218    }
    190219
    191220    function test_setpassword()
    192221    {
     222        $db =& DB::getInstance();
     223   
     224        $this->Auth_SQL->setParam(array('encryption_type' => AUTH_ENCRYPT_SHA1_HARDENED));
    193225        $this->Auth_SQL->setpassword(null, '123');
    194         $qid = DB::query("
     226        $qid = $db->query("
    195227            SELECT userpass
    196228            FROM test_user_tbl
    197229        ");
    198230        list($pass) = mysql_fetch_row($qid);
    199         $this->assertEquals('202cb962ac59075b964b07152d234b70', $pass);
     231        $this->assertEquals('33d90af96a5928ac93cbd41fc436e8c55d2768c2', $pass);
    200232    }
    201233
  • trunk/tests/DBSessionHandlerTest.php

    r42 r136  
    2424        require_once '../lib/DBSessionHandler.inc.php';
    2525        session_write_close();
    26         $this->DBSessionHandler = new DBSessionHandler($app->db);
    27         $this->DBSessionHandler = new DBSessionHandler(null, array(
    28             'db_server' => $app->getParam('db_server'),
    29             'db_name' => $app->getParam('db_name'),
    30             'db_user' => $app->getParam('db_user'),
    31             'db_pass' => $app->getParam('db_pass'),
    32             'db_always_debug' => $app->getParam('db_always_debug'),
    33             'db_debug' => $app->getParam('db_debug'),
    34             'db_die_on_failure' => $app->getParam('db_die_on_failure'),
     26        $this->DBSessionHandler = new DBSessionHandler($app->db, array(
     27            'db_table' => 'session_tbl',
     28            'create_table' => true,
    3529        ));
    3630    }
  • trunk/tests/RecordLockTest.php

    r42 r136  
    2121
    2222    function setUp()
    23     {
     23    {   
    2424        require dirname(__FILE__) . '/_config.inc.php';
    2525        require_once '../lib/RecordLock.inc.php';
    2626        require_once '../lib/Auth_SQL.inc.php';
    2727
    28         $this->Auth_SQL =& new Auth_SQL('testauth');
     28        $this->Auth_SQL =& new Auth_SQL('test');
    2929        $this->Auth_SQL->setParam(array(
    3030            'db_table'          => 'test_user_tbl',
     
    3939
    4040        // Insert test data.
    41         DB::query("
     41        $db =& DB::getInstance();
     42        $db->query("
    4243            INSERT INTO test_user_tbl (
    4344                username,
     
    4950            ) VALUES (
    5051                'testuser',
    51                 md5('testpass'),
     52                '" . $this->Auth_SQL->encryptPassword('testpass') . "',
    5253                'John',
    5354                'Doe',
     
    5758        ");
    5859        $this->Auth_SQL->login('testuser', 'testpass');
     60
     61        if (!$this->Auth_SQL->isLoggedIn()) {
     62            trigger_error("User login failed...tests canceled.", E_USER_ERROR);
     63        }
    5964
    6065        $this->RecordLock =& RecordLock::getInstance($this->Auth_SQL);
     
    6772    function tearDown()
    6873    {
     74        $db =& DB::getInstance();
     75   
    6976        unset($this->RecordLock);
    7077        unset($this->Auth_SQL);
    71         DB::query("DROP TABLE IF EXISTS test_user_tbl");
    72         DB::query("DROP TABLE IF EXISTS test_login_tbl");
    73         DB::query("DROP TABLE IF EXISTS test_lock_tbl");
     78        $db->query("DROP TABLE IF EXISTS test_user_tbl");
     79        $db->query("DROP TABLE IF EXISTS test_login_tbl");
     80        $db->query("DROP TABLE IF EXISTS test_lock_tbl");
    7481    }
    7582
  • trunk/tests/RecordVersionTest.php

    r42 r136  
    2121
    2222    function setUp()
    23     {
     23    {   
    2424        require dirname(__FILE__) . '/_config.inc.php';
    2525        require_once '../lib/RecordVersion.inc.php';
     
    3939
    4040        // Insert test data.
    41         DB::query("
     41        $db =& DB::getInstance();
     42        $db->query("
    4243            INSERT INTO test_user_tbl (
    4344                username,
     
    6869    function tearDown()
    6970    {
     71        $db =& DB::getInstance();
     72   
    7073        unset($this->RecordVersion);
    7174        unset($this->Auth_SQL);
    72         DB::query("DROP TABLE IF EXISTS test_user_tbl");
    73         DB::query("DROP TABLE IF EXISTS test_login_tbl");
    74         DB::query("DROP TABLE IF EXISTS test_version_tbl");
     75        $db->query("DROP TABLE IF EXISTS test_user_tbl");
     76        $db->query("DROP TABLE IF EXISTS test_login_tbl");
     77        $db->query("DROP TABLE IF EXISTS test_version_tbl");
    7578    }
    7679
  • trunk/tests/SessionCacheTest.php

    r42 r136  
    44
    55/**
    6  * PHPUnit test case for SessionCache
     6 * PHPUnit test case for Cache
    77 *
    88 * The method skeletons below need to be filled in with
     
    1313 */
    1414require_once 'PHPUnit.php';
    15 class SessionCacheTest extends PHPUnit_TestCase {
     15class CacheTest extends PHPUnit_TestCase {
    1616
    17     var $SessionCache;
     17    var $Cache;
    1818
    19     function SessionCacheTest($name)
     19    function CacheTest($name)
    2020    {
    2121        $this->PHPUnit_TestCase($name);
     
    2525    {
    2626        require dirname(__FILE__) . '/_config.inc.php';
    27         require_once '../lib/SessionCache.inc.php';
    28         $this->SessionCache =& new SessionCache(PARAM);
     27        require_once '../lib/Cache.inc.php';
     28        $this->Cache =& new Cache(PARAM);
    2929    }
    3030
    3131    function tearDown()
    3232    {
    33         unset($this->SessionCache);
     33        unset($this->Cache);
    3434    }
    3535
    3636    function test_getinstance()
    3737    {
    38         $result = $this->SessionCache->getinstance(PARAM);
     38        $result = $this->Cache->getinstance(PARAM);
    3939        $expected = EXPECTED_VAL;
    4040        $this->assertEquals($expected, $result);
     
    4343    function test_setparam()
    4444    {
    45         $result = $this->SessionCache->setparam(PARAM);
     45        $result = $this->Cache->setparam(PARAM);
    4646        $expected = EXPECTED_VAL;
    4747        $this->assertEquals($expected, $result);
     
    5050    function test_getparam()
    5151    {
    52         $result = $this->SessionCache->getparam(PARAM);
     52        $result = $this->Cache->getparam(PARAM);
    5353        $expected = EXPECTED_VAL;
    5454        $this->assertEquals($expected, $result);
     
    5757    function test_putcache()
    5858    {
    59         $result = $this->SessionCache->putcache(PARAM);
     59        $result = $this->Cache->putcache(PARAM);
    6060        $expected = EXPECTED_VAL;
    6161        $this->assertEquals($expected, $result);
     
    6464    function test_getcache()
    6565    {
    66         $result = $this->SessionCache->getcache(PARAM);
     66        $result = $this->Cache->getcache(PARAM);
    6767        $expected = EXPECTED_VAL;
    6868        $this->assertEquals($expected, $result);
     
    7171    function test_iscached()
    7272    {
    73         $result = $this->SessionCache->iscached(PARAM);
     73        $result = $this->Cache->iscached(PARAM);
    7474        $expected = EXPECTED_VAL;
    7575        $this->assertEquals($expected, $result);
     
    7878    function test_breakcache()
    7979    {
    80         $result = $this->SessionCache->breakcache(PARAM);
     80        $result = $this->Cache->breakcache(PARAM);
    8181        $expected = EXPECTED_VAL;
    8282        $this->assertEquals($expected, $result);
     
    8585}
    8686// Running the test.
    87 $suite = new PHPUnit_TestSuite('SessionCacheTest');
     87$suite = new PHPUnit_TestSuite('CacheTest');
    8888$result = PHPUnit::run($suite);
    8989echo $result->toString();
  • trunk/tests/_config.inc.php

    r43 r136  
    11<?php
    22require_once '../lib/App.inc.php';
    3 $app =& App::getinstance('testapp');
     3$app =& App::getInstance('testapp');
    44
    55$app->setParam(array(
Note: See TracChangeset for help on using the changeset viewer.