We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 1932
    • 137 Posts
    I wanted to include the necessary javascript for the WebLogin snippet externally, rather than including it inline for every document. I have made a small modification which can be downloaded below. Let me know what you guys think about working this functionality into the version bundled with MODx.

    Updated WebLogin snippet:
    <?php
    # WebLogin 1.0.1
    # Created By Raymond Irving 2004
    # Modified May, 2007
    #::::::::::::::::::::::::::::::::::::::::
    # Usage: 	
    #	Allows a web user to login to the website
    #
    # Params:	
    #       &jsinclude  - (Optional)
    #               specify this parameter to include an external
    #               javascript file rather than including it inline
    #               &jsinclude=`path/to/weblogin.js`
    #               if set to ``, no javascript will be included
    #
    #	&loginhomeid 	- (Optional)
    #		redirects the user to first authorized page in the list.
    #		If no id was specified then the login home page id or 
    #		the current document id will be used
    #
    #	&logouthomeid 	- (Optional)
    #		document id to load when user logs out	
    #
    #	&pwdreqid 	- (Optional)
    #		document id to load after the user has submited
    #		a request for a new password
    #
    #	&pwdactid 	- (Optional)
    #		document id to load when the after the user has activated
    #		their new password
    #
    #	&logintext		- (Optional) 
    #		Text to be displayed inside login button (for built-in form)
    #
    #	&logouttext 	- (Optional)
    #		Text to be displayed inside logout link (for built-in form)
    #	
    #	&tpl			- (Optional)
    #		Chunk name or document id to as a template
    #				  
    #	Note: Templates design:
    #			section 1: login template
    #			section 2: logout template 
    #			section 3: password reminder template 
    #
    #			See weblogin.tpl for more information
    #
    # Examples:
    #
    #	[[WebLogin? &loginhomeid=`8` &logouthomeid=`1`]] 
    #
    #	[[WebLogin? &loginhomeid=`8,18,7,5` &tpl=`Login`]] 
    
    # Set Snippet Paths 
    $snipPath = $modx->config['base_path'] . "assets/snippets/";
    
    # check if inside manager
    if ($m = $modx->insideManager()) {
    	return ''; # don't go any further when inside manager
    }
    
    # deprecated params - only for backward compatibility
    if(isset($loginid)) $loginhomeid=$loginid;
    if(isset($logoutid)) $logouthomeid = $logoutid;
    if(isset($template)) $tpl = $template;
    
    # Snippet customize settings
    $jsInclude       = isset($jsinclude) ? $jsinclude:-1;
    $liHomeId	= isset($loginhomeid)? explode(",",$loginhomeid):array($modx->config['login_home'],$modx->documentIdentifier);
    $loHomeId	= isset($logouthomeid)? $logouthomeid:$modx->documentIdentifier;
    $pwdReqId	= isset($pwdreqid)? $pwdreqid:0;
    $pwdActId	= isset($pwdactid)? $pwdactid:0;
    $loginText	= isset($logintext)? $logintext:'Login';
    $logoutText	= isset($logouttext)? $logouttext:'Logout';
    $tpl		= isset($tpl)? $tpl:"";
    
    # System settings
    $webLoginMode = isset($_REQUEST['webloginmode'])? $_REQUEST['webloginmode']: '';
    $isLogOut		= $webLoginMode=='lo' ? 1:0;
    $isPWDActivate	= $webLoginMode=='actp' ? 1:0;
    $isPostBack		= count($_POST) && (isset($_POST['cmdweblogin']) || isset($_POST['cmdweblogin_x']));
    $txtPwdRem 		= isset($_REQUEST['txtpwdrem'])? $_REQUEST['txtpwdrem']: 0;
    $isPWDReminder	= $isPostBack && $txtPwdRem=='1' ? 1:0;
    
    $site_id = isset($site_id)? $site_id: '';
    $cookieKey = substr(md5($site_id."Web-User"),0,15);
    
    # Start processing
    include_once $snipPath."weblogin/weblogin.common.inc.php";
    include_once ($modx->config['base_path'] . "manager/includes/crypt.class.inc.php");
    
    if ($isPWDActivate || $isPWDReminder || $isLogOut || $isPostBack) {
    	# include the logger class
    	include_once $modx->config['base_path'] . "manager/includes/log.class.inc.php";
    	include_once $snipPath."weblogin/weblogin.processor.inc.php";
    }
    
    include_once $snipPath."weblogin/weblogin.inc.php";
    
    # Return
    return $output;
    ?>
    


    WebLogin include file:
    <?php
    # WebLogin 1.0.1
    # Created By Raymond Irving 2004
    # Modified May, 2007
    #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    
    defined('IN_PARSER_MODE') or die();
    
    # load tpl
    if(is_numeric($tpl)) $tpl = ($doc=$modx->getDocuments($tpl)) ? $doc['content']:"Document '$tpl' not found.";
    else if($tpl) $tpl = ($chunk=$modx->getChunk($tpl)) ? $chunk:"Chunk '$tpl' not found.";
    if(!$tpl) $tpl = getWebLogintpl();
    
    // extract declarations
    $declare = webLoginExtractDeclarations($tpl);
    $tpls = explode((isset($declare["separator"]) ? $declare["separator"]:"<!--tpl_separator-->"),$tpl);
    
    if(!isset($_SESSION['webValidated'])){
        ob_start();
    //    if(isset($_COOKIE[$cookieKey])) {
    //        $cookieSet = 1;
    //        $sitename = $_COOKIE[$cookieKey];
    //        $thepasswd = substr($site_id,-5)."crypto"; // create a password based on site id
    //        $rc4 = new rc4crypt;
    //        $thestring = $rc4->endecrypt($thepasswd,$sitename,'de');
    //        $uid = $thestring;
    //    }else{
            $uid = isset($_POST['username'])? $modx->db->escape(strip_tags($_POST['username'])):'';
    //    }
        if ($jsInclude != -1) {
    	if ($jsInclude != "")
    	        $modx->regClientStartupScript($jsInclude); // Register external javascript with MODx
        } else {
        ?>
        <script type="text/JavaScript">
    
            function getElementById(id){
                var o, d=document;
                if (d.layers) {o=d.layers[id];if(o) o.style=o};
                if (!o && d.getElementById) o=d.getElementById(id);
                if (!o && d.all) o = d.all[id];
                return o;
            }
        
            function webLoginShowForm(i){
                var a = getElementById('WebLoginLayer0');
                var b = getElementById('WebLoginLayer2');
                if(i==1 && a && b) {
                    a.style.display="block";
                    b.style.display="none";
                    document.forms['loginreminder'].txtpwdrem.value = 0;
                }
                else if(i==2 && a && b) {
                    a.style.display="none";
                    b.style.display="block";    
                    document.forms['loginreminder'].txtpwdrem.value = 1;
                }
            };        
            function webLoginCheckRemember () {
                if(document.loginfrm.rememberme.value==1) {
                    document.loginfrm.rememberme.value=0;    
                } else {
                    document.loginfrm.rememberme.value=1;
                }
            }
            function webLoginEnter(nextfield,event) {
                if(event && event.keyCode == 13) {
                    if(nextfield.name=='cmdweblogin') {
                        document.loginfrm.submit();
                        return false; 
                    }
                    else {
                        nextfield.focus();
                        return false; 
                    }
                } else {
                    return true;
                }
            }
        </script>
        <?php
        }
          
            // display login
            $ref = isset($_REQUEST["refurl"]) ? "&refurl=".urlencode($_REQUEST["refurl"]):"";
            $tpl = "<div id='WebLoginLayer0' style='position:relative'>".$tpls[0]."</div>";
            $tpl.= "<div id='WebLoginLayer2' style='position:relative;display:none'>".$tpls[2]."</div>";
            $tpl = str_replace("[+action+]",$modx->makeUrl($modx->documentIdentifier,"",$ref),$tpl);
            $tpl = str_replace("[+rememberme+]",(isset($cookieSet) ? 1 : 0),$tpl);    
            $tpl = str_replace("[+username+]",$uid,$tpl);    
            $tpl = str_replace("[+checkbox+]",(isset($cookieSet) ? "checked" : ""),$tpl);
            $tpl = str_replace("[+logintext+]",$loginText,$tpl);    
            echo $tpl;
        ?>
        <script type="text/javascript">
            if (document.loginfrm) <?php echo !empty($uid) ? "document.loginfrm.password.focus()" : "document.loginfrm.username.focus()" ?>;
        </script>
        <?php
        $output .= ob_get_contents();
        ob_end_clean();
    } else {
        $output= '';
        $dbase = $modx->dbConfig['dbase'];
        $table_prefix = $modx->dbConfig['table_prefix'];
        
        if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
        else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
        else $ip = "UNKNOWN";$_SESSION['ip'] = $ip;
        
        $itemid = isset($_REQUEST['id']) ? $_REQUEST['id'] : 'NULL' ;$lasthittime = time();$a = 998;
        
        if($a!=1) {
            $sql = "REPLACE INTO $dbase.`".$table_prefix."active_users` (internalKey, username, lasthit, action, id, ip) values(-".$_SESSION['webInternalKey'].", '".$_SESSION['webShortname']."', '".$lasthittime."', '".$a."', '".$itemid."', '$ip')";
            if(!$rs = $modx->dbQuery($sql)) {
                $output = "error replacing into active users! SQL: ".$sql;
                return;
            }
        }
        
        // display logout
        $tpl = $tpls[1];
        $url = $modx->makeUrl($modx->documentIdentifier);
        $url = $url.((strpos($url,"?")===false) ? "?":"&")."webloginmode=lo";
        $tpl = str_replace("[+action+]",$url,$tpl);    
        $tpl = str_replace("[+logouttext+]",$logoutText,$tpl);    
        $output .= $tpl;
    }
    
    
    # Returns Default WebLogin tpl
    function getWebLogintpl(){
        ob_start();
        ?>
        <!-- #declare:separator <hr> --> 
        <!-- login form section-->
        <form method="post" name="loginfrm" action="[+action+]" style="margin: 0px; padding: 0px;"> 
        <input type="hidden" value="[+rememberme+]" name="rememberme" /> 
        <table border="0" cellspacing="0" cellpadding="0">
        <tr>
        <td>
        <table border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td><b>User:</b></td>
            <td><input type="text" name="username" tabindex="1" onkeypress="return webLoginEnter(document.loginfrm.password);" size="8" style="width: 150px;" value="[+username+]" /></td>
          </tr>
          <tr>
            <td><b>Password:</b></td>
            <td><input type="password" name="password" tabindex="2" onkeypress="return webLoginEnter(document.loginfrm.cmdweblogin);" style="width: 150px;" value="" /></td>
          </tr>
          <tr>
            <td><label for="chkbox" style="cursor:pointer">Remember me:  </label></td>
            <td>
            <table width="100%"  border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td valign="top"><input type="checkbox" id="chkbox" name="chkbox" tabindex="4" size="1" value="" [+checkbox+] onclick="webLoginCheckRemember()" /></td>
                <td align="right">                                    
                <input type="submit" value="[+logintext+]" name="cmdweblogin" /></td>
              </tr>
            </table>
            </td>
          </tr>
          <tr>
            <td colspan="2"><a href="#" onclick="webLoginShowForm(2);return false;">Forget Password?</a></td>
          </tr>
        </table>
        </td>
        </tr>
        </table>
        </form>
        <hr>
        <!-- log out hyperlink section -->
        <a href='[+action+]'>[+logouttext+]</a>
        <hr>
        <!-- Password reminder form section -->
        <form name="loginreminder" method="post" action="[+action+]" style="margin: 0px; padding: 0px;">
        <input type="hidden" name="txtpwdrem" value="0" />
        <table border="0">
            <tr>
              <td>Enter the email address of your account <br />below to receive your password:</td>
            </tr>
            <tr>
              <td><input type="text" name="txtwebemail" size="24" /></td>
            </tr>
            <tr>
              <td align="right"><input type="submit" value="Submit" name="cmdweblogin" />
              <input type="reset" value="Cancel" name="cmdcancel" onclick="webLoginShowForm(1);" /></td>
            </tr>
          </table>
        </form>
        <?php 
        $t = ob_get_contents();
        ob_end_clean();
        return $t;
    }
    ?>
    



    WebLogin JS file:
    function getElementById(id){
        var o, d=document;
        if (d.layers) {o=d.layers[id];if(o) o.style=o};
        if (!o && d.getElementById) o=d.getElementById(id);
        if (!o && d.all) o = d.all[id];
        return o;
    }
    function webLoginShowForm(i){
        var a = getElementById('WebLoginLayer0');
        var b = getElementById('WebLoginLayer2');
        if(i==1 && a && b) {
            a.style.display="block";
            b.style.display="none";
            document.forms['loginreminder'].txtpwdrem.value = 0;
        }
        else if(i==2 && a && b) {
            a.style.display="none";
            b.style.display="block";    
            document.forms['loginreminder'].txtpwdrem.value = 1;
        }
    }
    function webLoginCheckRemember () {
        if(document.loginfrm.rememberme.value==1) {
            document.loginfrm.rememberme.value=0;    
        } else {
            document.loginfrm.rememberme.value=1;
        }
    }
    function webLoginEnter(nextfield,event) {
        if(event && event.keyCode == 13) {
            if(nextfield.name=='cmdweblogin') {
                document.loginfrm.submit();
                return false; 
            } else {
                nextfield.focus();
                return false; 
            }
        } else {
            return true;
        }
    }