<?php 
/*#################################################################*\
|# Licence Number 0DT7-0122-0NW1-0210
|# -------------------------------------------------------------   #|
|# Copyright (c)2010 PHP Link Directory.                           #|
|# http://www.phplinkdirectory.com                                 #|
\*#################################################################*/
	
/**
# ################################################################################
# Project:   PHP Link Directory
#
# **********************************************************************
# Copyright (C) 2004-2009 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 in you purchased the $25 version
#      of the software.
#
# License holders are entitled to upgrades to the 3.4 branch of the software
# as they are made available at http://www.phplinkdirectory.com/
#
# 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-2009 NetCreated, Inc. (http://www.netcreated.com/)
# @projectManager David DuVal <david@david-duval.com>
# @package        PHPLinkDirectory
# @version        4.0.0
# ################################################################################
*/

require_once 'init.php';

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

if (empty ($_POST['submit']))
{
   SmartyValidate :: connect($tpl);
   SmartyValidate :: register_form('login', true);
   SmartyValidate :: register_validator('v_user', 'user', 'notEmpty', false, false, 'trim', 'login');
   SmartyValidate :: register_validator('v_pass', 'pass', 'notEmpty', false, false, 'trim', 'login');
}
else
{
   SmartyValidate :: connect($tpl);

   $_POST['user'] = strip_white_space($_POST['user']);
   $_POST['pass'] = strip_white_space($_POST['pass']);
   
   if (SmartyValidate :: is_valid($_POST, 'login'))
   {
       $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);
         SmartyValidate :: disconnect();
         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);

//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);


?>