QRCode.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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
  83. */
  84. protected $options;
  85. /**
  86. * @var \chillerlan\QRCode\Data\QRDataInterface
  87. */
  88. protected $dataInterface;
  89. /**
  90. * @see http://php.net/manual/function.mb-internal-encoding.php
  91. * @var string
  92. */
  93. protected $mbCurrentEncoding;
  94. /**
  95. * QRCode constructor.
  96. *
  97. * @param \chillerlan\Settings\SettingsContainerInterface|null $options
  98. */
  99. public function __construct(SettingsContainerInterface $options = null){
  100. // save the current mb encoding (in case it differs from UTF-8)
  101. $this->mbCurrentEncoding = mb_internal_encoding();
  102. // use UTF-8 from here on
  103. mb_internal_encoding('UTF-8');
  104. $this->options = $options ?? new QROptions;
  105. }
  106. /**
  107. * @return void
  108. */
  109. public function __destruct(){
  110. // restore the previous mb_internal_encoding, so that we don't mess up the rest of the script
  111. mb_internal_encoding($this->mbCurrentEncoding);
  112. }
  113. /**
  114. * Renders a QR Code for the given $data and QROptions
  115. *
  116. * @param string $data
  117. * @param string|null $file
  118. *
  119. * @return mixed
  120. */
  121. public function render(string $data, string $file = null){
  122. return $this->initOutputInterface($data)->dump($file);
  123. }
  124. /**
  125. * Returns a QRMatrix object for the given $data and current QROptions
  126. *
  127. * @param string $data
  128. *
  129. * @return \chillerlan\QRCode\Data\QRMatrix
  130. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  131. */
  132. public function getMatrix(string $data):QRMatrix{
  133. if(empty($data)){
  134. throw new QRCodeDataException('QRCode::getMatrix() No data given.');
  135. }
  136. $this->dataInterface = $this->initDataInterface($data);
  137. $maskPattern = $this->options->maskPattern === $this::MASK_PATTERN_AUTO
  138. ? $this->getBestMaskPattern()
  139. : $this->options->maskPattern;
  140. $matrix = $this->dataInterface->initMatrix($maskPattern);
  141. if((bool)$this->options->addQuietzone){
  142. $matrix->setQuietZone($this->options->quietzoneSize);
  143. }
  144. return $matrix;
  145. }
  146. /**
  147. * shoves a QRMatrix through the MaskPatternTester to find the lowest penalty mask pattern
  148. *
  149. * @see \chillerlan\QRCode\Data\MaskPatternTester
  150. *
  151. * @return int
  152. */
  153. protected function getBestMaskPattern():int{
  154. $penalties = [];
  155. for($pattern = 0; $pattern < 8; $pattern++){
  156. $tester = new MaskPatternTester($this->dataInterface->initMatrix($pattern, true));
  157. $penalties[$pattern] = $tester->testPattern();
  158. }
  159. return array_search(min($penalties), $penalties, true);
  160. }
  161. /**
  162. * returns a fresh QRDataInterface for the given $data
  163. *
  164. * @param string $data
  165. *
  166. * @return \chillerlan\QRCode\Data\QRDataInterface
  167. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  168. */
  169. public function initDataInterface(string $data):QRDataInterface{
  170. foreach(['Number', 'AlphaNum', 'Kanji', 'Byte'] as $mode){
  171. $dataInterface = __NAMESPACE__.'\\Data\\'.$mode;
  172. if(call_user_func_array([$this, 'is'.$mode], [$data]) && class_exists($dataInterface)){
  173. return new $dataInterface($this->options, $data);
  174. }
  175. }
  176. throw new QRCodeDataException('invalid data type'); // @codeCoverageIgnore
  177. }
  178. /**
  179. * returns a fresh (built-in) QROutputInterface
  180. *
  181. * @param string $data
  182. *
  183. * @return \chillerlan\QRCode\Output\QROutputInterface
  184. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  185. */
  186. protected function initOutputInterface(string $data):QROutputInterface{
  187. if($this->options->outputType === $this::OUTPUT_CUSTOM && class_exists($this->options->outputInterface)){
  188. return new $this->options->outputInterface($this->options, $this->getMatrix($data));
  189. }
  190. foreach($this::OUTPUT_MODES as $outputInterface => $modes){
  191. if(in_array($this->options->outputType, $modes, true) && class_exists($outputInterface)){
  192. return new $outputInterface($this->options, $this->getMatrix($data));
  193. }
  194. }
  195. throw new QRCodeOutputException('invalid output type');
  196. }
  197. /**
  198. * checks if a string qualifies as numeric
  199. *
  200. * @param string $string
  201. *
  202. * @return bool
  203. */
  204. public function isNumber(string $string):bool{
  205. return $this->checkString($string, QRDataInterface::NUMBER_CHAR_MAP);
  206. }
  207. /**
  208. * checks if a string qualifies as alphanumeric
  209. *
  210. * @param string $string
  211. *
  212. * @return bool
  213. */
  214. public function isAlphaNum(string $string):bool{
  215. return $this->checkString($string, QRDataInterface::ALPHANUM_CHAR_MAP);
  216. }
  217. /**
  218. * checks is a given $string matches the characters of a given $charmap, returns false on the first invalid occurence.
  219. *
  220. * @param string $string
  221. * @param array $charmap
  222. *
  223. * @return bool
  224. */
  225. protected function checkString(string $string, array $charmap):bool{
  226. $len = strlen($string);
  227. for($i = 0; $i < $len; $i++){
  228. if(!in_array($string[$i], $charmap, true)){
  229. return false;
  230. }
  231. }
  232. return true;
  233. }
  234. /**
  235. * checks if a string qualifies as Kanji
  236. *
  237. * @param string $string
  238. *
  239. * @return bool
  240. */
  241. public function isKanji(string $string):bool{
  242. $i = 0;
  243. $len = strlen($string);
  244. while($i + 1 < $len){
  245. $c = ((0xff & ord($string[$i])) << 8) | (0xff & ord($string[$i + 1]));
  246. if(!($c >= 0x8140 && $c <= 0x9FFC) && !($c >= 0xE040 && $c <= 0xEBBF)){
  247. return false;
  248. }
  249. $i += 2;
  250. }
  251. return $i >= $len;
  252. }
  253. /**
  254. * a dummy
  255. *
  256. * @param $data
  257. *
  258. * @return bool
  259. */
  260. protected function isByte(string $data):bool{
  261. return !empty($data);
  262. }
  263. }