QRCode.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. /**
  3. * Class QRCode
  4. *
  5. * @filesource QRCode.php
  6. * @created 26.11.2015
  7. * @package chillerlan\QRCode
  8. * @author Smiley <smiley@chillerlan.net>
  9. * @copyright 2015 Smiley
  10. * @license MIT
  11. */
  12. namespace chillerlan\QRCode;
  13. use chillerlan\QRCode\Data\{
  14. MaskPatternTester, QRCodeDataException, QRDataInterface, QRMatrix
  15. };
  16. use chillerlan\QRCode\Output\{
  17. QRCodeOutputException, QRImage, QRImagick, QRMarkup, QROutputInterface, QRString
  18. };
  19. use chillerlan\Settings\SettingsContainerInterface;
  20. use function array_search, call_user_func_array, class_exists, in_array, mb_internal_encoding, min, ord, strlen;
  21. /**
  22. * Turns a text string into a Model 2 QR Code
  23. *
  24. * @link https://github.com/kazuhikoarase/qrcode-generator/tree/master/php
  25. * @link http://www.qrcode.com/en/codes/model12.html
  26. * @link http://www.thonky.com/qr-code-tutorial/
  27. */
  28. class QRCode{
  29. /**
  30. * API constants
  31. */
  32. public const OUTPUT_MARKUP_HTML = 'html';
  33. public const OUTPUT_MARKUP_SVG = 'svg';
  34. public const OUTPUT_IMAGE_PNG = 'png';
  35. public const OUTPUT_IMAGE_JPG = 'jpg';
  36. public const OUTPUT_IMAGE_GIF = 'gif';
  37. public const OUTPUT_STRING_JSON = 'json';
  38. public const OUTPUT_STRING_TEXT = 'text';
  39. public const OUTPUT_IMAGICK = 'imagick';
  40. public const OUTPUT_CUSTOM = 'custom';
  41. public const VERSION_AUTO = -1;
  42. public const MASK_PATTERN_AUTO = -1;
  43. public const ECC_L = 0b01; // 7%.
  44. public const ECC_M = 0b00; // 15%.
  45. public const ECC_Q = 0b11; // 25%.
  46. public const ECC_H = 0b10; // 30%.
  47. public const DATA_NUMBER = 0b0001;
  48. public const DATA_ALPHANUM = 0b0010;
  49. public const DATA_BYTE = 0b0100;
  50. public const DATA_KANJI = 0b1000;
  51. public const ECC_MODES = [
  52. self::ECC_L => 0,
  53. self::ECC_M => 1,
  54. self::ECC_Q => 2,
  55. self::ECC_H => 3,
  56. ];
  57. public const DATA_MODES = [
  58. self::DATA_NUMBER => 0,
  59. self::DATA_ALPHANUM => 1,
  60. self::DATA_BYTE => 2,
  61. self::DATA_KANJI => 3,
  62. ];
  63. public const OUTPUT_MODES = [
  64. QRMarkup::class => [
  65. self::OUTPUT_MARKUP_SVG,
  66. self::OUTPUT_MARKUP_HTML,
  67. ],
  68. QRImage::class => [
  69. self::OUTPUT_IMAGE_PNG,
  70. self::OUTPUT_IMAGE_GIF,
  71. self::OUTPUT_IMAGE_JPG,
  72. ],
  73. QRString::class => [
  74. self::OUTPUT_STRING_JSON,
  75. self::OUTPUT_STRING_TEXT,
  76. ],
  77. QRImagick::class => [
  78. self::OUTPUT_IMAGICK,
  79. ],
  80. ];
  81. /**
  82. * @var \chillerlan\QRCode\QROptions|\chillerlan\Settings\SettingsContainerInterface
  83. */
  84. protected SettingsContainerInterface $options;
  85. protected QRDataInterface $dataInterface;
  86. /**
  87. * @see http://php.net/manual/function.mb-internal-encoding.php
  88. */
  89. protected string $mbCurrentEncoding;
  90. /**
  91. * QRCode constructor.
  92. */
  93. public function __construct(SettingsContainerInterface $options = null){
  94. // save the current mb encoding (in case it differs from UTF-8)
  95. $this->mbCurrentEncoding = mb_internal_encoding();
  96. // use UTF-8 from here on
  97. mb_internal_encoding('UTF-8');
  98. $this->options = $options ?? new QROptions;
  99. }
  100. /**
  101. * @return void
  102. */
  103. public function __destruct(){
  104. // restore the previous mb_internal_encoding, so that we don't mess up the rest of the script
  105. mb_internal_encoding($this->mbCurrentEncoding);
  106. }
  107. /**
  108. * Renders a QR Code for the given $data and QROptions
  109. *
  110. * @return mixed
  111. */
  112. public function render(string $data, string $file = null){
  113. return $this->initOutputInterface($data)->dump($file);
  114. }
  115. /**
  116. * Returns a QRMatrix object for the given $data and current QROptions
  117. *
  118. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  119. */
  120. public function getMatrix(string $data):QRMatrix{
  121. if(empty($data)){
  122. throw new QRCodeDataException('QRCode::getMatrix() No data given.');
  123. }
  124. $this->dataInterface = $this->initDataInterface($data);
  125. $maskPattern = $this->options->maskPattern === $this::MASK_PATTERN_AUTO
  126. ? $this->getBestMaskPattern()
  127. : $this->options->maskPattern;
  128. $matrix = $this->dataInterface->initMatrix($maskPattern);
  129. if((bool)$this->options->addQuietzone){
  130. $matrix->setQuietZone($this->options->quietzoneSize);
  131. }
  132. return $matrix;
  133. }
  134. /**
  135. * shoves a QRMatrix through the MaskPatternTester to find the lowest penalty mask pattern
  136. *
  137. * @see \chillerlan\QRCode\Data\MaskPatternTester
  138. */
  139. protected function getBestMaskPattern():int{
  140. $penalties = [];
  141. for($pattern = 0; $pattern < 8; $pattern++){
  142. $tester = new MaskPatternTester($this->dataInterface->initMatrix($pattern, true));
  143. $penalties[$pattern] = $tester->testPattern();
  144. }
  145. return array_search(min($penalties), $penalties, true);
  146. }
  147. /**
  148. * returns a fresh QRDataInterface for the given $data
  149. *
  150. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  151. */
  152. public function initDataInterface(string $data):QRDataInterface{
  153. $dataModes = ['Number', 'AlphaNum', 'Kanji', 'Byte'];
  154. $dataNamespace = __NAMESPACE__.'\\Data\\';
  155. // allow forcing the data mode
  156. // see https://github.com/chillerlan/php-qrcode/issues/39
  157. if(in_array($this->options->dataMode, $dataModes, true)){
  158. $dataInterface = $dataNamespace.$this->options->dataMode;
  159. return new $dataInterface($this->options, $data);
  160. }
  161. foreach($dataModes as $mode){
  162. $dataInterface = $dataNamespace.$mode;
  163. if(call_user_func_array([$this, 'is'.$mode], [$data]) && class_exists($dataInterface)){
  164. return new $dataInterface($this->options, $data);
  165. }
  166. }
  167. throw new QRCodeDataException('invalid data type'); // @codeCoverageIgnore
  168. }
  169. /**
  170. * returns a fresh (built-in) QROutputInterface
  171. *
  172. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  173. */
  174. protected function initOutputInterface(string $data):QROutputInterface{
  175. if($this->options->outputType === $this::OUTPUT_CUSTOM && class_exists($this->options->outputInterface)){
  176. return new $this->options->outputInterface($this->options, $this->getMatrix($data));
  177. }
  178. foreach($this::OUTPUT_MODES as $outputInterface => $modes){
  179. if(in_array($this->options->outputType, $modes, true) && class_exists($outputInterface)){
  180. return new $outputInterface($this->options, $this->getMatrix($data));
  181. }
  182. }
  183. throw new QRCodeOutputException('invalid output type');
  184. }
  185. /**
  186. * checks if a string qualifies as numeric
  187. */
  188. public function isNumber(string $string):bool{
  189. return $this->checkString($string, QRDataInterface::NUMBER_CHAR_MAP);
  190. }
  191. /**
  192. * checks if a string qualifies as alphanumeric
  193. */
  194. public function isAlphaNum(string $string):bool{
  195. return $this->checkString($string, QRDataInterface::ALPHANUM_CHAR_MAP);
  196. }
  197. /**
  198. * checks is a given $string matches the characters of a given $charmap, returns false on the first invalid occurence.
  199. */
  200. protected function checkString(string $string, array $charmap):bool{
  201. $len = strlen($string);
  202. for($i = 0; $i < $len; $i++){
  203. if(!in_array($string[$i], $charmap, true)){
  204. return false;
  205. }
  206. }
  207. return true;
  208. }
  209. /**
  210. * checks if a string qualifies as Kanji
  211. */
  212. public function isKanji(string $string):bool{
  213. $i = 0;
  214. $len = strlen($string);
  215. while($i + 1 < $len){
  216. $c = ((0xff & ord($string[$i])) << 8) | (0xff & ord($string[$i + 1]));
  217. if(!($c >= 0x8140 && $c <= 0x9FFC) && !($c >= 0xE040 && $c <= 0xEBBF)){
  218. return false;
  219. }
  220. $i += 2;
  221. }
  222. return $i >= $len;
  223. }
  224. /**
  225. * a dummy
  226. */
  227. protected function isByte(string $data):bool{
  228. return !empty($data);
  229. }
  230. }