/**
 * Returns the form database, if $forms is omitted.
 * Otherwise writes $forms as form database.
 *
 * @param array $forms A forms collection.
 *
 * @return mixed
 */
function Advancedform_db($forms = null)
{
    static $db;
    if (isset($forms)) {
        // write
        ksort($forms);
        $fn = Advancedform_dataFolder() . 'forms.dat';
        $contents = serialize($forms);
        if (!Advancedform_writeFile($fn, $contents)) {
            e('cntwriteto', 'file', $fn);
        }
        $db = $forms;
    } else {
        // read
        if (!isset($db)) {
            $fn = Advancedform_dataFolder() . 'forms.dat';
            $contents = Advancedform_readFile($fn);
            $db = $contents !== false ? unserialize($contents) : array();
            if (empty($db['%VERSION%'])) {
                $db['%VERSION%'] = 0;
            }
            if ($db['%VERSION%'] < ADVFRM_DB_VERSION) {
                $db = Advancedform_updatedDb($db);
                Advancedform_db($db);
            }
        }
        return $db;
    }
}
/**
 * Imports the form definition from a *.frm file. Returns the mail form
 * administration.
 *
 * @param string $id A form ID.
 *
 * @return string (X)HTML.
 *
 * @global array  The localization of the plugins.
 * @global string The (X)HTML fragment containing error messages.
 * @global object The CSRF protector.
 */
function Advancedform_importForm($id)
{
    global $plugin_tx, $e, $_XH_csrfProtection;
    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        return Advancedform_formsAdministration();
    }
    if (isset($_XH_csrfProtection)) {
        $_XH_csrfProtection->check();
    }
    $ptx = $plugin_tx['advancedform'];
    $forms = Advancedform_db();
    if (!isset($forms[$id])) {
        $fn = Advancedform_dataFolder() . $id . '.frm';
        if (($cnt = file_get_contents($fn)) !== false && ($form = unserialize($cnt)) !== false && isset($form['%VERSION%']) && count($form) == 2) {
            if ($form['%VERSION%'] < ADVFRM_DB_VERSION) {
                $form = Advancedform_updatedDb($form);
            }
            unset($form['%VERSION%']);
            foreach ($form as $f) {
                $f['name'] = $id;
                $forms[$id] = $f;
            }
            Advancedform_db($forms);
        } else {
            e('cntopen', 'file', $fn);
        }
    } else {
        $e .= '<li><b>' . $ptx['error_form_exists'] . '</b></li>';
    }
    return Advancedform_formsAdministration();
}