PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/xfw/includes/access.class.php

http://xfw-xkid-framework.googlecode.com/
PHP | 345 lines | 166 code | 10 blank | 169 comment | 28 complexity | 0766ae982b7c127853edd8458b9db9b6 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * PHP Class to user access (login, register, logout, etc)
  4. *
  5. * <code><?php
  6. * include('access.class.php');
  7. * $user = new flexibleAccess();
  8. * ? ></code>
  9. *
  10. * For support issues please refer to the webdigity forums :
  11. * http://www.webdigity.com/index.php/board,91.0.html
  12. * or the official web site:
  13. * http://phpUserClass.com/
  14. * ==============================================================================
  15. *
  16. * @version $Id: access.class.php,v 0.93 2008/05/02 10:54:32 $
  17. * @copyright Copyright (c) 2007 Nick Papanotas (http://www.webdigity.com)
  18. * @author Nick Papanotas <nikolas@webdigity.com>
  19. * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
  20. *
  21. * ==============================================================================
  22. */
  23. /**
  24. * Flexible Access - The main class
  25. *
  26. * @param string $dbName
  27. * @param string $dbHost
  28. * @param string $dbUser
  29. * @param string $dbPass
  30. * @param string $dbTable
  31. */
  32. class flexibleAccess{
  33. /*Settings*/
  34. /**
  35. * The database that we will use
  36. * var string
  37. */
  38. var $dbName = 'database';
  39. /**
  40. * The database host
  41. * var string
  42. */
  43. var $dbHost = 'localhost';
  44. /**
  45. * The database port
  46. * var int
  47. */
  48. var $dbPort = 3306;
  49. /**
  50. * The database user
  51. * var string
  52. */
  53. var $dbUser = 'user';
  54. /**
  55. * The database password
  56. * var string
  57. */
  58. var $dbPass = 'password';
  59. /**
  60. * The database table that holds all the information
  61. * var string
  62. */
  63. var $dbTable = 'users';
  64. /**
  65. * The session variable ($_SESSION[$sessionVariable]) which will hold the data while the user is logged on
  66. * var string
  67. */
  68. var $sessionVariable = 'userSessionValue';
  69. /**
  70. * Those are the fields that our table uses in order to fetch the needed data. The structure is 'fieldType' => 'fieldName'
  71. * var array
  72. */
  73. var $tbFields = array(
  74. 'userID'=> 'userID',
  75. 'login' => 'username',
  76. 'pass' => 'password',
  77. 'email' => 'email',
  78. 'active'=> 'active'
  79. );
  80. /**
  81. * When user wants the system to remember him/her, how much time to keep the cookie? (seconds)
  82. * var int
  83. */
  84. var $remTime = 2592000;//One month
  85. /**
  86. * The name of the cookie which we will use if user wants to be remembered by the system
  87. * var string
  88. */
  89. var $remCookieName = 'ckSavePass';
  90. /**
  91. * The cookie domain
  92. * var string
  93. */
  94. var $remCookieDomain = '';
  95. /**
  96. * The method used to encrypt the password. It can be sha1, md5 or nothing (no encryption)
  97. * var string
  98. */
  99. var $passMethod = 'sha1';
  100. /**
  101. * Display errors? Set this to true if you are going to seek for help, or have troubles with the script
  102. * var bool
  103. */
  104. var $displayErrors = true;
  105. /*Do not edit after this line*/
  106. var $userID;
  107. var $dbConn;
  108. var $userData=array();
  109. /**
  110. * Class Constructure
  111. *
  112. * @param string $dbConn
  113. * @param array $settings
  114. * @return void
  115. */
  116. function flexibleAccess($dbConn = '', $settings = '')
  117. {
  118. if ( is_array($settings) ){
  119. foreach ( $settings as $k => $v ){
  120. if ( !isset( $this->{$k} ) ) die('Property '.$k.' does not exists. Check your settings.');
  121. $this->{$k} = $v;
  122. }
  123. }
  124. $this->remCookieDomain = $this->remCookieDomain == '' ? $_SERVER['HTTP_HOST'] : $this->remCookieDomain;
  125. $this->dbConn = ($dbConn=='')? mysql_connect($this->dbHost.':'.$this->dbPort, $this->dbUser, $this->dbPass):$dbConn;
  126. if ( !$this->dbConn ) die(mysql_error($this->dbConn));
  127. mysql_select_db($this->dbName, $this->dbConn)or die(mysql_error($this->dbConn));
  128. if( !isset( $_SESSION ) ) session_start();
  129. if ( !empty($_SESSION[$this->sessionVariable]) )
  130. {
  131. $this->loadUser( $_SESSION[$this->sessionVariable] );
  132. }
  133. //Maybe there is a cookie?
  134. if ( isset($_COOKIE[$this->remCookieName]) && !$this->is_loaded()){
  135. //echo 'I know you<br />';
  136. $u = unserialize(base64_decode($_COOKIE[$this->remCookieName]));
  137. $this->login($u['uname'], $u['password']);
  138. }
  139. }
  140. /**
  141. * Login function
  142. * @param string $uname
  143. * @param string $password
  144. * @param bool $loadUser
  145. * @return bool
  146. */
  147. function login($uname, $password, $remember = false, $loadUser = true)
  148. {
  149. $uname = $this->escape($uname);
  150. $password = $originalPassword = $this->escape($password);
  151. switch(strtolower($this->passMethod)){
  152. case 'sha1':
  153. $password = "SHA1('$password')"; break;
  154. case 'md5' :
  155. $password = "MD5('$password')";break;
  156. case 'nothing':
  157. $password = "'$password'";
  158. }
  159. $res = $this->query("SELECT * FROM `{$this->dbTable}`
  160. WHERE `{$this->tbFields['login']}` = '$uname' AND `{$this->tbFields['pass']}` = $password LIMIT 1",__LINE__);
  161. if ( @mysql_num_rows($res) == 0)
  162. return false;
  163. if ( $loadUser )
  164. {
  165. $this->userData = mysql_fetch_array($res);
  166. $this->userID = $this->userData[$this->tbFields['userID']];
  167. $_SESSION[$this->sessionVariable] = $this->userID;
  168. if ( $remember ){
  169. $cookie = base64_encode(serialize(array('uname'=>$uname,'password'=>$originalPassword)));
  170. $a = setcookie($this->remCookieName,
  171. $cookie,time()+$this->remTime, '/', $this->remCookieDomain);
  172. }
  173. }
  174. return true;
  175. }
  176. /**
  177. * Logout function
  178. * param string $redirectTo
  179. * @return bool
  180. */
  181. function logout($redirectTo = '')
  182. {
  183. setcookie($this->remCookieName, '', time()-3600,'/',$this->remCookieDomain);
  184. $_SESSION[$this->sessionVariable] = '';
  185. $this->userData = '';
  186. if ( $redirectTo != '' && !headers_sent()){
  187. header('Location: '.$redirectTo );
  188. exit;//To ensure security
  189. }
  190. }
  191. /**
  192. * Function to determine if a property is true or false
  193. * param string $prop
  194. * @return bool
  195. */
  196. function is($prop){
  197. return $this->get_property($prop)==1?true:false;
  198. }
  199. /**
  200. * Get a property of a user. You should give here the name of the field that you seek from the user table
  201. * @param string $property
  202. * @return string
  203. */
  204. function get_property($property)
  205. {
  206. if (empty($this->userID)) $this->error('No user is loaded', __LINE__);
  207. if (!isset($this->userData[$property])) $this->error('Unknown property <b>'.$property.'</b>', __LINE__);
  208. return $this->userData[$property];
  209. }
  210. /**
  211. * Is the user an active user?
  212. * @return bool
  213. */
  214. function is_active()
  215. {
  216. return $this->userData[$this->tbFields['active']];
  217. }
  218. /**
  219. * Is the user loaded?
  220. * @ return bool
  221. */
  222. function is_loaded()
  223. {
  224. return empty($this->userID) ? false : true;
  225. }
  226. /**
  227. * Activates the user account
  228. * @return bool
  229. */
  230. function activate()
  231. {
  232. if (empty($this->userID)) $this->error('No user is loaded', __LINE__);
  233. if ( $this->is_active()) $this->error('Allready active account', __LINE__);
  234. $res = $this->query("UPDATE `{$this->dbTable}` SET {$this->tbFields['active']} = 1
  235. WHERE `{$this->tbFields['userID']}` = '".$this->escape($this->userID)."' LIMIT 1");
  236. if (@mysql_affected_rows() == 1)
  237. {
  238. $this->userData[$this->tbFields['active']] = true;
  239. return true;
  240. }
  241. return false;
  242. }
  243. /*
  244. * Creates a user account. The array should have the form 'database field' => 'value'
  245. * @param array $data
  246. * return int
  247. */
  248. function insertUser($data){
  249. if (!is_array($data)) $this->error('Data is not an array', __LINE__);
  250. switch(strtolower($this->passMethod)){
  251. case 'sha1':
  252. $password = "SHA1('".$data[$this->tbFields['pass']]."')"; break;
  253. case 'md5' :
  254. $password = "MD5('".$data[$this->tbFields['pass']]."')";break;
  255. case 'nothing':
  256. $password = $data[$this->tbFields['pass']];
  257. }
  258. foreach ($data as $k => $v ) $data[$k] = "'".$this->escape($v)."'";
  259. $data[$this->tbFields['pass']] = $password;
  260. $this->query("INSERT INTO `{$this->dbTable}` (`".implode('`, `', array_keys($data))."`) VALUES (".implode(", ", $data).")");
  261. return (int)mysql_insert_id($this->dbConn);
  262. }
  263. /*
  264. * Creates a random password. You can use it to create a password or a hash for user activation
  265. * param int $length
  266. * param string $chrs
  267. * return string
  268. */
  269. function randomPass($length=10, $chrs = '1234567890qwertyuiopasdfghjklzxcvbnm'){
  270. for($i = 0; $i < $length; $i++) {
  271. $pwd .= $chrs{mt_rand(0, strlen($chrs)-1)};
  272. }
  273. return $pwd;
  274. }
  275. ////////////////////////////////////////////
  276. // PRIVATE FUNCTIONS
  277. ////////////////////////////////////////////
  278. /**
  279. * SQL query function
  280. * @access private
  281. * @param string $sql
  282. * @return string
  283. */
  284. function query($sql, $line = 'Uknown')
  285. {
  286. //if (defined('DEVELOPMENT_MODE') ) echo '<b>Query to execute: </b>'.$sql.'<br /><b>Line: </b>'.$line.'<br />';
  287. $res = mysql_db_query($this->dbName, $sql, $this->dbConn);
  288. if ( !res )
  289. $this->error(mysql_error($this->dbConn), $line);
  290. return $res;
  291. }
  292. /**
  293. * A function that is used to load one user's data
  294. * @access private
  295. * @param string $userID
  296. * @return bool
  297. */
  298. function loadUser($userID)
  299. {
  300. $res = $this->query("SELECT * FROM `{$this->dbTable}` WHERE `{$this->tbFields['userID']}` = '".$this->escape($userID)."' LIMIT 1");
  301. if ( mysql_num_rows($res) == 0 )
  302. return false;
  303. $this->userData = mysql_fetch_array($res);
  304. $this->userID = $userID;
  305. $_SESSION[$this->sessionVariable] = $this->userID;
  306. return true;
  307. }
  308. /**
  309. * Produces the result of addslashes() with more safety
  310. * @access private
  311. * @param string $str
  312. * @return string
  313. */
  314. function escape($str) {
  315. $str = get_magic_quotes_gpc()?stripslashes($str):$str;
  316. $str = mysql_real_escape_string($str, $this->dbConn);
  317. return $str;
  318. }
  319. /**
  320. * Error holder for the class
  321. * @access private
  322. * @param string $error
  323. * @param int $line
  324. * @param bool $die
  325. * @return bool
  326. */
  327. function error($error, $line = '', $die = false) {
  328. if ( $this->displayErrors )
  329. echo '<b>Error: </b>'.$error.'<br /><b>Line: </b>'.($line==''?'Unknown':$line).'<br />';
  330. if ($die) exit;
  331. return false;
  332. }
  333. }
  334. ?>