<?php

  /*

      preferences.php

      Preferences pages.

      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release
        2005-07-03 arne_sf: Replaced all instances of column name 'user' for table tbl_User_Preferences with 'userid'
      
      ## PAGE CONTAINS HANDYANDY MYSQL MODS ##
      ## Copyright (C) 2005 Andy Deakin (handyandy.org.uk) ##

      ----

      Copyright (C) 2003  Central Manchester CLC
      Copyright (C) 2003  David Thorne (davethorne@gmail.com)

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation version 2.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  */

  // Start session and populate it with data
  session_start();

  // Page Security
  require_once 'system/security.php';
  if ($_SESSION['_usertype'] == '' || $_SESSION['_restricted'] == '1') { ThrowOut(); }

  // Retrieve Get/Post variables
  $act = $_REQUEST['act'];
  $identifier = $_REQUEST['identifier'];
  $type = $_REQUEST['type'] ? $_REQUEST['type'] : 'user';

  // Specific page security and titles
  switch ($type) {
  case "default":
    // Only root can edit default preferences and system preferences
    if ($_SESSION['_usertype'] != 'Root') ThrowOut();
    $pTitle = 'Preference defaults';
    break;
  case "domain":
    // Only Domain Administrators and higher can edit domain-wide preferences
    if ($_SESSION['_usertype'] != 'Root' && $_SESSION['_usertype'] != 'Domain Administrator') ThrowOut();
    $ptitle = 'Domain Preferences'; 
    break;
  default:
    $ptitle = 'My Preferences';
  }

  // Includes
  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/user_preferences.php';
  require_once 'system/message.php';

  // Prepare available language names
  $somecounter=1;
  if ($langfile = fopen("./locale/locale.alias","r")) {
    while ($aline = fgets($langfile)) {
      if (!($aline[0] == '#')) {
        $avail_lang[$somecounter] = split('[[:blank:]]{1,}',$aline);
        // Remove trailing newline
        $avail_lang[$somecounter][1] = trim($avail_lang[$somecounter][1]);
        $somecounter++;
      }
    }
  }

  function getprefs($type) {
    // Gets preferences from each level
    // if preference already exists in a higher level
    // it will be overwritten by a lower level preference of the same name
    if ($type == 'default') {
      ## $prefs = db_recordset("SELECT *, 'default' AS level FROM vw_default_preferences");
      $prefs = db_recordset("SELECT *, 'default' AS level
                             FROM tbl_Default_Preferences, tbl_Preference_Descriptions
                             WHERE tbl_Default_Preferences.identifier = tbl_Preference_Descriptions.identifier");
    } elseif ($type == 'domain') {
      ## $defprefs = db_recordset("SELECT *, 'default' AS level FROM vw_default_preferences");
      ## $domprefs = db_recordset("SELECT *, 'domain' AS level FROM vw_domain_preferences WHERE domain={$_SESSION['_domain']}");
      $defprefs = db_recordset("SELECT *, 'default' AS level
                                FROM tbl_Default_Preferences, tbl_Preference_Descriptions
                                WHERE tbl_Default_Preferences.identifier = tbl_Preference_Descriptions.identifier");
      $domprefs = db_recordset("SELECT *, 'domain' AS level
                                FROM tbl_Domain_Preferences, tbl_Preference_Descriptions
                                WHERE domain={$_SESSION['_domain']}
                                  AND tbl_Domain_Preferences.identifier = tbl_Preference_Descriptions.identifier");
      $prefs = merge_recordsets('identifier', $defprefs, $domprefs);
    } elseif ($type == 'user') {
      ## $defprefs = db_recordset("SELECT *, 'default' AS level FROM vw_default_preferences WHERE overridable=1");
      ## $domprefs = db_recordset("SELECT *, 'domain' AS level FROM vw_domain_preferences WHERE domain={$_SESSION['_domain']} AND overridable=1");
      ## $userprefs = db_recordset("SELECT *, 'user' AS level FROM vw_user_preferences WHERE domain={$_SESSION['_domain']} AND \"user\"={$_SESSION['_id']}");
      $defprefs = db_recordset("SELECT *, 'default' AS level
                                FROM tbl_Default_Preferences, tbl_Preference_Descriptions
                                WHERE tbl_Default_Preferences.identifier = tbl_Preference_Descriptions.identifier
                                  AND tbl_Preference_Descriptions.overridable=1");
      $domprefs = db_recordset("SELECT *, 'domain' AS level
                                FROM tbl_Domain_Preferences, tbl_Preference_Descriptions
                                WHERE domain={$_SESSION['_domain']}
                                  AND tbl_Domain_Preferences.identifier = tbl_Preference_Descriptions.identifier
                                  AND overridable=1");
      $userprefs = db_recordset("SELECT *, 'user' AS level
                                 FROM tbl_User_Preferences, tbl_Preference_Descriptions
                                 WHERE domain={$_SESSION['_domain']}
                                   AND userid={$_SESSION['_id']}
                                   AND tbl_User_Preferences.identifier = tbl_Preference_Descriptions.identifier");
        
      // Merge preferences into one, with userprefs overriding everything
      $prefs = merge_recordsets('identifier', $defprefs, $domprefs, $userprefs);
    }

    return $prefs;
  }

  // Action: Edit prefs
  if ($act == 'action') {

    // Get all preferences of the current type to determine if we need to
    // insert a new preference or update an existing one
    $allprefs = getprefs($type);
    foreach ($identifier as $currid) {
      $currpref=filter_records($allprefs, 'identifier', $currid);
      if (count($currpref) > 0 && $currpref[0]['level'] == $type) {
        // Preference already exists in current scope, so can just edit it
        $sql="UPDATE tbl_".ucwords($type)."_Preferences SET value='{$_REQUEST[$currid]}'
            WHERE identifier='$currid'";

        // Need to select relevant domain/user if needed
        if ($type == 'domain') {
          $sql .= " AND domain='{$_SESSION['_domain']}'";
        } elseif ($type == 'user') {
          $sql .= " AND userid='{$_SESSION['_id']}' AND
            domain='{$_SESSION['_domain']}'";
        }

        db_send($sql);

      } elseif (count($currpref) == 0 ||
        $currpref[0]['value'] != $_REQUEST[$currid]) {
        // Preference doesnt currently exist in current scope
        // So, if preference doesnt exist at all, or the value sumitted by the
        // form differs from the default value for the preference, then add
        // it to the current scope
        if ($type == 'domain') {
          $extraids = " domain,";
          $extravalues = " '{$_SESSION['_domain']}',";
        } elseif ($type == 'user') {
          $extraids = " domain, userid,";
          $extravalues = " '{$_SESSION['_domain']}', '{$_SESSION['_id']}',";
        }

        $sql="INSERT INTO tbl_".ucwords($type)."_Preferences (identifier,$extraids value)
          VALUES ('$currid',$extravalues '{$_REQUEST[$currid]}')";
        db_send($sql);
      }
    }

    $message = gettext("NOTE: Preferences successfully changed.");
    $act = '';
  }

  // Action: Revert preference to the default value fiven by above levels
  if ($act == 'revert') {
    if ($type != 'default') {
      $sql = "DELETE FROM tbl_".ucwords($type)."_Preferences WHERE identifier='$identifier'";
      db_send($sql);
      $message = gettext("NOTE: Preference value successfully restored");
    } else {
      $message = gettext("ERROR: You cannot delete default values for preferences");
    }
    $act = '';
  }

  // Default action: Display prefs
  if ($act == '') {

    require 'header.php';

    // Language selection
    set_text_domain("preferences");

    $unsortedprefs = getprefs($type);

    // Sort preferences
    $to_sort = array();
    foreach ($unsortedprefs as $pref) {
      array_push($to_sort, $pref['identifier']);
    }
    natcasesort($to_sort);

    $prefs = array();

    foreach ($to_sort as $key => $value) {
      array_push($prefs, $unsortedprefs[$key]);
    }

    if ($message) {
      display(gettext($message));
    }
?>

<?php
    if ($type == 'user') {
      $preftitle = gettext("My Preferences");
    } elseif ($type == 'domain') {
      $preftitle = gettext("Domain Preferences");
    } elseif ($type == 'default') {
      $preftitle = gettext("Preference Defaults");
    }
?>
    <h1><?php echo $preftitle?></h1>
    
    <h2>
<?php
    if ($type == 'user') {
      echo gettext("Change your personal preferences");
    } elseif ($type == 'domain') {
      echo gettext("Change domain level preferences for the current domain");
    } elseif ($type == 'default') {
      echo gettext("Change the default values for preferences");
    }
?></h2>
  
  <div class="block">
    <p><?php echo gettext("Please note that any preferences pertaining to email notification will require you to specify your email address in the <a href=\"details.php\">My Details</a> page.");?></p>
    <form name="mainform" id="mainform" method="post" action="">
      <input type="hidden" name="act" value="action" />
      <input type="hidden" name="type" value="<?php echo $type?>" />
      <div class="buttonpanel">
        <input name="submit" type="submit"
        value="<?php echo gettext("Submit Changes");?>"/>
        <input name="reset" type="reset" value="<?php echo gettext("Reset");?>" />
      </div>
<?php
    foreach($prefs as $pref) {
?>
      <div class="labelfieldpair">
        <div class="name">
         <label for="<?php echo $pref[identifier]?>"><?php echo $pref[identifier]?>:</label>
        </div>
        <div class="value"><?php echo gettext($pref[description])?></div>
      </div>
      <div class="labelfieldpair">
        <div class="name">
<?php
      if ($type == 'default') {
        echo '&nbsp;';
      } elseif ($pref['level'] != $type) {
        echo "[{$pref['level']}]";
      } else {
        echo "<a href=\"preferences.php?act=revert&identifier={$pref['identifier']}&type=$type\">[".gettext("Restore default")."]</a>";
      }
?></div>
          <input type="hidden" name="identifier[]" value="<?php echo $pref['identifier']?>" />
        <div class="field">
<?php
      if (strtolower($pref['type']) == 'boolean') {
        $value = $pref['value'];
?>
          <input type="radio" name="<?php echo $pref[identifier]?>" id="<?php echo $pref[identifier]?>true" value="true"<?php echo ($value == 'true'?' checked="checked"':'')?> />
          <label for="<?php echo $pref[identifier]?>true"><?php echo gettext("Yes");?></label>
          <input type="radio" name="<?php echo $pref[identifier]?>" id="<?php echo $pref[identifier]?>false" value="false"<?php echo ($value!='true'?' checked="checked"':'')?> />
          <label for="<?php echo $pref[identifier]?>false"><?php echo gettext("No");?></label>
<?php
      }
      if (strtolower($pref[type]) == 'number' ||
          strtolower($pref[type]) == 'text') {
        if (count($pref) > 0) {
          $value = $pref[0]['value'];
        } else {
          $value = '';
        }
?>
          <input type="text" name="<?php echo $pref[identifier]?>" id="<?php echo $pref[identifier]?>" value="<?php echo $pref['value']?>" size="20" maxlength="100" />
<?php
      }

      if (strtolower($pref[type]) == 'multitext') {
        if (count($pref) > 0) {
          $value = $pref[0]['value'];
        } else {
          $value = '';
        }
?>
          <textarea name="<?php echo $pref[identifier]?>" id="<?php echo $pref[identifier]?>"
            cols="62" rows="7"><?php echo $pref['value']?></textarea>
<?php
      }

      if (strtolower($pref[type]) == 'langlist') {
?>
        <select name="<?php echo $pref[identifier]?>">
<?php
        foreach($avail_lang as $zelanguage) {
          if ($zelanguage[1] == $pref['value']) {
            $selected=" selected=\"selected\"";
          } else {
            $selected='';
          }
          printf("<option %s value=\"%s\">%s</option>\n", $selected, $zelanguage[1], $zelanguage[0]);
        }
?>
                </select>
<?php
      }
?>
        </div>
    </div>
<?php
    }
?>
      <div class="buttonpanel">
        <input name="submit" type="submit" value="<?php echo gettext("Submit Changes");?>" />
        <input name="reset" type="reset" value="<?php echo gettext("Reset");?>" />
      </div>
    </form>
  </div>

<?php
  }

  // Include
  require 'footer.php';
?>
