Debian Codegraph @

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