prepareQuery();
$table 				= $config->sql_tablename_pictures();
$picpath			= $config->picture_storepath();
$fileshortcode 		= strtolower(trim($func->stripHtml($_REQUEST['s'])));
$startpage	 		= strtolower(trim($func->stripHtml($_REQUEST['m'])));
$requested_uri  	= urlencode(basename($_SERVER['REQUEST_URI']));
$stmt 				= $pdo->prepare("SELECT p_filename,p_uri FROM $table WHERE p_shortcode=:shortcode LIMIT 1");
$stmt->bindValue(':shortcode', $fileshortcode, PDO::PARAM_STR);
$stmt->execute();
$rows 				= $stmt->fetchAll(PDO::FETCH_ASSOC);
$filename			= trim($rows[0]["p_filename"]);
$source				= trim($rows[0]["p_uri"]);
$source_file    	= "$picpath/$filename";
$isMobile 			= $detect->isMobile();
$resolutions		= array(2000, 1440, 1024, 1382, 960, 760, 480, 320, 280, 230); 
$imageRetArray 		= $func->getScreenResolutionFromUA();
$x 					= $imageRetArray["x"];
$y 					= $imageRetArray["y"];
$fontsize 			= $imageRetArray["fontsize"];
$picQuality 		= $imageRetArray["picQuality"];
/* Check to see if a valid cookie exists */
if (isset($_COOKIE['resolution'])) {
  $cookie_value = floor($_COOKIE['resolution']);
  // does the cookie look valid? [whole number, comma, potential floating number]
  if (! preg_match("/^[0-9]+[,]*[0-9\.]+$/", "$cookie_value")) { // no it doesn't look valid
    setcookie("resolution", "$cookie_value", time()-100); // delete the mangled cookie
  }
  else { // the cookie is valid, do stuff with it
    $cookie_data   = explode(",", $_COOKIE['resolution']);
    $client_width  = (int) $cookie_data[0]; // the base resolution (CSS pixels)
    $total_width   = $client_width;
    $pixel_density = 1; // set a default, used for non-retina style JS snippet
    if (@$cookie_data[1]) { // the device's pixel density factor (physical pixels per CSS pixel)
      $pixel_density = $cookie_data[1];
    }
    rsort($resolutions); // make sure the supplied break-points are in reverse size order
    $resolution = $resolutions[0];//min($resolutions); // by default use the largest supported break-point
    // if pixel density is not 1, then we need to be smart about adapting and fitting into the defined breakpoints
    if($pixel_density != 1) {
      $total_width = $client_width * $pixel_density; // required physical pixel width of the image
      // the required image width is bigger than any existing value in $resolutions
      if($total_width > $resolutions[0]){
        // firstly, fit the CSS size into a break point ignoring the multiplier
        foreach ($resolutions as $break_point) { // filter down
          if ($total_width <= $break_point) {
            $resolution = $break_point;
          }
        }
        // now apply the multiplier
        $resolution = $resolution * $pixel_density;
      }
      // the required image fits into the existing breakpoints in $resolutions
      else {
        foreach ($resolutions as $break_point) { // filter down
          if ($total_width <= $break_point) {
            $resolution = $break_point;
          }
        }
      }
    }
    else { // pixel density is 1, just fit it into one of the breakpoints
      foreach ($resolutions as $break_point) { // filter down
        if ($total_width <= $break_point) {
          $resolution = $break_point;
        }
      }
    }
  }
}
/* No resolution was found (no cookie or invalid cookie) */
if (!$resolution) {
  // We send the lowest resolution for mobile-first approach, and highest otherwise
  //$resolution = $isMobile ? min($resolutions) : max($resolutions);
	$resolution = $isMobile ? min($resolutions) : 280;
}
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "google")){
	$resolution = 280; // min($resolutions);
}
/*
if (isset($startpage) && !empty($startpage)){
	$resolution = 120;
}
*
/* if the requested URL starts with a slash, remove the slash */
if(substr($requested_uri, 0,1) == "/") {
  $requested_uri = substr($requested_uri, 1);
}
/* whew might the cache file be? */
$resolution = floor($resolution);
/*
if ( stristr($_SERVER['HTTP_USER_AGENT'], "Google") !== false ){
	$resolution = 480;
}
if ($resolution > 760 ){
	$resolution = 760;
}
*/
$resolution = 280; //768;
$cache_file = $config->picture_cache_path()."/$resolution/".$fileshortcode;
//echo "cache_file=$cache_file
";
/* Use the resolution value as a path variable and check to see if an image of the same name exists at that path */
if (is_file($cache_file) && file_exists($cache_file) && is_readable($cache_file) && filesize($cache_file) >10 ) { // it exists cached at that size
 // echo "HIT cache_file=$cache_file
";
  //if ($watch_cache) { // if cache watching is enabled, compare cache and source modified dates to ensure the cache isn't stale
  //  $cache_file = $imgSrc->refreshCache($source_file, $cache_file, $resolution, $picQuality );
  //}
  $imgSrc->sendImage($cache_file, $browser_cache);
  exit(0);
}
//echo "HOT A MISS cache_file=$cache_file
";
//echo "$source_file, $cache_file";
/* It exists as a source file, and it doesn't exist cached - lets make one: */
//echo "generateImage($source_file, $cache_file, $resolution, $picQuality )";
$file 		= $imgSrc->generateImage($source_file, $cache_file, $resolution, $picQuality );
$imgSrc->sendImage($file, $browser_cache);
$stmt 				= null; // doing this is mandatory for connection to get closed
$pdo 				= null;
exit(0);
?>