function countRecordsByUser($tableName, $userNum = null)
{
    if (!$userNum) {
        $userNum = @$GLOBALS['CURRENT_USER']['num'];
    }
    return mysql_count($tableName, "`createdByUserNum` = '" . mysql_escape($userNum) . "'");
}
function getTableDetails()
{
    global $tableName;
    $tableDetails = array();
    $tableDetails['rowCount'] = mysql_count($tableName);
    return $tableDetails;
}
function getTableList()
{
    global $TABLE_PREFIX, $APP;
    // get table names
    $mysqlTables = getMysqlTablesWithPrefix();
    $schemaTables = getSchemaTables();
    // create multi query
    $tables = array();
    $tableRowCounts = array();
    foreach ($schemaTables as $tableName) {
        $tableNameWithPrefix = getTableNameWithPrefix($tableName);
        if (in_array($tableNameWithPrefix, $mysqlTables)) {
            $rowCount = mysql_count($tableNameWithPrefix);
        }
        $localTableSchema = loadSchema($tableName);
        array_push($tables, array('tableName' => $tableName, 'menuName' => @$localTableSchema['menuName'], 'menuType' => @$localTableSchema['menuType'], 'menuOrder' => @$localTableSchema['menuOrder'], 'menuHidden' => @$localTableSchema['menuHidden'], 'tableHidden' => @$localTableSchema['tableHidden'], '_indent' => @$localTableSchema['_indent'], 'recordCount' => $rowCount));
    }
    // sort table list
    uasort($tables, '_sortMenusByOrder');
    //
    return $tables;
}
function list_functions_init($options = array())
{
    global $CURRENT_USER, $isRelatedRecords;
    // set defaults
    $isRelatedRecords = @$options['isRelatedRecords'];
    $tableName = @$options['tableName'] ? $options['tableName'] : $GLOBALS['tableName'];
    $schema = @$options['tableName'] ? loadSchema(@$options['tableName']) : $GLOBALS['schema'];
    $accessWhere = @$options['where'] ? $options['where'] : 'true';
    $perPage = @$options['perPage'];
    // Perform search
    // if the search form was submitted, we need to reset page=1
    if (@$_REQUEST['_defaultAction']) {
        $_REQUEST['page'] = 1;
    }
    // Reset Search (and clear saved editor state)
    if (@$_REQUEST['_resetSearch'] || @$_REQUEST['_resetSavedSearch']) {
        // clear last state and request on resetSearch.  _resetSavedSearch is for custom links where you don't want previously saved search info to interfere
        $_SESSION['lastRequest'][$tableName] = array('showAdvancedSearch' => @$_SESSION['lastRequest'][$tableName]['showAdvancedSearch'], 'perPage' => @$_SESSION['lastRequest'][$tableName]['perPage'], 'page' => 1);
    }
    if (@$_REQUEST['_resetSearch']) {
        // clear last state and request on resetSearch
        $_REQUEST = array('menu' => @$_REQUEST['menu'], 'perPage' => @$_REQUEST['perPage'], 'page' => 1);
    }
    // Load last _REQUEST from _SESSION (current _REQUEST values override old ones)
    if (@$_SESSION['lastRequest'][$tableName] && !$isRelatedRecords && !@$_REQUEST['_ignoreSavedSearch']) {
        $sortByField = @$_SESSION['lastRequest'][$tableName]['sortBy'];
        $invalidSortByField = $sortByField && !@$schema[$sortByField];
        if ($invalidSortByField) {
            unset($_SESSION['lastRequest'][$tableName]['sortBy']);
        }
        // v2.52 remove invalid sort by fields
        $_REQUEST += $_SESSION['lastRequest'][$tableName];
    }
    // get user where (to limit to records user has access to)
    $showAllRecords = false;
    if (!@$schema['createdByUserNum']) {
        $showAllRecords = true;
    } elseif ($GLOBALS['hasEditorAccess']) {
        $showAllRecords = true;
    } elseif ($GLOBALS['hasViewerAccessOnly']) {
        $showAllRecords = true;
    } elseif ($GLOBALS['hasAuthorViewerAccess']) {
        $showAllRecords = true;
    }
    // viewers can see all records
    if (!$showAllRecords) {
        $accessWhere = "({$accessWhere}) AND `createdByUserNum` = '{$CURRENT_USER['num']}'";
    }
    if ($tableName == 'accounts' && !@$CURRENT_USER['isAdmin']) {
        $accessWhere = "({$accessWhere}) AND `isAdmin` = '0'";
    }
    // get ORDER BY
    $orderBy = $schema['listPageOrder'];
    if (@$_REQUEST['sortBy']) {
        if (!@$schema[$_REQUEST['sortBy']]) {
            die("Can't sortBy '" . htmlencode($_REQUEST['sortBy']) . "'.  Not a valid field!");
        }
        $orderBy = "`{$_REQUEST['sortBy']}` ";
        if (@$_REQUEST['sortDir'] == 'desc') {
            $orderBy .= " DESC";
        }
    }
    // $accessWhere -  This is for access control, records filtered out here aren't included in the record count (Total Record: 123)
    $accessWhere = applyFilters('list_where', $accessWhere, $tableName);
    // This is for searching, records filtered out here _are_ included in the record count (Total Record: 123)
    $accessWhere = applyFilters('record_access_where', $accessWhere, $tableName);
    // same as above, but this filter is also called in _displayRecordAccessErrors()
    $orderBy = applyFilters('list_orderBy', $orderBy, $tableName);
    // This is for modifying the orderBy option
    $searchWhere = $accessWhere;
    // load records
    list($records, $metaData) = getRecords(array('tableName' => $tableName, 'perPage' => $isRelatedRecords ? $perPage : getFirstDefinedValue(@$_REQUEST['perPage'], @$schema['_perPageDefault'], 25), 'pageNum' => $isRelatedRecords ? 1 : intval(@$_REQUEST['page']), 'orderBy' => $orderBy, 'where' => $searchWhere, 'allowSearch' => $isRelatedRecords ? false : true, 'requireSearchSuffix' => 'true', 'ignoreHidden' => true, 'ignorePublishDate' => true, 'ignoreRemoveDate' => true, 'includeDisabledAccounts' => true, 'loadPseudoFields' => false));
    $metaData['totalMatches'] = $metaData['totalRecords'];
    $metaData['totalRecords'] = mysql_count($tableName, $accessWhere);
    // save _REQUEST to _SESSION (this is how we maintain state when user returns to list page)
    if (!$isRelatedRecords) {
        $skipFields = array('menu');
        foreach ($_REQUEST as $key => $value) {
            // save all submitted values
            if (preg_match('/^_/', $key)) {
                continue;
            }
            // skip program command fields: _defaultAction, _advancedAction, etc
            if (in_array($key, $skipFields)) {
                continue;
            }
            //
            $_SESSION['lastRequest'][$tableName][$key] = $value;
        }
        $_SESSION['lastRequest'][$tableName]['page'] = $metaData['page'];
        // override page with calculated actual page from getRecords()
        $_SESSION['lastRequest'][$tableName]['perPage'] = $metaData['perPage'];
        // override perPage with actual perPage from getRecords()
    }
    //
    $listFields = preg_split("/\\s*,\\s*/", $schema['listPageFields']);
    // fields to show on list page
    return array($listFields, $records, $metaData);
}
function showMaxRecordsError($returnText = false)
{
    global $CURRENT_USER, $tableName, $escapedTableName, $schema, $hasEditorAccess;
    $errors = '';
    // check section record limit
    if (@$schema['_maxRecords'] != '') {
        $recordCount = mysql_count($tableName);
        if ($recordCount >= $schema['_maxRecords']) {
            $errors .= sprintf(t('This section only allows a total of \'%s\' records (section limit).'), $schema['_maxRecords']) . "<br/>\n";
        }
    }
    // check user records limit (regular users only)
    if (!$hasEditorAccess && @$schema['createdByUserNum']) {
        $recordCount = mysql_count($tableName, "`createdByUserNum` = '{$CURRENT_USER['num']}'");
        if (@$schema['_maxRecordsPerUser'] && $recordCount >= $schema['_maxRecordsPerUser']) {
            $errors .= sprintf(t('You are only allowed to have \'%s\' records in this section (Section Editor Limit).'), $schema['_maxRecordsPerUser']) . "<br/>\n";
        } elseif (@$CURRENT_USER['accessList'][$tableName]['maxRecords'] && $recordCount >= $CURRENT_USER['accessList'][$tableName]['maxRecords']) {
            $errors .= sprintf(t('You are only allowed to have \'%s\' records in this section (User Account Limit).'), $CURRENT_USER['accessList'][$tableName]['maxRecords']) . "<br/>\n";
        }
    }
    // display errors
    if ($errors) {
        if ($returnText) {
            return $errors;
        } else {
            alert($errors);
            include 'lib/menus/default/list.php';
            exit;
        }
    }
}
function _errorlog_sendEmailAlert()
{
    if (!$GLOBALS['SETTINGS']['advanced']['phpEmailErrors']) {
        return;
    }
    // once run function once per page-view
    static $alreadySent = false;
    if ($alreadySent) {
        return;
    }
    $alreadySent = true;
    // check if email sent in last hour
    $sentInLastHour = mysql_count('_error_log', " `dateLogged` > (NOW() - INTERVAL 1 HOUR) AND email_sent = 1");
    // send hourly alert
    if (!$sentInLastHour) {
        // send email
        $secondsAgo = time() - $GLOBALS['SETTINGS']['bgtasks_lastEmail'];
        if ($secondsAgo >= 60 * 60) {
            // don't email more than once an hour
            // get date format
            if ($GLOBALS['SETTINGS']['dateFormat'] == 'dmy') {
                $dateFormat = "jS M, Y - h:i:s A";
            } elseif ($GLOBALS['SETTINGS']['dateFormat'] == 'mdy') {
                $dateFormat = "M jS, Y - h:i:s A";
            } else {
                $dateFormat = "M jS, Y - h:i:s A";
            }
            // load latest error list
            $latestErrors = mysql_select('_error_log', "`dateLogged` > (NOW() - INTERVAL 1 HOUR) ORDER BY `dateLogged` DESC LIMIT 25");
            $latestErrorsList = '';
            foreach ($latestErrors as $thisError) {
                $latestErrorsList .= date($dateFormat, strtotime($thisError['dateLogged'])) . "\n";
                $latestErrorsList .= $thisError['error'] . "\n";
                $latestErrorsList .= $thisError['filepath'] . " (line " . $thisError['line_num'] . ")\n";
                $latestErrorsList .= $thisError['url'] . "\n\n";
            }
            // set email_sent flag for ALL records
            mysql_update('_error_log', null, 'TRUE', array('email_sent' => 1));
            // send email message
            $placeholders = array('error.hostname' => parse_url($GLOBALS['SETTINGS']['adminUrl'], PHP_URL_HOST), 'error.latestErrorsList' => nl2br(htmlencode($latestErrorsList)), 'error.errorLogUrl' => realUrl("?menu=_error_log", $GLOBALS['SETTINGS']['adminUrl']));
            $errors = sendMessage(emailTemplate_loadFromDB(array('template_id' => 'CMS-ERRORLOG-ALERT', 'placeholders' => $placeholders)));
            // log/display email sending errors
            if ($errors) {
                trigger_error("Unable to send error notification email from " . __FUNCTION__ . ": {$errors}", E_USER_NOTICE);
                die(__FUNCTION__ . ": {$errors}");
            }
        }
    }
}
function _getAdminMenus(&$menuOrder)
{
    global $CURRENT_USER;
    if (!@$CURRENT_USER['isAdmin']) {
        return array();
    }
    $menu = @$_REQUEST['menu'];
    $action = getRequestedAction();
    $adminMenus = array();
    $adminMenus[] = array('menuType' => 'menugroup', 'menuName' => t('Admin'), 'menuOrder' => ++$menuOrder, 'tableName' => '', 'link' => '', 'isSelected' => '');
    $adminMenus[] = array('menuType' => 'custom', 'menuName' => t('General Settings'), 'menuOrder' => ++$menuOrder, 'link' => '?menu=admin&amp;action=general', 'isSelected' => $menu == 'admin' && ($action == 'general' || $action == 'vendor' || $action == 'adminSave'));
    $adminMenus[] = array('menuType' => 'custom', 'menuName' => t('Section Editors'), 'menuOrder' => ++$menuOrder, 'link' => '?menu=database', 'isSelected' => $menu == 'database');
    $adminMenus[] = array('menuType' => 'custom', 'menuName' => t('Code Generator'), 'menuOrder' => ++$menuOrder, 'link' => '?menu=_codeGenerator', 'isSelected' => $menu == '_codeGenerator');
    $adminMenus[] = array('menuType' => 'custom', 'menuName' => t('Plugins'), 'menuOrder' => ++$menuOrder, 'link' => '?menu=admin&amp;action=plugins', 'isSelected' => $menu == 'admin' && $action == 'plugins');
    $adminMenus[] = array('menuType' => 'custom', 'menuName' => t('Email Templates'), 'menuOrder' => ++$menuOrder, 'link' => '?menu=_email_templates', 'isSelected' => $menu == '_email_templates');
    if (@$GLOBALS['SETTINGS']['advanced']['outgoingMail'] != 'sendOnly') {
        // only show outgoing mail menu if logging is enabled
        $count = mysql_count('_outgoing_mail');
        $countText = $count ? " ({$count})" : "";
        $adminMenus[] = array('menuType' => 'custom', 'menuName' => t('Outgoing Mail') . $countText, 'menuOrder' => ++$menuOrder, 'link' => '?menu=_outgoing_mail', 'isSelected' => $menu == '_outgoing_mail');
    }
    //
    $errorCount = mysql_count('_error_log');
    $adminMenus[] = array('menuType' => 'custom', 'menuName' => t('Error Log') . " ({$errorCount})", 'menuOrder' => ++$menuOrder, 'link' => '?menu=_error_log', 'isSelected' => $menu == '_error_log', 'tableName' => '_error_log', 'recordCount' => $errorCount);
    //array_pop($adminMenus); // remove "Error Log" from menu
    //
    return $adminMenus;
}
function emailTemplate_addToDB($record)
{
    if (!$record['template_id']) {
        dieAsCaller(__FUNCTION__ . ": No 'template_id' set in options");
    }
    // check if template id exists
    $templateExists = mysql_count('_email_templates', array('template_id' => $record['template_id']));
    if ($templateExists) {
        return false;
    }
    // get placeholder text
    $placeholderText = '';
    if (is_array($record['placeholders'])) {
        if ($record['placeholders']) {
            // if array isn't empty
            // hijack emailTemplate_replacePlaceholders() get us a placeholder list (including server placeholders) from placeholder array
            $placeholderText = array_value(emailTemplate_replacePlaceholders(array(), array_combine($record['placeholders'], $record['placeholders'])), 1);
        }
    } else {
        $placeholderText = $record['placeholders'];
    }
    // add template
    $colsToValues = array('createdDate=' => 'NOW()', 'createdByUserNum' => '0', 'updatedDate=' => 'NOW()', 'updatedByUserNum' => '0', 'template_id' => $record['template_id'], 'description' => $record['description'], 'from' => $record['from'], 'reply-to' => @$record['from'], 'to' => $record['to'], 'cc' => @$record['cc'], 'bcc' => @$record['bcc'], 'subject' => $record['subject'], 'html' => $record['html'], 'placeholders' => $placeholderText);
    mysql_insert('_email_templates', $colsToValues, true);
    // set notice
    //if ($showNotice) {
    //  notice(t("Adding email template:"). htmlencode($colsToValues['template_id']). "<br/>\n");
    //}
}
Example #9
0
function __getUniqueFieldErrors($fieldLabel, $fieldName, $fieldValue, $recordNum)
{
    global $escapedTableName, $tableName;
    $error = '';
    // check if value already in use
    $where = "`{$fieldName}` = '" . mysql_escape($fieldValue) . "'";
    if ($recordNum) {
        $where .= " AND num != '" . mysql_escape($recordNum) . "'";
    }
    # ignore records existing value (which might be the same)
    $count = mysql_count($tableName, $where);
    if ($count > 0) {
        $error = sprintf(t("'%s' value must be unique. The selected value is already in use!"), $fieldLabel) . "\n";
    }
    //
    return $error;
}
function installIfNeeded()
{
    global $SETTINGS, $APP, $TABLE_PREFIX;
    if (isInstalled()) {
        return;
    }
    // skip if already installed
    // rename default files
    renameOrRemoveDefaultFiles();
    // error checking
    if ($SETTINGS['uploadDir'] && !is_dir($SETTINGS['uploadDir'])) {
        print "Upload directory doesn't exist, please update 'uploadDir' in /data/" . SETTINGS_FILENAME . "<br/>\n";
        print "Current uploadDir value: " . htmlencode($SETTINGS['uploadDir']) . "<br/>\n";
        print "Suggested uploadDir value: uploads/ or ../uploads/<br/>\n";
        exit;
    }
    // error checking
    checkFilePermissions();
    // display license
    if (@$_REQUEST['menu'] == 'license') {
        showInterface('license.php');
    }
    // save
    if (@$_REQUEST['save']) {
        // error checking
        if (!$_REQUEST['licenseCompanyName']) {
            alert("Please enter your 'Company Name'<br/>\n");
        }
        if (!$_REQUEST['licenseDomainName']) {
            alert("Please enter your 'Domain Name'<br/>\n");
        }
        if (!$_REQUEST['licenseProductId']) {
            alert("Please enter your 'Product Id'<br/>\n");
        } else {
            if (!isValidProductId($_REQUEST['licenseProductId'])) {
                alert("Invalid Product Id!<br/>\n");
            }
        }
        if (!$_REQUEST['agreeToOneInstall']) {
            alert("Please check 'I agree not to use this 'Product Id' for multiple installs'<br/>\n");
        }
        if (!$_REQUEST['understandTermination']) {
            alert("Please check 'I understand doing so may cause be to lose my right to use this software'<br/>\n");
        }
        if (!$_REQUEST['agreeToLicense']) {
            alert("Please check 'I accept the terms of the License Agreement'<br/>\n");
        }
        if (!$_REQUEST['mysqlHostname']) {
            alert("Please enter your 'MySQL Hostname'<br/>\n");
        }
        if (!$_REQUEST['mysqlDatabase']) {
            alert("Please enter your 'MySQL Database'<br/>\n");
        }
        if (!$_REQUEST['mysqlUsername']) {
            alert("Please enter your 'MySQL Username'<br/>\n");
        }
        if (!$_REQUEST['mysqlTablePrefix']) {
            alert("Please enter your 'MySQL Table Prefix'<br/>\n");
        } elseif (preg_match("/[A-Z]/", $_REQUEST['mysqlTablePrefix'])) {
            alert("Value for 'MySQL Table Prefix' must be lowercase.<br/>\n");
        } elseif (!preg_match("/^[a-z]/i", $_REQUEST['mysqlTablePrefix'])) {
            alert("Value for 'MySQL Table Prefix' must start with a letter.<br/>\n");
        } elseif (!preg_match("/_\$/", $_REQUEST['mysqlTablePrefix'])) {
            alert("Value for 'MySQL Table Prefix' must end in underscore.<br/>\n");
        }
        // New Installation
        if (!@$_REQUEST['restoreFromBackup']) {
            if (!$_REQUEST['adminFullname']) {
                alert("Please enter 'Admin Full Name'<br/>\n");
            }
            if (!$_REQUEST['adminEmail']) {
                alert("Please enter 'Admin Email'<br/>\n");
            } elseif (!isValidEmail($_REQUEST['adminEmail'])) {
                alert("Please enter a valid email for 'Admin Email' (Example: user@example.com)<br/>\n");
            }
            if (!$_REQUEST['adminUsername']) {
                alert("Please enter 'Admin Username'<br/>\n");
            }
            $passwordErrors = getNewPasswordErrors($_REQUEST['adminPassword1'], $_REQUEST['adminPassword2'], $_REQUEST['adminUsername']);
            // v2.52
            if ($passwordErrors) {
                alert(nl2br(htmlencode($passwordErrors)));
            }
        }
        // Restore from Backup
        if (@$_REQUEST['restoreFromBackup']) {
            if (!$_REQUEST['restore']) {
                alert("Please select a backup file to restore<br/>\n");
            }
        }
        // Advanced - v2.53
        if (!@$_REQUEST['useCustomSettingsFile']) {
            if (is_file(SETTINGS_DEV_FILEPATH)) {
                alert(t("You must select 'Use Custom Settings File' since a custom settings file for this domain already exists!") . "<br/>\n");
            } elseif (isDevServer()) {
                alert("This is a development server, you must select 'Use Custom Settings File'." . "<br/>\n");
            }
        }
        if (@$_REQUEST['webPrefixUrl'] != '') {
            if (!preg_match("|^(\\w+:/)?/|", $_REQUEST['webPrefixUrl'])) {
                alert(t("Website Prefix URL must start with /") . "<br/>\n");
            }
            if (preg_match("|/\$|", $_REQUEST['webPrefixUrl'])) {
                alert(t("Website Prefix URL cannot end with /") . "<br/>\n");
            }
        }
        // update settings (not saved unless there are no errors)
        $SETTINGS['cookiePrefix'] = substr(md5(mt_rand()), 0, 5) . '_';
        //v2.51 shortened prefix so it's easy to see full cookie names in browser cookie list
        $SETTINGS['adminEmail'] = @$SETTINGS['adminEmail'] ? $SETTINGS['adminEmail'] : $_REQUEST['adminEmail'];
        $SETTINGS['licenseCompanyName'] = $_REQUEST['licenseCompanyName'];
        $SETTINGS['licenseDomainName'] = $_REQUEST['licenseDomainName'];
        $SETTINGS['licenseProductId'] = $_REQUEST['licenseProductId'];
        $SETTINGS['webRootDir'] = @$SETTINGS['webRootDir'] ? $SETTINGS['webRootDir'] : @$_SERVER['DOCUMENT_ROOT'];
        $SETTINGS['mysql']['hostname'] = $_REQUEST['mysqlHostname'];
        $SETTINGS['mysql']['database'] = $_REQUEST['mysqlDatabase'];
        $SETTINGS['mysql']['username'] = $_REQUEST['mysqlUsername'];
        $SETTINGS['mysql']['password'] = $_REQUEST['mysqlPassword'];
        $SETTINGS['mysql']['tablePrefix'] = $_REQUEST['mysqlTablePrefix'];
        $TABLE_PREFIX = $_REQUEST['mysqlTablePrefix'];
        // update TABLE_PREFIX global as well.
        $SETTINGS['webPrefixUrl'] = $_REQUEST['webPrefixUrl'];
        // display errors
        if (alert()) {
            require "lib/menus/install.php";
            exit;
        }
        // connect to mysql
        $errors = connectToMySQL('returnErrors');
        if ($errors) {
            alert($errors);
            require "lib/menus/install.php";
            exit;
        } else {
            connectToMySQL();
        }
        // create schema tables
        createMissingSchemaTablesAndFields();
        clearAlertsAndNotices();
        // don't show "created table/field" alerts
        // New Installation: check if admin user already exists
        if (!@$_REQUEST['restoreFromBackup']) {
            $passwordHash = getPasswordDigest($_REQUEST['adminPassword1']);
            $identicalUserExists = mysql_count('accounts', array('username' => $_REQUEST['adminUsername'], 'password' => $passwordHash, 'isAdmin' => '1'));
            if (!$identicalUserExists) {
                // if the don't exist, check if a user with the same username exists and show an error if they do
                $count = mysql_count('accounts', array('username' => $_REQUEST['adminUsername']));
                if (!$identicalUserExists && $count > 0) {
                    alert("Admin username already exists, please choose another.<br/>\n");
                }
            }
            // create admin user
            if (!$identicalUserExists && !alert()) {
                mysqlStrictMode(false);
                // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)
                mysql_query("INSERT INTO `{$TABLE_PREFIX}accounts` SET\n                          createdDate      = NOW(),\n                          createdByUserNum = '0',\n                          updatedDate      = NOW(),\n                          updatedByUserNum = '0',\n                          fullname         = '" . mysql_escape($_REQUEST['adminFullname']) . "', email    = '" . mysql_escape($_REQUEST['adminEmail']) . "',\n                          username         = '******'adminUsername']) . "', password = '******',\n                          disabled         = '0',\n                          isAdmin          = '1',\n                          expiresDate      = '0000-00-00 00:00:00',\n                          neverExpires     = '1'") or alert("MySQL Error Creating Admin User:<br/>\n" . htmlencode(mysql_error()) . "\n");
                // create accesslist entry
                mysql_query("INSERT INTO `{$TABLE_PREFIX}_accesslist` (userNum, tableName, accessLevel, maxRecords, randomSaveId)\n                          VALUES (LAST_INSERT_ID(), 'all', '9', NULL, '1234567890')") or alert("MySQL Error Creating Admin Access List:<br/>\n" . htmlencode(mysql_error()) . "\n");
            }
        }
        // Restore from Backup: Restore backup file
        if (@$_REQUEST['restoreFromBackup']) {
            $userCount = mysql_count('accounts');
            if ($userCount) {
                $userTable = $TABLE_PREFIX . 'accounts';
                $errorMessage = sprintf("Can't restore from backup because it would overwrite the %s existing user accounts in the specified database location.<br/>\n", $userCount);
                $errorMessage .= sprintf("Try changing the MySQL Database or Table Prefix to restore to a different location, or remove existing users from '%s'.<br/>\n", $userTable);
                alert($errorMessage);
            } else {
                // restore database
                $filename = @$_REQUEST['restore'];
                mysqlStrictMode(false);
                // disable Mysql strict errors
                restoreDatabase(DATA_DIR . '/backups/' . $filename);
                notice("Restored backup file /data/backups/{$filename}");
                makeAllUploadRecordsRelative();
            }
        }
        // save settings
        if (!alert()) {
            saveSettings(@$_REQUEST['useCustomSettingsFile']);
            isInstalled(true);
            // save installed status
            redirectBrowserToURL('?menu=home', true);
            // refresh page
            exitl;
        }
    }
    // set defaults
    if (!array_key_exists('licenseDomainName', $_REQUEST)) {
        $_REQUEST['licenseDomainName'] = $_SERVER['HTTP_HOST'];
    }
    if (!array_key_exists('mysqlHostname', $_REQUEST)) {
        $_REQUEST['mysqlHostname'] = $SETTINGS['mysql']['hostname'];
    }
    if (!array_key_exists('mysqlDatabase', $_REQUEST)) {
        $_REQUEST['mysqlDatabase'] = $SETTINGS['mysql']['database'];
    }
    if (!array_key_exists('mysqlUsername', $_REQUEST)) {
        $_REQUEST['mysqlUsername'] = $SETTINGS['mysql']['username'];
    }
    if (!array_key_exists('mysqlTablePrefix', $_REQUEST)) {
        $_REQUEST['mysqlTablePrefix'] = $SETTINGS['mysql']['tablePrefix'];
    }
    // show form
    require "lib/menus/install.php";
    exit;
}
        <div style="padding-left: 25px">
          <input class="text-input wide-input" type="text" name="restrictByIP_allowed" value="<?php 
echo htmlencode(@$SETTINGS['advanced']['restrictByIP_allowed']);
?>
" size="30" />
        </div>
      </td>
    </tr>



    <tr><td colspan="2">&nbsp;</td></tr>

    <?php 
$tips = array();
$errorLogCount = mysql_count('_error_log');
if (!isHTTPS()) {
    $tips[] = t("Use a secure https:// url to access this program.  You are currently using an insecure connection.");
}
if (!$SETTINGS['advanced']['requireHTTPS']) {
    $tips[] = t("Enable 'Require HTTPS' above to disallow insecure connections.");
}
if (ini_get('display_errors')) {
    $tips[] = t("Hide PHP Errors (for production and live web servers).");
}
if (!$SETTINGS['advanced']['phpEmailErrors']) {
    $tips[] = t("Enable 'Email PHP Errors' to be notified of PHP errors on website.");
}
if (ini_get('expose_php')) {
    $tips[] = t(sprintf("%s is currently enabled, disable it in php.ini.", '<a href="http://www.php.net/manual/en/ini.core.php#ini.expose-php">expose_php</a>'));
}
function recreateThumbnails()
{
    global $TABLE_PREFIX;
    $tableNameWithoutPrefix = getTablenameWithoutPrefix($_REQUEST['tablename']);
    // error checking
    $stopPrefix = "STOPJS:";
    // this tells javascript to stop creating thumbnails
    $requiredFields = array('tablename', 'fieldname', 'maxHeight', 'maxWidth');
    foreach ($requiredFields as $fieldname) {
        if (!@$_REQUEST[$fieldname]) {
            die($stopPrefix . "Required fieldname '{$fieldname}' not specified!");
        }
    }
    if (preg_match('/[^0-9\\_]/i', $_REQUEST['maxHeight'])) {
        die($stopPrefix . "Invalid value for max height!\n");
    }
    if (preg_match('/[^0-9\\_]/i', $_REQUEST['maxWidth'])) {
        die($stopPrefix . "Invalid value for max width!\n");
    }
    // get upload count
    static $count;
    if ($count == '') {
        $where = mysql_escapef("tableName = ? AND fieldName = ?", $tableNameWithoutPrefix, $_REQUEST['fieldname']);
        $totalUploads = mysql_count('uploads', $where);
    }
    // load upload
    $whereEtc = mysql_escapef("tableName = ? AND fieldname = ?", $tableNameWithoutPrefix, $_REQUEST['fieldname']);
    $whereEtc .= " LIMIT 1 OFFSET " . intval($_REQUEST['offset']);
    @(list($upload) = mysql_select('uploads', $whereEtc));
    //
    if ($upload) {
        // get uploadDir and uploadUrl
        $schema = loadSchema($upload['tableName']);
        list($uploadDir, $uploadUrl) = getUploadDirAndUrl($schema[$upload['fieldName']]);
        // get upload's absolute filepath
        $absoluteFilepath = addUploadPathPrefix($upload['filePath'], $uploadDir);
        // make path absolute
        // error checking
        if (!file_exists($absoluteFilepath)) {
            $error = "Upload doesn't exist '{$absoluteFilepath}'!<br/>\n";
            $error .= "Found in: {$upload['tableName']}, {$upload['fieldName']}, record {$upload['recordNum']}.";
            die($error);
        }
        ### resize image
        $isImage = preg_match("/\\.(gif|jpg|jpeg|png)\$/i", $absoluteFilepath);
        if ($isImage) {
            $thumbNum = $_REQUEST['thumbNum'];
            $thumbSavePath = preg_replace("|([^/]+)\$|", "thumb{$thumbNum}/\$1", $absoluteFilepath);
            $thumbUrlPath = preg_replace("|([^/]+)\$|", "thumb{$thumbNum}/\$1", $upload['urlPath']);
            // erase old thumbnail
            if (file_exists($thumbSavePath)) {
                @unlink($thumbSavePath) || die("Can't erase old thumbnail '{$thumbSavePath}': {$php_errormsg}");
            }
            // create new thumbnail
            list($thumbWidth, $thumbHeight) = saveResampledImageAs($thumbSavePath, $absoluteFilepath, $_REQUEST['maxWidth'], $_REQUEST['maxHeight']);
            doAction('upload_thumbnail_save', array($tableNameWithoutPrefix, $_REQUEST['fieldname'], $thumbNum, $thumbSavePath));
            // update upload database
            $query = "UPDATE `{$TABLE_PREFIX}uploads`\n";
            $query .= "   SET `thumbFilepath{$thumbNum}` = '" . mysql_escape(removeUploadPathPrefix($thumbSavePath, $uploadDir)) . "',\n";
            $query .= "       `thumbUrlPath{$thumbNum}`  = '" . mysql_escape(removeUploadPathPrefix($thumbUrlPath, $uploadUrl)) . "',\n";
            $query .= "       `thumbWidth{$thumbNum}`    = '" . mysql_escape($thumbWidth) . "',\n";
            $query .= "       `thumbHeight{$thumbNum}`   = '" . mysql_escape($thumbHeight) . "'\n";
            $query .= " WHERE num = '" . mysql_escape($upload['num']) . "'";
            mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n");
        }
    }
    // print status message
    $offset = $_REQUEST['offset'] + 1;
    if ($offset <= $totalUploads) {
        print "{$offset}/{$totalUploads}";
    } else {
        print "done";
    }
    exit;
}