Thursday, 22 December 2016

PHP CSRF Guard

PHP CSRF Guard

session_start(); //if you are copying this code, this line makes it work.
function store_in_session($key,$value)
{
if (isset($_SESSION))
{
$_SESSION[$key]=$value;
}
}
function unset_session($key)
{
$_SESSION[$key]=' ';
unset($_SESSION[$key]);
}
function get_from_session($key)
{
if (isset($_SESSION[$key]))
{
return $_SESSION[$key];
}
else {  return false; }
}
function csrfguard_generate_token($unique_form_name)
{
$token = random_bytes(64); // PHP 7, or via paragonie/random_compat
store_in_session($unique_form_name,$token);
return $token;
}
function csrfguard_validate_token($unique_form_name,$token_value)
{
$token = get_from_session($unique_form_name);
if (!is_string($token_value)) {
return false;

}
$result = hash_equals($token, $token_value);
unset_session($unique_form_name);
return $result;
}
function csrfguard_replace_forms($form_data_html)
{
$count=preg_match_all("/<form(.*?)>(.*?)<\\/form>/is",$form_data_html,$matches,PREG_SET_ORDER);
if (is_array($matches))
{
foreach ($matches as $m)
{
if (strpos($m[1],"nocsrf")!==false) { continue; }
$name="CSRFGuard_".mt_rand(0,mt_getrandmax());
$token=csrfguard_generate_token($name);
$form_data_html=str_replace($m[0],
"<form{$m[1]}>
<input type='hidden' name='CSRFName' value='{$name}' />
<input type='hidden' name='CSRFToken' value='{$token}' />{$m[2]}</form>",$form_data_html);
}
}
return $form_data_html;
}
function csrfguard_inject()
{
$data=ob_get_clean();
$data=csrfguard_replace_forms($data);
echo $data;
}
function csrfguard_start()
{
if (count($_POST))
{
if ( !isset($_POST['CSRFName']) or !isset($_POST['CSRFToken']) )
{
trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR);
}
$name =$_POST['CSRFName'];
$token=$_POST['CSRFToken'];
if (!csrfguard_validate_token($name, $token))
{
throw new Exception("Invalid CSRF token.");
}
}
ob_start();
/* adding double quotes for "csrfguard_inject" to prevent:
          Notice: Use of undefined constant csrfguard_inject - assumed 'csrfguard_inject' */
register_shutdown_function("csrfguard_inject");
}
csrfguard_start();
Description and Usage
The first three functions, are an abstraction over how session variables are stored. Replace them if you don't use native PHP sessions.

The generate function, creates a random secure one-time CSRF token. If SHA512 is available, it is used, otherwise a 512 bit random string in the same format is generated. This function also stores the generated token under a unique name in session variable.

The validate function, checks under the unique name for the token. There are three states:

Sessions not active: validate succeeds (no CSRF risk)
Token found but not the same, or token not found: validation fails
Token found and the same: validation succeeds
Either case, this function removes the token from sessions, ensuring one-timeness.

The replace function, receives a portion of html data, finds all <form> occurrences and adds two hidden fields to them: CSRFName and CSRFToken. If any of these forms has an attribute or value nocsrf', the addition won't be performed (note that using default inject and detect breaks with this).

The other two functions, inject and start are a demonstration of how to use the other functions. Using output buffering on your entire output is not recommended (some libraries might dump output buffering). This default behavior, enforces CSRF tokens on all forms using POST method. It is assumed that no sensitive operations with GET method are performed in the application, as required by RFC 2616.

To test this code, append the following HTML to it:

<form method='post'>
<input type='text' name='test' value='<?php echo "testing"?>' />
<input type='submit' />
</form>

<form class='nocsrf'>
</form>

Saturday, 26 November 2016

Timestamp calculations

public static Int64 GetTimeStamp(
                        int year, int month, int day,
                        int hour, int minute, int second, int milliseconds)
{
    Int64 timestamp = DateToTicks(year, month, day)
        + TimeToTicks(hour, minute, second);

    return timestamp + milliseconds * TicksInMillisecond;
}

static readonly int[] DaysToMonth365 =
    new int[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
static readonly int[] DaysToMonth366 =
    new int[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
const long TicksInSecond = TicksInMillisecond * 1000L;
const long TicksInMillisecond = 10000L;

public static bool IsLeapYear(int year)
{
    if ((year < 1) || (year > 9999))
        throw new ArgumentOutOfRangeException("year", "Bad year.");

    if ((year % 4) != 0)
        return false;

    if ((year % 100) == 0)
        return ((year % 400) == 0);

    return true;
}

private static long DateToTicks(int year, int month, int day)
{
    if (((year >= 1) && (year <= 9999)) && ((month >= 1) && (month <= 12)))
    {
        int[] daysToMonth = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
        if ((day >= 1) && (day <= (daysToMonth[month] - daysToMonth[month - 1])))
        {
            int previousYear = year - 1;
            int daysInPreviousYears = ((((previousYear * 365) + (previousYear / 4)) - (previousYear / 100)) + (previousYear / 400));

            int totalDays = ((daysInPreviousYears + daysToMonth[month - 1]) + day) - 1;
            return (totalDays * 0xc92a69c000L);
        }
    }
    throw new ArgumentOutOfRangeException();
}

private static long TimeToTicks(int hour, int minute, int second)
{
    long totalSeconds = ((hour * 3600L) + (minute * 60L)) + second;
    if ((totalSeconds > 0xd6bf94d5e5L) || (totalSeconds < -922337203685L))
        throw new ArgumentOutOfRangeException();

    return (totalSeconds * TicksInSecond);
}

Thursday, 24 November 2016

Scroll class changer according to position

Jquery :


$('nav a').on('click', function() {

    var scrollAnchor = $(this).attr('data-scroll'),
        scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top - 28;

    $('body,html').animate({
        scrollTop: scrollPoint
    }, 500);

    return false;

})

------


$(window).scroll(function() {
    var windscroll = $(window).scrollTop();
    if (windscroll >= 100) {
        $('nav').addClass('fixed');
        $('.wrapper section').each(function(i) {
            if ($(this).position().top <= windscroll - 20) {
                $('nav a.active').removeClass('active');
                $('nav a').eq(i).addClass('active');
            }
        });

    } else {

        $('nav').removeClass('fixed');
        $('nav a.active').removeClass('active');
        $('nav a:first').addClass('active');
    }

}).scroll();


-----

html:


<header></header>

<nav>
     
    <a href="#" data-scroll="top">TOP</a>
     
    <a href="#" data-scroll="news">NEWS</a>
     
    <a href="#" data-scroll="products">PRODUCTS</a>
     
    <a href="#" data-scroll="contact">CONTACT</a>
 
</nav>

<div class="wrapper">
     
    <section id="top" data-anchor="top">
     
        <h4>TOP</h4>
     
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

            <p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>
           
    </section>
 
    <section id="news" data-anchor="news">
     
        <h4>NEWS</h4>
     
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

            <p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>
           
    </section>
 
    <section id="products" data-anchor="products">
     
        <h4>PRODUCTS</h4>
     
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

            <p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>
           
    </section>
 
    <section id="contact" data-anchor="contact">
     
        <h4>CONTACT</h4>
     
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

            <p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.</p>
           
    </section>
 
</div>


CSS
-----\

body {
    padding: 0;
    margin: 0
}

header {
    background: transparent url('http://adventure.nationalgeographic.com/2008/11/ecotourism/lodge-jungle.jpg') 0 0;
    height: 100px;
}

h4 {
   font-weight: bold;
    
}

p {
    margin: 20px 0;
}

section {
    padding: 20px 0;
}

.wrapper {
    width: 400px;
    margin: 0 auto;
    position: relative;
    padding: 28px 0 0 0;
}

nav {
    position: absolute;
    left: 0;
    right; 0;
    top: 100px;
    background: green;
    display: block;
    width: 100%;
    padding: 4px 0;
    height: 30px;
    z-index: 100;
}

nav a {
    font-family: helvetica;
    color: #ffffff;
    padding: 2px; 4px;
    display: block;
    float: left;
    text-decoration: none;
    margin-right: 4px;
}

nav a:hover,
nav a.active {
    background: white;
    color: green
}

.fixed {
    position: fixed;
    top: 0

Thursday, 17 November 2016

Jquery datatable with date range search

html and php code
----------------------
<input type="text" id="mindate"/>
<input type="text" id="maxdate"/>

            <table id="example" class="display table table-striped table-bordered " cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>Owner ID</th>
                        <th>Type</th>
                        <th>State</th>
                        <th>City</th>
                        <th>Locality</th>
                        <th>Min Price</th>
                        <th>Max Price</th>
                        <th>Created Date</th>
                        <th>Actions</th>

                    </tr>
                </thead>
                <tfoot>
                    <tr>
                           <th>Owner ID</th>
                        <th>Type</th>
                        <th>State</th>
                        <th>City</th>
                        <th>Locality</th>
                        <th>Min Price</th>
                        <th>Max Price</th>
                        <th>Created Date</th>
                        <th>Actions</th>
                    </tr>
                </tfoot>
                <tbody>
                           
                    <?php if($projectsdate){ foreach($projectsdate as $pjdata)
                    {  $date = $pjdata['created']; ?>
                 
                    <tr>
                        <td><?php echo $pjdata['ownerid'] ?></td>
                        <td><?php echo $pjdata['propertytype'] ?></td>
                        <td><?php echo $pjdata['States']['statename']?></td>
                        <td><?php echo $pjdata['Cities']['cityname'] ?></td>
                        <td><?php echo $pjdata['locality'] ?></td>
                        <td><?php echo $pjdata['minprice'] ?></td>
                        <td><?php echo $pjdata['maxprice'] ?></td>
                        <td><?php  if($date){ echo date_format($date,"d-m-Y"); } ?></td>
                        <td>Approve</td>
                    </tr>
                         
                    <?php }} ?>
                 
       
                </tbody>
            </table>


Jquery code
-----------------
<script>
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var iFini = document.getElementById('mindate').value;
var iFfin = document.getElementById('maxdate').value;
var iStartDateCol = 7;
var iEndDateCol = 7;

iFini=iFini.substring(6,10) + iFini.substring(3,5)+ iFini.substring(0,2);
iFfin=iFfin.substring(6,10) + iFfin.substring(3,5)+ iFfin.substring(0,2);

var datofini=aData[iStartDateCol].substring(6,10) + aData[iStartDateCol].substring(3,5)+ aData[iStartDateCol].substring(0,2);
var datoffin=aData[iEndDateCol].substring(6,10) + aData[iEndDateCol].substring(3,5)+ aData[iEndDateCol].substring(0,2);

if ( iFini === "" && iFfin === "" )
{
return true;
}
else if ( iFini <= datofini && iFfin === "")
{
return true;
}
else if ( iFfin >= datoffin && iFini === "")
{
return true;
}
else if (iFini <= datofini && iFfin >= datoffin)
{
return true;
}
return false;
}
);
          $(document).ready(function () {
                $('.datepicker').datepicker({
                    format: "dd-mm-yyyy"
                });
         
            });
         
$(document).ready(function() {
    var table = $('#example').DataTable();
    var table2 = $('#example').DataTable();

        // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" class="footer" placeholder="Search '+title+'" />' );
    } );
    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
 

} );
</script>

Tuesday, 4 October 2016

My ajax datatable



/** ------------------------jquery datatable ----------------------------------**/

$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var iFini = document.getElementById('min').value;
var iFfin = document.getElementById('max').value;
var iStartDateCol = 7;
var iEndDateCol = 7;

iFini=iFini.substring(6,10) + iFini.substring(3,5)+ iFini.substring(0,2);
iFfin=iFfin.substring(6,10) + iFfin.substring(3,5)+ iFfin.substring(0,2);

var datofini=aData[iStartDateCol].substring(6,10) + aData[iStartDateCol].substring(3,5)+ aData[iStartDateCol].substring(0,2);
var datoffin=aData[iEndDateCol].substring(6,10) + aData[iEndDateCol].substring(3,5)+ aData[iEndDateCol].substring(0,2);

if ( iFini === "" && iFfin === "" )
{
return true;
}
else if ( iFini <= datofini && iFfin === "")
{
return true;
}
else if ( iFfin >= datoffin && iFini === "")
{
return true;
}
else if (iFini <= datofini && iFfin >= datoffin)
{
return true;
}
return false;
}
);
          $(document).ready(function () {
                $('.datepicker').datepicker({
                    format: "dd-mm-yyyy"
                });
           
            });
           
$(document).ready(function() {
    var table = $('#example').DataTable();
    var table2 = $('#example').DataTable();

        // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" class="footer" placeholder="Search '+title+'" />' );
    } );
    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
   

} );


/** --------- Table for builder Projects----------- **/
var TableDatatablesAjax76=function(){
var a=function(){$(".date-picker").datepicker({rtl:App.isRTL(),autoclose:!0})},e=function(){
var a=new Datatable;
a.init({src:$("#datatable_ajax76"),onSuccess:function(a,e){},onError:function(a){},
onDataLoad:function(a){},loadingMessage:"Loading...",
dataTable:{bStateSave:!0,lengthMenu:[[10,20,50,100,150,-1],[10,20,50,100,150,"All"]],buttons: [
                { extend: 'print', className: 'btn dark btn-outline' },              
                { extend: 'pdf', className: 'btn green btn-outline' },
                { extend: 'excel', className: 'btn yellow btn-outline ' },
                { extend: 'csv', className: 'btn purple btn-outline ' },
            ],"dom": "<<B>><<>r><t><'row'<'col-md-5 col-sm-12'i><p>>",pageLength:10,
ajax:{url:"https://static.t2hdev.com/kontrollit/search/regstatus"},order:[[1,"asc"]]}}),
a.getTableWrapper().on("click",".table-group-action-submit",function(e){e.preventDefault();
var t=$(".table-group-action-input",a.getTableWrapper());""!=t.val()&&a.getSelectedRowsCount()>0?(a.setAjaxParam("customActionType","group_action"),a.setAjaxParam("customActionName",t.val()),
a.setAjaxParam("id",a.getSelectedRows()),a.getDataTable().ajax.reload(),
a.clearAjaxParams()):""==t.val()?App.alert({type:"danger",icon:"warning",
message:"Please select an action",

container:a.getTableWrapper(),
place:"prepend"}):0===a.getSelectedRowsCount()&&App.alert({type:"danger",
icon:"warning",
message:"No record selected",
container:a.getTableWrapper(),place:"prepend"})})};
return{init:function(){a(),e()}}}();
jQuery(document).ready(function(){TableDatatablesAjax76.init()});





var TableDatatablesAjax77=function(){
var a=function(){$(".date-picker").datepicker({rtl:App.isRTL(),autoclose:!0})},e=function(){
var a=new Datatable;
a.init({src:$("#datatable_ajax77"),onSuccess:function(a,e){},onError:function(a){},
onDataLoad:function(a){},loadingMessage:"Loading...",
dataTable:{bStateSave:!0,lengthMenu:[[10,20,50,100,150,-1],[10,20,50,100,150,"All"]],pageLength:10,

ajax:{url:"https://static.t2hdev.com/kontrollit/search/regstatus"},order:[[1,"asc"]]}}),
a.getTableWrapper().on("click",".table-group-action-submit",function(e){e.preventDefault();
var t=$(".table-group-action-input",a.getTableWrapper());""!=t.val()&&a.getSelectedRowsCount()>0?(a.setAjaxParam("customActionType","group_action"),a.setAjaxParam("customActionName",t.val()),
a.setAjaxParam("id",a.getSelectedRows()),a.getDataTable().ajax.reload(),
a.clearAjaxParams()):""==t.val()?App.alert({type:"danger",icon:"warning",
message:"Please select an action",
container:a.getTableWrapper(),
place:"prepend"}):0===a.getSelectedRowsCount()&&App.alert({type:"danger",
icon:"warning",
message:"No record selected",
container:a.getTableWrapper(),place:"prepend"})})};
return{init:function(){a(),e()}}}();
jQuery(document).ready(function(){TableDatatablesAjax77.init()});
















Thursday, 29 September 2016

  1. $(':checkbox').on('change', function(event){
  2.      if(this.checked) {
  3.       $(this).val(1);
  4.         var id = $(this).attr('id');
  5.         $("."+id).remove();
  6.                 }else{
  7.       var name = $(this).attr('name');
  8.        var cls = $(this).attr('id');
  9.        $(this).after( "<input type='hidden' name='"+name+"' class='"+cls+"' value='0'/>" );
  10.                 } 
  11.       });