<?php 
/*#################################################################*\
|# Licence Number 0H6R-0808-0UVQ-0111
|# -------------------------------------------------------------   #|
|# Copyright (c)2012 PHP Link Directory.                           #|
|# http://www.phplinkdirectory.com                                 #|
\*#################################################################*/
	 
	
/**
 # ################################################################################
 # Project:   PHP Link Directory
 #
 # **********************************************************************
 # Copyright (C) 2004-2012 NetCreated, Inc. (http://www.netcreated.com/)
 #
 # This software is for use only to those who have purchased a license.
 # A license must be purchased for EACH installation of the software.
 #
 # By using the software you agree to the terms:
 #
 #    - You may not redistribute, sell or otherwise share this software
 #      in whole or in part without the consent of the the ownership
 #      of PHP Link Directory. Please contact david@david-duval.com
 #      if you need more information.
 #
 #    - You agree to retain a link back to http://www.phplinkdirectory.com/
 #      on all pages of your directory if you purchased any of our "link back" 
 #      versions of the software.
 #
 #
 # In some cases, license holders may be required to agree to changes
 # in the software license before receiving updates to the software.
 # **********************************************************************
 #
 # For questions, help, comments, discussion, etc., please join the
 # PHP Link Directory Forum http://www.phplinkdirectory.com/forum/
 #
 # @link           http://www.phplinkdirectory.com/
 # @copyright      2004-2012 NetCreated, Inc. (http://www.netcreated.com/)
 # @projectManager David DuVal <david@david-duval.com>
 # @package        PHPLinkDirectory
 # @version        4.2.1
 # ################################################################################
 */
 
require_once 'init.php';

//Disable any caching by the browser
disable_browser_cache();

//RALUCA: JQuery validation related
$validators = array(
	'rules' => array(
		'user' => array(
						'required' => true
				),
	    'pass' => array(
						'required' => true
				)
	)
);

$vld = json_custom_encode($validators);
$tpl->assign('validators', $vld);

$validator = new Validator($validators);
//RALUCA: end of JQuery validation related

if (empty ($_POST['submit']))
{
}
else
{
   $_POST['user'] = strip_white_space($_POST['user']);
   $_POST['pass'] = strip_white_space($_POST['pass']);
   
   
   //RALUCA: JQuery validation related - server side.
   $validator = new Validator($validators);
   $validator_res = $validator->validate($_POST);
   //RALUCA: end of JQuery validation related - server side.
   
   
   if (empty($validator_res))
   {
       $sql = "SELECT `ID`, `LOGIN`, `NAME`, `LEVEL`, `RANK`, `LANGUAGE` FROM `{$tables['user']['name']}` WHERE `LOGIN` = ".$db->qstr($_POST['user'])." AND `PASSWORD` = ".$db->qstr(encrypt_password($_POST['pass']))." AND `ACTIVE` = '1'";
       $row = $db->GetRow($sql);

     
      if (is_array ($row) && !empty ($row))
      {
//         $_SESSION['login_error'] = 0;
         //Create new phpLD user session if none exists
         //Don't break admin panel login data
         if (!isset ($_SESSION['phpld']))
         {
            $_SESSION['phpld'] = array();
         }

         //Create web user session
         $_SESSION['phpld']['user'] = array();

         //Load all user data into session

         foreach ($row as $field => $value)
         {
            $field = strtolower ($field);
            $_SESSION['phpld']['user'][$field] = $value;
         }
         
      if (isset($_SESSION['phpld']['user']['id'])) {
		   $user_level = get_user_level($_SESSION['phpld']['user']['id']);
		   if ($user_level == 1) {
		   		//delete expired links & articles (not paid though) on admin login
               //links
               $HaveExpiredEmail_sql = "DELETE FROM `{$tables['link']['name']}`
                                WHERE `OWNER_EMAIL_CONFIRMED` = '0'
                                AND DATE_ADD(`DATE_ADDED`, INTERVAL ".WAIT_FOR_EMAIL_CONF." DAY) <= now()
                                AND `PAYED` <> '1'";
  
    		   $HaveExpiredEmail = $db->Execute($HaveExpiredEmail_sql);
			   //articles
			   $HaveExpiredEmail_sql = "DELETE FROM `{$tables['article']['name']}`
                                WHERE `OWNER_EMAIL_CONFIRMED` = '0'
                                AND DATE_ADD(`DATE_ADDED`, INTERVAL ".WAIT_FOR_EMAIL_CONF." DAY) <= now() 
                                AND `PAYED`<>'1'";
  
    		   $HaveExpiredEmail = $db->Execute($HaveExpiredEmail_sql);	
    		   //end of delete
		   }
	  }
         
         $_SESSION['user_language'] = $_SESSION['phpld']['user']['language'];
         
         if (isset($_POST['rememberMe'])) {
         	$auth = array('user' => $_POST['user'], 'password' => $_POST['password']);
            $auth = serialize($auth);
            setcookie('auth', $auth, time() + 7 * 24 * 60 * 60, '/');
         } else {
            // unset the possibly seted cookie
            setcookie('auth', '', time() - 3600, '/');
         }
         
         
        // Update last login
		$user_id = $_SESSION['phpld']['user']['id'];
		  $data['LAST_LOGIN']     = $timenow;
		  $where = " `ID` = ".$db->qstr($user_id);
          $db->AutoExecute($tables['user']['name'], $data, 'UPDATE', $where);
         if (isset($_SESSION['prev_page'])) {
             http_custom_redirect($_SESSION['prev_page']);
         } else
         http_custom_redirect(DOC_ROOT."/profile.php?mode=logged");
      }
      else
         $tpl->assign('no_permission', true);
   }
   else {
      $tpl->assign('failed', true);
//      $_SESSION['login_error'] = 1;
   }
}

$path   = array ();
$path[] = array ('ID' => '0', 'TITLE' => _L(SITE_NAME), 'TITLE_URL' => DOC_ROOT, 'DESCRIPTION' => SITE_DESC);
$path[] = array ('ID' => '0', 'TITLE' => _L('Log in') , 'TITLE_URL' => ''      , 'DESCRIPTION' => _L('Log in'));
$tpl->assign('path', $path);

$tpl->assign('load_Javascript', 1);

//Clean whitespace
$tpl->load_filter('output', 'trimwhitespace');

//Compress output for faster loading
if (COMPRESS_OUTPUT == 1)
   $tpl->load_filter('output', 'CompressOutput');

   
   
//Make output
echo $tpl->fetch('login.tpl', $id);


?>