<?php

/**
  * SquirrelMail Multilogin Plugin
  * Copyright (c) 2003-2005 Paul Lesneiwski <paul@openguild.net>
  * Licensed under the GNU GPL. For full terms see the file COPYING.
  *
  * @package plugins
  * @subpackage multilogin
  *
  */



/**
  * store the user's IMAP server in the session
  *
  */
function multilogin_registerIMAPServer_do($args)
{

   // php 4.3 confuses login info when trying 
   // to login without having logged out last time
   //
   global $onetimepad;
   $onetimepad = '';
   sqsession_unregister('onetimepad');


   global $loginServer, $rememberLoginServer, $IMAPSelections;

   sqgetGlobalVar('loginServer', $loginServer, SQ_FORM);
   sqgetGlobalVar('rememberLoginServer', $rememberLoginServer, SQ_FORM);


   // can't use load_config here because compatibility
   // plugin isn't in the include path prior to this
   // hook call... but that's OK, as we were already
   // able to use load_config on the login page
   //
   //load_config('multilogin', 'config.php');
   include_once(SM_PATH . 'plugins/multilogin/config.php');


   if (isset($rememberLoginServer) && $rememberLoginServer)
   {
      // cookie expires in 30 days
      //
      setcookie('rememberLoginServer', $loginServer, (time()+60*60*24*30));
   }
   else
   {
      setcookie('rememberLoginServer', '', (time() - 3600));
   }

   if (is_array($IMAPSelections[$loginServer]))
   {

      global $config_override;
      sqsession_unregister('config_override');
////      $config_override = array();

      foreach ($IMAPSelections[$loginServer] as $setting => $value)
      {

         $config_override[$setting] = $value;

      }

      sqsession_register($config_override, 'config_override');


      multilogin_sqoverride_config_do($args);

   }
   else
   {

      include_once(SM_PATH . 'functions/display_messages.php');
      logout_error(_("Invalid server selection"));
      exit;

   }

}



/**
  * present IMAP server selection pull-down
  *
  */
function multilogin_insertIMAPSelection_do()
{

   global $enableIMAPSelection, $IMAPSelections, $rememberServer;

   // get global variable for versions of PHP < 4.1
   //
   if (!check_php_version(4,1)) {
      global $HTTP_COOKIE_VARS;
      $_COOKIE = $HTTP_COOKIE_VARS;
   }


   load_config('multilogin', 'config.php');


   bindtextdomain ('multilogin', SM_PATH . 'locale');
   textdomain ('multilogin');


   echo "<BR><CENTER>\n".
        "<TABLE COLS=\"1\" WIDTH=\"350\">\n".
        "  <TR><TD BGCOLOR=\"#DCDCDC\"><TABLE COLS=2 WIDTH=\"100%\">\n".
//        "  <TR><TD BGCOLOR=\"#888888\"><TABLE COLS=2 WIDTH=\"100%\">\n".
        "  <TR>\n".
        "    <TD WIDTH='30%' ALIGN=right>" . _("Log in to") . ":</TD>\n".
        "    <TD WIDTH=\"*\" ALIGN=left>\n".
        "       <SELECT NAME=\"loginServer\">\n";

   $foundMatchingLoginServer = 0;
   foreach (array_keys($IMAPSelections) as $IMAPServer)
   {

      echo '          <OPTION VALUE="' . $IMAPServer . '"';

      if (isset($_COOKIE['rememberLoginServer']) 
         && $_COOKIE['rememberLoginServer'] == $IMAPServer)
      {
         echo ' SELECTED';
         $foundMatchingLoginServer = 1;
      }
      echo '>'.$IMAPServer."\n";

   }

   echo "       </SELECT>\n".
        "    </TD>\n".
        "  </TR>\n".
        "</TABLE></TD></TR>\n";
   if ($rememberServer)
   {
      echo "<TR><TD><CENTER><INPUT TYPE='checkbox'" .
         ($foundMatchingLoginServer ? ' CHECKED' : '') . 
         " NAME='rememberLoginServer'>" . 
         _("Remember login server") . "\n</CENTER></TD></TR>\n";
   }
   echo "</TABLE>\n".
        "</CENTER>\n";


   bindtextdomain ('squirrelmail', SM_PATH . 'locale');
   textdomain ('squirrelmail');

}



/**
  * This will look for config overrides in the session,
  * which must be in an array called 'config_override'.
  * If found, any values stored there will take precedence
  * over preexisting config values.
  *
  */
function multilogin_sqoverride_config_do($args='')
{

   if (sqsession_is_registered('config_override'))
   {

      global $config_override, $plugins, $squirrelmail_plugin_hooks;
      sqgetGlobalVar('config_override', $config_override, SQ_SESSION);


      // grab all the config values out of the session
      // settings and override current settings with them
      //
//DEBUGGING
//sm_print_r($config_override);
      foreach ($config_override as $key => $value)
      {
//echo "$key == $value<br>";


         // enable additional plugins
         //
         if (stristr($key, 'enable_plugins'))
         {
            foreach ($value as $pluginName)
            {

               // changing the hook function array whilst in the
               // middle of iterating thru it for the same hook
               // doesn't always work, so we'll see if the hook
               // currently being executed has had its function
               // list changed; if so, we will execute the added
               // hook functions ourselves
//TODO: use $currentHookName instead of this backtrace hassle when $currentHookName
//      is part of more than just SM 1.5.1 (or part of compatibility plugin?)
//UPDATE: duh - current plugin name is first arg in all plugin hook calls
               //
               $hookName = '';
/*
               $backtrace = debug_backtrace();
               foreach ($backtrace as $trace)
                  if ($trace['function'] == 'do_hook'
                   || $trace['function'] == 'do_hook_function'
                   || $trace['function'] == 'concat_hook_function'
                   || $trace['function'] == 'boolean_hook_function')
                     $hookName = $trace['args'][0];
*/
               if (!empty($args[0]))
                  $hookName = $args[0];

               if (!empty($hookName) && is_array($squirrelmail_plugin_hooks[$hookName]))
                  $originalHookFunctions = $squirrelmail_plugin_hooks[$hookName];
               else
                  $originalHookFunctions = array();

               $plugins[] = $pluginName;
               if (function_exists('use_plugin'))
                  use_plugin($pluginName);

               // now get any new plugins for the current hook
               // and run their hooks
               //
               if (!empty($hookName))
               {
                  if (is_array($squirrelmail_plugin_hooks[$hookName]))
                     $newHookFunctions = array_diff($squirrelmail_plugin_hooks[$hookName],
                                                    $originalHookFunctions);
                  else
                     $newHookFunctions = array();

                  foreach ($newHookFunctions as $function)
                     if (function_exists($function))
// TODO: currently this code never gets run in a hook that needs data
//       passed to it or needs to return something, so the following 
//       call is fine, but if that ever changes, we'll need to get
//       the other function args from the backtrace and make the right
//       kind of call, etc.
                        $function();
               }

            }
            continue;
         }


         // disable plugins
         //
         if (stristr($key, 'disable_plugins'))
         {
            foreach ($value as $pluginName)
            {
               $pluginKey = array_search($pluginName, $plugins);
               if (!is_null($pluginKey) && $pluginKey !== FALSE)
               {
                  unset($plugins[$pluginKey]);
                  if (is_array($squirrelmail_plugin_hooks))
                     foreach (array_keys($squirrelmail_plugin_hooks) as $hookName)
                     {
                        unset($squirrelmail_plugin_hooks[$hookName][$pluginName]);
                     }
               }
            }
            continue;
         }


         //
         // replace SquirrelMail config values
         //

         global $$key;

         // embedded PHP in value need to be evaluated?
         //
         if (is_array($config_override['settingsWithEmbeddedPHP'])
          && in_array($key, $config_override['settingsWithEmbeddedPHP']))
            eval('$$key = ' . $value . ';');
         else
            $$key = $value;

      }

   }

}



?>
