<?php

# PLUGIN PREVIEW BY TEXTPATTERN.INFO


/*
    adi_prefs - Preference Sets

    Written by Adi Gilbert

    Released under the GNU General Public License

    Version history:
    0.3.2    - minor layout fixes
            - TXP 4.5+ only
            - tested in 4.6
    0.3.1    - fixed issue when upgrading from version 0.1
            - fixed Textpack download
    0.3        - TXP 4.5-ified
            - moved install/uninstall to plugin options
            - Textpack added
            - tooltips thrown in the tip
            - code tidy up
            - now uses lifecycle events
    0.2.1    - fixed: injudicious use of global variables, causing conflict with adi_matrix
    0.2        - enhancement: added new set "Testing" (for Maniqui)
            - enhancement: preference set visibility
    0.1        - initial release

*/

if (@txpinterface == 'admin') {
    global 
$adi_prefs_debug;

    
$adi_prefs_debug 0// display admin debug info

    // to infinity & beyond ...
    
if (!version_compare(txp_version,'4.5.0','>=')) return;

    
adi_prefs_init();

}

function 
adi_prefs_init() {
// initial setup
    
global $event,$prefs,$adi_prefs_debug,$adi_prefs_gtxt,$adi_prefs_default_set_list,$adi_prefs_current_prefs,$adi_prefs_plugin_status,$adi_prefs_default_list,$adi_prefs_list,$adi_prefs_url;

    
$adi_prefs_privs '1,6';

    
// default pref set titles
    
$adi_prefs_default_set_list = array(
        
'current' => array('title' => 'Current'),
        
'def' => array('title' => 'Default'),
        
'dev' => array('title' => 'Local'),
        
'demo' => array('title' => 'Staging'),
        
'test' => array('title' => 'Testing'),
        
'live' => array('title' => 'Live'),
    );

    
// default list of prefs
    
$adi_prefs_default_list 'siteurl,production_status,file_base_path,tempdir,rss_dbbk_path,rss_dbbk_mysql,rss_dbbk_dump,xxx';

# --- BEGIN PLUGIN TEXTPACK ---
    
$adi_prefs_gtxt = array(
        
'adi_install_fail' => 'Unable to install',
        
'adi_installed' => 'Installed',
        
'adi_not_installed' => 'Not installed',
        
'adi_prefs' => 'Preference Sets',
        
'adi_prefs_add' => 'Add Preference',
        
'adi_prefs_no_set_match' => 'No sets match the current preferences',
        
'adi_prefs_multiple_set_match' => 'The <b>{set}</b> sets match the current preferences',
        
'adi_prefs_one_set_match' => 'The <b>{set}</b> set matches the current preferences',
        
'adi_prefs_pref_add_fail' => 'Unable to add {pref} preference',
        
'adi_prefs_pref_added' => '{pref} preference added',
        
'adi_prefs_pref_not_selected' => 'No new preference selected',
        
'adi_prefs_pref_remove_fail' => 'Unable to remove {pref} preference',
        
'adi_prefs_pref_removed' => '{pref} preference removed',
        
'adi_prefs_remove_pref' => 'Remove preference?',
        
'adi_prefs_remove_pref_query' => 'Remove {pref} from preference sets?',
        
'adi_prefs_set_applied' => '{set} preference set applied',
        
'adi_prefs_set_apply_fail' => 'Unable to apply {set} preference set',
        
'adi_prefs_set_not_selected' => 'No preference set selected',
        
'adi_prefs_set_titles_updated' => 'Preference set titles updated',
        
'adi_prefs_set_titles_update_fail' => 'Unable to update preference set titles',
        
'adi_prefs_set_visibility_updated' => 'Preference set visibility updated',
        
'adi_prefs_set_visibility_update_fail' => 'Unable to update preference set visibility',
        
'adi_prefs_sets_update_fail' => 'Unable to update preference sets',
        
'adi_prefs_sets_updated' => 'Preference sets updated',
        
'adi_prefs_titles' => 'Preference Set Titles',
        
'adi_prefs_upgraded' => 'adi_prefs upgraded successfully',
        
'adi_prefs_upgrade_fail' => 'Unable to upgrade adi_prefs',
        
'adi_textpack_fail' => 'Textpack installation failed',
        
'adi_textpack_feedback' => 'Textpack feedback',
        
'adi_textpack_online' => 'Textpack also available online',
        
'adi_uninstall' => 'Uninstall',
        
'adi_uninstall_fail' => 'Unable to uninstall',
        
'adi_uninstalled' => 'Uninstalled',
        
'adi_update_prefs' => 'Update preferences',
        
'adi_upgrade_fail' => 'Unable to upgrade',
        
'adi_upgrade_required' => 'Upgrade required',
        
'adi_upgraded' => 'Upgraded',
        
'adi_visibility' => 'Visibility',
        );
# --- END PLUGIN TEXTPACK ---

    // Textpack
    
$adi_prefs_url = array(
        
'textpack' => 'http://www.greatoceanmedia.com.au/files/adi_textpack.txt',
        
'textpack_download' => 'http://www.greatoceanmedia.com.au/textpack/download',
        
'textpack_feedback' => 'http://www.greatoceanmedia.com.au/textpack/?plugin=adi_prefs',
    );
    if (
strpos($prefs['plugin_cache_dir'],'adi') !== FALSE// use Adi's local version
        
$adi_prefs_url['textpack'] = $prefs['plugin_cache_dir'].'/adi_textpack.txt';

    
// plugin lifecycle
    
register_callback('adi_prefs_lifecycle','plugin_lifecycle.adi_prefs');

    
// set the privilege levels
    
add_privs('adi_prefs_admin',$adi_prefs_privs);

    
// add new tab under 'Admin'
    
register_tab('admin','adi_prefs_admin',adi_prefs_gtxt('adi_prefs'));
    
register_callback('adi_prefs_admin','adi_prefs_admin');    // adi_prefs admin tab

    // style
    
if ($event == 'adi_prefs_admin')
        
register_callback('adi_prefs_style','admin_side','head_end');    // style for admin

    // plugin options
    
$adi_prefs_plugin_status fetch('status','txp_plugin','name','adi_prefs',$adi_prefs_debug);
    if (
$adi_prefs_plugin_status) { // proper install - options under Plugins tab
        
add_privs('plugin_prefs.adi_prefs'); // defaults to priv '1' only
        
register_callback('adi_prefs_options','plugin_prefs.adi_prefs');
    }
    else { 
// txpdev - options under Extensions tab
        
add_privs('adi_prefs_options'); // defaults to priv '1' only
        
register_tab('extensions','adi_prefs_options','adi_prefs options');
        
register_callback('adi_prefs_options','adi_prefs_options');
    }

    
// get current active prefs
    
$adi_prefs_current_prefs get_prefs();

    
// get stored prefs
    
$adi_prefs_list = array();
    if (
adi_prefs_installed())
        
$adi_prefs_list adi_prefs_get_list();
}

function 
adi_prefs_admin($event$step) {
// adi_prefs admin tab

    
global $adi_prefs_default_list,$adi_prefs_exclude_list,$adi_prefs_list,$adi_prefs_debug,$adi_prefs_set_list,$adi_prefs_default_set_list,$h,$adi_prefs_current_prefs,$plugin_status;

    
// list of prefs to exclude
    
$adi_prefs_exclude_list "dbupdatetime,gmtoffset,lastmod,prefs_id,timeoffset,timezone_key,version";
    
$adi_prefs_exclude_list explode(',',$adi_prefs_exclude_list);

    
// replace set titles with user defined, if any
    
foreach ($adi_prefs_default_set_list as $set_name => $value) {
        
$this_set_pref doSlash('adi_prefs_title_'.$set_name);
        
$val safe_field('val''txp_prefs'"name='$this_set_pref'");
        if (empty(
$val)) // use default set title
            
$adi_prefs_set_list[$set_name]['title'] = $adi_prefs_default_set_list[$set_name]['title'];
        else 
// read set title from database
            
$adi_prefs_set_list[$set_name]['title'] = $val;
    }

    
$message '';
    
$installed adi_prefs_installed();

    if (
$installed) {
        
$upgrade_required adi_prefs_upgrade();
        if (
$upgrade_required)
            
$message = array(adi_prefs_gtxt('adi_upgrade_required'),E_WARNING);
        else {
            if (
$adi_prefs_debug) {
                echo 
'$adi_prefs_list'.n;
                
dmp($adi_prefs_list);
            }
        }
    }
    else
        
$message = array(adi_prefs_gtxt('adi_not_installed'),E_ERROR);


    
$something doSlash(doStripTags(gps('something')));

    if (
$adi_prefs_debug) echo '<p>Event='.$event.', Step='.$step.', Something='.$something.'</p>';

    
// stepping out
    
if ($step == 'update') {
        foreach (
$adi_prefs_list as $pref_name => $value) {
            
$this_pref doStripTags(ps($pref_name));
            
$result TRUE;
            foreach (
$adi_prefs_set_list as $set_name => $value)
                if ((
$set_name != 'def') && ($set_name != 'current')) { // ignore 'def' & 'current' because they're for display only
                    
if ($adi_prefs_debug)
                        echo 
'<p>'.$pref_name.'['.$set_name.'] = '.$this_pref[$set_name].'</p>';
                    
$result $result && adi_prefs_set($pref_name,$set_name,$this_pref[$set_name]);
                }
        }
        if (
$result)
            
$message adi_prefs_gtxt('adi_prefs_sets_updated');
        else
            
$message = array(adi_prefs_gtxt('adi_prefs_sets_update_fail'),E_ERROR);
    }
    else if (
$step == 'apply') {
        if (
$something) { // i.e. set name
            
$result TRUE;
            foreach (
$adi_prefs_list as $pref_name => $value// apply "set" to the TXP database
                
$result $result && safe_update('txp_prefs',"val = '".doSlash(adi_prefs_get($pref_name,$something))."'","name = '".doSlash($pref_name)."'");
            if (
$result)
                
$message adi_prefs_gtxt('adi_prefs_set_applied',array('{set}'=>$adi_prefs_set_list[$something]['title']));
            else
                
$message = array(adi_prefs_gtxt('adi_prefs_set_apply_fail',array('{set}'=>$adi_prefs_set_list[$something]['title'])),E_ERROR);
        }
        else
            
$message = array(adi_prefs_gtxt('adi_prefs_set_not_selected'),E_WARNING);
    }
    else if (
$step == 'add') {
        if (
$something) { // $something = new pref from list
            
if ($something == '!none!')
                
$message = array(adi_prefs_gtxt('adi_prefs_pref_not_selected'),E_WARNING);
            else {
                
$result FALSE;
                if (
array_key_exists($something,$adi_prefs_current_prefs)) { // can't add what doesn't exist!
                    
$result TRUE;
                    
$current_value doSlash($adi_prefs_current_prefs[$something]);
                    foreach (
$adi_prefs_default_set_list as $set_name => $set_title) { // all set to current value
                        
$set_name doSlash($set_name);
                        if (
$set_name != 'current'$result $result && safe_upsert('adi_prefs',"$set_name='".$current_value."'","name='$something'",$adi_prefs_debug);
                    }
                }
                if (
$result)
                    
$message adi_prefs_gtxt('adi_prefs_pref_added',array('{pref}'=>$something));
                else
                    
$message = array(adi_prefs_gtxt('adi_prefs_pref_add_fail',array('{pref}'=>$something)),E_ERROR);
            }
        }
    }
    else if (
$step == 'remove') {
        if (
$something) { // $something = the pref to remove
            
$result safe_delete('adi_prefs',"name='$something'",$adi_prefs_debug); // remove pref from database
            
if ($result)
                
$message adi_prefs_gtxt('adi_prefs_pref_removed',array('{pref}'=>$something));
            else
                
$message = array(adi_prefs_gtxt('adi_prefs_pref_remove_fail',array('{pref}'=>$something)),E_ERROR);
        }
    }
    else if (
$step == 'change_title') {
        if (
$something) {
            
$result TRUE;
            foreach (
$something as $set_name => $value) {
                if (empty(
$value)) $value $adi_prefs_default_set_list[$set_name]['title']; // revert to default title if blank
                
$adi_prefs_set_list[$set_name]['title'] = $value// update sets array
                
$this_set_pref 'adi_prefs_title_'.$set_name;
                
set_pref($this_set_pref,$value,'adi_prefs_admin',2); // set's title pref
            
}
            if (
$result)
                
$message adi_prefs_gtxt('adi_prefs_set_titles_updated');
            else
                
$message = array(adi_prefs_gtxt('adi_prefs_set_titles_update_fail'),E_ERROR);
        }
    }
    else if (
$step == 'visibility') {
        
$visibility 'current,def'// always visible
        
$result TRUE;
        if (
$something) {
            foreach (
$something as $set_name => $value)
                if (
$value$visibility .= ','.$set_name;
        }
        
$result set_pref('adi_prefs_visibility',$visibility,'adi_prefs_admin',2); // visibility preference
        
if ($result)
            
$message adi_prefs_gtxt('adi_prefs_set_visibility_updated');
        else
            
$message = array(adi_prefs_gtxt('adi_prefs_set_visibility_update_fail'),E_ERROR);
    }

    if ((
$step == 'add') || ($step == 'remove') || ($step == 'update'))
        
safe_repair('adi_prefs'); // free up deleted space, so that new prefs go at end of list

    
pagetop(adi_prefs_gtxt('adi_prefs'),$message);

    if (
$installed && !$upgrade_required) {

        echo 
'<div class="adi_prefs">';

        
// read visibility from preference & store in general set array
        
$visibility safe_field('val''txp_prefs'"name='adi_prefs_visibility'");
        foreach (
$adi_prefs_set_list as $set_name => $value) {
            
$pos strpos($visibility$set_name);
            
$adi_prefs_set_list[$set_name]['visible'] = !($pos === false);
        }

        
// get stored prefs
        
$adi_prefs_list adi_prefs_get_list();

        
// get current active prefs
        
$adi_prefs_current_prefs get_prefs();

        
// find & display matching sets
        
$matches adi_prefs_set_match();
        foreach (
$adi_prefs_set_list as $set_name => $value// remove invisible sets from list
            
if (!$value['visible']) {
                
$key array_search($set_name$matches);
                if (!(
$key === FALSE))
                    unset(
$matches[$key]);
            }
        if (
count($matches) == 0// no match
            
echo graf(strong(adi_prefs_gtxt('adi_prefs_no_set_match').'.'),' class="adi_prefs_message"');
        else if (
count($matches) == 1// one match
            
echo graf(adi_prefs_gtxt('adi_prefs_one_set_match',array('{set}'=>$adi_prefs_set_list[$matches[0]]['title'])).'.',' class="adi_prefs_message"');
        else { 
// multiple matches
            
end($matches);
            
$last_index key($matches);
            
$match_list '';
            foreach (
$matches as $index => $set_name) {
                (
$index == $last_index) ? $glue ' &amp; ' $glue ', ';
                
$index $match_list .= $glue.$adi_prefs_set_list[$set_name]['title'] : $match_list .= $adi_prefs_set_list[$set_name]['title'];
            }
            echo 
graf(adi_prefs_gtxt('adi_prefs_multiple_set_match',array('{set}'=>$match_list)).'.',' class="adi_prefs_message"');
        }

        
// apply radio buttons
        
$set_radios '';
        foreach (
$adi_prefs_set_list as $set_name => $value)
            if (
$set_name != 'current') { // don't need to apply current!
                
if ($adi_prefs_set_list[$set_name]['visible'])
                    
$set_radios .=
                        
tag(
                            
$value['title']
                            .
sp
                            
.fInput("radio""something"$set_name"edit""""""20""1")
                            ,
'label'
                        
);
            }
        echo 
form(
            
$set_radios
            
.fInput("submit""do_something""Apply set""publish","",'return verify(\''.gTxt('are_you_sure').'\')')
            .
eInput("adi_prefs_admin").sInput("apply")
            ,
'','','post','adi_prefs_apply_set'
        
);

        
// preference table
        
$set_headings '';
        foreach (
$adi_prefs_set_list as $set_name => $value) {
            if (
$adi_prefs_set_list[$set_name]['visible'])
                
$class '';
            else
                
$class ' class="adi_prefs_invisible"';
            
$set_headings .= hcell($value['title'],'',$class);
        }
        echo 
form(
            
tag(adi_prefs_gtxt('adi_prefs'),'h2')
            .
startTable('list','','adi_prefs_table txp-list')
            .
tag(
                
tr(
                    
hcell(sp// filler for pref column
                    
.$set_headings
                    
.hcell(sp// filler for delete button column
                
)
                ,
'thead'
            
)
            .
tag(
                
adi_prefs_display_prefs()
                ,
'tbody'
            
)
            .
endTable()
            .
graf(
                
fInput("submit""update"'Update sets'"smallerbox")
                .
eInput("adi_prefs_admin")
                .
sInput("update")
            )
            ,
'','','post','adi_prefs_form'
        
);

        
// adi_prefs preferences
        
echo tag(
            
adi_prefs_prefs()
            ,
'div'
            
,' class="adi_prefs_prefs"'
        
);
    }

    echo 
'</div>';

    if (
$adi_prefs_debug) {
        echo 
'SET LIST:'.br;
        
dmp($adi_prefs_set_list);
        echo 
'PREFERENCE LIST:'.br;
        foreach (
$adi_prefs_list as $pref_name => $value)
            echo 
$pref_name.' - '.$value['title'].' - '.$value['html'].br;
        echo 
'STORED PREFERENCES:'.br;
        foreach (
$adi_prefs_list as $pref_name => $value)
            foreach (
$adi_prefs_set_list as $set_name => $value)
            if (
$set_name != 'current')
                echo 
$pref_name.' ('.$set_name.') = '.adi_prefs_get($pref_name,$set_name).br;
        echo 
'CURRENT PREFERENCES:'.br;
        foreach (
$adi_prefs_list as $name => $value)
            echo 
$name.' = '.$adi_prefs_current_prefs[$name].br;
    }
}

function 
adi_prefs_prefs() {
// preference set preferences
    
global $adi_prefs_set_list;

    
$out '';

    
// add new preference
    
$out .= form(
        
tag(adi_prefs_gtxt('adi_prefs_add'),"h2")
        .
adi_prefs_select_pref()
        .
sp
        
.fInput("submit""do_something",gTxt('add'),"smallerbox")
        .
eInput("adi_prefs_admin")
        .
sInput("add")
        ,
'','','post','adi_prefs_form'
    
);

    
// user-editable set titles
    
$out .= tag(adi_prefs_gtxt('adi_prefs_titles'),'h2');
    
$set_titles '';
    foreach (
$adi_prefs_set_list as $set_name => $value) {
        if (
$adi_prefs_set_list[$set_name]['visible'])
            
$set_titles .= fInput("text","something[$set_name]",$value['title'],'','','',25);
    }
    
$out .= form(
                
$set_titles
                
.graf(
                    
fInput("submit""do_something""Update titles""smallerbox")
                    .
eInput("adi_prefs_admin")
                    .
sInput("change_title")
                )
                ,
'','','post','adi_prefs_titles'
            
);

    
// preference set visibility
    
$out .= tag(adi_prefs_gtxt('adi_visibility'),'h2');
    
$visibility safe_field('val','txp_prefs',"name='adi_prefs_visibility'"); // read actual preference again, just in case
    
$set_checkboxes '';
    foreach (
$adi_prefs_set_list as $set_name => $value)
        if ((
$set_name != 'current') && ($set_name != 'def')) { // you can't hide these ones
            
$pos strpos($visibility$set_name);
            
$checked = !($pos === false);
            
$set_checkboxes .=
                
tag(
                    
$value['title']
                    .
sp
                    
.checkbox("something[$set_name]"TRUE$checked)
                    ,
'label'
                
);
        }
    
$out .= form(
        
$set_checkboxes
        
.graf(
            
fInput("submit""do_something""Update visibility""smallerbox")
            .
eInput("adi_prefs_admin")
            .
sInput("visibility")
        )
        ,
'','','post','adi_prefs_visibility'
    
);

    return 
$out;
}

function 
adi_prefs_options($event,$step) {
// adi_prefs options page
    
global $adi_prefs_debug,$adi_prefs_url,$adi_prefs_plugin_status,$adi_prefs_default_set_list,$adi_prefs_current_prefs,$adi_prefs_list;

    
$message '';

    
$installed adi_prefs_installed();
    if (
$installed) {
        
// get stored prefs
        
$adi_prefs_list adi_prefs_get_list();
        
// get current active prefs
        
$adi_prefs_current_prefs get_prefs();
        
// check for upgrade
        
if (adi_prefs_upgrade())
            
$step 'upgrade';
    }

    
// dance steps
    
if ($step == 'textpack') {
        
$adi_textpack file_get_contents($adi_prefs_url['textpack']);
        if (
$adi_textpack) {
            
$result install_textpack($adi_textpack);
            
$message gTxt('textpack_strings_installed', array('{count}' => $result));
            
$textarray load_lang(LANG); // load in new strings
        
}
        else
            
$message = array(adi_prefs_gtxt('adi_textpack_fail'),E_ERROR);
    }
    else if (
$step == 'upgrade') {
        
$result adi_prefs_upgrade(TRUE);
        
$result $message adi_prefs_gtxt('adi_upgraded') : $message = array(adi_prefs_gtxt('adi_upgrade_fail'),E_ERROR);
    }
    else if (
$step == 'install') {
        
$result adi_prefs_install();
        
$result $message adi_prefs_gtxt('adi_installed') : $message = array(adi_prefs_gtxt('adi_install_fail'),E_ERROR);
    }
    else if (
$step == 'uninstall') {
        
$result adi_prefs_uninstall();
        
$result $message adi_prefs_gtxt('adi_uninstalled') : $message = array(adi_prefs_gtxt('adi_uninstall_fail'),E_ERROR);
    }

    
// generate page
    
pagetop('adi_prefs - '.gTxt('plugin_prefs'),$message);

    
$install_button =
        
form(
            
fInput("submit""adi_prefs_options_submit"gTxt('install'), "publish","",'return verify(\''.gTxt('are_you_sure').'\')')
            .
eInput($event).sInput("install")
        );
    
$uninstall_button =
        
form(
            
fInput("submit""do_something"adi_prefs_gtxt('adi_uninstall'), "publish","",'return verify(\''.gTxt('are_you_sure').'\')')
            .
eInput($event).sInput("uninstall")
        );

    if (
$adi_prefs_plugin_status// proper plugin install, so lifecycle takes care of install/uninstall
        
$install_button $uninstall_button '';

    
$installed adi_prefs_installed();

    
// options
    
echo tag(
        
tag('adi_prefs '.gTxt('plugin_prefs'),'h2')
        .( 
$installed ?
            
// textpack links
            
graf(href(gTxt('install_textpack'),'?event='.$event.'&amp;step=textpack'))
            .
graf(href(adi_prefs_gtxt('adi_textpack_online'),$adi_prefs_url['textpack_download']))
            .
graf(href(adi_prefs_gtxt('adi_textpack_feedback'),$adi_prefs_url['textpack_feedback']))
            .
$uninstall_button
            
$install_button
        
)
        ,
'div'
        
,' style="text-align:center"'
    
);

    if (
$adi_prefs_debug) {
        
dmp($adi_prefs_default_set_list);
        
dmp($adi_prefs_current_prefs);
    }

}

function 
adi_prefs_installed($table='adi_prefs') {
// test if supplied table is present
    
$rs safe_query("SHOW TABLES LIKE '".safe_pfx($table)."'");
    
$a nextRow($rs);
    if (
$a)
        return 
TRUE;
    else
        return 
FALSE;
}

function 
adi_prefs_install() {
// create adi_prefs database table
    
global $adi_prefs_default_list,$adi_prefs_default_set_list,$adi_prefs_current_prefs,$adi_prefs_debug;

    if (
adi_prefs_installed())
        return 
TRUE;
    else {
        
// create list of "set" columns
        
$set_cols '';
        foreach (
$adi_prefs_default_set_list as $set_name => $set_title) {
            
$set_name doSlash($set_name);
            if (
$set_name != 'current'$set_cols .= ', '."`$set_name` varchar(255) NOT NULL default ''";
        }
        
// create database table
        
$res safe_query(
            
"CREATE TABLE IF NOT EXISTS ".safe_pfx('adi_prefs')." (
            `name` varchar(255) NOT NULL"
            
.$set_cols
            
.");"
            
,$adi_prefs_debug);
        
// add default list of prefs & initialise with current values
        
$pref_list explode(',',$adi_prefs_default_list);
        foreach (
$pref_list as $index => $pref_name) {
            if (
array_key_exists($pref_name,$adi_prefs_current_prefs)) { // check that default pref actually exists
                
$current_value doSlash($adi_prefs_current_prefs[$pref_name]);
                
$pref_name doSlash($pref_name);
                foreach (
$adi_prefs_default_set_list as $set_name => $set_title) {
                    
$set_name doSlash($set_name);
                    if (
$set_name != 'current'$res $res && safe_upsert('adi_prefs',"$set_name='".$current_value."'","name='$pref_name'",$adi_prefs_debug);
                }
            }
        }
        
// set titles in preferences
        
foreach ($adi_prefs_default_set_list as $set_name => $set)
            
$res $res && set_pref('adi_prefs_title_'.$set_name,$set['title'],'adi_prefs_admin',2);
        
$res $res && set_pref('adi_prefs_visibility',implode(',',array_keys($adi_prefs_default_set_list)),'adi_prefs_admin',2);
         return 
$res;
    }
}

function 
adi_prefs_upgrade($do_upgrade=FALSE) {
// check to see if upgrade required
    
global $adi_prefs_default_set_list,$adi_prefs_list,$adi_prefs_current_prefs,$adi_prefs_debug;

    
// check if upgrade required
    
$rs safe_query('SELECT * FROM '.safe_pfx('adi_prefs'),$adi_prefs_debug);
    
$a nextRow($rs);
    
$upgrade_required = !array_key_exists('test'$a);

    if (
$do_upgrade && $upgrade_required) {
        
// version 0.2 - add 'test' set
        
$res safe_query("ALTER TABLE ".safe_pfx("adi_prefs")." ADD test VARCHAR(255) NOT NULL default '';");
        
// initialise prefs with current values
        
foreach ($adi_prefs_list as $pref_name => $value) {
            if (
array_key_exists($pref_name,$adi_prefs_current_prefs)) { // check that pref actually exists (possibly pointless here?)
                
$current_value doSlash($adi_prefs_current_prefs[$pref_name]);
                
$pref_name doSlash($pref_name);
                
$res $res && safe_upsert('adi_prefs',"test='".$current_value."'","name='$pref_name'",$adi_prefs_debug);
            }
        }
        
// set title preference
        
$res $res && set_pref('adi_prefs_title_test',$adi_prefs_default_set_list['test']['title'],'adi_prefs_admin',2);
        
$set_list $adi_prefs_default_set_list;
        unset(
$set_list['test']); // Testing set invisible by default
        
$res $res && set_pref('adi_prefs_visibility',implode(',',array_keys($set_list)),'adi_prefs_admin',2);
         return 
$res;
        }
    else
        return 
$upgrade_required;
}

function 
adi_prefs_uninstall() {
// drop adi_prefs table
    
global $adi_prefs_debug;

    
// delete table
    
$res safe_query("DROP TABLE ".safe_pfx('adi_prefs').";",$adi_prefs_debug);
    
// delete preferences
    
$res $res && safe_delete('txp_prefs',"name LIKE 'adi_prefs_%'",$adi_prefs_debug);
    return 
$res;
}

function 
adi_prefs_lifecycle($event,$step) {
// a matter of life & death
// $event:    "plugin_lifecycle.adi_plugin"
// $step:    "installed", "enabled", disabled", "deleted"
// TXP 4.5: reinstall/upgrade only triggers "installed" event (now have to manually detect whether upgrade required)
    
global $adi_prefs_debug;

    
$result '?';
    
// set upgrade flag if reinstalling in TXP 4.5+
    
$upgrade = (($step == "installed") && adi_prefs_installed());
    if (
$step == 'enabled')
        
$result $upgrade adi_prefs_install();
    else if (
$step == 'deleted')
        
$result adi_prefs_uninstall();
    if (
$upgrade)
        
$result $result && adi_prefs_upgrade(TRUE);
    if (
$adi_prefs_debug)
        echo 
"Event=$event Step=$step Result=$result Upgrade=$upgrade";
}

function 
adi_prefs_get_list() {
// create preferences array - indexed by pref name, containing pref title & input control
    
$pref_list = array();
    
$rs safe_query("SELECT name FROM ".safe_pfx('adi_prefs'));
    while (
$a nextRow($rs)) {
        
extract($a); // so $name contains pref name
        
$name doSlash($name);
        
$b safe_row("*",'txp_prefs',"name = '$name'"); // read pref from txp_prefs table
        
if (!empty($b)) { // create array 'pref_name' => array('html' => input control)
            
$pref_list[$name]['title'] = gTxt($b['name']);
            
$pref_list[$name]['html'] = $b['html'];
        }
    }
    return 
$pref_list;
}

function 
adi_prefs_display_prefs() {
// generate table rows in admin tab
    
global $adi_prefs_list,$h,$adi_prefs_set_list,$adi_prefs_current_prefs;

    
$out '';
    foreach (
$adi_prefs_list as $pref_name => $pref_value) {
        
$site_prefs ='';
        foreach (
$adi_prefs_set_list as $set_name => $value) {
            if (
$adi_prefs_set_list[$set_name]['visible'])
                
$class '';
            else
                
$class ' class="adi_prefs_invisible"';
            if (
$set_name == 'def')
                
$site_prefs .= tda(adi_prefs_display(adi_prefs_get($pref_name,$set_name),$pref_value['html']));
            else if (
$set_name == 'current')
                
$site_prefs .= tda(adi_prefs_display($adi_prefs_current_prefs[$pref_name],$pref_value['html']));
            else
                
$site_prefs .= tda(adi_prefs_input($pref_name."[$set_name]",adi_prefs_get($pref_name,$set_name),$pref_value['html']),$class);
        }
        
$out .= tr(
            
tda($adi_prefs_list[$pref_name]['title'],' class="adi_prefs_pref_name"')
            .
$site_prefs
            
.tda(adi_prefs_delete_button($pref_name))
        );
    }
    return 
$out;
}

function 
adi_prefs_set($name='',$set='',$new_value='') {
// set preference
    
global $adi_prefs_current_prefs,$adi_prefs_list,$adi_prefs_debug;

    
$set doSlash($set);
    
$new_value doSlash($new_value);
    
$name doSlash($name);
    
$res TRUE;
    if (
$name && $set) { // need pref name and set name
        
$res safe_update('adi_prefs',"$set = '$new_value'","name = '$name'",$adi_prefs_debug);
    }
    return 
$res;
}

function 
adi_prefs_get($name='',$set='') {
// read preference
    
$name doSlash($name);
    
$a safe_row($set,'adi_prefs',"name = '$name'"); // read preference from TXP database
    
if ($a)
        return 
$a[$set];
}

function 
adi_prefs_input($name,$value,$input_control) {
// display pref value in human form
    
if ($name == '')
        return 
'blank input name'// better display something!
    
else {
        
$func 'adi_prefs_'.$input_control// translate input control into function name - adi_prefs_prod_levels, adi_prefs_yesnoradio etc
        
if (is_callable($func))
            return 
call_user_func($func,$name,$value);
        else 
// no specific function for input control, so use text input
            
return finput("text",$name,$value,'','','',25);
    }
}

function 
adi_prefs_display($value,$input_control) {
// display pref value in human form
    
if ($value == '')
        return 
'&nbsp;'// don't want table cell collapsing!
    
else {
        
$func 'adi_prefs_'.$input_control// translate input control into function name - adi_prefs_prod_levels, adi_prefs_yesnoradio etc
        
if (is_callable($func))
            return 
call_user_func($func,'',$value);
        else 
// no specific function for input control, so just display value
            
return $value;
    }
}

function 
adi_prefs_style() {
// some style for the page
    
echo
        
'<style type="text/css">
            /* adi_prefs */
            .txp-body { max-width:none }
            .txp-list { margin:0 auto; width:auto }
            .adi_prefs { text-align:center }
            .adi_prefs h2 { margin-top:1em }
            .adi_prefs th, .adi_prefs td { padding:0.5em }
            .adi_prefs_invisible { display:none }
            .adi_prefs_pref_name { font-style:italic }
            .adi_prefs_prefs { margin-top:6em }
            .adi_prefs_prefs h2 { margin-top:1.5em }
            .adi_prefs_apply_set label, .adi_prefs_visibility label { margin-left:2em }
            .adi_prefs_apply_set label:first-child, .adi_prefs_visibility label:first-child { margin-left:0 }
            .adi_prefs_apply_set input.publish { margin-left:2em }
            .adi_prefs_titles input { margin-left:2em }
            .adi_prefs_titles input:first-child { margin-left:0 }
            .adi_prefs input.smallerbox { margin:0 }
        </style>'
;
}

function 
adi_prefs_select_pref() {
// create select list from txp_prefs - ignoring adi_prefs prefs, prefs in exclude list and prefs already in preference sets
    
global $adi_prefs_list,$adi_prefs_exclude_list;

    
$event doSlash(substr('adi_prefs_admin',0,12)); // event name truncated to 12 chars in database
    
$pref_select_list = array();
    
$pref_select_list['!none!'] = 'Select preference ...';
    
$rs safe_rows_start('*''txp_prefs'"event != '$event' and prefs_id = 1 order by name");
    while (
$a nextRow($rs)) {
        
extract($a);
        if (!
array_key_exists($name,$adi_prefs_list)) // don't show prefs already in $adi_prefs_list
            
if (array_search($name,$adi_prefs_exclude_list) === FALSE// check exclude list
                
$pref_select_list[$name] = strip_tags(gTxt($name)); // get rid of embedded HTML tags from titles
    
}
    return 
selectInput('something'$pref_select_list,'');
}

function 
adi_prefs_delete_button($pref) {
// X marks the delete spot
    
$step 'remove';
    
$url '?event='.'adi_prefs_admin'.a.'step='.$step.a.'something='.$pref;
    return
        
'<a href="'
        
.$url
        
.'" class="dlink" title="'.adi_prefs_gtxt('adi_prefs_remove_pref').'" onclick="return verify(\''
        
.adi_prefs_gtxt('adi_prefs_remove_pref_query',array('{pref}'=>$pref))
        .
'\')">&#215;</a>';
}

function 
adi_prefs_set_match() {
// create list of sets whose pref values match the current values
    
global $adi_prefs_current_prefs,$adi_prefs_list,$adi_prefs_set_list;

    
$matches = array();
    foreach (
$adi_prefs_set_list as $set_name => $value) {
        
$set_match TRUE;
        if (
$set_name != 'current') {
            foreach (
$adi_prefs_list as $pref_name => $value) {
                
$set_match $set_match && adi_prefs_get($pref_name,$set_name) == $adi_prefs_current_prefs[$pref_name];
            }
            if (
$set_match)
                
$matches[] = $set_name;
        }
    }
    return 
$matches;
}

function 
adi_prefs_gtxt($phrase,$atts=array()) {
// will check installed language strings before embedded English strings - to pick up Textpack
// - for TXP standard strings gTxt() & adi_prefs_gtxt() are functionally equivalent
    
global $adi_prefs_gtxt;

    if (
strpos(gTxt($phrase,$atts),$phrase) !== FALSE) { // no TXP translation found
        
if (array_key_exists($phrase,$adi_prefs_gtxt)) // adi translation found
            
return strtr($adi_prefs_gtxt[$phrase],$atts);
        else 
// last resort
            
return $phrase;
        }
    else 
// TXP translation
        
return gTxt($phrase,$atts);
}

/*
    Input control functions copied from standard TXP
    - renamed
    - modified
        - to just return value of <input> name is blank
        - removed <input> IDs
*/

function adi_prefs_prod_levels($name,$val) {
// based on prod_levels() from txp_prefs.php
    
$vals = array(
        
'debug'        => gTxt('production_debug'),
        
'testing' => gTxt('production_test'),
        
'live'        => gTxt('production_live'),
    );
    if (
$name// input name supplied
        
return selectInput($name$vals$val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_yesnoradio($field,$var) {
// based on yesnoradio() and radioSet() from txplib_forms()
    
$vals = array(
        
'0' => gTxt('no'),
        
'1' => gTxt('yes')
    );
    if (
$field) { // input name supplied
        
$out = array();
        foreach (
$vals as $a => $b) {
            
$out[] = '<input type="radio" name="'.$field.'" value="'.$a.'" class="radio"';
            
$out[] = ($a == $var) ? ' checked="checked"' '';
            
$out[] = ' /><label>'.$b.'</label> ';
        }
        return 
join(''$out);
    }
    else 
// display only
        
return $vals[$var];
}

function 
adi_prefs_commentmode($name,$val) {
// based on commentmode() from txp_prefs.php
    
$vals = array(
        
'0' => gTxt('nopopup'),
        
'1' => gTxt('popup')
    );
    if (
$name// input name supplied
        
return selectInput($name$vals$val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_weeks($name,$val) {
// based on weeks() from txp_prefs.php
    
$weeks gTxt('weeks');
    
$vals = array(
        
'0' => gTxt('never'),
        
7    => '1 '.gTxt('week'),
        
14    => '2 '.$weeks,
        
21    => '3 '.$weeks,
        
28    => '4 '.$weeks,
        
35    => '5 '.$weeks,
        
42    => '6 '.$weeks
    
);
    if (
$name// input name supplied
        
return selectInput($name$vals$val''''$name);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_logging($name,$val) {
// based on logging() from txp_prefs.php
    
$vals = array(
        
'all'    => gTxt('all_hits'),
        
'refer' => gTxt('referrers_only'),
        
'none'    => gTxt('none')
    );
    if (
$name// input name supplied
        
return selectInput($name$vals$val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_dateformats($name,$val) {
// based on dateformats() from txp_prefs.php
    
$dayname '%A';
    
$dayshort '%a';
    
$daynum is_numeric(@strftime('%e')) ? '%e' '%d';
    
$daynumlead '%d';
    
$daynumord is_numeric(substr(trim(@strftime('%Oe')), 01)) ? '%Oe' $daynum;
    
$monthname '%B';
    
$monthshort '%b';
    
$monthnum '%m';
    
$year '%Y';
    
$yearshort '%y';
    
$time24 '%H:%M';
    
$time12 = @strftime('%p') ? '%I:%M %p' $time24;
    
$date = @strftime('%x') ? '%x' '%Y-%m-%d';
    
$formats = array(
            
"$monthshort $daynumord$time12",
            
"$daynum.$monthnum.$yearshort",
            
"$daynumord $monthname$time12",
            
"$yearshort.$monthnum.$daynumlead$time12",
            
"$dayshort $monthshort $daynumord$time12",
            
"$dayname $monthname $daynumord$year",
            
"$monthshort $daynumord",
            
"$daynumord $monthname $yearshort",
            
"$daynumord $monthnum $year - $time24",
            
"$daynumord $monthname $year",
            
"$daynumord $monthname $year$time24",
            
"$daynumord$monthname $year",
            
"$daynumord$monthname $year$time24",
            
"$year-$monthnum-$daynumlead",
            
"$year-$daynumlead-$monthnum",
            
"$date $time12",
            
"$date",
            
"$time24",
            
"$time12",
            
"$year-$monthnum-$daynumlead $time24",
    );
    
$ts time();
    
$vals = array();
    foreach (
$formats as $f) {
        if (
$d safe_strftime($f$ts)) {
            
$vals[$f] = $d;
        }
    }
    
$vals['since'] = gTxt('hours_days_ago');
    if (
$name// input name supplied
        
return selectInput($namearray_unique($vals), $val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_commentsendmail($name,$val) {
// based on commentsendmail() from txp_prefs.php
    
$vals = array(
    
'1'    => gTxt('all'),
    
'0' => gTxt('none'),
    
'2'    => gTxt('ham')
    );
    if (
$name// input name supplied
        
return selectInput($name$vals$val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_permlinkmodes($name,$val) {
// based on permlinkmodes() from txp_prefs.php
    
$vals = array(
        
'messy' => gTxt('messy'),
        
'id_title' => gTxt('id_title'),
        
'section_id_title' => gTxt('section_id_title'),
        
'year_month_day_title' => gTxt('year_month_day_title'),
        
'section_title' => gTxt('section_title'),
        
'title_only' => gTxt('title_only'),
        
// 'category_subcategory' => gTxt('category_subcategory')
        
);
    if (
$name// input name supplied
        
return selectInput($name$vals$val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_gmtoffset_select($name,$val) {
// based on gmtoffset_select() from txp_prefs.php
    
$key safe_field('val''txp_prefs'"name='timezone_key'");
    
$tz = new timezone;
    
$ui $tz->selectInput('timezone_key'$keytrue'''gmtoffset');
    
$tzd $tz->details();
    if (
$name// input name supplied
        
return $ui;
    else 
// display only
        
return $tzd[$key]['offset']; // TO BE FIXED UP
}

function 
adi_prefs_themename($name,$val) {
// based on themename() from txp_prefs.php
    
$themes theme::names();
    foreach (
$themes as $t) {
        
$theme theme::factory($t);
        if (
$theme) {
            
$m $theme->manifest();
            
$title = empty($m['title']) ? ucwords($theme->name) : $m['title'];
            
$vals[$t] = $title;
            unset(
$theme);
        }
    }
    
asort($valsSORT_STRING);
    if (
$name)
        return 
selectInput($name$vals$val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_languages($name,$val) {
// based on languages() from txp_prefs.php
    
$installed_langs safe_column('lang''txp_lang'"1 = 1 group by lang");
    
$vals = array();
    foreach (
$installed_langs as $lang) {
        
$vals[$lang] = safe_field('data''txp_lang'"name = '".doSlash($lang)."' AND lang = '".doSlash($lang)."'");
        if (
trim($vals[$lang]) == '')
            
$vals[$lang] = $lang;
    }
    
asort($vals);
    
reset($vals);
    
$out n.'<select name="'.$name.'" class="list">';
    foreach (
$vals as $avalue => $alabel) {
        
$selected = ($avalue == $val || $alabel == $val) ?
        
' selected="selected"' :
        
'';
        
$out .= n.t.'<option value="'.htmlspecialchars($avalue).'"'.$selected.'>'.htmlspecialchars($alabel).'</option>'.n;
    }
    
$out .= n.'</select>';
    if (
$name// input name supplied
        
return $out;
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_pref_text($name,$val) {
// based on pref_text() from txplib_html.php
    
$vals = array(
        
USE_TEXTILE          => gTxt('use_textile'),
        
CONVERT_LINEBREAKS   => gTxt('convert_linebreaks'),
        
LEAVE_TEXT_UNTOUCHED => gTxt('leave_text_untouched')
    );
    if (
$name// input name supplied
        
return selectInput($name$vals$val);
    else 
// display only
        
return $vals[$val];
}

function 
adi_prefs_default_event($name,$val) {
// based on default_event() from txp_prefs.php
    
$vals areas();
    
$out = array();
    foreach (
$vals as $a => $b) {
        if (
count($b) > 0) {
            
$out[] = n.t.'<optgroup label="'.gTxt('tab_'.$a).'">';
            foreach (
$b as $c => $d) {
                
$out[] = n.t.t.'<option value="'.$d.'"'.( $val == $d ' selected="selected"' '' ).'>'.$c.'</option>';
                if (
$val == $d$this_event $c// note the event
            
}
            
$out[] = n.t.'</optgroup>';
        }
    }
    if (
$name// input name supplied
        
return n.'<select name="'.$name.'" class="list">'join(''$out). n.'</select>';
    else 
// display only
        
return $this_event;
}

function 
adi_prefs_is_dst($name,$val) {
// original does some sexy javascript - gloss over for now!
    
return adi_prefs_yesnoradio($name,$val);
}