<?php
/**
 * Print to PDF
 *
 * Requires: wkhtmltopdf installed (http://code.google.com/p/wkhtmltopdf)
 */

define('WKHTMLTOPDF_BIN', '/usr/local/bin/wkhtmltopdf');

define('MATRIX_SESSIONS_ENABLED',false);
$allowed_urls = array(
    'fedtraining.clients.squiz.net',
    'www.federationtraining.edu.au',
    'federationtraining.edu.au',
   'www.tafegippsland.edu.au',
   'tafegippsland.edu.au'
  );

define('DEFAULT_PDF_NAME','Page');

// Is the user logged in?
if (MATRIX_SESSIONS_ENABLED) {
  // We need to start matrix and do some quick permission/session checking
  require_once '../../core/include/init.inc';
  
  if (!isset($_SESSION['userid'])) {
      die('Script used out of context unexpectedly');
  }// End if
}// End if

// The script needs the url parameter
if (!isset($_GET['url'])) {
    die('Expecting url query parameter');
}// End if

// The url we receive will probably be encoded to allow query params like
// ?SQ_DESIGN_NAME= to be passed
$url = urldecode($_GET['url']);
$name = isset( $_GET['name'] ) ? urldecode( $_GET['name'] ) : DEFAULT_PDF_NAME;
$safeUrl = escapeshellarg($url);
$coreUrl = array_pop(array_reverse(explode('?',preg_replace('/^http(s)?:\/\//','',$url))));

// Permission check against the URL
if (MATRIX_SESSIONS_ENABLED) {
  $asset = $GLOBALS['SQ_SYSTEM']->am->getAssetFromURL('http',$coreUrl);
  if (!$asset) {
      die(); // Matrix will output an error for this, just kill the script
  }// End if
  
  if (!$asset->readAccess()) {
      die('You do not have permissons to generate a pdf for this page');
  }// End if
}

// Do a url check against the micor site
$domain = array_shift(explode('/',$coreUrl));
if (!in_array( $domain, $allowed_urls )) {
    die("The supplied URL is not valid.");
}// End if

// Run wkhtmltopdf to create a temporary file
$path = dirname(__FILE__) . "/tmp_" . time() . ".pdf";

$command = WKHTMLTOPDF_BIN . " $safeUrl $path";

if (!is_file(WKHTMLTOPDF_BIN)) {
   die('The utility "wkhtmltopdf" may not been installed on this server. http://code.google.com/p/wkhtmltopdf');
}// End if

exec($command);
if (!is_file($path)) {
    die(time() . ' ERROR: Failed to generate PDF for this page');
}// End if

$content = file_get_contents($path);

header('Content-Type: application/pdf');
header('Content-Length: ' . strlen($content));
header('Content-Disposition: inline; filename="' . $name . '.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');

// Remove the temporary file
unlink($path);

die($content);
?>
