Path: blob/master/externals/phpqrcode/phpqrcode.php
12240 views
<?php12/*3* PHP QR Code encoder4*5* This file contains MERGED version of PHP QR Code library.6* It was auto-generated from full version for your convenience.7*8* This merged version was configured to not requre any external files,9* with disabled cache, error loging and weker but faster mask matching.10* If you need tune it up please use non-merged version.11*12* For full version, documentation, examples of use please visit:13*14* http://phpqrcode.sourceforge.net/15* https://sourceforge.net/projects/phpqrcode/16*17* PHP QR Code is distributed under LGPL 318* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>19*20* This library is free software; you can redistribute it and/or21* modify it under the terms of the GNU Lesser General Public22* License as published by the Free Software Foundation; either23* version 3 of the License, or any later version.24*25* This library is distributed in the hope that it will be useful,26* but WITHOUT ANY WARRANTY; without even the implied warranty of27* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU28* Lesser General Public License for more details.29*30* You should have received a copy of the GNU Lesser General Public31* License along with this library; if not, write to the Free Software32* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA33*/34353637/*38* Version: 1.1.439* Build: 201010072140*/41424344//---- qrconst.php -----------------------------454647484950/*51* PHP QR Code encoder52*53* Common constants54*55* Based on libqrencode C library distributed under LGPL 2.156* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>57*58* PHP QR Code is distributed under LGPL 359* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>60*61* This library is free software; you can redistribute it and/or62* modify it under the terms of the GNU Lesser General Public63* License as published by the Free Software Foundation; either64* version 3 of the License, or any later version.65*66* This library is distributed in the hope that it will be useful,67* but WITHOUT ANY WARRANTY; without even the implied warranty of68* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU69* Lesser General Public License for more details.70*71* You should have received a copy of the GNU Lesser General Public72* License along with this library; if not, write to the Free Software73* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA74*/7576// Encoding modes7778define('QR_MODE_NUL', -1);79define('QR_MODE_NUM', 0);80define('QR_MODE_AN', 1);81define('QR_MODE_8', 2);82define('QR_MODE_KANJI', 3);83define('QR_MODE_STRUCTURE', 4);8485// Levels of error correction.8687define('QR_ECLEVEL_L', 0);88define('QR_ECLEVEL_M', 1);89define('QR_ECLEVEL_Q', 2);90define('QR_ECLEVEL_H', 3);9192// Supported output formats9394define('QR_FORMAT_TEXT', 0);95define('QR_FORMAT_PNG', 1);9697class qrstr {98public static function set(&$srctab, $x, $y, $repl, $replLen = false) {99$srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl));100}101}102103104105//---- merged_config.php -----------------------------106107108109110/*111* PHP QR Code encoder112*113* Config file, tuned-up for merged verion114*/115116define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there117define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true118define('QR_LOG_DIR', false); // default error logs dir119120define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code121define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly122define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false123124define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images125126127128129//---- qrtools.php -----------------------------130131132133134/*135* PHP QR Code encoder136*137* Toolset, handy and debug utilites.138*139* PHP QR Code is distributed under LGPL 3140* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>141*142* This library is free software; you can redistribute it and/or143* modify it under the terms of the GNU Lesser General Public144* License as published by the Free Software Foundation; either145* version 3 of the License, or any later version.146*147* This library is distributed in the hope that it will be useful,148* but WITHOUT ANY WARRANTY; without even the implied warranty of149* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU150* Lesser General Public License for more details.151*152* You should have received a copy of the GNU Lesser General Public153* License along with this library; if not, write to the Free Software154* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA155*/156157class QRtools {158159//----------------------------------------------------------------------160public static function binarize($frame)161{162$len = count($frame);163foreach ($frame as &$frameLine) {164165for($i=0; $i<$len; $i++) {166$frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0';167}168}169170return $frame;171}172173//----------------------------------------------------------------------174public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037')175{176$barcode_array = array();177178if (!is_array($mode))179$mode = explode(',', $mode);180181$eccLevel = 'L';182183if (count($mode) > 1) {184$eccLevel = $mode[1];185}186187$qrTab = QRcode::text($code, false, $eccLevel);188$size = count($qrTab);189190$barcode_array['num_rows'] = $size;191$barcode_array['num_cols'] = $size;192$barcode_array['bcode'] = array();193194foreach ($qrTab as $line) {195$arrAdd = array();196foreach(str_split($line) as $char)197$arrAdd[] = ($char=='1')?1:0;198$barcode_array['bcode'][] = $arrAdd;199}200201return $barcode_array;202}203204//----------------------------------------------------------------------205public static function clearCache()206{207self::$frames = array();208}209210//----------------------------------------------------------------------211public static function buildCache()212{213QRtools::markTime('before_build_cache');214215$mask = new QRmask();216for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) {217$frame = QRspec::newFrame($a);218if (QR_IMAGE) {219$fileName = QR_CACHE_DIR.'frame_'.$a.'.png';220QRimage::png(self::binarize($frame), $fileName, 1, 0);221}222223$width = count($frame);224$bitMask = array_fill(0, $width, array_fill(0, $width, 0));225for ($maskNo=0; $maskNo<8; $maskNo++)226$mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true);227}228229QRtools::markTime('after_build_cache');230}231232//----------------------------------------------------------------------233public static function log($outfile, $err)234{235if (QR_LOG_DIR !== false) {236if ($err != '') {237if ($outfile !== false) {238file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);239} else {240file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);241}242}243}244}245246//----------------------------------------------------------------------247public static function dumpMask($frame)248{249$width = count($frame);250for($y=0;$y<$width;$y++) {251for($x=0;$x<$width;$x++) {252echo ord($frame[$y][$x]).',';253}254}255}256257//----------------------------------------------------------------------258public static function markTime($markerId)259{260list($usec, $sec) = explode(" ", microtime());261$time = ((float)$usec + (float)$sec);262263if (!isset($GLOBALS['qr_time_bench']))264$GLOBALS['qr_time_bench'] = array();265266$GLOBALS['qr_time_bench'][$markerId] = $time;267}268269//----------------------------------------------------------------------270public static function timeBenchmark()271{272self::markTime('finish');273274$lastTime = 0;275$startTime = 0;276$p = 0;277278echo '<table cellpadding="3" cellspacing="1">279<thead><tr style="border-bottom:1px solid silver"><td colspan="2" style="text-align:center">BENCHMARK</td></tr></thead>280<tbody>';281282foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) {283if ($p > 0) {284echo '<tr><th style="text-align:right">till '.$markerId.': </th><td>'.number_format($thisTime-$lastTime, 6).'s</td></tr>';285} else {286$startTime = $thisTime;287}288289$p++;290$lastTime = $thisTime;291}292293echo '</tbody><tfoot>294<tr style="border-top:2px solid black"><th style="text-align:right">TOTAL: </th><td>'.number_format($lastTime-$startTime, 6).'s</td></tr>295</tfoot>296</table>';297}298299}300301//##########################################################################302303QRtools::markTime('start');304305306307308//---- qrspec.php -----------------------------309310311312313/*314* PHP QR Code encoder315*316* QR Code specifications317*318* Based on libqrencode C library distributed under LGPL 2.1319* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>320*321* PHP QR Code is distributed under LGPL 3322* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>323*324* The following data / specifications are taken from325* "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)326* or327* "Automatic identification and data capture techniques --328* QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)329*330* This library is free software; you can redistribute it and/or331* modify it under the terms of the GNU Lesser General Public332* License as published by the Free Software Foundation; either333* version 3 of the License, or any later version.334*335* This library is distributed in the hope that it will be useful,336* but WITHOUT ANY WARRANTY; without even the implied warranty of337* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU338* Lesser General Public License for more details.339*340* You should have received a copy of the GNU Lesser General Public341* License along with this library; if not, write to the Free Software342* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA343*/344345define('QRSPEC_VERSION_MAX', 40);346define('QRSPEC_WIDTH_MAX', 177);347348define('QRCAP_WIDTH', 0);349define('QRCAP_WORDS', 1);350define('QRCAP_REMINDER', 2);351define('QRCAP_EC', 3);352353class QRspec {354355public static $capacity = array(356array( 0, 0, 0, array( 0, 0, 0, 0)),357array( 21, 26, 0, array( 7, 10, 13, 17)), // 1358array( 25, 44, 7, array( 10, 16, 22, 28)),359array( 29, 70, 7, array( 15, 26, 36, 44)),360array( 33, 100, 7, array( 20, 36, 52, 64)),361array( 37, 134, 7, array( 26, 48, 72, 88)), // 5362array( 41, 172, 7, array( 36, 64, 96, 112)),363array( 45, 196, 0, array( 40, 72, 108, 130)),364array( 49, 242, 0, array( 48, 88, 132, 156)),365array( 53, 292, 0, array( 60, 110, 160, 192)),366array( 57, 346, 0, array( 72, 130, 192, 224)), //10367array( 61, 404, 0, array( 80, 150, 224, 264)),368array( 65, 466, 0, array( 96, 176, 260, 308)),369array( 69, 532, 0, array( 104, 198, 288, 352)),370array( 73, 581, 3, array( 120, 216, 320, 384)),371array( 77, 655, 3, array( 132, 240, 360, 432)), //15372array( 81, 733, 3, array( 144, 280, 408, 480)),373array( 85, 815, 3, array( 168, 308, 448, 532)),374array( 89, 901, 3, array( 180, 338, 504, 588)),375array( 93, 991, 3, array( 196, 364, 546, 650)),376array( 97, 1085, 3, array( 224, 416, 600, 700)), //20377array(101, 1156, 4, array( 224, 442, 644, 750)),378array(105, 1258, 4, array( 252, 476, 690, 816)),379array(109, 1364, 4, array( 270, 504, 750, 900)),380array(113, 1474, 4, array( 300, 560, 810, 960)),381array(117, 1588, 4, array( 312, 588, 870, 1050)), //25382array(121, 1706, 4, array( 336, 644, 952, 1110)),383array(125, 1828, 4, array( 360, 700, 1020, 1200)),384array(129, 1921, 3, array( 390, 728, 1050, 1260)),385array(133, 2051, 3, array( 420, 784, 1140, 1350)),386array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30387array(141, 2323, 3, array( 480, 868, 1290, 1530)),388array(145, 2465, 3, array( 510, 924, 1350, 1620)),389array(149, 2611, 3, array( 540, 980, 1440, 1710)),390array(153, 2761, 3, array( 570, 1036, 1530, 1800)),391array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35392array(161, 3034, 0, array( 600, 1120, 1680, 1980)),393array(165, 3196, 0, array( 630, 1204, 1770, 2100)),394array(169, 3362, 0, array( 660, 1260, 1860, 2220)),395array(173, 3532, 0, array( 720, 1316, 1950, 2310)),396array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40397);398399//----------------------------------------------------------------------400public static function getDataLength($version, $level)401{402return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level];403}404405//----------------------------------------------------------------------406public static function getECCLength($version, $level)407{408return self::$capacity[$version][QRCAP_EC][$level];409}410411//----------------------------------------------------------------------412public static function getWidth($version)413{414return self::$capacity[$version][QRCAP_WIDTH];415}416417//----------------------------------------------------------------------418public static function getRemainder($version)419{420return self::$capacity[$version][QRCAP_REMINDER];421}422423//----------------------------------------------------------------------424public static function getMinimumVersion($size, $level)425{426427for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) {428$words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level];429if($words >= $size)430return $i;431}432433return -1;434}435436//######################################################################437438public static $lengthTableBits = array(439array(10, 12, 14),440array( 9, 11, 13),441array( 8, 16, 16),442array( 8, 10, 12)443);444445//----------------------------------------------------------------------446public static function lengthIndicator($mode, $version)447{448if ($mode == QR_MODE_STRUCTURE)449return 0;450451if ($version <= 9) {452$l = 0;453} else if ($version <= 26) {454$l = 1;455} else {456$l = 2;457}458459return self::$lengthTableBits[$mode][$l];460}461462//----------------------------------------------------------------------463public static function maximumWords($mode, $version)464{465if($mode == QR_MODE_STRUCTURE)466return 3;467468if($version <= 9) {469$l = 0;470} else if($version <= 26) {471$l = 1;472} else {473$l = 2;474}475476$bits = self::$lengthTableBits[$mode][$l];477$words = (1 << $bits) - 1;478479if($mode == QR_MODE_KANJI) {480$words *= 2; // the number of bytes is required481}482483return $words;484}485486// Error correction code -----------------------------------------------487// Table of the error correction code (Reed-Solomon block)488// See Table 12-16 (pp.30-36), JIS X0510:2004.489490public static $eccTable = array(491array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)),492array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1493array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)),494array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)),495array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)),496array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5497array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)),498array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)),499array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)),500array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)),501array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10502array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)),503array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)),504array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)),505array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)),506array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15507array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)),508array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)),509array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)),510array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)),511array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20512array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)),513array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)),514array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)),515array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)),516array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25517array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)),518array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)),519array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)),520array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)),521array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30522array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)),523array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)),524array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)),525array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)),526array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35527array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)),528array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)),529array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)),530array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)),531array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40532);533534//----------------------------------------------------------------------535// CACHEABLE!!!536537public static function getEccSpec($version, $level, array &$spec)538{539if (count($spec) < 5) {540$spec = array(0,0,0,0,0);541}542543$b1 = self::$eccTable[$version][$level][0];544$b2 = self::$eccTable[$version][$level][1];545$data = self::getDataLength($version, $level);546$ecc = self::getECCLength($version, $level);547548if($b2 == 0) {549$spec[0] = $b1;550$spec[1] = (int)($data / $b1);551$spec[2] = (int)($ecc / $b1);552$spec[3] = 0;553$spec[4] = 0;554} else {555$spec[0] = $b1;556$spec[1] = (int)($data / ($b1 + $b2));557$spec[2] = (int)($ecc / ($b1 + $b2));558$spec[3] = $b2;559$spec[4] = $spec[1] + 1;560}561}562563// Alignment pattern ---------------------------------------------------564565// Positions of alignment patterns.566// This array includes only the second and the third position of the567// alignment patterns. Rest of them can be calculated from the distance568// between them.569570// See Table 1 in Appendix E (pp.71) of JIS X0510:2004.571572public static $alignmentPattern = array(573array( 0, 0),574array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5575array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10576array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15577array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20578array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25579array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30580array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35581array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40582);583584585/** --------------------------------------------------------------------586* Put an alignment marker.587* @param frame588* @param width589* @param ox,oy center coordinate of the pattern590*/591public static function putAlignmentMarker(array &$frame, $ox, $oy)592{593$finder = array(594"\xa1\xa1\xa1\xa1\xa1",595"\xa1\xa0\xa0\xa0\xa1",596"\xa1\xa0\xa1\xa0\xa1",597"\xa1\xa0\xa0\xa0\xa1",598"\xa1\xa1\xa1\xa1\xa1"599);600601$yStart = $oy-2;602$xStart = $ox-2;603604for($y=0; $y<5; $y++) {605QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]);606}607}608609//----------------------------------------------------------------------610public static function putAlignmentPattern($version, &$frame, $width)611{612if($version < 2)613return;614615$d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0];616if($d < 0) {617$w = 2;618} else {619$w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2);620}621622if($w * $w - 3 == 1) {623$x = self::$alignmentPattern[$version][0];624$y = self::$alignmentPattern[$version][0];625self::putAlignmentMarker($frame, $x, $y);626return;627}628629$cx = self::$alignmentPattern[$version][0];630for($x=1; $x<$w - 1; $x++) {631self::putAlignmentMarker($frame, 6, $cx);632self::putAlignmentMarker($frame, $cx, 6);633$cx += $d;634}635636$cy = self::$alignmentPattern[$version][0];637for($y=0; $y<$w-1; $y++) {638$cx = self::$alignmentPattern[$version][0];639for($x=0; $x<$w-1; $x++) {640self::putAlignmentMarker($frame, $cx, $cy);641$cx += $d;642}643$cy += $d;644}645}646647// Version information pattern -----------------------------------------648649// Version information pattern (BCH coded).650// See Table 1 in Appendix D (pp.68) of JIS X0510:2004.651652// size: [QRSPEC_VERSION_MAX - 6]653654public static $versionPattern = array(6550x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d,6560x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9,6570x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75,6580x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64,6590x27541, 0x28c69660);661662//----------------------------------------------------------------------663public static function getVersionPattern($version)664{665if($version < 7 || $version > QRSPEC_VERSION_MAX)666return 0;667668return self::$versionPattern[$version -7];669}670671// Format information --------------------------------------------------672// See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib)673674public static $formatInfo = array(675array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976),676array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0),677array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed),678array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b)679);680681public static function getFormatInfo($mask, $level)682{683if($mask < 0 || $mask > 7)684return 0;685686if($level < 0 || $level > 3)687return 0;688689return self::$formatInfo[$level][$mask];690}691692// Frame ---------------------------------------------------------------693// Cache of initial frames.694695public static $frames = array();696697/** --------------------------------------------------------------------698* Put a finder pattern.699* @param frame700* @param width701* @param ox,oy upper-left coordinate of the pattern702*/703public static function putFinderPattern(&$frame, $ox, $oy)704{705$finder = array(706"\xc1\xc1\xc1\xc1\xc1\xc1\xc1",707"\xc1\xc0\xc0\xc0\xc0\xc0\xc1",708"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",709"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",710"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",711"\xc1\xc0\xc0\xc0\xc0\xc0\xc1",712"\xc1\xc1\xc1\xc1\xc1\xc1\xc1"713);714715for($y=0; $y<7; $y++) {716QRstr::set($frame, $ox, $oy+$y, $finder[$y]);717}718}719720//----------------------------------------------------------------------721public static function createFrame($version)722{723$width = self::$capacity[$version][QRCAP_WIDTH];724$frameLine = str_repeat ("\0", $width);725$frame = array_fill(0, $width, $frameLine);726727// Finder pattern728self::putFinderPattern($frame, 0, 0);729self::putFinderPattern($frame, $width - 7, 0);730self::putFinderPattern($frame, 0, $width - 7);731732// Separator733$yOffset = $width - 7;734735for($y=0; $y<7; $y++) {736$frame[$y][7] = "\xc0";737$frame[$y][$width - 8] = "\xc0";738$frame[$yOffset][7] = "\xc0";739$yOffset++;740}741742$setPattern = str_repeat("\xc0", 8);743744QRstr::set($frame, 0, 7, $setPattern);745QRstr::set($frame, $width-8, 7, $setPattern);746QRstr::set($frame, 0, $width - 8, $setPattern);747748// Format info749$setPattern = str_repeat("\x84", 9);750QRstr::set($frame, 0, 8, $setPattern);751QRstr::set($frame, $width - 8, 8, $setPattern, 8);752753$yOffset = $width - 8;754755for($y=0; $y<8; $y++,$yOffset++) {756$frame[$y][8] = "\x84";757$frame[$yOffset][8] = "\x84";758}759760// Timing pattern761762for($i=1; $i<$width-15; $i++) {763$frame[6][7+$i] = chr(0x90 | ($i & 1));764$frame[7+$i][6] = chr(0x90 | ($i & 1));765}766767// Alignment pattern768self::putAlignmentPattern($version, $frame, $width);769770// Version information771if($version >= 7) {772$vinf = self::getVersionPattern($version);773774$v = $vinf;775776for($x=0; $x<6; $x++) {777for($y=0; $y<3; $y++) {778$frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1));779$v = $v >> 1;780}781}782783$v = $vinf;784for($y=0; $y<6; $y++) {785for($x=0; $x<3; $x++) {786$frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1));787$v = $v >> 1;788}789}790}791792// and a little bit...793$frame[$width - 8][8] = "\x81";794795return $frame;796}797798//----------------------------------------------------------------------799public static function debug($frame, $binary_mode = false)800{801if ($binary_mode) {802803foreach ($frame as &$frameLine) {804$frameLine = join('<span class="m"> </span>', explode('0', $frameLine));805$frameLine = join('██', explode('1', $frameLine));806}807808?>809<style>810.m { background-color: white; }811</style>812<?php813echo '<pre><tt><br/ ><br/ ><br/ > ';814echo join("<br/ > ", $frame);815echo '</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >';816817} else {818819foreach ($frame as &$frameLine) {820$frameLine = join('<span class="m"> </span>', explode("\xc0", $frameLine));821$frameLine = join('<span class="m">▒</span>', explode("\xc1", $frameLine));822$frameLine = join('<span class="p"> </span>', explode("\xa0", $frameLine));823$frameLine = join('<span class="p">▒</span>', explode("\xa1", $frameLine));824$frameLine = join('<span class="s">◇</span>', explode("\x84", $frameLine)); //format 0825$frameLine = join('<span class="s">◆</span>', explode("\x85", $frameLine)); //format 1826$frameLine = join('<span class="x">☢</span>', explode("\x81", $frameLine)); //special bit827$frameLine = join('<span class="c"> </span>', explode("\x90", $frameLine)); //clock 0828$frameLine = join('<span class="c">◷</span>', explode("\x91", $frameLine)); //clock 1829$frameLine = join('<span class="f"> </span>', explode("\x88", $frameLine)); //version830$frameLine = join('<span class="f">▒</span>', explode("\x89", $frameLine)); //version831$frameLine = join('♦', explode("\x01", $frameLine));832$frameLine = join('⋅', explode("\0", $frameLine));833}834835?>836<style>837.p { background-color: yellow; }838.m { background-color: #00FF00; }839.s { background-color: #FF0000; }840.c { background-color: aqua; }841.x { background-color: pink; }842.f { background-color: gold; }843</style>844<?php845echo "<pre><tt>";846echo join("<br/ >", $frame);847echo "</tt></pre>";848849}850}851852//----------------------------------------------------------------------853public static function serial($frame)854{855return gzcompress(join("\n", $frame), 9);856}857858//----------------------------------------------------------------------859public static function unserial($code)860{861return explode("\n", gzuncompress($code));862}863864//----------------------------------------------------------------------865public static function newFrame($version)866{867if($version < 1 || $version > QRSPEC_VERSION_MAX)868return null;869870if(!isset(self::$frames[$version])) {871872$fileName = QR_CACHE_DIR.'frame_'.$version.'.dat';873874if (QR_CACHEABLE) {875if (file_exists($fileName)) {876self::$frames[$version] = self::unserial(file_get_contents($fileName));877} else {878self::$frames[$version] = self::createFrame($version);879file_put_contents($fileName, self::serial(self::$frames[$version]));880}881} else {882self::$frames[$version] = self::createFrame($version);883}884}885886if(is_null(self::$frames[$version]))887return null;888889return self::$frames[$version];890}891892//----------------------------------------------------------------------893public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; }894public static function rsBlockNum1($spec) { return $spec[0]; }895public static function rsDataCodes1($spec) { return $spec[1]; }896public static function rsEccCodes1($spec) { return $spec[2]; }897public static function rsBlockNum2($spec) { return $spec[3]; }898public static function rsDataCodes2($spec) { return $spec[4]; }899public static function rsEccCodes2($spec) { return $spec[2]; }900public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); }901public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; }902903}904905906907//---- qrimage.php -----------------------------908909910911912/*913* PHP QR Code encoder914*915* Image output of code using GD2916*917* PHP QR Code is distributed under LGPL 3918* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>919*920* This library is free software; you can redistribute it and/or921* modify it under the terms of the GNU Lesser General Public922* License as published by the Free Software Foundation; either923* version 3 of the License, or any later version.924*925* This library is distributed in the hope that it will be useful,926* but WITHOUT ANY WARRANTY; without even the implied warranty of927* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU928* Lesser General Public License for more details.929*930* You should have received a copy of the GNU Lesser General Public931* License along with this library; if not, write to the Free Software932* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA933*/934935define('QR_IMAGE', true);936937class QRimage {938939//----------------------------------------------------------------------940public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE)941{942$image = self::image($frame, $pixelPerPoint, $outerFrame);943944if ($filename === false) {945Header("Content-type: image/png");946ImagePng($image);947} else {948if($saveandprint===TRUE){949ImagePng($image, $filename);950header("Content-type: image/png");951ImagePng($image);952}else{953ImagePng($image, $filename);954}955}956957ImageDestroy($image);958}959960//----------------------------------------------------------------------961public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85)962{963$image = self::image($frame, $pixelPerPoint, $outerFrame);964965if ($filename === false) {966Header("Content-type: image/jpeg");967ImageJpeg($image, null, $q);968} else {969ImageJpeg($image, $filename, $q);970}971972ImageDestroy($image);973}974975//----------------------------------------------------------------------976private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4)977{978$h = count($frame);979$w = strlen($frame[0]);980981$imgW = $w + 2*$outerFrame;982$imgH = $h + 2*$outerFrame;983984$base_image =ImageCreate($imgW, $imgH);985986$col[0] = ImageColorAllocate($base_image,255,255,255);987$col[1] = ImageColorAllocate($base_image,0,0,0);988989imagefill($base_image, 0, 0, $col[0]);990991for($y=0; $y<$h; $y++) {992for($x=0; $x<$w; $x++) {993if ($frame[$y][$x] == '1') {994ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]);995}996}997}998999$target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint);1000ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH);1001ImageDestroy($base_image);10021003return $target_image;1004}1005}1006100710081009//---- qrinput.php -----------------------------10101011101210131014/*1015* PHP QR Code encoder1016*1017* Input encoding class1018*1019* Based on libqrencode C library distributed under LGPL 2.11020* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>1021*1022* PHP QR Code is distributed under LGPL 31023* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>1024*1025* This library is free software; you can redistribute it and/or1026* modify it under the terms of the GNU Lesser General Public1027* License as published by the Free Software Foundation; either1028* version 3 of the License, or any later version.1029*1030* This library is distributed in the hope that it will be useful,1031* but WITHOUT ANY WARRANTY; without even the implied warranty of1032* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU1033* Lesser General Public License for more details.1034*1035* You should have received a copy of the GNU Lesser General Public1036* License along with this library; if not, write to the Free Software1037* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA1038*/10391040define('STRUCTURE_HEADER_BITS', 20);1041define('MAX_STRUCTURED_SYMBOLS', 16);10421043class QRinputItem {10441045public $mode;1046public $size;1047public $data;1048public $bstream;10491050public function __construct($mode, $size, $data, $bstream = null)1051{1052$setData = array_slice($data, 0, $size);10531054if (count($setData) < $size) {1055$setData = array_merge($setData, array_fill(0,$size-count($setData),0));1056}10571058if(!QRinput::check($mode, $size, $setData)) {1059throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData));1060return null;1061}10621063$this->mode = $mode;1064$this->size = $size;1065$this->data = $setData;1066$this->bstream = $bstream;1067}10681069//----------------------------------------------------------------------1070public function encodeModeNum($version)1071{1072try {10731074$words = (int)($this->size / 3);1075$bs = new QRbitstream();10761077$val = 0x1;1078$bs->appendNum(4, $val);1079$bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size);10801081for($i=0; $i<$words; $i++) {1082$val = (ord($this->data[$i*3 ]) - ord('0')) * 100;1083$val += (ord($this->data[$i*3+1]) - ord('0')) * 10;1084$val += (ord($this->data[$i*3+2]) - ord('0'));1085$bs->appendNum(10, $val);1086}10871088if($this->size - $words * 3 == 1) {1089$val = ord($this->data[$words*3]) - ord('0');1090$bs->appendNum(4, $val);1091} else if($this->size - $words * 3 == 2) {1092$val = (ord($this->data[$words*3 ]) - ord('0')) * 10;1093$val += (ord($this->data[$words*3+1]) - ord('0'));1094$bs->appendNum(7, $val);1095}10961097$this->bstream = $bs;1098return 0;10991100} catch (Exception $e) {1101return -1;1102}1103}11041105//----------------------------------------------------------------------1106public function encodeModeAn($version)1107{1108try {1109$words = (int)($this->size / 2);1110$bs = new QRbitstream();11111112$bs->appendNum(4, 0x02);1113$bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size);11141115for($i=0; $i<$words; $i++) {1116$val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45;1117$val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1]));11181119$bs->appendNum(11, $val);1120}11211122if($this->size & 1) {1123$val = QRinput::lookAnTable(ord($this->data[$words * 2]));1124$bs->appendNum(6, $val);1125}11261127$this->bstream = $bs;1128return 0;11291130} catch (Exception $e) {1131return -1;1132}1133}11341135//----------------------------------------------------------------------1136public function encodeMode8($version)1137{1138try {1139$bs = new QRbitstream();11401141$bs->appendNum(4, 0x4);1142$bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size);11431144for($i=0; $i<$this->size; $i++) {1145$bs->appendNum(8, ord($this->data[$i]));1146}11471148$this->bstream = $bs;1149return 0;11501151} catch (Exception $e) {1152return -1;1153}1154}11551156//----------------------------------------------------------------------1157public function encodeModeKanji($version)1158{1159try {11601161$bs = new QRbitrtream();11621163$bs->appendNum(4, 0x8);1164$bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2));11651166for($i=0; $i<$this->size; $i+=2) {1167$val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]);1168if($val <= 0x9ffc) {1169$val -= 0x8140;1170} else {1171$val -= 0xc140;1172}11731174$h = ($val >> 8) * 0xc0;1175$val = ($val & 0xff) + $h;11761177$bs->appendNum(13, $val);1178}11791180$this->bstream = $bs;1181return 0;11821183} catch (Exception $e) {1184return -1;1185}1186}11871188//----------------------------------------------------------------------1189public function encodeModeStructure()1190{1191try {1192$bs = new QRbitstream();11931194$bs->appendNum(4, 0x03);1195$bs->appendNum(4, ord($this->data[1]) - 1);1196$bs->appendNum(4, ord($this->data[0]) - 1);1197$bs->appendNum(8, ord($this->data[2]));11981199$this->bstream = $bs;1200return 0;12011202} catch (Exception $e) {1203return -1;1204}1205}12061207//----------------------------------------------------------------------1208public function estimateBitStreamSizeOfEntry($version)1209{1210$bits = 0;12111212if($version == 0)1213$version = 1;12141215switch($this->mode) {1216case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break;1217case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break;1218case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break;1219case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break;1220case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS;1221default:1222return 0;1223}12241225$l = QRspec::lengthIndicator($this->mode, $version);1226$m = 1 << $l;1227$num = (int)(($this->size + $m - 1) / $m);12281229$bits += $num * (4 + $l);12301231return $bits;1232}12331234//----------------------------------------------------------------------1235public function encodeBitStream($version)1236{1237try {12381239unset($this->bstream);1240$words = QRspec::maximumWords($this->mode, $version);12411242if($this->size > $words) {12431244$st1 = new QRinputItem($this->mode, $words, $this->data);1245$st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words));12461247$st1->encodeBitStream($version);1248$st2->encodeBitStream($version);12491250$this->bstream = new QRbitstream();1251$this->bstream->append($st1->bstream);1252$this->bstream->append($st2->bstream);12531254unset($st1);1255unset($st2);12561257} else {12581259$ret = 0;12601261switch($this->mode) {1262case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break;1263case QR_MODE_AN: $ret = $this->encodeModeAn($version); break;1264case QR_MODE_8: $ret = $this->encodeMode8($version); break;1265case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break;1266case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break;12671268default:1269break;1270}12711272if($ret < 0)1273return -1;1274}12751276return $this->bstream->size();12771278} catch (Exception $e) {1279return -1;1280}1281}1282};12831284//##########################################################################12851286class QRinput {12871288public $items;12891290private $version;1291private $level;12921293//----------------------------------------------------------------------1294public function __construct($version = 0, $level = QR_ECLEVEL_L)1295{1296if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) {1297throw new Exception('Invalid version no');1298return NULL;1299}13001301$this->version = $version;1302$this->level = $level;1303}13041305//----------------------------------------------------------------------1306public function getVersion()1307{1308return $this->version;1309}13101311//----------------------------------------------------------------------1312public function setVersion($version)1313{1314if($version < 0 || $version > QRSPEC_VERSION_MAX) {1315throw new Exception('Invalid version no');1316return -1;1317}13181319$this->version = $version;13201321return 0;1322}13231324//----------------------------------------------------------------------1325public function getErrorCorrectionLevel()1326{1327return $this->level;1328}13291330//----------------------------------------------------------------------1331public function setErrorCorrectionLevel($level)1332{1333if($level > QR_ECLEVEL_H) {1334throw new Exception('Invalid ECLEVEL');1335return -1;1336}13371338$this->level = $level;13391340return 0;1341}13421343//----------------------------------------------------------------------1344public function appendEntry(QRinputItem $entry)1345{1346$this->items[] = $entry;1347}13481349//----------------------------------------------------------------------1350public function append($mode, $size, $data)1351{1352try {1353$entry = new QRinputItem($mode, $size, $data);1354$this->items[] = $entry;1355return 0;1356} catch (Exception $e) {1357return -1;1358}1359}13601361//----------------------------------------------------------------------13621363public function insertStructuredAppendHeader($size, $index, $parity)1364{1365if( $size > MAX_STRUCTURED_SYMBOLS ) {1366throw new Exception('insertStructuredAppendHeader wrong size');1367}13681369if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) {1370throw new Exception('insertStructuredAppendHeader wrong index');1371}13721373$buf = array($size, $index, $parity);13741375try {1376$entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf);1377array_unshift($this->items, $entry);1378return 0;1379} catch (Exception $e) {1380return -1;1381}1382}13831384//----------------------------------------------------------------------1385public function calcParity()1386{1387$parity = 0;13881389foreach($this->items as $item) {1390if($item->mode != QR_MODE_STRUCTURE) {1391for($i=$item->size-1; $i>=0; $i--) {1392$parity ^= $item->data[$i];1393}1394}1395}13961397return $parity;1398}13991400//----------------------------------------------------------------------1401public static function checkModeNum($size, $data)1402{1403for($i=0; $i<$size; $i++) {1404if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){1405return false;1406}1407}14081409return true;1410}14111412//----------------------------------------------------------------------1413public static function estimateBitsModeNum($size)1414{1415$w = (int)$size / 3;1416$bits = $w * 10;14171418switch($size - $w * 3) {1419case 1:1420$bits += 4;1421break;1422case 2:1423$bits += 7;1424break;1425default:1426break;1427}14281429return $bits;1430}14311432//----------------------------------------------------------------------1433public static $anTable = array(1434-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,1435-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,143636, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,14370, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1,1438-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,143925, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,1440-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,1441-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -11442);14431444//----------------------------------------------------------------------1445public static function lookAnTable($c)1446{1447return (($c > 127)?-1:self::$anTable[$c]);1448}14491450//----------------------------------------------------------------------1451public static function checkModeAn($size, $data)1452{1453for($i=0; $i<$size; $i++) {1454if (self::lookAnTable(ord($data[$i])) == -1) {1455return false;1456}1457}14581459return true;1460}14611462//----------------------------------------------------------------------1463public static function estimateBitsModeAn($size)1464{1465$w = (int)($size / 2);1466$bits = $w * 11;14671468if($size & 1) {1469$bits += 6;1470}14711472return $bits;1473}14741475//----------------------------------------------------------------------1476public static function estimateBitsMode8($size)1477{1478return $size * 8;1479}14801481//----------------------------------------------------------------------1482public function estimateBitsModeKanji($size)1483{1484return (int)(($size / 2) * 13);1485}14861487//----------------------------------------------------------------------1488public static function checkModeKanji($size, $data)1489{1490if($size & 1)1491return false;14921493for($i=0; $i<$size; $i+=2) {1494$val = (ord($data[$i]) << 8) | ord($data[$i+1]);1495if( $val < 0x81401496|| ($val > 0x9ffc && $val < 0xe040)1497|| $val > 0xebbf) {1498return false;1499}1500}15011502return true;1503}15041505/***********************************************************************1506* Validation1507**********************************************************************/15081509public static function check($mode, $size, $data)1510{1511if($size <= 0)1512return false;15131514switch($mode) {1515case QR_MODE_NUM: return self::checkModeNum($size, $data); break;1516case QR_MODE_AN: return self::checkModeAn($size, $data); break;1517case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break;1518case QR_MODE_8: return true; break;1519case QR_MODE_STRUCTURE: return true; break;15201521default:1522break;1523}15241525return false;1526}152715281529//----------------------------------------------------------------------1530public function estimateBitStreamSize($version)1531{1532$bits = 0;15331534foreach($this->items as $item) {1535$bits += $item->estimateBitStreamSizeOfEntry($version);1536}15371538return $bits;1539}15401541//----------------------------------------------------------------------1542public function estimateVersion()1543{1544$version = 0;1545$prev = 0;1546do {1547$prev = $version;1548$bits = $this->estimateBitStreamSize($prev);1549$version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);1550if ($version < 0) {1551return -1;1552}1553} while ($version > $prev);15541555return $version;1556}15571558//----------------------------------------------------------------------1559public static function lengthOfCode($mode, $version, $bits)1560{1561$payload = $bits - 4 - QRspec::lengthIndicator($mode, $version);1562switch($mode) {1563case QR_MODE_NUM:1564$chunks = (int)($payload / 10);1565$remain = $payload - $chunks * 10;1566$size = $chunks * 3;1567if($remain >= 7) {1568$size += 2;1569} else if($remain >= 4) {1570$size += 1;1571}1572break;1573case QR_MODE_AN:1574$chunks = (int)($payload / 11);1575$remain = $payload - $chunks * 11;1576$size = $chunks * 2;1577if($remain >= 6)1578$size++;1579break;1580case QR_MODE_8:1581$size = (int)($payload / 8);1582break;1583case QR_MODE_KANJI:1584$size = (int)(($payload / 13) * 2);1585break;1586case QR_MODE_STRUCTURE:1587$size = (int)($payload / 8);1588break;1589default:1590$size = 0;1591break;1592}15931594$maxsize = QRspec::maximumWords($mode, $version);1595if($size < 0) $size = 0;1596if($size > $maxsize) $size = $maxsize;15971598return $size;1599}16001601//----------------------------------------------------------------------1602public function createBitStream()1603{1604$total = 0;16051606foreach($this->items as $item) {1607$bits = $item->encodeBitStream($this->version);16081609if($bits < 0)1610return -1;16111612$total += $bits;1613}16141615return $total;1616}16171618//----------------------------------------------------------------------1619public function convertData()1620{1621$ver = $this->estimateVersion();1622if($ver > $this->getVersion()) {1623$this->setVersion($ver);1624}16251626for(;;) {1627$bits = $this->createBitStream();16281629if($bits < 0)1630return -1;16311632$ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);1633if($ver < 0) {1634throw new Exception('WRONG VERSION');1635return -1;1636} else if($ver > $this->getVersion()) {1637$this->setVersion($ver);1638} else {1639break;1640}1641}16421643return 0;1644}16451646//----------------------------------------------------------------------1647public function appendPaddingBit(&$bstream)1648{1649$bits = $bstream->size();1650$maxwords = QRspec::getDataLength($this->version, $this->level);1651$maxbits = $maxwords * 8;16521653if ($maxbits == $bits) {1654return 0;1655}16561657if ($maxbits - $bits < 5) {1658return $bstream->appendNum($maxbits - $bits, 0);1659}16601661$bits += 4;1662$words = (int)(($bits + 7) / 8);16631664$padding = new QRbitstream();1665$ret = $padding->appendNum($words * 8 - $bits + 4, 0);16661667if($ret < 0)1668return $ret;16691670$padlen = $maxwords - $words;16711672if($padlen > 0) {16731674$padbuf = array();1675for($i=0; $i<$padlen; $i++) {1676$padbuf[$i] = ($i&1)?0x11:0xec;1677}16781679$ret = $padding->appendBytes($padlen, $padbuf);16801681if($ret < 0)1682return $ret;16831684}16851686$ret = $bstream->append($padding);16871688return $ret;1689}16901691//----------------------------------------------------------------------1692public function mergeBitStream()1693{1694if($this->convertData() < 0) {1695return null;1696}16971698$bstream = new QRbitstream();16991700foreach($this->items as $item) {1701$ret = $bstream->append($item->bstream);1702if($ret < 0) {1703return null;1704}1705}17061707return $bstream;1708}17091710//----------------------------------------------------------------------1711public function getBitStream()1712{17131714$bstream = $this->mergeBitStream();17151716if($bstream == null) {1717return null;1718}17191720$ret = $this->appendPaddingBit($bstream);1721if($ret < 0) {1722return null;1723}17241725return $bstream;1726}17271728//----------------------------------------------------------------------1729public function getByteStream()1730{1731$bstream = $this->getBitStream();1732if($bstream == null) {1733return null;1734}17351736return $bstream->toByte();1737}1738}1739174017411742174317441745//---- qrbitstream.php -----------------------------17461747174817491750/*1751* PHP QR Code encoder1752*1753* Bitstream class1754*1755* Based on libqrencode C library distributed under LGPL 2.11756* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>1757*1758* PHP QR Code is distributed under LGPL 31759* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>1760*1761* This library is free software; you can redistribute it and/or1762* modify it under the terms of the GNU Lesser General Public1763* License as published by the Free Software Foundation; either1764* version 3 of the License, or any later version.1765*1766* This library is distributed in the hope that it will be useful,1767* but WITHOUT ANY WARRANTY; without even the implied warranty of1768* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU1769* Lesser General Public License for more details.1770*1771* You should have received a copy of the GNU Lesser General Public1772* License along with this library; if not, write to the Free Software1773* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA1774*/17751776class QRbitstream {17771778public $data = array();17791780//----------------------------------------------------------------------1781public function size()1782{1783return count($this->data);1784}17851786//----------------------------------------------------------------------1787public function allocate($setLength)1788{1789$this->data = array_fill(0, $setLength, 0);1790return 0;1791}17921793//----------------------------------------------------------------------1794public static function newFromNum($bits, $num)1795{1796$bstream = new QRbitstream();1797$bstream->allocate($bits);17981799$mask = 1 << ($bits - 1);1800for($i=0; $i<$bits; $i++) {1801if($num & $mask) {1802$bstream->data[$i] = 1;1803} else {1804$bstream->data[$i] = 0;1805}1806$mask = $mask >> 1;1807}18081809return $bstream;1810}18111812//----------------------------------------------------------------------1813public static function newFromBytes($size, $data)1814{1815$bstream = new QRbitstream();1816$bstream->allocate($size * 8);1817$p=0;18181819for($i=0; $i<$size; $i++) {1820$mask = 0x80;1821for($j=0; $j<8; $j++) {1822if($data[$i] & $mask) {1823$bstream->data[$p] = 1;1824} else {1825$bstream->data[$p] = 0;1826}1827$p++;1828$mask = $mask >> 1;1829}1830}18311832return $bstream;1833}18341835//----------------------------------------------------------------------1836public function append(QRbitstream $arg)1837{1838if (is_null($arg)) {1839return -1;1840}18411842if($arg->size() == 0) {1843return 0;1844}18451846if($this->size() == 0) {1847$this->data = $arg->data;1848return 0;1849}18501851$this->data = array_values(array_merge($this->data, $arg->data));18521853return 0;1854}18551856//----------------------------------------------------------------------1857public function appendNum($bits, $num)1858{1859if ($bits == 0)1860return 0;18611862$b = QRbitstream::newFromNum($bits, $num);18631864if(is_null($b))1865return -1;18661867$ret = $this->append($b);1868unset($b);18691870return $ret;1871}18721873//----------------------------------------------------------------------1874public function appendBytes($size, $data)1875{1876if ($size == 0)1877return 0;18781879$b = QRbitstream::newFromBytes($size, $data);18801881if(is_null($b))1882return -1;18831884$ret = $this->append($b);1885unset($b);18861887return $ret;1888}18891890//----------------------------------------------------------------------1891public function toByte()1892{18931894$size = $this->size();18951896if($size == 0) {1897return array();1898}18991900$data = array_fill(0, (int)(($size + 7) / 8), 0);1901$bytes = (int)($size / 8);19021903$p = 0;19041905for($i=0; $i<$bytes; $i++) {1906$v = 0;1907for($j=0; $j<8; $j++) {1908$v = $v << 1;1909$v |= $this->data[$p];1910$p++;1911}1912$data[$i] = $v;1913}19141915if($size & 7) {1916$v = 0;1917for($j=0; $j<($size & 7); $j++) {1918$v = $v << 1;1919$v |= $this->data[$p];1920$p++;1921}1922$data[$bytes] = $v;1923}19241925return $data;1926}19271928}19291930193119321933//---- qrsplit.php -----------------------------19341935193619371938/*1939* PHP QR Code encoder1940*1941* Input splitting classes1942*1943* Based on libqrencode C library distributed under LGPL 2.11944* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>1945*1946* PHP QR Code is distributed under LGPL 31947* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>1948*1949* The following data / specifications are taken from1950* "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)1951* or1952* "Automatic identification and data capture techniques --1953* QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)1954*1955* This library is free software; you can redistribute it and/or1956* modify it under the terms of the GNU Lesser General Public1957* License as published by the Free Software Foundation; either1958* version 3 of the License, or any later version.1959*1960* This library is distributed in the hope that it will be useful,1961* but WITHOUT ANY WARRANTY; without even the implied warranty of1962* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU1963* Lesser General Public License for more details.1964*1965* You should have received a copy of the GNU Lesser General Public1966* License along with this library; if not, write to the Free Software1967* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA1968*/1969class QRsplit {19701971public $dataStr = '';1972public $input;1973public $modeHint;19741975//----------------------------------------------------------------------1976public function __construct($dataStr, $input, $modeHint)1977{1978$this->dataStr = $dataStr;1979$this->input = $input;1980$this->modeHint = $modeHint;1981}19821983//----------------------------------------------------------------------1984public static function isdigitat($str, $pos)1985{1986if ($pos >= strlen($str))1987return false;19881989return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9')));1990}19911992//----------------------------------------------------------------------1993public static function isalnumat($str, $pos)1994{1995if ($pos >= strlen($str))1996return false;19971998return (QRinput::lookAnTable(ord($str[$pos])) >= 0);1999}20002001//----------------------------------------------------------------------2002public function identifyMode($pos)2003{2004if ($pos >= strlen($this->dataStr))2005return QR_MODE_NUL;20062007$c = $this->dataStr[$pos];20082009if(self::isdigitat($this->dataStr, $pos)) {2010return QR_MODE_NUM;2011} else if(self::isalnumat($this->dataStr, $pos)) {2012return QR_MODE_AN;2013} else if($this->modeHint == QR_MODE_KANJI) {20142015if ($pos+1 < strlen($this->dataStr))2016{2017$d = $this->dataStr[$pos+1];2018$word = (ord($c) << 8) | ord($d);2019if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) {2020return QR_MODE_KANJI;2021}2022}2023}20242025return QR_MODE_8;2026}20272028//----------------------------------------------------------------------2029public function eatNum()2030{2031$ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());20322033$p = 0;2034while(self::isdigitat($this->dataStr, $p)) {2035$p++;2036}20372038$run = $p;2039$mode = $this->identifyMode($p);20402041if($mode == QR_MODE_8) {2042$dif = QRinput::estimateBitsModeNum($run) + 4 + $ln2043+ QRinput::estimateBitsMode8(1) // + 4 + l82044- QRinput::estimateBitsMode8($run + 1); // - 4 - l82045if($dif > 0) {2046return $this->eat8();2047}2048}2049if($mode == QR_MODE_AN) {2050$dif = QRinput::estimateBitsModeNum($run) + 4 + $ln2051+ QRinput::estimateBitsModeAn(1) // + 4 + la2052- QRinput::estimateBitsModeAn($run + 1);// - 4 - la2053if($dif > 0) {2054return $this->eatAn();2055}2056}20572058$ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr));2059if($ret < 0)2060return -1;20612062return $run;2063}20642065//----------------------------------------------------------------------2066public function eatAn()2067{2068$la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());2069$ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());20702071$p = 0;20722073while(self::isalnumat($this->dataStr, $p)) {2074if(self::isdigitat($this->dataStr, $p)) {2075$q = $p;2076while(self::isdigitat($this->dataStr, $q)) {2077$q++;2078}20792080$dif = QRinput::estimateBitsModeAn($p) // + 4 + la2081+ QRinput::estimateBitsModeNum($q - $p) + 4 + $ln2082- QRinput::estimateBitsModeAn($q); // - 4 - la20832084if($dif < 0) {2085break;2086} else {2087$p = $q;2088}2089} else {2090$p++;2091}2092}20932094$run = $p;20952096if(!self::isalnumat($this->dataStr, $p)) {2097$dif = QRinput::estimateBitsModeAn($run) + 4 + $la2098+ QRinput::estimateBitsMode8(1) // + 4 + l82099- QRinput::estimateBitsMode8($run + 1); // - 4 - l82100if($dif > 0) {2101return $this->eat8();2102}2103}21042105$ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr));2106if($ret < 0)2107return -1;21082109return $run;2110}21112112//----------------------------------------------------------------------2113public function eatKanji()2114{2115$p = 0;21162117while($this->identifyMode($p) == QR_MODE_KANJI) {2118$p += 2;2119}21202121$ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr));2122if($ret < 0)2123return -1;21242125return $run;2126}21272128//----------------------------------------------------------------------2129public function eat8()2130{2131$la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());2132$ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());21332134$p = 1;2135$dataStrLen = strlen($this->dataStr);21362137while($p < $dataStrLen) {21382139$mode = $this->identifyMode($p);2140if($mode == QR_MODE_KANJI) {2141break;2142}2143if($mode == QR_MODE_NUM) {2144$q = $p;2145while(self::isdigitat($this->dataStr, $q)) {2146$q++;2147}2148$dif = QRinput::estimateBitsMode8($p) // + 4 + l82149+ QRinput::estimateBitsModeNum($q - $p) + 4 + $ln2150- QRinput::estimateBitsMode8($q); // - 4 - l82151if($dif < 0) {2152break;2153} else {2154$p = $q;2155}2156} else if($mode == QR_MODE_AN) {2157$q = $p;2158while(self::isalnumat($this->dataStr, $q)) {2159$q++;2160}2161$dif = QRinput::estimateBitsMode8($p) // + 4 + l82162+ QRinput::estimateBitsModeAn($q - $p) + 4 + $la2163- QRinput::estimateBitsMode8($q); // - 4 - l82164if($dif < 0) {2165break;2166} else {2167$p = $q;2168}2169} else {2170$p++;2171}2172}21732174$run = $p;2175$ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr));21762177if($ret < 0)2178return -1;21792180return $run;2181}21822183//----------------------------------------------------------------------2184public function splitString()2185{2186while (strlen($this->dataStr) > 0)2187{2188if($this->dataStr == '')2189return 0;21902191$mode = $this->identifyMode(0);21922193switch ($mode) {2194case QR_MODE_NUM: $length = $this->eatNum(); break;2195case QR_MODE_AN: $length = $this->eatAn(); break;2196case QR_MODE_KANJI:2197if ($hint == QR_MODE_KANJI)2198$length = $this->eatKanji();2199else $length = $this->eat8();2200break;2201default: $length = $this->eat8(); break;22022203}22042205if($length == 0) return 0;2206if($length < 0) return -1;22072208$this->dataStr = substr($this->dataStr, $length);2209}2210}22112212//----------------------------------------------------------------------2213public function toUpper()2214{2215$stringLen = strlen($this->dataStr);2216$p = 0;22172218while ($p<$stringLen) {2219$mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint);2220if($mode == QR_MODE_KANJI) {2221$p += 2;2222} else {2223if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) {2224$this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32);2225}2226$p++;2227}2228}22292230return $this->dataStr;2231}22322233//----------------------------------------------------------------------2234public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true)2235{2236if(is_null($string) || $string == '\0' || $string == '') {2237throw new Exception('empty string!!!');2238}22392240$split = new QRsplit($string, $input, $modeHint);22412242if(!$casesensitive)2243$split->toUpper();22442245return $split->splitString();2246}2247}2248224922502251//---- qrrscode.php -----------------------------22522253225422552256/*2257* PHP QR Code encoder2258*2259* Reed-Solomon error correction support2260*2261* Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q2262* (libfec is released under the GNU Lesser General Public License.)2263*2264* Based on libqrencode C library distributed under LGPL 2.12265* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>2266*2267* PHP QR Code is distributed under LGPL 32268* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>2269*2270* This library is free software; you can redistribute it and/or2271* modify it under the terms of the GNU Lesser General Public2272* License as published by the Free Software Foundation; either2273* version 3 of the License, or any later version.2274*2275* This library is distributed in the hope that it will be useful,2276* but WITHOUT ANY WARRANTY; without even the implied warranty of2277* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU2278* Lesser General Public License for more details.2279*2280* You should have received a copy of the GNU Lesser General Public2281* License along with this library; if not, write to the Free Software2282* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA2283*/22842285class QRrsItem {22862287public $mm; // Bits per symbol2288public $nn; // Symbols per block (= (1<<mm)-1)2289public $alpha_to = array(); // log lookup table2290public $index_of = array(); // Antilog lookup table2291public $genpoly = array(); // Generator polynomial2292public $nroots; // Number of generator roots = number of parity symbols2293public $fcr; // First consecutive root, index form2294public $prim; // Primitive element, index form2295public $iprim; // prim-th root of 1, index form2296public $pad; // Padding bytes in shortened block2297public $gfpoly;22982299//----------------------------------------------------------------------2300public function modnn($x)2301{2302while ($x >= $this->nn) {2303$x -= $this->nn;2304$x = ($x >> $this->mm) + ($x & $this->nn);2305}23062307return $x;2308}23092310//----------------------------------------------------------------------2311public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)2312{2313// Common code for intializing a Reed-Solomon control block (char or int symbols)2314// Copyright 2004 Phil Karn, KA9Q2315// May be used under the terms of the GNU Lesser General Public License (LGPL)23162317$rs = null;23182319// Check parameter ranges2320if($symsize < 0 || $symsize > 8) return $rs;2321if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs;2322if($prim <= 0 || $prim >= (1<<$symsize)) return $rs;2323if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values!2324if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding23252326$rs = new QRrsItem();2327$rs->mm = $symsize;2328$rs->nn = (1<<$symsize)-1;2329$rs->pad = $pad;23302331$rs->alpha_to = array_fill(0, $rs->nn+1, 0);2332$rs->index_of = array_fill(0, $rs->nn+1, 0);23332334// PHP style macro replacement ;)2335$NN =& $rs->nn;2336$A0 =& $NN;23372338// Generate Galois field lookup tables2339$rs->index_of[0] = $A0; // log(zero) = -inf2340$rs->alpha_to[$A0] = 0; // alpha**-inf = 02341$sr = 1;23422343for($i=0; $i<$rs->nn; $i++) {2344$rs->index_of[$sr] = $i;2345$rs->alpha_to[$i] = $sr;2346$sr <<= 1;2347if($sr & (1<<$symsize)) {2348$sr ^= $gfpoly;2349}2350$sr &= $rs->nn;2351}23522353if($sr != 1){2354// field generator polynomial is not primitive!2355$rs = NULL;2356return $rs;2357}23582359/* Form RS code generator polynomial from its roots */2360$rs->genpoly = array_fill(0, $nroots+1, 0);23612362$rs->fcr = $fcr;2363$rs->prim = $prim;2364$rs->nroots = $nroots;2365$rs->gfpoly = $gfpoly;23662367/* Find prim-th root of 1, used in decoding */2368for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn)2369; // intentional empty-body loop!23702371$rs->iprim = (int)($iprim / $prim);2372$rs->genpoly[0] = 1;23732374for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) {2375$rs->genpoly[$i+1] = 1;23762377// Multiply rs->genpoly[] by @**(root + x)2378for ($j = $i; $j > 0; $j--) {2379if ($rs->genpoly[$j] != 0) {2380$rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)];2381} else {2382$rs->genpoly[$j] = $rs->genpoly[$j-1];2383}2384}2385// rs->genpoly[0] can never be zero2386$rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)];2387}23882389// convert rs->genpoly[] to index form for quicker encoding2390for ($i = 0; $i <= $nroots; $i++)2391$rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]];23922393return $rs;2394}23952396//----------------------------------------------------------------------2397public function encode_rs_char($data, &$parity)2398{2399$MM =& $this->mm;2400$NN =& $this->nn;2401$ALPHA_TO =& $this->alpha_to;2402$INDEX_OF =& $this->index_of;2403$GENPOLY =& $this->genpoly;2404$NROOTS =& $this->nroots;2405$FCR =& $this->fcr;2406$PRIM =& $this->prim;2407$IPRIM =& $this->iprim;2408$PAD =& $this->pad;2409$A0 =& $NN;24102411$parity = array_fill(0, $NROOTS, 0);24122413for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) {24142415$feedback = $INDEX_OF[$data[$i] ^ $parity[0]];2416if($feedback != $A0) {2417// feedback term is non-zero24182419// This line is unnecessary when GENPOLY[NROOTS] is unity, as it must2420// always be for the polynomials constructed by init_rs()2421$feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback);24222423for($j=1;$j<$NROOTS;$j++) {2424$parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])];2425}2426}24272428// Shift2429array_shift($parity);2430if($feedback != $A0) {2431array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]);2432} else {2433array_push($parity, 0);2434}2435}2436}2437}24382439//##########################################################################24402441class QRrs {24422443public static $items = array();24442445//----------------------------------------------------------------------2446public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)2447{2448foreach(self::$items as $rs) {2449if($rs->pad != $pad) continue;2450if($rs->nroots != $nroots) continue;2451if($rs->mm != $symsize) continue;2452if($rs->gfpoly != $gfpoly) continue;2453if($rs->fcr != $fcr) continue;2454if($rs->prim != $prim) continue;24552456return $rs;2457}24582459$rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad);2460array_unshift(self::$items, $rs);24612462return $rs;2463}2464}2465246624672468//---- qrmask.php -----------------------------24692470247124722473/*2474* PHP QR Code encoder2475*2476* Masking2477*2478* Based on libqrencode C library distributed under LGPL 2.12479* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>2480*2481* PHP QR Code is distributed under LGPL 32482* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>2483*2484* This library is free software; you can redistribute it and/or2485* modify it under the terms of the GNU Lesser General Public2486* License as published by the Free Software Foundation; either2487* version 3 of the License, or any later version.2488*2489* This library is distributed in the hope that it will be useful,2490* but WITHOUT ANY WARRANTY; without even the implied warranty of2491* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU2492* Lesser General Public License for more details.2493*2494* You should have received a copy of the GNU Lesser General Public2495* License along with this library; if not, write to the Free Software2496* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA2497*/24982499define('N1', 3);2500define('N2', 3);2501define('N3', 40);2502define('N4', 10);25032504class QRmask {25052506public $runLength = array();25072508//----------------------------------------------------------------------2509public function __construct()2510{2511$this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0);2512}25132514//----------------------------------------------------------------------2515public function writeFormatInformation($width, &$frame, $mask, $level)2516{2517$blacks = 0;2518$format = QRspec::getFormatInfo($mask, $level);25192520for($i=0; $i<8; $i++) {2521if($format & 1) {2522$blacks += 2;2523$v = 0x85;2524} else {2525$v = 0x84;2526}25272528$frame[8][$width - 1 - $i] = chr($v);2529if($i < 6) {2530$frame[$i][8] = chr($v);2531} else {2532$frame[$i + 1][8] = chr($v);2533}2534$format = $format >> 1;2535}25362537for($i=0; $i<7; $i++) {2538if($format & 1) {2539$blacks += 2;2540$v = 0x85;2541} else {2542$v = 0x84;2543}25442545$frame[$width - 7 + $i][8] = chr($v);2546if($i == 0) {2547$frame[8][7] = chr($v);2548} else {2549$frame[8][6 - $i] = chr($v);2550}25512552$format = $format >> 1;2553}25542555return $blacks;2556}25572558//----------------------------------------------------------------------2559public function mask0($x, $y) { return ($x+$y)&1; }2560public function mask1($x, $y) { return ($y&1); }2561public function mask2($x, $y) { return ($x%3); }2562public function mask3($x, $y) { return ($x+$y)%3; }2563public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; }2564public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; }2565public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; }2566public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; }25672568//----------------------------------------------------------------------2569private function generateMaskNo($maskNo, $width, $frame)2570{2571$bitMask = array_fill(0, $width, array_fill(0, $width, 0));25722573for($y=0; $y<$width; $y++) {2574for($x=0; $x<$width; $x++) {2575if(ord($frame[$y][$x]) & 0x80) {2576$bitMask[$y][$x] = 0;2577} else {2578$maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y);2579$bitMask[$y][$x] = ($maskFunc == 0)?1:0;2580}25812582}2583}25842585return $bitMask;2586}25872588//----------------------------------------------------------------------2589public static function serial($bitFrame)2590{2591$codeArr = array();25922593foreach ($bitFrame as $line)2594$codeArr[] = join('', $line);25952596return gzcompress(join("\n", $codeArr), 9);2597}25982599//----------------------------------------------------------------------2600public static function unserial($code)2601{2602$codeArr = array();26032604$codeLines = explode("\n", gzuncompress($code));2605foreach ($codeLines as $line)2606$codeArr[] = str_split($line);26072608return $codeArr;2609}26102611//----------------------------------------------------------------------2612public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false)2613{2614$b = 0;2615$bitMask = array();26162617$fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat';26182619if (QR_CACHEABLE) {2620if (file_exists($fileName)) {2621$bitMask = self::unserial(file_get_contents($fileName));2622} else {2623$bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);2624if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo))2625mkdir(QR_CACHE_DIR.'mask_'.$maskNo);2626file_put_contents($fileName, self::serial($bitMask));2627}2628} else {2629$bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);2630}26312632if ($maskGenOnly)2633return;26342635$d = $s;26362637for($y=0; $y<$width; $y++) {2638for($x=0; $x<$width; $x++) {2639if($bitMask[$y][$x] == 1) {2640$d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]);2641}2642$b += (int)(ord($d[$y][$x]) & 1);2643}2644}26452646return $b;2647}26482649//----------------------------------------------------------------------2650public function makeMask($width, $frame, $maskNo, $level)2651{2652$masked = array_fill(0, $width, str_repeat("\0", $width));2653$this->makeMaskNo($maskNo, $width, $frame, $masked);2654$this->writeFormatInformation($width, $masked, $maskNo, $level);26552656return $masked;2657}26582659//----------------------------------------------------------------------2660public function calcN1N3($length)2661{2662$demerit = 0;26632664for($i=0; $i<$length; $i++) {26652666if($this->runLength[$i] >= 5) {2667$demerit += (N1 + ($this->runLength[$i] - 5));2668}2669if($i & 1) {2670if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) {2671$fact = (int)($this->runLength[$i] / 3);2672if(($this->runLength[$i-2] == $fact) &&2673($this->runLength[$i-1] == $fact) &&2674($this->runLength[$i+1] == $fact) &&2675($this->runLength[$i+2] == $fact)) {2676if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) {2677$demerit += N3;2678} else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) {2679$demerit += N3;2680}2681}2682}2683}2684}2685return $demerit;2686}26872688//----------------------------------------------------------------------2689public function evaluateSymbol($width, $frame)2690{2691$head = 0;2692$demerit = 0;26932694for($y=0; $y<$width; $y++) {2695$head = 0;2696$this->runLength[0] = 1;26972698$frameY = $frame[$y];26992700if ($y>0)2701$frameYM = $frame[$y-1];27022703for($x=0; $x<$width; $x++) {2704if(($x > 0) && ($y > 0)) {2705$b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]);2706$w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]);27072708if(($b22 | ($w22 ^ 1))&1) {2709$demerit += N2;2710}2711}2712if(($x == 0) && (ord($frameY[$x]) & 1)) {2713$this->runLength[0] = -1;2714$head = 1;2715$this->runLength[$head] = 1;2716} else if($x > 0) {2717if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) {2718$head++;2719$this->runLength[$head] = 1;2720} else {2721$this->runLength[$head]++;2722}2723}2724}27252726$demerit += $this->calcN1N3($head+1);2727}27282729for($x=0; $x<$width; $x++) {2730$head = 0;2731$this->runLength[0] = 1;27322733for($y=0; $y<$width; $y++) {2734if($y == 0 && (ord($frame[$y][$x]) & 1)) {2735$this->runLength[0] = -1;2736$head = 1;2737$this->runLength[$head] = 1;2738} else if($y > 0) {2739if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) {2740$head++;2741$this->runLength[$head] = 1;2742} else {2743$this->runLength[$head]++;2744}2745}2746}27472748$demerit += $this->calcN1N3($head+1);2749}27502751return $demerit;2752}275327542755//----------------------------------------------------------------------2756public function mask($width, $frame, $level)2757{2758$minDemerit = PHP_INT_MAX;2759$bestMaskNum = 0;2760$bestMask = array();27612762$checked_masks = array(0,1,2,3,4,5,6,7);27632764if (QR_FIND_FROM_RANDOM !== false) {27652766$howManuOut = 8-(QR_FIND_FROM_RANDOM % 9);2767for ($i = 0; $i < $howManuOut; $i++) {2768$remPos = rand (0, count($checked_masks)-1);2769unset($checked_masks[$remPos]);2770$checked_masks = array_values($checked_masks);2771}27722773}27742775$bestMask = $frame;27762777foreach($checked_masks as $i) {2778$mask = array_fill(0, $width, str_repeat("\0", $width));27792780$demerit = 0;2781$blacks = 0;2782$blacks = $this->makeMaskNo($i, $width, $frame, $mask);2783$blacks += $this->writeFormatInformation($width, $mask, $i, $level);2784$blacks = (int)(100 * $blacks / ($width * $width));2785$demerit = (int)((int)(abs($blacks - 50) / 5) * N4);2786$demerit += $this->evaluateSymbol($width, $mask);27872788if($demerit < $minDemerit) {2789$minDemerit = $demerit;2790$bestMask = $mask;2791$bestMaskNum = $i;2792}2793}27942795return $bestMask;2796}27972798//----------------------------------------------------------------------2799}28002801280228032804//---- qrencode.php -----------------------------28052806280728082809/*2810* PHP QR Code encoder2811*2812* Main encoder classes.2813*2814* Based on libqrencode C library distributed under LGPL 2.12815* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <[email protected]>2816*2817* PHP QR Code is distributed under LGPL 32818* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>2819*2820* This library is free software; you can redistribute it and/or2821* modify it under the terms of the GNU Lesser General Public2822* License as published by the Free Software Foundation; either2823* version 3 of the License, or any later version.2824*2825* This library is distributed in the hope that it will be useful,2826* but WITHOUT ANY WARRANTY; without even the implied warranty of2827* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU2828* Lesser General Public License for more details.2829*2830* You should have received a copy of the GNU Lesser General Public2831* License along with this library; if not, write to the Free Software2832* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA2833*/28342835class QRrsblock {2836public $dataLength;2837public $data = array();2838public $eccLength;2839public $ecc = array();28402841public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs)2842{2843$rs->encode_rs_char($data, $ecc);28442845$this->dataLength = $dl;2846$this->data = $data;2847$this->eccLength = $el;2848$this->ecc = $ecc;2849}2850};28512852//##########################################################################28532854class QRrawcode {2855public $version;2856public $datacode = array();2857public $ecccode = array();2858public $blocks;2859public $rsblocks = array(); //of RSblock2860public $count;2861public $dataLength;2862public $eccLength;2863public $b1;28642865//----------------------------------------------------------------------2866public function __construct(QRinput $input)2867{2868$spec = array(0,0,0,0,0);28692870$this->datacode = $input->getByteStream();2871if(is_null($this->datacode)) {2872throw new Exception('null imput string');2873}28742875QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec);28762877$this->version = $input->getVersion();2878$this->b1 = QRspec::rsBlockNum1($spec);2879$this->dataLength = QRspec::rsDataLength($spec);2880$this->eccLength = QRspec::rsEccLength($spec);2881$this->ecccode = array_fill(0, $this->eccLength, 0);2882$this->blocks = QRspec::rsBlockNum($spec);28832884$ret = $this->init($spec);2885if($ret < 0) {2886throw new Exception('block alloc error');2887return null;2888}28892890$this->count = 0;2891}28922893//----------------------------------------------------------------------2894public function init(array $spec)2895{2896$dl = QRspec::rsDataCodes1($spec);2897$el = QRspec::rsEccCodes1($spec);2898$rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);289929002901$blockNo = 0;2902$dataPos = 0;2903$eccPos = 0;2904for($i=0; $i<QRspec::rsBlockNum1($spec); $i++) {2905$ecc = array_slice($this->ecccode,$eccPos);2906$this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);2907$this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);29082909$dataPos += $dl;2910$eccPos += $el;2911$blockNo++;2912}29132914if(QRspec::rsBlockNum2($spec) == 0)2915return 0;29162917$dl = QRspec::rsDataCodes2($spec);2918$el = QRspec::rsEccCodes2($spec);2919$rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);29202921if($rs == NULL) return -1;29222923for($i=0; $i<QRspec::rsBlockNum2($spec); $i++) {2924$ecc = array_slice($this->ecccode,$eccPos);2925$this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);2926$this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);29272928$dataPos += $dl;2929$eccPos += $el;2930$blockNo++;2931}29322933return 0;2934}29352936//----------------------------------------------------------------------2937public function getCode()2938{2939$ret = null;29402941if($this->count < $this->dataLength) {2942$row = $this->count % $this->blocks;2943$col = $this->count / $this->blocks;2944if($col >= $this->rsblocks[0]->dataLength) {2945$row += $this->b1;2946}2947$ret = $this->rsblocks[$row]->data[$col];2948} else if($this->count < $this->dataLength + $this->eccLength) {2949$row = ($this->count - $this->dataLength) % $this->blocks;2950$col = ($this->count - $this->dataLength) / $this->blocks;2951$ret = $this->rsblocks[$row]->ecc[$col];2952} else {2953return 0;2954}2955$this->count++;29562957return $ret;2958}2959}29602961//##########################################################################29622963class QRcode {29642965public $version;2966public $width;2967public $data;29682969//----------------------------------------------------------------------2970public function encodeMask(QRinput $input, $mask)2971{2972if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) {2973throw new Exception('wrong version');2974}2975if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) {2976throw new Exception('wrong level');2977}29782979$raw = new QRrawcode($input);29802981QRtools::markTime('after_raw');29822983$version = $raw->version;2984$width = QRspec::getWidth($version);2985$frame = QRspec::newFrame($version);29862987$filler = new FrameFiller($width, $frame);2988if(is_null($filler)) {2989return NULL;2990}29912992// inteleaved data and ecc codes2993for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) {2994$code = $raw->getCode();2995$bit = 0x80;2996for($j=0; $j<8; $j++) {2997$addr = $filler->next();2998$filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0));2999$bit = $bit >> 1;3000}3001}30023003QRtools::markTime('after_filler');30043005unset($raw);30063007// remainder bits3008$j = QRspec::getRemainder($version);3009for($i=0; $i<$j; $i++) {3010$addr = $filler->next();3011$filler->setFrameAt($addr, 0x02);3012}30133014$frame = $filler->frame;3015unset($filler);301630173018// masking3019$maskObj = new QRmask();3020if($mask < 0) {30213022if (QR_FIND_BEST_MASK) {3023$masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel());3024} else {3025$masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel());3026}3027} else {3028$masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel());3029}30303031if($masked == NULL) {3032return NULL;3033}30343035QRtools::markTime('after_mask');30363037$this->version = $version;3038$this->width = $width;3039$this->data = $masked;30403041return $this;3042}30433044//----------------------------------------------------------------------3045public function encodeInput(QRinput $input)3046{3047return $this->encodeMask($input, -1);3048}30493050//----------------------------------------------------------------------3051public function encodeString8bit($string, $version, $level)3052{3053if(string == NULL) {3054throw new Exception('empty string!');3055return NULL;3056}30573058$input = new QRinput($version, $level);3059if($input == NULL) return NULL;30603061$ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string));3062if($ret < 0) {3063unset($input);3064return NULL;3065}3066return $this->encodeInput($input);3067}30683069//----------------------------------------------------------------------3070public function encodeString($string, $version, $level, $hint, $casesensitive)3071{30723073if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) {3074throw new Exception('bad hint');3075return NULL;3076}30773078$input = new QRinput($version, $level);3079if($input == NULL) return NULL;30803081$ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive);3082if($ret < 0) {3083return NULL;3084}30853086return $this->encodeInput($input);3087}30883089//----------------------------------------------------------------------3090public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)3091{3092$enc = QRencode::factory($level, $size, $margin);3093return $enc->encodePNG($text, $outfile, $saveandprint=false);3094}30953096//----------------------------------------------------------------------3097public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)3098{3099$enc = QRencode::factory($level, $size, $margin);3100return $enc->encode($text, $outfile);3101}31023103//----------------------------------------------------------------------3104public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)3105{3106$enc = QRencode::factory($level, $size, $margin);3107return $enc->encodeRAW($text, $outfile);3108}3109}31103111//##########################################################################31123113class FrameFiller {31143115public $width;3116public $frame;3117public $x;3118public $y;3119public $dir;3120public $bit;31213122//----------------------------------------------------------------------3123public function __construct($width, &$frame)3124{3125$this->width = $width;3126$this->frame = $frame;3127$this->x = $width - 1;3128$this->y = $width - 1;3129$this->dir = -1;3130$this->bit = -1;3131}31323133//----------------------------------------------------------------------3134public function setFrameAt($at, $val)3135{3136$this->frame[$at['y']][$at['x']] = chr($val);3137}31383139//----------------------------------------------------------------------3140public function getFrameAt($at)3141{3142return ord($this->frame[$at['y']][$at['x']]);3143}31443145//----------------------------------------------------------------------3146public function next()3147{3148do {31493150if($this->bit == -1) {3151$this->bit = 0;3152return array('x'=>$this->x, 'y'=>$this->y);3153}31543155$x = $this->x;3156$y = $this->y;3157$w = $this->width;31583159if($this->bit == 0) {3160$x--;3161$this->bit++;3162} else {3163$x++;3164$y += $this->dir;3165$this->bit--;3166}31673168if($this->dir < 0) {3169if($y < 0) {3170$y = 0;3171$x -= 2;3172$this->dir = 1;3173if($x == 6) {3174$x--;3175$y = 9;3176}3177}3178} else {3179if($y == $w) {3180$y = $w - 1;3181$x -= 2;3182$this->dir = -1;3183if($x == 6) {3184$x--;3185$y -= 8;3186}3187}3188}3189if($x < 0 || $y < 0) return null;31903191$this->x = $x;3192$this->y = $y;31933194} while(ord($this->frame[$y][$x]) & 0x80);31953196return array('x'=>$x, 'y'=>$y);3197}31983199} ;32003201//##########################################################################32023203class QRencode {32043205public $casesensitive = true;3206public $eightbit = false;32073208public $version = 0;3209public $size = 3;3210public $margin = 4;32113212public $structured = 0; // not supported yet32133214public $level = QR_ECLEVEL_L;3215public $hint = QR_MODE_8;32163217//----------------------------------------------------------------------3218public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4)3219{3220$enc = new QRencode();3221$enc->size = $size;3222$enc->margin = $margin;32233224switch ($level.'') {3225case '0':3226case '1':3227case '2':3228case '3':3229$enc->level = $level;3230break;3231case 'l':3232case 'L':3233$enc->level = QR_ECLEVEL_L;3234break;3235case 'm':3236case 'M':3237$enc->level = QR_ECLEVEL_M;3238break;3239case 'q':3240case 'Q':3241$enc->level = QR_ECLEVEL_Q;3242break;3243case 'h':3244case 'H':3245$enc->level = QR_ECLEVEL_H;3246break;3247}32483249return $enc;3250}32513252//----------------------------------------------------------------------3253public function encodeRAW($intext, $outfile = false)3254{3255$code = new QRcode();32563257if($this->eightbit) {3258$code->encodeString8bit($intext, $this->version, $this->level);3259} else {3260$code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);3261}32623263return $code->data;3264}32653266//----------------------------------------------------------------------3267public function encode($intext, $outfile = false)3268{3269$code = new QRcode();32703271if($this->eightbit) {3272$code->encodeString8bit($intext, $this->version, $this->level);3273} else {3274$code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);3275}32763277QRtools::markTime('after_encode');32783279if ($outfile!== false) {3280file_put_contents($outfile, join("\n", QRtools::binarize($code->data)));3281} else {3282return QRtools::binarize($code->data);3283}3284}32853286//----------------------------------------------------------------------3287public function encodePNG($intext, $outfile = false,$saveandprint=false)3288{3289try {32903291ob_start();3292$tab = $this->encode($intext);3293$err = ob_get_contents();3294ob_end_clean();32953296if ($err != '')3297QRtools::log($outfile, $err);32983299$maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin));33003301QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint);33023303} catch (Exception $e) {33043305QRtools::log($outfile, $e->getMessage());33063307}3308}3309}33103311331233133314