[add] #465 #459 #458 #457 #455 : Make a admin interface for this feature. Not exactly the same, but same idea.

This commit is contained in:
Knah Tsaeb 2013-05-31 12:28:30 +02:00
parent c665a3cdec
commit e557660d28
15 changed files with 704 additions and 197 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
cache/* cache/*
!cache/index.html !cache/index.html
.project .project
.settings

View file

@ -1,13 +1,5 @@
AddDefaultCharset UTF-8 AddDefaultCharset UTF-8
Options -Indexes Options -Indexes
DirectoryIndex index.php index.html DirectoryIndex index.php index.html
Header set cache-control: public
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/png "access plus 1 days"
ExpiresByType image/vnd.microsoft.icon "access plus 10 years"
ExpiresByType image/x-icon "access plus 10 years"
</IfModule>
FileETag none FileETag none
SetOutputFilter DEFLATE SetOutputFilter DEFLATE

BIN
bin/error_thumb.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
bin/loadingGen_thumb.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -10,7 +10,6 @@ do
echo "#################################################" echo "#################################################"
echo "######### PRESS CTRL+C FOR STOP MONITOR #########" echo "######### PRESS CTRL+C FOR STOP MONITOR #########"
echo "#################################################" echo "#################################################"
tail '../cache/logs/logs.txt'
sleep 3 # 3 second between two refresh sleep 3 # 3 second between two refresh
done done

View file

@ -7,7 +7,7 @@ if (phantom.args.length < 2) {
} else { } else {
address = phantom.args[0]; address = phantom.args[0];
output = phantom.args[1]; output = phantom.args[1];
page.settings.userAgent = 'SoShot Agent';
page.viewportSize = { width: 1280, height: 1024 }; page.viewportSize = { width: 1280, height: 1024 };
page.open(address, function (status) { page.open(address, function (status) {

View file

@ -9,6 +9,10 @@ thumbSize=$3 # size of thumb widthxheight ex : 190x90
sizeNameDir=$4 # name of size dir sizeNameDir=$4 # name of size dir
onlyThumb=$5 # make only thumbshot no full size image onlyThumb=$5 # make only thumbshot no full size image
waitForResult=$6 # if true we try to make soon as possible or add to queue waitForResult=$6 # if true we try to make soon as possible or add to queue
##########################################
##### DON'T EDIT THIS PARAM USE #####
##### cache/config/serverOptions.php #####
##########################################
maxThread=1 # max parralle work. For me the best is nb core - 1 maxThread=1 # max parralle work. For me the best is nb core - 1
timeOut=60 # default time out, after this time the site are declared in error timeOut=60 # default time out, after this time the site are declared in error
log=false # log all generation success and error log=false # log all generation success and error
@ -20,6 +24,12 @@ firstLevel=${hashUrl:0:2}
secondLevel=${hashUrl:2:2} secondLevel=${hashUrl:2:2}
startPath=$sizeNameDir/$firstLevel/$secondLevel/ startPath=$sizeNameDir/$firstLevel/$secondLevel/
if [ $site == "manual" ]
then
site=$(cat "cache/tmp/manual.txt")
echo '' > "cache/tmp/manual.txt"
fi
mkdir -p "cache/img/$startPath" mkdir -p "cache/img/$startPath"
if [ -f "cache/config/serverOptions.php" ] if [ -f "cache/config/serverOptions.php" ]
@ -43,12 +53,18 @@ fi
start_time=`date +%s` start_time=`date +%s`
timeout $timeOut ./bin/phantomjs --disk-cache=false --local-storage-path=/bin/ --ignore-ssl-errors=true /bin/rasterize.js "$site" "cache/tmp/$hashUrl.png" timeout $timeOut ./bin/phantomjs --disk-cache=false --local-storage-path=/bin/ --ignore-ssl-errors=true /bin/rasterize.js "$site" "cache/tmp/$hashUrl.png"
if [ ! -f "cache/tmp/$hashUrl.png" ] if [ ! -f "cache/tmp/$hashUrl.png" ]
then then
echo 0 echo 0
errorCode=`echo $(curl -k --write-out %{http_code} --silent -S --connect-timeout $timeOut \--no-keepalive --output /dev/null $site)` errorCode=`echo $(curl -k --write-out %{http_code} --silent -S --connect-timeout $timeOut \--no-keepalive --output /dev/null $site)`
if [ $site == 'manual' ]
then
errorCode='manual'
fi
case $errorCode in case $errorCode in
000) cp "bin/000.png" "cache/img/$startPath""$hashUrl""_thumb.png" && cp "bin/000.png" "cache/img/$startPath""$hashUrl.png" ;; 000) cp "bin/000.png" "cache/img/$startPath""$hashUrl""_thumb.png" && cp "bin/000.png" "cache/img/$startPath""$hashUrl.png" ;;
200) cp "bin/error.png" "cache/img/$startPath""$hashUrl""_thumb.png" && cp "bin/error.png" "cache/img/$startPath""$hashUrl.png" ;;
404) cp "bin/404.png" "cache/img/$startPath""$hashUrl""_thumb.png" && cp "bin/404.png" "cache/img/$startPath""$hashUrl.png" ;; 404) cp "bin/404.png" "cache/img/$startPath""$hashUrl""_thumb.png" && cp "bin/404.png" "cache/img/$startPath""$hashUrl.png" ;;
*) cp "bin/error.png" "cache/img/$startPath""$hashUrl""_thumb.png" && cp "bin/error.png" "cache/img/$startPath""$hashUrl.png" ;; *) cp "bin/error.png" "cache/img/$startPath""$hashUrl""_thumb.png" && cp "bin/error.png" "cache/img/$startPath""$hashUrl.png" ;;
esac esac
@ -56,7 +72,12 @@ then
then then
end_time=`date +%s` end_time=`date +%s`
logDate=`date +'[%a %d %b %Y] [%H:%M:%S]'` logDate=`date +'[%a %d %b %Y] [%H:%M:%S]'`
echo $logDate `expr $end_time - $start_time`s --- ERROR --- httpstatus $errorCode --- $site >> 'cache/logs/logs.txt' if [ $errorCode == 200 ]
then
echo "none --- "$site" --- "$hashUrl" --- "$thumbSize" --- "$sizeNameDir" --- "$onlyThumb" --- true --- "$errorCode > "cache/logs/retry/"$hashUrl".log"
else
echo "none --- "$site" --- "$hashUrl" --- "$thumbSize" --- "$sizeNameDir" --- "$onlyThumb" --- true --- "$errorCode > "cache/logs/other/"$hashUrl".log"
fi
fi fi
exit exit
fi fi
@ -97,5 +118,5 @@ if $log
then then
end_time=`date +%s` end_time=`date +%s`
logDate=`date +'[%a %d %b %Y] [%H:%M:%S]'` logDate=`date +'[%a %d %b %Y] [%H:%M:%S]'`
echo $logDate `expr $end_time - $start_time`s --- $site >> 'cache/logs/logs.txt' echo $logDate `expr $end_time - $start_time`s >> 'cache/logs/success.txt'
fi fi

1
cache/index.html vendored
View file

@ -1 +0,0 @@

196
inc/admin.php Normal file
View file

@ -0,0 +1,196 @@
<?php
$acceptParam['log'] = array(
'suspect',
'success',
'other',
'retry'
);
if (isset($ui['pwd'])) {
checkAdmin($ui['pwd']);
}
if (isset($ui['log']) && !in_array($ui['log'], $acceptParam['log']) || $_SESSION['login'] !== true) {
die('Tell me, Mr Anderson, what good is a phone call if you\'re unable to speak ?');
}
if (empty($ui['log'])) {
$ui['log'] = 'success';
}
function clearLog($log) {
if (file_exists('cache/logs/'.$log.'.txt') && is_file('cache/logs/'.$log.'.txt')) {
file_put_contents('cache/logs/'.$log.'.txt', '');
}
}
function parseSuccessLog() {
if (file_exists('cache/logs/success.txt')) {
$file = fopen('cache/logs/success.txt', "r");
$res = '';
if (!empty($file)) {
while (!feof($file)) {
$currentLine = trim(fgets($file));
$currentLine = explode(' ', $currentLine);
$currentLine = str_replace('s', '', $currentLine);
if (!empty($currentLine[5])) {
$res['genTime'][] = $currentLine[5];
}
}
} else {
$res['genTime'] = array();
}
fclose($file);
return $res;
}
}
function parseFailLog($log) {
if (empty($log) || ($log !== 'suspect' && $log !== 'retry' && $log !== 'other')) {
die('Are you sure about this.');
}
$res = '';
$list = glob('cache/logs/'.$log.'/*.log');
if (!empty($list)) {
foreach ($list as $value) {
$line = file_get_contents($value);
$line = trim($line);
$line = explode(' --- ', $line);
if (!empty($line[7])) {
$res[] = array(
$line[1],
$line[2],
$line[4],
'Error '.$line[7].' - '
);
} else {
$res[] = array(
$line[1],
$line[2],
$line[4],
''
);
}
}
}
return $res;
}
function manualGen($hash, $log) {
$line = file_get_contents('cache/logs/'.$log.'/'.$hash.'.log');
$line = trim($line);
$line = explode(' --- ', $line);
$hash = sha1($GLOBALS['config']['salt'].rawurldecode($line[1]));
file_put_contents('cache/tmp/manual.txt', $line[1]);
exec('bin/thumb_server.sh manual '.escapeshellarg($hash).' '.escapeshellarg($line[3]).' '.escapeshellarg($line[4]).' 0 1', $result);
if ((int)$result[0] === 1) {
$res['success'] = 1;
$res['filePath'] = pathForFile($line[4], $hash).'.png';
return $res;
}
}
function delAndRegen($hash, $size) {
$path = pathForFile($size, $hash);
if (file_exists($path.'.png')) {
unlink($path.'.png');
}
if (file_exists($path.'_thumb.png')) {
unlink($path.'_thumb.png');
}
}
function tryRootDomain($hash, $log) {
$line = file_get_contents('cache/logs/'.$log.'/'.$hash.'.log');
$line = trim($line);
$line = explode(' --- ', $line);
$hash = sha1($GLOBALS['config']['salt'].rawurldecode($line[1]));
$parts = parse_url($line[1]);
$url = $parts['scheme'].'://'.trim($parts['host']);
file_put_contents('cache/tmp/manual.txt', $url);
exec('bin/thumb_server.sh manual '.escapeshellarg($hash).' '.escapeshellarg($line[3]).' '.escapeshellarg($line[4]).' 0 1', $result);
if ((int)$result[0] === 1) {
$res['success'] = 1;
$res['filePath'] = pathForFile($line[4], $hash).'.png';
return $res;
}
}
function keepThisThumb($hash, $log) {
unlink('cache/logs/'.$log.'/'.$hash.'.log');
}
if (isset($ui['clear']) && (int)$ui['clear'] === 1) {
clearLog($ui['log']);
}
?>
<div class="hMenu">
<ul>
<li>
<a href="?p=admin&log=success">Success</a>
</li>
<li>
<a href="?p=admin&log=suspect">Suspect</a>
</li>
<li>
<a href="?p=admin&log=retry">Retry</a>
</li>
<li>
<a href="?p=admin&log=other">Other error</a>
</li>
<li>
<a href="?logout=1">Logout</a>
</li>
</ul>
</div>
<div id="log">
<?php
if ($ui['log'] === 'success') {
$logs = parseSuccessLog();
if (!empty($logs)) {
$nbThumb = 0;
$nbThumb = count($logs['genTime']);
echo 'Total request : ', $nbThumb, '</br>';
echo 'Moyenne per request : ', round(array_sum($logs['genTime']) / $nbThumb, 2), 's (min (', min($logs['genTime']), 's) max (', max($logs['genTime']), 's))</br>';
} else {
echo 'No result';
}
echo '<p class="clear" ><a href="?p=admin&log=success&clear=1">Clear success log</a></p>';
}
if ($ui['log'] === 'suspect' || $ui['log'] === 'retry' || $ui['log'] === 'other') {
if (isset($ui['hash']) && !empty($ui['hash'])) {
$ui['hash'] = validHash($ui['hash']);
if (isset($ui['root']) && (int)$ui['root'] === 1) {
$success = tryRootDomain($ui['hash'], $ui['log']);
}
if (isset($ui['cache']) && (int)$ui['cache'] === 1) {
$success['filePath'] = pathForFile($ui['s'], $ui['hash']).'.png';
}
if (isset($ui['keep']) && (int)$ui['keep'] === 1) {
keepThisThumb($ui['hash'], $ui['log']);
}
if (isset($ui['mGen']) && (int)$ui['mGen'] === 1)
$success = manualGen($ui['hash'], $ui['log']);
}
$logs = parseFailLog($ui['log']);
if (!empty($logs)) {
echo '<ul>';
foreach ($logs as $value) {
echo '<li>', htmlentities(strip_tags($value['3'])), htmlentities(strip_tags($value['0'])), '</br><a href="?p=admin&log=', $ui['log'], '&hash=', $value['1'], '&mGen=1">manuel launch</a> <a href="', htmlentities(strip_tags($value['0'])), '">view site</a> <a href="?p=admin&log=', $ui['log'], '&hash=', $value['1'], '&cache=1&s=', $value['2'], '">view image in cache</a></li>';
}
echo '</ul>';
} else {
echo 'No result';
}
}
echo '</div>';
if (!empty($success)) {
echo '<div id="result">';
echo '<img src="', $success['filePath'], '?r=', time(), '" style="width:100%;"/>';
echo '<p><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['filePath'], '" onclick="this.select()"/></p>';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&root=1">Try with root domain</a> / ';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&keep=1">Keep this thumbshot</a>';
echo '</div>';
}
?>

41
inc/index.php Normal file
View file

@ -0,0 +1,41 @@
<form method="post">
<p>
<input type="url" placeholder="<?php echo $defUrl; ?>" value="<?php echo $defUrl; ?>" name="url"/>
</p>
<p>
<label>Size</label>
<select name="s">
<?php
foreach ($GLOBALS['config']['thumbSize'] as $key => $value) {
if ($value === $width) {
echo '<option value="', $key, '" selected="selected">', $value, '</option>';
} else {
echo '<option value="', $key, '">', $value, '</option>';
}
}
?>
</select>
</p>
<p>
<label>Force refresh</label>
<input type="checkbox" value="1" name="fr" />
</p>
<p>
<input type="hidden" name="token" value="<?php echo genToken(); ?>" />
<input type="submit" value="Generate"/>
</p>
<p class="info">
<a href="http://forge.leslibres.org/projects/soshot">Homepage</a>
</p>
</form>
<?php
if (!empty($success)) {
echo '<div id="result">';
echo '<h3>This image will be removed in ', $GLOBALS['config']['expireCache'], 'h</h3>';
echo '<img src="data:image/png;base64,',base64_encode(file_get_contents($success['thumb'])), '"/>';
echo '<p><label>Thumbshot</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['thumb'], '" onclick="this.select()"/>';
if ($GLOBALS['config']['onlyThumb'] === false) {
echo '<p><label>1280x1024</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['thumb'], '" onclick="this.select()"/></p>';
}
echo '</div>';
}

32
inc/install.php Normal file
View file

@ -0,0 +1,32 @@
<?php
if(file_exists('cache/config/genConf.php') && $GLOBALS['config']['pwd'] !== 'install'){
die ('Seriously Dude, Where\'s My Car ?');
}
if(isset($ui['passOne'])){
savePass($ui['passOne'], $ui['passTwo'], $ui['token']);
}
?>
<div class="message">
This is the key for generate thumbnail whith GET method. Save it !
<p class="alert">
<?php
echo $serverKey;
?>
</p>
</div>
<form action="?" method="post">
<p>
<label>Password</label>
<input type="password" name="passOne" />
</p>
<p>
<label>Confirm</label>
<input type="password" name="passTwo" />
</p>
<p>
<input type="hidden" name="token" value="<?php echo genToken();?>"/>
<input type="hidden" name="p" value="install"/>
<input type="submit">
</p>
</form>

11
inc/login.php Normal file
View file

@ -0,0 +1,11 @@
<form action="?" method="post">
<p>
<label>Password</label>
<input type="password" name="pwd" />
</p>
<p>
<input type="hidden" name="token" value="<?php echo genToken();?>"/>
<input type="hidden" name="p" value="admin" />
<input type="submit">
</p>
</form>

View file

@ -6,11 +6,24 @@ html {
background-color: #dedede; background-color: #dedede;
} }
form, #result, #header{ a {
text-decoration: none;
color:#8AC007;
}
a:hover {
text-decoration: underline;
}
a:visited {
color : #8AC007;
}
form, #result, #header, .message, .hMenu, #log {
padding: 1em; padding: 1em;
text-align: center; text-align: center;
width: 50%; width: 50%;
margin: 0 auto; margin: 1em auto;
background-color: #ffffff; background-color: #ffffff;
border-radius: 5px; border-radius: 5px;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.50), 0 85px 180px 0 #FFFFFF, 0 12px 8px -5px rgba(0, 0, 0, 0.95); box-shadow: 0 0 8px rgba(0, 0, 0, 0.50), 0 85px 180px 0 #FFFFFF, 0 12px 8px -5px rgba(0, 0, 0, 0.95);
@ -55,6 +68,31 @@ form .info {
border-radius: 5px; border-radius: 5px;
} }
.message {
background-color: orange;
}
.hMenu li {
display: inline-block;
font-size: 1.2em;
}
.hMenu li:after {
content: " / ";
}
.hMenu li:last-child:after {
content: "";
}
.clear {
text-align: right;
}
#log li {
text-align: left;
}
@media screen and (min-width: 320px) and (max-width: 800px) { @media screen and (min-width: 320px) and (max-width: 800px) {
html { html {

479
index.php
View file

@ -1,6 +1,8 @@
<?php <?php
if (empty($_SESSION)) {
session_start(); session_start();
if (empty($_SESSION['login'])) {
$_SESSION['login'] = false;
} }
// change if you want no inpact // change if you want no inpact
date_default_timezone_set('Europe/Paris'); date_default_timezone_set('Europe/Paris');
@ -8,16 +10,16 @@ date_default_timezone_set('Europe/Paris');
$GLOBALS['config']['onlyLocalServer'] = false; $GLOBALS['config']['onlyLocalServer'] = false;
// No form for post url only acces by GET method // No form for post url only acces by GET method
$GLOBALS['config']['NoWebPage'] = false; $GLOBALS['config']['NoWebPage'] = false;
// After 3 criticla error ban user // After 3 critical error ban user
$GLOBALS['config']['maxErrorBeforeBan'] = 3; $GLOBALS['config']['maxErrorBeforeBan'] = 3;
// Ban for 60 minutes // Ban for 60 minutes
$GLOBALS['config']['banTime'] = 60; $GLOBALS['config']['banTime'] = 60;
// default url for form // default url for form
$GLOBALS['config']['defaultUrl'] = 'https://google.com'; $GLOBALS['config']['defaultUrl'] = 'https://duckduckgo.com/';
// default size for thumbnail // default size for thumbnail
$GLOBALS['config']['defaultThumbSize'] = '120x90'; $GLOBALS['config']['defaultThumbSize'] = '120x90';
// generate only thumbnail or generate thumbnail + 1280x1024 image // generate only thumbnail or generate thumbnail + 1280x1024 image
$GLOBALS['config']['onlyThumb'] = TRUE; $GLOBALS['config']['onlyThumb'] = true;
// list of available size for thumb // list of available size for thumb
$GLOBALS['config']['thumbSize'] = array( $GLOBALS['config']['thumbSize'] = array(
's' => '120x90', 's' => '120x90',
@ -28,13 +30,63 @@ $GLOBALS['config']['thumbSize'] = array(
); );
// Remove image older than 12 hours // Remove image older than 12 hours
$GLOBALS['config']['expireCache'] = 12; $GLOBALS['config']['expireCache'] = 12;
// Disable exec command for launch script and use cron task
$GLOBALS['config']['disableExec'] = false;
// Enable log for success, suspect, error
$GLOBALS['config']['log'] = false;
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
if (!empty($_POST)) {
$ui = $_POST;
$ui['request'] = 'form';
$ui['iw'] = 1;
unset($_POST);
}
if (!empty($_GET)) {
$ui = $_GET;
$ui['request'] = 'api';
unset($_GET);
}
if (empty($ui['request'])) {
$ui['request'] = '';
}
if (empty($ui['p'])) {
$ui['p'] = 'index';
}
if (empty($ui['fr'])) {
$ui['fr'] = '';
}
if (isset($ui['logout']) && (int)$ui['logout'] === 1) {
session_destroy();
header("Location:?");
exit();
}
if (!file_exists('cache/config/genConf.php')) { if (!file_exists('cache/config/genConf.php')) {
install(); $serverKey = install();
$ui['p'] = 'install';
} }
require 'cache/config/genConf.php'; require 'cache/config/genConf.php';
$ui = '';
if ($GLOBALS['config']['pwd'] === 'install' && $ui['p'] !== 'install') {
reloadInstall();
header("Location:?");
}
if (($GLOBALS['config']['onlyLocalServer'] === true && $_SERVER['REMOTE_ADDR'] !== '127.0.0.1') || checkIfBan() === true) { if (($GLOBALS['config']['onlyLocalServer'] === true && $_SERVER['REMOTE_ADDR'] !== '127.0.0.1') || checkIfBan() === true) {
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
@ -50,17 +102,6 @@ if ($GLOBALS['config']['NoWebPage'] === true && empty($_GET)) {
exit(); exit();
} }
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
function testExistImg($file) { function testExistImg($file) {
if ($GLOBALS['config']['onlyThumb'] === true) { if ($GLOBALS['config']['onlyThumb'] === true) {
if (file_exists($file.'_thumb.png')) { if (file_exists($file.'_thumb.png')) {
@ -83,10 +124,10 @@ function testExistImg($file) {
* @author Knah Tsaeb * @author Knah Tsaeb
* @date 2013-02-12 * @date 2013-02-12
* @param $url (string) url for thumbshot * @param $url (string) url for thumbshot
* @param $hashUrl (md5) md5($url) * @param $hashUrl (hash) hash($url)
* @param $width (string) size of thumbnail 190x90 * @param $width (string) size of thumbnail 190x90
* @param $onlyThumb (bool) * @param $onlyThumb (bool)
* @param $waiForResult (bool) * @param $waitForResult (bool)
* @return * @return
*/ */
function launchScript($url, $hashUrl, $width, $size, $onlyThumb, $waitForResult = false) { function launchScript($url, $hashUrl, $width, $size, $onlyThumb, $waitForResult = false) {
@ -99,11 +140,15 @@ function launchScript($url, $hashUrl, $width, $size, $onlyThumb, $waitForResult
$onlyThumb = 0; $onlyThumb = 0;
} }
if ($GLOBALS['config']['disableExec'] === false) {
if ($waitForResult === false) { if ($waitForResult === false) {
exec('bin/thumb_server.sh '.$url.' '.$hashUrl.' '.$width.' '.$size.' '.$onlyThumb.' > /dev/null &', $result); exec('bin/thumb_server.sh '.$url.' '.$hashUrl.' '.$width.' '.$size.' '.$onlyThumb.' > /dev/null &', $result);
} else { } else {
exec('bin/thumb_server.sh '.$url.' '.$hashUrl.' '.$width.' '.$size.' '.$onlyThumb.' 1', $result); exec('bin/thumb_server.sh '.$url.' '.$hashUrl.' '.$width.' '.$size.' '.$onlyThumb.' 1', $result);
} }
} else {
return 0;
}
return $result; return $result;
} }
@ -126,11 +171,12 @@ function testValidUrl($url) {
function genToken() { function genToken() {
$token = sha1(uniqid(rand(), true).'_'.mt_rand()); $token = sha1(uniqid(rand(), true).'_'.mt_rand());
$_SESSION['token'] = $token; $_SESSION['token'] = $token;
$_SESSION['tokenTime'] = time();
return $token; return $token;
} }
function verifToken($token) { function verifToken($token) {
if ($token !== $_SESSION['token']) { if ($token !== $_SESSION['token'] || $_SESSION['tokenTime'] <= time() - 24000) {
ban(); ban();
die('So Long, and Thanks for All the Fish.'); die('So Long, and Thanks for All the Fish.');
} }
@ -173,16 +219,25 @@ function install() {
if (!is_writable('cache')) { if (!is_writable('cache')) {
die('Make dir "cache" writable'); die('Make dir "cache" writable');
} }
if (!mkdir('cache/config', 0705)) { if (!is_dir('cache/config') && !mkdir('cache/config', 0705)) {
die('Error on create dir "cache/config".'); die('Error on create dir "cache/config".');
} }
if (!mkdir('cache/img', 0705)) { if (!is_dir('cache/img') && !mkdir('cache/img', 0705)) {
die('Error on create dir "cache/img".'); die('Error on create dir "cache/img".');
} }
if (!mkdir('cache/logs', 0705)) { if (!is_dir('cache/logs') && !mkdir('cache/logs', 0705)) {
die('Error on create dir "cache/logs".'); die('Error on create dir "cache/logs".');
} }
if (!mkdir('cache/tmp', 0705)) { if (!is_dir('cache/logs/suspect') && !mkdir('cache/logs/suspect', 0705)) {
die('Error on create dir "cache/logs/suspect".');
}
if (!is_dir('cache/logs/retry') && !mkdir('cache/logs/retry', 0705)) {
die('Error on create dir "cache/logs/retry".');
}
if (!is_dir('cache/logs/other') && !mkdir('cache/logs/other', 0705)) {
die('Error on create dir "cache/logs/other".');
}
if (!is_dir('cache/tmp') && !mkdir('cache/tmp', 0705)) {
die('Error on create dir "cache/tmp".'); die('Error on create dir "cache/tmp".');
} }
$salt = sha1(uniqid(rand(), true).'_'.mt_rand()); $salt = sha1(uniqid(rand(), true).'_'.mt_rand());
@ -190,28 +245,24 @@ function install() {
$encryptServerKey = sha1($serverKey.$salt); $encryptServerKey = sha1($serverKey.$salt);
if (!is_file('cache/config/genConf.php')) { if (!is_file('cache/config/genConf.php')) {
file_put_contents('cache/config/genConf.php', "<?php\n\$GLOBALS['config']['serverKey'] = '$encryptServerKey';\n\$GLOBALS['config']['salt'] = '$salt';\n?>"); file_put_contents('cache/config/genConf.php', "<?php\n\$GLOBALS['config']['serverKey'] = '$encryptServerKey';\n\$GLOBALS['config']['salt'] = '$salt';\n\$GLOBALS['config']['pwd'] = 'install';\n?>");
} }
if (!is_file('cache/config/serverOptions.php')) { if (!is_file('cache/config/serverOptions.php')) {
touch('cache/config/serverOptions.php'); touch('cache/config/serverOptions.php');
} }
if (!is_file('cache/index.html')) {
touch('cache/index.html');
}
if (!is_file('cache/config/options.php')) { if (!is_file('cache/config/options.php')) {
file_put_contents('cache/config/options.php', "<?php\n\n?>"); file_put_contents('cache/config/options.php', "<?php\n\n?>");
} }
if (!is_file('cache/logs/banUser.php')) { if (!is_file('cache/logs/banUser.php')) {
file_put_contents('cache/logs/banUser.php', "<?php\n\n?>"); file_put_contents('cache/logs/banUser.php', "<?php\n\n?>");
} }
if (!is_file('cache/logs/log.txt')) { $GLOBALS['config']['serverKey'] = $encryptServerKey;
touch('cache/logs/log.txt'); $GLOBALS['config']['salt'] = $salt;
} $GLOBALS['config']['pwd'] = 'install';
echo ' return $serverKey;
<div>
This is the key for generate thumbnail whith GET method. Save it, this key is secret, don\'t share it.
<p class="alert">
', $serverKey, '
</p>
</div>';
checkInstall();
} }
function checkInstall() { function checkInstall() {
@ -229,7 +280,7 @@ function checkInstall() {
} }
} }
function removeOlderThan($dir = 'cache/img/shortLived') { function removeOlderThan($dir = 'cache/img/shortLive') {
if (is_dir($dir)) { if (is_dir($dir)) {
$objects = scandir($dir); $objects = scandir($dir);
foreach ($objects as $object) { foreach ($objects as $object) {
@ -247,84 +298,174 @@ function removeOlderThan($dir = 'cache/img/shortLived') {
} }
} }
checkInstall(); function pathForFile($size, $hashUrl) {
removeOlderThan();
if ($_GET) {
$ui = $_GET;
unset($_GET);
if (empty($ui['key']) || empty($ui['url'])) {
die('Are you Ken ?');
}
if (sha1($ui['key'].$GLOBALS['config']['salt']) !== $GLOBALS['config']['serverKey']) {
ban();
die('I take a chips and give it to Godzilla. I print a shoes and .............. KAMOULOX ! Well done Jean Pierre.');
}
if (!array_key_exists($ui['s'], $GLOBALS['config']['thumbSize'])) {
die('Die another day !');
}
$ui['url'] = rawurldecode($ui['url']);
$testUrl = testValidUrl($ui['url']);
if ($testUrl !== true) {
header("Content-type: image/png");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo file_get_contents('bin/error.png');
exit();
}
$defUrl = $ui['url'];
if (isset($ui['s']) && array_key_exists($ui['s'], $GLOBALS['config']['thumbSize'])) {
$width = $GLOBALS['config']['thumbSize'][$ui['s']];
} else {
$width = $GLOBALS['config']['defaultThumbSize'];
}
$hashUrl = sha1($GLOBALS['config']['serverKey'].$defUrl);
$startPath = substr($hashUrl, 0, 2).'/'.substr($hashUrl, 2, 2).'/'; $startPath = substr($hashUrl, 0, 2).'/'.substr($hashUrl, 2, 2).'/';
$file = 'cache/img/'.$ui['s'].'/'.$startPath.$hashUrl; $file = 'cache/img/'.$size.'/'.$startPath.$hashUrl;
return $file;
}
if (testExistImg($file) !== true || isset($ui['fr']) && (int)$ui['fr'] === 1) { function validHash($hash) {
if (isset($ui['iw']) && (int)$ui['iw'] === 1) { if (empty($hash)) {
launchScript($defUrl, $hashUrl, $width, $ui['s'], $GLOBALS['config']['onlyThumb'], true); die('You talking to me');
}
if (!preg_match('/^[0-9a-f]{40}$/i', $hash)) {
die('I don\'t understand biiip bip bip biiiip bip bip bip biiiiiiip biip ...');
}
return $hash;
}
function checkAdmin($pwd) {
$pwd = sha1($GLOBALS['config']['salt'].$pwd.$GLOBALS['config']['serverKey']);
if (validHash($pwd) !== $GLOBALS['config']['pwd']) {
ban();
die('1, 2, 3, 4, 5 ? That\'s amazing ! I\'ve got the same combination on my luggage !');
}
$_SESSION['login'] = true;
return true;
}
function savePass($passOne, $passTwo, $token) {
verifToken($token);
if ($passOne !== $passTwo || empty($passOne) || empty($passTwo)) {
reloadInstall();
} else { } else {
$res = launchScript($defUrl, $hashUrl, $width, $ui['s'], $GLOBALS['config']['onlyThumb'], false); $GLOBALS['config']['pwd'] = sha1($GLOBALS['config']['salt'].$passOne.$GLOBALS['config']['serverKey']);
header("Content-type: image/png"); $confServerKey = $GLOBALS['config']['serverKey'];
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); $confSalt = $GLOBALS['config']['salt'];
echo file_get_contents('bin/loadingGen.png'); $confPwd = $GLOBALS['config']['pwd'];
exit(); $confFile = '
<?php
$GLOBALS[\'config\'][\'serverKey\'] = \''.$confServerKey.'\';
$GLOBALS[\'config\'][\'salt\'] = \''.$confSalt.'\';
$GLOBALS[\'config\'][\'pwd\'] = \''.$confPwd.'\';
?>';
file_put_contents('cache/config/genConf.php',$confFile);
} }
header("Location:?");
} }
function reloadInstall() {
array_map('unlink', glob("cache/config/*"));
}
/**
* Améliore la sortie print
*
* @author Tatane http://www.tatane.info/index.php/print_rn
* @author http://www.blog.cactuscrew.com/77-print_rn.html
* @param $data (array) tableau ou variable à examiner
* @param $name (string) nom a afficher
* @return false affiche les clef valeur du tableau $data
* @example n_print($array, 'Tableau de valeur');
*/
function n_print($data, $name = '') {
$aBackTrace = debug_backtrace();
echo '<h2>', $name, '</h2>';
echo '<fieldset style="border: 1px solid orange; padding: 5px;color: #333; background-color: #fff;">';
echo '<legend style="border:1px solid orange;padding: 1px;background-color:#eee;color:orange;">
', basename($aBackTrace[0]['file']), ' ligne => ', $aBackTrace[0]['line'], '
</legend>';
echo '<pre>', htmlentities(print_r($data, 1)), '</pre>';
echo '
</fieldset>
<br />
';
}
function printThumbShot($file) {
ob_end_clean();
header("Content-type: image/png"); header("Content-type: image/png");
header('Expires: ', gmdate('D, d M Y H:i:s', time()).' GMT'); header('Expires: ', gmdate('D, d M Y H:i:s', time()).' GMT');
if (!empty($ui['t']) && $ui['t'] === 'full') {
echo file_get_contents($file.'.png');
} else {
echo file_get_contents($file.'_thumb.png'); echo file_get_contents($file.'_thumb.png');
}
exit() ; exit() ;
} }
if ($_POST) { function getPage($page) {
$ui = $_POST; $page = htmlspecialchars($page);
unset($_POST); switch ($page) {
if (empty($ui['url'])) { case 'login' :
die('No url, no thumb'); return 'inc/login.php';
break;
case 'install' :
return 'inc/install.php';
break;
case 'admin' :
return 'inc/admin.php';
break;
default :
return 'inc/index.php';
break;
} }
verifToken($ui['token']);
$ui['url'] = rawurldecode($ui['url']);
$testUrl = testValidUrl($ui['url']);
if ($testUrl !== true) {
echo $testUrl['msg'];
exit();
} }
if (!array_key_exists($ui['s'], $GLOBALS['config']['thumbSize'])) { function testIfImg($url) {
die('Die another day !'); $ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'png' || $ext === 'gif') {
return $ext;
} else {
return false;
}
} }
$defUrl = $ui['url']; function makeImgThumb($url, $ext, $hashUrl, $width, $path, $onlyThumb) {
if (!function_exists('imagecreatefromjpeg')) {
return false;
}
$image = file_get_contents($url);
$fullSize = file_put_contents('cache/tmp/'.$hashUrl.'.'.$ext, $image);
if ($ext === 'jpg' || $ext === 'jpeg') {
$tmpImg = imagecreatefromjpeg('cache/tmp/'.$hashUrl.'.'.$ext);
}
if ($ext === 'png') {
$tmpImg = imagecreatefrompng('cache/tmp/'.$hashUrl.'.'.$ext);
}
if ($ext === 'gif') {
$tmpImg = imagecreatefromgif('cache/tmp/'.$hashUrl.'.'.$ext);
}
if (!$tmpImg) {
unlink('cache/tmp/'.$hashUrl.'.'.$ext);
return false;
}
$w = imagesx($tmpImg);
$h = imagesy($tmpImg);
$ystart = 0;
$yheight = $h;
if ($h > $w) { $ystart = ($h / 2) - ($w / 2);
$yheight = $w / 2;
}
$nh = min(floor(($h * $width) / $w), $width);
$im2 = imagecreatetruecolor($width, $nh);
imagecopyresampled($im2, $tmpImg, 0, 0, 0, $ystart, $width, $nh, $w, $yheight);
$tempname = 'cache/tmp/'.$hashUrl.'_TEMP.png';
imagepng($im2, $tempname, 9);
if (!is_dir($path)) {
mkdir($path, 0775, true);
}
imagedestroy($tmpImg);
imagedestroy($im2);
unlink('cache/tmp/'.$hashUrl.'.'.$ext);
rename($tempname, $path.$hashUrl.'_thumb.png');
if (file_exists($path.$hashUrl.'_thumb.png')) {
return true;
} else {
return false;
}
}
/*
$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //save the image on your server
*
*
*/
checkInstall();
removeOlderThan();
if (empty($defUrl)) {
$defUrl = $GLOBALS['config']['defaultUrl'];
}
if (isset($ui['s']) && array_key_exists($ui['s'], $GLOBALS['config']['thumbSize'])) { if (isset($ui['s']) && array_key_exists($ui['s'], $GLOBALS['config']['thumbSize'])) {
$width = $GLOBALS['config']['thumbSize'][$ui['s']]; $width = $GLOBALS['config']['thumbSize'][$ui['s']];
@ -332,76 +473,110 @@ if ($_POST) {
$width = $GLOBALS['config']['defaultThumbSize']; $width = $GLOBALS['config']['defaultThumbSize'];
} }
$hashUrl = sha1($GLOBALS['config']['serverKey'].$defUrl); // Generate or return img
$startPath = substr($hashUrl, 0, 2).'/'.substr($hashUrl, 2, 2).'/'; if (!empty($ui['request']) && $ui['p'] !== 'install' && $ui['p'] !== 'login' && $ui['p'] !== 'admin') {
$file = 'cache/img/shortLived/'.$startPath.$hashUrl; if (empty($ui['url'])) {
die('You see in this world there\'s two kinds of people, my friend. Those with loaded guns, and those who dig. You dig.');
if (testExistImg($file) !== true || isset($ui['fr']) && (int)$ui['fr'] === 1) {
launchScript($defUrl, $hashUrl, $width, 'shortLived', $GLOBALS['config']['onlyThumb'], true);
} }
$ui['url'] = trim(rawurldecode($ui['url']));
$ui['url'] = rtrim($ui['url'], '/');
$hashUrl = sha1($GLOBALS['config']['salt'].$ui['url']);
$startPath = substr($hashUrl, 0, 2).'/'.substr($hashUrl, 2, 2).'/';
$file = 'cache/img/'.$ui['s'].'/'.$startPath.$hashUrl;
$testUrl = testValidUrl($ui['url']);
$defUrl = $ui['url'];
if ($ui['request'] === 'form') {
$file = 'cache/img/shortLive/'.$startPath.$hashUrl;
$file = 'cache/img/shortLive/'.$startPath.$hashUrl;
}
if (testExistImg($file) === true && (int)$ui['fr'] !== 1) {
if ($ui['request'] === 'api') {
printThumbShot($file);
}
if ($ui['request'] === 'form') {
$success = array( $success = array(
'normal' => $file.'.png', 'normal' => $file.'.png',
'thumb' => $file.'_thumb.png' 'thumb' => $file.'_thumb.png'
); );
} }
} else {
if (empty($defUrl)) { if ($ui['request'] === 'api') {
$defUrl = $GLOBALS['config']['defaultUrl']; if (empty($ui['key']) || empty($ui['url'])) {
die('Are you Ken ?');
}
if (sha1($ui['key'].$GLOBALS['config']['salt']) !== $GLOBALS['config']['serverKey']) {
ban();
die('I take a chips and give it to Godzilla. I give high kick in Chuck Norris face and I go to ... Humm .... Ehh .... Arg ....... KAMOULOX ! Well done Jean Pierre.');
}
} else {
verifToken($ui['token']);
}
if ($testUrl !== true) {
if (!file_exists('cache/logs/'.$hashUrl.'log')) {
file_put_contents('cache/logs/suspect/'.$hashUrl.'.log', $_SERVER['REMOTE_ADDR'].' --- '.$ui['url'].' --- '.$hashUrl.' --- '.$width.' --- '.$ui['s'].' --- '.$GLOBALS['config']['onlyThumb'].' --- true'."\n");
}
if ($ui['request'] === 'api') {
printThumbShot('bin/error');
} else {
$success = array(
'normal' => 'bin/error.png',
'thumb' => 'bin/error_thumb.png'
);
}
} else {
$ext = testIfImg($ui['url']);
if ($ext !== false) {
$genWidth = explode("x", $width);
if ($ui['request'] === 'api') {
$makeImg = makeImgThumb($ui['url'], $ext, $hashUrl, $genWidth[0], 'cache/img/'.$ui['s'].'/'.$startPath, $GLOBALS['config']['onlyThumb']);
} else {
$makeImg = makeImgThumb($ui['url'], $ext, $hashUrl, $genWidth[0], 'cache/img/shortLive/'.$startPath, $GLOBALS['config']['onlyThumb']);
}
if ($makeImg === true) {
$GLOBALS['config']['disableExec'] = true;
if ($ui['request'] === 'api') {
printThumbShot($file);
} else {
$success = array(
'normal' => $file.'.png',
'thumb' => $file.'_thumb.png'
);
}
}
}
if ((isset($ui['iw']) && (int)$ui['iw'] === 1 && $ui['request'] === 'api')) {
$res = launchScript($defUrl, $hashUrl, $width, $ui['s'], $GLOBALS['config']['onlyThumb'], true);
} elseif ((isset($ui['iw']) && (int)$ui['iw'] === 1 && $ui['request'] === 'form')) {
$res = launchScript($defUrl, $hashUrl, $width, 'shortLive', $GLOBALS['config']['onlyThumb'], true);
} else {
$res = launchScript($defUrl, $hashUrl, $width, $ui['s'], $GLOBALS['config']['onlyThumb'], false);
}
if ($ui['request'] === 'api') {
$file = 'bin/loadingGen';
printThumbShot($file);
} else {
$success = array(
'normal' => $file.'.png',
'thumb' => $file.'_thumb.png'
);
}
}
} }
if (empty($width)) {
$width = $GLOBALS['config']['defaultThumbSize'];
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>KT WebThumb</title> <title>SoShot</title>
<meta name="description" content="My web thumbnailer"> <meta name="description" content="Personal webshot">
<link rel="stylesheet" href="inc/style.css"> <link rel="stylesheet" href="inc/style.css">
</head> </head>
<body> <body>
<form method="post">
<p>
<input type="url" placeholder="<?php echo $defUrl; ?>" value="<?php echo $defUrl; ?>" name="url"/>
</p>
<p>
<label>Size</label>
<select name="s">
<?php <?php
foreach ($GLOBALS['config']['thumbSize'] as $key => $value) { require getPage($ui['p']);
if ($value === $width) {
echo '<option value="', $key, '" selected="selected">', $value, '</option>';
} else {
echo '<option value="', $key, '">', $value, '</option>';
}
}
?>
</select>
</p>
<p>
<label>Force refresh</label>
<input type="checkbox" value="1" name="fr" />
</p>
<p>
<input type="hidden" name="token" value="<?php echo genToken(); ?>" />
<input type="submit" value="Generate"/>
</p>
<p class="info">
<a href="http://forge.leslibres.org/projects/soshot">Homepage</a>
</p>
</form>
<?php
if (!empty($success)) {
echo '<div id="result">';
echo '<h3>This image will removed in 24h</h3>';
echo '<img src="', $success['thumb'], '?r=', time(), '"/>';
echo '<p><label>', $width, '</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['thumb'], '" onclick="this.select()"/></p>';
if ($GLOBALS['config']['onlyThumb'] === false) {
echo '<p><label>1280x1024</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['normal'], '" onclick="this.select()"/></p>';
}
}
echo '</div>';
?> ?>
</body> </body>
</html> </html>

2
robots.txt Normal file
View file

@ -0,0 +1,2 @@
User-agent: *
Disallow: /