diff --git a/.gitignore b/.gitignore index 9a3d92c..0323182 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Ignore data/, tmp/ and vendor/ data/ +!lib/data/ tmp/ vendor/ # Ignore for safety diff --git a/INSTALL.md b/INSTALL.md index 5848f98..6c76e81 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -9,7 +9,7 @@ instance. ### Requirements -- PHP version 5.2.6 or above +- PHP version 5.3.0 or above - GD extension - mcrypt extension (recommended) - some disk space or (optional) a database supported by PDO diff --git a/composer.json b/composer.json index 89964c5..f76ea5f 100644 --- a/composer.json +++ b/composer.json @@ -23,5 +23,10 @@ "require-dev": { "codacy/coverage": "dev-master", "codeclimate/php-test-reporter": "dev-master" + }, + "autoload": { + "psr-4": { + "PrivateBin\\": "lib/" + } } } diff --git a/i18n/de.json b/i18n/de.json index 60353d9..e726bee 100644 --- a/i18n/de.json +++ b/i18n/de.json @@ -2,8 +2,8 @@ "en": "de", "Paste does not exist, has expired or has been deleted.": "Diesen Text gibt es nicht, er ist abgelaufen oder wurde gelöscht.", - "PrivateBin requires php 5.2.6 or above to work. Sorry.": - "PrivateBin benötigt PHP 5.2.6 oder höher, um zu funktionieren. Sorry.", + "PrivateBin requires php 5.3.0 or above to work. Sorry.": + "PrivateBin benötigt PHP 5.3.0 oder höher, um zu funktionieren. Sorry.", "PrivateBin requires configuration section [%s] to be present in configuration file.": "PrivateBin benötigt den Konfigurationsabschnitt [%s] in der Konfigurationsdatei um zu funktionieren.", "Please wait %d seconds between each post.": diff --git a/i18n/fr.json b/i18n/fr.json index 50d5602..fd4de96 100644 --- a/i18n/fr.json +++ b/i18n/fr.json @@ -2,8 +2,8 @@ "en": "fr", "Paste does not exist, has expired or has been deleted.": "Le paste n'existe pas, a expiré, ou a été supprimé.", - "PrivateBin requires php 5.2.6 or above to work. Sorry.": - "Désolé, PrivateBin nécessite php 5.2.6 ou supérieur pour fonctionner.", + "PrivateBin requires php 5.3.0 or above to work. Sorry.": + "Désolé, PrivateBin nécessite php 5.3.0 ou supérieur pour fonctionner.", "PrivateBin requires configuration section [%s] to be present in configuration file.": "PrivateBin a besoin de la section de configuration [%s] dans le fichier de configuration pour fonctionner.", "Please wait %d seconds between each post.": diff --git a/i18n/pl.json b/i18n/pl.json index 6a1a63e..0c60fbb 100644 --- a/i18n/pl.json +++ b/i18n/pl.json @@ -2,8 +2,8 @@ "en": "pl", "Paste does not exist, has expired or has been deleted.": "Wklejka nie istnieje, wygasła albo została usunięta.", - "PrivateBin requires php 5.2.6 or above to work. Sorry.": - "PrivateBin wymaga PHP w wersji 5.2.6 lub nowszej, sorry.", + "PrivateBin requires php 5.3.0 or above to work. Sorry.": + "PrivateBin wymaga PHP w wersji 5.3.0 lub nowszej, sorry.", "PrivateBin requires configuration section [%s] to be present in configuration file.": "PrivateBin wymaga obecności sekcji [%s] w pliku konfiguracyjnym.", "Please wait %d seconds between each post.": diff --git a/i18n/sl.json b/i18n/sl.json index a159bf8..98978a4 100644 --- a/i18n/sl.json +++ b/i18n/sl.json @@ -2,8 +2,8 @@ "en": "sl", "Paste does not exist, has expired or has been deleted.": "Prilepek ne obstaja, mu je potekla življenjska doba, ali pa je izbrisan.", - "PrivateBin requires php 5.2.6 or above to work. Sorry.": - "Oprosti, PrivateBin za delovanje potrebuje vsaj php 5.2.6.", + "PrivateBin requires php 5.3.0 or above to work. Sorry.": + "Oprosti, PrivateBin za delovanje potrebuje vsaj php 5.3.0.", "PrivateBin requires configuration section [%s] to be present in configuration file.": "PrivateBin potrebuje sekcijo konfiguracij [%s] v konfiguracijski datoteki.", "Please wait %d seconds between each post.": diff --git a/i18n/zh.json b/i18n/zh.json index 6a40769..f7e6395 100644 --- a/i18n/zh.json +++ b/i18n/zh.json @@ -2,8 +2,8 @@ "en": "zh", "Paste does not exist, has expired or has been deleted.": "粘贴不存在,已过期或者已被删除。", - "PrivateBin requires php 5.2.6 or above to work. Sorry.": - "PrivateBin需要工作于PHP 5.2.6及以上版本,抱歉。", + "PrivateBin requires php 5.3.0 or above to work. Sorry.": + "PrivateBin需要工作于PHP 5.3.0及以上版本,抱歉。", "PrivateBin requires configuration section [%s] to be present in configuration file.": "PrivateBin需要设置配置文件中 [%s] 的部分。", "Please wait %d seconds between each post.": diff --git a/index.php b/index.php index 06c3617..ec40497 100644 --- a/index.php +++ b/index.php @@ -14,5 +14,5 @@ define('PATH', ''); define('PUBLIC_PATH', dirname(__FILE__)); -require PATH . 'lib/auto.php'; -new privatebin; +require __DIR__ . '/vendor/autoload.php'; +new PrivateBin\privatebin; diff --git a/lib/auto.php b/lib/auto.php deleted file mode 100644 index 30ef778..0000000 --- a/lib/auto.php +++ /dev/null @@ -1,38 +0,0 @@ - 'data', ), 'model' => array( - 'class' => 'privatebin_data', + 'class' => 'PrivateBin\data\data', ), 'model_options' => array( 'dir' => 'data', @@ -93,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)) { @@ -103,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; @@ -121,8 +122,7 @@ class configuration $this->_configuration['model']['class'], array('privatebin_db', 'zerobin_db') ) - ) - { + ) { $values = array( 'dsn' => 'sqlite:' . PATH . 'data/db.sq3', 'tbl' => null, @@ -137,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]; } } @@ -191,15 +173,20 @@ class configuration } } - // support for old config file format, before the fork was renamed + // support for old config file format, before the fork was renamed and PSR-4 introduced $this->_configuration['model']['class'] = str_replace( 'zerobin_', 'privatebin_', $this->_configuration['model']['class'] ); + $this->_configuration['model']['class'] = str_replace( + array('privatebin_data', 'privatebin_db'), + array('PrivateBin\\data\\data', 'PrivateBin\\data\\db'), + $this->_configuration['model']['class'] + ); + // 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']); } } @@ -235,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]; @@ -251,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/privatebin/abstract.php b/lib/data/AbstractData.php similarity index 88% rename from lib/privatebin/abstract.php rename to lib/data/AbstractData.php index 8a6223f..6f99f3d 100644 --- a/lib/privatebin/abstract.php +++ b/lib/data/AbstractData.php @@ -10,12 +10,14 @@ * @version 0.22 */ +namespace PrivateBin\data; + /** * privatebin_abstract * * Abstract model for PrivateBin data access, implemented as a singleton. */ -abstract class privatebin_abstract +abstract class AbstractData { /** * singleton instance @@ -33,7 +35,9 @@ abstract class privatebin_abstract * * @access protected */ - protected function __construct() {} + protected function __construct() + { + } /** * enforce singleton, disable cloning @@ -42,7 +46,9 @@ abstract class privatebin_abstract * * @access private */ - private function __clone() {} + private function __clone() + { + } /** * get instance of singleton @@ -52,7 +58,9 @@ abstract class privatebin_abstract * @param array $options * @return privatebin_abstract */ - public static function getInstance($options) {} + public static function getInstance($options) + { + } /** * Create a paste. @@ -141,12 +149,12 @@ abstract class privatebin_abstract */ 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); } } @@ -162,10 +170,11 @@ abstract class privatebin_abstract */ 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/privatebin/data.php b/lib/data/data.php similarity index 84% rename from lib/privatebin/data.php rename to lib/data/data.php index e1d125a..4482638 100644 --- a/lib/privatebin/data.php +++ b/lib/data/data.php @@ -10,12 +10,14 @@ * @version 0.22 */ +namespace PrivateBin\data; + /** * privatebin_data * * Model for data access, implemented as a singleton. */ -class privatebin_data extends privatebin_abstract +class data extends AbstractData { /** * directory where data is stored @@ -40,7 +42,9 @@ class privatebin_data extends privatebin_abstract 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; @@ -60,8 +64,12 @@ class privatebin_data extends privatebin_abstract 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)); } @@ -74,16 +82,16 @@ class privatebin_data extends privatebin_abstract */ 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); } @@ -105,13 +113,13 @@ class privatebin_data extends privatebin_abstract // 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(); @@ -146,8 +154,12 @@ class privatebin_data extends privatebin_abstract { $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)); } @@ -162,18 +174,15 @@ class privatebin_data extends privatebin_abstract { $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. @@ -224,11 +233,9 @@ class privatebin_data extends privatebin_abstract 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]), @@ -236,8 +243,7 @@ class privatebin_data extends privatebin_abstract ); // skip this folder in the next checks if it is empty - if (count($secondLevel) == 0) - { + if (count($secondLevel) == 0) { unset($firstLevel[$firstKey]); continue; } @@ -245,26 +251,32 @@ class privatebin_data extends privatebin_abstract $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('model_paste', 'isValidId') + 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; + } } } } @@ -282,10 +294,11 @@ class privatebin_data extends privatebin_abstract 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/privatebin/db.php b/lib/data/db.php similarity index 90% rename from lib/privatebin/db.php rename to lib/data/db.php index 8acb04d..0c572ea 100644 --- a/lib/privatebin/db.php +++ b/lib/data/db.php @@ -10,12 +10,20 @@ * @version 0.22 */ +namespace PrivateBin\data; + +use Exception; +use PDO; +use PDOException; +use PrivateBin\privatebin; +use stdClass; + /** * privatebin_db * * Model for DB access, implemented as a singleton. */ -class privatebin_db extends privatebin_abstract +class db extends AbstractData { /** * cache for select queries @@ -63,14 +71,15 @@ class privatebin_db extends privatebin_abstract 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 ( @@ -78,8 +87,7 @@ class privatebin_db extends privatebin_abstract 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; @@ -102,40 +110,34 @@ class privatebin_db extends privatebin_abstract $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 ); @@ -158,7 +160,7 @@ class privatebin_db extends privatebin_abstract if ( array_key_exists($pasteid, self::$_cache) ) { - if(false !== self::$_cache[$pasteid]) { + if (false !== self::$_cache[$pasteid]) { return false; } else { unset(self::$_cache[$pasteid]); @@ -170,28 +172,23 @@ class privatebin_db extends privatebin_abstract $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']); } @@ -230,31 +227,29 @@ class privatebin_db extends privatebin_abstract ' 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']; } } @@ -263,13 +258,19 @@ class privatebin_db extends privatebin_abstract $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; + } } } @@ -295,7 +296,9 @@ class privatebin_db extends privatebin_abstract ); if ( array_key_exists($pasteid, self::$_cache) - ) unset(self::$_cache[$pasteid]); + ) { + unset(self::$_cache[$pasteid]); + } } /** @@ -309,7 +312,9 @@ class privatebin_db extends privatebin_abstract { if ( !array_key_exists($pasteid, self::$_cache) - ) self::$_cache[$pasteid] = $this->read($pasteid); + ) { + self::$_cache[$pasteid] = $this->read($pasteid); + } return (bool) self::$_cache[$pasteid]; } @@ -325,10 +330,8 @@ class privatebin_db extends privatebin_abstract */ 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; } } @@ -363,10 +366,8 @@ class privatebin_db extends privatebin_abstract // 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']; @@ -374,10 +375,12 @@ class privatebin_db extends privatebin_abstract $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); } @@ -416,10 +419,8 @@ class privatebin_db extends privatebin_abstract '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']; } } @@ -477,8 +478,7 @@ class privatebin_db extends privatebin_abstract */ private static function _getTableQuery($type) { - switch($type) - { + switch ($type) { case 'ibm': $sql = 'SELECT tabname FROM SYSCAT.TABLES '; break; @@ -551,12 +551,9 @@ class privatebin_db extends privatebin_abstract 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); @@ -659,8 +656,7 @@ class privatebin_db extends privatebin_abstract 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 { @@ -679,8 +675,7 @@ class privatebin_db extends privatebin_abstract ); // 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;' @@ -690,9 +685,7 @@ class privatebin_db extends privatebin_abstract " 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 538a4cb..06af9c2 100644 --- a/lib/filter.php +++ b/lib/filter.php @@ -10,6 +10,11 @@ * @version 0.22 */ +namespace PrivateBin; + +use Exception; +use PrivateBin\i18n; + /** * filter * @@ -28,7 +33,7 @@ class filter public static function stripslashes_deep($value) { return is_array($value) ? - array_map('filter::stripslashes_deep', $value) : + array_map('PrivateBin\\filter::stripslashes_deep', $value) : stripslashes($value); } @@ -73,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]); } @@ -93,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 4d1b70c..6a9a8dc 100644 --- a/lib/i18n.php +++ b/lib/i18n.php @@ -10,6 +10,8 @@ * @version 0.22 */ +namespace PrivateBin; + /** * i18n * @@ -82,7 +84,7 @@ class i18n */ public static function _($messageId) { - return call_user_func_array(array('i18n', 'translate'), func_get_args()); + return call_user_func_array(array('self', 'translate'), func_get_args()); } /** @@ -96,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); @@ -139,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 ); @@ -168,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]; } } @@ -195,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]); @@ -250,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)); } @@ -268,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; + } } /** @@ -282,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 : ''); @@ -324,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); @@ -383,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 341f44a..de79bb3 100644 --- a/lib/model.php +++ b/lib/model.php @@ -10,6 +10,10 @@ * @version 0.22 */ +namespace PrivateBin; + +use PrivateBin\model\paste; + /** * model * @@ -50,8 +54,10 @@ class model */ public function getPaste($pasteId = null) { - $paste = new model_paste($this->_conf, $this->_getStore()); - if ($pasteId !== null) $paste->setId($pasteId); + $paste = new paste($this->_conf, $this->_getStore()); + if ($pasteId !== null) { + $paste->setId($pasteId); + } return $paste; } @@ -63,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')); } } @@ -76,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/abstract.php b/lib/model/AbstractModel.php similarity index 85% rename from lib/model/abstract.php rename to lib/model/AbstractModel.php index 5e0435d..af834f4 100644 --- a/lib/model/abstract.php +++ b/lib/model/AbstractModel.php @@ -10,12 +10,20 @@ * @version 0.22 */ +namespace PrivateBin\Model; + +use Exception; +use PrivateBin\configuration; +use PrivateBin\data\AbstractData; +use PrivateBin\sjcl; +use stdClass; + /** * model_abstract * * Abstract model for PrivateBin objects. */ -abstract class model_abstract +abstract class AbstractModel { /** * Instance ID. @@ -57,7 +65,7 @@ abstract class model_abstract * @param privatebin_abstract $storage * @return void */ - public function __construct(configuration $configuration, privatebin_abstract $storage) + public function __construct(configuration $configuration, AbstractData $storage) { $this->_conf = $configuration; $this->_store = $storage; @@ -86,7 +94,9 @@ abstract class model_abstract */ 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; } @@ -100,7 +110,9 @@ abstract class model_abstract */ 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 011649d..786a7ba 100644 --- a/lib/model/comment.php +++ b/lib/model/comment.php @@ -10,12 +10,19 @@ * @version 0.22 */ +namespace PrivateBin\model; + +use Exception; +use PrivateBin\sjcl; +use PrivateBin\trafficlimiter; +use PrivateBin\vizhash16x16; + /** * model_comment * * Model of a PrivateBin comment. */ -class model_comment extends model_abstract +class comment extends AbstractModel { /** * Instance's parent. @@ -59,16 +66,19 @@ class model_comment extends model_abstract { // 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(); @@ -80,7 +90,9 @@ class model_comment extends model_abstract $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); + } } /** @@ -118,7 +130,7 @@ class model_comment extends model_abstract * @throws Exception * @return void */ - public function setPaste(model_paste $paste) + public function setPaste(paste $paste) { $this->_paste = $paste; $this->_data->meta->pasteid = $paste->getId(); @@ -145,7 +157,9 @@ class model_comment extends model_abstract */ 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; } @@ -157,7 +171,9 @@ class model_comment extends model_abstract */ 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; } @@ -171,19 +187,19 @@ class model_comment extends model_abstract */ 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 57b86b6..e18211e 100644 --- a/lib/model/paste.php +++ b/lib/model/paste.php @@ -10,12 +10,19 @@ * @version 0.22 */ +namespace PrivateBin\model; + +use Exception; +use PrivateBin\privatebin; +use PrivateBin\serversalt; +use PrivateBin\sjcl; + /** * model_paste * * Model of a PrivateBin paste. */ -class model_paste extends model_abstract +class paste extends AbstractModel { /** * Get paste data. @@ -27,13 +34,13 @@ class model_paste extends model_abstract 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); } @@ -42,22 +49,17 @@ class model_paste extends model_abstract } // 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()); @@ -77,8 +79,9 @@ class model_paste extends model_abstract 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(); @@ -89,7 +92,9 @@ class model_paste extends model_abstract $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); + } } /** @@ -126,14 +131,15 @@ class model_paste extends model_abstract */ public function getComment($parentId, $commentId = null) { - if (!$this->exists()) - { + if (!$this->exists()) { throw new Exception('Invalid data.', 62); } - $comment = new model_comment($this->_conf, $this->_store); + $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; } @@ -160,7 +166,9 @@ class model_paste extends model_abstract */ 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(), @@ -178,8 +186,9 @@ class model_paste extends model_abstract */ 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; } @@ -193,8 +202,9 @@ class model_paste extends model_abstract */ 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; } @@ -208,16 +218,15 @@ class model_paste extends model_abstract 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; + } } /** @@ -230,14 +239,12 @@ class model_paste extends model_abstract */ 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; } @@ -257,14 +264,12 @@ class model_paste extends model_abstract !$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; } } @@ -279,8 +284,7 @@ class model_paste extends model_abstract */ 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; @@ -295,7 +299,9 @@ class model_paste extends model_abstract */ 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; } @@ -310,7 +316,9 @@ class model_paste extends model_abstract */ 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 d65f844..e42f117 100644 --- a/lib/persistence.php +++ b/lib/persistence.php @@ -10,6 +10,10 @@ * @version 0.22 */ +namespace PrivateBin; + +use Exception; + /** * persistence * @@ -49,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; } } @@ -84,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 . @@ -119,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 eb6f9cb..d2a70b9 100644 --- a/lib/privatebin.php +++ b/lib/privatebin.php @@ -10,6 +10,10 @@ * @version 0.22 */ +namespace PrivateBin; + +use Exception; + /** * privatebin * @@ -113,16 +117,14 @@ class privatebin */ public function __construct() { - if (version_compare(PHP_VERSION, '5.2.6') < 0) - { - throw new Exception(i18n::_('PrivateBin requires php 5.2.6 or above to work. Sorry.'), 1); + 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; @@ -141,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(); } } @@ -163,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; @@ -183,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); } @@ -214,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'); @@ -229,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) { @@ -315,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) { @@ -367,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)); } } @@ -413,18 +404,16 @@ 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); } // translate all the formatter options - $formatters = array_map(array('i18n', 'translate'), $this->_conf->getSection('formatter_options')); + $formatters = array_map(array('PrivateBin\\i18n', 'translate'), $this->_conf->getSection('formatter_options')); // 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); } @@ -467,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=', @@ -500,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 d8c595a..8261b9a 100644 --- a/lib/purgelimiter.php +++ b/lib/purgelimiter.php @@ -10,6 +10,8 @@ * @version 0.22 */ +namespace PrivateBin; + /** * purgelimiter * @@ -64,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 1339e84..fec1054 100644 --- a/lib/request.php +++ b/lib/request.php @@ -10,6 +10,8 @@ * @version 0.22 */ +namespace PrivateBin; + /** * request * @@ -79,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); @@ -90,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); @@ -107,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']; } @@ -116,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'; } } @@ -203,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 91cfcdc..60a9930 100644 --- a/lib/serversalt.php +++ b/lib/serversalt.php @@ -10,6 +10,10 @@ * @version 0.22 */ +namespace PrivateBin; + +use Exception; + /** * serversalt * @@ -41,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); } } @@ -64,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)) { @@ -93,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 ae09c9c..2d2981f 100644 --- a/lib/sjcl.php +++ b/lib/sjcl.php @@ -10,6 +10,8 @@ * @version 0.22 */ +namespace PrivateBin; + /** * sjcl * @@ -33,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 b0fc5a7..0c49a66 100644 --- a/lib/trafficlimiter.php +++ b/lib/trafficlimiter.php @@ -10,6 +10,8 @@ * @version 0.22 */ +namespace PrivateBin; + /** * trafficlimiter * @@ -60,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; } } @@ -95,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 4595200..d420e75 100644 --- a/lib/view.php +++ b/lib/view.php @@ -10,6 +10,10 @@ * @version 0.22 */ +namespace PrivateBin; + +use Exception; + /** * view * @@ -49,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 47b725d..54e4cfd 100644 --- a/lib/vizhash16x16.php +++ b/lib/vizhash16x16.php @@ -11,6 +11,8 @@ * @version 0.0.4 beta PrivateBin 0.22 */ +namespace PrivateBin; + /** * vizhash16x16 * @@ -86,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(); @@ -180,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; } /** @@ -209,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 e39652e..c2858e1 100644 --- a/tpl/bootstrap-compact.php +++ b/tpl/bootstrap-compact.php @@ -5,15 +5,15 @@ - <?php echo i18n::_('PrivateBin'); ?> + <?php echo PrivateBin\i18n::_('PrivateBin'); ?> + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -45,39 +45,39 @@ endif; ?>
@@ -202,9 +202,9 @@ endif; ?> - - -
@@ -238,16 +238,16 @@ endif; ?>
diff --git a/tpl/bootstrap-dark-page.php b/tpl/bootstrap-dark-page.php index 8f264cd..5ea66f9 100644 --- a/tpl/bootstrap-dark-page.php +++ b/tpl/bootstrap-dark-page.php @@ -5,15 +5,15 @@ - <?php echo i18n::_('PrivateBin'); ?> + <?php echo PrivateBin\i18n::_('PrivateBin'); ?> + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -44,39 +44,39 @@ endif; ?>
@@ -198,9 +198,9 @@ endif; ?> - - -
@@ -234,16 +234,16 @@ endif; ?>
diff --git a/tpl/bootstrap-dark.php b/tpl/bootstrap-dark.php index 321d16b..2e0aae1 100644 --- a/tpl/bootstrap-dark.php +++ b/tpl/bootstrap-dark.php @@ -5,15 +5,15 @@ - <?php echo i18n::_('PrivateBin'); ?> + <?php echo PrivateBin\i18n::_('PrivateBin'); ?> + if (strlen($SYNTAXHIGHLIGHTINGTHEME)): ?> @@ -44,39 +44,39 @@ endif; ?>