dbhost = $db_host; $this->dbuser = $db_user; $this->dbpass = $db_pass; $this->dbname = $db_name; $this->setErrorReporting($error_reporting); $this->setCharset($charset); $this->connect(); $this->initializeCharset(); } /** * Łączenie z bazą danych * * @access private */ private function connect() { if ($this->error_reporting) { $this->connection = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass, true); mysql_select_db($this->dbname) or die ('Nie można wybrać bazy'); } else { // $this->connection = @new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname); // $this->connection->select_db($this->dbname); $this->connection = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpass, true) or die ('x'); mysql_select_db($this->dbname) or die (''); } } /** * Ustawianie kodowania znaków * * @access private * @param string $charset Zestaw kodowy */ private function setCharset($charset = 'utf8') { $this->charset = $charset; } /** * Pobieranie kodowania znaków * * @access private * @return string Zestaw kodowy */ private function getCharset() { return $this->charset; } /** * Inicjalizowanie kodowania znaków w bazie danych * * @access private */ private function initializeCharset() { $this->query('SET NAMES '.$this->getCharset()); } /** * Ustawianie raportowania błędów * * @access private * @param bool $value Stan raportowania błędów */ private function setErrorReporting($value = false) { $this->error_reporting = $value; } /** * Wywołanie zapytania do bazy danych * * @access public * @param string $query Zapytanie * @return int|false Liczba wybranych/dodanych wierszy lub błąd */ public function query($query) { // new $this->flush(); $this->query = $query; $this->result = @mysql_query( $this->query, $this->connection ); if ( $this->error = mysql_error( $this->connection ) ) { $this->print_error($this->error); return false; } if ( preg_match( '/^\s*(create|alter|truncate|drop) /i', $query ) ) { $return_val = $this->result; } elseif ( preg_match( '/^\s*(insert|delete|update|replace) /i', $query ) ) { $this->rows_affected = mysql_affected_rows( $this->connection ); // Id dodawanego rekordu if ( preg_match( '/^\s*(insert|replace) /i', $query ) ) { $this->insert_id = mysql_insert_id($this->connection); } // Liczba zmienionych/dodanych rekordów $return_val = $this->rows_affected; } else // select { $i = 0; while ( $i < @mysql_num_fields( $this->result ) ) { $this->column_info[$i] = @mysql_fetch_field( $this->result ); $i++; } $num_rows = 0; while ( $row = @mysql_fetch_object( $this->result ) ) { $this->last_result[$num_rows] = $row; $num_rows++; } @mysql_free_result( $this->result ); $this->num_rows = $num_rows; $return_val = $num_rows; } return $return_val; } /** * Drukowanie na ekranie kodów błędów * * @access private * @param string $string Komunikat błędu */ private function print_error($string = '') { if ( !$string ) $string = mysql_error( $this->connection ); if ( !$this->error_reporting ) return false; $string = htmlspecialchars( $string, ENT_QUOTES ); $query = htmlspecialchars( $this->query, ENT_QUOTES ); print "

Database error: [$string]
$query

"; } /** * Pobieranie pojedynczej wartości z bazy danych * * @access public * @param string|null $query Zapytanie * @param int $x Kolumna * @param int $y Wiersz * @return string|null Rezultat zapytania lub null w przypadku błędu */ public function get_var( $query = null, $x = 0, $y = 0 ) { if ( $query ) $this->query( $query ); // Extract var out of cached results based x,y vals if ( !empty( $this->last_result[$y] ) ) { $values = array_values( get_object_vars( $this->last_result[$y] ) ); } // If there is a value return it else return null return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null; } /** * Pobieranie wiersza z bazy danych * * @access public * @param string|null $query Zapytanie * @param string $output Typ zwracanych danych, OBJECT - obiekty, ARRAY_A - tablica assocjacyjna, ARRAY_N - tablica numerowana * @param int $y Wiersz * @return mixed Rezultat zapytania lub null w przypadku błędu */ public function get_row( $query = null, $output = OBJECT, $y = 0 ) { if ( $query ) $this->query( $query ); else return null; if ( !isset( $this->last_result[$y] ) ) return null; if ( $output == OBJECT ) { return $this->last_result[$y] ? $this->last_result[$y] : null; } elseif ( $output == ARRAY_A ) { return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null; } elseif ( $output == ARRAY_N ) { return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null; } else { $this->print_error(/*GETROW_ERROR*/" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N"/*/GETROW_ERROR*/); } } /** * Pobieranie całego rezultatu zapytania z bazy danych * * @access public * @param string|null $query Zapytanie * @param string $output Typ zwracanych danych, OBJECT - obiekty, ARRAY_A - tablica assocjacyjna, ARRAY_N - tablica numerowana * @return mixed Rezultat zapytania lub null w przypadku błędu */ public function get_results( $query = null, $output = OBJECT ) { if ( $query ) $this->query( $query ); else return null; $new_array = array(); if ( $output == OBJECT ) { // Return an integer-keyed array of row objects return $this->last_result; } elseif ( $output == OBJECT_K ) { // Return an array of row objects with keys from column 1 // (Duplicates are discarded) foreach ( $this->last_result as $row ) { $key = array_shift( get_object_vars( $row ) ); if ( ! isset( $new_array[ $key ] ) ) $new_array[ $key ] = $row; } return $new_array; } elseif ( $output == ARRAY_A || $output == ARRAY_N ) { // Return an integer-keyed array of... if ( $this->last_result ) { foreach( (array) $this->last_result as $row ) { if ( $output == ARRAY_N ) { // ...integer-keyed row arrays $new_array[] = array_values( get_object_vars( $row ) ); } else { // ...column name-keyed row arrays $new_array[] = get_object_vars( $row ); } } } return $new_array; } return null; } /** * Weak escape, using addslashes() * * @see addslashes() * @access private * * @param string $string * @return string */ private function _weak_escape( $string ) { return addslashes( $string ); } /** * Real escape, using mysql_real_escape_string() or addslashes() * * @see mysql_real_escape_string() * @see addslashes() * @access private * * @param string $string to escape * @return string escaped */ private function _real_escape( $string ) { if ( $this->connection && $this->real_escape ) return mysql_real_escape_string( $string, $this->connection ); else return addslashes( $string ); } /** * Escape data. Works on arrays. * * @uses wpdb::_escape() * @uses wpdb::_real_escape() * @access private * * @param string|array $data * @return string|array escaped */ private function _escape( $data ) { if ( is_array( $data ) ) { foreach ( (array) $data as $k => $v ) { if ( is_array($v) ) $data[$k] = $this->_escape( $v ); else $data[$k] = $this->_real_escape( $v ); } } else { $data = $this->_real_escape( $data ); } return $data; } /** * Escapes content for insertion into the database using addslashes(), for security. * * Works on arrays. * * @param string|array $data to escape * @return string|array escaped as query safe string */ private function escape( $data ) { if ( is_array( $data ) ) { foreach ( (array) $data as $k => $v ) { if ( is_array( $v ) ) $data[$k] = $this->escape( $v ); else $data[$k] = $this->_weak_escape( $v ); } } else { $data = $this->_weak_escape( $data ); } return $data; } /** * Escapes content by reference for insertion into the database, for security * * @param string $string to escape * @return void */ private function escape_by_ref( &$string ) { $string = $this->_real_escape( $string ); } /** * Prepares a SQL query for safe execution. Uses sprintf()-like syntax. * * The following directives can be used in the query format string: * %d (decimal number) * %s (string) * %% (literal percentage sign - no argument needed) * * Both %d and %s are to be left unquoted in the query string and they need an argument passed for them. * Literals (%) as parts of the query must be properly written as %%. * * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string). * Does not support sign, padding, alignment, width or precision specifiers. * Does not support argument numbering/swapping. * * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}. * * Both %d and %s should be left unquoted in the query string. * * * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 ) * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' ); * * * * @param string $query Query statement with sprintf()-like placeholders * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if * being called like {@link http://php.net/sprintf sprintf()}. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like * {@link http://php.net/sprintf sprintf()}. * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string * if there was something to prepare */ private function prepare( $query = null ) { // ( $query, *$args ) if ( is_null( $query ) ) return; $args = func_get_args(); array_shift( $args ); // If args were passed as an array (as in vsprintf), move them up if ( isset( $args[0] ) && is_array($args[0]) ) $args = $args[0]; $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting $query = preg_replace( '|(? * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) ) * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) ) * * * * @param string $table table name * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. * @return int|false The number of rows inserted, or false on error. */ public function insert( $table, $data, $format = null ) { return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' ); } /** * Replace a row into a table. * * * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) ) * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) ) * * * @param string $table table name * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. * @return int|false The number of rows affected, or false on error. */ public function replace( $table, $data, $format = null ) { return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' ); } /** * Helper function for insert and replace. * * Runs an insert or replace query based on $type argument. * * @access private * @param string $table table name * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. * @return int|false The number of rows affected, or false on error. */ private function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) { if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) return false; $formats = $format = (array) $format; $fields = array_keys( $data ); $formatted_fields = array(); foreach ( $fields as $field ) { if ( !empty( $format ) ) $form = ( $form = array_shift( $formats ) ) ? $form : $format[0]; elseif ( isset( $this->field_types[$field] ) ) $form = $this->field_types[$field]; else $form = '%s'; $formatted_fields[] = $form; } $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')"; // echo $sql; return $this->query( $this->prepare( $sql, $data ) ); } public function update( $table, $data, $where, $format = null, $where_format = null ) { if ( ! is_array( $data ) || ! is_array( $where ) ) return false; $formats = $format = (array) $format; $bits = $wheres = array(); foreach ( (array) array_keys( $data ) as $field ) { if ( !empty( $format ) ) $form = ( $form = array_shift( $formats ) ) ? $form : $format[0]; elseif ( isset($this->field_types[$field]) ) $form = $this->field_types[$field]; else $form = '%s'; $bits[] = "`$field` = {$form}"; } $where_formats = $where_format = (array) $where_format; foreach ( (array) array_keys( $where ) as $field ) { if ( !empty( $where_format ) ) $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0]; elseif ( isset( $this->field_types[$field] ) ) $form = $this->field_types[$field]; else $form = '%s'; $wheres[] = "`$field` = {$form}"; } $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ); return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) ); } /** * Usunięcie rekordu z bazy danych * * @access public * @param string $table Nazwa tabeli * @param string $conditions Warunki, jakie spełniać mają usuwane rekordy * @return int|false Liczba usuniętych rekordów lub błąd */ public function delete($table, $conditions) { return $this->query("DELETE FROM $table WHERE $conditions"); } public function flush() { $this->last_result = null; $this->num_rows = 0; } public function __destruct() { @mysql_close($this->connection); } } ?> db = new database($SETTINGS['db']['host'], $SETTINGS['db']['username'], $SETTINGS['db']['password'], $SETTINGS['db']['database']); if ($this->checkSession()) { $this->setSession(); } elseif ($this->checkCookie()) { $this->setCookie(); $this->setSession(); } else $this->logged_user = null; } /** * Sprawdzanie stanu sesji * * @access private * @return bool Użytkownik zalogowany (true) lub nie (false) */ private function checkSession() { if (isSet($_SESSION['user_id']) && session_id() == $_SESSION['id']) { $this->logged_user = $_SESSION['user_id']; return true; } else return false; } /** * Ustalanie danych sesji * * @access private */ private function setSession() { $_SESSION['user_id'] = $this->logged_user; $_SESSION['id'] = session_id(); } /** * Logowanie użytkownika na podstawie podanego loginu i hasła * * @access public * @param string $login Nazwa użytkownika * @param string $password Hasło * @param bool $cookie Czy ustanowić ciasteczko * @return bool Zwraca, czy użytkownik zalogował się poprawnie (true) czy nie (false) */ public function login($oauth_uid, $provider, $cookie = true) { $result = $this->db->get_row("SELECT * FROM users WHERE oauth_provider='$provider' AND oauth_uid='$oauth_uid' AND active=1"); if (!empty($result)) { $this->logged_user = intval($result->id); $this->setSession(); if ($cookie) { $this->setCookie(); } return true; } return false; } /** * Funkcja sprawdzająca, czy jakiś użytkownik jest aktualnie zalogowany * * @access public * @return int|false Zwraca numer id zalogowanego użytkownika lub false w przypadku, gdy nikt nie jest zalogowany */ public function is_logged() { if (!empty($this->logged_user)) return intval($this->logged_user); else return false; } /** * Wylogowanie aktualnego użytkownika * * @access public */ public function logout() { unset($_COOKIE); $this->destroyCookie(); session_destroy(); $this->logged_user = null; } /** * Sprawdzanie stanu ciasteczka * * @access private * @return bool Użytkownik zalogowany (true) lub nie (false) */ private function checkCookie() { if (isSet($_COOKIE['uxid']) && isSet($_COOKIE['sxid'])) // są ciasteczka { $login = $_COOKIE['uxid']; $secret = $_COOKIE['sxid']; // sprawdzamy czy ciasteczka są poprawne, uxid - numer id użytkownika, sxid - numer secret użytkownika $result = intval($this->db->get_var("SELECT COUNT(*) FROM users WHERE id=$login AND secret='$secret' AND active=1")); if($result > 0) { $this->logged_user = $login; return true; } else return false; } else return false; } /** * Ustalanie danych ciasteczka * * @access private */ private function setCookie() { $user_id = $this->logged_user; $secret = $this->db->get_var("SELECT secret FROM users WHERE id=".$user_id); setcookie ("uxid", $user_id,time()+(3600*24*30), "/", $this->cookieDomain); setcookie ("sxid", $secret,time()+(3600*24*30), "/", $this->cookieDomain); } /** * Niszczy ciasteczka * * @access private */ private function destroyCookie() { setcookie ("uxid", "", time()-3600, "/", $this->cookieDomain); setcookie ("sxid", "", time()-3600, "/", $this->cookieDomain); } public function __destruct() { return true; } } ?>db = new database($SETTINGS['db']['host'], $SETTINGS['db']['username'], $SETTINGS['db']['password'], $SETTINGS['db']['database']); } /** * Pobieranie numeru id użytkownika na podstawie nazwy użytkownika * * @access public * @param string $nickname Nazwa użytkownika * @return int|false Id użytkownika lub false w przypadku braku użytkownika o zadanej nazwie */ public function getUserIdByNickname($nickname) { $user_id = $this->db->get_var("SELECT id FROM users WHERE nick='$nickname'"); if(!empty($user_id)) return (int)$user_id; else return false; } /** * Pobieranie numeru id użytkownika na podstawie adresu e-mail * * @access public * @param string $email Adres e-mail * @return int|false Id użytkownika lub false w przypadku braku użytkownika o zadanym adresie */ public function getUserIdByEmail($email, $type = null) { if(!$type) { $user_id = $this->db->get_var("SELECT id FROM users WHERE email='$email'"); } else { $user_id = $this->db->get_var("SELECT id FROM users WHERE email='$email' AND oauth_provider='$type'"); } if(!empty($user_id)) return (int)$user_id; else return false; } /** * Sprawdzenie czy w bazie istnieje zadany adres e-mail * * @access public * @param string $email Adres email * @return bool Wynik sprawdzenia (true/false) */ public function emailExists($email, $type = null) { if($this->getUserIdByEmail($email, $type)) return true; else return false; } /** * Sprawdzenie czy w bazie istnieje użytkownik o podanym numerze id * * @access public * @param int $user_id Numer id użytkownika * @return bool Wynik sprawdzenia (true/false) */ public function userExists($user_id) { $exists = $this->db->get_var("SELECT id FROM users WHERE id=$user_id"); if(!empty($exists)) return true; else return false; } /** * Sprawdzenie czy w bazie istnieje zadana nazwa użytkownika * * @access public * @param string $nickname Nazwa użytkownika * @return bool Wynik sprawdzenia (true/false) */ public function nicknameExists($nickname) { if($this->getUserIdByNickname($nickname)) return true; else return false; } /** * Dodanie użytkownika do bazy danych * * * user::addUser(array ('field1' => 'value1', 'field2' => 'value2') ); * * * @access public * @param array $array Tablica z parametrami do dodania oraz ich wartościami * @return int|false Liczba dodanych użytkowników lub false w przypadku niepowodzenia */ public function addUser($array) { $add = $this->db->insert( 'users', $array); if(!$add) { return $add; } return $add; //return $this->db->insert( 'users', $array); } /** * Usuwanie użytkownika z bazy danych * * @access public * @param int $user_id Numer id użytkownika do usunięcia * @return int|false Liczba usuniętych użytkowników lub false w przypadku niepowodzenia */ public function deleteUser($user_id) { return $this->db->delete( 'users', "id=$user_id"); } /** * Edycja danych użytkownika * * @access public * @param int $user_id Numer id użytkownika do edycji * @param array $data Tablica z polami do aktualizacji * @return int|false Liczba zaktualizowanych użytkowników lub false w przypadku niepowodzenia */ public function updateUser($user_id, $data) { return $this->db->update( 'users', $data, array( 'id' => $user_id ) ); } /** * Generowanie tajnego hasła * * @access public * @return string Tajne hasło dla użytkownika */ public function generateSecret() { $length = 10; $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } $string = md5($string); return $string; } public function __destruct() { unset($this->db); return true; } } ?>db = new database($SETTINGS['db']['host'], $SETTINGS['db']['username'], $SETTINGS['db']['password'], $SETTINGS['db']['database']); $row = $this->db->get_results("SELECT * FROM general_settings"); if($row) { foreach($row as $single) $array[$single->name] = $single->value; } $this->settings = $array; } /** * Pobieranie danego ustawienia * * @access public * @param string $field Nazwa szukanego parametru * @return mixed Zwraca wartość szukanego parametru */ public function get($type) { return $this->settings[$type]; } public function __destruct() { return true; } } ?>