Skip to content

Commit

Permalink
Revert "Revert "first upload""
Browse files Browse the repository at this point in the history
This reverts commit 17966ee.
  • Loading branch information
iranianpep committed Aug 3, 2014
1 parent 17966ee commit ebbe019
Show file tree
Hide file tree
Showing 28 changed files with 1,302 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 Ehsan Abbasi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Empty file added ajax/index.html
Empty file.
42 changes: 42 additions & 0 deletions ajax/process_livesearch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

header('Access-Control-Allow-Origin: http://ajaxlivesearch.com');
header('Access-Control-Allow-Methods: *');
header('Content-Type: application/json');
header_remove('X-Powered-By');

file_exists(realpath(__DIR__ .DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'handler.php')) ? require_once(realpath(__DIR__ .DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'handler.php')) : die('There is no such a file: handler.php');

// 1. Validate all inputs
$errors = Handler::validate_input($_POST);
if (count($errors) === 0)
{
// 2. A layer of security against those Bots that submit a form quickly
if (Handler::verify_bot_searched($_POST['ls_page_loaded_at']))
{
// 3. Verify the token - CSRF protection
if (Handler::verify_session_value('token', $_POST['ls_token']) && Handler::verify_session_value('anti_bot' ,$_POST['ls_anti_bot']))
{
// 4. Start looking for the query
$result = json_encode(Handler::get_result($_POST['ls_query'], (int) $_POST['ls_current_page'], (int) $_POST['ls_items_per_page']));

// 5. Return the result
Handler::form_response('success', 'Successful request', $result);
}
else
{
// Tokens are not matched
Handler::form_response('failed', 'Error: Please refresh the page. It seems that your session is expired.');
}
}
else
{
// Searching is started sooner than the search start time offset
Handler::form_response('failed', 'Error: You are too fast, or this is a Bot. Please search now.');
}
}
else
{
// Required inputs are not provided
Handler::form_response('failed', "Error: Required or invalid inputs: " . implode(',', $errors));
}
27 changes: 27 additions & 0 deletions class/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

if(count(get_included_files()) === 1)
exit("Direct access not permitted.");

class Config
{
// ***** Database ***** //
const HOST = 'localhost';
const DATABASE = 'your_database';
const USERNAME = 'your_username';
const PASS = 'your_pass';

// ***** Table ***** //
const USER_TABLE = 'your_table';
const SEARCH_COLUMN = 'first_name';

// ***** Form ***** //
// This must be the same as form_anti_bot in script.min.js or script.js
const ANTI_BOT = "Ehsan's guard";

// Assigning more than 3 seconds is not recommended
const SEARCH_START_TIME_OFFSET = 3;

// ***** Search Input ***** //
const MAX_INPUT_LENGTH = 20;
}
36 changes: 36 additions & 0 deletions class/db.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

if(count(get_included_files()) === 1)
exit("Direct access not permitted.");

file_exists(__DIR__.DIRECTORY_SEPARATOR.'config.php') ? require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php') : die('There is no such a file: config.php');


class DB
{
private static $db;

private function __construct(){
try {
self::$db = new PDO('mysql:host='.Config::HOST.';dbname='.Config::DATABASE.';charset=utf8',Config::USERNAME,Config::PASS);
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

// To prevent PDO sql injection
// According to http://stackoverflow.com/a/12202218/2045041
self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}

public static function getConnection() {
if(!isset(self::$db))
{
new DB();
}

return self::$db;
}
}
169 changes: 169 additions & 0 deletions class/handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
<?php

if(count(get_included_files()) === 1)
exit("Direct access not permitted.");

if(session_id() == '')
session_start();

file_exists(__DIR__.DIRECTORY_SEPARATOR.'db.php') ? require_once(__DIR__.DIRECTORY_SEPARATOR.'db.php') : die('There is no such a file: db.php');
file_exists(__DIR__.DIRECTORY_SEPARATOR.'config.php') ? require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php') : die('There is no such a file: config.php');

class Handler
{

/*
* returns a 32 bits token and resets the old token if exists
*/
public static function get_token()
{
// create a form token to protect against CSRF
$token = bin2hex(openssl_random_pseudo_bytes(32));
$_SESSION['ls_session']['token'] = $token;
return $token;
}

/*
* receives a posted variable and checks it against the same one in the session
*/
public static function verify_session_value($session_parameter, $session_value)
{
$white_list = array('token', 'anti_bot');

if (in_array($session_parameter, $white_list) && $_SESSION['ls_session'][$session_parameter] === $session_value)
return true;
else
return false;
}

/*
* checks required fields, max length for search input and numbers for pagination
*/
public static function validate_input($input_array)
{
$error = array();

foreach($input_array as $k => $v)
{
if (!isset($v) || (trim($v) == "" && $v != "0") || $v == null)
{
array_push($error, $k);
}
elseif ($k === 'ls_current_page' || $k === 'ls_items_per_page')
{
if ((int) $v < 0)
array_push($error, $k);
}
elseif ($k === 'ls_query' && $v > Config::MAX_INPUT_LENGTH)
array_push($error, $k);
}

return $error;
}

/*
* forms the response object including
* status (success or failed)
* message
* result (html result)
*/
public static function form_response($status, $message, $result = '')
{
$css_class = ($status === 'failed') ? 'error' : 'success';

$message = "<tr><td class='{$css_class}'>{$message}</td></tr>";

echo json_encode(array('status' => $status, 'message' => $message, 'result' => $result));
}

public static function get_result($query, $current_page = 1, $items_per_page = 0)
{
// get connection
$db = DB::getConnection();

// get the number of total result
$stmt = $db->prepare('SELECT COUNT(id) FROM ' . Config::USER_TABLE . ' WHERE ' . Config::SEARCH_COLUMN . ' LIKE :query');
$search_query = $query.'%';
$stmt->bindParam(':query', $search_query, PDO::PARAM_STR);
$stmt->execute();
$number_of_result = $stmt->fetch(PDO::FETCH_COLUMN);

// initialize variables
$HTML = '';
$number_of_pages = 1;

if ( (int) $number_of_result !== 0)
{
if ($items_per_page === 0)
{
// show all
$stmt = $db->prepare('SELECT * FROM ' . Config::USER_TABLE . ' WHERE ' . Config::SEARCH_COLUMN . ' LIKE :query ORDER BY ' .Config::SEARCH_COLUMN);
$search_query = $query.'%';
$stmt->bindParam(':query', $search_query, PDO::PARAM_STR);
}
else
{
/*
* pagination
*
* calculate total pages
*/
if ($number_of_result < $items_per_page)
$number_of_pages = 1;
elseif ($number_of_result > $items_per_page)
$number_of_pages = floor($number_of_result / $items_per_page) + 1;
else
$number_of_pages = $number_of_result / $items_per_page;

/*
* pagination
*
* calculate start
*/
$start = ($current_page > 0 ) ? ($current_page - 1) * $items_per_page : 0;

$stmt = $db->prepare('SELECT * FROM ' . Config::USER_TABLE . ' WHERE ' . Config::SEARCH_COLUMN . ' LIKE :query ORDER BY '.Config::SEARCH_COLUMN.' LIMIT ' . $start . ', ' . $items_per_page);
$search_query = $query.'%';
$stmt->bindParam(':query', $search_query, PDO::PARAM_STR);
}

// run the query and get the result
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// generate HTML
foreach($results as $result)
{
$HTML .= "<tr><td>{$result['first_name']}</td><td>{$result['last_name']}</td><td>{$result['age']}</td><td>{$result['country']}</td></tr>";
}

}
else
{
// To prevent XSS prevention convert user input to HTML entities
$query = htmlentities($query, ENT_NOQUOTES, 'UTF-8');

// there is no result - return an appropriate message.
$HTML .= "<tr><td>There is no result for \"{$query}\"</td></tr>";
}

// form the return
return array('html' => $HTML, 'number_of_results' => (int) $number_of_result, 'total_pages' => $number_of_pages);
}

public static function get_javascript_anti_bot()
{
$_SESSION['ls_session']['anti_bot'] = Config::ANTI_BOT;
return Config::ANTI_BOT;
}

/*
* Calculate the timestamp difference between the time page is loaded
* and the time searching is started for the first time in seconds
*/
public static function verify_bot_searched($page_loaded_at)
{
// if searching starts less than start time offset it seems it's a Bot
return (time() - $page_loaded_at < Config::SEARCH_START_TIME_OFFSET) ? false : true;
}
}
Empty file added class/index.html
Empty file.
85 changes: 85 additions & 0 deletions css/animation.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
Animation example, for spinners
*/
.animate-spin {
-moz-animation: spin 2s infinite linear;
-o-animation: spin 2s infinite linear;
-webkit-animation: spin 2s infinite linear;
animation: spin 2s infinite linear;
display: inline-block;
}
@-moz-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}

100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-webkit-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}

100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-o-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}

100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-ms-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}

100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}

100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
3 changes: 3 additions & 0 deletions css/fontello-codes.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

.icon-left-circle:before { content: '\e800'; } /* '' */
.icon-right-circle:before { content: '\e801'; } /* '' */
Loading

0 comments on commit ebbe019

Please sign in to comment.