QRCode.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. AlphaNum, Byte, Kanji, MaskPatternTester, Number, QRCodeDataException, QRDataInterface, QRMatrix
  15. };
  16. use chillerlan\QRCode\Output\{
  17. QRCodeOutputException, QRImage, QRMarkup, QROutputInterface, QRString
  18. };
  19. use chillerlan\Traits\ClassLoader;
  20. /**
  21. * Turns a text string into a Model 2 QR Code
  22. *
  23. * @link https://github.com/kazuhikoarase/qrcode-generator/tree/master/php
  24. * @link http://www.qrcode.com/en/codes/model12.html
  25. * @link http://www.thonky.com/qr-code-tutorial/
  26. */
  27. class QRCode{
  28. use ClassLoader;
  29. /**
  30. * API constants
  31. */
  32. const OUTPUT_MARKUP_HTML = 'html';
  33. const OUTPUT_MARKUP_SVG = 'svg';
  34. # const OUTPUT_MARKUP_EPS = 'eps';
  35. # const OUTPUT_MARKUP_XML = 'xml'; // anyone?
  36. const OUTPUT_IMAGE_PNG = 'png';
  37. const OUTPUT_IMAGE_JPG = 'jpg';
  38. const OUTPUT_IMAGE_GIF = 'gif';
  39. const OUTPUT_STRING_JSON = 'json';
  40. const OUTPUT_STRING_TEXT = 'text';
  41. const OUTPUT_CUSTOM = 'custom';
  42. const VERSION_AUTO = -1;
  43. const MASK_PATTERN_AUTO = -1;
  44. const ECC_L = 0b01; // 7%.
  45. const ECC_M = 0b00; // 15%.
  46. const ECC_Q = 0b11; // 25%.
  47. const ECC_H = 0b10; // 30%.
  48. const DATA_NUMBER = 0b0001;
  49. const DATA_ALPHANUM = 0b0010;
  50. const DATA_BYTE = 0b0100;
  51. const DATA_KANJI = 0b1000;
  52. const ECC_MODES = [
  53. self::ECC_L => 0,
  54. self::ECC_M => 1,
  55. self::ECC_Q => 2,
  56. self::ECC_H => 3,
  57. ];
  58. const DATA_MODES = [
  59. self::DATA_NUMBER => 0,
  60. self::DATA_ALPHANUM => 1,
  61. self::DATA_BYTE => 2,
  62. self::DATA_KANJI => 3,
  63. ];
  64. const OUTPUT_MODES = [
  65. QRMarkup::class => [
  66. self::OUTPUT_MARKUP_SVG,
  67. self::OUTPUT_MARKUP_HTML,
  68. # self::OUTPUT_MARKUP_EPS,
  69. ],
  70. QRImage::class => [
  71. self::OUTPUT_IMAGE_PNG,
  72. self::OUTPUT_IMAGE_GIF,
  73. self::OUTPUT_IMAGE_JPG,
  74. ],
  75. QRString::class => [
  76. self::OUTPUT_STRING_JSON,
  77. self::OUTPUT_STRING_TEXT,
  78. ]
  79. ];
  80. /**
  81. * @var \chillerlan\QRCode\QROptions
  82. */
  83. protected $options;
  84. /**
  85. * @var \chillerlan\QRCode\Data\QRDataInterface
  86. */
  87. protected $dataInterface;
  88. /**
  89. * QRCode constructor.
  90. *
  91. * @param \chillerlan\QRCode\QROptions|null $options
  92. */
  93. public function __construct(QROptions $options = null){
  94. mb_internal_encoding('UTF-8');
  95. $this->setOptions($options ?? new QROptions);
  96. }
  97. /**
  98. * Sets the options, called internally by the constructor
  99. *
  100. * @param \chillerlan\QRCode\QROptions $options
  101. *
  102. * @return \chillerlan\QRCode\QRCode
  103. * @throws \chillerlan\QRCode\QRCodeException
  104. */
  105. public function setOptions(QROptions $options):QRCode{
  106. if(!array_key_exists($options->eccLevel, $this::ECC_MODES)){
  107. throw new QRCodeException('Invalid error correct level: '.$options->eccLevel);
  108. }
  109. if(!is_array($options->imageTransparencyBG) || count($options->imageTransparencyBG) < 3){
  110. $options->imageTransparencyBG = [255, 255, 255];
  111. }
  112. $options->version = (int)$options->version;
  113. // clamp min/max version number
  114. $options->versionMin = (int)min($options->versionMin, $options->versionMax);
  115. $options->versionMax = (int)max($options->versionMin, $options->versionMax);
  116. $this->options = $options;
  117. return $this;
  118. }
  119. /**
  120. * Renders a QR Code for the given $data and QROptions
  121. *
  122. * @param string $data
  123. *
  124. * @return mixed
  125. */
  126. public function render(string $data){
  127. return $this->initOutputInterface($data)->dump();
  128. }
  129. /**
  130. * Returns a QRMatrix object for the given $data and current QROptions
  131. *
  132. * @param string $data
  133. *
  134. * @return \chillerlan\QRCode\Data\QRMatrix
  135. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  136. */
  137. public function getMatrix(string $data):QRMatrix {
  138. //NOTE: input sanitization should be done outside
  139. //$data = trim($data);
  140. if(empty($data)){
  141. throw new QRCodeDataException('QRCode::getMatrix() No data given.');
  142. }
  143. $this->dataInterface = $this->initDataInterface($data);
  144. $maskPattern = $this->options->maskPattern === $this::MASK_PATTERN_AUTO
  145. ? $this->getBestMaskPattern()
  146. : min(7, max(0, (int)$this->options->maskPattern));
  147. $matrix = $this
  148. ->dataInterface
  149. ->initMatrix($maskPattern)
  150. ;
  151. if((bool)$this->options->addQuietzone){
  152. $matrix->setQuietZone($this->options->quietzoneSize);
  153. }
  154. return $matrix;
  155. }
  156. /**
  157. * shoves a QRMatrix through the MaskPatternTester to find the lowest penalty mask pattern
  158. *
  159. * @see \chillerlan\QRCode\Data\MaskPatternTester
  160. *
  161. * @return int
  162. */
  163. protected function getBestMaskPattern():int{
  164. $penalties = [];
  165. $tester = new MaskPatternTester;
  166. for($testPattern = 0; $testPattern < 8; $testPattern++){
  167. $matrix = $this
  168. ->dataInterface
  169. ->initMatrix($testPattern, true);
  170. $tester->setMatrix($matrix);
  171. $penalties[$testPattern] = $tester->testPattern();
  172. }
  173. return array_search(min($penalties), $penalties, true);
  174. }
  175. /**
  176. * returns a fresh QRDataInterface for the given $data
  177. *
  178. * @param string $data
  179. *
  180. * @return \chillerlan\QRCode\Data\QRDataInterface
  181. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  182. */
  183. public function initDataInterface(string $data):QRDataInterface{
  184. $DATA_MODES = [
  185. Number::class => 'Number',
  186. AlphaNum::class => 'AlphaNum',
  187. Kanji::class => 'Kanji',
  188. Byte::class => 'Byte',
  189. ];
  190. foreach($DATA_MODES as $dataInterface => $mode){
  191. if(call_user_func_array([$this, 'is'.$mode], [$data]) === true){
  192. return $this->loadClass($dataInterface, QRDataInterface::class, $this->options, $data);
  193. }
  194. }
  195. throw new QRCodeDataException('invalid data type'); // @codeCoverageIgnore
  196. }
  197. /**
  198. * returns a fresh (built-in) QROutputInterface
  199. *
  200. * @param string $data
  201. *
  202. * @return \chillerlan\QRCode\Output\QROutputInterface
  203. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  204. */
  205. protected function initOutputInterface(string $data):QROutputInterface{
  206. if($this->options->outputType === $this::OUTPUT_CUSTOM && $this->options->outputInterface !== null){
  207. return $this->loadClass($this->options->outputInterface, QROutputInterface::class, $this->options, $this->getMatrix($data));
  208. }
  209. foreach($this::OUTPUT_MODES as $outputInterface => $modes){
  210. if(in_array($this->options->outputType, $modes, true)){
  211. return $this->loadClass($outputInterface, QROutputInterface::class, $this->options, $this->getMatrix($data));
  212. }
  213. }
  214. throw new QRCodeOutputException('invalid output type');
  215. }
  216. /**
  217. * checks if a string qualifies as numeric
  218. *
  219. * @param string $string
  220. *
  221. * @return bool
  222. */
  223. public function isNumber(string $string):bool {
  224. $len = strlen($string);
  225. $map = str_split('0123456789');
  226. for($i = 0; $i < $len; $i++){
  227. if(!in_array($string[$i], $map, true)){
  228. return false;
  229. }
  230. }
  231. return true;
  232. }
  233. /**
  234. * checks if a string qualifies as alphanumeric
  235. *
  236. * @param string $string
  237. *
  238. * @return bool
  239. */
  240. public function isAlphaNum(string $string):bool {
  241. $len = strlen($string);
  242. for($i = 0; $i < $len; $i++){
  243. if(!in_array($string[$i], AlphaNum::CHAR_MAP, true)){
  244. return false;
  245. }
  246. }
  247. return true;
  248. }
  249. /**
  250. * checks if a string qualifies as Kanji
  251. *
  252. * @param string $string
  253. *
  254. * @return bool
  255. */
  256. public function isKanji(string $string):bool {
  257. $i = 0;
  258. $len = strlen($string);
  259. while($i + 1 < $len){
  260. $c = ((0xff&ord($string[$i])) << 8)|(0xff&ord($string[$i + 1]));
  261. if(!($c >= 0x8140 && $c <= 0x9FFC) && !($c >= 0xE040 && $c <= 0xEBBF)){
  262. return false;
  263. }
  264. $i += 2;
  265. }
  266. return $i >= $len;
  267. }
  268. /**
  269. * a dummy
  270. *
  271. * @param $data
  272. *
  273. * @return bool
  274. */
  275. protected function isByte(string $data):bool{
  276. return !empty($data);
  277. }
  278. }