Convert to PSR-2 coding style (using phpcs-fixer)

This commit is contained in:
Sobak 2016-07-26 08:19:35 +02:00
parent 884310add6
commit 5d7003ecc1
37 changed files with 636 additions and 665 deletions

View File

@ -98,8 +98,7 @@ class configuration
{ {
$config = array(); $config = array();
$configFile = PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.ini'; $configFile = PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.ini';
if (is_readable($configFile)) if (is_readable($configFile)) {
{
$config = parse_ini_file($configFile, true); $config = parse_ini_file($configFile, true);
foreach (array('main', 'model', 'model_options') as $section) { foreach (array('main', 'model', 'model_options') as $section) {
if (!array_key_exists($section, $config)) { if (!array_key_exists($section, $config)) {
@ -108,14 +107,11 @@ class configuration
} }
} }
$opts = '_options'; $opts = '_options';
foreach (self::getDefaults() as $section => $values) foreach (self::getDefaults() as $section => $values) {
{
// fill missing sections with default values // fill missing sections with default values
if (!array_key_exists($section, $config) || count($config[$section]) == 0) if (!array_key_exists($section, $config) || count($config[$section]) == 0) {
{
$this->_configuration[$section] = $values; $this->_configuration[$section] = $values;
if (array_key_exists('dir', $this->_configuration[$section])) if (array_key_exists('dir', $this->_configuration[$section])) {
{
$this->_configuration[$section]['dir'] = PATH . $this->_configuration[$section]['dir']; $this->_configuration[$section]['dir'] = PATH . $this->_configuration[$section]['dir'];
} }
continue; continue;
@ -126,8 +122,7 @@ class configuration
$this->_configuration['model']['class'], $this->_configuration['model']['class'],
array('privatebin_db', 'zerobin_db') array('privatebin_db', 'zerobin_db')
) )
) ) {
{
$values = array( $values = array(
'dsn' => 'sqlite:' . PATH . 'data/db.sq3', 'dsn' => 'sqlite:' . PATH . 'data/db.sq3',
'tbl' => null, 'tbl' => null,
@ -142,52 +137,34 @@ class configuration
$section !== 'model_options' && $section !== 'model_options' &&
($from = strlen($section) - strlen($opts)) >= 0 && ($from = strlen($section) - strlen($opts)) >= 0 &&
strpos($section, $opts, $from) !== false strpos($section, $opts, $from) !== false
) ) {
{ if (is_int(current($values))) {
if (is_int(current($values)))
{
$config[$section] = array_map('intval', $config[$section]); $config[$section] = array_map('intval', $config[$section]);
} }
$this->_configuration[$section] = $config[$section]; $this->_configuration[$section] = $config[$section];
} }
// check for missing keys and set defaults if necessary // check for missing keys and set defaults if necessary
else else {
{ foreach ($values as $key => $val) {
foreach ($values as $key => $val) if ($key == 'dir') {
{
if ($key == 'dir')
{
$val = PATH . $val; $val = PATH . $val;
} }
$result = $val; $result = $val;
if (array_key_exists($key, $config[$section])) if (array_key_exists($key, $config[$section])) {
{ if ($val === null) {
if ($val === null)
{
$result = $config[$section][$key]; $result = $config[$section][$key];
} } elseif (is_bool($val)) {
elseif (is_bool($val))
{
$val = strtolower($config[$section][$key]); $val = strtolower($config[$section][$key]);
if (in_array($val, array('true', 'yes', 'on'))) if (in_array($val, array('true', 'yes', 'on'))) {
{
$result = true; $result = true;
} } elseif (in_array($val, array('false', 'no', 'off'))) {
elseif (in_array($val, array('false', 'no', 'off')))
{
$result = false; $result = false;
} } else {
else
{
$result = (bool) $config[$section][$key]; $result = (bool) $config[$section][$key];
} }
} } elseif (is_int($val)) {
elseif (is_int($val))
{
$result = (int) $config[$section][$key]; $result = (int) $config[$section][$key];
} } elseif (is_string($val) && !empty($config[$section][$key])) {
elseif (is_string($val) && !empty($config[$section][$key]))
{
$result = (string) $config[$section][$key]; $result = (string) $config[$section][$key];
} }
} }
@ -209,8 +186,7 @@ class configuration
); );
// ensure a valid expire default key is set // ensure a valid expire default key is set
if (!array_key_exists($this->_configuration['expire']['default'], $this->_configuration['expire_options'])) if (!array_key_exists($this->_configuration['expire']['default'], $this->_configuration['expire_options'])) {
{
$this->_configuration['expire']['default'] = key($this->_configuration['expire_options']); $this->_configuration['expire']['default'] = key($this->_configuration['expire_options']);
} }
} }
@ -246,8 +222,7 @@ class configuration
public function getKey($key, $section = 'main') public function getKey($key, $section = 'main')
{ {
$options = $this->getSection($section); $options = $this->getSection($section);
if (!array_key_exists($key, $options)) if (!array_key_exists($key, $options)) {
{
throw new Exception(i18n::_('Invalid data.') . " $section / $key", 4); throw new Exception(i18n::_('Invalid data.') . " $section / $key", 4);
} }
return $this->_configuration[$section][$key]; return $this->_configuration[$section][$key];
@ -262,8 +237,7 @@ class configuration
*/ */
public function getSection($section) public function getSection($section)
{ {
if (!array_key_exists($section, $this->_configuration)) if (!array_key_exists($section, $this->_configuration)) {
{
throw new Exception(i18n::_('PrivateBin requires configuration section [%s] to be present in configuration file.', $section), 3); throw new Exception(i18n::_('PrivateBin requires configuration section [%s] to be present in configuration file.', $section), 3);
} }
return $this->_configuration[$section]; return $this->_configuration[$section];

View File

@ -35,7 +35,9 @@ abstract class AbstractData
* *
* @access protected * @access protected
*/ */
protected function __construct() {} protected function __construct()
{
}
/** /**
* enforce singleton, disable cloning * enforce singleton, disable cloning
@ -44,7 +46,9 @@ abstract class AbstractData
* *
* @access private * @access private
*/ */
private function __clone() {} private function __clone()
{
}
/** /**
* get instance of singleton * get instance of singleton
@ -54,7 +58,9 @@ abstract class AbstractData
* @param array $options * @param array $options
* @return privatebin_abstract * @return privatebin_abstract
*/ */
public static function getInstance($options) {} public static function getInstance($options)
{
}
/** /**
* Create a paste. * Create a paste.
@ -143,12 +149,12 @@ abstract class AbstractData
*/ */
public function purge($batchsize) public function purge($batchsize)
{ {
if ($batchsize < 1) return; if ($batchsize < 1) {
return;
}
$pastes = $this->_getExpiredPastes($batchsize); $pastes = $this->_getExpiredPastes($batchsize);
if (count($pastes)) if (count($pastes)) {
{ foreach ($pastes as $pasteid) {
foreach ($pastes as $pasteid)
{
$this->delete($pasteid); $this->delete($pasteid);
} }
} }
@ -164,10 +170,11 @@ abstract class AbstractData
*/ */
protected function getOpenSlot(&$comments, $postdate) protected function getOpenSlot(&$comments, $postdate)
{ {
if (array_key_exists($postdate, $comments)) if (array_key_exists($postdate, $comments)) {
{
$parts = explode('.', $postdate, 2); $parts = explode('.', $postdate, 2);
if (!array_key_exists(1, $parts)) $parts[1] = 0; if (!array_key_exists(1, $parts)) {
$parts[1] = 0;
}
++$parts[1]; ++$parts[1];
return $this->getOpenSlot($comments, implode('.', $parts)); return $this->getOpenSlot($comments, implode('.', $parts));
} }

View File

@ -42,7 +42,9 @@ class data extends AbstractData
if ( if (
is_array($options) && is_array($options) &&
array_key_exists('dir', $options) array_key_exists('dir', $options)
) self::$_dir = $options['dir'] . DIRECTORY_SEPARATOR; ) {
self::$_dir = $options['dir'] . DIRECTORY_SEPARATOR;
}
// if needed initialize the singleton // if needed initialize the singleton
if (!(self::$_instance instanceof privatebin_data)) { if (!(self::$_instance instanceof privatebin_data)) {
self::$_instance = new self; self::$_instance = new self;
@ -62,8 +64,12 @@ class data extends AbstractData
public function create($pasteid, $paste) public function create($pasteid, $paste)
{ {
$storagedir = self::_dataid2path($pasteid); $storagedir = self::_dataid2path($pasteid);
if (is_file($storagedir . $pasteid)) return false; if (is_file($storagedir . $pasteid)) {
if (!is_dir($storagedir)) mkdir($storagedir, 0705, true); return false;
}
if (!is_dir($storagedir)) {
mkdir($storagedir, 0705, true);
}
return (bool) @file_put_contents($storagedir . $pasteid, json_encode($paste)); return (bool) @file_put_contents($storagedir . $pasteid, json_encode($paste));
} }
@ -76,16 +82,16 @@ class data extends AbstractData
*/ */
public function read($pasteid) public function read($pasteid)
{ {
if (!$this->exists($pasteid)) return false; if (!$this->exists($pasteid)) {
return false;
}
$paste = json_decode( $paste = json_decode(
file_get_contents(self::_dataid2path($pasteid) . $pasteid) file_get_contents(self::_dataid2path($pasteid) . $pasteid)
); );
if (property_exists($paste->meta, 'attachment')) if (property_exists($paste->meta, 'attachment')) {
{
$paste->attachment = $paste->meta->attachment; $paste->attachment = $paste->meta->attachment;
unset($paste->meta->attachment); unset($paste->meta->attachment);
if (property_exists($paste->meta, 'attachmentname')) if (property_exists($paste->meta, 'attachmentname')) {
{
$paste->attachmentname = $paste->meta->attachmentname; $paste->attachmentname = $paste->meta->attachmentname;
unset($paste->meta->attachmentname); unset($paste->meta->attachmentname);
} }
@ -107,13 +113,13 @@ class data extends AbstractData
// Delete discussion if it exists. // Delete discussion if it exists.
$discdir = self::_dataid2discussionpath($pasteid); $discdir = self::_dataid2discussionpath($pasteid);
if (is_dir($discdir)) if (is_dir($discdir)) {
{
// Delete all files in discussion directory // Delete all files in discussion directory
$dir = dir($discdir); $dir = dir($discdir);
while (false !== ($filename = $dir->read())) while (false !== ($filename = $dir->read())) {
{ if (is_file($discdir . $filename)) {
if (is_file($discdir . $filename)) @unlink($discdir . $filename); @unlink($discdir . $filename);
}
} }
$dir->close(); $dir->close();
@ -148,8 +154,12 @@ class data extends AbstractData
{ {
$storagedir = self::_dataid2discussionpath($pasteid); $storagedir = self::_dataid2discussionpath($pasteid);
$filename = $pasteid . '.' . $commentid . '.' . $parentid; $filename = $pasteid . '.' . $commentid . '.' . $parentid;
if (is_file($storagedir . $filename)) return false; if (is_file($storagedir . $filename)) {
if (!is_dir($storagedir)) mkdir($storagedir, 0705, true); return false;
}
if (!is_dir($storagedir)) {
mkdir($storagedir, 0705, true);
}
return (bool) @file_put_contents($storagedir . $filename, json_encode($comment)); return (bool) @file_put_contents($storagedir . $filename, json_encode($comment));
} }
@ -164,18 +174,15 @@ class data extends AbstractData
{ {
$comments = array(); $comments = array();
$discdir = self::_dataid2discussionpath($pasteid); $discdir = self::_dataid2discussionpath($pasteid);
if (is_dir($discdir)) if (is_dir($discdir)) {
{
// Delete all files in discussion directory // Delete all files in discussion directory
$dir = dir($discdir); $dir = dir($discdir);
while (false !== ($filename = $dir->read())) while (false !== ($filename = $dir->read())) {
{
// Filename is in the form pasteid.commentid.parentid: // Filename is in the form pasteid.commentid.parentid:
// - pasteid is the paste this reply belongs to. // - pasteid is the paste this reply belongs to.
// - commentid is the comment identifier itself. // - commentid is the comment identifier itself.
// - parentid is the comment this comment replies to (It can be pasteid) // - parentid is the comment this comment replies to (It can be pasteid)
if (is_file($discdir . $filename)) if (is_file($discdir . $filename)) {
{
$comment = json_decode(file_get_contents($discdir . $filename)); $comment = json_decode(file_get_contents($discdir . $filename));
$items = explode('.', $filename); $items = explode('.', $filename);
// Add some meta information not contained in file. // Add some meta information not contained in file.
@ -226,11 +233,9 @@ class data extends AbstractData
scandir(self::$_dir), scandir(self::$_dir),
array('self', '_isFirstLevelDir') array('self', '_isFirstLevelDir')
); );
if (count($firstLevel) > 0) if (count($firstLevel) > 0) {
{
// try at most 10 times the $batchsize pastes before giving up // try at most 10 times the $batchsize pastes before giving up
for ($i = 0, $max = $batchsize * 10; $i < $max; ++$i) for ($i = 0, $max = $batchsize * 10; $i < $max; ++$i) {
{
$firstKey = array_rand($firstLevel); $firstKey = array_rand($firstLevel);
$secondLevel = array_filter( $secondLevel = array_filter(
scandir(self::$_dir . $firstLevel[$firstKey]), scandir(self::$_dir . $firstLevel[$firstKey]),
@ -238,8 +243,7 @@ class data extends AbstractData
); );
// skip this folder in the next checks if it is empty // skip this folder in the next checks if it is empty
if (count($secondLevel) == 0) if (count($secondLevel) == 0) {
{
unset($firstLevel[$firstKey]); unset($firstLevel[$firstKey]);
continue; continue;
} }
@ -247,26 +251,32 @@ class data extends AbstractData
$secondKey = array_rand($secondLevel); $secondKey = array_rand($secondLevel);
$path = self::$_dir . $firstLevel[$firstKey] . $path = self::$_dir . $firstLevel[$firstKey] .
DIRECTORY_SEPARATOR . $secondLevel[$secondKey]; DIRECTORY_SEPARATOR . $secondLevel[$secondKey];
if (!is_dir($path)) continue; if (!is_dir($path)) {
continue;
}
$thirdLevel = array_filter( $thirdLevel = array_filter(
scandir($path), scandir($path),
array('PrivateBin\\model\\paste', 'isValidId') array('PrivateBin\\model\\paste', 'isValidId')
); );
if (count($thirdLevel) == 0) continue; if (count($thirdLevel) == 0) {
continue;
}
$thirdKey = array_rand($thirdLevel); $thirdKey = array_rand($thirdLevel);
$pasteid = $thirdLevel[$thirdKey]; $pasteid = $thirdLevel[$thirdKey];
if (in_array($pasteid, $pastes)) continue; if (in_array($pasteid, $pastes)) {
continue;
}
if ($this->exists($pasteid)) if ($this->exists($pasteid)) {
{
$data = $this->read($pasteid); $data = $this->read($pasteid);
if ( if (
property_exists($data->meta, 'expire_date') && property_exists($data->meta, 'expire_date') &&
$data->meta->expire_date < time() $data->meta->expire_date < time()
) ) {
{
$pastes[] = $pasteid; $pastes[] = $pasteid;
if (count($pastes) >= $batchsize) break; if (count($pastes) >= $batchsize) {
break;
}
} }
} }
} }
@ -284,10 +294,11 @@ class data extends AbstractData
private static function _init() private static function _init()
{ {
// Create storage directory if it does not exist. // Create storage directory if it does not exist.
if (!is_dir(self::$_dir)) mkdir(self::$_dir, 0705); if (!is_dir(self::$_dir)) {
mkdir(self::$_dir, 0705);
}
// Create .htaccess file if it does not exist. // Create .htaccess file if it does not exist.
if (!is_file(self::$_dir . '.htaccess')) if (!is_file(self::$_dir . '.htaccess')) {
{
file_put_contents( file_put_contents(
self::$_dir . '.htaccess', self::$_dir . '.htaccess',
'Allow from none' . PHP_EOL . 'Allow from none' . PHP_EOL .

View File

@ -75,10 +75,11 @@ class db extends AbstractData
self::$_instance = new self; self::$_instance = new self;
} }
if (is_array($options)) if (is_array($options)) {
{
// set table prefix if given // set table prefix if given
if (array_key_exists('tbl', $options)) self::$_prefix = $options['tbl']; if (array_key_exists('tbl', $options)) {
self::$_prefix = $options['tbl'];
}
// initialize the db connection with new options // initialize the db connection with new options
if ( if (
@ -86,8 +87,7 @@ class db extends AbstractData
array_key_exists('usr', $options) && array_key_exists('usr', $options) &&
array_key_exists('pwd', $options) && array_key_exists('pwd', $options) &&
array_key_exists('opt', $options) array_key_exists('opt', $options)
) ) {
{
// set default 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_EMULATE_PREPARES] = false;
@ -110,40 +110,34 @@ class db extends AbstractData
$tables = self::$_db->query($tableQuery)->fetchAll(PDO::FETCH_COLUMN, 0); $tables = self::$_db->query($tableQuery)->fetchAll(PDO::FETCH_COLUMN, 0);
// create paste table if necessary // create paste table if necessary
if (!in_array(self::_sanitizeIdentifier('paste'), $tables)) if (!in_array(self::_sanitizeIdentifier('paste'), $tables)) {
{
self::_createPasteTable(); self::_createPasteTable();
$db_tables_exist = false; $db_tables_exist = false;
} }
// create comment table if necessary // create comment table if necessary
if (!in_array(self::_sanitizeIdentifier('comment'), $tables)) if (!in_array(self::_sanitizeIdentifier('comment'), $tables)) {
{
self::_createCommentTable(); self::_createCommentTable();
$db_tables_exist = false; $db_tables_exist = false;
} }
// create config table if necessary // create config table if necessary
$db_version = privatebin::VERSION; $db_version = privatebin::VERSION;
if (!in_array(self::_sanitizeIdentifier('config'), $tables)) if (!in_array(self::_sanitizeIdentifier('config'), $tables)) {
{
self::_createConfigTable(); self::_createConfigTable();
// if we only needed to create the config table, the DB is older then 0.22 // if we only needed to create the config table, the DB is older then 0.22
if ($db_tables_exist) $db_version = '0.21'; if ($db_tables_exist) {
$db_version = '0.21';
} }
else } else {
{
$db_version = self::_getConfig('VERSION'); $db_version = self::_getConfig('VERSION');
} }
// update database structure if necessary // update database structure if necessary
if (version_compare($db_version, privatebin::VERSION, '<')) if (version_compare($db_version, privatebin::VERSION, '<')) {
{
self::_upgradeDatabase($db_version); self::_upgradeDatabase($db_version);
} }
} } else {
else
{
throw new Exception( throw new Exception(
'Missing configuration for key dsn, usr, pwd or opt in the section model_options, please check your configuration file', 6 'Missing configuration for key dsn, usr, pwd or opt in the section model_options, please check your configuration file', 6
); );
@ -178,28 +172,23 @@ class db extends AbstractData
$meta = $paste['meta']; $meta = $paste['meta'];
unset($meta['postdate']); unset($meta['postdate']);
$expire_date = 0; $expire_date = 0;
if (array_key_exists('expire_date', $paste['meta'])) if (array_key_exists('expire_date', $paste['meta'])) {
{
$expire_date = (int) $paste['meta']['expire_date']; $expire_date = (int) $paste['meta']['expire_date'];
unset($meta['expire_date']); unset($meta['expire_date']);
} }
if (array_key_exists('opendiscussion', $paste['meta'])) if (array_key_exists('opendiscussion', $paste['meta'])) {
{
$opendiscussion = (bool) $paste['meta']['opendiscussion']; $opendiscussion = (bool) $paste['meta']['opendiscussion'];
unset($meta['opendiscussion']); unset($meta['opendiscussion']);
} }
if (array_key_exists('burnafterreading', $paste['meta'])) if (array_key_exists('burnafterreading', $paste['meta'])) {
{
$burnafterreading = (bool) $paste['meta']['burnafterreading']; $burnafterreading = (bool) $paste['meta']['burnafterreading'];
unset($meta['burnafterreading']); unset($meta['burnafterreading']);
} }
if (array_key_exists('attachment', $paste['meta'])) if (array_key_exists('attachment', $paste['meta'])) {
{
$attachment = $paste['meta']['attachment']; $attachment = $paste['meta']['attachment'];
unset($meta['attachment']); unset($meta['attachment']);
} }
if (array_key_exists('attachmentname', $paste['meta'])) if (array_key_exists('attachmentname', $paste['meta'])) {
{
$attachmentname = $paste['meta']['attachmentname']; $attachmentname = $paste['meta']['attachmentname'];
unset($meta['attachmentname']); unset($meta['attachmentname']);
} }
@ -244,25 +233,23 @@ class db extends AbstractData
self::$_cache[$pasteid]->data = $paste['data']; self::$_cache[$pasteid]->data = $paste['data'];
$meta = json_decode($paste['meta']); $meta = json_decode($paste['meta']);
if (!is_object($meta)) $meta = new stdClass; if (!is_object($meta)) {
$meta = new stdClass;
}
// support older attachments // support older attachments
if (property_exists($meta, 'attachment')) if (property_exists($meta, 'attachment')) {
{
self::$_cache[$pasteid]->attachment = $meta->attachment; self::$_cache[$pasteid]->attachment = $meta->attachment;
unset($meta->attachment); unset($meta->attachment);
if (property_exists($meta, 'attachmentname')) if (property_exists($meta, 'attachmentname')) {
{
self::$_cache[$pasteid]->attachmentname = $meta->attachmentname; self::$_cache[$pasteid]->attachmentname = $meta->attachmentname;
unset($meta->attachmentname); unset($meta->attachmentname);
} }
} }
// support current attachments // support current attachments
elseif (array_key_exists('attachment', $paste) && strlen($paste['attachment'])) elseif (array_key_exists('attachment', $paste) && strlen($paste['attachment'])) {
{
self::$_cache[$pasteid]->attachment = $paste['attachment']; self::$_cache[$pasteid]->attachment = $paste['attachment'];
if (array_key_exists('attachmentname', $paste) && strlen($paste['attachmentname'])) if (array_key_exists('attachmentname', $paste) && strlen($paste['attachmentname'])) {
{
self::$_cache[$pasteid]->attachmentname = $paste['attachmentname']; self::$_cache[$pasteid]->attachmentname = $paste['attachmentname'];
} }
} }
@ -271,13 +258,19 @@ class db extends AbstractData
$expire_date = (int) $paste['expiredate']; $expire_date = (int) $paste['expiredate'];
if ( if (
$expire_date > 0 $expire_date > 0
) self::$_cache[$pasteid]->meta->expire_date = $expire_date; ) {
self::$_cache[$pasteid]->meta->expire_date = $expire_date;
}
if ( if (
$paste['opendiscussion'] $paste['opendiscussion']
) self::$_cache[$pasteid]->meta->opendiscussion = true; ) {
self::$_cache[$pasteid]->meta->opendiscussion = true;
}
if ( if (
$paste['burnafterreading'] $paste['burnafterreading']
) self::$_cache[$pasteid]->meta->burnafterreading = true; ) {
self::$_cache[$pasteid]->meta->burnafterreading = true;
}
} }
} }
@ -303,7 +296,9 @@ class db extends AbstractData
); );
if ( if (
array_key_exists($pasteid, self::$_cache) array_key_exists($pasteid, self::$_cache)
) unset(self::$_cache[$pasteid]); ) {
unset(self::$_cache[$pasteid]);
}
} }
/** /**
@ -317,7 +312,9 @@ class db extends AbstractData
{ {
if ( if (
!array_key_exists($pasteid, self::$_cache) !array_key_exists($pasteid, self::$_cache)
) self::$_cache[$pasteid] = $this->read($pasteid); ) {
self::$_cache[$pasteid] = $this->read($pasteid);
}
return (bool) self::$_cache[$pasteid]; return (bool) self::$_cache[$pasteid];
} }
@ -333,10 +330,8 @@ class db extends AbstractData
*/ */
public function createComment($pasteid, $parentid, $commentid, $comment) public function createComment($pasteid, $parentid, $commentid, $comment)
{ {
foreach (array('nickname', 'vizhash') as $key) foreach (array('nickname', 'vizhash') as $key) {
{ if (!array_key_exists($key, $comment['meta'])) {
if (!array_key_exists($key, $comment['meta']))
{
$comment['meta'][$key] = null; $comment['meta'][$key] = null;
} }
} }
@ -371,10 +366,8 @@ class db extends AbstractData
// create comment list // create comment list
$comments = array(); $comments = array();
if (count($rows)) if (count($rows)) {
{ foreach ($rows as $row) {
foreach ($rows as $row)
{
$i = $this->getOpenSlot($comments, (int) $row['postdate']); $i = $this->getOpenSlot($comments, (int) $row['postdate']);
$comments[$i] = new stdClass; $comments[$i] = new stdClass;
$comments[$i]->id = $row['dataid']; $comments[$i]->id = $row['dataid'];
@ -382,11 +375,13 @@ class db extends AbstractData
$comments[$i]->data = $row['data']; $comments[$i]->data = $row['data'];
$comments[$i]->meta = new stdClass; $comments[$i]->meta = new stdClass;
$comments[$i]->meta->postdate = (int) $row['postdate']; $comments[$i]->meta->postdate = (int) $row['postdate'];
if (array_key_exists('nickname', $row) && !empty($row['nickname'])) if (array_key_exists('nickname', $row) && !empty($row['nickname'])) {
$comments[$i]->meta->nickname = $row['nickname']; $comments[$i]->meta->nickname = $row['nickname'];
if (array_key_exists('vizhash', $row) && !empty($row['vizhash'])) }
if (array_key_exists('vizhash', $row) && !empty($row['vizhash'])) {
$comments[$i]->meta->vizhash = $row['vizhash']; $comments[$i]->meta->vizhash = $row['vizhash'];
} }
}
ksort($comments); ksort($comments);
} }
return $comments; return $comments;
@ -424,10 +419,8 @@ class db extends AbstractData
'SELECT dataid FROM ' . self::_sanitizeIdentifier('paste') . 'SELECT dataid FROM ' . self::_sanitizeIdentifier('paste') .
' WHERE expiredate < ? LIMIT ?', array(time(), $batchsize) ' WHERE expiredate < ? LIMIT ?', array(time(), $batchsize)
); );
if (count($rows)) if (count($rows)) {
{ foreach ($rows as $row) {
foreach ($rows as $row)
{
$pastes[] = $row['dataid']; $pastes[] = $row['dataid'];
} }
} }
@ -485,8 +478,7 @@ class db extends AbstractData
*/ */
private static function _getTableQuery($type) private static function _getTableQuery($type)
{ {
switch($type) switch ($type) {
{
case 'ibm': case 'ibm':
$sql = 'SELECT tabname FROM SYSCAT.TABLES '; $sql = 'SELECT tabname FROM SYSCAT.TABLES ';
break; break;
@ -559,12 +551,9 @@ class db extends AbstractData
private static function _getPrimaryKeyClauses($key = 'dataid') private static function _getPrimaryKeyClauses($key = 'dataid')
{ {
$main_key = $after_key = ''; $main_key = $after_key = '';
if (self::$_type === 'mysql') if (self::$_type === 'mysql') {
{
$after_key = ", PRIMARY KEY ($key)"; $after_key = ", PRIMARY KEY ($key)";
} } else {
else
{
$main_key = ' PRIMARY KEY'; $main_key = ' PRIMARY KEY';
} }
return array($main_key, $after_key); return array($main_key, $after_key);
@ -667,8 +656,7 @@ class db extends AbstractData
private static function _upgradeDatabase($oldversion) private static function _upgradeDatabase($oldversion)
{ {
$dataType = self::$_type === 'pgsql' ? 'TEXT' : 'BLOB'; $dataType = self::$_type === 'pgsql' ? 'TEXT' : 'BLOB';
switch ($oldversion) switch ($oldversion) {
{
case '0.21': case '0.21':
// create the meta column if necessary (pre 0.21 change) // create the meta column if necessary (pre 0.21 change)
try { try {
@ -687,8 +675,7 @@ class db extends AbstractData
); );
// SQLite doesn't support MODIFY, but it allows TEXT of similar // SQLite doesn't support MODIFY, but it allows TEXT of similar
// size as BLOB, so there is no need to change it there // size as BLOB, so there is no need to change it there
if (self::$_type !== 'sqlite') if (self::$_type !== 'sqlite') {
{
self::$_db->exec( self::$_db->exec(
'ALTER TABLE ' . self::_sanitizeIdentifier('paste') . 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') .
' ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType;' ' ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType;'
@ -698,9 +685,7 @@ class db extends AbstractData
" ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType, " . " ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType, " .
"MODIFY COLUMN nickname $dataType, MODIFY COLUMN vizhash $dataType;" "MODIFY COLUMN nickname $dataType, MODIFY COLUMN vizhash $dataType;"
); );
} } else {
else
{
self::$_db->exec( self::$_db->exec(
'CREATE UNIQUE INDEX IF NOT EXISTS paste_dataid ON ' . 'CREATE UNIQUE INDEX IF NOT EXISTS paste_dataid ON ' .
self::_sanitizeIdentifier('paste') . '(dataid);' self::_sanitizeIdentifier('paste') . '(dataid);'

View File

@ -98,8 +98,7 @@ class filter
public static function slow_equals($a, $b) public static function slow_equals($a, $b)
{ {
$diff = strlen($a) ^ strlen($b); $diff = strlen($a) ^ strlen($b);
for($i = 0; $i < strlen($a) && $i < strlen($b); $i++) for ($i = 0; $i < strlen($a) && $i < strlen($b); $i++) {
{
$diff |= ord($a[$i]) ^ ord($b[$i]); $diff |= ord($a[$i]) ^ ord($b[$i]);
} }
return $diff === 0; return $diff === 0;

View File

@ -98,30 +98,31 @@ class i18n
*/ */
public static function translate($messageId) public static function translate($messageId)
{ {
if (empty($messageId)) return $messageId; if (empty($messageId)) {
if (count(self::$_translations) === 0) self::loadTranslations(); return $messageId;
}
if (count(self::$_translations) === 0) {
self::loadTranslations();
}
$messages = $messageId; $messages = $messageId;
if (is_array($messageId)) if (is_array($messageId)) {
{
$messageId = count($messageId) > 1 ? $messageId[1] : $messageId[0]; $messageId = count($messageId) > 1 ? $messageId[1] : $messageId[0];
} }
if (!array_key_exists($messageId, self::$_translations)) if (!array_key_exists($messageId, self::$_translations)) {
{
self::$_translations[$messageId] = $messages; self::$_translations[$messageId] = $messages;
} }
$args = func_get_args(); $args = func_get_args();
if (is_array(self::$_translations[$messageId])) if (is_array(self::$_translations[$messageId])) {
{
$number = (int) $args[1]; $number = (int) $args[1];
$key = self::_getPluralForm($number); $key = self::_getPluralForm($number);
$max = count(self::$_translations[$messageId]) - 1; $max = count(self::$_translations[$messageId]) - 1;
if ($key > $max) $key = $max; if ($key > $max) {
$key = $max;
}
$args[0] = self::$_translations[$messageId][$key]; $args[0] = self::$_translations[$messageId][$key];
$args[1] = $number; $args[1] = $number;
} } else {
else
{
$args[0] = self::$_translations[$messageId]; $args[0] = self::$_translations[$messageId];
} }
return call_user_func_array('sprintf', $args); return call_user_func_array('sprintf', $args);
@ -141,13 +142,11 @@ class i18n
$availableLanguages = self::getAvailableLanguages(); $availableLanguages = self::getAvailableLanguages();
// check if the lang cookie was set and that language exists // check if the lang cookie was set and that language exists
if (array_key_exists('lang', $_COOKIE) && in_array($_COOKIE['lang'], $availableLanguages)) if (array_key_exists('lang', $_COOKIE) && in_array($_COOKIE['lang'], $availableLanguages)) {
{
$match = $availableLanguages[array_search($_COOKIE['lang'], $availableLanguages)]; $match = $availableLanguages[array_search($_COOKIE['lang'], $availableLanguages)];
} }
// find a translation file matching the browsers language preferences // find a translation file matching the browsers language preferences
else else {
{
$match = self::_getMatchingLanguage( $match = self::_getMatchingLanguage(
self::getBrowserLanguages(), $availableLanguages self::getBrowserLanguages(), $availableLanguages
); );
@ -170,13 +169,10 @@ class i18n
*/ */
public static function getAvailableLanguages() public static function getAvailableLanguages()
{ {
if (count(self::$_availableLanguages) == 0) if (count(self::$_availableLanguages) == 0) {
{
$i18n = dir(self::_getPath()); $i18n = dir(self::_getPath());
while (false !== ($file = $i18n->read())) while (false !== ($file = $i18n->read())) {
{ if (preg_match('/^([a-z]{2}).json$/', $file, $match) === 1) {
if (preg_match('/^([a-z]{2}).json$/', $file, $match) === 1)
{
self::$_availableLanguages[] = $match[1]; self::$_availableLanguages[] = $match[1];
} }
} }
@ -197,26 +193,19 @@ class i18n
public static function getBrowserLanguages() public static function getBrowserLanguages()
{ {
$languages = array(); $languages = array();
if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
{
$languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])); $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
foreach ($languageRanges as $languageRange) foreach ($languageRanges as $languageRange) {
{
if (preg_match( if (preg_match(
'/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/', '/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/',
trim($languageRange), $match trim($languageRange), $match
)) )) {
{ if (!isset($match[2])) {
if (!isset($match[2]))
{
$match[2] = '1.0'; $match[2] = '1.0';
} } else {
else
{
$match[2] = (string) floatval($match[2]); $match[2] = (string) floatval($match[2]);
} }
if (!isset($languages[$match[2]])) if (!isset($languages[$match[2]])) {
{
$languages[$match[2]] = array(); $languages[$match[2]] = array();
} }
$languages[$match[2]][] = strtolower($match[1]); $languages[$match[2]][] = strtolower($match[1]);
@ -252,11 +241,12 @@ class i18n
public static function getLanguageLabels($languages = array()) public static function getLanguageLabels($languages = array())
{ {
$file = self::_getPath('languages.json'); $file = self::_getPath('languages.json');
if (count(self::$_languageLabels) == 0 && is_readable($file)) if (count(self::$_languageLabels) == 0 && is_readable($file)) {
{
self::$_languageLabels = json_decode(file_get_contents($file), true); self::$_languageLabels = json_decode(file_get_contents($file), true);
} }
if (count($languages) == 0) return self::$_languageLabels; if (count($languages) == 0) {
return self::$_languageLabels;
}
return array_intersect_key(self::$_languageLabels, array_flip($languages)); return array_intersect_key(self::$_languageLabels, array_flip($languages));
} }
@ -270,9 +260,10 @@ class i18n
*/ */
public static function setLanguageFallback($lang) public static function setLanguageFallback($lang)
{ {
if (in_array($lang, self::getAvailableLanguages())) if (in_array($lang, self::getAvailableLanguages())) {
self::$_languageFallback = $lang; self::$_languageFallback = $lang;
} }
}
/** /**
* get language file path * get language file path
@ -284,8 +275,7 @@ class i18n
*/ */
protected static function _getPath($file = '') protected static function _getPath($file = '')
{ {
if (strlen(self::$_path) == 0) if (strlen(self::$_path) == 0) {
{
self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n'; self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
} }
return self::$_path . (strlen($file) ? DIRECTORY_SEPARATOR . $file : ''); return self::$_path . (strlen($file) ? DIRECTORY_SEPARATOR . $file : '');
@ -326,47 +316,40 @@ class i18n
* @param array $availableLanguages * @param array $availableLanguages
* @return string * @return string
*/ */
protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages) { protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
{
$matches = array(); $matches = array();
$any = false; $any = false;
foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
{
$acceptedQuality = floatval($acceptedQuality); $acceptedQuality = floatval($acceptedQuality);
if ($acceptedQuality === 0.0) continue; if ($acceptedQuality === 0.0) {
foreach ($availableLanguages as $availableValue) continue;
{ }
foreach ($availableLanguages as $availableValue) {
$availableQuality = 1.0; $availableQuality = 1.0;
foreach ($acceptedValues as $acceptedValue) foreach ($acceptedValues as $acceptedValue) {
{ if ($acceptedValue === '*') {
if ($acceptedValue === '*')
{
$any = true; $any = true;
} }
$matchingGrade = self::_matchLanguage($acceptedValue, $availableValue); $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
if ($matchingGrade > 0) if ($matchingGrade > 0) {
{
$q = (string) ($acceptedQuality * $availableQuality * $matchingGrade); $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
if (!isset($matches[$q])) if (!isset($matches[$q])) {
{
$matches[$q] = array(); $matches[$q] = array();
} }
if (!in_array($availableValue, $matches[$q])) if (!in_array($availableValue, $matches[$q])) {
{
$matches[$q][] = $availableValue; $matches[$q][] = $availableValue;
} }
} }
} }
} }
} }
if (count($matches) === 0 && $any) if (count($matches) === 0 && $any) {
{ if (count($availableLanguages) > 0) {
if (count($availableLanguages) > 0)
{
$matches['1.0'] = $availableLanguages; $matches['1.0'] = $availableLanguages;
} }
} }
if (count($matches) === 0) if (count($matches) === 0) {
{
return self::$_languageFallback; return self::$_languageFallback;
} }
krsort($matches); krsort($matches);
@ -385,12 +368,14 @@ class i18n
* @param string $b * @param string $b
* @return float * @return float
*/ */
protected static function _matchLanguage($a, $b) { protected static function _matchLanguage($a, $b)
{
$a = explode('-', $a); $a = explode('-', $a);
$b = explode('-', $b); $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]) {
if ($a[$i] !== $b[$i]) break; break;
}
} }
return $i === 0 ? 0 : (float) $i / count($a); return $i === 0 ? 0 : (float) $i / count($a);
} }

View File

@ -55,7 +55,9 @@ class model
public function getPaste($pasteId = null) public function getPaste($pasteId = null)
{ {
$paste = new paste($this->_conf, $this->_getStore()); $paste = new paste($this->_conf, $this->_getStore());
if ($pasteId !== null) $paste->setId($pasteId); if ($pasteId !== null) {
$paste->setId($pasteId);
}
return $paste; return $paste;
} }
@ -67,8 +69,7 @@ class model
public function purge() public function purge()
{ {
purgelimiter::setConfiguration($this->_conf); purgelimiter::setConfiguration($this->_conf);
if (purgelimiter::canPurge()) if (purgelimiter::canPurge()) {
{
$this->_getStore()->purge($this->_conf->getKey('batchsize', 'purge')); $this->_getStore()->purge($this->_conf->getKey('batchsize', 'purge'));
} }
} }
@ -80,8 +81,7 @@ class model
*/ */
private function _getStore() private function _getStore()
{ {
if ($this->_store === null) if ($this->_store === null) {
{
$this->_store = forward_static_call( $this->_store = forward_static_call(
array($this->_conf->getKey('class', 'model'), 'getInstance'), array($this->_conf->getKey('class', 'model'), 'getInstance'),
$this->_conf->getSection('model_options') $this->_conf->getSection('model_options')

View File

@ -94,7 +94,9 @@ abstract class AbstractModel
*/ */
public function setId($id) public function setId($id)
{ {
if (!self::isValidId($id)) throw new Exception('Invalid paste ID.', 60); if (!self::isValidId($id)) {
throw new Exception('Invalid paste ID.', 60);
}
$this->_id = $id; $this->_id = $id;
} }
@ -108,7 +110,9 @@ abstract class AbstractModel
*/ */
public function setData($data) public function setData($data)
{ {
if (!sjcl::isValid($data)) throw new Exception('Invalid data.', 61); if (!sjcl::isValid($data)) {
throw new Exception('Invalid data.', 61);
}
$this->_data->data = $data; $this->_data->data = $data;
// We just want a small hash to avoid collisions: // We just want a small hash to avoid collisions:

View File

@ -66,16 +66,19 @@ class comment extends AbstractModel
{ {
// Make sure paste exists. // Make sure paste exists.
$pasteid = $this->getPaste()->getId(); $pasteid = $this->getPaste()->getId();
if (!$this->getPaste()->exists()) if (!$this->getPaste()->exists()) {
throw new Exception('Invalid data.', 67); throw new Exception('Invalid data.', 67);
}
// Make sure the discussion is opened in this paste and in configuration. // Make sure the discussion is opened in this paste and in configuration.
if (!$this->getPaste()->isOpendiscussion() || !$this->_conf->getKey('discussion')) if (!$this->getPaste()->isOpendiscussion() || !$this->_conf->getKey('discussion')) {
throw new Exception('Invalid data.', 68); throw new Exception('Invalid data.', 68);
}
// Check for improbable collision. // Check for improbable collision.
if ($this->exists()) if ($this->exists()) {
throw new Exception('You are unlucky. Try again.', 69); throw new Exception('You are unlucky. Try again.', 69);
}
$this->_data->meta->postdate = time(); $this->_data->meta->postdate = time();
@ -87,7 +90,9 @@ class comment extends AbstractModel
$this->getId(), $this->getId(),
json_decode(json_encode($this->_data), true) json_decode(json_encode($this->_data), true)
) === false ) === false
) throw new Exception('Error saving comment. Sorry.', 70); ) {
throw new Exception('Error saving comment. Sorry.', 70);
}
} }
/** /**
@ -152,7 +157,9 @@ class comment extends AbstractModel
*/ */
public function setParentId($id) public function setParentId($id)
{ {
if (!self::isValidId($id)) throw new Exception('Invalid paste ID.', 65); if (!self::isValidId($id)) {
throw new Exception('Invalid paste ID.', 65);
}
$this->_data->meta->parentid = $id; $this->_data->meta->parentid = $id;
} }
@ -164,7 +171,9 @@ class comment extends AbstractModel
*/ */
public function getParentId() public function getParentId()
{ {
if (!property_exists($this->_data->meta, 'parentid')) $this->_data->meta->parentid = ''; if (!property_exists($this->_data->meta, 'parentid')) {
$this->_data->meta->parentid = '';
}
return $this->_data->meta->parentid; return $this->_data->meta->parentid;
} }
@ -178,19 +187,19 @@ class comment extends AbstractModel
*/ */
public function setNickname($nickname) public function setNickname($nickname)
{ {
if (!sjcl::isValid($nickname)) throw new Exception('Invalid data.', 66); if (!sjcl::isValid($nickname)) {
throw new Exception('Invalid data.', 66);
}
$this->_data->meta->nickname = $nickname; $this->_data->meta->nickname = $nickname;
if ($this->_conf->getKey('vizhash')) if ($this->_conf->getKey('vizhash')) {
{
// Generation of the anonymous avatar (Vizhash): // Generation of the anonymous avatar (Vizhash):
// If a nickname is provided, we generate a Vizhash. // If a nickname is provided, we generate a Vizhash.
// (We assume that if the user did not enter a nickname, he/she wants // (We assume that if the user did not enter a nickname, he/she wants
// to be anonymous and we will not generate the vizhash.) // to be anonymous and we will not generate the vizhash.)
$vh = new vizhash16x16(); $vh = new vizhash16x16();
$pngdata = $vh->generate(trafficlimiter::getIp()); $pngdata = $vh->generate(trafficlimiter::getIp());
if ($pngdata != '') if ($pngdata != '') {
{
$this->_data->meta->vizhash = 'data:image/png;base64,' . base64_encode($pngdata); $this->_data->meta->vizhash = 'data:image/png;base64,' . base64_encode($pngdata);
} }
// Once the avatar is generated, we do not keep the IP address, nor its hash. // Once the avatar is generated, we do not keep the IP address, nor its hash.

View File

@ -34,13 +34,13 @@ class paste extends AbstractModel
public function get() public function get()
{ {
$this->_data = $this->_store->read($this->getId()); $this->_data = $this->_store->read($this->getId());
if ($this->_data === false) throw new Exception(privatebin::GENERIC_ERROR, 64); if ($this->_data === false) {
throw new Exception(privatebin::GENERIC_ERROR, 64);
}
// check if paste has expired and delete it if neccessary. // check if paste has expired and delete it if neccessary.
if (property_exists($this->_data->meta, 'expire_date')) if (property_exists($this->_data->meta, 'expire_date')) {
{ if ($this->_data->meta->expire_date < time()) {
if ($this->_data->meta->expire_date < time())
{
$this->delete(); $this->delete();
throw new Exception(privatebin::GENERIC_ERROR, 63); throw new Exception(privatebin::GENERIC_ERROR, 63);
} }
@ -49,22 +49,17 @@ class paste extends AbstractModel
} }
// set formatter for for the view. // set formatter for for the view.
if (!property_exists($this->_data->meta, 'formatter')) if (!property_exists($this->_data->meta, 'formatter')) {
{
// support < 0.21 syntax highlighting // support < 0.21 syntax highlighting
if (property_exists($this->_data->meta, 'syntaxcoloring') && $this->_data->meta->syntaxcoloring === true) if (property_exists($this->_data->meta, 'syntaxcoloring') && $this->_data->meta->syntaxcoloring === true) {
{
$this->_data->meta->formatter = 'syntaxhighlighting'; $this->_data->meta->formatter = 'syntaxhighlighting';
} } else {
else
{
$this->_data->meta->formatter = $this->_conf->getKey('defaultformatter'); $this->_data->meta->formatter = $this->_conf->getKey('defaultformatter');
} }
} }
// support old paste format with server wide salt // support old paste format with server wide salt
if (!property_exists($this->_data->meta, 'salt')) if (!property_exists($this->_data->meta, 'salt')) {
{
$this->_data->meta->salt = serversalt::get(); $this->_data->meta->salt = serversalt::get();
} }
$this->_data->comments = array_values($this->getComments()); $this->_data->comments = array_values($this->getComments());
@ -84,8 +79,9 @@ class paste extends AbstractModel
public function store() public function store()
{ {
// Check for improbable collision. // Check for improbable collision.
if ($this->exists()) if ($this->exists()) {
throw new Exception('You are unlucky. Try again.', 75); throw new Exception('You are unlucky. Try again.', 75);
}
$this->_data->meta->postdate = time(); $this->_data->meta->postdate = time();
$this->_data->meta->salt = serversalt::generate(); $this->_data->meta->salt = serversalt::generate();
@ -96,7 +92,9 @@ class paste extends AbstractModel
$this->getId(), $this->getId(),
json_decode(json_encode($this->_data), true) json_decode(json_encode($this->_data), true)
) === false ) === false
) throw new Exception('Error saving paste. Sorry.', 76); ) {
throw new Exception('Error saving paste. Sorry.', 76);
}
} }
/** /**
@ -133,14 +131,15 @@ class paste extends AbstractModel
*/ */
public function getComment($parentId, $commentId = null) public function getComment($parentId, $commentId = null)
{ {
if (!$this->exists()) if (!$this->exists()) {
{
throw new Exception('Invalid data.', 62); throw new Exception('Invalid data.', 62);
} }
$comment = new comment($this->_conf, $this->_store); $comment = new comment($this->_conf, $this->_store);
$comment->setPaste($this); $comment->setPaste($this);
$comment->setParentId($parentId); $comment->setParentId($parentId);
if ($commentId !== null) $comment->setId($commentId); if ($commentId !== null) {
$comment->setId($commentId);
}
return $comment; return $comment;
} }
@ -167,7 +166,9 @@ class paste extends AbstractModel
*/ */
public function getDeleteToken() public function getDeleteToken()
{ {
if (!property_exists($this->_data->meta, 'salt')) $this->get(); if (!property_exists($this->_data->meta, 'salt')) {
$this->get();
}
return hash_hmac( return hash_hmac(
$this->_conf->getKey('zerobincompatibility') ? 'sha1' : 'sha256', $this->_conf->getKey('zerobincompatibility') ? 'sha1' : 'sha256',
$this->getId(), $this->getId(),
@ -185,8 +186,9 @@ class paste extends AbstractModel
*/ */
public function setAttachment($attachment) public function setAttachment($attachment)
{ {
if (!$this->_conf->getKey('fileupload') || !sjcl::isValid($attachment)) if (!$this->_conf->getKey('fileupload') || !sjcl::isValid($attachment)) {
throw new Exception('Invalid attachment.', 71); throw new Exception('Invalid attachment.', 71);
}
$this->_data->meta->attachment = $attachment; $this->_data->meta->attachment = $attachment;
} }
@ -200,8 +202,9 @@ class paste extends AbstractModel
*/ */
public function setAttachmentName($attachmentname) public function setAttachmentName($attachmentname)
{ {
if (!$this->_conf->getKey('fileupload') || !sjcl::isValid($attachmentname)) if (!$this->_conf->getKey('fileupload') || !sjcl::isValid($attachmentname)) {
throw new Exception('Invalid attachment.', 72); throw new Exception('Invalid attachment.', 72);
}
$this->_data->meta->attachmentname = $attachmentname; $this->_data->meta->attachmentname = $attachmentname;
} }
@ -215,16 +218,15 @@ class paste extends AbstractModel
public function setExpiration($expiration) public function setExpiration($expiration)
{ {
$expire_options = $this->_conf->getSection('expire_options'); $expire_options = $this->_conf->getSection('expire_options');
if (array_key_exists($expiration, $expire_options)) if (array_key_exists($expiration, $expire_options)) {
{
$expire = $expire_options[$expiration]; $expire = $expire_options[$expiration];
} } else {
else
{
// using getKey() to ensure a default value is present // using getKey() to ensure a default value is present
$expire = $this->_conf->getKey($this->_conf->getKey('default', 'expire'), 'expire_options'); $expire = $this->_conf->getKey($this->_conf->getKey('default', 'expire'), 'expire_options');
} }
if ($expire > 0) $this->_data->meta->expire_date = time() + $expire; if ($expire > 0) {
$this->_data->meta->expire_date = time() + $expire;
}
} }
/** /**
@ -237,14 +239,12 @@ class paste extends AbstractModel
*/ */
public function setBurnafterreading($burnafterreading = '1') public function setBurnafterreading($burnafterreading = '1')
{ {
if ($burnafterreading === '0') if ($burnafterreading === '0') {
{
$this->_data->meta->burnafterreading = false; $this->_data->meta->burnafterreading = false;
} } else {
else if ($burnafterreading !== '1') {
{
if ($burnafterreading !== '1')
throw new Exception('Invalid data.', 73); throw new Exception('Invalid data.', 73);
}
$this->_data->meta->burnafterreading = true; $this->_data->meta->burnafterreading = true;
$this->_data->meta->opendiscussion = false; $this->_data->meta->opendiscussion = false;
} }
@ -264,14 +264,12 @@ class paste extends AbstractModel
!$this->_conf->getKey('discussion') || !$this->_conf->getKey('discussion') ||
$this->isBurnafterreading() || $this->isBurnafterreading() ||
$opendiscussion === '0' $opendiscussion === '0'
) ) {
{
$this->_data->meta->opendiscussion = false; $this->_data->meta->opendiscussion = false;
} } else {
else if ($opendiscussion !== '1') {
{
if ($opendiscussion !== '1')
throw new Exception('Invalid data.', 74); throw new Exception('Invalid data.', 74);
}
$this->_data->meta->opendiscussion = true; $this->_data->meta->opendiscussion = true;
} }
} }
@ -286,8 +284,7 @@ class paste extends AbstractModel
*/ */
public function setFormatter($format) public function setFormatter($format)
{ {
if (!array_key_exists($format, $this->_conf->getSection('formatter_options'))) if (!array_key_exists($format, $this->_conf->getSection('formatter_options'))) {
{
$format = $this->_conf->getKey('defaultformatter'); $format = $this->_conf->getKey('defaultformatter');
} }
$this->_data->meta->formatter = $format; $this->_data->meta->formatter = $format;
@ -302,7 +299,9 @@ class paste extends AbstractModel
*/ */
public function isBurnafterreading() public function isBurnafterreading()
{ {
if (!property_exists($this->_data, 'data')) $this->get(); if (!property_exists($this->_data, 'data')) {
$this->get();
}
return property_exists($this->_data->meta, 'burnafterreading') && return property_exists($this->_data->meta, 'burnafterreading') &&
$this->_data->meta->burnafterreading === true; $this->_data->meta->burnafterreading === true;
} }
@ -317,7 +316,9 @@ class paste extends AbstractModel
*/ */
public function isOpendiscussion() public function isOpendiscussion()
{ {
if (!property_exists($this->_data, 'data')) $this->get(); if (!property_exists($this->_data, 'data')) {
$this->get();
}
return property_exists($this->_data->meta, 'opendiscussion') && return property_exists($this->_data->meta, 'opendiscussion') &&
$this->_data->meta->opendiscussion === true; $this->_data->meta->opendiscussion === true;
} }

View File

@ -53,12 +53,9 @@ abstract class persistence
*/ */
public static function getPath($filename = null) public static function getPath($filename = null)
{ {
if (strlen($filename)) if (strlen($filename)) {
{
return self::$_path . DIRECTORY_SEPARATOR . $filename; return self::$_path . DIRECTORY_SEPARATOR . $filename;
} } else {
else
{
return self::$_path; return self::$_path;
} }
} }
@ -88,14 +85,15 @@ abstract class persistence
protected static function _initialize() protected static function _initialize()
{ {
// Create storage directory if it does not exist. // Create storage directory if it does not exist.
if (!is_dir(self::$_path)) if (!is_dir(self::$_path)) {
if (!@mkdir(self::$_path)) if (!@mkdir(self::$_path)) {
throw new Exception('unable to create directory ' . self::$_path, 10); throw new Exception('unable to create directory ' . self::$_path, 10);
}
}
// Create .htaccess file if it does not exist. // Create .htaccess file if it does not exist.
$file = self::$_path . DIRECTORY_SEPARATOR . '.htaccess'; $file = self::$_path . DIRECTORY_SEPARATOR . '.htaccess';
if (!is_file($file)) if (!is_file($file)) {
{
$writtenBytes = @file_put_contents( $writtenBytes = @file_put_contents(
$file, $file,
'Allow from none' . PHP_EOL . 'Allow from none' . PHP_EOL .
@ -123,8 +121,7 @@ abstract class persistence
self::_initialize(); self::_initialize();
$file = self::$_path . DIRECTORY_SEPARATOR . $filename; $file = self::$_path . DIRECTORY_SEPARATOR . $filename;
$writtenBytes = @file_put_contents($file, $data, LOCK_EX); $writtenBytes = @file_put_contents($file, $data, LOCK_EX);
if ($writtenBytes === false || $writtenBytes < strlen($data)) if ($writtenBytes === false || $writtenBytes < strlen($data)) {
{
throw new Exception('unable to write to file ' . $file, 13); throw new Exception('unable to write to file ' . $file, 13);
} }
@chmod($file, 0640); // protect file access @chmod($file, 0640); // protect file access

View File

@ -117,16 +117,14 @@ class privatebin
*/ */
public function __construct() public function __construct()
{ {
if (version_compare(PHP_VERSION, '5.3.0') < 0) if (version_compare(PHP_VERSION, '5.3.0') < 0) {
{
throw new Exception(i18n::_('PrivateBin requires php 5.3.0 or above to work. Sorry.'), 1); throw new Exception(i18n::_('PrivateBin requires php 5.3.0 or above to work. Sorry.'), 1);
} }
// load config from ini file // load config from ini file
$this->_init(); $this->_init();
switch ($this->_request->getOperation()) switch ($this->_request->getOperation()) {
{
case 'create': case 'create':
$this->_create(); $this->_create();
break; break;
@ -145,16 +143,13 @@ class privatebin
} }
// output JSON or HTML // output JSON or HTML
if ($this->_request->isJsonApiCall()) if ($this->_request->isJsonApiCall()) {
{
header('Content-type: ' . request::MIME_JSON); header('Content-type: ' . request::MIME_JSON);
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type'); header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
echo $this->_json; echo $this->_json;
} } else {
else
{
$this->_view(); $this->_view();
} }
} }
@ -167,15 +162,16 @@ class privatebin
*/ */
private function _init() private function _init()
{ {
foreach (array('cfg', 'lib') as $dir) foreach (array('cfg', 'lib') as $dir) {
{ if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) {
if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) file_put_contents( file_put_contents(
PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess', PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
'Allow from none' . PHP_EOL . 'Allow from none' . PHP_EOL .
'Deny from all'. PHP_EOL, 'Deny from all'. PHP_EOL,
LOCK_EX LOCK_EX
); );
} }
}
$this->_conf = new configuration; $this->_conf = new configuration;
$this->_model = new model($this->_conf); $this->_model = new model($this->_conf);
@ -187,8 +183,7 @@ class privatebin
$lang = $this->_conf->getKey('languagedefault'); $lang = $this->_conf->getKey('languagedefault');
i18n::setLanguageFallback($lang); i18n::setLanguageFallback($lang);
// force default language, if language selection is disabled and a default is set // force default language, if language selection is disabled and a default is set
if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
{
$_COOKIE['lang'] = $lang; $_COOKIE['lang'] = $lang;
setcookie('lang', $lang); setcookie('lang', $lang);
} }
@ -218,12 +213,14 @@ class privatebin
{ {
// Ensure last paste from visitors IP address was more than configured amount of seconds ago. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
trafficlimiter::setConfiguration($this->_conf); trafficlimiter::setConfiguration($this->_conf);
if (!trafficlimiter::canPass()) return $this->_return_message( if (!trafficlimiter::canPass()) {
return $this->_return_message(
1, i18n::_( 1, i18n::_(
'Please wait %d seconds between each post.', 'Please wait %d seconds between each post.',
$this->_conf->getKey('limit', 'traffic') $this->_conf->getKey('limit', 'traffic')
) )
); );
}
$data = $this->_request->getParam('data'); $data = $this->_request->getParam('data');
$attachment = $this->_request->getParam('attachment'); $attachment = $this->_request->getParam('attachment');
@ -233,32 +230,34 @@ class privatebin
$sizelimit = $this->_conf->getKey('sizelimit'); $sizelimit = $this->_conf->getKey('sizelimit');
if ( if (
strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
) return $this->_return_message( ) {
return $this->_return_message(
1, 1,
i18n::_( i18n::_(
'Paste is limited to %s of encrypted data.', 'Paste is limited to %s of encrypted data.',
filter::size_humanreadable($sizelimit) filter::size_humanreadable($sizelimit)
) )
); );
}
// Ensure attachment did not get lost due to webserver limits or Suhosin // Ensure attachment did not get lost due to webserver limits or Suhosin
if (strlen($attachmentname) > 0 && strlen($attachment) == 0) if (strlen($attachmentname) > 0 && strlen($attachment) == 0) {
{
return $this->_return_message(1, 'Attachment missing in data received by server. Please check your webserver or suhosin configuration for maximum POST parameter limitations.'); return $this->_return_message(1, 'Attachment missing in data received by server. Please check your webserver or suhosin configuration for maximum POST parameter limitations.');
} }
// The user posts a comment. // The user posts a comment.
$pasteid = $this->_request->getParam('pasteid'); $pasteid = $this->_request->getParam('pasteid');
$parentid = $this->_request->getParam('parentid'); $parentid = $this->_request->getParam('parentid');
if (!empty($pasteid) && !empty($parentid)) if (!empty($pasteid) && !empty($parentid)) {
{
$paste = $this->_model->getPaste($pasteid); $paste = $this->_model->getPaste($pasteid);
if ($paste->exists()) { if ($paste->exists()) {
try { try {
$comment = $paste->getComment($parentid); $comment = $paste->getComment($parentid);
$nickname = $this->_request->getParam('nickname'); $nickname = $this->_request->getParam('nickname');
if (!empty($nickname)) $comment->setNickname($nickname); if (!empty($nickname)) {
$comment->setNickname($nickname);
}
$comment->setData($data); $comment->setData($data);
$comment->store(); $comment->store();
@ -266,38 +265,43 @@ class privatebin
return $this->_return_message(1, $e->getMessage()); return $this->_return_message(1, $e->getMessage());
} }
$this->_return_message(0, $comment->getId()); $this->_return_message(0, $comment->getId());
} } else {
else
{
$this->_return_message(1, 'Invalid data.'); $this->_return_message(1, 'Invalid data.');
} }
} }
// The user posts a standard paste. // The user posts a standard paste.
else else {
{
$this->_model->purge(); $this->_model->purge();
$paste = $this->_model->getPaste(); $paste = $this->_model->getPaste();
try { try {
$paste->setData($data); $paste->setData($data);
if (!empty($attachment)) if (!empty($attachment)) {
{
$paste->setAttachment($attachment); $paste->setAttachment($attachment);
if (!empty($attachmentname)) if (!empty($attachmentname)) {
$paste->setAttachmentName($attachmentname); $paste->setAttachmentName($attachmentname);
} }
}
$expire = $this->_request->getParam('expire'); $expire = $this->_request->getParam('expire');
if (!empty($expire)) $paste->setExpiration($expire); if (!empty($expire)) {
$paste->setExpiration($expire);
}
$burnafterreading = $this->_request->getParam('burnafterreading'); $burnafterreading = $this->_request->getParam('burnafterreading');
if (!empty($burnafterreading)) $paste->setBurnafterreading($burnafterreading); if (!empty($burnafterreading)) {
$paste->setBurnafterreading($burnafterreading);
}
$opendiscussion = $this->_request->getParam('opendiscussion'); $opendiscussion = $this->_request->getParam('opendiscussion');
if (!empty($opendiscussion)) $paste->setOpendiscussion($opendiscussion); if (!empty($opendiscussion)) {
$paste->setOpendiscussion($opendiscussion);
}
$formatter = $this->_request->getParam('formatter'); $formatter = $this->_request->getParam('formatter');
if (!empty($formatter)) $paste->setFormatter($formatter); if (!empty($formatter)) {
$paste->setFormatter($formatter);
}
$paste->store(); $paste->store();
} catch (Exception $e) { } catch (Exception $e) {
@ -319,40 +323,28 @@ class privatebin
{ {
try { try {
$paste = $this->_model->getPaste($dataid); $paste = $this->_model->getPaste($dataid);
if ($paste->exists()) if ($paste->exists()) {
{
// accessing this property ensures that the paste would be // accessing this property ensures that the paste would be
// deleted if it has already expired // deleted if it has already expired
$burnafterreading = $paste->isBurnafterreading(); $burnafterreading = $paste->isBurnafterreading();
if ($deletetoken == 'burnafterreading') if ($deletetoken == 'burnafterreading') {
{ if ($burnafterreading) {
if ($burnafterreading)
{
$paste->delete(); $paste->delete();
$this->_return_message(0, $dataid); $this->_return_message(0, $dataid);
} } else {
else
{
$this->_return_message(1, 'Paste is not of burn-after-reading type.'); $this->_return_message(1, 'Paste is not of burn-after-reading type.');
} }
} } else {
else
{
// Make sure the token is valid. // Make sure the token is valid.
if (filter::slow_equals($deletetoken, $paste->getDeleteToken())) if (filter::slow_equals($deletetoken, $paste->getDeleteToken())) {
{
// Paste exists and deletion token is valid: Delete the paste. // Paste exists and deletion token is valid: Delete the paste.
$paste->delete(); $paste->delete();
$this->_status = 'Paste was properly deleted.'; $this->_status = 'Paste was properly deleted.';
} } else {
else
{
$this->_error = 'Wrong deletion token. Paste was not deleted.'; $this->_error = 'Wrong deletion token. Paste was not deleted.';
} }
} }
} } else {
else
{
$this->_error = self::GENERIC_ERROR; $this->_error = self::GENERIC_ERROR;
} }
} catch (Exception $e) { } catch (Exception $e) {
@ -371,29 +363,24 @@ class privatebin
{ {
try { try {
$paste = $this->_model->getPaste($dataid); $paste = $this->_model->getPaste($dataid);
if ($paste->exists()) if ($paste->exists()) {
{
$data = $paste->get(); $data = $paste->get();
$this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date'); $this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date');
if (property_exists($data->meta, 'salt')) unset($data->meta->salt); if (property_exists($data->meta, 'salt')) {
$this->_data = json_encode($data); unset($data->meta->salt);
} }
else $this->_data = json_encode($data);
{ } else {
$this->_error = self::GENERIC_ERROR; $this->_error = self::GENERIC_ERROR;
} }
} catch (Exception $e) { } catch (Exception $e) {
$this->_error = $e->getMessage(); $this->_error = $e->getMessage();
} }
if ($this->_request->isJsonApiCall()) if ($this->_request->isJsonApiCall()) {
{ if (strlen($this->_error)) {
if (strlen($this->_error))
{
$this->_return_message(1, $this->_error); $this->_return_message(1, $this->_error);
} } else {
else
{
$this->_return_message(0, $dataid, json_decode($this->_data, true)); $this->_return_message(0, $dataid, json_decode($this->_data, true));
} }
} }
@ -417,8 +404,7 @@ class privatebin
// label all the expiration options // label all the expiration options
$expire = array(); $expire = array();
foreach ($this->_conf->getSection('expire_options') as $time => $seconds) foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
{
$expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time); $expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time);
} }
@ -427,8 +413,7 @@ class privatebin
// set language cookie if that functionality was enabled // set language cookie if that functionality was enabled
$languageselection = ''; $languageselection = '';
if ($this->_conf->getKey('languageselection')) if ($this->_conf->getKey('languageselection')) {
{
$languageselection = i18n::getLanguage(); $languageselection = i18n::getLanguage();
setcookie('lang', $languageselection); setcookie('lang', $languageselection);
} }
@ -471,14 +456,12 @@ class privatebin
if ( if (
$type !== 'paste' && $type !== 'comment' && $type !== 'paste' && $type !== 'comment' &&
$type !== 'pastemeta' && $type !== 'commentmeta' $type !== 'pastemeta' && $type !== 'commentmeta'
) ) {
{
$type = ''; $type = '';
} }
$content = '{}'; $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)) if (is_readable($file)) {
{
$content = str_replace( $content = str_replace(
'?jsonld=', '?jsonld=',
$this->_urlbase . '?jsonld=', $this->_urlbase . '?jsonld=',
@ -504,12 +487,9 @@ class privatebin
private function _return_message($status, $message, $other = array()) private function _return_message($status, $message, $other = array())
{ {
$result = array('status' => $status); $result = array('status' => $status);
if ($status) if ($status) {
{
$result['message'] = i18n::_($message); $result['message'] = i18n::_($message);
} } else {
else
{
$result['id'] = $message; $result['id'] = $message;
$result['url'] = $this->_urlbase . '?' . $message; $result['url'] = $this->_urlbase . '?' . $message;
} }

View File

@ -66,12 +66,13 @@ class purgelimiter extends persistence
public static function canPurge() public static function canPurge()
{ {
// disable limits if set to less then 1 // disable limits if set to less then 1
if (self::$_limit < 1) return true; if (self::$_limit < 1) {
return true;
}
$file = 'purge_limiter.php'; $file = 'purge_limiter.php';
$now = time(); $now = time();
if (!self::_exists($file)) if (!self::_exists($file)) {
{
self::_store( self::_store(
$file, $file,
'<?php' . PHP_EOL . '<?php' . PHP_EOL .
@ -83,12 +84,9 @@ class purgelimiter extends persistence
require $path; require $path;
$pl = $GLOBALS['purge_limiter']; $pl = $GLOBALS['purge_limiter'];
if ($pl + self::$_limit >= $now) if ($pl + self::$_limit >= $now) {
{
$result = false; $result = false;
} } else {
else
{
$result = true; $result = true;
self::_store( self::_store(
$file, $file,

View File

@ -81,8 +81,7 @@ class request
public function __construct() public function __construct()
{ {
// in case stupid admin has left magic_quotes enabled in php.ini (for PHP < 5.4) // in case stupid admin has left magic_quotes enabled in php.ini (for PHP < 5.4)
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
{
$_POST = array_map('filter::stripslashes_deep', $_POST); $_POST = array_map('filter::stripslashes_deep', $_POST);
$_GET = array_map('filter::stripslashes_deep', $_GET); $_GET = array_map('filter::stripslashes_deep', $_GET);
$_COOKIE = array_map('filter::stripslashes_deep', $_COOKIE); $_COOKIE = array_map('filter::stripslashes_deep', $_COOKIE);
@ -92,8 +91,7 @@ class request
$this->_isJsonApi = $this->_detectJsonRequest(); $this->_isJsonApi = $this->_detectJsonRequest();
// parse parameters, depending on request type // parse parameters, depending on request type
switch (array_key_exists('REQUEST_METHOD', $_SERVER) ? $_SERVER['REQUEST_METHOD'] : 'GET') switch (array_key_exists('REQUEST_METHOD', $_SERVER) ? $_SERVER['REQUEST_METHOD'] : 'GET') {
{
case 'DELETE': case 'DELETE':
case 'PUT': case 'PUT':
parse_str(file_get_contents(self::$_inputStream), $this->_params); parse_str(file_get_contents(self::$_inputStream), $this->_params);
@ -109,8 +107,7 @@ class request
!array_key_exists('jsonld', $this->_params) && !array_key_exists('jsonld', $this->_params) &&
array_key_exists('QUERY_STRING', $_SERVER) && array_key_exists('QUERY_STRING', $_SERVER) &&
!empty($_SERVER['QUERY_STRING']) !empty($_SERVER['QUERY_STRING'])
) ) {
{
$this->_params['pasteid'] = $_SERVER['QUERY_STRING']; $this->_params['pasteid'] = $_SERVER['QUERY_STRING'];
} }
@ -118,23 +115,15 @@ class request
if ( if (
(array_key_exists('data', $this->_params) && !empty($this->_params['data'])) || (array_key_exists('data', $this->_params) && !empty($this->_params['data'])) ||
(array_key_exists('attachment', $this->_params) && !empty($this->_params['attachment'])) (array_key_exists('attachment', $this->_params) && !empty($this->_params['attachment']))
) ) {
{
$this->_operation = 'create'; $this->_operation = 'create';
} } elseif (array_key_exists('pasteid', $this->_params) && !empty($this->_params['pasteid'])) {
elseif (array_key_exists('pasteid', $this->_params) && !empty($this->_params['pasteid'])) if (array_key_exists('deletetoken', $this->_params) && !empty($this->_params['deletetoken'])) {
{
if (array_key_exists('deletetoken', $this->_params) && !empty($this->_params['deletetoken']))
{
$this->_operation = 'delete'; $this->_operation = 'delete';
} } else {
else
{
$this->_operation = 'read'; $this->_operation = 'read';
} }
} } elseif (array_key_exists('jsonld', $this->_params) && !empty($this->_params['jsonld'])) {
elseif (array_key_exists('jsonld', $this->_params) && !empty($this->_params['jsonld']))
{
$this->_operation = 'jsonld'; $this->_operation = 'jsonld';
} }
} }
@ -205,53 +194,42 @@ class request
strpos($acceptHeader, self::MIME_JSON) !== false && strpos($acceptHeader, self::MIME_JSON) !== false &&
strpos($acceptHeader, self::MIME_HTML) === false && strpos($acceptHeader, self::MIME_HTML) === false &&
strpos($acceptHeader, self::MIME_XHTML) === false) strpos($acceptHeader, self::MIME_XHTML) === false)
) ) {
{
return true; return true;
} }
// advanced case: media type negotiation // advanced case: media type negotiation
$mediaTypes = array(); $mediaTypes = array();
if ($hasAcceptHeader) if ($hasAcceptHeader) {
{
$mediaTypeRanges = explode(',', trim($acceptHeader)); $mediaTypeRanges = explode(',', trim($acceptHeader));
foreach ($mediaTypeRanges as $mediaTypeRange) foreach ($mediaTypeRanges as $mediaTypeRange) {
{
if (preg_match( if (preg_match(
'#(\*/\*|[a-z\-]+/[a-z\-+*]+(?:\s*;\s*[^q]\S*)*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?#', '#(\*/\*|[a-z\-]+/[a-z\-+*]+(?:\s*;\s*[^q]\S*)*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?#',
trim($mediaTypeRange), $match trim($mediaTypeRange), $match
)) )) {
{ if (!isset($match[2])) {
if (!isset($match[2]))
{
$match[2] = '1.0'; $match[2] = '1.0';
} } else {
else
{
$match[2] = (string) floatval($match[2]); $match[2] = (string) floatval($match[2]);
} }
if (!isset($mediaTypes[$match[2]])) if (!isset($mediaTypes[$match[2]])) {
{
$mediaTypes[$match[2]] = array(); $mediaTypes[$match[2]] = array();
} }
$mediaTypes[$match[2]][] = strtolower($match[1]); $mediaTypes[$match[2]][] = strtolower($match[1]);
} }
} }
krsort($mediaTypes); krsort($mediaTypes);
foreach ($mediaTypes as $acceptedQuality => $acceptedValues) foreach ($mediaTypes as $acceptedQuality => $acceptedValues) {
{ if ($acceptedQuality === 0.0) {
if ($acceptedQuality === 0.0) continue; continue;
foreach ($acceptedValues as $acceptedValue) }
{ foreach ($acceptedValues as $acceptedValue) {
if ( if (
strpos($acceptedValue, self::MIME_HTML) === 0 || strpos($acceptedValue, self::MIME_HTML) === 0 ||
strpos($acceptedValue, self::MIME_XHTML) === 0 strpos($acceptedValue, self::MIME_XHTML) === 0
) ) {
{
return false; return false;
} } elseif (strpos($acceptedValue, self::MIME_JSON) === 0) {
elseif (strpos($acceptedValue, self::MIME_JSON) === 0)
{
return true; return true;
} }
} }

View File

@ -45,12 +45,11 @@ class serversalt extends persistence
public static function generate() public static function generate()
{ {
$randomSalt = ''; $randomSalt = '';
if (function_exists('mcrypt_create_iv')) if (function_exists('mcrypt_create_iv')) {
{
$randomSalt = bin2hex(mcrypt_create_iv(256, MCRYPT_DEV_URANDOM)); $randomSalt = bin2hex(mcrypt_create_iv(256, MCRYPT_DEV_URANDOM));
} } else {
else // fallback to mt_rand() // fallback to mt_rand()
{
for ($i = 0; $i < 256; ++$i) { for ($i = 0; $i < 256; ++$i) {
$randomSalt .= base_convert(mt_rand(), 10, 16); $randomSalt .= base_convert(mt_rand(), 10, 16);
} }
@ -68,7 +67,9 @@ class serversalt extends persistence
*/ */
public static function get() public static function get()
{ {
if (strlen(self::$_salt)) return self::$_salt; if (strlen(self::$_salt)) {
return self::$_salt;
}
$file = 'salt.php'; $file = 'salt.php';
if (self::_exists($file)) { if (self::_exists($file)) {

View File

@ -35,39 +35,68 @@ class sjcl
// Make sure content is valid json // Make sure content is valid json
$decoded = json_decode($encoded); $decoded = json_decode($encoded);
if (is_null($decoded)) return false; if (is_null($decoded)) {
return false;
}
$decoded = (array) $decoded; $decoded = (array) $decoded;
// Make sure no additionnal keys were added. // Make sure no additionnal keys were added.
if ( if (
count(array_keys($decoded)) != count($accepted_keys) count(array_keys($decoded)) != count($accepted_keys)
) return false; ) {
return false;
}
// Make sure required fields are present and contain base64 data. // Make sure required fields are present and contain base64 data.
foreach($accepted_keys as $k) foreach ($accepted_keys as $k) {
{ if (!array_key_exists($k, $decoded)) {
if (!array_key_exists($k, $decoded)) return false; return false;
}
} }
// Make sure some fields are base64 data. // Make sure some fields are base64 data.
if (!base64_decode($decoded['iv'], true)) return false; if (!base64_decode($decoded['iv'], true)) {
if (!base64_decode($decoded['salt'], true)) return false; return false;
if (!($ct = base64_decode($decoded['ct'], true))) return false; }
if (!base64_decode($decoded['salt'], true)) {
return false;
}
if (!($ct = base64_decode($decoded['ct'], true))) {
return false;
}
// Make sure some fields have a reasonable size. // Make sure some fields have a reasonable size.
if (strlen($decoded['iv']) > 24) return false; if (strlen($decoded['iv']) > 24) {
if (strlen($decoded['salt']) > 14) return false; return false;
}
if (strlen($decoded['salt']) > 14) {
return false;
}
// Make sure some fields contain no unsupported values. // Make sure some fields contain no unsupported values.
if (!(is_int($decoded['v']) || is_float($decoded['v'])) || (float) $decoded['v'] < 1) return false; if (!(is_int($decoded['v']) || is_float($decoded['v'])) || (float) $decoded['v'] < 1) {
if (!is_int($decoded['iter']) || $decoded['iter'] <= 100) return false; return false;
if (!in_array($decoded['ks'], array(128, 192, 256), true)) return false; }
if (!in_array($decoded['ts'], array(64, 96, 128), true)) return false; if (!is_int($decoded['iter']) || $decoded['iter'] <= 100) {
if (!in_array($decoded['mode'], array('ccm', 'ocb2', 'gcm'), true)) return false; return false;
if ($decoded['cipher'] !== 'aes') return false; }
if (!in_array($decoded['ks'], array(128, 192, 256), true)) {
return false;
}
if (!in_array($decoded['ts'], array(64, 96, 128), true)) {
return false;
}
if (!in_array($decoded['mode'], array('ccm', 'ocb2', 'gcm'), true)) {
return false;
}
if ($decoded['cipher'] !== 'aes') {
return false;
}
// Reject data if entropy is too low // Reject data if entropy is too low
if (strlen($ct) > strlen(gzdeflate($ct))) return false; if (strlen($ct) > strlen(gzdeflate($ct))) {
return false;
}
return true; return true;
} }

View File

@ -62,11 +62,9 @@ class trafficlimiter extends persistence
{ {
self::setLimit($conf->getKey('limit', 'traffic')); self::setLimit($conf->getKey('limit', 'traffic'));
self::setPath($conf->getKey('dir', 'traffic')); self::setPath($conf->getKey('dir', 'traffic'));
if (($option = $conf->getKey('header', 'traffic')) !== null) if (($option = $conf->getKey('header', 'traffic')) !== null) {
{
$httpHeader = 'HTTP_' . $option; $httpHeader = 'HTTP_' . $option;
if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) {
{
self::$_ipKey = $httpHeader; self::$_ipKey = $httpHeader;
} }
} }
@ -97,13 +95,14 @@ class trafficlimiter extends persistence
public static function canPass() public static function canPass()
{ {
// disable limits if set to less then 1 // disable limits if set to less then 1
if (self::$_limit < 1) return true; if (self::$_limit < 1) {
return true;
}
$ip = hash_hmac('sha256', self::getIp(), serversalt::get()); $ip = hash_hmac('sha256', self::getIp(), serversalt::get());
$file = 'traffic_limiter.php'; $file = 'traffic_limiter.php';
if (!self::_exists($file)) if (!self::_exists($file)) {
{
self::_store( self::_store(
$file, $file,
'<?php' . PHP_EOL . '<?php' . PHP_EOL .
@ -117,16 +116,13 @@ class trafficlimiter extends persistence
$tl = $GLOBALS['traffic_limiter']; $tl = $GLOBALS['traffic_limiter'];
// purge file of expired IPs to keep it small // purge file of expired IPs to keep it small
foreach ($tl as $key => $time) foreach ($tl as $key => $time) {
{ if ($time + self::$_limit < $now) {
if ($time + self::$_limit < $now)
{
unset($tl[$key]); unset($tl[$key]);
} }
} }
if (array_key_exists($ip, $tl) && ($tl[$ip] + self::$_limit >= $now)) if (array_key_exists($ip, $tl) && ($tl[$ip] + self::$_limit >= $now)) {
{
$result = false; $result = false;
} else { } else {
$tl[$ip] = time(); $tl[$ip] = time();

View File

@ -53,8 +53,7 @@ class view
public function draw($template) public function draw($template)
{ {
$path = PATH . 'tpl' . DIRECTORY_SEPARATOR . $template . '.php'; $path = PATH . 'tpl' . DIRECTORY_SEPARATOR . $template . '.php';
if (!file_exists($path)) if (!file_exists($path)) {
{
throw new Exception('Template ' . $template . ' not found!', 80); throw new Exception('Template ' . $template . ' not found!', 80);
} }
extract($this->_variables); extract($this->_variables);

View File

@ -88,7 +88,9 @@ class vizhash16x16
*/ */
public function generate($text) public function generate($text)
{ {
if (!function_exists('gd_info')) return ''; if (!function_exists('gd_info')) {
return '';
}
// We hash the input string. // We hash the input string.
$hash=hash('sha1', $text.$this->salt).hash('md5', $text.$this->salt); $hash=hash('sha1', $text.$this->salt).hash('md5', $text.$this->salt);
@ -97,28 +99,37 @@ class vizhash16x16
// We convert the hash into an array of integers. // We convert the hash into an array of integers.
$this->VALUES=array(); $this->VALUES=array();
for($i=0; $i<$hashlen; $i=$i+2){ array_push($this->VALUES,hexdec(substr($hash,$i,2))); } for ($i=0; $i<$hashlen; $i=$i+2) {
array_push($this->VALUES, hexdec(substr($hash, $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. // Then use these integers to drive the creation of an image.
$image = imagecreatetruecolor($this->width, $this->height); $image = imagecreatetruecolor($this->width, $this->height);
$r0 = $this->getInt();$r=$r0; $r0 = $this->getInt();
$g0 = $this->getInt();$g=$g0; $r=$r0;
$b0 = $this->getInt();$b=$b0; $g0 = $this->getInt();
$g=$g0;
$b0 = $this->getInt();
$b=$b0;
// First, create an image with a specific gradient background. // 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)); $image = $this->degrade($image, $op, array($r0, $g0, $b0), array(0, 0, 0));
for($i=0; $i<7; $i=$i+1) for ($i=0; $i<7; $i=$i+1) {
{
$action=$this->getInt(); $action=$this->getInt();
$color = imagecolorallocate($image, $r, $g, $b); $color = imagecolorallocate($image, $r, $g, $b);
$r = ($r0 + $this->getInt()/25)%256; $r = ($r0 + $this->getInt()/25)%256;
$g = ($g0 + $this->getInt()/25)%256; $g = ($g0 + $this->getInt()/25)%256;
$b = ($b0 + $this->getInt()/25)%256; $b = ($b0 + $this->getInt()/25)%256;
$r0=$r; $g0=$g; $b0=$b; $r0=$r;
$g0=$g;
$b0=$b;
$this->drawshape($image, $action, $color); $this->drawshape($image, $action, $color);
} }
@ -184,20 +195,27 @@ class vizhash16x16
*/ */
private function degrade($img, $direction, $color1, $color2) private function degrade($img, $direction, $color1, $color2)
{ {
if($direction=='h') { $size = imagesx($img); $sizeinv = imagesy($img); } if ($direction=='h') {
else { $size = imagesy($img); $sizeinv = imagesx($img);} $size = imagesx($img);
$sizeinv = imagesy($img);
} else {
$size = imagesy($img);
$sizeinv = imagesx($img);
}
$diffs = array( $diffs = array(
(($color2[0]-$color1[0])/$size), (($color2[0]-$color1[0])/$size),
(($color2[1]-$color1[1])/$size), (($color2[1]-$color1[1])/$size),
(($color2[2]-$color1[2])/$size) (($color2[2]-$color1[2])/$size)
); );
for($i=0;$i<$size;$i++) for ($i=0;$i<$size;$i++) {
{
$r = $color1[0]+($diffs[0]*$i); $r = $color1[0]+($diffs[0]*$i);
$g = $color1[1]+($diffs[1]*$i); $g = $color1[1]+($diffs[1]*$i);
$b = $color1[2]+($diffs[2]*$i); $b = $color1[2]+($diffs[2]*$i);
if($direction=='h') { imageline($img,$i,0,$i,$sizeinv,imagecolorallocate($img,$r,$g,$b)); } if ($direction=='h') {
else { imageline($img,0,$i,$sizeinv,$i,imagecolorallocate($img,$r,$g,$b)); } imageline($img, $i, 0, $i, $sizeinv, imagecolorallocate($img, $r, $g, $b));
} else {
imageline($img, 0, $i, $sizeinv, $i, imagecolorallocate($img, $r, $g, $b));
}
} }
return $img; return $img;
} }
@ -213,8 +231,7 @@ class vizhash16x16
*/ */
private function drawshape($image, $action, $color) private function drawshape($image, $action, $color)
{ {
switch($action%7) switch ($action%7) {
{
case 0: case 0:
ImageFilledRectangle($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $color); ImageFilledRectangle($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $color);
break; break;

View File

@ -5,10 +5,18 @@ use PrivateBin\serversalt;
error_reporting(E_ALL | E_STRICT); error_reporting(E_ALL | E_STRICT);
// change this, if your php files and data is outside of your webservers document root // change this, if your php files and data is outside of your webservers document root
if (!defined('PUBLIC_PATH')) define('PUBLIC_PATH', '..'); if (!defined('PUBLIC_PATH')) {
if (!defined('PATH')) define('PATH', '..' . DIRECTORY_SEPARATOR); define('PUBLIC_PATH', '..');
if (!defined('CONF')) define('CONF', PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.ini'); }
if (!is_file(CONF)) copy(CONF . '.sample', CONF); if (!defined('PATH')) {
define('PATH', '..' . DIRECTORY_SEPARATOR);
}
if (!defined('CONF')) {
define('CONF', PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.ini');
}
if (!is_file(CONF)) {
copy(CONF . '.sample', CONF);
}
require PATH . 'vendor/autoload.php'; require PATH . 'vendor/autoload.php';
@ -103,8 +111,9 @@ class helper
$example = self::getPaste(); $example = self::getPaste();
// the JSON shouldn't contain the salt // the JSON shouldn't contain the salt
unset($example['meta']['salt']); unset($example['meta']['salt']);
if (count($meta)) if (count($meta)) {
$example['meta'] = $meta; $example['meta'] = $meta;
}
$example['comments'] = array(); $example['comments'] = array();
$example['comment_count'] = 0; $example['comment_count'] = 0;
$example['comment_offset'] = 0; $example['comment_offset'] = 0;
@ -181,9 +190,10 @@ class helper
*/ */
public static function confBackup() public static function confBackup()
{ {
if (!is_file(CONF . '.bak') && is_file(CONF)) if (!is_file(CONF . '.bak') && is_file(CONF)) {
rename(CONF, CONF . '.bak'); rename(CONF, CONF . '.bak');
} }
}
/** /**
* restor backup of the config file * restor backup of the config file
@ -192,9 +202,10 @@ class helper
*/ */
public static function confRestore() public static function confRestore()
{ {
if (is_file(CONF . '.bak')) if (is_file(CONF . '.bak')) {
rename(CONF . '.bak', CONF); rename(CONF . '.bak', CONF);
} }
}
/** /**
* create ini file * create ini file

View File

@ -388,7 +388,8 @@ class configurationTestGenerator
* constructor, generates the configuration test * constructor, generates the configuration test
* @param array $options * @param array $options
*/ */
public function __construct($options) { public function __construct($options)
{
$this->_options = $options; $this->_options = $options;
// generate all possible combinations of options: options^settings // generate all possible combinations of options: options^settings
$this->_generateConfigurations(); $this->_generateConfigurations();
@ -653,7 +654,8 @@ EOT;
* @throws Exception * @throws Exception
* @return array * @return array
*/ */
private function _addSetting(&$configuration, &$setting, &$section, &$option) { private function _addSetting(&$configuration, &$setting, &$section, &$option)
{
if (++$this->_iterationCount > self::MAX_ITERATIONS) { if (++$this->_iterationCount > self::MAX_ITERATIONS) {
echo 'max iterations reached, stopping', PHP_EOL; echo 'max iterations reached, stopping', PHP_EOL;
return $configuration; return $configuration;

View File

@ -135,5 +135,4 @@ class configurationTest extends PHPUnit_Framework_TestCase
$conf = new configuration; $conf = new configuration;
$this->assertEquals('PrivateBin\data\db', $conf->getKey('class', 'model'), 'old db class gets renamed'); $this->assertEquals('PrivateBin\data\db', $conf->getKey('class', 'model'), 'old db class gets renamed');
} }
} }

View File

@ -28,8 +28,9 @@ class jsonApiTest extends PHPUnit_Framework_TestCase
$_POST = array(); $_POST = array();
$_GET = array(); $_GET = array();
$_SERVER = array(); $_SERVER = array();
if ($this->_model->exists(helper::getPasteId())) if ($this->_model->exists(helper::getPasteId())) {
$this->_model->delete(helper::getPasteId()); $this->_model->delete(helper::getPasteId());
}
helper::confRestore(); helper::confRestore();
} }
@ -263,5 +264,4 @@ class jsonApiTest extends PHPUnit_Framework_TestCase
$content = ob_get_contents(); $content = ob_get_contents();
$this->assertEquals('{}', $content, 'does not output nasty data'); $this->assertEquals('{}', $content, 'does not output nasty data');
} }
} }

View File

@ -227,31 +227,23 @@ class modelTest extends PHPUnit_Framework_TestCase
$paste = helper::getPaste(array('expire_date' => time() + 3600)); $paste = helper::getPaste(array('expire_date' => time() + 3600));
$keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z'); $keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z');
$ids = array(); $ids = array();
foreach ($keys as $key) foreach ($keys as $key) {
{
$ids[$key] = substr(md5($key), 0, 16); $ids[$key] = substr(md5($key), 0, 16);
$store->delete($ids[$key]); $store->delete($ids[$key]);
$this->assertFalse($store->exists($ids[$key]), "paste $key does not yet exist"); $this->assertFalse($store->exists($ids[$key]), "paste $key does not yet exist");
if (in_array($key, array('x', 'y', 'z'))) if (in_array($key, array('x', 'y', 'z'))) {
{
$this->assertTrue($store->create($ids[$key], $paste), "store $key paste"); $this->assertTrue($store->create($ids[$key], $paste), "store $key paste");
} } else {
else
{
$this->assertTrue($store->create($ids[$key], $expired), "store $key paste"); $this->assertTrue($store->create($ids[$key], $expired), "store $key paste");
} }
$this->assertTrue($store->exists($ids[$key]), "paste $key exists after storing it"); $this->assertTrue($store->exists($ids[$key]), "paste $key exists after storing it");
} }
$this->_model->purge(10); $this->_model->purge(10);
foreach ($ids as $key => $id) foreach ($ids as $key => $id) {
{ if (in_array($key, array('x', 'y', 'z'))) {
if (in_array($key, array('x', 'y', 'z')))
{
$this->assertTrue($this->_model->getPaste($id)->exists(), "paste $key exists after purge"); $this->assertTrue($this->_model->getPaste($id)->exists(), "paste $key exists after purge");
$this->_model->getPaste($id)->delete(); $this->_model->getPaste($id)->delete();
} } else {
else
{
$this->assertFalse($this->_model->getPaste($id)->exists(), "paste $key was purged"); $this->assertFalse($this->_model->getPaste($id)->exists(), "paste $key was purged");
} }
} }

View File

@ -27,8 +27,9 @@ class privatebinTest extends PHPUnit_Framework_TestCase
$_POST = array(); $_POST = array();
$_GET = array(); $_GET = array();
$_SERVER = array(); $_SERVER = array();
if ($this->_model->exists(helper::getPasteId())) if ($this->_model->exists(helper::getPasteId())) {
$this->_model->delete(helper::getPasteId()); $this->_model->delete(helper::getPasteId());
}
helper::confRestore(); helper::confRestore();
} }

View File

@ -73,30 +73,22 @@ class privatebin_dataTest extends PHPUnit_Framework_TestCase
$paste = helper::getPaste(array('expire_date' => time() + 3600)); $paste = helper::getPaste(array('expire_date' => time() + 3600));
$keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z'); $keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z');
$ids = array(); $ids = array();
foreach ($keys as $key) foreach ($keys as $key) {
{
$ids[$key] = substr(md5($key), 0, 16); $ids[$key] = substr(md5($key), 0, 16);
$this->assertFalse($this->_model->exists($ids[$key]), "paste $key does not yet exist"); $this->assertFalse($this->_model->exists($ids[$key]), "paste $key does not yet exist");
if (in_array($key, array('x', 'y', 'z'))) if (in_array($key, array('x', 'y', 'z'))) {
{
$this->assertTrue($this->_model->create($ids[$key], $paste), "store $key paste"); $this->assertTrue($this->_model->create($ids[$key], $paste), "store $key paste");
} } else {
else
{
$this->assertTrue($this->_model->create($ids[$key], $expired), "store $key paste"); $this->assertTrue($this->_model->create($ids[$key], $expired), "store $key paste");
} }
$this->assertTrue($this->_model->exists($ids[$key]), "paste $key exists after storing it"); $this->assertTrue($this->_model->exists($ids[$key]), "paste $key exists after storing it");
} }
$this->_model->purge(10); $this->_model->purge(10);
foreach ($ids as $key => $id) foreach ($ids as $key => $id) {
{ if (in_array($key, array('x', 'y', 'z'))) {
if (in_array($key, array('x', 'y', 'z')))
{
$this->assertTrue($this->_model->exists($id), "paste $key exists after purge"); $this->assertTrue($this->_model->exists($id), "paste $key exists after purge");
$this->_model->delete($id); $this->_model->delete($id);
} } else {
else
{
$this->assertFalse($this->_model->exists($id), "paste $key was purged"); $this->assertFalse($this->_model->exists($id), "paste $key was purged");
} }
} }

View File

@ -22,7 +22,9 @@ class privatebin_dbTest extends PHPUnit_Framework_TestCase
public function tearDown() public function tearDown()
{ {
/* Tear Down Routine */ /* Tear Down Routine */
if (is_dir(PATH . 'data')) helper::rmdir(PATH . 'data'); if (is_dir(PATH . 'data')) {
helper::rmdir(PATH . 'data');
}
} }
public function testDatabaseBasedDataStoreWorks() public function testDatabaseBasedDataStoreWorks()
@ -78,31 +80,23 @@ class privatebin_dbTest extends PHPUnit_Framework_TestCase
$paste = helper::getPaste(array('expire_date' => time() + 3600)); $paste = helper::getPaste(array('expire_date' => time() + 3600));
$keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z'); $keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z');
$ids = array(); $ids = array();
foreach ($keys as $key) foreach ($keys as $key) {
{
$ids[$key] = substr(md5($key), 0, 16); $ids[$key] = substr(md5($key), 0, 16);
$this->_model->delete($ids[$key]); $this->_model->delete($ids[$key]);
$this->assertFalse($this->_model->exists($ids[$key]), "paste $key does not yet exist"); $this->assertFalse($this->_model->exists($ids[$key]), "paste $key does not yet exist");
if (in_array($key, array('x', 'y', 'z'))) if (in_array($key, array('x', 'y', 'z'))) {
{
$this->assertTrue($this->_model->create($ids[$key], $paste), "store $key paste"); $this->assertTrue($this->_model->create($ids[$key], $paste), "store $key paste");
} } else {
else
{
$this->assertTrue($this->_model->create($ids[$key], $expired), "store $key paste"); $this->assertTrue($this->_model->create($ids[$key], $expired), "store $key paste");
} }
$this->assertTrue($this->_model->exists($ids[$key]), "paste $key exists after storing it"); $this->assertTrue($this->_model->exists($ids[$key]), "paste $key exists after storing it");
} }
$this->_model->purge(10); $this->_model->purge(10);
foreach ($ids as $key => $id) foreach ($ids as $key => $id) {
{ if (in_array($key, array('x', 'y', 'z'))) {
if (in_array($key, array('x', 'y', 'z')))
{
$this->assertTrue($this->_model->exists($id), "paste $key exists after purge"); $this->assertTrue($this->_model->exists($id), "paste $key exists after purge");
$this->_model->delete($id); $this->_model->delete($id);
} } else {
else
{
$this->assertFalse($this->_model->exists($id), "paste $key was purged"); $this->assertFalse($this->_model->exists($id), "paste $key was purged");
} }
} }

View File

@ -24,7 +24,9 @@ class privatebinWithDbTest extends privatebinTest
{ {
/* Setup Routine */ /* Setup Routine */
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data'; $this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
if(!is_dir($this->_path)) mkdir($this->_path); if (!is_dir($this->_path)) {
mkdir($this->_path);
}
$this->_options['dsn'] = 'sqlite:' . $this->_path . DIRECTORY_SEPARATOR . 'tst.sq3'; $this->_options['dsn'] = 'sqlite:' . $this->_path . DIRECTORY_SEPARATOR . 'tst.sq3';
$this->_model = db::getInstance($this->_options); $this->_model = db::getInstance($this->_options);
$this->reset(); $this->reset();

View File

@ -10,7 +10,9 @@ class purgelimiterTest extends PHPUnit_Framework_TestCase
{ {
/* Setup Routine */ /* Setup Routine */
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data'; $this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
if(!is_dir($this->_path)) mkdir($this->_path); if (!is_dir($this->_path)) {
mkdir($this->_path);
}
purgelimiter::setPath($this->_path); purgelimiter::setPath($this->_path);
} }

View File

@ -16,13 +16,17 @@ class serversaltTest extends PHPUnit_Framework_TestCase
{ {
/* Setup Routine */ /* Setup Routine */
$this->_path = PATH . 'data'; $this->_path = PATH . 'data';
if(!is_dir($this->_path)) mkdir($this->_path); if (!is_dir($this->_path)) {
mkdir($this->_path);
}
serversalt::setPath($this->_path); serversalt::setPath($this->_path);
$this->_otherPath = $this->_path . DIRECTORY_SEPARATOR . 'foo'; $this->_otherPath = $this->_path . DIRECTORY_SEPARATOR . 'foo';
$this->_invalidPath = $this->_path . DIRECTORY_SEPARATOR . 'bar'; $this->_invalidPath = $this->_path . DIRECTORY_SEPARATOR . 'bar';
if(!is_dir($this->_invalidPath)) mkdir($this->_invalidPath); if (!is_dir($this->_invalidPath)) {
mkdir($this->_invalidPath);
}
$this->_invalidFile = $this->_invalidPath . DIRECTORY_SEPARATOR . 'salt.php'; $this->_invalidFile = $this->_invalidPath . DIRECTORY_SEPARATOR . 'salt.php';
} }
@ -40,9 +44,10 @@ class serversaltTest extends PHPUnit_Framework_TestCase
$salt = serversalt::get(); $salt = serversalt::get();
// mcrypt mock // mcrypt mock
if (!function_exists('mcrypt_create_iv')) if (!function_exists('mcrypt_create_iv')) {
{ if (!defined('MCRYPT_DEV_URANDOM')) {
if (!defined('MCRYPT_DEV_URANDOM')) define('MCRYPT_DEV_URANDOM', 1); define('MCRYPT_DEV_URANDOM', 1);
}
function mcrypt_create_iv($int, $flag) function mcrypt_create_iv($int, $flag)
{ {
$randomSalt = ''; $randomSalt = '';
@ -50,8 +55,7 @@ class serversaltTest extends PHPUnit_Framework_TestCase
$randomSalt .= base_convert(mt_rand(), 10, 16); $randomSalt .= base_convert(mt_rand(), 10, 16);
} }
// hex2bin requires an even length, pad if necessary // hex2bin requires an even length, pad if necessary
if (strlen($randomSalt) % 2) if (strlen($randomSalt) % 2) {
{
$randomSalt = '0' . $randomSalt; $randomSalt = '0' . $randomSalt;
} }
return hex2bin($randomSalt); return hex2bin($randomSalt);

View File

@ -13,7 +13,9 @@ class vizhash16x16Test extends PHPUnit_Framework_TestCase
{ {
/* Setup Routine */ /* Setup Routine */
$this->_path = PATH . 'data'; $this->_path = PATH . 'data';
if(!is_dir($this->_path)) mkdir($this->_path); if (!is_dir($this->_path)) {
mkdir($this->_path);
}
$this->_file = $this->_path . DIRECTORY_SEPARATOR . 'vizhash.png'; $this->_file = $this->_path . DIRECTORY_SEPARATOR . 'vizhash.png';
serversalt::setPath($this->_path); serversalt::setPath($this->_path);
} }