Sunday, December 24, 2017

IMAGE THUMBNAILER

#!/bin/bash
#set -x 
declare -i THUMBCLOBBER=${2:-0}
declare -i REBUILDHTML=${1:-0}
declare -r THUMBNAILSIZE="100x100"
declare -r THUMBDIR=".thumb" 
declare -r IMGEXT="{jpg,jpeg,img,gif,png}"
declare -r THUMBSHTML=".thumbs.html" 
declare -r THUMBPREFIX="_thumb_"
declare -r TOGGLENULLGLOB="$(shopt -p nullglob)"
declare -r TOGGLEFAILGLOB="$(shopt -p failglob)"
declare -i CLOSEHTMLFLAG=0 

  ## any additional argument means rebuild all thumbnails 
[[ ! -z $1 ]] && THUMBCLOBBER=1
[[ ! -z $2 ]] && THUMBCLOBBER=0 && REBUILDHTML=1 

function get_html_clock() { 
cat << EOF

<script>
var clsStopwatch = function() {
  // Private vars
  var startAt = 0; // Time of last start / resume. (0 if not running)
  var lapTime = 0; // Time on the clock when last stopped in milliseconds

  var now = function() {
    return (new Date()).getTime(); 
   }; 
 
  // Public methods
  // Start or resume
  this.start = function() {
    startAt = startAt ? startAt : now();
   };

  // Stop or pause
  this.stop = function() {
    // If running, update elapsed time otherwise keep it
    lapTime = startAt ? lapTime + now() - startAt : lapTime;
    startAt = 0; // Paused
   };

  // Reset
  this.reset = function() {
    lapTime = startAt = 0;
   };

  // Duration
  this.time = function() {
    return lapTime + (startAt ? now() - startAt : 0); 
   };
};

var x = new clsStopwatch();
var \$time;
var clocktimer;

function pad(num, size) {
 var s = "0000" + num;
 return s.substr(s.length - size);
}

function formatTime(time) {
 var h = m = s = ms = 0;
 var newTime = '';

 h = Math.floor( time / (60 * 60 * 1000) );
 time = time % (60 * 60 * 1000);
 m = Math.floor( time / (60 * 1000) );
 time = time % (60 * 1000);
 s = Math.floor( time / 1000 );
 ms = time % 1000;

 newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2);
 return newTime;
}

function startTime() {
 \$time = document.getElementById('clock');
 update();
    start(); 
}

function update() {
 \$time.innerHTML = formatTime(x.time());
}

function start() {
 clocktimer = setInterval("update()", 1);
 x.start();
}

function stop() {
 x.stop();
 clearInterval(clocktimer);
}

function reset() {
 stop();
 x.reset();
 update();
}
</script>

<style type="text/css">
.clock {
    position: fixed;
    background: rgba(255,255,255,.5);
    bottom: 0px;
    padding: 10px;
    left: 40%;
    width: 180px;
}
</style>
EOF
}

[[ ! -d "$THUMBDIR" ]] && mkdir "$THUMBDIR"
if [[ ! -f "$THUMBSHTML" ]] || (($THUMBCLOBBER)) || (($REBUILDHTML)); then
 echo "Begin - searching for images, generating thumbnails and index file ... "  
 echo "<html><head><title>generated thumbs</title>$(get_html_clock)</head><body onload=\"startTime()\"><div class=\"clock\" id=\"clock\"></div>" > "$THUMBSHTML"
else 
   ## rid the last line since we will be appending.. 
 echo "Appending to existing thumbnail file $THUMBSHTML ... "  
 sed -i '$d' "$THUMBSHTML"
fi 

echo "Making thumbnails for all $IMGEXT files ... " 
## use ls not echo in the eval since the echo is eval'd and the glob needs to match we can't add a newline 
## ls will parse the glob and spit out newlines that we can use 
#set -x 
shopt -s nullglob  
shopt -s failglob

 ## Url encodes the troublesome ascii range of 20-47. 
function urlencode() { 
 ## Note, keep the % replacement all the way on the lefthand side so it doesn't 
 ## get applied to the subsequent subtitutions. \x25 the period '.' was removed 
 ## since it causes trouble to sed and isn't necessary. 
 sed 's/\x25/%25/g;s/\x20/%20/g;s/\x21/%21/g;s/\x22/%22/g;s/\x23/%23/g;s/\x5c\x24/%24/g;s/\x26/%26/g;s/\x27/%27/g;s/\x28/%28/g;s/\x29/%29/g;s/\x2A/%2A/g;s/\x2B/%2B/g;s/\x2C/%2C/g;s/\x2D/%2D/g;s/\x3A/%3A/g;s/\x3F/%3F/g;s/\x7C/%7C/g;s/\x5c\x5B/%5B/g'  <<< "${1}"
} 

while IFS= read -r -d '' each_img; do 
 THUMBNAME="${THUMBDIR}/${THUMBPREFIX}$(basename "${each_img}")" ## get the base name, we're following links
if [[ ! -f "$THUMBNAME" ]] || (($THUMBCLOBBER)) || (($REBUILDHTML)); then 
 ((! $REBUILDHTML)) && echo "Creating $THUMBNAILSIZE thumbnail for $each_img in ${PWD}/${THUMBDIR} ... "  
  ((! $REBUILDHTML)) && /usr/bin/convert -- "${each_img}" -resize "$THUMBNAILSIZE" "$THUMBNAME"  
 if (($REBUILDHTML)); then 
   if [[ -f "$THUMBNAME" ]]; then 
      echo "Rebuilding Html skipping create thumb for $THUMBNAME exists already.. " 
   else 
      echo "*** Rebuilding html file yet $THUMBNAME does not yet exist !! .. " 
      continue; ## jump to top of for loop without writing this html entry
   fi  
 fi    
   ## Encode any %'s into a percent in html, %25. URL Encode single quotes \x27->%27, #'s \x23->%23.                 
 echo "<a href='${each_img}'><img src='http://localhost:8000$(pwd)/$(urlencode "${THUMBNAME}")' alt='${each_img}'/></a>" >> "$THUMBSHTML"
 CLOSEHTMLFLAG=1 
else 
 echo "Skipping ${PWD}/${THUMBDIR} file already exists ... "
fi 
done < <(find . -maxdepth 1 \( -type f -o -type l \) ! -path .thumb \( -name '*.jpg' -o -name '*.jpeg' -o -name '*.png' -o -name '*.JPG' -o -name '*.gif' \) -exec readlink -fz {} \;);          

if (($CLOSEHTMLFLAG)); then 
 echo -en "</body></html>" >> "$THUMBSHTML"
else 
 IMAGES=$(grep -c "img src" "$THUMBSHTML") 
 if ((! ! $IMAGES)); then 
   echo "</body></html>" >> "$THUMBSHTML"
 else 
   rm "$THUMBSHTML"; # no images so html file is empty.. better to be tidy and nip it here than
 fi                  # offload to other programs that use this file..  
 echo "No images to process .. " 
fi  

eval "$TOGGLENULLGLOB"
eval "$TOGGLEFAILGLOB"
echo "Done ..."
exit 0 
alias mvthm='_(){ thumbs.bsh "$1" "$2";if [[ -f ".thumbs.html" ]];then firefox ".thumbs.html"; fi; }; _'

Monday, December 18, 2017

Simple Self-Contained RECAPTCHA Example

<!doctype html>
<html>
    <head>
        <title>Google reCAPTCHA demo</title>
        <script src='https://www.google.com/recaptcha/api.js'></script>
    </head>
    <body>
        <form method="post" action="recaptcha_test.php">
            <div class="g-recaptcha" data-sitekey="CHANGE THIS TO YOUR SITE KEY"></div>
            <input type="submit" />
        </form>
    </body>
</html>

<?php

    if($_SERVER["REQUEST_METHOD"] === "POST")
    {
        // Copy this (the html above too) to recaptcha_test.php (/tmp/recaptcha_test.php)   
        // cd to directory, start up php -S localhost:9000, 
        // then browse to http://localhost:9000/recaptcha_test.php
        
        //form submitted    

        //check if other form details are correct

        //verify captcha
        $recaptcha_secret = "CHANGE THIS TO YOUR SECRET KEY";
        $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
        $response = json_decode($response, true);
        if($response["success"] === true)
        {
            echo "Logged In Successfully";
        }
        else
        {
            echo "You are a robot";
        }
    }
?>