From 5d7003ecc1468969909a77bf9aa93156a861d55a Mon Sep 17 00:00:00 2001 From: Sobak Date: Tue, 26 Jul 2016 08:19:35 +0200 Subject: [PATCH] Convert to PSR-2 coding style (using phpcs-fixer) --- lib/configuration.php | 68 ++++++------------ lib/data/AbstractData.php | 29 +++++--- lib/data/data.php | 87 ++++++++++++---------- lib/data/db.php | 135 ++++++++++++++++------------------ lib/filter.php | 11 ++- lib/i18n.php | 119 ++++++++++++++---------------- lib/model.php | 10 +-- lib/model/AbstractModel.php | 8 ++- lib/model/comment.php | 31 +++++--- lib/model/paste.php | 89 +++++++++++------------ lib/persistence.php | 19 +++-- lib/privatebin.php | 140 ++++++++++++++++-------------------- lib/purgelimiter.php | 14 ++-- lib/request.php | 66 ++++++----------- lib/serversalt.php | 17 ++--- lib/sjcl.php | 63 +++++++++++----- lib/trafficlimiter.php | 22 +++--- lib/view.php | 3 +- lib/vizhash16x16.php | 87 +++++++++++++--------- tpl/bootstrap-compact.php | 20 +++--- tpl/bootstrap-dark-page.php | 20 +++--- tpl/bootstrap-dark.php | 20 +++--- tpl/bootstrap-page.php | 20 +++--- tpl/bootstrap.php | 20 +++--- tpl/page.php | 28 ++++---- tst/bootstrap.php | 41 +++++++---- tst/configGenerator.php | 8 ++- tst/configuration.php | 1 - tst/jsonApi.php | 4 +- tst/model.php | 20 ++---- tst/privatebin.php | 3 +- tst/privatebin/data.php | 20 ++---- tst/privatebin/db.php | 24 +++---- tst/privatebinWithDb.php | 4 +- tst/purgelimiter.php | 4 +- tst/serversalt.php | 20 +++--- tst/vizhash16x16.php | 6 +- 37 files changed, 636 insertions(+), 665 deletions(-) diff --git a/lib/configuration.php b/lib/configuration.php index 86a4577a..b80b1477 100644 --- a/lib/configuration.php +++ b/lib/configuration.php @@ -98,8 +98,7 @@ class configuration { $config = array(); $configFile = PATH . 'cfg' . DIRECTORY_SEPARATOR . 'conf.ini'; - if (is_readable($configFile)) - { + if (is_readable($configFile)) { $config = parse_ini_file($configFile, true); foreach (array('main', 'model', 'model_options') as $section) { if (!array_key_exists($section, $config)) { @@ -108,14 +107,11 @@ class configuration } } $opts = '_options'; - foreach (self::getDefaults() as $section => $values) - { + foreach (self::getDefaults() as $section => $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; - 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']; } continue; @@ -126,8 +122,7 @@ class configuration $this->_configuration['model']['class'], array('privatebin_db', 'zerobin_db') ) - ) - { + ) { $values = array( 'dsn' => 'sqlite:' . PATH . 'data/db.sq3', 'tbl' => null, @@ -142,52 +137,34 @@ class configuration $section !== 'model_options' && ($from = strlen($section) - strlen($opts)) >= 0 && strpos($section, $opts, $from) !== false - ) - { - if (is_int(current($values))) - { + ) { + if (is_int(current($values))) { $config[$section] = array_map('intval', $config[$section]); } $this->_configuration[$section] = $config[$section]; } // check for missing keys and set defaults if necessary - else - { - foreach ($values as $key => $val) - { - if ($key == 'dir') - { + else { + foreach ($values as $key => $val) { + if ($key == 'dir') { $val = PATH . $val; } $result = $val; - if (array_key_exists($key, $config[$section])) - { - if ($val === null) - { + if (array_key_exists($key, $config[$section])) { + if ($val === null) { $result = $config[$section][$key]; - } - elseif (is_bool($val)) - { + } elseif (is_bool($val)) { $val = strtolower($config[$section][$key]); - if (in_array($val, array('true', 'yes', 'on'))) - { + if (in_array($val, array('true', 'yes', 'on'))) { $result = true; - } - elseif (in_array($val, array('false', 'no', 'off'))) - { + } elseif (in_array($val, array('false', 'no', 'off'))) { $result = false; - } - else - { + } else { $result = (bool) $config[$section][$key]; } - } - elseif (is_int($val)) - { + } elseif (is_int($val)) { $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]; } } @@ -209,8 +186,7 @@ class configuration ); // 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']); } } @@ -246,8 +222,7 @@ class configuration public function getKey($key, $section = 'main') { $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); } return $this->_configuration[$section][$key]; @@ -262,8 +237,7 @@ class configuration */ 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); } return $this->_configuration[$section]; diff --git a/lib/data/AbstractData.php b/lib/data/AbstractData.php index 5b0394f0..6f99f3da 100644 --- a/lib/data/AbstractData.php +++ b/lib/data/AbstractData.php @@ -35,7 +35,9 @@ abstract class AbstractData * * @access protected */ - protected function __construct() {} + protected function __construct() + { + } /** * enforce singleton, disable cloning @@ -44,7 +46,9 @@ abstract class AbstractData * * @access private */ - private function __clone() {} + private function __clone() + { + } /** * get instance of singleton @@ -54,7 +58,9 @@ abstract class AbstractData * @param array $options * @return privatebin_abstract */ - public static function getInstance($options) {} + public static function getInstance($options) + { + } /** * Create a paste. @@ -143,12 +149,12 @@ abstract class AbstractData */ public function purge($batchsize) { - if ($batchsize < 1) return; + if ($batchsize < 1) { + return; + } $pastes = $this->_getExpiredPastes($batchsize); - if (count($pastes)) - { - foreach ($pastes as $pasteid) - { + if (count($pastes)) { + foreach ($pastes as $pasteid) { $this->delete($pasteid); } } @@ -164,10 +170,11 @@ abstract class AbstractData */ protected function getOpenSlot(&$comments, $postdate) { - if (array_key_exists($postdate, $comments)) - { + if (array_key_exists($postdate, $comments)) { $parts = explode('.', $postdate, 2); - if (!array_key_exists(1, $parts)) $parts[1] = 0; + if (!array_key_exists(1, $parts)) { + $parts[1] = 0; + } ++$parts[1]; return $this->getOpenSlot($comments, implode('.', $parts)); } diff --git a/lib/data/data.php b/lib/data/data.php index a04e8d54..44826381 100644 --- a/lib/data/data.php +++ b/lib/data/data.php @@ -42,7 +42,9 @@ class data extends AbstractData if ( is_array($options) && array_key_exists('dir', $options) - ) self::$_dir = $options['dir'] . DIRECTORY_SEPARATOR; + ) { + self::$_dir = $options['dir'] . DIRECTORY_SEPARATOR; + } // if needed initialize the singleton if (!(self::$_instance instanceof privatebin_data)) { self::$_instance = new self; @@ -62,8 +64,12 @@ class data extends AbstractData public function create($pasteid, $paste) { $storagedir = self::_dataid2path($pasteid); - if (is_file($storagedir . $pasteid)) return false; - if (!is_dir($storagedir)) mkdir($storagedir, 0705, true); + if (is_file($storagedir . $pasteid)) { + return false; + } + if (!is_dir($storagedir)) { + mkdir($storagedir, 0705, true); + } return (bool) @file_put_contents($storagedir . $pasteid, json_encode($paste)); } @@ -76,16 +82,16 @@ class data extends AbstractData */ public function read($pasteid) { - if (!$this->exists($pasteid)) return false; + if (!$this->exists($pasteid)) { + return false; + } $paste = json_decode( file_get_contents(self::_dataid2path($pasteid) . $pasteid) ); - if (property_exists($paste->meta, 'attachment')) - { + if (property_exists($paste->meta, 'attachment')) { $paste->attachment = $paste->meta->attachment; unset($paste->meta->attachment); - if (property_exists($paste->meta, 'attachmentname')) - { + if (property_exists($paste->meta, 'attachmentname')) { $paste->attachmentname = $paste->meta->attachmentname; unset($paste->meta->attachmentname); } @@ -107,13 +113,13 @@ class data extends AbstractData // Delete discussion if it exists. $discdir = self::_dataid2discussionpath($pasteid); - if (is_dir($discdir)) - { + if (is_dir($discdir)) { // Delete all files in discussion directory $dir = dir($discdir); - while (false !== ($filename = $dir->read())) - { - if (is_file($discdir . $filename)) @unlink($discdir . $filename); + while (false !== ($filename = $dir->read())) { + if (is_file($discdir . $filename)) { + @unlink($discdir . $filename); + } } $dir->close(); @@ -148,8 +154,12 @@ class data extends AbstractData { $storagedir = self::_dataid2discussionpath($pasteid); $filename = $pasteid . '.' . $commentid . '.' . $parentid; - if (is_file($storagedir . $filename)) return false; - if (!is_dir($storagedir)) mkdir($storagedir, 0705, true); + if (is_file($storagedir . $filename)) { + return false; + } + if (!is_dir($storagedir)) { + mkdir($storagedir, 0705, true); + } return (bool) @file_put_contents($storagedir . $filename, json_encode($comment)); } @@ -164,18 +174,15 @@ class data extends AbstractData { $comments = array(); $discdir = self::_dataid2discussionpath($pasteid); - if (is_dir($discdir)) - { + if (is_dir($discdir)) { // Delete all files in discussion directory $dir = dir($discdir); - while (false !== ($filename = $dir->read())) - { + while (false !== ($filename = $dir->read())) { // Filename is in the form pasteid.commentid.parentid: // - pasteid is the paste this reply belongs to. // - commentid is the comment identifier itself. // - 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)); $items = explode('.', $filename); // Add some meta information not contained in file. @@ -226,11 +233,9 @@ class data extends AbstractData scandir(self::$_dir), array('self', '_isFirstLevelDir') ); - if (count($firstLevel) > 0) - { + if (count($firstLevel) > 0) { // 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); $secondLevel = array_filter( scandir(self::$_dir . $firstLevel[$firstKey]), @@ -238,8 +243,7 @@ class data extends AbstractData ); // skip this folder in the next checks if it is empty - if (count($secondLevel) == 0) - { + if (count($secondLevel) == 0) { unset($firstLevel[$firstKey]); continue; } @@ -247,26 +251,32 @@ class data extends AbstractData $secondKey = array_rand($secondLevel); $path = self::$_dir . $firstLevel[$firstKey] . DIRECTORY_SEPARATOR . $secondLevel[$secondKey]; - if (!is_dir($path)) continue; + if (!is_dir($path)) { + continue; + } $thirdLevel = array_filter( scandir($path), array('PrivateBin\\model\\paste', 'isValidId') ); - if (count($thirdLevel) == 0) continue; + if (count($thirdLevel) == 0) { + continue; + } $thirdKey = array_rand($thirdLevel); $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); if ( property_exists($data->meta, 'expire_date') && $data->meta->expire_date < time() - ) - { + ) { $pastes[] = $pasteid; - if (count($pastes) >= $batchsize) break; + if (count($pastes) >= $batchsize) { + break; + } } } } @@ -284,10 +294,11 @@ class data extends AbstractData private static function _init() { // 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. - if (!is_file(self::$_dir . '.htaccess')) - { + if (!is_file(self::$_dir . '.htaccess')) { file_put_contents( self::$_dir . '.htaccess', 'Allow from none' . PHP_EOL . diff --git a/lib/data/db.php b/lib/data/db.php index 848fc8d4..0c572ea9 100644 --- a/lib/data/db.php +++ b/lib/data/db.php @@ -71,14 +71,15 @@ class db extends AbstractData public static function getInstance($options = null) { // if needed initialize the singleton - if(!(self::$_instance instanceof privatebin_db)) { + if (!(self::$_instance instanceof privatebin_db)) { self::$_instance = new self; } - if (is_array($options)) - { + if (is_array($options)) { // 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 if ( @@ -86,8 +87,7 @@ class db extends AbstractData array_key_exists('usr', $options) && array_key_exists('pwd', $options) && array_key_exists('opt', $options) - ) - { + ) { // set default options $options['opt'][PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; $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); // create paste table if necessary - if (!in_array(self::_sanitizeIdentifier('paste'), $tables)) - { + if (!in_array(self::_sanitizeIdentifier('paste'), $tables)) { self::_createPasteTable(); $db_tables_exist = false; } // create comment table if necessary - if (!in_array(self::_sanitizeIdentifier('comment'), $tables)) - { + if (!in_array(self::_sanitizeIdentifier('comment'), $tables)) { self::_createCommentTable(); $db_tables_exist = false; } // create config table if necessary $db_version = privatebin::VERSION; - if (!in_array(self::_sanitizeIdentifier('config'), $tables)) - { + if (!in_array(self::_sanitizeIdentifier('config'), $tables)) { self::_createConfigTable(); // if we only needed to create the config table, the DB is older then 0.22 - if ($db_tables_exist) $db_version = '0.21'; - } - else - { + if ($db_tables_exist) { + $db_version = '0.21'; + } + } else { $db_version = self::_getConfig('VERSION'); } // update database structure if necessary - if (version_compare($db_version, privatebin::VERSION, '<')) - { + if (version_compare($db_version, privatebin::VERSION, '<')) { self::_upgradeDatabase($db_version); } - } - else - { + } else { throw new Exception( 'Missing configuration for key dsn, usr, pwd or opt in the section model_options, please check your configuration file', 6 ); @@ -166,7 +160,7 @@ class db extends AbstractData if ( array_key_exists($pasteid, self::$_cache) ) { - if(false !== self::$_cache[$pasteid]) { + if (false !== self::$_cache[$pasteid]) { return false; } else { unset(self::$_cache[$pasteid]); @@ -178,28 +172,23 @@ class db extends AbstractData $meta = $paste['meta']; unset($meta['postdate']); $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']; unset($meta['expire_date']); } - if (array_key_exists('opendiscussion', $paste['meta'])) - { + if (array_key_exists('opendiscussion', $paste['meta'])) { $opendiscussion = (bool) $paste['meta']['opendiscussion']; unset($meta['opendiscussion']); } - if (array_key_exists('burnafterreading', $paste['meta'])) - { + if (array_key_exists('burnafterreading', $paste['meta'])) { $burnafterreading = (bool) $paste['meta']['burnafterreading']; unset($meta['burnafterreading']); } - if (array_key_exists('attachment', $paste['meta'])) - { + if (array_key_exists('attachment', $paste['meta'])) { $attachment = $paste['meta']['attachment']; unset($meta['attachment']); } - if (array_key_exists('attachmentname', $paste['meta'])) - { + if (array_key_exists('attachmentname', $paste['meta'])) { $attachmentname = $paste['meta']['attachmentname']; unset($meta['attachmentname']); } @@ -238,31 +227,29 @@ class db extends AbstractData ' WHERE dataid = ?', array($pasteid), true ); - if(false !== $paste) { + if (false !== $paste) { // create object self::$_cache[$pasteid] = new stdClass; self::$_cache[$pasteid]->data = $paste['data']; $meta = json_decode($paste['meta']); - if (!is_object($meta)) $meta = new stdClass; + if (!is_object($meta)) { + $meta = new stdClass; + } // support older attachments - if (property_exists($meta, 'attachment')) - { + if (property_exists($meta, 'attachment')) { self::$_cache[$pasteid]->attachment = $meta->attachment; unset($meta->attachment); - if (property_exists($meta, 'attachmentname')) - { + if (property_exists($meta, 'attachmentname')) { self::$_cache[$pasteid]->attachmentname = $meta->attachmentname; unset($meta->attachmentname); } } // 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']; - if (array_key_exists('attachmentname', $paste) && strlen($paste['attachmentname'])) - { + if (array_key_exists('attachmentname', $paste) && strlen($paste['attachmentname'])) { self::$_cache[$pasteid]->attachmentname = $paste['attachmentname']; } } @@ -271,13 +258,19 @@ class db extends AbstractData $expire_date = (int) $paste['expiredate']; if ( $expire_date > 0 - ) self::$_cache[$pasteid]->meta->expire_date = $expire_date; + ) { + self::$_cache[$pasteid]->meta->expire_date = $expire_date; + } if ( $paste['opendiscussion'] - ) self::$_cache[$pasteid]->meta->opendiscussion = true; + ) { + self::$_cache[$pasteid]->meta->opendiscussion = true; + } if ( $paste['burnafterreading'] - ) self::$_cache[$pasteid]->meta->burnafterreading = true; + ) { + self::$_cache[$pasteid]->meta->burnafterreading = true; + } } } @@ -303,7 +296,9 @@ class db extends AbstractData ); if ( array_key_exists($pasteid, self::$_cache) - ) unset(self::$_cache[$pasteid]); + ) { + unset(self::$_cache[$pasteid]); + } } /** @@ -317,7 +312,9 @@ class db extends AbstractData { if ( !array_key_exists($pasteid, self::$_cache) - ) self::$_cache[$pasteid] = $this->read($pasteid); + ) { + self::$_cache[$pasteid] = $this->read($pasteid); + } return (bool) self::$_cache[$pasteid]; } @@ -333,10 +330,8 @@ class db extends AbstractData */ public function createComment($pasteid, $parentid, $commentid, $comment) { - foreach (array('nickname', 'vizhash') as $key) - { - if (!array_key_exists($key, $comment['meta'])) - { + foreach (array('nickname', 'vizhash') as $key) { + if (!array_key_exists($key, $comment['meta'])) { $comment['meta'][$key] = null; } } @@ -371,10 +366,8 @@ class db extends AbstractData // create comment list $comments = array(); - if (count($rows)) - { - foreach ($rows as $row) - { + if (count($rows)) { + foreach ($rows as $row) { $i = $this->getOpenSlot($comments, (int) $row['postdate']); $comments[$i] = new stdClass; $comments[$i]->id = $row['dataid']; @@ -382,10 +375,12 @@ class db extends AbstractData $comments[$i]->data = $row['data']; $comments[$i]->meta = new stdClass; $comments[$i]->meta->postdate = (int) $row['postdate']; - if (array_key_exists('nickname', $row) && !empty($row['nickname'])) + if (array_key_exists('nickname', $row) && !empty($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']; + } } ksort($comments); } @@ -424,10 +419,8 @@ class db extends AbstractData 'SELECT dataid FROM ' . self::_sanitizeIdentifier('paste') . ' WHERE expiredate < ? LIMIT ?', array(time(), $batchsize) ); - if (count($rows)) - { - foreach ($rows as $row) - { + if (count($rows)) { + foreach ($rows as $row) { $pastes[] = $row['dataid']; } } @@ -485,8 +478,7 @@ class db extends AbstractData */ private static function _getTableQuery($type) { - switch($type) - { + switch ($type) { case 'ibm': $sql = 'SELECT tabname FROM SYSCAT.TABLES '; break; @@ -559,12 +551,9 @@ class db extends AbstractData private static function _getPrimaryKeyClauses($key = 'dataid') { $main_key = $after_key = ''; - if (self::$_type === 'mysql') - { + if (self::$_type === 'mysql') { $after_key = ", PRIMARY KEY ($key)"; - } - else - { + } else { $main_key = ' PRIMARY KEY'; } return array($main_key, $after_key); @@ -667,8 +656,7 @@ class db extends AbstractData private static function _upgradeDatabase($oldversion) { $dataType = self::$_type === 'pgsql' ? 'TEXT' : 'BLOB'; - switch ($oldversion) - { + switch ($oldversion) { case '0.21': // create the meta column if necessary (pre 0.21 change) try { @@ -687,8 +675,7 @@ class db extends AbstractData ); // SQLite doesn't support MODIFY, but it allows TEXT of similar // size as BLOB, so there is no need to change it there - if (self::$_type !== 'sqlite') - { + if (self::$_type !== 'sqlite') { self::$_db->exec( 'ALTER TABLE ' . self::_sanitizeIdentifier('paste') . ' ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType;' @@ -698,9 +685,7 @@ class db extends AbstractData " ADD PRIMARY KEY (dataid), MODIFY COLUMN data $dataType, " . "MODIFY COLUMN nickname $dataType, MODIFY COLUMN vizhash $dataType;" ); - } - else - { + } else { self::$_db->exec( 'CREATE UNIQUE INDEX IF NOT EXISTS paste_dataid ON ' . self::_sanitizeIdentifier('paste') . '(dataid);' diff --git a/lib/filter.php b/lib/filter.php index 1922901d..06af9c2d 100644 --- a/lib/filter.php +++ b/lib/filter.php @@ -78,9 +78,9 @@ class filter { $iec = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'); $i = 0; - while ( ( $size / 1024 ) >= 1 ) { - $size = $size / 1024; - $i++; + while (($size / 1024) >= 1) { + $size = $size / 1024; + $i++; } return number_format($size, ($i ? 2 : 0), '.', ' ') . ' ' . i18n::_($iec[$i]); } @@ -98,10 +98,9 @@ class filter public static function slow_equals($a, $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]); } return $diff === 0; - } + } } diff --git a/lib/i18n.php b/lib/i18n.php index 5cd66d52..6a9a8dcc 100644 --- a/lib/i18n.php +++ b/lib/i18n.php @@ -98,30 +98,31 @@ class i18n */ public static function translate($messageId) { - if (empty($messageId)) return $messageId; - if (count(self::$_translations) === 0) self::loadTranslations(); + if (empty($messageId)) { + return $messageId; + } + if (count(self::$_translations) === 0) { + self::loadTranslations(); + } $messages = $messageId; - if (is_array($messageId)) - { + if (is_array($messageId)) { $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; } $args = func_get_args(); - if (is_array(self::$_translations[$messageId])) - { + if (is_array(self::$_translations[$messageId])) { $number = (int) $args[1]; $key = self::_getPluralForm($number); $max = count(self::$_translations[$messageId]) - 1; - if ($key > $max) $key = $max; + if ($key > $max) { + $key = $max; + } $args[0] = self::$_translations[$messageId][$key]; $args[1] = $number; - } - else - { + } else { $args[0] = self::$_translations[$messageId]; } return call_user_func_array('sprintf', $args); @@ -141,13 +142,11 @@ class i18n $availableLanguages = self::getAvailableLanguages(); // 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)]; } // find a translation file matching the browsers language preferences - else - { + else { $match = self::_getMatchingLanguage( self::getBrowserLanguages(), $availableLanguages ); @@ -170,13 +169,10 @@ class i18n */ public static function getAvailableLanguages() { - if (count(self::$_availableLanguages) == 0) - { + if (count(self::$_availableLanguages) == 0) { $i18n = dir(self::_getPath()); - while (false !== ($file = $i18n->read())) - { - if (preg_match('/^([a-z]{2}).json$/', $file, $match) === 1) - { + while (false !== ($file = $i18n->read())) { + if (preg_match('/^([a-z]{2}).json$/', $file, $match) === 1) { self::$_availableLanguages[] = $match[1]; } } @@ -197,26 +193,19 @@ class i18n public static function getBrowserLanguages() { $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'])); - foreach ($languageRanges as $languageRange) - { + foreach ($languageRanges as $languageRange) { 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})))?/', trim($languageRange), $match - )) - { - if (!isset($match[2])) - { + )) { + if (!isset($match[2])) { $match[2] = '1.0'; - } - else - { + } else { $match[2] = (string) floatval($match[2]); } - if (!isset($languages[$match[2]])) - { + if (!isset($languages[$match[2]])) { $languages[$match[2]] = array(); } $languages[$match[2]][] = strtolower($match[1]); @@ -252,11 +241,12 @@ class i18n public static function getLanguageLabels($languages = array()) { $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); } - if (count($languages) == 0) return self::$_languageLabels; + if (count($languages) == 0) { + return self::$_languageLabels; + } return array_intersect_key(self::$_languageLabels, array_flip($languages)); } @@ -270,8 +260,9 @@ class i18n */ public static function setLanguageFallback($lang) { - if (in_array($lang, self::getAvailableLanguages())) + if (in_array($lang, self::getAvailableLanguages())) { self::$_languageFallback = $lang; + } } /** @@ -284,8 +275,7 @@ class i18n */ protected static function _getPath($file = '') { - if (strlen(self::$_path) == 0) - { + if (strlen(self::$_path) == 0) { self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n'; } return self::$_path . (strlen($file) ? DIRECTORY_SEPARATOR . $file : ''); @@ -326,47 +316,40 @@ class i18n * @param array $availableLanguages * @return string */ - protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages) { + protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages) + { $matches = array(); $any = false; - foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) - { + foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) { $acceptedQuality = floatval($acceptedQuality); - if ($acceptedQuality === 0.0) continue; - foreach ($availableLanguages as $availableValue) - { + if ($acceptedQuality === 0.0) { + continue; + } + foreach ($availableLanguages as $availableValue) { $availableQuality = 1.0; - foreach ($acceptedValues as $acceptedValue) - { - if ($acceptedValue === '*') - { + foreach ($acceptedValues as $acceptedValue) { + if ($acceptedValue === '*') { $any = true; } $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue); - if ($matchingGrade > 0) - { + if ($matchingGrade > 0) { $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade); - if (!isset($matches[$q])) - { + if (!isset($matches[$q])) { $matches[$q] = array(); } - if (!in_array($availableValue, $matches[$q])) - { + if (!in_array($availableValue, $matches[$q])) { $matches[$q][] = $availableValue; } } } } } - if (count($matches) === 0 && $any) - { - if (count($availableLanguages) > 0) - { + if (count($matches) === 0 && $any) { + if (count($availableLanguages) > 0) { $matches['1.0'] = $availableLanguages; } } - if (count($matches) === 0) - { + if (count($matches) === 0) { return self::$_languageFallback; } krsort($matches); @@ -385,12 +368,14 @@ class i18n * @param string $b * @return float */ - protected static function _matchLanguage($a, $b) { + protected static function _matchLanguage($a, $b) + { $a = explode('-', $a); $b = explode('-', $b); - for ($i=0, $n = min(count($a), count($b)); $i < $n; ++$i) - { - if ($a[$i] !== $b[$i]) break; + for ($i=0, $n = min(count($a), count($b)); $i < $n; ++$i) { + if ($a[$i] !== $b[$i]) { + break; + } } return $i === 0 ? 0 : (float) $i / count($a); } diff --git a/lib/model.php b/lib/model.php index 9fbf968e..de79bb3d 100644 --- a/lib/model.php +++ b/lib/model.php @@ -55,7 +55,9 @@ class model public function getPaste($pasteId = null) { $paste = new paste($this->_conf, $this->_getStore()); - if ($pasteId !== null) $paste->setId($pasteId); + if ($pasteId !== null) { + $paste->setId($pasteId); + } return $paste; } @@ -67,8 +69,7 @@ class model public function purge() { purgelimiter::setConfiguration($this->_conf); - if (purgelimiter::canPurge()) - { + if (purgelimiter::canPurge()) { $this->_getStore()->purge($this->_conf->getKey('batchsize', 'purge')); } } @@ -80,8 +81,7 @@ class model */ private function _getStore() { - if ($this->_store === null) - { + if ($this->_store === null) { $this->_store = forward_static_call( array($this->_conf->getKey('class', 'model'), 'getInstance'), $this->_conf->getSection('model_options') diff --git a/lib/model/AbstractModel.php b/lib/model/AbstractModel.php index c7979b2c..af834f4b 100644 --- a/lib/model/AbstractModel.php +++ b/lib/model/AbstractModel.php @@ -94,7 +94,9 @@ abstract class AbstractModel */ 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; } @@ -108,7 +110,9 @@ abstract class AbstractModel */ 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; // We just want a small hash to avoid collisions: diff --git a/lib/model/comment.php b/lib/model/comment.php index 42057ab1..786a7baa 100644 --- a/lib/model/comment.php +++ b/lib/model/comment.php @@ -66,16 +66,19 @@ class comment extends AbstractModel { // Make sure paste exists. $pasteid = $this->getPaste()->getId(); - if (!$this->getPaste()->exists()) + if (!$this->getPaste()->exists()) { throw new Exception('Invalid data.', 67); + } // 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); + } // Check for improbable collision. - if ($this->exists()) + if ($this->exists()) { throw new Exception('You are unlucky. Try again.', 69); + } $this->_data->meta->postdate = time(); @@ -87,7 +90,9 @@ class comment extends AbstractModel $this->getId(), json_decode(json_encode($this->_data), true) ) === 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) { - 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; } @@ -164,7 +171,9 @@ class comment extends AbstractModel */ 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; } @@ -178,19 +187,19 @@ class comment extends AbstractModel */ 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; - if ($this->_conf->getKey('vizhash')) - { + if ($this->_conf->getKey('vizhash')) { // Generation of the anonymous avatar (Vizhash): // If a nickname is provided, we generate a Vizhash. // (We assume that if the user did not enter a nickname, he/she wants // to be anonymous and we will not generate the vizhash.) $vh = new vizhash16x16(); $pngdata = $vh->generate(trafficlimiter::getIp()); - if ($pngdata != '') - { + if ($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. diff --git a/lib/model/paste.php b/lib/model/paste.php index 42946144..e18211e0 100644 --- a/lib/model/paste.php +++ b/lib/model/paste.php @@ -34,13 +34,13 @@ class paste extends AbstractModel public function get() { $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. - if (property_exists($this->_data->meta, 'expire_date')) - { - if ($this->_data->meta->expire_date < time()) - { + if (property_exists($this->_data->meta, 'expire_date')) { + if ($this->_data->meta->expire_date < time()) { $this->delete(); throw new Exception(privatebin::GENERIC_ERROR, 63); } @@ -49,22 +49,17 @@ class paste extends AbstractModel } // 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 - 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'; - } - else - { + } else { $this->_data->meta->formatter = $this->_conf->getKey('defaultformatter'); } } // 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->comments = array_values($this->getComments()); @@ -84,8 +79,9 @@ class paste extends AbstractModel public function store() { // Check for improbable collision. - if ($this->exists()) + if ($this->exists()) { throw new Exception('You are unlucky. Try again.', 75); + } $this->_data->meta->postdate = time(); $this->_data->meta->salt = serversalt::generate(); @@ -96,7 +92,9 @@ class paste extends AbstractModel $this->getId(), json_decode(json_encode($this->_data), true) ) === 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) { - if (!$this->exists()) - { + if (!$this->exists()) { throw new Exception('Invalid data.', 62); } $comment = new comment($this->_conf, $this->_store); $comment->setPaste($this); $comment->setParentId($parentId); - if ($commentId !== null) $comment->setId($commentId); + if ($commentId !== null) { + $comment->setId($commentId); + } return $comment; } @@ -167,7 +166,9 @@ class paste extends AbstractModel */ public function getDeleteToken() { - if (!property_exists($this->_data->meta, 'salt')) $this->get(); + if (!property_exists($this->_data->meta, 'salt')) { + $this->get(); + } return hash_hmac( $this->_conf->getKey('zerobincompatibility') ? 'sha1' : 'sha256', $this->getId(), @@ -185,8 +186,9 @@ class paste extends AbstractModel */ 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); + } $this->_data->meta->attachment = $attachment; } @@ -200,8 +202,9 @@ class paste extends AbstractModel */ 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); + } $this->_data->meta->attachmentname = $attachmentname; } @@ -215,16 +218,15 @@ class paste extends AbstractModel public function setExpiration($expiration) { $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]; - } - else - { + } else { // using getKey() to ensure a default value is present $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') { - if ($burnafterreading === '0') - { + if ($burnafterreading === '0') { $this->_data->meta->burnafterreading = false; - } - else - { - if ($burnafterreading !== '1') + } else { + if ($burnafterreading !== '1') { throw new Exception('Invalid data.', 73); + } $this->_data->meta->burnafterreading = true; $this->_data->meta->opendiscussion = false; } @@ -264,14 +264,12 @@ class paste extends AbstractModel !$this->_conf->getKey('discussion') || $this->isBurnafterreading() || $opendiscussion === '0' - ) - { + ) { $this->_data->meta->opendiscussion = false; - } - else - { - if ($opendiscussion !== '1') + } else { + if ($opendiscussion !== '1') { throw new Exception('Invalid data.', 74); + } $this->_data->meta->opendiscussion = true; } } @@ -286,8 +284,7 @@ class paste extends AbstractModel */ 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'); } $this->_data->meta->formatter = $format; @@ -302,7 +299,9 @@ class paste extends AbstractModel */ 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') && $this->_data->meta->burnafterreading === true; } @@ -317,7 +316,9 @@ class paste extends AbstractModel */ 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') && $this->_data->meta->opendiscussion === true; } diff --git a/lib/persistence.php b/lib/persistence.php index 28259def..e42f1171 100644 --- a/lib/persistence.php +++ b/lib/persistence.php @@ -53,12 +53,9 @@ abstract class persistence */ public static function getPath($filename = null) { - if (strlen($filename)) - { + if (strlen($filename)) { return self::$_path . DIRECTORY_SEPARATOR . $filename; - } - else - { + } else { return self::$_path; } } @@ -88,14 +85,15 @@ abstract class persistence protected static function _initialize() { // Create storage directory if it does not exist. - if (!is_dir(self::$_path)) - if (!@mkdir(self::$_path)) + if (!is_dir(self::$_path)) { + if (!@mkdir(self::$_path)) { throw new Exception('unable to create directory ' . self::$_path, 10); + } + } // Create .htaccess file if it does not exist. $file = self::$_path . DIRECTORY_SEPARATOR . '.htaccess'; - if (!is_file($file)) - { + if (!is_file($file)) { $writtenBytes = @file_put_contents( $file, 'Allow from none' . PHP_EOL . @@ -123,8 +121,7 @@ abstract class persistence self::_initialize(); $file = self::$_path . DIRECTORY_SEPARATOR . $filename; $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); } @chmod($file, 0640); // protect file access diff --git a/lib/privatebin.php b/lib/privatebin.php index a159f9da..d2a70b97 100644 --- a/lib/privatebin.php +++ b/lib/privatebin.php @@ -117,16 +117,14 @@ class privatebin */ 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); } // load config from ini file $this->_init(); - switch ($this->_request->getOperation()) - { + switch ($this->_request->getOperation()) { case 'create': $this->_create(); break; @@ -145,16 +143,13 @@ class privatebin } // output JSON or HTML - if ($this->_request->isJsonApiCall()) - { + if ($this->_request->isJsonApiCall()) { header('Content-type: ' . request::MIME_JSON); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: X-Requested-With, Content-Type'); echo $this->_json; - } - else - { + } else { $this->_view(); } } @@ -167,14 +162,15 @@ class privatebin */ private function _init() { - foreach (array('cfg', 'lib') as $dir) - { - if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) file_put_contents( + foreach (array('cfg', 'lib') as $dir) { + if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) { + file_put_contents( PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess', 'Allow from none' . PHP_EOL . 'Deny from all'. PHP_EOL, LOCK_EX ); + } } $this->_conf = new configuration; @@ -187,8 +183,7 @@ class privatebin $lang = $this->_conf->getKey('languagedefault'); i18n::setLanguageFallback($lang); // 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; setcookie('lang', $lang); } @@ -218,12 +213,14 @@ class privatebin { // Ensure last paste from visitors IP address was more than configured amount of seconds ago. trafficlimiter::setConfiguration($this->_conf); - if (!trafficlimiter::canPass()) return $this->_return_message( + if (!trafficlimiter::canPass()) { + return $this->_return_message( 1, i18n::_( 'Please wait %d seconds between each post.', $this->_conf->getKey('limit', 'traffic') ) ); + } $data = $this->_request->getParam('data'); $attachment = $this->_request->getParam('attachment'); @@ -233,71 +230,78 @@ class privatebin $sizelimit = $this->_conf->getKey('sizelimit'); if ( strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit - ) return $this->_return_message( + ) { + return $this->_return_message( 1, i18n::_( 'Paste is limited to %s of encrypted data.', filter::size_humanreadable($sizelimit) ) ); + } // 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.'); } // The user posts a comment. $pasteid = $this->_request->getParam('pasteid'); $parentid = $this->_request->getParam('parentid'); - if (!empty($pasteid) && !empty($parentid)) - { + if (!empty($pasteid) && !empty($parentid)) { $paste = $this->_model->getPaste($pasteid); if ($paste->exists()) { try { $comment = $paste->getComment($parentid); $nickname = $this->_request->getParam('nickname'); - if (!empty($nickname)) $comment->setNickname($nickname); + if (!empty($nickname)) { + $comment->setNickname($nickname); + } $comment->setData($data); $comment->store(); - } catch(Exception $e) { + } catch (Exception $e) { return $this->_return_message(1, $e->getMessage()); } $this->_return_message(0, $comment->getId()); - } - else - { + } else { $this->_return_message(1, 'Invalid data.'); } } // The user posts a standard paste. - else - { + else { $this->_model->purge(); $paste = $this->_model->getPaste(); try { $paste->setData($data); - if (!empty($attachment)) - { + if (!empty($attachment)) { $paste->setAttachment($attachment); - if (!empty($attachmentname)) + if (!empty($attachmentname)) { $paste->setAttachmentName($attachmentname); + } } $expire = $this->_request->getParam('expire'); - if (!empty($expire)) $paste->setExpiration($expire); + if (!empty($expire)) { + $paste->setExpiration($expire); + } $burnafterreading = $this->_request->getParam('burnafterreading'); - if (!empty($burnafterreading)) $paste->setBurnafterreading($burnafterreading); + if (!empty($burnafterreading)) { + $paste->setBurnafterreading($burnafterreading); + } $opendiscussion = $this->_request->getParam('opendiscussion'); - if (!empty($opendiscussion)) $paste->setOpendiscussion($opendiscussion); + if (!empty($opendiscussion)) { + $paste->setOpendiscussion($opendiscussion); + } $formatter = $this->_request->getParam('formatter'); - if (!empty($formatter)) $paste->setFormatter($formatter); + if (!empty($formatter)) { + $paste->setFormatter($formatter); + } $paste->store(); } catch (Exception $e) { @@ -319,40 +323,28 @@ class privatebin { try { $paste = $this->_model->getPaste($dataid); - if ($paste->exists()) - { + if ($paste->exists()) { // accessing this property ensures that the paste would be // deleted if it has already expired $burnafterreading = $paste->isBurnafterreading(); - if ($deletetoken == 'burnafterreading') - { - if ($burnafterreading) - { + if ($deletetoken == 'burnafterreading') { + if ($burnafterreading) { $paste->delete(); $this->_return_message(0, $dataid); - } - else - { + } else { $this->_return_message(1, 'Paste is not of burn-after-reading type.'); } - } - else - { + } else { // 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->delete(); $this->_status = 'Paste was properly deleted.'; - } - else - { + } else { $this->_error = 'Wrong deletion token. Paste was not deleted.'; } } - } - else - { + } else { $this->_error = self::GENERIC_ERROR; } } catch (Exception $e) { @@ -371,29 +363,24 @@ class privatebin { try { $paste = $this->_model->getPaste($dataid); - if ($paste->exists()) - { + if ($paste->exists()) { $data = $paste->get(); $this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date'); - if (property_exists($data->meta, 'salt')) unset($data->meta->salt); + if (property_exists($data->meta, 'salt')) { + unset($data->meta->salt); + } $this->_data = json_encode($data); - } - else - { + } else { $this->_error = self::GENERIC_ERROR; } } catch (Exception $e) { $this->_error = $e->getMessage(); } - if ($this->_request->isJsonApiCall()) - { - if (strlen($this->_error)) - { + if ($this->_request->isJsonApiCall()) { + if (strlen($this->_error)) { $this->_return_message(1, $this->_error); - } - else - { + } else { $this->_return_message(0, $dataid, json_decode($this->_data, true)); } } @@ -417,8 +404,7 @@ class privatebin // label all the expiration options $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); } @@ -427,8 +413,7 @@ class privatebin // set language cookie if that functionality was enabled $languageselection = ''; - if ($this->_conf->getKey('languageselection')) - { + if ($this->_conf->getKey('languageselection')) { $languageselection = i18n::getLanguage(); setcookie('lang', $languageselection); } @@ -471,14 +456,12 @@ class privatebin if ( $type !== 'paste' && $type !== 'comment' && $type !== 'pastemeta' && $type !== 'commentmeta' - ) - { + ) { $type = ''; } $content = '{}'; $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld'; - if (is_readable($file)) - { + if (is_readable($file)) { $content = str_replace( '?jsonld=', $this->_urlbase . '?jsonld=', @@ -504,12 +487,9 @@ class privatebin private function _return_message($status, $message, $other = array()) { $result = array('status' => $status); - if ($status) - { + if ($status) { $result['message'] = i18n::_($message); - } - else - { + } else { $result['id'] = $message; $result['url'] = $this->_urlbase . '?' . $message; } diff --git a/lib/purgelimiter.php b/lib/purgelimiter.php index 36fa9ce8..8261b9a3 100644 --- a/lib/purgelimiter.php +++ b/lib/purgelimiter.php @@ -66,12 +66,13 @@ class purgelimiter extends persistence public static function canPurge() { // disable limits if set to less then 1 - if (self::$_limit < 1) return true; + if (self::$_limit < 1) { + return true; + } $file = 'purge_limiter.php'; $now = time(); - if (!self::_exists($file)) - { + if (!self::_exists($file)) { self::_store( $file, '= $now) - { + if ($pl + self::$_limit >= $now) { $result = false; - } - else - { + } else { $result = true; self::_store( $file, diff --git a/lib/request.php b/lib/request.php index d5d9c9d5..fec10542 100644 --- a/lib/request.php +++ b/lib/request.php @@ -81,8 +81,7 @@ class request public function __construct() { // 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); $_GET = array_map('filter::stripslashes_deep', $_GET); $_COOKIE = array_map('filter::stripslashes_deep', $_COOKIE); @@ -92,8 +91,7 @@ class request $this->_isJsonApi = $this->_detectJsonRequest(); // 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 'PUT': parse_str(file_get_contents(self::$_inputStream), $this->_params); @@ -109,8 +107,7 @@ class request !array_key_exists('jsonld', $this->_params) && array_key_exists('QUERY_STRING', $_SERVER) && !empty($_SERVER['QUERY_STRING']) - ) - { + ) { $this->_params['pasteid'] = $_SERVER['QUERY_STRING']; } @@ -118,23 +115,15 @@ class request if ( (array_key_exists('data', $this->_params) && !empty($this->_params['data'])) || (array_key_exists('attachment', $this->_params) && !empty($this->_params['attachment'])) - ) - { + ) { $this->_operation = 'create'; - } - elseif (array_key_exists('pasteid', $this->_params) && !empty($this->_params['pasteid'])) - { - if (array_key_exists('deletetoken', $this->_params) && !empty($this->_params['deletetoken'])) - { + } elseif (array_key_exists('pasteid', $this->_params) && !empty($this->_params['pasteid'])) { + if (array_key_exists('deletetoken', $this->_params) && !empty($this->_params['deletetoken'])) { $this->_operation = 'delete'; - } - else - { + } else { $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'; } } @@ -205,53 +194,42 @@ class request strpos($acceptHeader, self::MIME_JSON) !== false && strpos($acceptHeader, self::MIME_HTML) === false && strpos($acceptHeader, self::MIME_XHTML) === false) - ) - { + ) { return true; } // advanced case: media type negotiation $mediaTypes = array(); - if ($hasAcceptHeader) - { + if ($hasAcceptHeader) { $mediaTypeRanges = explode(',', trim($acceptHeader)); - foreach ($mediaTypeRanges as $mediaTypeRange) - { + foreach ($mediaTypeRanges as $mediaTypeRange) { if (preg_match( '#(\*/\*|[a-z\-]+/[a-z\-+*]+(?:\s*;\s*[^q]\S*)*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?#', trim($mediaTypeRange), $match - )) - { - if (!isset($match[2])) - { + )) { + if (!isset($match[2])) { $match[2] = '1.0'; - } - else - { + } else { $match[2] = (string) floatval($match[2]); } - if (!isset($mediaTypes[$match[2]])) - { + if (!isset($mediaTypes[$match[2]])) { $mediaTypes[$match[2]] = array(); } $mediaTypes[$match[2]][] = strtolower($match[1]); } } krsort($mediaTypes); - foreach ($mediaTypes as $acceptedQuality => $acceptedValues) - { - if ($acceptedQuality === 0.0) continue; - foreach ($acceptedValues as $acceptedValue) - { + foreach ($mediaTypes as $acceptedQuality => $acceptedValues) { + if ($acceptedQuality === 0.0) { + continue; + } + foreach ($acceptedValues as $acceptedValue) { if ( strpos($acceptedValue, self::MIME_HTML) === 0 || strpos($acceptedValue, self::MIME_XHTML) === 0 - ) - { + ) { return false; - } - elseif (strpos($acceptedValue, self::MIME_JSON) === 0) - { + } elseif (strpos($acceptedValue, self::MIME_JSON) === 0) { return true; } } diff --git a/lib/serversalt.php b/lib/serversalt.php index fe28fefb..60a99305 100644 --- a/lib/serversalt.php +++ b/lib/serversalt.php @@ -45,13 +45,12 @@ class serversalt extends persistence public static function generate() { $randomSalt = ''; - if (function_exists('mcrypt_create_iv')) - { + if (function_exists('mcrypt_create_iv')) { $randomSalt = bin2hex(mcrypt_create_iv(256, MCRYPT_DEV_URANDOM)); - } - else // fallback to mt_rand() - { - for($i = 0; $i < 256; ++$i) { + } else { + // fallback to mt_rand() + + for ($i = 0; $i < 256; ++$i) { $randomSalt .= base_convert(mt_rand(), 10, 16); } } @@ -68,7 +67,9 @@ class serversalt extends persistence */ public static function get() { - if (strlen(self::$_salt)) return self::$_salt; + if (strlen(self::$_salt)) { + return self::$_salt; + } $file = 'salt.php'; if (self::_exists($file)) { @@ -97,7 +98,7 @@ class serversalt extends persistence */ public static function setPath($path) { - self::$_salt = ''; + self::$_salt = ''; parent::setPath($path); } } diff --git a/lib/sjcl.php b/lib/sjcl.php index cc79cea4..2d2981fb 100644 --- a/lib/sjcl.php +++ b/lib/sjcl.php @@ -35,39 +35,68 @@ class sjcl // Make sure content is valid json $decoded = json_decode($encoded); - if (is_null($decoded)) return false; + if (is_null($decoded)) { + return false; + } $decoded = (array) $decoded; // Make sure no additionnal keys were added. if ( count(array_keys($decoded)) != count($accepted_keys) - ) return false; + ) { + return false; + } // Make sure required fields are present and contain base64 data. - foreach($accepted_keys as $k) - { - if (!array_key_exists($k, $decoded)) return false; + foreach ($accepted_keys as $k) { + if (!array_key_exists($k, $decoded)) { + return false; + } } // Make sure some fields are base64 data. - if (!base64_decode($decoded['iv'], true)) return false; - if (!base64_decode($decoded['salt'], true)) return false; - if (!($ct = base64_decode($decoded['ct'], true))) return false; + if (!base64_decode($decoded['iv'], 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. - if (strlen($decoded['iv']) > 24) return false; - if (strlen($decoded['salt']) > 14) return false; + if (strlen($decoded['iv']) > 24) { + return false; + } + if (strlen($decoded['salt']) > 14) { + return false; + } // 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['iter']) || $decoded['iter'] <= 100) 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; + if (!(is_int($decoded['v']) || is_float($decoded['v'])) || (float) $decoded['v'] < 1) { + return false; + } + if (!is_int($decoded['iter']) || $decoded['iter'] <= 100) { + 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 - if (strlen($ct) > strlen(gzdeflate($ct))) return false; + if (strlen($ct) > strlen(gzdeflate($ct))) { + return false; + } return true; } diff --git a/lib/trafficlimiter.php b/lib/trafficlimiter.php index ed1f5345..0c49a665 100644 --- a/lib/trafficlimiter.php +++ b/lib/trafficlimiter.php @@ -62,11 +62,9 @@ class trafficlimiter extends persistence { self::setLimit($conf->getKey('limit', 'traffic')); self::setPath($conf->getKey('dir', 'traffic')); - if (($option = $conf->getKey('header', 'traffic')) !== null) - { + if (($option = $conf->getKey('header', 'traffic')) !== null) { $httpHeader = 'HTTP_' . $option; - if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) - { + if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) { self::$_ipKey = $httpHeader; } } @@ -97,13 +95,14 @@ class trafficlimiter extends persistence public static function canPass() { // 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()); $file = 'traffic_limiter.php'; - if (!self::_exists($file)) - { + if (!self::_exists($file)) { self::_store( $file, ' $time) - { - if ($time + self::$_limit < $now) - { + foreach ($tl as $key => $time) { + if ($time + self::$_limit < $now) { 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; } else { $tl[$ip] = time(); diff --git a/lib/view.php b/lib/view.php index a63c2d2e..d420e754 100644 --- a/lib/view.php +++ b/lib/view.php @@ -53,8 +53,7 @@ class view public function draw($template) { $path = PATH . 'tpl' . DIRECTORY_SEPARATOR . $template . '.php'; - if (!file_exists($path)) - { + if (!file_exists($path)) { throw new Exception('Template ' . $template . ' not found!', 80); } extract($this->_variables); diff --git a/lib/vizhash16x16.php b/lib/vizhash16x16.php index 314a3997..54e4cfd5 100644 --- a/lib/vizhash16x16.php +++ b/lib/vizhash16x16.php @@ -88,42 +88,53 @@ class vizhash16x16 */ public function generate($text) { - if (!function_exists('gd_info')) return ''; + if (!function_exists('gd_info')) { + return ''; + } // 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); $hash=$hash.strrev($hash); # more data to make graphics $hashlen=strlen($hash); // We convert the hash into an array of integers. $this->VALUES=array(); - for($i=0; $i<$hashlen; $i=$i+2){ array_push($this->VALUES,hexdec(substr($hash,$i,2))); } + 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. // 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; - $g0 = $this->getInt();$g=$g0; - $b0 = $this->getInt();$b=$b0; + $r0 = $this->getInt(); + $r=$r0; + $g0 = $this->getInt(); + $g=$g0; + $b0 = $this->getInt(); + $b=$b0; // First, create an image with a specific gradient background. - $op='v'; if (($this->getInt()%2)==0) { $op='h'; }; - $image = $this->degrade($image,$op,array($r0,$g0,$b0),array(0,0,0)); + $op='v'; + if (($this->getInt()%2)==0) { + $op='h'; + }; + $image = $this->degrade($image, $op, array($r0, $g0, $b0), array(0, 0, 0)); - for($i=0; $i<7; $i=$i+1) - { + for ($i=0; $i<7; $i=$i+1) { $action=$this->getInt(); - $color = imagecolorallocate($image, $r,$g,$b); + $color = imagecolorallocate($image, $r, $g, $b); $r = ($r0 + $this->getInt()/25)%256; $g = ($g0 + $this->getInt()/25)%256; $b = ($b0 + $this->getInt()/25)%256; - $r0=$r; $g0=$g; $b0=$b; - $this->drawshape($image,$action,$color); + $r0=$r; + $g0=$g; + $b0=$b; + $this->drawshape($image, $action, $color); } - $color = imagecolorallocate($image,$this->getInt(),$this->getInt(),$this->getInt()); - $this->drawshape($image,$this->getInt(),$color); + $color = imagecolorallocate($image, $this->getInt(), $this->getInt(), $this->getInt()); + $this->drawshape($image, $this->getInt(), $color); ob_start(); imagepng($image); $imagedata = ob_get_contents(); @@ -182,24 +193,31 @@ class vizhash16x16 * @param array $color2 * @return resource */ - private function degrade($img,$direction,$color1,$color2) + private function degrade($img, $direction, $color1, $color2) { - if($direction=='h') { $size = imagesx($img); $sizeinv = imagesy($img); } - else { $size = imagesy($img); $sizeinv = imagesx($img);} - $diffs = array( + if ($direction=='h') { + $size = imagesx($img); + $sizeinv = imagesy($img); + } else { + $size = imagesy($img); + $sizeinv = imagesx($img); + } + $diffs = array( (($color2[0]-$color1[0])/$size), (($color2[1]-$color1[1])/$size), (($color2[2]-$color1[2])/$size) ); - for($i=0;$i<$size;$i++) - { - $r = $color1[0]+($diffs[0]*$i); - $g = $color1[1]+($diffs[1]*$i); - $b = $color1[2]+($diffs[2]*$i); - if($direction=='h') { imageline($img,$i,0,$i,$sizeinv,imagecolorallocate($img,$r,$g,$b)); } - else { imageline($img,0,$i,$sizeinv,$i,imagecolorallocate($img,$r,$g,$b)); } + for ($i=0;$i<$size;$i++) { + $r = $color1[0]+($diffs[0]*$i); + $g = $color1[1]+($diffs[1]*$i); + $b = $color1[2]+($diffs[2]*$i); + if ($direction=='h') { + imageline($img, $i, 0, $i, $sizeinv, imagecolorallocate($img, $r, $g, $b)); + } else { + imageline($img, 0, $i, $sizeinv, $i, imagecolorallocate($img, $r, $g, $b)); } - return $img; + } + return $img; } /** @@ -211,24 +229,23 @@ class vizhash16x16 * @param int $color * @return void */ - private function drawshape($image,$action,$color) + private function drawshape($image, $action, $color) { - switch($action%7) - { + switch ($action%7) { case 0: - ImageFilledRectangle ($image,$this->getX(),$this->getY(),$this->getX(),$this->getY(),$color); + ImageFilledRectangle($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $color); break; case 1: case 2: - ImageFilledEllipse ($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $color); + ImageFilledEllipse($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $color); break; case 3: $points = array($this->getX(), $this->getY(), $this->getX(), $this->getY(), $this->getX(), $this->getY(),$this->getX(), $this->getY()); - ImageFilledPolygon ($image, $points, 4, $color); + ImageFilledPolygon($image, $points, 4, $color); break; default: $start=$this->getInt()*360/256; $end=$start+$this->getInt()*180/256; - ImageFilledArc ($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(),$start,$end,$color,IMG_ARC_PIE); + ImageFilledArc($image, $this->getX(), $this->getY(), $this->getX(), $this->getY(), $start, $end, $color, IMG_ARC_PIE); } } } diff --git a/tpl/bootstrap-compact.php b/tpl/bootstrap-compact.php index 7d299add..c2858e1d 100644 --- a/tpl/bootstrap-compact.php +++ b/tpl/bootstrap-compact.php @@ -11,9 +11,9 @@ + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -73,8 +73,8 @@ endif; ?> @@ -103,8 +103,8 @@ if ($DISCUSSION): ?> diff --git a/tpl/bootstrap-dark-page.php b/tpl/bootstrap-dark-page.php index 10cb75d0..5ea66f9a 100644 --- a/tpl/bootstrap-dark-page.php +++ b/tpl/bootstrap-dark-page.php @@ -11,9 +11,9 @@ + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -72,8 +72,8 @@ endif; ?> @@ -102,8 +102,8 @@ if ($DISCUSSION): ?> @@ -137,8 +137,8 @@ endif; ?> @@ -158,13 +158,13 @@ if (strlen($LANGUAGESELECTION)): ?> diff --git a/tpl/bootstrap-dark.php b/tpl/bootstrap-dark.php index 34446473..2e0aae12 100644 --- a/tpl/bootstrap-dark.php +++ b/tpl/bootstrap-dark.php @@ -11,9 +11,9 @@ + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -72,8 +72,8 @@ endif; ?> @@ -102,8 +102,8 @@ if ($DISCUSSION): ?> @@ -137,8 +137,8 @@ endif; ?> @@ -158,13 +158,13 @@ if (strlen($LANGUAGESELECTION)): ?> diff --git a/tpl/bootstrap-page.php b/tpl/bootstrap-page.php index 1bcf4ecc..e4d979e9 100644 --- a/tpl/bootstrap-page.php +++ b/tpl/bootstrap-page.php @@ -11,9 +11,9 @@ + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -72,8 +72,8 @@ endif; ?> @@ -102,8 +102,8 @@ if ($DISCUSSION): ?> @@ -137,8 +137,8 @@ endif; ?> @@ -158,13 +158,13 @@ if (strlen($LANGUAGESELECTION)): ?> diff --git a/tpl/bootstrap.php b/tpl/bootstrap.php index e246418a..ea1476f6 100644 --- a/tpl/bootstrap.php +++ b/tpl/bootstrap.php @@ -11,9 +11,9 @@ + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -72,8 +72,8 @@ endif; ?> @@ -102,8 +102,8 @@ if ($DISCUSSION): ?> @@ -137,8 +137,8 @@ endif; ?> @@ -158,13 +158,13 @@ if (strlen($LANGUAGESELECTION)): ?> diff --git a/tpl/page.php b/tpl/page.php index 897f9a4e..3cdae635 100644 --- a/tpl/page.php +++ b/tpl/page.php @@ -7,9 +7,9 @@ + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -70,8 +70,8 @@ endif; ?> @@ -85,11 +85,11 @@ endif; ?> /> if ($DISCUSSION): ?> @@ -101,19 +101,19 @@ endif; ?>
diff --git a/tst/bootstrap.php b/tst/bootstrap.php index d1cb374b..af03a150 100644 --- a/tst/bootstrap.php +++ b/tst/bootstrap.php @@ -2,13 +2,21 @@ 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 -if (!defined('PUBLIC_PATH')) define('PUBLIC_PATH', '..'); -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); +if (!defined('PUBLIC_PATH')) { + define('PUBLIC_PATH', '..'); +} +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'; @@ -103,8 +111,9 @@ class helper $example = self::getPaste(); // the JSON shouldn't contain the salt unset($example['meta']['salt']); - if (count($meta)) + if (count($meta)) { $example['meta'] = $meta; + } $example['comments'] = array(); $example['comment_count'] = 0; $example['comment_offset'] = 0; @@ -157,19 +166,19 @@ class helper { $path .= DIRECTORY_SEPARATOR; $dir = dir($path); - while(false !== ($file = $dir->read())) { - if($file != '.' && $file != '..') { - if(is_dir($path . $file)) { + while (false !== ($file = $dir->read())) { + if ($file != '.' && $file != '..') { + if (is_dir($path . $file)) { self::rmdir($path . $file); - } elseif(is_file($path . $file)) { - if(!@unlink($path . $file)) { + } elseif (is_file($path . $file)) { + if (!@unlink($path . $file)) { throw new Exception('Error deleting file "' . $path . $file . '".'); } } } } $dir->close(); - if(!@rmdir($path)) { + if (!@rmdir($path)) { throw new Exception('Error deleting directory "' . $path . '".'); } } @@ -181,8 +190,9 @@ class helper */ public static function confBackup() { - if (!is_file(CONF . '.bak') && is_file(CONF)) + if (!is_file(CONF . '.bak') && is_file(CONF)) { rename(CONF, CONF . '.bak'); + } } /** @@ -192,8 +202,9 @@ class helper */ public static function confRestore() { - if (is_file(CONF . '.bak')) + if (is_file(CONF . '.bak')) { rename(CONF . '.bak', CONF); + } } /** @@ -209,7 +220,7 @@ class helper $ini = fopen($pathToFile, 'a'); foreach ($values as $section => $options) { fwrite($ini, "[$section]" . PHP_EOL); - foreach($options as $option => $setting) { + foreach ($options as $option => $setting) { if (is_null($setting)) { continue; } elseif (is_string($setting)) { diff --git a/tst/configGenerator.php b/tst/configGenerator.php index 64081d52..a0fc0888 100755 --- a/tst/configGenerator.php +++ b/tst/configGenerator.php @@ -388,7 +388,8 @@ class configurationTestGenerator * constructor, generates the configuration test * @param array $options */ - public function __construct($options) { + public function __construct($options) + { $this->_options = $options; // generate all possible combinations of options: options^settings $this->_generateConfigurations(); @@ -418,7 +419,7 @@ class configurationTestGenerator while (list($path, $setting) = each($test['conditions'])) { if ($path == 'steps' && !in_array($step, $setting)) { continue 2; - } elseif($path != 'steps') { + } elseif ($path != 'steps') { list($section, $option) = explode('/', $path); if ($fullOptions[$section][$option] !== $setting) { continue 2; @@ -653,7 +654,8 @@ EOT; * @throws Exception * @return array */ - private function _addSetting(&$configuration, &$setting, &$section, &$option) { + private function _addSetting(&$configuration, &$setting, &$section, &$option) + { if (++$this->_iterationCount > self::MAX_ITERATIONS) { echo 'max iterations reached, stopping', PHP_EOL; return $configuration; diff --git a/tst/configuration.php b/tst/configuration.php index 8ee44cb6..43950bbe 100644 --- a/tst/configuration.php +++ b/tst/configuration.php @@ -135,5 +135,4 @@ class configurationTest extends PHPUnit_Framework_TestCase $conf = new configuration; $this->assertEquals('PrivateBin\data\db', $conf->getKey('class', 'model'), 'old db class gets renamed'); } - } diff --git a/tst/jsonApi.php b/tst/jsonApi.php index ccfc220a..0c572364 100644 --- a/tst/jsonApi.php +++ b/tst/jsonApi.php @@ -28,8 +28,9 @@ class jsonApiTest extends PHPUnit_Framework_TestCase $_POST = array(); $_GET = array(); $_SERVER = array(); - if ($this->_model->exists(helper::getPasteId())) + if ($this->_model->exists(helper::getPasteId())) { $this->_model->delete(helper::getPasteId()); + } helper::confRestore(); } @@ -263,5 +264,4 @@ class jsonApiTest extends PHPUnit_Framework_TestCase $content = ob_get_contents(); $this->assertEquals('{}', $content, 'does not output nasty data'); } - } diff --git a/tst/model.php b/tst/model.php index 6fc9ec8f..4244253b 100644 --- a/tst/model.php +++ b/tst/model.php @@ -227,31 +227,23 @@ class modelTest extends PHPUnit_Framework_TestCase $paste = helper::getPaste(array('expire_date' => time() + 3600)); $keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z'); $ids = array(); - foreach ($keys as $key) - { + foreach ($keys as $key) { $ids[$key] = substr(md5($key), 0, 16); $store->delete($ids[$key]); $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"); - } - else - { + } else { $this->assertTrue($store->create($ids[$key], $expired), "store $key paste"); } $this->assertTrue($store->exists($ids[$key]), "paste $key exists after storing it"); } $this->_model->purge(10); - foreach ($ids as $key => $id) - { - if (in_array($key, array('x', 'y', 'z'))) - { + foreach ($ids as $key => $id) { + if (in_array($key, array('x', 'y', 'z'))) { $this->assertTrue($this->_model->getPaste($id)->exists(), "paste $key exists after purge"); $this->_model->getPaste($id)->delete(); - } - else - { + } else { $this->assertFalse($this->_model->getPaste($id)->exists(), "paste $key was purged"); } } diff --git a/tst/privatebin.php b/tst/privatebin.php index eccffdf5..c3848a3d 100644 --- a/tst/privatebin.php +++ b/tst/privatebin.php @@ -27,8 +27,9 @@ class privatebinTest extends PHPUnit_Framework_TestCase $_POST = array(); $_GET = array(); $_SERVER = array(); - if ($this->_model->exists(helper::getPasteId())) + if ($this->_model->exists(helper::getPasteId())) { $this->_model->delete(helper::getPasteId()); + } helper::confRestore(); } diff --git a/tst/privatebin/data.php b/tst/privatebin/data.php index 9248a7ae..79a2b09b 100644 --- a/tst/privatebin/data.php +++ b/tst/privatebin/data.php @@ -73,30 +73,22 @@ class privatebin_dataTest extends PHPUnit_Framework_TestCase $paste = helper::getPaste(array('expire_date' => time() + 3600)); $keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z'); $ids = array(); - foreach ($keys as $key) - { + foreach ($keys as $key) { $ids[$key] = substr(md5($key), 0, 16); $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"); - } - else - { + } else { $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->_model->purge(10); - foreach ($ids as $key => $id) - { - if (in_array($key, array('x', 'y', 'z'))) - { + foreach ($ids as $key => $id) { + if (in_array($key, array('x', 'y', 'z'))) { $this->assertTrue($this->_model->exists($id), "paste $key exists after purge"); $this->_model->delete($id); - } - else - { + } else { $this->assertFalse($this->_model->exists($id), "paste $key was purged"); } } diff --git a/tst/privatebin/db.php b/tst/privatebin/db.php index 6a48b026..b5bf8f33 100644 --- a/tst/privatebin/db.php +++ b/tst/privatebin/db.php @@ -22,7 +22,9 @@ class privatebin_dbTest extends PHPUnit_Framework_TestCase public function tearDown() { /* Tear Down Routine */ - if (is_dir(PATH . 'data')) helper::rmdir(PATH . 'data'); + if (is_dir(PATH . 'data')) { + helper::rmdir(PATH . 'data'); + } } public function testDatabaseBasedDataStoreWorks() @@ -78,31 +80,23 @@ class privatebin_dbTest extends PHPUnit_Framework_TestCase $paste = helper::getPaste(array('expire_date' => time() + 3600)); $keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'x', 'y', 'z'); $ids = array(); - foreach ($keys as $key) - { + foreach ($keys as $key) { $ids[$key] = substr(md5($key), 0, 16); $this->_model->delete($ids[$key]); $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"); - } - else - { + } else { $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->_model->purge(10); - foreach ($ids as $key => $id) - { - if (in_array($key, array('x', 'y', 'z'))) - { + foreach ($ids as $key => $id) { + if (in_array($key, array('x', 'y', 'z'))) { $this->assertTrue($this->_model->exists($id), "paste $key exists after purge"); $this->_model->delete($id); - } - else - { + } else { $this->assertFalse($this->_model->exists($id), "paste $key was purged"); } } diff --git a/tst/privatebinWithDb.php b/tst/privatebinWithDb.php index 569454f0..9df0a248 100644 --- a/tst/privatebinWithDb.php +++ b/tst/privatebinWithDb.php @@ -24,7 +24,9 @@ class privatebinWithDbTest extends privatebinTest { /* Setup Routine */ $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->_model = db::getInstance($this->_options); $this->reset(); diff --git a/tst/purgelimiter.php b/tst/purgelimiter.php index ffe816a7..127698b5 100644 --- a/tst/purgelimiter.php +++ b/tst/purgelimiter.php @@ -10,7 +10,9 @@ class purgelimiterTest extends PHPUnit_Framework_TestCase { /* Setup Routine */ $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); } diff --git a/tst/serversalt.php b/tst/serversalt.php index 9e3ac974..7b5c67ad 100644 --- a/tst/serversalt.php +++ b/tst/serversalt.php @@ -16,13 +16,17 @@ class serversaltTest extends PHPUnit_Framework_TestCase { /* Setup Routine */ $this->_path = PATH . 'data'; - if(!is_dir($this->_path)) mkdir($this->_path); + if (!is_dir($this->_path)) { + mkdir($this->_path); + } serversalt::setPath($this->_path); $this->_otherPath = $this->_path . DIRECTORY_SEPARATOR . 'foo'; $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'; } @@ -40,18 +44,18 @@ class serversaltTest extends PHPUnit_Framework_TestCase $salt = serversalt::get(); // mcrypt mock - if (!function_exists('mcrypt_create_iv')) - { - if (!defined('MCRYPT_DEV_URANDOM')) define('MCRYPT_DEV_URANDOM', 1); + if (!function_exists('mcrypt_create_iv')) { + if (!defined('MCRYPT_DEV_URANDOM')) { + define('MCRYPT_DEV_URANDOM', 1); + } function mcrypt_create_iv($int, $flag) { $randomSalt = ''; - for($i = 0; $i < $int; ++$i) { + for ($i = 0; $i < $int; ++$i) { $randomSalt .= base_convert(mt_rand(), 10, 16); } // hex2bin requires an even length, pad if necessary - if (strlen($randomSalt) % 2) - { + if (strlen($randomSalt) % 2) { $randomSalt = '0' . $randomSalt; } return hex2bin($randomSalt); diff --git a/tst/vizhash16x16.php b/tst/vizhash16x16.php index 005332e7..a0e0850e 100644 --- a/tst/vizhash16x16.php +++ b/tst/vizhash16x16.php @@ -13,7 +13,9 @@ class vizhash16x16Test extends PHPUnit_Framework_TestCase { /* Setup Routine */ $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'; serversalt::setPath($this->_path); } @@ -22,7 +24,7 @@ class vizhash16x16Test extends PHPUnit_Framework_TestCase { /* Tear Down Routine */ chmod($this->_path, 0700); - if(!@unlink($this->_file)) { + if (!@unlink($this->_file)) { throw new Exception('Error deleting file "' . $this->_file . '".'); } helper::rmdir($this->_path);