upgraded PHP libraries

This commit is contained in:
El RIDO 2019-06-16 07:10:24 +02:00
parent 362045c664
commit db4ae09ee3
No known key found for this signature in database
GPG key ID: 0F5C940A6BD81F92
24 changed files with 469 additions and 331 deletions

View file

@ -1,32 +1,44 @@
{ {
"name": "privatebin/privatebin", "name" : "privatebin/privatebin",
"description": "PrivateBin is a minimalist, open source online pastebin where the server has zero knowledge of pasted data. Data is encrypted/decrypted in the browser using 256 bit AES in Galois Counter mode (GCM).", "description" : "PrivateBin is a minimalist, open source online pastebin where the server has zero knowledge of pasted data. Data is encrypted/decrypted in the browser using 256 bit AES in Galois Counter mode (GCM).",
"type": "project", "type" : "project",
"keywords": ["private", "secure", "end-to-end-encrypted", "e2e", "paste", "pastebin", "zero", "zero-knowledge", "encryption", "encrypted", "AES"], "keywords" : [
"homepage": "https://privatebin.info/", "private",
"license":"zlib-acknowledgement", "secure",
"support": { "end-to-end-encrypted",
"issues": "https://github.com/PrivateBin/PrivateBin/issues", "e2e",
"wiki": "https://github.com/PrivateBin/PrivateBin/wiki", "paste",
"source": "https://github.com/PrivateBin/PrivateBin", "pastebin",
"docs": "https://privatebin.info/codedoc/" "zero",
}, "zero-knowledge",
"require": { "encryption",
"php": "^5.4.0 || ^7.0", "encrypted",
"paragonie/random_compat": "2.0.15", "AES"
"yzalis/identicon": "1.1.0" ],
}, "homepage" : "https://privatebin.info/",
"require-dev": { "license" : "zlib-acknowledgement",
"codacy/coverage": "dev-master", "support" : {
"codeclimate/php-test-reporter": "dev-master", "issues" : "https://github.com/PrivateBin/PrivateBin/issues",
"phpunit/phpunit": "^4.6 || ^5.0" "wiki" : "https://github.com/PrivateBin/PrivateBin/wiki",
}, "source" : "https://github.com/PrivateBin/PrivateBin",
"autoload": { "docs" : "https://privatebin.info/codedoc/"
"psr-4": { },
"PrivateBin\\": "lib/" "require" : {
} "php" : "^5.4.0 || ^7.0",
}, "paragonie/random_compat" : "2.0.18",
"config": { "yzalis/identicon" : "1.2.0"
"autoloader-suffix": "DontChange" },
} "require-dev" : {
} "codacy/coverage" : "dev-master",
"codeclimate/php-test-reporter" : "dev-master",
"phpunit/phpunit" : "^4.6 || ^5.0"
},
"autoload" : {
"psr-4" : {
"PrivateBin\\" : "lib/"
}
},
"config" : {
"autoloader-suffix" : "DontChange"
}
}

View file

@ -10,6 +10,7 @@ return array(
'Identicon\\Generator\\GdGenerator' => $vendorDir . '/yzalis/identicon/src/Identicon/Generator/GdGenerator.php', 'Identicon\\Generator\\GdGenerator' => $vendorDir . '/yzalis/identicon/src/Identicon/Generator/GdGenerator.php',
'Identicon\\Generator\\GeneratorInterface' => $vendorDir . '/yzalis/identicon/src/Identicon/Generator/GeneratorInterface.php', 'Identicon\\Generator\\GeneratorInterface' => $vendorDir . '/yzalis/identicon/src/Identicon/Generator/GeneratorInterface.php',
'Identicon\\Generator\\ImageMagickGenerator' => $vendorDir . '/yzalis/identicon/src/Identicon/Generator/ImageMagickGenerator.php', 'Identicon\\Generator\\ImageMagickGenerator' => $vendorDir . '/yzalis/identicon/src/Identicon/Generator/ImageMagickGenerator.php',
'Identicon\\Generator\\SvgGenerator' => $vendorDir . '/yzalis/identicon/src/Identicon/Generator/SvgGenerator.php',
'Identicon\\Identicon' => $vendorDir . '/yzalis/identicon/src/Identicon/Identicon.php', 'Identicon\\Identicon' => $vendorDir . '/yzalis/identicon/src/Identicon/Identicon.php',
'PrivateBin\\Configuration' => $baseDir . '/lib/Configuration.php', 'PrivateBin\\Configuration' => $baseDir . '/lib/Configuration.php',
'PrivateBin\\Controller' => $baseDir . '/lib/Controller.php', 'PrivateBin\\Controller' => $baseDir . '/lib/Controller.php',
@ -17,6 +18,7 @@ return array(
'PrivateBin\\Data\\Database' => $baseDir . '/lib/Data/Database.php', 'PrivateBin\\Data\\Database' => $baseDir . '/lib/Data/Database.php',
'PrivateBin\\Data\\Filesystem' => $baseDir . '/lib/Data/Filesystem.php', 'PrivateBin\\Data\\Filesystem' => $baseDir . '/lib/Data/Filesystem.php',
'PrivateBin\\Filter' => $baseDir . '/lib/Filter.php', 'PrivateBin\\Filter' => $baseDir . '/lib/Filter.php',
'PrivateBin\\FormatV2' => $baseDir . '/lib/FormatV2.php',
'PrivateBin\\I18n' => $baseDir . '/lib/I18n.php', 'PrivateBin\\I18n' => $baseDir . '/lib/I18n.php',
'PrivateBin\\Json' => $baseDir . '/lib/Json.php', 'PrivateBin\\Json' => $baseDir . '/lib/Json.php',
'PrivateBin\\Model' => $baseDir . '/lib/Model.php', 'PrivateBin\\Model' => $baseDir . '/lib/Model.php',
@ -29,7 +31,6 @@ return array(
'PrivateBin\\Persistence\\ServerSalt' => $baseDir . '/lib/Persistence/ServerSalt.php', 'PrivateBin\\Persistence\\ServerSalt' => $baseDir . '/lib/Persistence/ServerSalt.php',
'PrivateBin\\Persistence\\TrafficLimiter' => $baseDir . '/lib/Persistence/TrafficLimiter.php', 'PrivateBin\\Persistence\\TrafficLimiter' => $baseDir . '/lib/Persistence/TrafficLimiter.php',
'PrivateBin\\Request' => $baseDir . '/lib/Request.php', 'PrivateBin\\Request' => $baseDir . '/lib/Request.php',
'PrivateBin\\FormatV2' => $baseDir . '/lib/FormatV2.php',
'PrivateBin\\View' => $baseDir . '/lib/View.php', 'PrivateBin\\View' => $baseDir . '/lib/View.php',
'PrivateBin\\Vizhash16x16' => $baseDir . '/lib/Vizhash16x16.php', 'PrivateBin\\Vizhash16x16' => $baseDir . '/lib/Vizhash16x16.php',
); );

View file

@ -6,5 +6,4 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir); $baseDir = dirname($vendorDir);
return array( return array(
'Identicon' => array($vendorDir . '/yzalis/identicon/src'),
); );

View file

@ -7,4 +7,5 @@ $baseDir = dirname($vendorDir);
return array( return array(
'PrivateBin\\' => array($baseDir . '/lib'), 'PrivateBin\\' => array($baseDir . '/lib'),
'Identicon\\' => array($vendorDir . '/yzalis/identicon/src/Identicon'),
); );

View file

@ -15,6 +15,10 @@ class ComposerStaticInitDontChange
array ( array (
'PrivateBin\\' => 11, 'PrivateBin\\' => 11,
), ),
'I' =>
array (
'Identicon\\' => 10,
),
); );
public static $prefixDirsPsr4 = array ( public static $prefixDirsPsr4 = array (
@ -22,15 +26,9 @@ class ComposerStaticInitDontChange
array ( array (
0 => __DIR__ . '/../..' . '/lib', 0 => __DIR__ . '/../..' . '/lib',
), ),
); 'Identicon\\' =>
public static $prefixesPsr0 = array (
'I' =>
array ( array (
'Identicon' => 0 => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon',
array (
0 => __DIR__ . '/..' . '/yzalis/identicon/src',
),
), ),
); );
@ -39,6 +37,7 @@ class ComposerStaticInitDontChange
'Identicon\\Generator\\GdGenerator' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Generator/GdGenerator.php', 'Identicon\\Generator\\GdGenerator' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Generator/GdGenerator.php',
'Identicon\\Generator\\GeneratorInterface' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Generator/GeneratorInterface.php', 'Identicon\\Generator\\GeneratorInterface' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Generator/GeneratorInterface.php',
'Identicon\\Generator\\ImageMagickGenerator' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Generator/ImageMagickGenerator.php', 'Identicon\\Generator\\ImageMagickGenerator' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Generator/ImageMagickGenerator.php',
'Identicon\\Generator\\SvgGenerator' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Generator/SvgGenerator.php',
'Identicon\\Identicon' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Identicon.php', 'Identicon\\Identicon' => __DIR__ . '/..' . '/yzalis/identicon/src/Identicon/Identicon.php',
'PrivateBin\\Configuration' => __DIR__ . '/../..' . '/lib/Configuration.php', 'PrivateBin\\Configuration' => __DIR__ . '/../..' . '/lib/Configuration.php',
'PrivateBin\\Controller' => __DIR__ . '/../..' . '/lib/Controller.php', 'PrivateBin\\Controller' => __DIR__ . '/../..' . '/lib/Controller.php',
@ -46,6 +45,7 @@ class ComposerStaticInitDontChange
'PrivateBin\\Data\\Database' => __DIR__ . '/../..' . '/lib/Data/Database.php', 'PrivateBin\\Data\\Database' => __DIR__ . '/../..' . '/lib/Data/Database.php',
'PrivateBin\\Data\\Filesystem' => __DIR__ . '/../..' . '/lib/Data/Filesystem.php', 'PrivateBin\\Data\\Filesystem' => __DIR__ . '/../..' . '/lib/Data/Filesystem.php',
'PrivateBin\\Filter' => __DIR__ . '/../..' . '/lib/Filter.php', 'PrivateBin\\Filter' => __DIR__ . '/../..' . '/lib/Filter.php',
'PrivateBin\\FormatV2' => __DIR__ . '/../..' . '/lib/FormatV2.php',
'PrivateBin\\I18n' => __DIR__ . '/../..' . '/lib/I18n.php', 'PrivateBin\\I18n' => __DIR__ . '/../..' . '/lib/I18n.php',
'PrivateBin\\Json' => __DIR__ . '/../..' . '/lib/Json.php', 'PrivateBin\\Json' => __DIR__ . '/../..' . '/lib/Json.php',
'PrivateBin\\Model' => __DIR__ . '/../..' . '/lib/Model.php', 'PrivateBin\\Model' => __DIR__ . '/../..' . '/lib/Model.php',
@ -58,7 +58,6 @@ class ComposerStaticInitDontChange
'PrivateBin\\Persistence\\ServerSalt' => __DIR__ . '/../..' . '/lib/Persistence/ServerSalt.php', 'PrivateBin\\Persistence\\ServerSalt' => __DIR__ . '/../..' . '/lib/Persistence/ServerSalt.php',
'PrivateBin\\Persistence\\TrafficLimiter' => __DIR__ . '/../..' . '/lib/Persistence/TrafficLimiter.php', 'PrivateBin\\Persistence\\TrafficLimiter' => __DIR__ . '/../..' . '/lib/Persistence/TrafficLimiter.php',
'PrivateBin\\Request' => __DIR__ . '/../..' . '/lib/Request.php', 'PrivateBin\\Request' => __DIR__ . '/../..' . '/lib/Request.php',
'PrivateBin\\FormatV2' => __DIR__ . '/../..' . '/lib/FormatV2.php',
'PrivateBin\\View' => __DIR__ . '/../..' . '/lib/View.php', 'PrivateBin\\View' => __DIR__ . '/../..' . '/lib/View.php',
'PrivateBin\\Vizhash16x16' => __DIR__ . '/../..' . '/lib/Vizhash16x16.php', 'PrivateBin\\Vizhash16x16' => __DIR__ . '/../..' . '/lib/Vizhash16x16.php',
); );
@ -68,7 +67,6 @@ class ComposerStaticInitDontChange
return \Closure::bind(function () use ($loader) { return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitDontChange::$prefixLengthsPsr4; $loader->prefixLengthsPsr4 = ComposerStaticInitDontChange::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitDontChange::$prefixDirsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInitDontChange::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInitDontChange::$prefixesPsr0;
$loader->classMap = ComposerStaticInitDontChange::$classMap; $loader->classMap = ComposerStaticInitDontChange::$classMap;
}, null, ClassLoader::class); }, null, ClassLoader::class);

View file

@ -28,8 +28,9 @@
if (!is_callable('RandomCompat_strlen')) { if (!is_callable('RandomCompat_strlen')) {
if ( if (
defined('MB_OVERLOAD_STRING') && defined('MB_OVERLOAD_STRING')
ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING &&
((int) ini_get('mbstring.func_overload')) & MB_OVERLOAD_STRING
) { ) {
/** /**
* strlen() implementation that isn't brittle to mbstring.func_overload * strlen() implementation that isn't brittle to mbstring.func_overload
@ -82,8 +83,8 @@ if (!is_callable('RandomCompat_substr')) {
if ( if (
defined('MB_OVERLOAD_STRING') defined('MB_OVERLOAD_STRING')
&& &&
ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING ((int) ini_get('mbstring.func_overload')) & MB_OVERLOAD_STRING
) { ) {
/** /**
* substr() implementation that isn't brittle to mbstring.func_overload * substr() implementation that isn't brittle to mbstring.func_overload
@ -93,7 +94,7 @@ if (!is_callable('RandomCompat_substr')) {
* *
* @param string $binary_string * @param string $binary_string
* @param int $start * @param int $start
* @param int $length (optional) * @param int|null $length (optional)
* *
* @throws TypeError * @throws TypeError
* *
@ -118,6 +119,7 @@ if (!is_callable('RandomCompat_substr')) {
* mb_substr($str, 0, NULL, '8bit') returns an empty string on * mb_substr($str, 0, NULL, '8bit') returns an empty string on
* PHP 5.3, so we have to find the length ourselves. * PHP 5.3, so we have to find the length ourselves.
*/ */
/** @var int $length */
$length = RandomCompat_strlen($binary_string) - $start; $length = RandomCompat_strlen($binary_string) - $start;
} elseif (!is_int($length)) { } elseif (!is_int($length)) {
throw new TypeError( throw new TypeError(
@ -133,7 +135,12 @@ if (!is_callable('RandomCompat_substr')) {
return ''; return '';
} }
return (string) mb_substr($binary_string, $start, $length, '8bit'); return (string) mb_substr(
(string) $binary_string,
(int) $start,
(int) $length,
'8bit'
);
} }
} else { } else {
@ -145,7 +152,7 @@ if (!is_callable('RandomCompat_substr')) {
* *
* @param string $binary_string * @param string $binary_string
* @param int $start * @param int $start
* @param int $length (optional) * @param int|null $length (optional)
* *
* @throws TypeError * @throws TypeError
* *
@ -172,10 +179,17 @@ if (!is_callable('RandomCompat_substr')) {
); );
} }
return (string) substr($binary_string, $start, $length); return (string) substr(
(string )$binary_string,
(int) $start,
(int) $length
);
} }
return (string) substr($binary_string, $start); return (string) substr(
(string) $binary_string,
(int) $start
);
} }
} }
} }

View file

@ -27,19 +27,19 @@
*/ */
if (!is_callable('RandomCompat_intval')) { if (!is_callable('RandomCompat_intval')) {
/** /**
* Cast to an integer if we can, safely. * Cast to an integer if we can, safely.
* *
* If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX) * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
* (non-inclusive), it will sanely cast it to an int. If you it's equal to * (non-inclusive), it will sanely cast it to an int. If you it's equal to
* ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
* lose precision, so the <= and => operators might accidentally let a float * lose precision, so the <= and => operators might accidentally let a float
* through. * through.
* *
* @param int|float $number The number we want to convert to an int * @param int|float $number The number we want to convert to an int
* @param bool $fail_open Set to true to not throw an exception * @param bool $fail_open Set to true to not throw an exception
* *
* @return float|int * @return float|int
* @psalm-suppress InvalidReturnType * @psalm-suppress InvalidReturnType
* *
@ -50,14 +50,16 @@ if (!is_callable('RandomCompat_intval')) {
if (is_int($number) || is_float($number)) { if (is_int($number) || is_float($number)) {
$number += 0; $number += 0;
} elseif (is_numeric($number)) { } elseif (is_numeric($number)) {
/** @psalm-suppress InvalidOperand */
$number += 0; $number += 0;
} }
/** @var int|float $number */
if ( if (
is_float($number) is_float($number)
&& &&
$number > ~PHP_INT_MAX $number > ~PHP_INT_MAX
&& &&
$number < PHP_INT_MAX $number < PHP_INT_MAX
) { ) {
$number = (int) $number; $number = (int) $number;

View file

@ -1,12 +1,12 @@
<?php <?php
/** /**
* Random_* Compatibility Library * Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects * for using the new PHP 7 random_* API in PHP 5 projects
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
@ -30,7 +30,7 @@ if (!class_exists('Error', false)) {
// We can't really avoid making this extend Exception in PHP 5. // We can't really avoid making this extend Exception in PHP 5.
class Error extends Exception class Error extends Exception
{ {
} }
} }
@ -38,12 +38,12 @@ if (!class_exists('TypeError', false)) {
if (is_subclass_of('Error', 'Exception')) { if (is_subclass_of('Error', 'Exception')) {
class TypeError extends Error class TypeError extends Error
{ {
} }
} else { } else {
class TypeError extends Exception class TypeError extends Exception
{ {
} }
} }
} }

View file

@ -3,8 +3,8 @@
* Random_* Compatibility Library * Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects * for using the new PHP 7 random_* API in PHP 5 projects
* *
* @version 2.0.15 * @version 2.0.17
* @released 2018-06-08 * @released 2018-07-04
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
@ -203,7 +203,6 @@ if (!is_callable('random_bytes')) {
* and hope the developer won't let it fail silently. * and hope the developer won't let it fail silently.
* *
* @param mixed $length * @param mixed $length
* @psalm-suppress MissingReturnType
* @psalm-suppress InvalidReturnType * @psalm-suppress InvalidReturnType
* @throws Exception * @throws Exception
* @return string * @return string

View file

@ -1,22 +1,22 @@
<?php <?php
/** /**
* Random_* Compatibility Library * Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects * for using the new PHP 7 random_* API in PHP 5 projects
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -41,6 +41,7 @@ if (!is_callable('random_bytes')) {
function random_bytes($bytes) function random_bytes($bytes)
{ {
try { try {
/** @var int $bytes */
$bytes = RandomCompat_intval($bytes); $bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) { } catch (TypeError $ex) {
throw new TypeError( throw new TypeError(
@ -54,12 +55,14 @@ if (!is_callable('random_bytes')) {
); );
} }
/** @var string $buf */
$buf = ''; $buf = '';
if (!class_exists('COM')) { if (!class_exists('COM')) {
throw new Error( throw new Error(
'COM does not exist' 'COM does not exist'
); );
} }
/** @var COM $util */
$util = new COM('CAPICOM.Utilities.1'); $util = new COM('CAPICOM.Utilities.1');
$execCount = 0; $execCount = 0;
@ -68,12 +71,12 @@ if (!is_callable('random_bytes')) {
* get N bytes of random data, then CAPICOM has failed us. * get N bytes of random data, then CAPICOM has failed us.
*/ */
do { do {
$buf .= base64_decode($util->GetRandom($bytes, 0)); $buf .= base64_decode((string) $util->GetRandom($bytes, 0));
if (RandomCompat_strlen($buf) >= $bytes) { if (RandomCompat_strlen($buf) >= $bytes) {
/** /**
* Return our random entropy buffer here: * Return our random entropy buffer here:
*/ */
return RandomCompat_substr($buf, 0, $bytes); return (string) RandomCompat_substr($buf, 0, $bytes);
} }
++$execCount; ++$execCount;
} while ($execCount < $bytes); } while ($execCount < $bytes);
@ -85,4 +88,4 @@ if (!is_callable('random_bytes')) {
'Could not gather sufficient random data' 'Could not gather sufficient random data'
); );
} }
} }

View file

@ -1,22 +1,22 @@
<?php <?php
/** /**
* Random_* Compatibility Library * Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects * for using the new PHP 7 random_* API in PHP 5 projects
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -36,6 +36,7 @@ if (!is_callable('random_bytes')) {
* random numbers in accordance with best practices * random numbers in accordance with best practices
* *
* Why we use /dev/urandom and not /dev/random * Why we use /dev/urandom and not /dev/random
* @ref https://www.2uo.de/myths-about-urandom
* @ref http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers * @ref http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers
* *
* @param int $bytes * @param int $bytes
@ -46,25 +47,47 @@ if (!is_callable('random_bytes')) {
*/ */
function random_bytes($bytes) function random_bytes($bytes)
{ {
/** @var resource $fp */
static $fp = null; static $fp = null;
/** /**
* This block should only be run once * This block should only be run once
*/ */
if (empty($fp)) { if (empty($fp)) {
/** /**
* We use /dev/urandom if it is a char device. * We don't want to ever read C:\dev\random, only /dev/urandom on
* We never fall back to /dev/random * Unix-like operating systems. While we guard against this
* condition in random.php, it doesn't hurt to be defensive in depth
* here.
*
* To that end, we only try to open /dev/urandom if we're on a Unix-
* like operating system (which means the directory separator is set
* to "/" not "\".
*/ */
$fp = fopen('/dev/urandom', 'rb'); if (DIRECTORY_SEPARATOR === '/') {
if (!empty($fp)) { if (!is_readable('/dev/urandom')) {
$st = fstat($fp); throw new Exception(
if (($st['mode'] & 0170000) !== 020000) { 'Environment misconfiguration: ' .
fclose($fp); '/dev/urandom cannot be read.'
$fp = false; );
}
/**
* We use /dev/urandom if it is a char device.
* We never fall back to /dev/random
*/
/** @var resource|bool $fp */
$fp = fopen('/dev/urandom', 'rb');
if (is_resource($fp)) {
/** @var array<string, int> $st */
$st = fstat($fp);
if (($st['mode'] & 0170000) !== 020000) {
fclose($fp);
$fp = false;
}
} }
} }
if (!empty($fp)) { if (is_resource($fp)) {
/** /**
* stream_set_read_buffer() does not exist in HHVM * stream_set_read_buffer() does not exist in HHVM
* *
@ -83,6 +106,7 @@ if (!is_callable('random_bytes')) {
} }
try { try {
/** @var int $bytes */
$bytes = RandomCompat_intval($bytes); $bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) { } catch (TypeError $ex) {
throw new TypeError( throw new TypeError(
@ -103,7 +127,7 @@ if (!is_callable('random_bytes')) {
* if (empty($fp)) line is logic that should only be run once per * if (empty($fp)) line is logic that should only be run once per
* page load. * page load.
*/ */
if (!empty($fp)) { if (is_resource($fp)) {
/** /**
* @var int * @var int
*/ */
@ -123,29 +147,28 @@ if (!is_callable('random_bytes')) {
*/ */
$read = fread($fp, $remaining); $read = fread($fp, $remaining);
if (!is_string($read)) { if (!is_string($read)) {
if ($read === false) { /**
/** * We cannot safely read from the file. Exit the
* We cannot safely read from the file. Exit the * do-while loop and trigger the exception condition
* do-while loop and trigger the exception condition *
* * @var string|bool
* @var string|bool */
*/ $buf = false;
$buf = false; break;
break;
}
} }
/** /**
* Decrease the number of bytes returned from remaining * Decrease the number of bytes returned from remaining
*/ */
$remaining -= RandomCompat_strlen($read); $remaining -= RandomCompat_strlen($read);
/** /**
* @var string|bool * @var string $buf
*/ */
$buf = $buf . $read; $buf .= $read;
} while ($remaining > 0); } while ($remaining > 0);
/** /**
* Is our result valid? * Is our result valid?
* @var string|bool $buf
*/ */
if (is_string($buf)) { if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) { if (RandomCompat_strlen($buf) === $bytes) {

View file

@ -1,22 +1,22 @@
<?php <?php
/** /**
* Random_* Compatibility Library * Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects * for using the new PHP 7 random_* API in PHP 5 projects
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -43,6 +43,7 @@ if (!is_callable('random_bytes')) {
function random_bytes($bytes) function random_bytes($bytes)
{ {
try { try {
/** @var int $bytes */
$bytes = RandomCompat_intval($bytes); $bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) { } catch (TypeError $ex) {
throw new TypeError( throw new TypeError(
@ -60,6 +61,7 @@ if (!is_callable('random_bytes')) {
* \Sodium\randombytes_buf() doesn't allow more than 2147483647 bytes to be * \Sodium\randombytes_buf() doesn't allow more than 2147483647 bytes to be
* generated in one invocation. * generated in one invocation.
*/ */
/** @var string|bool $buf */
if ($bytes > 2147483647) { if ($bytes > 2147483647) {
$buf = ''; $buf = '';
for ($i = 0; $i < $bytes; $i += 1073741824) { for ($i = 0; $i < $bytes; $i += 1073741824) {
@ -69,10 +71,11 @@ if (!is_callable('random_bytes')) {
$buf .= \Sodium\randombytes_buf($n); $buf .= \Sodium\randombytes_buf($n);
} }
} else { } else {
/** @var string|bool $buf */
$buf = \Sodium\randombytes_buf($bytes); $buf = \Sodium\randombytes_buf($bytes);
} }
if ($buf !== false) { if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) { if (RandomCompat_strlen($buf) === $bytes) {
return $buf; return $buf;
} }

View file

@ -1,22 +1,22 @@
<?php <?php
/** /**
* Random_* Compatibility Library * Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects * for using the new PHP 7 random_* API in PHP 5 projects
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -43,6 +43,7 @@ if (!is_callable('random_bytes')) {
function random_bytes($bytes) function random_bytes($bytes)
{ {
try { try {
/** @var int $bytes */
$bytes = RandomCompat_intval($bytes); $bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) { } catch (TypeError $ex) {
throw new TypeError( throw new TypeError(

View file

@ -1,22 +1,22 @@
<?php <?php
/** /**
* Random_* Compatibility Library * Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects * for using the new PHP 7 random_* API in PHP 5 projects
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises * Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -42,6 +42,7 @@ if (!is_callable('random_bytes')) {
function random_bytes($bytes) function random_bytes($bytes)
{ {
try { try {
/** @var int $bytes */
$bytes = RandomCompat_intval($bytes); $bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) { } catch (TypeError $ex) {
throw new TypeError( throw new TypeError(
@ -55,10 +56,11 @@ if (!is_callable('random_bytes')) {
); );
} }
$buf = @mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM); /** @var string|bool $buf */
$buf = @mcrypt_create_iv((int) $bytes, (int) MCRYPT_DEV_URANDOM);
if ( if (
$buf !== false is_string($buf)
&& &&
RandomCompat_strlen($buf) === $bytes RandomCompat_strlen($buf) === $bytes
) { ) {
/** /**

View file

@ -51,6 +51,7 @@ if (!is_callable('random_int')) {
*/ */
try { try {
/** @var int $min */
$min = RandomCompat_intval($min); $min = RandomCompat_intval($min);
} catch (TypeError $ex) { } catch (TypeError $ex) {
throw new TypeError( throw new TypeError(
@ -59,6 +60,7 @@ if (!is_callable('random_int')) {
} }
try { try {
/** @var int $max */
$max = RandomCompat_intval($max); $max = RandomCompat_intval($max);
} catch (TypeError $ex) { } catch (TypeError $ex) {
throw new TypeError( throw new TypeError(
@ -90,11 +92,18 @@ if (!is_callable('random_int')) {
* so we can minimize the number of discards * so we can minimize the number of discards
*/ */
$attempts = $bits = $bytes = $mask = $valueShift = 0; $attempts = $bits = $bytes = $mask = $valueShift = 0;
/** @var int $attempts */
/** @var int $bits */
/** @var int $bytes */
/** @var int $mask */
/** @var int $valueShift */
/** /**
* At this point, $range is a positive number greater than 0. It might * At this point, $range is a positive number greater than 0. It might
* overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to * overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to
* a float and we will lose some precision. * a float and we will lose some precision.
*
* @var int|float $range
*/ */
$range = $max - $min; $range = $max - $min;
@ -115,6 +124,7 @@ if (!is_callable('random_int')) {
* @ref http://3v4l.org/XX9r5 (64-bit) * @ref http://3v4l.org/XX9r5 (64-bit)
*/ */
$bytes = PHP_INT_SIZE; $bytes = PHP_INT_SIZE;
/** @var int $mask */
$mask = ~0; $mask = ~0;
} else { } else {
@ -129,16 +139,19 @@ if (!is_callable('random_int')) {
} }
++$bits; ++$bits;
$range >>= 1; $range >>= 1;
/** @var int $mask */
$mask = $mask << 1 | 1; $mask = $mask << 1 | 1;
} }
$valueShift = $min; $valueShift = $min;
} }
/** @var int $val */
$val = 0; $val = 0;
/** /**
* Now that we have our parameters set up, let's begin generating * Now that we have our parameters set up, let's begin generating
* random integers until one falls between $min and $max * random integers until one falls between $min and $max
*/ */
/** @psalm-suppress RedundantCondition */
do { do {
/** /**
* The rejection probability is at most 0.5, so this corresponds * The rejection probability is at most 0.5, so this corresponds
@ -169,6 +182,7 @@ if (!is_callable('random_int')) {
for ($i = 0; $i < $bytes; ++$i) { for ($i = 0; $i < $bytes; ++$i) {
$val |= ord($randomByteString[$i]) << ($i * 8); $val |= ord($randomByteString[$i]) << ($i * 8);
} }
/** @var int $val */
/** /**
* Apply mask * Apply mask

View file

@ -1,57 +0,0 @@
<?php
$dist = dirname(__DIR__).'/dist';
if (!is_dir($dist)) {
mkdir($dist, 0755);
}
if (file_exists($dist.'/random_compat.phar')) {
unlink($dist.'/random_compat.phar');
}
$phar = new Phar(
$dist.'/random_compat.phar',
FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME,
'random_compat.phar'
);
rename(
dirname(__DIR__).'/lib/random.php',
dirname(__DIR__).'/lib/index.php'
);
$phar->buildFromDirectory(dirname(__DIR__).'/lib');
rename(
dirname(__DIR__).'/lib/index.php',
dirname(__DIR__).'/lib/random.php'
);
/**
* If we pass an (optional) path to a private key as a second argument, we will
* sign the Phar with OpenSSL.
*
* If you leave this out, it will produce an unsigned .phar!
*/
if ($argc > 1) {
if (!@is_readable($argv[1])) {
echo 'Could not read the private key file:', $argv[1], "\n";
exit(255);
}
$pkeyFile = file_get_contents($argv[1]);
$private = openssl_get_privatekey($pkeyFile);
if ($private !== false) {
$pkey = '';
openssl_pkey_export($private, $pkey);
$phar->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
/**
* Save the corresponding public key to the file
*/
if (!@is_readable($dist.'/random_compat.phar.pubkey')) {
$details = openssl_pkey_get_details($private);
file_put_contents(
$dist.'/random_compat.phar.pubkey',
$details['key']
);
}
} else {
echo 'An error occurred reading the private key from OpenSSL.', "\n";
exit(255);
}
}

View file

@ -1,9 +0,0 @@
<?php
require_once 'lib/byte_safe_strings.php';
require_once 'lib/cast_to_int.php';
require_once 'lib/error_polyfill.php';
require_once 'other/ide_stubs/libsodium.php';
require_once 'lib/random.php';
$int = random_int(0, 65536);

View file

@ -2,7 +2,7 @@
namespace Identicon\Generator; namespace Identicon\Generator;
use Identicon\Generator\GeneratorInterface; use Exception;
/** /**
* @author Benjamin Laugueux <benjamin@yzalis.com> * @author Benjamin Laugueux <benjamin@yzalis.com>
@ -15,22 +15,22 @@ class BaseGenerator
protected $generatedImage; protected $generatedImage;
/** /**
* @var integer * @var array
*/ */
protected $color; protected $color;
/** /**
* @var integer * @var array
*/ */
protected $backgroundColor; protected $backgroundColor;
/** /**
* @var integer * @var int
*/ */
protected $size; protected $size;
/** /**
* @var integer * @var int
*/ */
protected $pixelRatio; protected $pixelRatio;
@ -42,14 +42,14 @@ class BaseGenerator
/** /**
* @var array * @var array
*/ */
private $arrayOfSquare = array(); private $arrayOfSquare = [];
/** /**
* Set the image color * Set the image color.
* *
* @param string|array $color The color in hexa (6 chars) or rgb array * @param string|array $color The color in hexa (3 or 6 chars) or rgb array
* *
* @return this * @return $this
*/ */
public function setColor($color) public function setColor($color)
{ {
@ -63,11 +63,11 @@ class BaseGenerator
} }
/** /**
* Set the image background color * Set the image background color.
* *
* @param string|array $backgroundColor The color in hexa (6 chars) or rgb array * @param string|array $backgroundColor The color in hexa (3 or 6 chars) or rgb array
* *
* @return this * @return $this
*/ */
public function setBackgroundColor($backgroundColor) public function setBackgroundColor($backgroundColor)
{ {
@ -80,27 +80,32 @@ class BaseGenerator
return $this; return $this;
} }
/**
* @param array|string $color
*
* @return array
*/
private function convertColor($color) private function convertColor($color)
{ {
$convertedColor = array();
if (is_array($color)) { if (is_array($color)) {
$convertedColor[0] = $color[0]; return $color;
$convertedColor[1] = $color[1];
$convertedColor[2] = $color[2];
} else {
if (false !== strpos($color, '#')) {
$color = substr($color, 1);
}
$convertedColor[0] = hexdec(substr($color, 0, 2));
$convertedColor[1] = hexdec(substr($color, 2, 2));
$convertedColor[2] = hexdec(substr($color, 4, 2));
} }
return $convertedColor; if (preg_match('/^#?([a-z\d])([a-z\d])([a-z\d])$/i', $color, $matches)) {
$color = $matches[1].$matches[1];
$color .= $matches[2].$matches[2];
$color .= $matches[3].$matches[3];
}
preg_match('/#?([a-z\d]{2})([a-z\d]{2})([a-z\d]{2})$/i', $color, $matches);
return array_map(function ($value) {
return hexdec($value);
}, array_slice($matches, 1, 3));
} }
/** /**
* Get the color * Get the color.
* *
* @return array * @return array
*/ */
@ -109,9 +114,8 @@ class BaseGenerator
return $this->color; return $this->color;
} }
/** /**
* Get the background color * Get the background color.
* *
* @return array * @return array
*/ */
@ -121,48 +125,51 @@ class BaseGenerator
} }
/** /**
* Convert the hash into an multidimensionnal array of boolean * Convert the hash into an multidimensional array of boolean.
* *
* @return this * @return $this
*/ */
private function convertHashToArrayOfBoolean() private function convertHashToArrayOfBoolean()
{ {
preg_match_all('/(\w)(\w)/', $this->hash, $chars); preg_match_all('/(\w)(\w)/', $this->hash, $chars);
foreach ($chars[1] as $i => $char) { foreach ($chars[1] as $i => $char) {
if ($i % 3 == 0) { $index = (int) ($i / 3);
$this->arrayOfSquare[$i/3][0] = $this->convertHexaToBoolean($char); $data = $this->convertHexaToBoolean($char);
$this->arrayOfSquare[$i/3][4] = $this->convertHexaToBoolean($char);
} elseif ($i % 3 == 1) { $items = [
$this->arrayOfSquare[$i/3][1] = $this->convertHexaToBoolean($char); 0 => [0, 4],
$this->arrayOfSquare[$i/3][3] = $this->convertHexaToBoolean($char); 1 => [1, 3],
} else { 2 => [2],
$this->arrayOfSquare[$i/3][2] = $this->convertHexaToBoolean($char); ];
foreach ($items[$i % 3] as $item) {
$this->arrayOfSquare[$index][$item] = $data;
} }
ksort($this->arrayOfSquare[$i/3]);
ksort($this->arrayOfSquare[$index]);
} }
$this->color[0] = hexdec(array_pop($chars[1]))*16; $this->color = array_map(function ($data) {
$this->color[1] = hexdec(array_pop($chars[1]))*16; return hexdec($data) * 16;
$this->color[2] = hexdec(array_pop($chars[1]))*16; }, array_reverse($chars[1]));
return $this; return $this;
} }
/** /**
* Convert an heaxecimal number into a boolean * Convert an hexadecimal number into a boolean.
* *
* @param string $hexa * @param string $hexa
* *
* @return boolean * @return bool
*/ */
private function convertHexaToBoolean($hexa) private function convertHexaToBoolean($hexa)
{ {
return (bool) intval(round(hexdec($hexa)/10)); return (bool) round(hexdec($hexa) / 10);
} }
/** /**
*
*
* @return array * @return array
*/ */
public function getArrayOfSquare() public function getArrayOfSquare()
@ -171,7 +178,7 @@ class BaseGenerator
} }
/** /**
* Get the identicon string hash * Get the identicon string hash.
* *
* @return string * @return string
*/ */
@ -181,16 +188,18 @@ class BaseGenerator
} }
/** /**
* Generate a hash fron the original string * Generate a hash from the original string.
* *
* @param string $string * @param string $string
* *
* @return this * @throws \Exception
*
* @return $this
*/ */
public function setString($string) public function setString($string)
{ {
if (null === $string) { if (null === $string) {
throw new \Exception('The string cannot be null.'); throw new Exception('The string cannot be null.');
} }
$this->hash = md5($string); $this->hash = md5($string);
@ -201,11 +210,11 @@ class BaseGenerator
} }
/** /**
* Set the image size * Set the image size.
* *
* @param integer $size * @param int $size
* *
* @return this * @return $this
*/ */
public function setSize($size) public function setSize($size)
{ {
@ -214,15 +223,15 @@ class BaseGenerator
} }
$this->size = $size; $this->size = $size;
$this->pixelRatio = round($size / 5); $this->pixelRatio = (int) round($size / 5);
return $this; return $this;
} }
/** /**
* Get the image size * Get the image size.
* *
* @return integer * @return int
*/ */
public function getSize() public function getSize()
{ {
@ -230,9 +239,9 @@ class BaseGenerator
} }
/** /**
* Get the pixel ratio * Get the pixel ratio.
* *
* @return array * @return int
*/ */
public function getPixelRatio() public function getPixelRatio()
{ {

View file

@ -2,20 +2,34 @@
namespace Identicon\Generator; namespace Identicon\Generator;
use Identicon\Generator\GeneratorInterface; use Exception;
/** /**
* @author Benjamin Laugueux <benjamin@yzalis.com> * @author Benjamin Laugueux <benjamin@yzalis.com>
*/ */
class GdGenerator extends BaseGenerator implements GeneratorInterface class GdGenerator extends BaseGenerator implements GeneratorInterface
{ {
/**
* GdGenerator constructor.
*/
public function __construct() public function __construct()
{ {
if (!extension_loaded('gd')) { if (!extension_loaded('gd') && !extension_loaded('ext-gd')) {
throw new \Exception('GD does not appear to be avaliable in your PHP installation. Please try another generator'); throw new Exception('GD does not appear to be available in your PHP installation. Please try another generator');
} }
} }
/**
* @return string
*/
public function getMimeType()
{
return 'image/png';
}
/**
* @return $this
*/
private function generateImage() private function generateImage()
{ {
// prepare image // prepare image
@ -30,7 +44,7 @@ class GdGenerator extends BaseGenerator implements GeneratorInterface
imagefill($this->generatedImage, 0, 0, $background); imagefill($this->generatedImage, 0, 0, $background);
} }
// prepage color // prepare color
$rgbColor = $this->getColor(); $rgbColor = $this->getColor();
$gdColor = imagecolorallocate($this->generatedImage, $rgbColor[0], $rgbColor[1], $rgbColor[2]); $gdColor = imagecolorallocate($this->generatedImage, $rgbColor[0], $rgbColor[1], $rgbColor[2]);
@ -47,7 +61,7 @@ class GdGenerator extends BaseGenerator implements GeneratorInterface
} }
/** /**
* {@inheritDoc} * {@inheritdoc}
*/ */
public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null) public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null)
{ {
@ -60,7 +74,7 @@ class GdGenerator extends BaseGenerator implements GeneratorInterface
} }
/** /**
* {@inheritDoc} * {@inheritdoc}
*/ */
public function getImageResource($string, $size = null, $color = null, $backgroundColor = null) public function getImageResource($string, $size = null, $color = null, $backgroundColor = null)
{ {

View file

@ -8,26 +8,36 @@ namespace Identicon\Generator;
interface GeneratorInterface interface GeneratorInterface
{ {
/** /**
* * @param string $string
* * @param int $size
* @param string $string * @param array|string $color
* @param integer $size * @param array|string $backgroundColor
* @param array|string $color
* @param array|string $backgroundColor
* *
* @return mixed * @return mixed
*/ */
function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null); public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null);
/** /**
* * @param string $string
* * @param int $size
* @param string $string * @param array|string $color
* @param integer $size * @param array|string $backgroundColor
* @param array|string $color
* @param array|string $backgroundColor
* *
* @return string * @return string
*/ */
function getImageResource($string, $size = null, $color = null, $backgroundColor = null); public function getImageResource($string, $size = null, $color = null, $backgroundColor = null);
/**
* Return the mime-type of this identicon.
*
* @return string
*/
public function getMimeType();
/**
* Return the color of the created identicon.
*
* @return array
*/
public function getColor();
} }

View file

@ -2,20 +2,38 @@
namespace Identicon\Generator; namespace Identicon\Generator;
use Identicon\Generator\GeneratorInterface; use Exception;
use ImagickDraw;
use ImagickPixel;
/** /**
* @author Francis Chuang <francis.chuang@gmail.com> * @author Francis Chuang <francis.chuang@gmail.com>
*/ */
class ImageMagickGenerator extends BaseGenerator implements GeneratorInterface class ImageMagickGenerator extends BaseGenerator implements GeneratorInterface
{ {
/**
* ImageMagickGenerator constructor.
*
* @throws \Exception
*/
public function __construct() public function __construct()
{ {
if (!extension_loaded('imagick')) { if (!extension_loaded('imagick')) {
throw new \Exception('ImageMagick does not appear to be avaliable in your PHP installation. Please try another generator'); throw new Exception('ImageMagick does not appear to be avaliable in your PHP installation. Please try another generator');
} }
} }
/**
* @return string
*/
public function getMimeType()
{
return 'image/png';
}
/**
* @return $this
*/
private function generateImage() private function generateImage()
{ {
$this->generatedImage = new \Imagick(); $this->generatedImage = new \Imagick();
@ -24,23 +42,23 @@ class ImageMagickGenerator extends BaseGenerator implements GeneratorInterface
if (null === $rgbBackgroundColor) { if (null === $rgbBackgroundColor) {
$background = 'none'; $background = 'none';
} else { } else {
$background = new \ImagickPixel("rgb($rgbBackgroundColor[0],$rgbBackgroundColor[1],$rgbBackgroundColor[2])"); $background = new ImagickPixel("rgb($rgbBackgroundColor[0],$rgbBackgroundColor[1],$rgbBackgroundColor[2])");
} }
$this->generatedImage->newImage($this->pixelRatio * 5, $this->pixelRatio * 5, $background, 'png'); $this->generatedImage->newImage($this->pixelRatio * 5, $this->pixelRatio * 5, $background, 'png');
// prepare color // prepare color
$rgbColor = $this->getColor(); $rgbColor = $this->getColor();
$color = new \ImagickPixel("rgb($rgbColor[0],$rgbColor[1],$rgbColor[2])"); $color = new ImagickPixel("rgb($rgbColor[0],$rgbColor[1],$rgbColor[2])");
$draw = new \ImagickDraw(); $draw = new ImagickDraw();
$draw->setFillColor($color); $draw->setFillColor($color);
// draw the content // draw the content
foreach ($this->getArrayOfSquare() as $lineKey => $lineValue) { foreach ($this->getArrayOfSquare() as $lineKey => $lineValue) {
foreach ($lineValue as $colKey => $colValue) { foreach ($lineValue as $colKey => $colValue) {
if (true === $colValue) { if (true === $colValue) {
$draw->rectangle( $colKey * $this->pixelRatio, $lineKey * $this->pixelRatio, ($colKey + 1) * $this->pixelRatio, ($lineKey + 1) * $this->pixelRatio); $draw->rectangle($colKey * $this->pixelRatio, $lineKey * $this->pixelRatio, ($colKey + 1) * $this->pixelRatio, ($lineKey + 1) * $this->pixelRatio);
} }
} }
} }
@ -51,7 +69,7 @@ class ImageMagickGenerator extends BaseGenerator implements GeneratorInterface
} }
/** /**
* {@inheritDoc} * {@inheritdoc}
*/ */
public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null) public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null)
{ {
@ -64,7 +82,7 @@ class ImageMagickGenerator extends BaseGenerator implements GeneratorInterface
} }
/** /**
* {@inheritDoc} * {@inheritdoc}
*/ */
public function getImageResource($string, $size = null, $color = null, $backgroundColor = null) public function getImageResource($string, $size = null, $color = null, $backgroundColor = null)
{ {

View file

@ -0,0 +1,88 @@
<?php
namespace Identicon\Generator;
/**
* @author Grummfy <grummfy@gmail.com>
*/
class SvgGenerator extends BaseGenerator implements GeneratorInterface
{
/**
* {@inheritdoc}
*/
public function getMimeType()
{
return 'image/svg+xml';
}
/**
* {@inheritdoc}
*/
public function getImageBinaryData($string, $size = null, $color = null, $backgroundColor = null)
{
return $this->getImageResource($string, $size, $color, $backgroundColor);
}
/**
* {@inheritdoc}
*/
public function getImageResource($string, $size = null, $color = null, $backgroundColor = null)
{
$this
->setString($string)
->setSize($size)
->setColor($color)
->setBackgroundColor($backgroundColor)
->_generateImage();
return $this->generatedImage;
}
/**
* @return $this
*/
protected function _generateImage()
{
// prepare image
$w = $this->getPixelRatio() * 5;
$h = $this->getPixelRatio() * 5;
$svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="'.$w.'" height="'.$h.'">';
$backgroundColor = '#FFFFFF';
$rgbBackgroundColor = $this->getBackgroundColor();
if (!is_null($rgbBackgroundColor)) {
$backgroundColor = $this->_toUnderstandableColor($rgbBackgroundColor);
}
$svg .= '<rect width="'.$w.'" height="'.$h.'" style="fill:'.$backgroundColor.';stroke-width:1;stroke:'.$backgroundColor.'"/>';
$rgbColor = $this->_toUnderstandableColor($this->getColor());
// draw content
foreach ($this->getArrayOfSquare() as $lineKey => $lineValue) {
foreach ($lineValue as $colKey => $colValue) {
if (true === $colValue) {
$svg .= '<rect x="'.$colKey * $this->getPixelRatio().'" y="'.$lineKey * $this->getPixelRatio().'" width="'.($this->getPixelRatio()).'" height="'.$this->getPixelRatio().'" style="fill:'.$rgbColor.';stroke-width:0;"/>';
}
}
}
$svg .= '</svg>';
$this->generatedImage = $svg;
return $this;
}
/**
* @param array|string $color
*
* @return string
*/
protected function _toUnderstandableColor($color)
{
if (is_array($color)) {
return 'rgb('.implode(', ', $color).')';
}
return $color;
}
}

View file

@ -11,10 +11,15 @@ use Identicon\Generator\GeneratorInterface;
class Identicon class Identicon
{ {
/** /**
* @var GeneratorInterface * @var \Identicon\Generator\GeneratorInterface
*/ */
private $generator; private $generator;
/**
* Identicon constructor.
*
* @param \Identicon\Generator\GeneratorInterface|null $generator
*/
public function __construct($generator = null) public function __construct($generator = null)
{ {
if (null === $generator) { if (null === $generator) {
@ -22,15 +27,14 @@ class Identicon
} else { } else {
$this->generator = $generator; $this->generator = $generator;
} }
} }
/** /**
* Set the image generetor * Set the image generator.
* *
* @param GeneratorInterface $generator * @param \Identicon\Generator\GeneratorInterface $generator
* *
* @throws \Exception * @return $this
*/ */
public function setGenerator(GeneratorInterface $generator) public function setGenerator(GeneratorInterface $generator)
{ {
@ -40,26 +44,26 @@ class Identicon
} }
/** /**
* Display an Identicon image * Display an Identicon image.
* *
* @param string $string * @param string $string
* @param integer $size * @param int $size
* @param string $color * @param string $color
* @param string $backgroundColor * @param string $backgroundColor
*/ */
public function displayImage($string, $size = 64, $color = null, $backgroundColor = null) public function displayImage($string, $size = 64, $color = null, $backgroundColor = null)
{ {
header("Content-Type: image/png"); header('Content-Type: '.$this->generator->getMimeType());
echo $this->getImageData($string, $size, $color, $backgroundColor); echo $this->getImageData($string, $size, $color, $backgroundColor);
} }
/** /**
* Get an Identicon PNG image data * Get an Identicon PNG image data.
* *
* @param string $string * @param string $string
* @param integer $size * @param int $size
* @param string $color * @param string $color
* @param string $backgroundColor * @param string $backgroundColor
* *
* @return string * @return string
*/ */
@ -69,12 +73,12 @@ class Identicon
} }
/** /**
* Get an Identicon PNG image resource * Get an Identicon PNG image resource.
* *
* @param string $string * @param string $string
* @param integer $size * @param int $size
* @param string $color * @param string $color
* @param string $backgroundColor * @param string $backgroundColor
* *
* @return string * @return string
*/ */
@ -84,17 +88,36 @@ class Identicon
} }
/** /**
* Get an Identicon PNG image data as base 64 encoded * Get an Identicon PNG image data as base 64 encoded.
* *
* @param string $string * @param string $string
* @param integer $size * @param int $size
* @param string $color * @param string $color
* @param string $backgroundColor * @param string $backgroundColor
* *
* @return string * @return string
*/ */
public function getImageDataUri($string, $size = 64, $color = null, $backgroundColor = null) public function getImageDataUri($string, $size = 64, $color = null, $backgroundColor = null)
{ {
return sprintf('data:image/png;base64,%s', base64_encode($this->getImageData($string, $size, $color, $backgroundColor))); return sprintf('data:%s;base64,%s', $this->generator->getMimeType(), base64_encode($this->getImageData($string, $size, $color, $backgroundColor)));
} }
/**
* Get the color of the Identicon
*
* Returns an array with RGB values of the Identicon's color. Colors may be NULL if no image has been generated
* so far (e.g., when calling the method on a new Identicon()).
*
* @return array
*/
public function getColor()
{
$colors = $this->generator->getColor();
return [
"r" => $colors[0],
"g" => $colors[1],
"b" => $colors[2]
];
}
} }

View file

@ -1,30 +0,0 @@
<?php
/**
* Simple autoloader that follow the PHP Standards Recommendation #0 (PSR-0)
* @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md for more informations.
*
* Code inspired from the SplClassLoader RFC
* @see https://wiki.php.net/rfc/splclassloader#example_implementation
*/
spl_autoload_register(function($className) {
$className = ltrim($className, '\\');
if (0 != strpos($className, 'Identicon')) {
return false;
}
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName = __DIR__ . DIRECTORY_SEPARATOR . $fileName . $className . '.php';
if (is_file($fileName)) {
require $fileName;
return true;
}
return false;
});