Merge branch 'master' into prng, resolve merge conflicts

This commit is contained in:
rugk
2016-08-15 18:15:57 +02:00
47 changed files with 1971 additions and 347 deletions

View File

@@ -50,8 +50,8 @@ class Configuration
'languageselection' => false,
'languagedefault' => '',
'urlshortener' => '',
'vizhash' => true,
'cspheader' => 'default-src \'none\'; connect-src *; script-src \'self\'; style-src \'self\'; font-src \'self\'; img-src \'self\';',
'icon' => 'identicon',
'cspheader' => 'default-src \'none\'; connect-src *; script-src \'self\'; style-src \'self\'; font-src \'self\'; img-src \'self\' data:;',
'zerobincompatibility' => false,
),
'expire' => array(
@@ -98,7 +98,7 @@ class Configuration
*/
public function __construct()
{
$config = array();
$config = array();
$configFile = PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.ini';
if (is_readable($configFile)) {
$config = parse_ini_file($configFile, true);

View File

@@ -71,7 +71,7 @@ class Database extends AbstractData
public static function getInstance($options = null)
{
// if needed initialize the singleton
if (!(self::$_instance instanceof Database)) {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self;
}
@@ -89,17 +89,17 @@ class Database extends AbstractData
array_key_exists('opt', $options)
) {
// set default options
$options['opt'][PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$options['opt'][PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$options['opt'][PDO::ATTR_EMULATE_PREPARES] = false;
$options['opt'][PDO::ATTR_PERSISTENT] = true;
$db_tables_exist = true;
$options['opt'][PDO::ATTR_PERSISTENT] = true;
$db_tables_exist = true;
// setup type and dabase connection
self::$_type = strtolower(
substr($options['dsn'], 0, strpos($options['dsn'], ':'))
);
$tableQuery = self::_getTableQuery(self::$_type);
self::$_db = new PDO(
self::$_db = new PDO(
$options['dsn'],
$options['usr'],
$options['pwd'],
@@ -168,8 +168,8 @@ class Database extends AbstractData
}
$opendiscussion = $burnafterreading = false;
$attachment = $attachmentname = '';
$meta = $paste['meta'];
$attachment = $attachmentname = '';
$meta = $paste['meta'];
unset($meta['postdate']);
$expire_date = 0;
if (array_key_exists('expire_date', $paste['meta'])) {
@@ -222,14 +222,14 @@ class Database extends AbstractData
!array_key_exists($pasteid, self::$_cache)
) {
self::$_cache[$pasteid] = false;
$paste = self::_select(
$paste = self::_select(
'SELECT * FROM ' . self::_sanitizeIdentifier('paste') .
' WHERE dataid = ?', array($pasteid), true
);
if (false !== $paste) {
// create object
self::$_cache[$pasteid] = new stdClass;
self::$_cache[$pasteid] = new stdClass;
self::$_cache[$pasteid]->data = $paste['data'];
$meta = json_decode($paste['meta']);
@@ -253,9 +253,9 @@ class Database extends AbstractData
self::$_cache[$pasteid]->attachmentname = $paste['attachmentname'];
}
}
self::$_cache[$pasteid]->meta = $meta;
self::$_cache[$pasteid]->meta = $meta;
self::$_cache[$pasteid]->meta->postdate = (int) $paste['postdate'];
$expire_date = (int) $paste['expiredate'];
$expire_date = (int) $paste['expiredate'];
if (
$expire_date > 0
) {
@@ -368,12 +368,12 @@ class Database extends AbstractData
$comments = array();
if (count($rows)) {
foreach ($rows as $row) {
$i = $this->getOpenSlot($comments, (int) $row['postdate']);
$comments[$i] = new stdClass;
$comments[$i]->id = $row['dataid'];
$comments[$i]->parentid = $row['parentid'];
$comments[$i]->data = $row['data'];
$comments[$i]->meta = new stdClass;
$i = $this->getOpenSlot($comments, (int) $row['postdate']);
$comments[$i] = new stdClass;
$comments[$i]->id = $row['dataid'];
$comments[$i]->parentid = $row['parentid'];
$comments[$i]->data = $row['data'];
$comments[$i]->meta = new stdClass;
$comments[$i]->meta->postdate = (int) $row['postdate'];
if (array_key_exists('nickname', $row) && !empty($row['nickname'])) {
$comments[$i]->meta->nickname = $row['nickname'];
@@ -415,7 +415,7 @@ class Database extends AbstractData
protected function _getExpiredPastes($batchsize)
{
$pastes = array();
$rows = self::_select(
$rows = self::_select(
'SELECT dataid FROM ' . self::_sanitizeIdentifier('paste') .
' WHERE expiredate < ? LIMIT ?', array(time(), $batchsize)
);
@@ -440,7 +440,7 @@ class Database extends AbstractData
private static function _exec($sql, array $params)
{
$statement = self::$_db->prepare($sql);
$result = $statement->execute($params);
$result = $statement->execute($params);
$statement->closeCursor();
return $result;
}
@@ -486,7 +486,7 @@ class Database extends AbstractData
$sql = 'SELECT tabname FROM systables ';
break;
case 'mssql':
$sql = "SELECT name FROM sysobjects "
$sql = 'SELECT name FROM sysobjects '
. "WHERE type = 'U' ORDER BY name";
break;
case 'mysql':
@@ -496,22 +496,22 @@ class Database extends AbstractData
$sql = 'SELECT table_name FROM all_tables';
break;
case 'pgsql':
$sql = "SELECT c.relname AS table_name "
. "FROM pg_class c, pg_user u "
$sql = 'SELECT c.relname AS table_name '
. 'FROM pg_class c, pg_user u '
. "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
. "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
. 'AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) '
. "AND c.relname !~ '^(pg_|sql_)' "
. "UNION "
. "SELECT c.relname AS table_name "
. "FROM pg_class c "
. 'UNION '
. 'SELECT c.relname AS table_name '
. 'FROM pg_class c '
. "WHERE c.relkind = 'r' "
. "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
. "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
. 'AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) '
. 'AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) '
. "AND c.relname !~ '^pg_'";
break;
case 'sqlite':
$sql = "SELECT name FROM sqlite_master WHERE type='table' "
. "UNION ALL SELECT name FROM sqlite_temp_master "
. 'UNION ALL SELECT name FROM sqlite_temp_master '
. "WHERE type='table' ORDER BY name";
break;
default:
@@ -569,7 +569,7 @@ class Database extends AbstractData
private static function _createPasteTable()
{
list($main_key, $after_key) = self::_getPrimaryKeyClauses();
$dataType = self::$_type === 'pgsql' ? 'TEXT' : 'BLOB';
$dataType = self::$_type === 'pgsql' ? 'TEXT' : 'BLOB';
self::$_db->exec(
'CREATE TABLE ' . self::_sanitizeIdentifier('paste') . ' ( ' .
"dataid CHAR(16) NOT NULL$main_key, " .
@@ -594,7 +594,7 @@ class Database extends AbstractData
private static function _createCommentTable()
{
list($main_key, $after_key) = self::_getPrimaryKeyClauses();
$dataType = self::$_type === 'pgsql' ? 'text' : 'BLOB';
$dataType = self::$_type === 'pgsql' ? 'text' : 'BLOB';
self::$_db->exec(
'CREATE TABLE ' . self::_sanitizeIdentifier('comment') . ' ( ' .
"dataid CHAR(16) NOT NULL$main_key, " .

View File

@@ -13,6 +13,7 @@
namespace PrivateBin\Data;
use PrivateBin\Model\Paste;
use PrivateBin\Json;
/**
* Filesystem
@@ -48,7 +49,7 @@ class Filesystem extends AbstractData
self::$_dir = $options['dir'] . DIRECTORY_SEPARATOR;
}
// if needed initialize the singleton
if (!(self::$_instance instanceof Filesystem)) {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self;
self::_init();
}
@@ -61,6 +62,7 @@ class Filesystem extends AbstractData
* @access public
* @param string $pasteid
* @param array $paste
* @throws Exception
* @return bool
*/
public function create($pasteid, $paste)
@@ -72,7 +74,7 @@ class Filesystem extends AbstractData
if (!is_dir($storagedir)) {
mkdir($storagedir, 0700, true);
}
return (bool) file_put_contents($storagedir . $pasteid, json_encode($paste));
return (bool) file_put_contents($storagedir . $pasteid, Json::encode($paste));
}
/**
@@ -153,19 +155,20 @@ class Filesystem extends AbstractData
* @param string $parentid
* @param string $commentid
* @param array $comment
* @throws Exception
* @return bool
*/
public function createComment($pasteid, $parentid, $commentid, $comment)
{
$storagedir = self::_dataid2discussionpath($pasteid);
$filename = $pasteid . '.' . $commentid . '.' . $parentid;
$filename = $pasteid . '.' . $commentid . '.' . $parentid;
if (is_file($storagedir . $filename)) {
return false;
}
if (!is_dir($storagedir)) {
mkdir($storagedir, 0700, true);
}
return (bool) file_put_contents($storagedir . $filename, json_encode($comment));
return (bool) file_put_contents($storagedir . $filename, Json::encode($comment));
}
/**
@@ -178,7 +181,7 @@ class Filesystem extends AbstractData
public function readComments($pasteid)
{
$comments = array();
$discdir = self::_dataid2discussionpath($pasteid);
$discdir = self::_dataid2discussionpath($pasteid);
if (is_dir($discdir)) {
// Delete all files in discussion directory
$dir = dir($discdir);
@@ -189,13 +192,13 @@ class Filesystem extends AbstractData
// - parentid is the comment this comment replies to (It can be pasteid)
if (is_file($discdir . $filename)) {
$comment = json_decode(file_get_contents($discdir . $filename));
$items = explode('.', $filename);
$items = explode('.', $filename);
// Add some meta information not contained in file.
$comment->id = $items[1];
$comment->id = $items[1];
$comment->parentid = $items[2];
// Store in array
$key = $this->getOpenSlot($comments, (int) $comment->meta->postdate);
$key = $this->getOpenSlot($comments, (int) $comment->meta->postdate);
$comments[$key] = $comment;
}
}
@@ -233,7 +236,7 @@ class Filesystem extends AbstractData
*/
protected function _getExpiredPastes($batchsize)
{
$pastes = array();
$pastes = array();
$firstLevel = array_filter(
scandir(self::$_dir),
'self::_isFirstLevelDir'
@@ -241,7 +244,7 @@ class Filesystem extends AbstractData
if (count($firstLevel) > 0) {
// try at most 10 times the $batchsize pastes before giving up
for ($i = 0, $max = $batchsize * 10; $i < $max; ++$i) {
$firstKey = array_rand($firstLevel);
$firstKey = array_rand($firstLevel);
$secondLevel = array_filter(
scandir(self::$_dir . $firstLevel[$firstKey]),
'self::_isSecondLevelDir'
@@ -254,7 +257,7 @@ class Filesystem extends AbstractData
}
$secondKey = array_rand($secondLevel);
$path = self::$_dir . $firstLevel[$firstKey] .
$path = self::$_dir . $firstLevel[$firstKey] .
DIRECTORY_SEPARATOR . $secondLevel[$secondKey];
if (!is_dir($path)) {
continue;
@@ -267,7 +270,7 @@ class Filesystem extends AbstractData
continue;
}
$thirdKey = array_rand($thirdLevel);
$pasteid = $thirdLevel[$thirdKey];
$pasteid = $thirdLevel[$thirdKey];
if (in_array($pasteid, $pastes)) {
continue;
}

View File

@@ -77,7 +77,7 @@ class Filter
public static function formatHumanReadableSize($size)
{
$iec = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
$i = 0;
$i = 0;
while (($size / 1024) >= 1) {
$size = $size / 1024;
$i++;

View File

@@ -114,8 +114,8 @@ class I18n
$args = func_get_args();
if (is_array(self::$_translations[$messageId])) {
$number = (int) $args[1];
$key = self::_getPluralForm($number);
$max = count(self::$_translations[$messageId]) - 1;
$key = self::_getPluralForm($number);
$max = count(self::$_translations[$messageId]) - 1;
if ($key > $max) {
$key = $max;
}
@@ -143,7 +143,7 @@ class I18n
// check if the lang cookie was set and that language exists
if (array_key_exists('lang', $_COOKIE) && in_array($_COOKIE['lang'], $availableLanguages)) {
$match = $availableLanguages[array_search($_COOKIE['lang'], $availableLanguages)];
$match = $_COOKIE['lang'];
}
// find a translation file matching the browsers language preferences
else {
@@ -153,7 +153,7 @@ class I18n
}
// load translations
self::$_language = $match;
self::$_language = $match;
self::$_translations = ($match == 'en') ? array() : json_decode(
file_get_contents(self::_getPath($match . '.json')),
true
@@ -319,7 +319,7 @@ class I18n
protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
{
$matches = array();
$any = false;
$any = false;
foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
$acceptedQuality = floatval($acceptedQuality);
if ($acceptedQuality === 0.0) {
@@ -372,7 +372,7 @@ class I18n
{
$a = explode('-', $a);
$b = explode('-', $b);
for ($i=0, $n = min(count($a), count($b)); $i < $n; ++$i) {
for ($i = 0, $n = min(count($a), count($b)); $i < $n; ++$i) {
if ($a[$i] !== $b[$i]) {
break;
}

48
lib/Json.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
/**
* PrivateBin
*
* a zero-knowledge paste bin
*
* @link https://github.com/PrivateBin/PrivateBin
* @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
* @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
* @version 0.22
*/
namespace PrivateBin;
use Exception;
/**
* Json
*
* Provides JSON functions in an object oriented way.
*/
class Json
{
/**
* Returns a string containing the JSON representation of the given input
*
* @access public
* @static
* @param mixed $input
* @throws Exception
* @return string
*/
public static function encode($input)
{
$jsonString = json_encode($input);
$errorCode = json_last_error();
if ($errorCode === JSON_ERROR_NONE) {
return $jsonString;
}
$message = 'A JSON error occurred';
if (function_exists('json_last_error_msg')) {
$message .= ': ' . json_last_error_msg();
}
$message .= ' (' . $errorCode . ')';
throw new Exception($message, 90);
}
}

View File

@@ -67,9 +67,9 @@ abstract class AbstractModel
*/
public function __construct(Configuration $configuration, AbstractData $storage)
{
$this->_conf = $configuration;
$this->_store = $storage;
$this->_data = new stdClass;
$this->_conf = $configuration;
$this->_store = $storage;
$this->_data = new stdClass;
$this->_data->meta = new stdClass;
}

View File

@@ -10,11 +10,12 @@
* @version 0.22
*/
namespace PrivateBin\model;
namespace PrivateBin\Model;
use PrivateBin\Sjcl;
use PrivateBin\Persistence\TrafficLimiter;
use PrivateBin\Vizhash16x16;
use Identicon\Identicon;
use Exception;
/**
@@ -132,7 +133,7 @@ class Comment extends AbstractModel
*/
public function setPaste(Paste $paste)
{
$this->_paste = $paste;
$this->_paste = $paste;
$this->_data->meta->pasteid = $paste->getId();
}
@@ -192,17 +193,26 @@ class Comment extends AbstractModel
}
$this->_data->meta->nickname = $nickname;
if ($this->_conf->getKey('vizhash')) {
// Generation of the anonymous avatar (Vizhash):
// If a nickname is provided, we generate a Vizhash.
// (We assume that if the user did not enter a nickname, he/she wants
// to be anonymous and we will not generate the vizhash.)
$vh = new Vizhash16x16();
$pngdata = $vh->generate(TrafficLimiter::getIp());
if ($pngdata != '') {
$this->_data->meta->vizhash = 'data:image/png;base64,' . base64_encode($pngdata);
// If a nickname is provided, we generate an icon based on a SHA512 HMAC
// of the users IP. (We assume that if the user did not enter a nickname,
// the user wants to be anonymous and we will not generate an icon.)
$icon = $this->_conf->getKey('icon');
if ($icon != 'none') {
$pngdata = '';
$hmac = TrafficLimiter::getHash();
if ($icon == 'identicon') {
$identicon = new Identicon();
$pngdata = $identicon->getImageDataUri($hmac, 16);
} elseif ($icon == 'vizhash') {
$vh = new Vizhash16x16();
$pngdata = 'data:image/png;base64,' . base64_encode(
$vh->generate($hmac)
);
}
if ($pngdata != '') {
$this->_data->meta->vizhash = $pngdata;
}
// Once the avatar is generated, we do not keep the IP address, nor its hash.
}
// Once the icon is generated, we do not keep the IP address hash.
}
}

View File

@@ -62,11 +62,11 @@ class Paste extends AbstractModel
if (!property_exists($data->meta, 'salt')) {
$data->meta->salt = ServerSalt::get();
}
$data->comments = array_values($this->getComments());
$data->comment_count = count($data->comments);
$data->comments = array_values($this->getComments());
$data->comment_count = count($data->comments);
$data->comment_offset = 0;
$data->{'@context'} = 'js/paste.jsonld';
$this->_data = $data;
$data->{'@context'} = 'js/paste.jsonld';
$this->_data = $data;
return $this->_data;
}
@@ -85,7 +85,7 @@ class Paste extends AbstractModel
}
$this->_data->meta->postdate = time();
$this->_data->meta->salt = serversalt::generate();
$this->_data->meta->salt = serversalt::generate();
// store paste
if (
@@ -247,7 +247,7 @@ class Paste extends AbstractModel
throw new Exception('Invalid data.', 73);
}
$this->_data->meta->burnafterreading = true;
$this->_data->meta->opendiscussion = false;
$this->_data->meta->opendiscussion = false;
}
}
@@ -296,7 +296,7 @@ class Paste extends AbstractModel
*
* @access public
* @throws Exception
* @return boolean
* @return bool
*/
public function isBurnafterreading()
{
@@ -313,7 +313,7 @@ class Paste extends AbstractModel
*
* @access public
* @throws Exception
* @return boolean
* @return bool
*/
public function isOpendiscussion()
{

View File

@@ -119,7 +119,7 @@ abstract class AbstractPersistence
protected static function _store($filename, $data)
{
self::_initialize();
$file = self::$_path . DIRECTORY_SEPARATOR . $filename;
$file = self::$_path . DIRECTORY_SEPARATOR . $filename;
$writtenBytes = @file_put_contents($file, $data, LOCK_EX);
if ($writtenBytes === false || $writtenBytes < strlen($data)) {
throw new Exception('unable to write to file ' . $file, 13);

View File

@@ -72,8 +72,8 @@ class PurgeLimiter extends AbstractPersistence
return true;
}
$file = 'purge_limiter.php';
$now = time();
$file = 'purge_limiter.php';
$now = time();
$content = '<?php' . PHP_EOL . '$GLOBALS[\'purge_limiter\'] = ' . $now . ';' . PHP_EOL;
if (!self::_exists($file)) {
self::_store($file, $content);

View File

@@ -73,15 +73,16 @@ class TrafficLimiter extends AbstractPersistence
}
/**
* get the current visitors IP address
* get a HMAC of the current visitors IP address
*
* @access public
* @static
* @param string $algo
* @return string
*/
public static function getIp()
public static function getHash($algo = 'sha512')
{
return $_SERVER[self::$_ipKey];
return hash_hmac($algo, $_SERVER[self::$_ipKey], ServerSalt::get());
}
/**
@@ -101,8 +102,6 @@ class TrafficLimiter extends AbstractPersistence
return true;
}
$ip = hash_hmac('sha256', self::getIp(), ServerSalt::get());
$file = 'traffic_limiter.php';
if (!self::_exists($file)) {
self::_store(
@@ -115,20 +114,22 @@ class TrafficLimiter extends AbstractPersistence
$path = self::getPath($file);
require $path;
$now = time();
$tl = $GLOBALS['traffic_limiter'];
$tl = $GLOBALS['traffic_limiter'];
// purge file of expired IPs to keep it small
// purge file of expired hashes to keep it small
foreach ($tl as $key => $time) {
if ($time + self::$_limit < $now) {
unset($tl[$key]);
}
}
if (array_key_exists($ip, $tl) && ($tl[$ip] + self::$_limit >= $now)) {
// this hash is used as an array key, hence a shorter hash is used
$hash = self::getHash('sha256');
if (array_key_exists($hash, $tl) && ($tl[$hash] + self::$_limit >= $now)) {
$result = false;
} else {
$tl[$ip] = time();
$result = true;
$tl[$hash] = time();
$result = true;
}
self::_store(
$file,

View File

@@ -168,14 +168,14 @@ class PrivateBin
file_put_contents(
PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
'Allow from none' . PHP_EOL .
'Deny from all'. PHP_EOL,
'Deny from all' . PHP_EOL,
LOCK_EX
);
}
}
$this->_conf = new Configuration;
$this->_model = new Model($this->_conf);
$this->_conf = new Configuration;
$this->_model = new Model($this->_conf);
$this->_request = new Request;
$this->_urlBase = array_key_exists('REQUEST_URI', $_SERVER) ?
htmlspecialchars($_SERVER['REQUEST_URI']) : '/';
@@ -223,8 +223,8 @@ class PrivateBin
);
}
$data = $this->_request->getParam('data');
$attachment = $this->_request->getParam('attachment');
$data = $this->_request->getParam('data');
$attachment = $this->_request->getParam('attachment');
$attachmentname = $this->_request->getParam('attachmentname');
// Ensure content is not too big.
@@ -247,7 +247,7 @@ class PrivateBin
}
// The user posts a comment.
$pasteid = $this->_request->getParam('pasteid');
$pasteid = $this->_request->getParam('pasteid');
$parentid = $this->_request->getParam('parentid');
if (!empty($pasteid) && !empty($parentid)) {
$paste = $this->_model->getPaste($pasteid);
@@ -365,7 +365,7 @@ class PrivateBin
try {
$paste = $this->_model->getPaste($dataid);
if ($paste->exists()) {
$data = $paste->get();
$data = $paste->get();
$this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date');
if (property_exists($data->meta, 'salt')) {
unset($data->meta->salt);
@@ -407,7 +407,7 @@ class PrivateBin
// label all the expiration options
$expire = array();
foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
$expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)): Filter::formatHumanReadableTime($time);
$expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
}
// translate all the formatter options
@@ -462,7 +462,7 @@ class PrivateBin
$type = '';
}
$content = '{}';
$file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
$file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
if (is_readable($file)) {
$content = str_replace(
'?jsonld=',
@@ -492,7 +492,7 @@ class PrivateBin
if ($status) {
$result['message'] = I18n::_($message);
} else {
$result['id'] = $message;
$result['id'] = $message;
$result['url'] = $this->_urlBase . '?' . $message;
}
$result += $other;

View File

@@ -16,7 +16,7 @@ namespace PrivateBin;
* Request
*
* parses request parameters and provides helper functions for routing
*/
*/
class Request
{
/**
@@ -184,7 +184,7 @@ class Request
private function _detectJsonRequest()
{
$hasAcceptHeader = array_key_exists('HTTP_ACCEPT', $_SERVER);
$acceptHeader = $hasAcceptHeader ? $_SERVER['HTTP_ACCEPT'] : '';
$acceptHeader = $hasAcceptHeader ? $_SERVER['HTTP_ACCEPT'] : '';
// simple cases
if (

View File

@@ -11,6 +11,7 @@
*/
namespace PrivateBin;
use Exception;
/**

View File

@@ -13,8 +13,6 @@
namespace PrivateBin;
use PrivateBin\Persistence\ServerSalt;
/**
* Vizhash16x16
*
@@ -60,14 +58,6 @@ class Vizhash16x16
*/
private $height;
/**
* salt used when generating the image
*
* @access private
* @var string
*/
private $salt;
/**
* constructor
*
@@ -78,12 +68,13 @@ class Vizhash16x16
{
$this->width = 16;
$this->height = 16;
$this->salt = ServerSalt::get();
}
/**
* Generate a 16x16 png corresponding to $text.
*
* The given text should to be 128 to 150 characters long
*
* @access public
* @param string $text
* @return string PNG data. Or empty string if GD is not available.
@@ -94,44 +85,35 @@ class Vizhash16x16
return '';
}
// We hash the input string.
$hash=hash('sha1', $text.$this->salt).hash('md5', $text.$this->salt);
$hash=$hash.strrev($hash); # more data to make graphics
$hashlen=strlen($hash);
$textlen = strlen($text);
// We convert the hash into an array of integers.
$this->VALUES=array();
for ($i=0; $i<$hashlen; $i=$i+2) {
array_push($this->VALUES, hexdec(substr($hash, $i, 2)));
$this->VALUES = array();
for ($i = 0; $i < $textlen; $i = $i + 2) {
array_push($this->VALUES, hexdec(substr($text, $i, 2)));
}
$this->VALUES_INDEX=0; // to walk the array.
$this->VALUES_INDEX = 0; // to walk the array.
// Then use these integers to drive the creation of an image.
$image = imagecreatetruecolor($this->width, $this->height);
$r0 = $this->getInt();
$r=$r0;
$g0 = $this->getInt();
$g=$g0;
$b0 = $this->getInt();
$b=$b0;
$r = $r0 = $this->getInt();
$g = $g0 = $this->getInt();
$b = $b0 = $this->getInt();
// First, create an image with a specific gradient background.
$op='v';
if (($this->getInt()%2)==0) {
$op='h';
$op = 'v';
if (($this->getInt() % 2) == 0) {
$op = 'h';
};
$image = $this->degrade($image, $op, array($r0, $g0, $b0), array(0, 0, 0));
for ($i=0; $i<7; $i=$i+1) {
$action=$this->getInt();
$color = imagecolorallocate($image, $r, $g, $b);
$r = ($r0 + $this->getInt()/25)%256;
$g = ($g0 + $this->getInt()/25)%256;
$b = ($b0 + $this->getInt()/25)%256;
$r0=$r;
$g0=$g;
$b0=$b;
for ($i = 0; $i < 7; ++$i) {
$action = $this->getInt();
$color = imagecolorallocate($image, $r, $g, $b);
$r = $r0 = ($r0 + $this->getInt() / 25) % 256;
$g = $g0 = ($g0 + $this->getInt() / 25) % 256;
$b = $b0 = ($b0 + $this->getInt() / 25) % 256;
$this->drawshape($image, $action, $color);
}
@@ -154,8 +136,8 @@ class Vizhash16x16
*/
private function getInt()
{
$v= $this->VALUES[$this->VALUES_INDEX];
$this->VALUES_INDEX++;
$v = $this->VALUES[$this->VALUES_INDEX];
++$this->VALUES_INDEX;
$this->VALUES_INDEX %= count($this->VALUES); // Warp around the array
return $v;
}
@@ -168,7 +150,7 @@ class Vizhash16x16
*/
private function getX()
{
return $this->width*$this->getInt()/256;
return $this->width * $this->getInt() / 256;
}
/**
@@ -179,7 +161,7 @@ class Vizhash16x16
*/
private function getY()
{
return $this->height*$this->getInt()/256;
return $this->height * $this->getInt() / 256;
}
/**
@@ -197,23 +179,23 @@ class Vizhash16x16
*/
private function degrade($img, $direction, $color1, $color2)
{
if ($direction=='h') {
$size = imagesx($img);
if ($direction == 'h') {
$size = imagesx($img);
$sizeinv = imagesy($img);
} else {
$size = imagesy($img);
$size = imagesy($img);
$sizeinv = imagesx($img);
}
$diffs = array(
(($color2[0]-$color1[0])/$size),
(($color2[1]-$color1[1])/$size),
(($color2[2]-$color1[2])/$size)
);
for ($i=0;$i<$size;$i++) {
$r = $color1[0]+($diffs[0]*$i);
$g = $color1[1]+($diffs[1]*$i);
$b = $color1[2]+($diffs[2]*$i);
if ($direction=='h') {
(($color2[0] - $color1[0]) / $size),
(($color2[1] - $color1[1]) / $size),
(($color2[2] - $color1[2]) / $size)
);
for ($i = 0; $i < $size; ++$i) {
$r = $color1[0] + ($diffs[0] * $i);
$g = $color1[1] + ($diffs[1] * $i);
$b = $color1[2] + ($diffs[2] * $i);
if ($direction == 'h') {
imageline($img, $i, 0, $i, $sizeinv, imagecolorallocate($img, $r, $g, $b));
} else {
imageline($img, 0, $i, $sizeinv, $i, imagecolorallocate($img, $r, $g, $b));
@@ -233,7 +215,7 @@ class Vizhash16x16
*/
private function drawshape($image, $action, $color)
{
switch ($action%7) {
switch ($action % 7) {
case 0:
ImageFilledRectangle($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $color);
break;
@@ -242,11 +224,12 @@ class Vizhash16x16
ImageFilledEllipse($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $color);
break;
case 3:
$points = array($this->getX(), $this->getY(), $this->getX(), $this->getY(), $this->getX(), $this->getY(),$this->getX(), $this->getY());
$points = array($this->getX(), $this->getY(), $this->getX(), $this->getY(), $this->getX(), $this->getY(), $this->getX(), $this->getY());
ImageFilledPolygon($image, $points, 4, $color);
break;
default:
$start=$this->getInt()*360/256; $end=$start+$this->getInt()*180/256;
$start = $this->getInt() * 360 / 256;
$end = $start + $this->getInt() * 180 / 256;
ImageFilledArc($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $start, $end, $color, IMG_ARC_PIE);
}
}