Debian Codegraph @

vendor/bacon/bacon-qr-code/src/Encoder/Encoder.php

raw
1 <?php
2 declare(strict_types = 1);
3
4 namespace BaconQrCode\Encoder;
5
6 use BaconQrCode\Common\BitArray;
7 use BaconQrCode\Common\CharacterSetEci;
8 use BaconQrCode\Common\ErrorCorrectionLevel;
9 use BaconQrCode\Common\Mode;
10 use BaconQrCode\Common\ReedSolomonCodec;
11 use BaconQrCode\Common\Version;
12 use BaconQrCode\Exception\WriterException;
13 use SplFixedArray;
14
15 /**
16 * Encoder.
17 */
18 final class Encoder
19 {
20 /**
21 * Default byte encoding.
22 */
23 public const DEFAULT_BYTE_MODE_ENCODING = 'ISO-8859-1';
24
25 /** @deprecated use DEFAULT_BYTE_MODE_ENCODING */
26 public const DEFAULT_BYTE_MODE_ECODING = self::DEFAULT_BYTE_MODE_ENCODING;
27
28 /**
29 * The original table is defined in the table 5 of JISX0510:2004 (p.19).
30 */
31 private const ALPHANUMERIC_TABLE = [
32 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
33 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
34 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
35 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
36 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
37 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
38 ];
39
40 /**
41 * Codec cache.
42 *
43 * @var array<string,ReedSolomonCodec>
44 */
45 private static array $codecs = [];
46
47 /**
48 * Encodes "content" with the error correction level "ecLevel".
49 */
50 public static function encode(
51 string $content,
52 ErrorCorrectionLevel $ecLevel,
53 string $encoding = self::DEFAULT_BYTE_MODE_ENCODING,
54 ?Version $forcedVersion = null,
55 // Barcode scanner might not be able to read the encoded message of the QR code with the prefix ECI of UTF-8
56 bool $prefixEci = true
57 ) : QrCode {
58 // Pick an encoding mode appropriate for the content. Note that this
59 // will not attempt to use multiple modes / segments even if that were
60 // more efficient. Would be nice.
61 $mode = self::chooseMode($content, $encoding);
62
63 // This will store the header information, like mode and length, as well
64 // as "header" segments like an ECI segment.
65 $headerBits = new BitArray();
66
67 // Append ECI segment if applicable
68 if ($prefixEci && Mode::BYTE() === $mode && self::DEFAULT_BYTE_MODE_ENCODING !== $encoding) {
69 $eci = CharacterSetEci::getCharacterSetEciByName($encoding);
70
71 if (null !== $eci) {
72 self::appendEci($eci, $headerBits);
73 }
74 }
75
76 // (With ECI in place,) Write the mode marker
77 self::appendModeInfo($mode, $headerBits);
78
79 // Collect data within the main segment, separately, to count its size
80 // if needed. Don't add it to main payload yet.
81 $dataBits = new BitArray();
82 self::appendBytes($content, $mode, $dataBits, $encoding);
83
84 // Hard part: need to know version to know how many bits length takes.
85 // But need to know how many bits it takes to know version. First we
86 // take a guess at version by assuming version will be the minimum, 1:
87 $provisionalBitsNeeded = $headerBits->getSize()
88 + $mode->getCharacterCountBits(Version::getVersionForNumber(1))
89 + $dataBits->getSize();
90 $provisionalVersion = self::chooseVersion($provisionalBitsNeeded, $ecLevel);
91
92 // Use that guess to calculate the right version. I am still not sure
93 // this works in 100% of cases.
94 $bitsNeeded = $headerBits->getSize()
95 + $mode->getCharacterCountBits($provisionalVersion)
96 + $dataBits->getSize();
97 $version = self::chooseVersion($bitsNeeded, $ecLevel);
98
99 if (null !== $forcedVersion) {
100 // Forced version check
101 if ($version->getVersionNumber() <= $forcedVersion->getVersionNumber()) {
102 // Calculated minimum version is same or equal as forced version
103 $version = $forcedVersion;
104 } else {
105 throw new WriterException(
106 'Invalid version! Calculated version: '
107 . $version->getVersionNumber()
108 . ', requested version: '
109 . $forcedVersion->getVersionNumber()
110 );
111 }
112 }
113
114 $headerAndDataBits = new BitArray();
115 $headerAndDataBits->appendBitArray($headerBits);
116
117 // Find "length" of main segment and write it.
118 $numLetters = (Mode::BYTE() === $mode ? $dataBits->getSizeInBytes() : strlen($content));
119 self::appendLengthInfo($numLetters, $version, $mode, $headerAndDataBits);
120
121 // Put data together into the overall payload.
122 $headerAndDataBits->appendBitArray($dataBits);
123 $ecBlocks = $version->getEcBlocksForLevel($ecLevel);
124 $numDataBytes = $version->getTotalCodewords() - $ecBlocks->getTotalEcCodewords();
125
126 // Terminate the bits properly.
127 self::terminateBits($numDataBytes, $headerAndDataBits);
128
129 // Interleave data bits with error correction code.
130 $finalBits = self::interleaveWithEcBytes(
131 $headerAndDataBits,
132 $version->getTotalCodewords(),
133 $numDataBytes,
134 $ecBlocks->getNumBlocks()
135 );
136
137 // Choose the mask pattern.
138 $dimension = $version->getDimensionForVersion();
139 $matrix = new ByteMatrix($dimension, $dimension);
140 $maskPattern = self::chooseMaskPattern($finalBits, $ecLevel, $version, $matrix);
141
142 // Build the matrix.
143 MatrixUtil::buildMatrix($finalBits, $ecLevel, $version, $maskPattern, $matrix);
144
145 return new QrCode($mode, $ecLevel, $version, $maskPattern, $matrix);
146 }
147
148 /**
149 * Gets the alphanumeric code for a byte.
150 */
151 private static function getAlphanumericCode(int $code) : int
152 {
153 if (isset(self::ALPHANUMERIC_TABLE[$code])) {
154 return self::ALPHANUMERIC_TABLE[$code];
155 }
156
157 return -1;
158 }
159
160 /**
161 * Chooses the best mode for a given content.
162 */
163 private static function chooseMode(string $content, ?string $encoding = null) : Mode
164 {
165 if (null !== $encoding && 0 === strcasecmp($encoding, 'SHIFT-JIS')) {
166 return self::isOnlyDoubleByteKanji($content) ? Mode::KANJI() : Mode::BYTE();
167 }
168
169 $hasNumeric = false;
170 $hasAlphanumeric = false;
171 $contentLength = strlen($content);
172
173 for ($i = 0; $i < $contentLength; ++$i) {
174 $char = $content[$i];
175
176 if (ctype_digit($char)) {
177 $hasNumeric = true;
178 } elseif (-1 !== self::getAlphanumericCode(ord($char))) {
179 $hasAlphanumeric = true;
180 } else {
181 return Mode::BYTE();
182 }
183 }
184
185 if ($hasAlphanumeric) {
186 return Mode::ALPHANUMERIC();
187 } elseif ($hasNumeric) {
188 return Mode::NUMERIC();
189 }
190
191 return Mode::BYTE();
192 }
193
194 /**
195 * Calculates the mask penalty for a matrix.
196 */
197 private static function calculateMaskPenalty(ByteMatrix $matrix) : int
198 {
199 return (
200 MaskUtil::applyMaskPenaltyRule1($matrix)
201 + MaskUtil::applyMaskPenaltyRule2($matrix)
202 + MaskUtil::applyMaskPenaltyRule3($matrix)
203 + MaskUtil::applyMaskPenaltyRule4($matrix)
204 );
205 }
206
207 /**
208 * Checks if content only consists of double-byte kanji characters.
209 */
210 private static function isOnlyDoubleByteKanji(string $content) : bool
211 {
212 $bytes = @iconv('utf-8', 'SHIFT-JIS', $content);
213
214 if (false === $bytes) {
215 return false;
216 }
217
218 $length = strlen($bytes);
219
220 if (0 !== $length % 2) {
221 return false;
222 }
223
224 for ($i = 0; $i < $length; $i += 2) {
225 $byte = ord($bytes[$i]) & 0xff;
226
227 if (($byte < 0x81 || $byte > 0x9f) && $byte < 0xe0 || $byte > 0xeb) {
228 return false;
229 }
230 }
231
232 return true;
233 }
234
235 /**
236 * Chooses the best mask pattern for a matrix.
237 */
238 private static function chooseMaskPattern(
239 BitArray $bits,
240 ErrorCorrectionLevel $ecLevel,
241 Version $version,
242 ByteMatrix $matrix
243 ) : int {
244 $minPenalty = PHP_INT_MAX;
245 $bestMaskPattern = -1;
246
247 for ($maskPattern = 0; $maskPattern < QrCode::NUM_MASK_PATTERNS; ++$maskPattern) {
248 MatrixUtil::buildMatrix($bits, $ecLevel, $version, $maskPattern, $matrix);
249 $penalty = self::calculateMaskPenalty($matrix);
250
251 if ($penalty < $minPenalty) {
252 $minPenalty = $penalty;
253 $bestMaskPattern = $maskPattern;
254 }
255 }
256
257 return $bestMaskPattern;
258 }
259
260 /**
261 * Chooses the best version for the input.
262 *
263 * @throws WriterException if data is too big
264 */
265 private static function chooseVersion(int $numInputBits, ErrorCorrectionLevel $ecLevel) : Version
266 {
267 for ($versionNum = 1; $versionNum <= 40; ++$versionNum) {
268 $version = Version::getVersionForNumber($versionNum);
269 $numBytes = $version->getTotalCodewords();
270
271 $ecBlocks = $version->getEcBlocksForLevel($ecLevel);
272 $numEcBytes = $ecBlocks->getTotalEcCodewords();
273
274 $numDataBytes = $numBytes - $numEcBytes;
275 $totalInputBytes = intdiv($numInputBits + 8, 8);
276
277 if ($numDataBytes >= $totalInputBytes) {
278 return $version;
279 }
280 }
281
282 throw new WriterException('Data too big');
283 }
284
285 /**
286 * Terminates the bits in a bit array.
287 *
288 * @throws WriterException if data bits cannot fit in the QR code
289 * @throws WriterException if bits size does not equal the capacity
290 */
291 private static function terminateBits(int $numDataBytes, BitArray $bits) : void
292 {
293 $capacity = $numDataBytes << 3;
294
295 if ($bits->getSize() > $capacity) {
296 throw new WriterException('Data bits cannot fit in the QR code');
297 }
298
299 for ($i = 0; $i < 4 && $bits->getSize() < $capacity; ++$i) {
300 $bits->appendBit(false);
301 }
302
303 $numBitsInLastByte = $bits->getSize() & 0x7;
304
305 if ($numBitsInLastByte > 0) {
306 for ($i = $numBitsInLastByte; $i < 8; ++$i) {
307 $bits->appendBit(false);
308 }
309 }
310
311 $numPaddingBytes = $numDataBytes - $bits->getSizeInBytes();
312
313 for ($i = 0; $i < $numPaddingBytes; ++$i) {
314 $bits->appendBits(0 === ($i & 0x1) ? 0xec : 0x11, 8);
315 }
316
317 if ($bits->getSize() !== $capacity) {
318 throw new WriterException('Bits size does not equal capacity');
319 }
320 }
321
322 /**
323 * Gets number of data- and EC bytes for a block ID.
324 *
325 * @return int[]
326 * @throws WriterException if block ID is too large
327 * @throws WriterException if EC bytes mismatch
328 * @throws WriterException if RS blocks mismatch
329 * @throws WriterException if total bytes mismatch
330 */
331 private static function getNumDataBytesAndNumEcBytesForBlockId(
332 int $numTotalBytes,
333 int $numDataBytes,
334 int $numRsBlocks,
335 int $blockId
336 ) : array {
337 if ($blockId >= $numRsBlocks) {
338 throw new WriterException('Block ID too large');
339 }
340
341 $numRsBlocksInGroup2 = $numTotalBytes % $numRsBlocks;
342 $numRsBlocksInGroup1 = $numRsBlocks - $numRsBlocksInGroup2;
343 $numTotalBytesInGroup1 = intdiv($numTotalBytes, $numRsBlocks);
344 $numTotalBytesInGroup2 = $numTotalBytesInGroup1 + 1;
345 $numDataBytesInGroup1 = intdiv($numDataBytes, $numRsBlocks);
346 $numDataBytesInGroup2 = $numDataBytesInGroup1 + 1;
347 $numEcBytesInGroup1 = $numTotalBytesInGroup1 - $numDataBytesInGroup1;
348 $numEcBytesInGroup2 = $numTotalBytesInGroup2 - $numDataBytesInGroup2;
349
350 if ($numEcBytesInGroup1 !== $numEcBytesInGroup2) {
351 throw new WriterException('EC bytes mismatch');
352 }
353
354 if ($numRsBlocks !== $numRsBlocksInGroup1 + $numRsBlocksInGroup2) {
355 throw new WriterException('RS blocks mismatch');
356 }
357
358 if ($numTotalBytes !==
359 (($numDataBytesInGroup1 + $numEcBytesInGroup1) * $numRsBlocksInGroup1)
360 + (($numDataBytesInGroup2 + $numEcBytesInGroup2) * $numRsBlocksInGroup2)
361 ) {
362 throw new WriterException('Total bytes mismatch');
363 }
364
365 if ($blockId < $numRsBlocksInGroup1) {
366 return [$numDataBytesInGroup1, $numEcBytesInGroup1];
367 } else {
368 return [$numDataBytesInGroup2, $numEcBytesInGroup2];
369 }
370 }
371
372 /**
373 * Interleaves data with EC bytes.
374 *
375 * @throws WriterException if number of bits and data bytes does not match
376 * @throws WriterException if data bytes does not match offset
377 * @throws WriterException if an interleaving error occurs
378 */
379 private static function interleaveWithEcBytes(
380 BitArray $bits,
381 int $numTotalBytes,
382 int $numDataBytes,
383 int $numRsBlocks
384 ) : BitArray {
385 if ($bits->getSizeInBytes() !== $numDataBytes) {
386 throw new WriterException('Number of bits and data bytes does not match');
387 }
388
389 $dataBytesOffset = 0;
390 $maxNumDataBytes = 0;
391 $maxNumEcBytes = 0;
392
393 $blocks = new SplFixedArray($numRsBlocks);
394
395 for ($i = 0; $i < $numRsBlocks; ++$i) {
396 list($numDataBytesInBlock, $numEcBytesInBlock) = self::getNumDataBytesAndNumEcBytesForBlockId(
397 $numTotalBytes,
398 $numDataBytes,
399 $numRsBlocks,
400 $i
401 );
402
403 $size = $numDataBytesInBlock;
404 $dataBytes = $bits->toBytes(8 * $dataBytesOffset, $size);
405 $ecBytes = self::generateEcBytes($dataBytes, $numEcBytesInBlock);
406 $blocks[$i] = new BlockPair($dataBytes, $ecBytes);
407
408 $maxNumDataBytes = max($maxNumDataBytes, $size);
409 $maxNumEcBytes = max($maxNumEcBytes, count($ecBytes));
410 $dataBytesOffset += $numDataBytesInBlock;
411 }
412
413 if ($numDataBytes !== $dataBytesOffset) {
414 throw new WriterException('Data bytes does not match offset');
415 }
416
417 $result = new BitArray();
418
419 for ($i = 0; $i < $maxNumDataBytes; ++$i) {
420 foreach ($blocks as $block) {
421 $dataBytes = $block->getDataBytes();
422
423 if ($i < count($dataBytes)) {
424 $result->appendBits($dataBytes[$i], 8);
425 }
426 }
427 }
428
429 for ($i = 0; $i < $maxNumEcBytes; ++$i) {
430 foreach ($blocks as $block) {
431 $ecBytes = $block->getErrorCorrectionBytes();
432
433 if ($i < count($ecBytes)) {
434 $result->appendBits($ecBytes[$i], 8);
435 }
436 }
437 }
438
439 if ($numTotalBytes !== $result->getSizeInBytes()) {
440 throw new WriterException(
441 'Interleaving error: ' . $numTotalBytes . ' and ' . $result->getSizeInBytes() . ' differ'
442 );
443 }
444
445 return $result;
446 }
447
448 /**
449 * Generates EC bytes for given data.
450 *
451 * @param SplFixedArray<int> $dataBytes
452 * @return SplFixedArray<int>
453 */
454 private static function generateEcBytes(SplFixedArray $dataBytes, int $numEcBytesInBlock) : SplFixedArray
455 {
456 $numDataBytes = count($dataBytes);
457 $toEncode = new SplFixedArray($numDataBytes + $numEcBytesInBlock);
458
459 for ($i = 0; $i < $numDataBytes; $i++) {
460 $toEncode[$i] = $dataBytes[$i] & 0xff;
461 }
462
463 $ecBytes = new SplFixedArray($numEcBytesInBlock);
464 $codec = self::getCodec($numDataBytes, $numEcBytesInBlock);
465 $codec->encode($toEncode, $ecBytes);
466
467 return $ecBytes;
468 }
469
470 /**
471 * Gets an RS codec and caches it.
472 */
473 private static function getCodec(int $numDataBytes, int $numEcBytesInBlock) : ReedSolomonCodec
474 {
475 $cacheId = $numDataBytes . '-' . $numEcBytesInBlock;
476
477 if (isset(self::$codecs[$cacheId])) {
478 return self::$codecs[$cacheId];
479 }
480
481 return self::$codecs[$cacheId] = new ReedSolomonCodec(
482 8,
483 0x11d,
484 0,
485 1,
486 $numEcBytesInBlock,
487 255 - $numDataBytes - $numEcBytesInBlock
488 );
489 }
490
491 /**
492 * Appends mode information to a bit array.
493 */
494 private static function appendModeInfo(Mode $mode, BitArray $bits) : void
495 {
496 $bits->appendBits($mode->getBits(), 4);
497 }
498
499 /**
500 * Appends length information to a bit array.
501 *
502 * @throws WriterException if num letters is bigger than expected
503 */
504 private static function appendLengthInfo(int $numLetters, Version $version, Mode $mode, BitArray $bits) : void
505 {
506 $numBits = $mode->getCharacterCountBits($version);
507
508 if ($numLetters >= (1 << $numBits)) {
509 throw new WriterException($numLetters . ' is bigger than ' . ((1 << $numBits) - 1));
510 }
511
512 $bits->appendBits($numLetters, $numBits);
513 }
514
515 /**
516 * Appends bytes to a bit array in a specific mode.
517 *
518 * @throws WriterException if an invalid mode was supplied
519 */
520 private static function appendBytes(string $content, Mode $mode, BitArray $bits, string $encoding) : void
521 {
522 switch ($mode) {
523 case Mode::NUMERIC():
524 self::appendNumericBytes($content, $bits);
525 break;
526
527 case Mode::ALPHANUMERIC():
528 self::appendAlphanumericBytes($content, $bits);
529 break;
530
531 case Mode::BYTE():
532 self::append8BitBytes($content, $bits, $encoding);
533 break;
534
535 case Mode::KANJI():
536 self::appendKanjiBytes($content, $bits);
537 break;
538
539 default:
540 throw new WriterException('Invalid mode: ' . $mode);
541 }
542 }
543
544 /**
545 * Appends numeric bytes to a bit array.
546 */
547 private static function appendNumericBytes(string $content, BitArray $bits) : void
548 {
549 $length = strlen($content);
550 $i = 0;
551
552 while ($i < $length) {
553 $num1 = (int) $content[$i];
554
555 if ($i + 2 < $length) {
556 // Encode three numeric letters in ten bits.
557 $num2 = (int) $content[$i + 1];
558 $num3 = (int) $content[$i + 2];
559 $bits->appendBits($num1 * 100 + $num2 * 10 + $num3, 10);
560 $i += 3;
561 } elseif ($i + 1 < $length) {
562 // Encode two numeric letters in seven bits.
563 $num2 = (int) $content[$i + 1];
564 $bits->appendBits($num1 * 10 + $num2, 7);
565 $i += 2;
566 } else {
567 // Encode one numeric letter in four bits.
568 $bits->appendBits($num1, 4);
569 ++$i;
570 }
571 }
572 }
573
574 /**
575 * Appends alpha-numeric bytes to a bit array.
576 *
577 * @throws WriterException if an invalid alphanumeric code was found
578 */
579 private static function appendAlphanumericBytes(string $content, BitArray $bits) : void
580 {
581 $length = strlen($content);
582 $i = 0;
583
584 while ($i < $length) {
585 $code1 = self::getAlphanumericCode(ord($content[$i]));
586
587 if (-1 === $code1) {
588 throw new WriterException('Invalid alphanumeric code');
589 }
590
591 if ($i + 1 < $length) {
592 $code2 = self::getAlphanumericCode(ord($content[$i + 1]));
593
594 if (-1 === $code2) {
595 throw new WriterException('Invalid alphanumeric code');
596 }
597
598 // Encode two alphanumeric letters in 11 bits.
599 $bits->appendBits($code1 * 45 + $code2, 11);
600 $i += 2;
601 } else {
602 // Encode one alphanumeric letter in six bits.
603 $bits->appendBits($code1, 6);
604 ++$i;
605 }
606 }
607 }
608
609 /**
610 * Appends regular 8-bit bytes to a bit array.
611 *
612 * @throws WriterException if content cannot be encoded to target encoding
613 */
614 private static function append8BitBytes(string $content, BitArray $bits, string $encoding) : void
615 {
616 $bytes = @iconv('utf-8', $encoding, $content);
617
618 if (false === $bytes) {
619 throw new WriterException('Could not encode content to ' . $encoding);
620 }
621
622 $length = strlen($bytes);
623
624 for ($i = 0; $i < $length; $i++) {
625 $bits->appendBits(ord($bytes[$i]), 8);
626 }
627 }
628
629 /**
630 * Appends KANJI bytes to a bit array.
631 *
632 * @throws WriterException if content does not seem to be encoded in SHIFT-JIS
633 * @throws WriterException if an invalid byte sequence occurs
634 */
635 private static function appendKanjiBytes(string $content, BitArray $bits) : void
636 {
637 $bytes = @iconv('utf-8', 'SHIFT-JIS', $content);
638
639 if (false === $bytes) {
640 throw new WriterException('Content could not be converted to SHIFT-JIS');
641 }
642
643 if (strlen($bytes) % 2 > 0) {
644 // We just do a simple length check here. The for loop will check
645 // individual characters.
646 throw new WriterException('Content does not seem to be encoded in SHIFT-JIS');
647 }
648
649 $length = strlen($bytes);
650
651 for ($i = 0; $i < $length; $i += 2) {
652 $byte1 = ord($bytes[$i]) & 0xff;
653 $byte2 = ord($bytes[$i + 1]) & 0xff;
654 $code = ($byte1 << 8) | $byte2;
655
656 if ($code >= 0x8140 && $code <= 0x9ffc) {
657 $subtracted = $code - 0x8140;
658 } elseif ($code >= 0xe040 && $code <= 0xebbf) {
659 $subtracted = $code - 0xc140;
660 } else {
661 throw new WriterException('Invalid byte sequence');
662 }
663
664 $encoded = (($subtracted >> 8) * 0xc0) + ($subtracted & 0xff);
665
666 $bits->appendBits($encoded, 13);
667 }
668 }
669
670 /**
671 * Appends ECI information to a bit array.
672 */
673 private static function appendEci(CharacterSetEci $eci, BitArray $bits) : void
674 {
675 $mode = Mode::ECI();
676 $bits->appendBits($mode->getBits(), 4);
677 $bits->appendBits($eci->getValue(), 8);
678 }
679 }