Fix for first admin login
[mailer.git] / inc / modules / admin / admin-inc.php
index 9e2e39a423da4f3f4c8646bd4dc6727e15c89a44..899bd4c36ae215796af42622702046358dd6a016 100644 (file)
@@ -39,20 +39,17 @@ if (ereg(basename(__FILE__), $_SERVER['PHP_SELF']))
 }
 
 //
-function REGISTER_ADMIN ($user, $md5)
+function REGISTER_ADMIN ($user, $md5, $email=WEBMASTER)
 {
        $ret = "failed";
        $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
         array($user), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 0)
-       {
+       if (SQL_NUMROWS($result) == 0) {
                // Ok, let's create the admin login
-               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins (login, password, email) VALUES('%s', '%s', '".WEBMASTER."')",
-                array($user, $md5), __FILE__, __LINE__);
+               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins (login, password, email) VALUES('%s', '%s', '%s')",
+                array($user, $md5, $email), __FILE__, __LINE__);
                $ret = "done";
-       }
-        else
-       {
+       } else {
                // Free memory
                SQL_FREERESULT($result);
 
@@ -64,37 +61,32 @@ function REGISTER_ADMIN ($user, $md5)
 // Only be executed on login procedure!
 function CHECK_ADMIN_LOGIN ($admin_login, $password)
 {
-       global $ADMINS, $_CONFIG, $CACHE;
+       global $cacheArray, $_CONFIG, $cacheInstance;
        $ret = "404"; $pass = "";
-       if (!empty($ADMINS['aid'][$admin_login]))
-       {
+       if (!empty($cacheArray['admins']['aid'][$admin_login])) {
                // Get password from cache
-               $pass = $ADMINS['password'][$admin_login];
+               $pass = $cacheArray['admins']['password'][$admin_login];
                $ret = "pass";
                $_CONFIG['cache_hits']++;
-       }
-        else
-       {
+       } else {
                // Get password from DB
                $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
                 array($admin_login), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
+               if (SQL_NUMROWS($result) == 1) {
                        $ret = "pass";
                        list($pass) = SQL_FETCHROW($result);
                        SQL_FREERESULT($result);
                }
        }
 
-       //* DEBUG: */ echo "*".$pass."/".$password."/".$ret."<br />";
-       if ((strlen($pass) == 32) && ($pass == md5($password)))
-       {
+       /* DEBUG: */ echo "*".$pass."/".md5($password)."/".$ret."<br />";
+       if ((strlen($pass) == 32) && ($pass == md5($password))) {
                // Generate new hash
                $pass = generateHash($password);
-               if (($ret == "pass") && (GET_EXT_VERSION("sql_patches") < "0.3.6")) $ret = "done";
-       }
-        elseif ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == ""))
-       {
+
+               // Is the sql_patches not installed, than we cannot have a valid hashed password here!
+               if (($ret == "pass") && ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
+       } elseif ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) {
                // Old hashing way
                return $ret;
        }
@@ -104,133 +96,175 @@ function CHECK_ADMIN_LOGIN ($admin_login, $password)
        $salt = __SALT;
 
        // Check if password is same
-       if (($ret == "pass") && ($pass == generateHash($password, $salt)) && (!empty($salt)))
-       {
+       //* DEBUG: */ echo "*".$ret.",".$pass.",".$password.",".$salt."*<br >\n";
+       if (($ret == "pass") && ($pass == generateHash($password, $salt)) && (!empty($salt)))   {
+               // Change the passord hash here
+               $pass = generateHash($password);
+
                // Update password
                $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE login='%s' LIMIT 1",
                 array($pass, $admin_login), __FILE__, __LINE__);
 
                // Shall I remove the cache file?
-               if ((EXT_IS_ACTIVE("cache")) && ($CACHE != false))
-               {
-                       if ($CACHE->cache_file("admins", true)) $CACHE->cache_destroy();
+               if ((EXT_IS_ACTIVE("cache")) && ($cacheInstance != false)) {
+                       if ($cacheInstance->cache_file("admins", true)) $cacheInstance->cache_destroy();
                }
 
-               // Password matches!
-               $ret = "done";
-       }
-        elseif ((empty($salt)) && ($ret == "pass"))
-       {
+               // Login has failed by default... ;-)
+               $ret = "failed";
+
+               // Password matches so login here
+               if (LOGIN_ADMIN($admin_login, $pass)) {
+                       // All done now
+                       $ret = "done";
+               }
+       } elseif ((empty($salt)) && ($ret == "pass")) {
                // Something bad went wrong
                $ret = "failed";
+       } elseif ($ret == "done") {
+               // Try to login here if we have the old hashing way (sql_patches not installed?)
+               if (!LOGIN_ADMIN($admin_login, $pass)) {
+                       // Something went wrong
+                       $ret = "failed";
+               }
        }
+
+       // Return the result
+       //* DEBUG: */ die("RETURN=".$ret);
        return $ret;
 }
+
+// Try to login the admin by setting some session/cookie variables
+function LOGIN_ADMIN ($adminLogin, $passHash) {
+       // Now set all session variables and return the result
+       return (
+               (
+                       set_session("admin_md5", generatePassString($passHash))
+               ) && (
+                       set_session("admin_login", $adminLogin)
+               ) && (
+                       set_session("admin_last", time())
+               ) && (
+                       set_session("admin_to", $_POST['timeout'])
+               )
+       );
+}
+
 // Only be executed on cookie checking
-function CHECK_ADMIN_COOKIES ($admin_login, $password)
-{
-       global $ADMINS, $_CONFIG;
+function CHECK_ADMIN_COOKIES ($admin_login, $password) {
+       global $cacheArray, $_CONFIG;
        $ret = "404"; $pass = "";
-       if (!empty($ADMINS['aid'][$admin_login]))
-       {
+       if (!empty($cacheArray['admins']['aid'][$admin_login])) {
                // Get password from cache
-               $pass = $ADMINS['password'][$admin_login];
+               $pass = $cacheArray['admins']['password'][$admin_login];
                $ret = "pass";
                $_CONFIG['cache_hits']++;
-       }
-        else
-       {
+       } else {
                // Get password from DB
                $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
                 array($admin_login), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
+               if (SQL_NUMROWS($result) == 1) {
+                       // Entry found
                        $ret = "pass";
+
+                       // Fetch password
                        list($pass) = SQL_FETCHROW($result);
-                       SQL_FREERESULT($result);
                }
+
+               // Free result
+               SQL_FREERESULT($result);
        }
 
-       //* DEBUG: */ echo "*".$pass."/".$password."<br />";
+       //* DEBUG: */ echo __FUNCTION__.":".$pass."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
 
        // Check if password matches
-       if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password)))
-       {
+       if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
                // Passwords matches!
                $ret = "done";
        }
+
+       // Return result
        return $ret;
 }
 //
-function admin_WriteData ($file, $comment, $prefix, $suffix, $DATA, $seek=0)
-{
-       $done = false;  $seek++; $found = false;
-       if (file_exists($file))
-       {
+function admin_WriteData ($file, $comment, $prefix, $suffix, $DATA, $seek=0) {
+       // Initialize some variables
+       $done = false;
+       $seek++;
+       $found = false;
+
+       // Is the file there and read-/write-able?
+       if ((file_exists($file)) && (is_readable($file)) && (is_writeable($file))) {
                $search = "CFG: ".$comment;
                $tmp = $file.".tmp";
-               $fp = fopen($file, 'r') or OUTPUT_HTML("<STRONG>READ:</STRONG> ".$file."<br />");
-               if ($fp)
-               {
-                       $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<STRONG>WRITE:</STRONG> ".$tmp."<br />");
-                       if ($fp_tmp)
-                       {
-                               while (! feof($fp))
-                               {
+
+               // Open the source file
+               $fp = @fopen($file, 'r') or OUTPUT_HTML("<STRONG>READ:</STRONG> ".$file."<br />");
+
+               // Is the resource valid?
+               if (is_resource($fp)) {
+                       // Open temporary file
+                       $fp_tmp = @fopen($tmp, 'w') or OUTPUT_HTML("<STRONG>WRITE:</STRONG> ".$tmp."<br />");
+
+                       // Is the resource again valid?
+                       if (is_resource($fp_tmp)) {
+                               while (!feof($fp)) {
+                                       // Read from source file
                                        $line = fgets ($fp, 1024);
+
                                        if (strpos($line, $search) > -1) { $next = 0; $found = true; }
-                                       if ($next > -1)
-                                       {
-                                               if ($next == $seek)
-                                               {
+
+                                       if ($next > -1) {
+                                               if ($next == $seek) {
                                                        $next = -1;
                                                        $line = $prefix . $DATA . $suffix."\n";
-                                               }
-                                                else
-                                               {
+                                               } else {
                                                        $next++;
                                                }
                                        }
+
+                                       // Write to temp file
                                        fputs($fp_tmp, $line);
                                }
+
+                               // Close temp file
                                fclose($fp_tmp);
+
                                // Finished writing tmp file
                                $done = true;
                        }
+
+                       // Close source file
                        fclose($fp);
-                       if (($done) && ($found))
-                       {
+
+                       if (($done) && ($found)) {
                                // Copy back tmp file and delete tmp :-)
                                @copy($tmp, $file);
                                @unlink($tmp);
-                               define ('_FATAL', false);
-                       }
-                        elseif (!$found)
-                       {
+                               define('_FATAL', false);
+                       } elseif (!$found) {
                                OUTPUT_HTML("<STRONG>CHANGE:</STRONG> 404!");
-                               define ('_FATAL', true);
-                       }
-                        else
-                       {
+                               define('_FATAL', true);
+                       } else {
                                OUTPUT_HTML("<STRONG>TMP:</STRONG> UNDONE!");
-                               define ('_FATAL', true);
+                               define('_FATAL', true);
                        }
                }
-       }
-        else
-       {
+       } else {
+               // File not found, not readable or writeable
                OUTPUT_HTML("<STRONG>404:</STRONG> ".$file."<br />");
        }
 }
+
 //
 function ADMIN_DO_ACTION($wht)
 {
-       global $menuDesription, $menuTitle, $_CONFIG, $EXTENSIONS, $link, $DATA;
+       global $menuDesription, $menuTitle, $_CONFIG, $cacheArray, $link, $DATA, $DEPTH;
        //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
        if (EXT_IS_ACTIVE("cache"))
        {
                // Include cache instance
-               global $CACHE;
+               global $cacheInstance;
        }
 
        // Remove any spaces from variable
@@ -249,8 +283,8 @@ function ADMIN_DO_ACTION($wht)
        $act = GET_ACTION($GLOBALS['module'], $wht);
 
        // Define admin login name and ID number
-       define('__ADMIN_LOGIN', SQL_ESCAPE($_COOKIE['admin_login']));
-       define('__ADMIN_ID'   , GET_ADMIN_ID($_COOKIE['admin_login']));
+       define('__ADMIN_LOGIN', SQL_ESCAPE(get_session('admin_login')));
+       define('__ADMIN_ID'   , GET_ADMIN_ID(get_session('admin_login')));
 
        // Preload templates
        if (EXT_IS_ACTIVE("admins")) {
@@ -304,7 +338,7 @@ LIMIT 1", array($act, $wht, $wht), __FILE__, __LINE__);
 //
 function ADD_ADMIN_MENU($act, $wht,$return=false)
 {
-       global $_GET, $menuDesription, $menuTitle, $link;
+       global $menuDesription, $menuTitle, $link;
        $SUB = false;
 
        // Menu descriptions
@@ -338,9 +372,9 @@ function ADD_ADMIN_MENU($act, $wht,$return=false)
                                        $menuDesription[$menu] = $descr;
                                }
                                $OUT .= "<TR>
-  <TD class=\"admin_menu\" colspan=\"2\">
-    <NOBR>&nbsp;<STRONG>&middot;</STRONG>&nbsp;";
-                               if (($menu == $act) && (empty($wht)))
+       <TD class=\"admin_menu\" colspan=\"2\">
+               <NOBR>&nbsp;<STRONG>&middot;</STRONG>&nbsp;";
+                                       if (($menu == $act) && (empty($wht)))
                                {
                                        $OUT .= "<STRONG>";
                                }
@@ -349,7 +383,7 @@ function ADD_ADMIN_MENU($act, $wht,$return=false)
                                        $OUT .= "[&nbsp;<A href=\"".URL."/modules.php?module=admin&amp;action=".$menu."\">";
                                }
                                $OUT .= $title;
-                               if (($menu == $act) && (empty($wht)))
+                                       if (($menu == $act) && (empty($wht)))
                                {
                                        $OUT .= "</STRONG>";
                                }
@@ -366,10 +400,10 @@ function ADD_ADMIN_MENU($act, $wht,$return=false)
                                        $menuDesription = array();
                                        $menuTitle = array(); $SUB = true;
                                        $OUT .= "<TR>
-  <TD width=\"10\" class=\"seperator\">&nbsp;</TD>
-  <TD class=\"admin_menu\">
-    <TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
-                                       while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what))
+       <TD width=\"10\" class=\"seperator\">&nbsp;</TD>
+       <TD class=\"admin_menu\">
+               <TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
+                                               while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what))
                                        {
                                                // Filename
                                                $INC = sprintf(PATH."inc/modules/admin/what-%s.php", $wht_sub);
@@ -389,8 +423,8 @@ function ADD_ADMIN_MENU($act, $wht,$return=false)
                                                        $menuTitle[$wht_sub]        = $title_what;
                                                        $menuDesription[$wht_sub] = $desc_what;
                                                        $OUT .= "<TR>
-  <TD class=\"admin_menu\" colspan=\"2\">
-    <NOBR>&nbsp;<STRONG>--&gt;</STRONG>&nbsp;";
+       <TD class=\"admin_menu\" colspan=\"2\">
+               <NOBR>&nbsp;<STRONG>--&gt;</STRONG>&nbsp;";
                                                        if ($readable)
                                                        {
                                                                if ($wht == $wht_sub)
@@ -430,7 +464,7 @@ function ADD_ADMIN_MENU($act, $wht,$return=false)
                                        // Free memory
                                        SQL_FREERESULT($result_what);
                                        $OUT .= "    </TABLE>
-  </TD>
+       </TD>
 </TR>\n";
                                }
                                $OUT .= "<TR><TD height=\"7\" colspan=\"2\"></TD></TR>\n";
@@ -457,7 +491,6 @@ function ADD_ADMIN_MENU($act, $wht,$return=false)
 //
 function ADD_MEMBER_SELECTION_BOX($add_all = false, $return = false, $none = false, $def = "0")
 {
-       global $_GET;
        // Output selection form with all confirmed user accounts listed
        $result = SQL_QUERY("SELECT userid, surname, family FROM "._MYSQL_PREFIX."_user_data ORDER BY userid", __FILE__, __LINE__);
        $OUT = "";
@@ -478,8 +511,7 @@ function ADD_MEMBER_SELECTION_BOX($add_all = false, $return = false, $none = fal
        // Remeber options in constant
        define('_MEMBER_SELECTION', $OUT);
 
-       if (!$return)
-       {
+       if (!$return) {
                // Display selection box
                define('__LANG_VALUE', GET_LANGUAGE());
 
@@ -488,8 +520,7 @@ function ADD_MEMBER_SELECTION_BOX($add_all = false, $return = false, $none = fal
        }
 }
 //
-function ADMIN_MENU_SELECTION($MODE, $default="", $defid="")
-{
+function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
        $wht = "what != ''";
        if ($MODE == "action") $wht = "what='' AND action !='login'";
        $result = SQL_QUERY_ESC("SELECT %s, title FROM "._MYSQL_PREFIX."_admin_menu WHERE ".$wht." ORDER BY sort",
@@ -500,7 +531,7 @@ function ADMIN_MENU_SELECTION($MODE, $default="", $defid="")
                $OUT = "<SELECT name=\"".$MODE."_menu";
                if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
                $OUT .= "\" size=\"1\" class=\"admin_select\">
-  <OPTION value=\"\">".SELECT_NONE."</OPTION>\n";
+       <OPTION value=\"\">".SELECT_NONE."</OPTION>\n";
                while (list($menu, $title) = SQL_FETCHROW($result))
                {
                        $OUT .= "  <OPTION value=\"".$menu."\"";
@@ -524,7 +555,7 @@ function ADMIN_MENU_SELECTION($MODE, $default="", $defid="")
 //
 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma = array(), $alwaysAdd=false)
 {
-       global $_CONFIG, $CFG_CACHE, $CACHE;
+       global $_CONFIG, $cacheArray, $cacheInstance;
        $DATA = array();
        $skip = false; $TEST2 = "";
        foreach ($POST as $id=>$val) {
@@ -626,8 +657,8 @@ function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="con
        // Is the config table updated and the cache extension installed?
        if ((GET_EXT_VERSION("cache") >= "0.1.2") && ($tableName == "_config")) {
                // Remove it here...
-               if ($CACHE->cache_file("config", true)) $CACHE->cache_destroy();
-               unset($CFG_CACHE);
+               if ($cacheInstance->cache_file("config", true)) $cacheInstance->cache_destroy();
+               unset($cacheArray);
        }
 
        // Settings saved
@@ -679,23 +710,23 @@ function ADMIN_USER_PROFILE_LINK($uid, $title="", $wht="list_user")
 //
 function ADMIN_CHECK_MENU_MODE()
 {
-       global $_CONFIG, $ADMINS, $_COOKIE;
+       global $_CONFIG, $cacheArray;
 
        // Set the global mode as the mode for all admins
        $MODE = $_CONFIG['admin_menu']; $ADMIN = $MODE;
 
        // Check individual settings of current admin
-       if (isset($ADMINS['la_mode'][$_COOKIE['admin_login']]))
+       if (isset($cacheArray['admins']['la_mode'][get_session('admin_login')]))
        {
                // Load from cache
-               $ADMIN = $ADMINS['la_mode'][$_COOKIE['admin_login']];
+               $ADMIN = $cacheArray['admins']['la_mode'][get_session('admin_login')];
                $_CONFIG['cache_hits']++;
        }
         elseif (GET_EXT_VERSION("admins") >= "0.6.7")
        {
                // Load from database when version of "admins" is enough
                $result = SQL_QUERY_ESC("SELECT la_mode FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
-                array($_COOKIE['admin_login']), __FILE__, __LINE__);
+                array(get_session('admin_login')), __FILE__, __LINE__);
                if (SQL_NUMROWS($result) == 1)
                {
                        // Load data