Commit 32a21538 by Tobin

daily commit

parent 41c9a7b4
[1] Merchant ID : 201901291000002
[2] Merchant Key : +Hu4bL6iVk943JmFAvGtWEYMODFry4fad2I+iM0X2m0=
[3] Collaborator ID : BAYANPAY
[4] Bayan URL : https://staging.bayanpay.sa/direcpay/secure/PaymentTxnServlet
[5] Block Existence Indicator : 1110000
[6] DataBlock1 : TransactionDataBlock1 : 11111111|1552564762|100.00|http://localhost/timeOut/Api/paymentGateway|http://localhost/timeOut/Api/paymentGateway|INTERNET|CC|01|SAR
[7] DataBlock2 : billingDataBlock : 1111111111000|Soloman|Vandy|123,ParkStreet|Park Street|Riyadh|Riyadh|400081|IN|solomanv@test.com|9820998209
[8] DataBlock3 : shippingDataBlock : 111111110001|Soloman|Vandy|123ParkStreet|parkstreet|Riyadh|Riyadh|400081|IN|9820998209
[9] DataBlock4 : paymentDataBlock : NULL
[10] DataBlock5 : merchantDataBlock : NULL
[11] DataBlock6 : otherDataBlock : NULL
[12] DataBlock7 : DCCDataBlock : NULL
[13] beforeEncryptionString : 1110000||11111111|1552564762|100.00|http://localhost/timeOut/Api/paymentGateway|http://localhost/timeOut/Api/paymentGateway|INTERNET|CC|01|SAR||1111111111000|Soloman|Vandy|123,ParkStreet|Park Street|Riyadh|Riyadh|400081|IN|solomanv@test.com|9820998209||111111110001|Soloman|Vandy|123ParkStreet|parkstreet|Riyadh|Riyadh|400081|IN|9820998209
[14] EncryptedString : RKeCiPHQnrq4Ih8pVYOhUNd0KfqxD2Qby/wkUPbEvj23Xft2HvphIethb29a7Myq8E5b0uHFoKs9UpMiz9/j9ntt08QUmxUUx6796JKGexbz3qX7HwMuZaG31+FgM6BL1NqoybToj95/b2VpJ+PiznhjDPKtRHw1ghUTYRUdmM6z8dhuPGjfgKHvD93wH7p3SnktHyQVwa77nPyBT+3xVSARLWSHMzJn128/EaKVn37Hw9ml6NBR//D2fZhopsnvcdOWVLS9EOGffPbaSX3oijDjxaiW1BzrfC9opGdzXY9Vih9sohxhgqHIWvNakCk5Ctqav7hC23iZ5Aj4PCaILTpDUfQsHpF4RaP4HtC+P94DYFWPuScMYy+yeEjWCuDWNj1pcJBUwFqmN4ZHlafClfMm6vLfJOCspMq+8MShA0T/NvYd9fNYPg8C5Kl3HSTEF7cbGU7qNFT/vrlNlHkYNw==
[15] BayanPostData : 201901291000002||BAYANPAY||RKeCiPHQnrq4Ih8pVYOhUNd0KfqxD2Qby/wkUPbEvj23Xft2HvphIethb29a7Myq8E5b0uHFoKs9UpMiz9/j9ntt08QUmxUUx6796JKGexbz3qX7HwMuZaG31+FgM6BL1NqoybToj95/b2VpJ+PiznhjDPKtRHw1ghUTYRUdmM6z8dhuPGjfgKHvD93wH7p3SnktHyQVwa77nPyBT+3xVSARLWSHMzJn128/EaKVn37Hw9ml6NBR//D2fZhopsnvcdOWVLS9EOGffPbaSX3oijDjxaiW1BzrfC9opGdzXY9Vih9sohxhgqHIWvNakCk5Ctqav7hC23iZ5Aj4PCaILTpDUfQsHpF4RaP4HtC+P94DYFWPuScMYy+yeEjWCuDWNj1pcJBUwFqmN4ZHlafClfMm6vLfJOCspMq+8MShA0T/NvYd9fNYPg8C5Kl3HSTEF7cbGU7qNFT/vrlNlHkYNw==
\ No newline at end of file
......@@ -23,7 +23,7 @@ defined('BASEPATH') OR exit('No direct script access allowed');
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = "https://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
$config['base_url'] = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
/*
|--------------------------------------------------------------------------
......
......@@ -75,10 +75,10 @@ $query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'nuvento_timeout',
'hostname' => '192.168.140.123',
'username' => 'root',
'password' => 'Golden_123',
'database' => 'nuvento_timeout',
'database' => 'tobin_eventTimeOut',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
......
......@@ -298,8 +298,140 @@ class Api extends CI_Controller {
}
}
public function paymentGateway(){
BayanPayPayment();
// Please read the documentation and readme.txt file before implementing the code
$BayanPayArray = array('BayanPay_Online_setting' => array(
'merchantKey' => "+Hu4bL6iVk943JmFAvGtWEYMODFry4fad2I+iM0X2m0=", // Your key provided by BayanPay
'merchantId' => '201901291000002', // Your merchant ID ex: 201408191000001
'collaboratorId' => 'BAYANPAY', // Constant used by BayanPay
'iv' => '0123456789abcdef', // Used for initializing CBC encryption mode
'url' => false // Set to false if you are using testing environment , set to true if you are using live environment
),
'Block_Existence_Indicator' => array(
'transactionDataBlock' => true,
'billingDataBlock' => true,
'shippingDataBlock' => true,
'paymentDataBlock' => false,
'merchantDataBlock' => false,
'otherDataBlock' => false,
'DCCDataBlock' => false
),
'Field_Existence_Indicator_Transaction' => array(
'merchantOrderNumber' => time(),
'amount' => '100.00',
'successUrl' => $this->baseurl(),
'failureUrl' => $this->baseurl(),
'transactionMode' => 'INTERNET',
'payModeType' => 'CC',
'transactionType' => '01',
'currency' => 'SAR'
),
'Field_Existence_Indicator_Billing' => array(
'billToFirstName' => 'Soloman',
'billToLastName' => 'Vandy',
'billToStreet1' => '123,ParkStreet',
'billToStreet2' => 'Park Street',
'billToCity' => 'Riyadh',
'billToState' => 'Riyadh',
'billtoPostalCode' => '400081',
'billToCountry' => 'IN',
'billToEmail' => 'solomanv@test.com',
'billToMobileNumber' => '9820998209',
'billToPhoneNumber1' => '',
'billToPhoneNumber2' => '',
'billToPhoneNumber3' => ''
),
'Field_Existence_Indicator_Shipping' => array(
'shipToFirstName' => 'Soloman',
'shipToLastName' => 'Vandy',
'shipToStreet1' => '123ParkStreet',
'shipToStreet2' => 'parkstreet',
'shipToCity' => 'Riyadh',
'shipToState' => 'Riyadh',
'shipToPostalCode' => '400081',
'shipToCountry' => 'IN',
'shipToPhoneNumber1' => '',
'shipToPhoneNumber2' => '',
'shipToPhoneNumber3' => '',
'shipToMobileNumber' => '9820998209'
),
'Field_Existence_Indicator_Payment' => array(
'cardNumber' => '4111111111111111', // 1. Card Number
'expMonth' => '08', // 2. Expiry Month
'expYear' => '2020', // 3. Expiry Year
'CVV' => '123', // 4. CVV
'cardHolderName' => 'Soloman', // 5. Card Holder Name
'cardType' => 'Visa', // 6. Card Type
'custMobileNumber'=> '9820998209', // 7. Customer Mobile Number
'paymentID' => '123456', // 8. Payment ID
'OTP' => '123456', // 9. OTP field
'gatewayID' => '1026', // 10.Gateway ID
'cardToken' => '1202' // 11.Card Token
),
'Field_Existence_Indicator_Merchant' => array(
'UDF1' => '115.121.181.112', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF2' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF3' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF4' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF5' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF6' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF7' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF8' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF9' => 'abc', // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
'UDF10' => 'abc' // This is a ‘user-defined field’ that can be used to send additional information about the transaction.
),
'Field_Existence_Indicator_OtherData' => array(
'custID' => '12345',
'transactionSource' => 'IVR',
'productInfo' => 'Book',
'isUserLoggedIn' => 'Y',
'itemTotal' => '500.00, 1000.00',
'itemCategory' => 'CD, Book',
'ignoreValidationResult' => 'FALSE'
),
'Field_Existence_Indicator_DCC' => array(
'DCCReferenceNumber' => '09898787', // DCC Reference Number
'foreignAmount' => '240.00', // Foreign Amount
'ForeignCurrency' => 'USD' // Foreign Currency
)
);
$BayanPayOnlineObject = new BayanPayBitmapPaymentIntegration($BayanPayArray);
if(isset($_REQUEST['responseParameter']) && $_REQUEST['responseParameter'] != ''){
$response = $BayanPayOnlineObject->decryptData($_REQUEST['responseParameter'],$BayanPayOnlineObject->merchantKey,$BayanPayOnlineObject->iv);
$BayanPayOnlineObject->AddLog('BayanPay Response : '.print_r($response, TRUE),'16');
}
$requestParameter = $BayanPayOnlineObject->BayanPostData;
// // if($BayanPayOnlineObject->url)
// $requestUrl = 'https://payments.bayanpay.sa/direcpay/secure/PaymentTxnServlet';
// else
$requestUrl = 'https://staging.bayanpay.sa/direcpay/secure/PaymentTxnServlet';
?>
<form action="<?php echo $requestUrl; ?>" method="post" name="BayanPay_online_payment"
id="BayanPay_online_payment">
<?php echo '<input type="hidden" name="requestParameter" value='.$requestParameter.'>'; ?>
<input type="submit" value="Submit">
</form>
<?php
}
function baseurl(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
}
\ No newline at end of file
......@@ -210,5 +210,10 @@ class Booking extends CI_Controller {
}
return $reportData;
}
function aaa($name=''){
$url = genQRcode($name);
echo base_url().$url;
}
}
?>
\ No newline at end of file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class CMS extends CI_Controller {
public function __construct() {
parent::__construct();
date_default_timezone_set("Asia/Kolkata");
$this->load->model('Cms_model');
if(!$this->session->userdata('logged_in')) {
redirect(base_url('Login'));
}
if($this->session->userdata['user_type'] != 1){
$flashMsg = array('message'=>'Access Denied You don\'t have permission to access this Page',
'class'=>'error');
$this->session->set_flashdata('message',$flashMsg);
redirect(base_url());
}
}
public function index() {
$template['page'] = 'CMS/cms_management';
$template['menu'] = "CMS Settings";
$template['smenu'] = "Change CMS Data";
$template['pTitle'] = "CMS";
$template['page_head'] = "Booking Management";
$template['pDescription'] = "Edit or View CMS Data";
$template['cmsData'] = $this->Cms_model->getCMSdata();
$this->load->view('template',$template);
}
public function changeCMSdata(){
$url = 'CMS/changeCMSdata';
$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
if(!isset($_POST) || empty($_POST)){
$this->session->set_flashdata('message',$flashMsg);
redirect(base_url($url));
}
if(isset($_POST['faq']) && empty($_POST['faq'])){
unset($_POST['faq']);
}
if(isset($_POST['privacy_policy']) && empty($_POST['privacy_policy'])){
unset($_POST['privacy_policy']);
}
if(isset($_POST['terms_and_conditions']) && empty($_POST['terms_and_conditions'])){
unset($_POST['terms_and_conditions']);
}
$status = $this->Cms_model->updateCMS($_POST);
if($status){
$url = '';
$flashMsg['class'] = 'success';
$flashMsg['message'] = 'Settings Successfully Updated..!';
}
$this->session->set_flashdata('message',$flashMsg);
redirect(base_url($url));
}
}
?>
\ No newline at end of file
......@@ -86,6 +86,8 @@ class Event extends CI_Controller {
$errMsg = 'Provide Proper Layout details';
}
$_POST['has_payment'] = (isset($_POST['has_payment']) && $_POST['has_payment'] == 1)?'1':'0';
$_POST['seat_pricing'] = $_POST['custom_seat_layout'] = '';
if(isset($_POST['fare_type']) && $_POST['fare_type'] == 1){
$cstmSeatLayout = array();
......@@ -116,6 +118,7 @@ class Event extends CI_Controller {
'category_id'=>$_POST['category_id'],
'provider_id'=>$provider,
'max_booking'=>$_POST['max_booking'],
'has_payment'=>$_POST['has_payment'],
'seat_pricing'=>$_POST['seat_pricing'],
'event_discription'=>$_POST['event_discription'],
'custom_seat_layout'=>$_POST['custom_seat_layout']);
......@@ -247,6 +250,8 @@ class Event extends CI_Controller {
$errMsg = 'Provide Proper Layout details';
}
$_POST['has_payment'] = (isset($_POST['has_payment']) && $_POST['has_payment'] == 1)?'1':'0';
$_POST['seat_pricing'] = $_POST['custom_seat_layout'] = '';
if(isset($_POST['fare_type']) && $_POST['fare_type'] == 1){
$cstmSeatLayout = array();
......@@ -277,6 +282,7 @@ class Event extends CI_Controller {
'category_id'=>$_POST['category_id'],
'provider_id'=>$provider,
'max_booking'=>$_POST['max_booking'],
'has_payment'=>$_POST['has_payment'],
'seat_pricing'=>$_POST['seat_pricing'],
'event_discription'=>$_POST['event_discription'],
'custom_seat_layout'=>$_POST['custom_seat_layout']);
......
<?php
class Validation_model extends CI_Model {
public $validation_array = array(
'login'=> array('email_id'=>array('required'=>array('code'=>'ER02', 'message'=>'Email id is null or empty'),
'email'=>array('code'=>'ER03', 'message'=>'Invalid Email id')
),
'password'=>array('required'=>array('code'=>'ER04', 'message'=>'Password is null or empty'),
)
),
'register'=> array('email_id'=>array('required'=>array('code'=>'ER02', 'message'=>'Email id is null or empty'),
'email'=>array('code'=>'ER03', 'message'=>'Invalid Email id')
),
'phone'=>array('required'=>array('code'=>'ER07', 'message'=>'Phone no is null or empty'),
'phone'=>array('code'=>'ER08', 'message'=>'Invalid Phone no'),
),
'password'=>array('required'=>array('code'=>'ER04', 'message'=>'Password is null or empty'),
)
),
'forgot'=> array('email_id'=>array('required'=>array('code'=>'ER02', 'message'=>'Email id is null or empty'),
'email'=>array('code'=>'ER03', 'message'=>'Invalid Email id')
)
),
'popular'=>array(),
'category'=>array(),
'locality'=>array(),
'favourite'=>array('event_id'=>array('required'=>array('code'=>'ER16', 'message'=>'Event id is null or empty')
),
'auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
'status'=>array('required'=>array('code'=>'ER18', 'message'=>'Favourite status is missing'),
),
),
'favouritelist'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
),
'bookedlist'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
),
'bookingdetails'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
'bookingCode'=>array('required'=>array('code'=>'ER23', 'message'=>'Booking code is null or empty'),
),
),
'cancel'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
'bookingCode'=>array('required'=>array('code'=>'ER23', 'message'=>'Booking code is null or empty'),
),
),
'confirm'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
'bookingCode'=>array('required'=>array('code'=>'ER23', 'message'=>'Booking code is null or empty'),
),
),
'userinfo'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
),
'profile'=>array('name'=>array('required'=>array('code'=>'ER27', 'message'=>'Name is null or empty')
),
'gender'=>array('required'=>array('code'=>'ER28', 'message'=>'Gender is null or empty')
),
'dob'=>array('required'=>array('code'=>'ER29', 'message'=>'Date of birth is null or empty')
),
'city'=>array('required'=>array('code'=>'ER30', 'message'=>'City no is null or empty')
),
'auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
),
'tempbooking'=>array('event_id'=>array('required'=>array('code'=>'ER16', 'message'=>'Event id is null or empty')
),
'event_date_id'=>array('required'=>array('code'=>'ER33', 'message'=>'Event date and time is null or empty')
),
'amount'=>array('required'=>array('code'=>'ER35', 'message'=>'Amount is null or empty')
),
'no_of_ticket'=>array('required'=>array('code'=>'ER36', 'message'=>'no of ticket is null or empty')
),
'auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
),
'recommend'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
),
'search'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
),
'discover'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
'cat_id'=>array('required'=>array('code'=>'ER38', 'message'=>'Category id null or empty')
),
),
'event'=>array('auth_token'=>array('required'=>array('code'=>'ER17', 'message'=>'User Id is null or empty'),
),
'event_id'=>array('required'=>array('code'=>'ER16', 'message'=>'Event id is null or empty')
),
),
'searchEvent'=>array()
);
public function _consruct(){
parent::_construct();
}
public function validation_check($method_name, $parms) {
$state = 0;
$rules = $this->validation_array[$method_name];
$error_key = '';
foreach ($rules as $key => $value) {
foreach ($value as $keys => $values) {
switch ($keys) {
case 'required':
if(!isset($parms[$key]) || $parms[$key]=='' || $parms[$key]== null){
$state = 1;
$error_key = $values;
}
break;
case 'email':
if (isset($parms[$key]) && !filter_var($parms[$key], FILTER_VALIDATE_EMAIL)) {
$state = 1;
$error_key = $values;
}
break;
case 'phone':
if(isset($parms[$key])){
$phone = preg_replace('/[^0-9]/', '', $parms[$key]);
if (strlen($phone) !== 10) {
$state = 1;
$error_key = $values;
}
}
break;
default:
# code...
break;
}
if($state==1){
break;
}
}
if($state==1){
break;
}
}
return array('state'=>$state,'response'=>$error_key);
}
}
?>
\ No newline at end of file
......@@ -95,4 +95,34 @@
$unique = md5(uniqid(time().mt_rand(), true));
return $unique;
}
function genQRcode($data){
include 'qr_code/autoload.php';
$logo = 'assets/images/asset_logo.png';
$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs=500x500&chl='.urlencode($data));
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
$logo_qr_width = $QR_width/3;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
$savePath = "assets/uploads/qrcode/bookCode_".time().".png";
imagepng($QR, $savePath);
return $savePath;
}
function BayanPayPayment(){
include 'BayanPayPaymentLibrary.php';
}
?>
\ No newline at end of file
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit6bacbab18d503bdab77e94c6a6c19f18::getLoader();
composer.lock
vendor
nbproject
.idea
.buildpath
.project
.DS_Store
.*.sw*
.*.un~
language: php
php:
- 5.4
- 5.5
- 5.6
- 7.0
- 7.1
- hhvm
install:
- travis_retry composer install --no-interaction
- composer info -i
script: vendor/bin/phpunit --bootstrap tests/bootstrap.php --configuration tests/phpunit.xml tests
Copyright (c) 2013, Ben 'DASPRiD' Scholzen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
/**
* Module for generating QR codes.
*/
class Module implements AutoloaderProviderInterface
{
/**
* Get autoloader config.
*
* @return array
*/
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
QR Code generator
=================
Master: [![Build Status](https://api.travis-ci.org/Bacon/BaconQrCode.png?branch=master)](http://travis-ci.org/Bacon/BaconQrCode)
Introduction
------------
BaconQrCode is a port of QR code portion of the ZXing library. It currently
only features the encoder part, but could later receive the decoder part as
well.
As the Reed Solomon codec implementation of the ZXing library performs quite
slow in PHP, it was exchanged with the implementation by Phil Karn.
Example usage
-------------
```php
$renderer = new \BaconQrCode\Renderer\Image\Png();
$renderer->setHeight(256);
$renderer->setWidth(256);
$writer = new \BaconQrCode\Writer($renderer);
$writer->writeFile('Hello World!', 'qrcode.png');
```
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
'BaconQrCode\Common\AbstractEnum' => __DIR__ . '/src/BaconQrCode/Common/AbstractEnum.php',
'BaconQrCode\Common\BitArray' => __DIR__ . '/src/BaconQrCode/Common/BitArray.php',
'BaconQrCode\Common\BitMatrix' => __DIR__ . '/src/BaconQrCode/Common/BitMatrix.php',
'BaconQrCode\Common\BitUtils' => __DIR__ . '/src/BaconQrCode/Common/BitUtils.php',
'BaconQrCode\Common\CharacterSetEci' => __DIR__ . '/src/BaconQrCode/Common/CharacterSetEci.php',
'BaconQrCode\Common\EcBlock' => __DIR__ . '/src/BaconQrCode/Common/EcBlock.php',
'BaconQrCode\Common\EcBlocks' => __DIR__ . '/src/BaconQrCode/Common/EcBlocks.php',
'BaconQrCode\Common\ErrorCorrectionLevel' => __DIR__ . '/src/BaconQrCode/Common/ErrorCorrectionLevel.php',
'BaconQrCode\Common\FormatInformation' => __DIR__ . '/src/BaconQrCode/Common/FormatInformation.php',
'BaconQrCode\Common\Mode' => __DIR__ . '/src/BaconQrCode/Common/Mode.php',
'BaconQrCode\Common\ReedSolomonCodec' => __DIR__ . '/src/BaconQrCode/Common/ReedSolomonCodec.php',
'BaconQrCode\Common\Version' => __DIR__ . '/src/BaconQrCode/Common/Version.php',
'BaconQrCode\Encoder\BlockPair' => __DIR__ . '/src/BaconQrCode/Encoder/BlockPair.php',
'BaconQrCode\Encoder\ByteMatrix' => __DIR__ . '/src/BaconQrCode/Encoder/ByteMatrix.php',
'BaconQrCode\Encoder\Encoder' => __DIR__ . '/src/BaconQrCode/Encoder/Encoder.php',
'BaconQrCode\Encoder\MaskUtil' => __DIR__ . '/src/BaconQrCode/Encoder/MaskUtil.php',
'BaconQrCode\Encoder\MatrixUtil' => __DIR__ . '/src/BaconQrCode/Encoder/MatrixUtil.php',
'BaconQrCode\Encoder\QrCode' => __DIR__ . '/src/BaconQrCode/Encoder/QrCode.php',
'BaconQrCode\Exception\ExceptionInterface' => __DIR__ . '/src/BaconQrCode/Exception/ExceptionInterface.php',
'BaconQrCode\Exception\InvalidArgumentException' => __DIR__ . '/src/BaconQrCode/Exception/InvalidArgumentException.php',
'BaconQrCode\Exception\OutOfBoundsException' => __DIR__ . '/src/BaconQrCode/Exception/OutOfBoundsException.php',
'BaconQrCode\Exception\RuntimeException' => __DIR__ . '/src/BaconQrCode/Exception/RuntimeException.php',
'BaconQrCode\Exception\UnexpectedValueException' => __DIR__ . '/src/BaconQrCode/Exception/UnexpectedValueException.php',
'BaconQrCode\Exception\WriterException' => __DIR__ . '/src/BaconQrCode/Exception/WriterException.php',
'BaconQrCode\Renderer\Color\Cmyk' => __DIR__ . '/src/BaconQrCode/Renderer/Color/Cmyk.php',
'BaconQrCode\Renderer\Color\ColorInterface' => __DIR__ . '/src/BaconQrCode/Renderer/Color/ColorInterface.php',
'BaconQrCode\Renderer\Color\Gray' => __DIR__ . '/src/BaconQrCode/Renderer/Color/Gray.php',
'BaconQrCode\Renderer\Color\Rgb' => __DIR__ . '/src/BaconQrCode/Renderer/Color/Rgb.php',
'BaconQrCode\Renderer\Image\AbstractRenderer' => __DIR__ . '/src/BaconQrCode/Renderer/Image/AbstractRenderer.php',
'BaconQrCode\Renderer\Image\Decorator\DecoratorInterface' => __DIR__ . '/src/BaconQrCode/Renderer/Image/Decorator/DecoratorInterface.php',
'BaconQrCode\Renderer\Image\Decorator\FinderPattern' => __DIR__ . '/src/BaconQrCode/Renderer/Image/Decorator/FinderPattern.php',
'BaconQrCode\Renderer\Image\Eps' => __DIR__ . '/src/BaconQrCode/Renderer/Image/Eps.php',
'BaconQrCode\Renderer\Image\Png' => __DIR__ . '/src/BaconQrCode/Renderer/Image/Png.php',
'BaconQrCode\Renderer\Image\RendererInterface' => __DIR__ . '/src/BaconQrCode/Renderer/Image/RendererInterface.php',
'BaconQrCode\Renderer\Image\Svg' => __DIR__ . '/src/BaconQrCode/Renderer/Image/Svg.php',
'BaconQrCode\Renderer\RendererInterface' => __DIR__ . '/src/BaconQrCode/Renderer/RendererInterface.php',
'BaconQrCode\Renderer\Text\Plain' => __DIR__ . '/src/BaconQrCode/Renderer/Text/Plain.php',
'BaconQrCode\Renderer\Text\Html' => __DIR__ . '/src/BaconQrCode/Renderer/Text/Html.php',
'BaconQrCode\Writer' => __DIR__ . '/src/BaconQrCode/Writer.php',
);
\ No newline at end of file
<?php
return function ($class) {
static $map;
if (!$map) {
$map = include __DIR__ . '/autoload_classmap.php';
}
if (!isset($map[$class])) {
return false;
}
return include $map[$class];
};
\ No newline at end of file
<?php
spl_autoload_register(include __DIR__ . '/autoload_function.php');
{
"name": "bacon/bacon-qr-code",
"description": "BaconQrCode is a QR code generator for PHP.",
"license" : "BSD-2-Clause",
"homepage": "https://github.com/Bacon/BaconQrCode",
"require": {
"php": "^5.4|^7.0",
"ext-iconv": "*"
},
"suggest": {
"ext-gd": "to generate QR code images"
},
"authors": [
{
"name": "Ben Scholzen 'DASPRiD'",
"email": "mail@dasprids.de",
"homepage": "http://www.dasprids.de",
"role": "Developer"
}
],
"autoload": {
"psr-0": {
"BaconQrCode": "src/"
}
},
"require-dev": {
"phpunit/phpunit": "^4.8"
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
use BaconQrCode\Exception;
use ReflectionClass;
/**
* A general enum implementation until we got SplEnum.
*/
abstract class AbstractEnum
{
/**
* Default value.
*/
const __default = null;
/**
* Current value.
*
* @var mixed
*/
protected $value;
/**
* Cache of constants.
*
* @var array
*/
protected $constants;
/**
* Whether to handle values strict or not.
*
* @var boolean
*/
protected $strict;
/**
* Creates a new enum.
*
* @param mixed $initialValue
* @param boolean $strict
*/
public function __construct($initialValue = null, $strict = false)
{
$this->strict = $strict;
$this->change($initialValue);
}
/**
* Changes the value of the enum.
*
* @param mixed $value
* @return void
*/
public function change($value)
{
if (!in_array($value, $this->getConstList(), $this->strict)) {
throw new Exception\UnexpectedValueException('Value not a const in enum ' . get_class($this));
}
$this->value = $value;
}
/**
* Gets current value.
*
* @return mixed
*/
public function get()
{
return $this->value;
}
/**
* Gets all constants (possible values) as an array.
*
* @param boolean $includeDefault
* @return array
*/
public function getConstList($includeDefault = true)
{
if ($this->constants === null) {
$reflection = new ReflectionClass($this);
$this->constants = $reflection->getConstants();
}
if ($includeDefault) {
return $this->constants;
}
$constants = $this->constants;
unset($constants['__default']);
return $constants;
}
/**
* Gets the name of the enum.
*
* @return string
*/
public function __toString()
{
return array_search($this->value, $this->getConstList());
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
use SplFixedArray;
/**
* Bit matrix.
*
* Represents a 2D matrix of bits. In function arguments below, and throughout
* the common module, x is the column position, and y is the row position. The
* ordering is always x, y. The origin is at the top-left.
*/
class BitMatrix
{
/**
* Width of the bit matrix.
*
* @var integer
*/
protected $width;
/**
* Height of the bit matrix.
*
* @var integer
*/
protected $height;
/**
* Size in bits of each individual row.
*
* @var integer
*/
protected $rowSize;
/**
* Bits representation.
*
* @var SplFixedArray
*/
protected $bits;
/**
* Creates a new bit matrix with given dimensions.
*
* @param integer $width
* @param integer|null $height
* @throws Exception\InvalidArgumentException
*/
public function __construct($width, $height = null)
{
if ($height === null) {
$height = $width;
}
if ($width < 1 || $height < 1) {
throw new Exception\InvalidArgumentException('Both dimensions must be greater than zero');
}
$this->width = $width;
$this->height = $height;
$this->rowSize = ($width + 31) >> 5;
$this->bits = new SplFixedArray($this->rowSize * $height);
}
/**
* Gets the requested bit, where true means black.
*
* @param integer $x
* @param integer $y
* @return boolean
*/
public function get($x, $y)
{
$offset = $y * $this->rowSize + ($x >> 5);
return (BitUtils::unsignedRightShift($this->bits[$offset], ($x & 0x1f)) & 1) !== 0;
}
/**
* Sets the given bit to true.
*
* @param integer $x
* @param integer $y
* @return void
*/
public function set($x, $y)
{
$offset = $y * $this->rowSize + ($x >> 5);
$this->bits[$offset] = $this->bits[$offset] | (1 << ($x & 0x1f));
}
/**
* Flips the given bit.
*
* @param integer $x
* @param integer $y
* @return void
*/
public function flip($x, $y)
{
$offset = $y * $this->rowSize + ($x >> 5);
$this->bits[$offset] = $this->bits[$offset] ^ (1 << ($x & 0x1f));
}
/**
* Clears all bits (set to false).
*
* @return void
*/
public function clear()
{
$max = count($this->bits);
for ($i = 0; $i < $max; $i++) {
$this->bits[$i] = 0;
}
}
/**
* Sets a square region of the bit matrix to true.
*
* @param integer $left
* @param integer $top
* @param integer $width
* @param integer $height
* @return void
*/
public function setRegion($left, $top, $width, $height)
{
if ($top < 0 || $left < 0) {
throw new Exception\InvalidArgumentException('Left and top must be non-negative');
}
if ($height < 1 || $width < 1) {
throw new Exception\InvalidArgumentException('Width and height must be at least 1');
}
$right = $left + $width;
$bottom = $top + $height;
if ($bottom > $this->height || $right > $this->width) {
throw new Exception\InvalidArgumentException('The region must fit inside the matrix');
}
for ($y = $top; $y < $bottom; $y++) {
$offset = $y * $this->rowSize;
for ($x = $left; $x < $right; $x++) {
$index = $offset + ($x >> 5);
$this->bits[$index] = $this->bits[$index] | (1 << ($x & 0x1f));
}
}
}
/**
* A fast method to retrieve one row of data from the matrix as a BitArray.
*
* @param integer $y
* @param BitArray $row
* @return BitArray
*/
public function getRow($y, BitArray $row = null)
{
if ($row === null || $row->getSize() < $this->width) {
$row = new BitArray($this->width);
}
$offset = $y * $this->rowSize;
for ($x = 0; $x < $this->rowSize; $x++) {
$row->setBulk($x << 5, $this->bits[$offset + $x]);
}
return $row;
}
/**
* Sets a row of data from a BitArray.
*
* @param integer $y
* @param BitArray $row
* @return void
*/
public function setRow($y, BitArray $row)
{
$bits = $row->getBitArray();
for ($i = 0; $i < $this->rowSize; $i++) {
$this->bits[$y * $this->rowSize + $i] = $bits[$i];
}
}
/**
* This is useful in detecting the enclosing rectangle of a 'pure' barcode.
*
* @return SplFixedArray
*/
public function getEnclosingRectangle()
{
$left = $this->width;
$top = $this->height;
$right = -1;
$bottom = -1;
for ($y = 0; $y < $this->height; $y++) {
for ($x32 = 0; $x32 < $this->rowSize; $x32++) {
$bits = $this->bits[$y * $this->rowSize + $x32];
if ($bits !== 0) {
if ($y < $top) {
$top = $y;
}
if ($y > $bottom) {
$bottom = $y;
}
if ($x32 * 32 < $left) {
$bit = 0;
while (($bits << (31 - $bit)) === 0) {
$bit++;
}
if (($x32 * 32 + $bit) < $left) {
$left = $x32 * 32 + $bit;
}
}
}
if ($x32 * 32 + 31 > $right) {
$bit = 31;
while (BitUtils::unsignedRightShift($bits, $bit) === 0) {
$bit--;
}
if (($x32 * 32 + $bit) > $right) {
$right = $x32 * 32 + $bit;
}
}
}
}
$width = $right - $left;
$height = $bottom - $top;
if ($width < 0 || $height < 0) {
return null;
}
return SplFixedArray::fromArray(array($left, $top, $width, $height), false);
}
/**
* Gets the most top left set bit.
*
* This is useful in detecting a corner of a 'pure' barcode.
*
* @return SplFixedArray
*/
public function getTopLeftOnBit()
{
$bitsOffset = 0;
while ($bitsOffset < count($this->bits) && $this->bits[$bitsOffset] === 0) {
$bitsOffset++;
}
if ($bitsOffset === count($this->bits)) {
return null;
}
$x = intval($bitsOffset / $this->rowSize);
$y = ($bitsOffset % $this->rowSize) << 5;
$bits = $this->bits[$bitsOffset];
$bit = 0;
while (($bits << (31 - $bit)) === 0) {
$bit++;
}
$x += $bit;
return SplFixedArray::fromArray(array($x, $y), false);
}
/**
* Gets the most bottom right set bit.
*
* This is useful in detecting a corner of a 'pure' barcode.
*
* @return SplFixedArray
*/
public function getBottomRightOnBit()
{
$bitsOffset = count($this->bits) - 1;
while ($bitsOffset >= 0 && $this->bits[$bitsOffset] === 0) {
$bitsOffset--;
}
if ($bitsOffset < 0) {
return null;
}
$x = intval($bitsOffset / $this->rowSize);
$y = ($bitsOffset % $this->rowSize) << 5;
$bits = $this->bits[$bitsOffset];
$bit = 0;
while (BitUtils::unsignedRightShift($bits, $bit) === 0) {
$bit--;
}
$x += $bit;
return SplFixedArray::fromArray(array($x, $y), false);
}
/**
* Gets the width of the matrix,
*
* @return integer
*/
public function getWidth()
{
return $this->width;
}
/**
* Gets the height of the matrix.
*
* @return integer
*/
public function getHeight()
{
return $this->height;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
/**
* General bit utilities.
*
* All utility methods are based on 32-bit integers and also work on 64-bit
* systems.
*/
class BitUtils
{
/**
* Performs an unsigned right shift.
*
* This is the same as the unsigned right shift operator ">>>" in other
* languages.
*
* @param integer $a
* @param integer $b
* @return integer
*/
public static function unsignedRightShift($a, $b)
{
return (
$a >= 0
? $a >> $b
: (($a & 0x7fffffff) >> $b) | (0x40000000 >> ($b - 1))
);
}
/**
* Gets the number of trailing zeros.
*
* @param integer $i
* @return integer
*/
public static function numberOfTrailingZeros($i)
{
$lastPos = strrpos(str_pad(decbin($i), 32, '0', STR_PAD_LEFT), '1');
return $lastPos === false ? 32 : 31 - $lastPos;
}
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
/**
* Encapsulates a Character Set ECI, according to "Extended Channel
* Interpretations" 5.3.1.1 of ISO 18004.
*/
class CharacterSetEci extends AbstractEnum
{
/**#@+
* Character set constants.
*/
const CP437 = 0;
const ISO8859_1 = 1;
const ISO8859_2 = 4;
const ISO8859_3 = 5;
const ISO8859_4 = 6;
const ISO8859_5 = 7;
const ISO8859_6 = 8;
const ISO8859_7 = 9;
const ISO8859_8 = 10;
const ISO8859_9 = 11;
const ISO8859_10 = 12;
const ISO8859_11 = 13;
const ISO8859_12 = 14;
const ISO8859_13 = 15;
const ISO8859_14 = 16;
const ISO8859_15 = 17;
const ISO8859_16 = 18;
const SJIS = 20;
const CP1250 = 21;
const CP1251 = 22;
const CP1252 = 23;
const CP1256 = 24;
const UNICODE_BIG_UNMARKED = 25;
const UTF8 = 26;
const ASCII = 27;
const BIG5 = 28;
const GB18030 = 29;
const EUC_KR = 30;
/**#@-*/
/**
* Map between character names and their ECI values.
*
* @var array
*/
protected static $nameToEci = array(
'ISO-8859-1' => self::ISO8859_1,
'ISO-8859-2' => self::ISO8859_2,
'ISO-8859-3' => self::ISO8859_3,
'ISO-8859-4' => self::ISO8859_4,
'ISO-8859-5' => self::ISO8859_5,
'ISO-8859-6' => self::ISO8859_6,
'ISO-8859-7' => self::ISO8859_7,
'ISO-8859-8' => self::ISO8859_8,
'ISO-8859-9' => self::ISO8859_9,
'ISO-8859-10' => self::ISO8859_10,
'ISO-8859-11' => self::ISO8859_11,
'ISO-8859-12' => self::ISO8859_12,
'ISO-8859-13' => self::ISO8859_13,
'ISO-8859-14' => self::ISO8859_14,
'ISO-8859-15' => self::ISO8859_15,
'ISO-8859-16' => self::ISO8859_16,
'SHIFT-JIS' => self::SJIS,
'WINDOWS-1250' => self::CP1250,
'WINDOWS-1251' => self::CP1251,
'WINDOWS-1252' => self::CP1252,
'WINDOWS-1256' => self::CP1256,
'UTF-16BE' => self::UNICODE_BIG_UNMARKED,
'UTF-8' => self::UTF8,
'ASCII' => self::ASCII,
'GBK' => self::GB18030,
'EUC-KR' => self::EUC_KR,
);
/**
* Additional possible values for character sets.
*
* @var array
*/
protected $additionalValues = array(
self::CP437 => 2,
self::ASCII => 170,
);
/**
* Gets character set ECI by value.
*
* @param string $name
* @return CharacterSetEci|null
*/
public static function getCharacterSetECIByValue($value)
{
if ($value < 0 || $value >= 900) {
throw new Exception\InvalidArgumentException('Value must be between 0 and 900');
}
if (false !== ($key = array_search($value, self::$additionalValues))) {
$value = $key;
}
try {
return new self($value);
} catch (Exception\UnexpectedValueException $e) {
return null;
}
}
/**
* Gets character set ECI by name.
*
* @param string $name
* @return CharacterSetEci|null
*/
public static function getCharacterSetECIByName($name)
{
$name = strtoupper($name);
if (isset(self::$nameToEci[$name])) {
return new self(self::$nameToEci[$name]);
}
return null;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
/**
* Encapsualtes the parameters for one error-correction block in one symbol
* version. This includes the number of data codewords, and the number of times
* a block with these parameters is used consecutively in the QR code version's
* format.
*/
class EcBlock
{
/**
* How many times the block is used.
*
* @var integer
*/
protected $count;
/**
* Number of data codewords.
*
* @var integer
*/
protected $dataCodewords;
/**
* Creates a new EC block.
*
* @param integer $count
* @param integer $dataCodewords
*/
public function __construct($count, $dataCodewords)
{
$this->count = $count;
$this->dataCodewords = $dataCodewords;
}
/**
* Returns how many times the block is used.
*
* @return integer
*/
public function getCount()
{
return $this->count;
}
/**
* Returns the number of data codewords.
*
* @return integer
*/
public function getDataCodewords()
{
return $this->dataCodewords;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
use SplFixedArray;
/**
* Encapsulates a set of error-correction blocks in one symbol version. Most
* versions will use blocks of differing sizes within one version, so, this
* encapsulates the parameters for each set of blocks. It also holds the number
* of error-correction codewords per block since it will be the same across all
* blocks within one version.
*/
class EcBlocks
{
/**
* Number of EC codewords per block.
*
* @var integer
*/
protected $ecCodewordsPerBlock;
/**
* List of EC blocks.
*
* @var SplFixedArray
*/
protected $ecBlocks;
/**
* Creates a new EC blocks instance.
*
* @param integer $ecCodewordsPerBlock
* @param EcBlock $ecb1
* @param EcBlock|null $ecb2
*/
public function __construct($ecCodewordsPerBlock, EcBlock $ecb1, EcBlock $ecb2 = null)
{
$this->ecCodewordsPerBlock = $ecCodewordsPerBlock;
$this->ecBlocks = new SplFixedArray($ecb2 === null ? 1 : 2);
$this->ecBlocks[0] = $ecb1;
if ($ecb2 !== null) {
$this->ecBlocks[1] = $ecb2;
}
}
/**
* Gets the number of EC codewords per block.
*
* @return integer
*/
public function getEcCodewordsPerBlock()
{
return $this->ecCodewordsPerBlock;
}
/**
* Gets the total number of EC block appearances.
*
* @return integer
*/
public function getNumBlocks()
{
$total = 0;
foreach ($this->ecBlocks as $ecBlock) {
$total += $ecBlock->getCount();
}
return $total;
}
/**
* Gets the total count of EC codewords.
*
* @return integer
*/
public function getTotalEcCodewords()
{
return $this->ecCodewordsPerBlock * $this->getNumBlocks();
}
/**
* Gets the EC blocks included in this collection.
*
* @return SplFixedArray
*/
public function getEcBlocks()
{
return $this->ecBlocks;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
/**
* Enum representing the four error correction levels.
*/
class ErrorCorrectionLevel extends AbstractEnum
{
/**
* Level L, ~7% correction.
*/
const L = 0x1;
/**
* Level M, ~15% correction.
*/
const M = 0x0;
/**
* Level Q, ~25% correction.
*/
const Q = 0x3;
/**
* Level H, ~30% correction.
*/
const H = 0x2;
/**
* Gets the ordinal of this enumeration constant.
*
* @return integer
*/
public function getOrdinal()
{
switch ($this->value) {
case self::L:
return 0;
break;
case self::M:
return 1;
break;
case self::Q:
return 2;
break;
case self::H:
return 3;
break;
}
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
/**
* Encapsulates a QR Code's format information, including the data mask used and
* error correction level.
*/
class FormatInformation
{
/**
* Mask for format information.
*/
const FORMAT_INFO_MASK_QR = 0x5412;
/**
* Lookup table for decoding format information.
*
* See ISO 18004:2006, Annex C, Table C.1
*
* @var array
*/
protected static $formatInfoDecodeLookup = array(
array(0x5412, 0x00),
array(0x5125, 0x01),
array(0x5e7c, 0x02),
array(0x5b4b, 0x03),
array(0x45f9, 0x04),
array(0x40ce, 0x05),
array(0x4f97, 0x06),
array(0x4aa0, 0x07),
array(0x77c4, 0x08),
array(0x72f3, 0x09),
array(0x7daa, 0x0a),
array(0x789d, 0x0b),
array(0x662f, 0x0c),
array(0x6318, 0x0d),
array(0x6c41, 0x0e),
array(0x6976, 0x0f),
array(0x1689, 0x10),
array(0x13be, 0x11),
array(0x1ce7, 0x12),
array(0x19d0, 0x13),
array(0x0762, 0x14),
array(0x0255, 0x15),
array(0x0d0c, 0x16),
array(0x083b, 0x17),
array(0x355f, 0x18),
array(0x3068, 0x19),
array(0x3f31, 0x1a),
array(0x3a06, 0x1b),
array(0x24b4, 0x1c),
array(0x2183, 0x1d),
array(0x2eda, 0x1e),
array(0x2bed, 0x1f),
);
/**
* Offset i holds the number of 1 bits in the binary representation of i.
*
* @var array
*/
protected static $bitsSetInHalfByte = array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4);
/**
* Error correction level.
*
* @var ErrorCorrectionLevel
*/
protected $ecLevel;
/**
* Data mask.
*
* @var integer
*/
protected $dataMask;
/**
* Creates a new format information instance.
*
* @param integer $formatInfo
*/
protected function __construct($formatInfo)
{
$this->ecLevel = new ErrorCorrectionLevel(($formatInfo >> 3) & 0x3);
$this->dataMask = $formatInfo & 0x7;
}
/**
* Checks how many bits are different between two integers.
*
* @param integer $a
* @param integer $b
* @return integer
*/
public static function numBitsDiffering($a, $b)
{
$a ^= $b;
return (
self::$bitsSetInHalfByte[$a & 0xf]
+ self::$bitsSetInHalfByte[(BitUtils::unsignedRightShift($a, 4) & 0xf)]
+ self::$bitsSetInHalfByte[(BitUtils::unsignedRightShift($a, 8) & 0xf)]
+ self::$bitsSetInHalfByte[(BitUtils::unsignedRightShift($a, 12) & 0xf)]
+ self::$bitsSetInHalfByte[(BitUtils::unsignedRightShift($a, 16) & 0xf)]
+ self::$bitsSetInHalfByte[(BitUtils::unsignedRightShift($a, 20) & 0xf)]
+ self::$bitsSetInHalfByte[(BitUtils::unsignedRightShift($a, 24) & 0xf)]
+ self::$bitsSetInHalfByte[(BitUtils::unsignedRightShift($a, 28) & 0xf)]
);
}
/**
* Decodes format information.
*
* @param integer $maskedFormatInfo1
* @param integer $maskedFormatInfo2
* @return FormatInformation|null
*/
public static function decodeFormatInformation($maskedFormatInfo1, $maskedFormatInfo2)
{
$formatInfo = self::doDecodeFormatInformation($maskedFormatInfo1, $maskedFormatInfo2);
if ($formatInfo !== null) {
return $formatInfo;
}
// Should return null, but, some QR codes apparently do not mask this
// info. Try again by actually masking the pattern first.
return self::doDecodeFormatInformation(
$maskedFormatInfo1 ^ self::FORMAT_INFO_MASK_QR,
$maskedFormatInfo2 ^ self::FORMAT_INFO_MASK_QR
);
}
/**
* Internal method for decoding format information.
*
* @param integer $maskedFormatInfo1
* @param integer $maskedFormatInfo2
* @return FormatInformation|null
*/
protected static function doDecodeFormatInformation($maskedFormatInfo1, $maskedFormatInfo2)
{
$bestDifference = PHP_INT_MAX;
$bestFormatInfo = 0;
foreach (self::$formatInfoDecodeLookup as $decodeInfo) {
$targetInfo = $decodeInfo[0];
if ($targetInfo === $maskedFormatInfo1 || $targetInfo === $maskedFormatInfo2) {
// Found an exact match
return new self($decodeInfo[1]);
}
$bitsDifference = self::numBitsDiffering($maskedFormatInfo1, $targetInfo);
if ($bitsDifference < $bestDifference) {
$bestFormatInfo = $decodeInfo[1];
$bestDifference = $bitsDifference;
}
if ($maskedFormatInfo1 !== $maskedFormatInfo2) {
// Also try the other option
$bitsDifference = self::numBitsDiffering($maskedFormatInfo2, $targetInfo);
if ($bitsDifference < $bestDifference) {
$bestFormatInfo = $decodeInfo[1];
$bestDifference = $bitsDifference;
}
}
}
// Hamming distance of the 32 masked codes is 7, by construction, so
// <= 3 bits differing means we found a match.
if ($bestDifference <= 3) {
return new self($bestFormatInfo);
}
return null;
}
/**
* Gets the error correction level.
*
* @return ErrorCorrectionLevel
*/
public function getErrorCorrectionLevel()
{
return $this->ecLevel;
}
/**
* Gets the data mask.
*
* @return integer
*/
public function getDataMask()
{
return $this->dataMask;
}
/**
* Hashes the code of the EC level.
*
* @return integer
*/
public function hashCode()
{
return ($this->ecLevel->get() << 3) | $this->dataMask;
}
/**
* Verifies if this instance equals another one.
*
* @param mixed $other
* @return boolean
*/
public function equals($other) {
if (!$other instanceof self) {
return false;
}
return (
$this->ecLevel->get() === $other->getErrorCorrectionLevel()->get()
&& $this->dataMask === $other->getDataMask()
);
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Common;
/**
* Enum representing various modes in which data can be encoded to bits.
*/
class Mode extends AbstractEnum
{
/**#@+
* Mode constants.
*/
const TERMINATOR = 0x0;
const NUMERIC = 0x1;
const ALPHANUMERIC = 0x2;
const STRUCTURED_APPEND = 0x3;
const BYTE = 0x4;
const ECI = 0x7;
const KANJI = 0x8;
const FNC1_FIRST_POSITION = 0x5;
const FNC1_SECOND_POSITION = 0x9;
const HANZI = 0xd;
/**#@-*/
/**
* Character count bits for each version.
*
* @var array
*/
protected static $characterCountBitsForVersions = array(
self::TERMINATOR => array(0, 0, 0),
self::NUMERIC => array(10, 12, 14),
self::ALPHANUMERIC => array(9, 11, 13),
self::STRUCTURED_APPEND => array(0, 0, 0),
self::BYTE => array(8, 16, 16),
self::ECI => array(0, 0, 0),
self::KANJI => array(8, 10, 12),
self::FNC1_FIRST_POSITION => array(0, 0, 0),
self::FNC1_SECOND_POSITION => array(0, 0, 0),
self::HANZI => array(8, 10, 12),
);
/**
* Gets the number of bits used in a specific QR code version.
*
* @param Version $version
* @return integer
*/
public function getCharacterCountBits(Version $version)
{
$number = $version->getVersionNumber();
if ($number <= 9) {
$offset = 0;
} elseif ($number <= 26) {
$offset = 1;
} else {
$offset = 2;
}
return self::$characterCountBitsForVersions[$this->value][$offset];
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Encoder;
use SplFixedArray;
/**
* Block pair.
*/
class BlockPair
{
/**
* Data bytes in the block.
*
* @var SplFixedArray
*/
protected $dataBytes;
/**
* Error correction bytes in the block.
*
* @var SplFixedArray
*/
protected $errorCorrectionBytes;
/**
* Creates a new block pair.
*
* @param SplFixedArray $data
* @param SplFixedArray $errorCorrection
*/
public function __construct(SplFixedArray $data, SplFixedArray $errorCorrection)
{
$this->dataBytes = $data;
$this->errorCorrectionBytes = $errorCorrection;
}
/**
* Gets the data bytes.
*
* @return SplFixedArray
*/
public function getDataBytes()
{
return $this->dataBytes;
}
/**
* Gets the error correction bytes.
*
* @return SplFixedArray
*/
public function getErrorCorrectionBytes()
{
return $this->errorCorrectionBytes;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Encoder;
use SplFixedArray;
/**
* Byte matrix.
*/
class ByteMatrix
{
/**
* Bytes in the matrix, represented as array.
*
* @var SplFixedArray
*/
protected $bytes;
/**
* Width of the matrix.
*
* @var integer
*/
protected $width;
/**
* Height of the matrix.
*
* @var integer
*/
protected $height;
/**
* Creates a new byte matrix.
*
* @param integer $width
* @param integer $height
*/
public function __construct($width, $height)
{
$this->height = $height;
$this->width = $width;
$this->bytes = new SplFixedArray($height);
for ($y = 0; $y < $height; $y++) {
$this->bytes[$y] = new SplFixedArray($width);
}
}
/**
* Gets the width of the matrix.
*
* @return integer
*/
public function getWidth()
{
return $this->width;
}
/**
* Gets the height of the matrix.
*
* @return integer
*/
public function getHeight()
{
return $this->height;
}
/**
* Gets the internal representation of the matrix.
*
* @return SplFixedArray
*/
public function getArray()
{
return $this->bytes;
}
/**
* Gets the byte for a specific position.
*
* @param integer $x
* @param integer $y
* @return integer
*/
public function get($x, $y)
{
return $this->bytes[$y][$x];
}
/**
* Sets the byte for a specific position.
*
* @param integer $x
* @param integer $y
* @param integer $value
* @return void
*/
public function set($x, $y, $value)
{
$this->bytes[$y][$x] = (int) $value;
}
/**
* Clears the matrix with a specific value.
*
* @param integer $value
* @return void
*/
public function clear($value)
{
for ($y = 0; $y < $this->height; $y++) {
for ($x = 0; $x < $this->width; $x++) {
$this->bytes[$y][$x] = $value;
}
}
}
/**
* Returns a string representation of the matrix.
*
* @return string
*/
public function __toString()
{
$result = '';
for ($y = 0; $y < $this->height; $y++) {
for ($x = 0; $x < $this->width; $x++) {
switch ($this->bytes[$y][$x]) {
case 0:
$result .= ' 0';
break;
case 1:
$result .= ' 1';
break;
default:
$result .= ' ';
break;
}
}
$result .= "\n";
}
return $result;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Encoder;
use BaconQrCode\Common\BitUtils;
/**
* Mask utility.
*/
class MaskUtil
{
/**#@+
* Penalty weights from section 6.8.2.1
*/
const N1 = 3;
const N2 = 3;
const N3 = 40;
const N4 = 10;
/**#@-*/
/**
* Applies mask penalty rule 1 and returns the penalty.
*
* Finds repetitive cells with the same color and gives penalty to them.
* Example: 00000 or 11111.
*
* @param ByteMatrix $matrix
* @return integer
*/
public static function applyMaskPenaltyRule1(ByteMatrix $matrix)
{
return (
self::applyMaskPenaltyRule1Internal($matrix, true)
+ self::applyMaskPenaltyRule1Internal($matrix, false)
);
}
/**
* Applies mask penalty rule 2 and returns the penalty.
*
* Finds 2x2 blocks with the same color and gives penalty to them. This is
* actually equivalent to the spec's rule, which is to find MxN blocks and
* give a penalty proportional to (M-1)x(N-1), because this is the number of
* 2x2 blocks inside such a block.
*
* @param ByteMatrix $matrix
* @return integer
*/
public static function applyMaskPenaltyRule2(ByteMatrix $matrix)
{
$penalty = 0;
$array = $matrix->getArray();
$width = $matrix->getWidth();
$height = $matrix->getHeight();
for ($y = 0; $y < $height - 1; $y++) {
for ($x = 0; $x < $width - 1; $x++) {
$value = $array[$y][$x];
if ($value === $array[$y][$x + 1] && $value === $array[$y + 1][$x] && $value === $array[$y + 1][$x + 1]) {
$penalty++;
}
}
}
return self::N2 * $penalty;
}
/**
* Applies mask penalty rule 3 and returns the penalty.
*
* Finds consecutive cells of 00001011101 or 10111010000, and gives penalty
* to them. If we find patterns like 000010111010000, we give penalties
* twice (i.e. 40 * 2).
*
* @param ByteMatrix $matrix
* @return integer
*/
public static function applyMaskPenaltyRule3(ByteMatrix $matrix)
{
$penalty = 0;
$array = $matrix->getArray();
$width = $matrix->getWidth();
$height = $matrix->getHeight();
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
if (
$x + 6 < $width
&& $array[$y][$x] === 1
&& $array[$y][$x + 1] === 0
&& $array[$y][$x + 2] === 1
&& $array[$y][$x + 3] === 1
&& $array[$y][$x + 4] === 1
&& $array[$y][$x + 5] === 0
&& $array[$y][$x + 6] === 1
&& (
(
$x + 10 < $width
&& $array[$y][$x + 7] === 0
&& $array[$y][$x + 8] === 0
&& $array[$y][$x + 9] === 0
&& $array[$y][$x + 10] === 0
)
|| (
$x - 4 >= 0
&& $array[$y][$x - 1] === 0
&& $array[$y][$x - 2] === 0
&& $array[$y][$x - 3] === 0
&& $array[$y][$x - 4] === 0
)
)
) {
$penalty += self::N3;
}
if (
$y + 6 < $height
&& $array[$y][$x] === 1
&& $array[$y + 1][$x] === 0
&& $array[$y + 2][$x] === 1
&& $array[$y + 3][$x] === 1
&& $array[$y + 4][$x] === 1
&& $array[$y + 5][$x] === 0
&& $array[$y + 6][$x] === 1
&& (
(
$y + 10 < $height
&& $array[$y + 7][$x] === 0
&& $array[$y + 8][$x] === 0
&& $array[$y + 9][$x] === 0
&& $array[$y + 10][$x] === 0
)
|| (
$y - 4 >= 0
&& $array[$y - 1][$x] === 0
&& $array[$y - 2][$x] === 0
&& $array[$y - 3][$x] === 0
&& $array[$y - 4][$x] === 0
)
)
) {
$penalty += self::N3;
}
}
}
return $penalty;
}
/**
* Applies mask penalty rule 4 and returns the penalty.
*
* Calculates the ratio of dark cells and gives penalty if the ratio is far
* from 50%. It gives 10 penalty for 5% distance.
*
* @param ByteMatrix $matrix
* @return integer
*/
public static function applyMaskPenaltyRule4(ByteMatrix $matrix)
{
$numDarkCells = 0;
$array = $matrix->getArray();
$width = $matrix->getWidth();
$height = $matrix->getHeight();
for ($y = 0; $y < $height; $y++) {
$arrayY = $array[$y];
for ($x = 0; $x < $width; $x++) {
if ($arrayY[$x] === 1) {
$numDarkCells++;
}
}
}
$numTotalCells = $height * $width;
$darkRatio = $numDarkCells / $numTotalCells;
$fixedPercentVariances = (int) (abs($darkRatio - 0.5) * 20);
return $fixedPercentVariances * self::N4;
}
/**
* Returns the mask bit for "getMaskPattern" at "x" and "y".
*
* See 8.8 of JISX0510:2004 for mask pattern conditions.
*
* @param integer $maskPattern
* @param integer $x
* @param integer $y
* @return integer
* @throws Exception\InvalidArgumentException
*/
public static function getDataMaskBit($maskPattern, $x, $y)
{
switch ($maskPattern) {
case 0:
$intermediate = ($y + $x) & 0x1;
break;
case 1:
$intermediate = $y & 0x1;
break;
case 2:
$intermediate = $x % 3;
break;
case 3:
$intermediate = ($y + $x) % 3;
break;
case 4:
$intermediate = (BitUtils::unsignedRightShift($y, 1) + ($x / 3)) & 0x1;
break;
case 5:
$temp = $y * $x;
$intermediate = ($temp & 0x1) + ($temp % 3);
break;
case 6:
$temp = $y * $x;
$intermediate = (($temp & 0x1) + ($temp % 3)) & 0x1;
break;
case 7:
$temp = $y * $x;
$intermediate = (($temp % 3) + (($y + $x) & 0x1)) & 0x1;
break;
default:
throw new Exception\InvalidArgumentException('Invalid mask pattern: ' . $maskPattern);
}
return $intermediate === 0;
}
/**
* Helper function for applyMaskPenaltyRule1.
*
* We need this for doing this calculation in both vertical and horizontal
* orders respectively.
*
* @param ByteMatrix $matrix
* @param boolean $isHorizontal
* @return integer
*/
protected static function applyMaskPenaltyRule1Internal(ByteMatrix $matrix, $isHorizontal)
{
$penalty = 0;
$iLimit = $isHorizontal ? $matrix->getHeight() : $matrix->getWidth();
$jLimit = $isHorizontal ? $matrix->getWidth() : $matrix->getHeight();
$array = $matrix->getArray();
for ($i = 0; $i < $iLimit; $i++) {
$numSameBitCells = 0;
$prevBit = -1;
for ($j = 0; $j < $jLimit; $j++) {
$bit = $isHorizontal ? $array[$i][$j] : $array[$j][$i];
if ($bit === $prevBit) {
$numSameBitCells++;
} else {
if ($numSameBitCells >= 5) {
$penalty += self::N1 + ($numSameBitCells - 5);
}
$numSameBitCells = 1;
$prevBit = $bit;
}
}
if ($numSameBitCells >= 5) {
$penalty += self::N1 + ($numSameBitCells - 5);
}
}
return $penalty;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Encoder;
use BaconQrCode\Common\ErrorCorrectionLevel;
use BaconQrCode\Common\Mode;
use BaconQrCode\Common\Version;
/**
* QR code.
*/
class QrCode
{
/**
* Number of possible mask patterns.
*/
const NUM_MASK_PATTERNS = 8;
/**
* Mode of the QR code.
*
* @var Mode
*/
protected $mode;
/**
* EC level of the QR code.
*
* @var ErrorCorrectionLevel
*/
protected $errorCorrectionLevel;
/**
* Version of the QR code.
*
* @var Version
*/
protected $version;
/**
* Mask pattern of the QR code.
*
* @var integer
*/
protected $maskPattern = -1;
/**
* Matrix of the QR code.
*
* @var ByteMatrix
*/
protected $matrix;
/**
* Gets the mode.
*
* @return Mode
*/
public function getMode()
{
return $this->mode;
}
/**
* Sets the mode.
*
* @param Mode $mode
* @return void
*/
public function setMode(Mode $mode)
{
$this->mode = $mode;
}
/**
* Gets the EC level.
*
* @return ErrorCorrectionLevel
*/
public function getErrorCorrectionLevel()
{
return $this->errorCorrectionLevel;
}
/**
* Sets the EC level.
*
* @param ErrorCorrectionLevel $errorCorrectionLevel
* @return void
*/
public function setErrorCorrectionLevel(ErrorCorrectionLevel $errorCorrectionLevel)
{
$this->errorCorrectionLevel = $errorCorrectionLevel;
}
/**
* Gets the version.
*
* @return Version
*/
public function getVersion()
{
return $this->version;
}
/**
* Sets the version.
*
* @param Version $version
* @return void
*/
public function setVersion(Version $version)
{
$this->version = $version;
}
/**
* Gets the mask pattern.
*
* @return integer
*/
public function getMaskPattern()
{
return $this->maskPattern;
}
/**
* Sets the mask pattern.
*
* @param integer $maskPattern
* @return void
*/
public function setMaskPattern($maskPattern)
{
$this->maskPattern = $maskPattern;
}
/**
* Gets the matrix.
*
* @return ByteMatrix
*/
public function getMatrix()
{
return $this->matrix;
}
/**
* Sets the matrix.
*
* @param ByteMatrix $matrix
* @return void
*/
public function setMatrix(ByteMatrix $matrix)
{
$this->matrix = $matrix;
}
/**
* Validates whether a mask pattern is valid.
*
* @param integer $maskPattern
* @return boolean
*/
public static function isValidMaskPattern($maskPattern)
{
return $maskPattern > 0 && $maskPattern < self::NUM_MASK_PATTERNS;
}
/**
* Returns a string representation of the QR code.
*
* @return string
*/
public function __toString()
{
$result = "<<\n"
. " mode: " . $this->mode . "\n"
. " ecLevel: " . $this->errorCorrectionLevel . "\n"
. " version: " . $this->version . "\n"
. " maskPattern: " . $this->maskPattern . "\n";
if ($this->matrix === null) {
$result .= " matrix: null\n";
} else {
$result .= " matrix:\n";
$result .= $this->matrix;
}
$result .= ">>\n";
return $result;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Exception;
interface ExceptionInterface
{
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Exception;
class OutOfBoundsException extends \OutOfBoundsException implements ExceptionInterface
{
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Exception;
class UnexpectedValueException extends \UnexpectedValueException implements ExceptionInterface
{
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Exception;
class WriterException extends \RuntimeException implements ExceptionInterface
{
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Color;
use BaconQrCode\Exception;
/**
* CMYK color.
*/
class Cmyk implements ColorInterface
{
/**
* Cyan value.
*
* @var integer
*/
protected $cyan;
/**
* Magenta value.
*
* @var integer
*/
protected $magenta;
/**
* Yellow value.
*
* @var integer
*/
protected $yellow;
/**
* Black value.
*
* @var integer
*/
protected $black;
/**
* Creates a new CMYK color.
*
* @param integer $cyan
* @param integer $magenta
* @param integer $yellow
* @param integer $black
*/
public function __construct($cyan, $magenta, $yellow, $black)
{
if ($cyan < 0 || $cyan > 100) {
throw new Exception\InvalidArgumentException('Cyan must be between 0 and 100');
}
if ($magenta < 0 || $magenta > 100) {
throw new Exception\InvalidArgumentException('Magenta must be between 0 and 100');
}
if ($yellow < 0 || $yellow > 100) {
throw new Exception\InvalidArgumentException('Yellow must be between 0 and 100');
}
if ($black < 0 || $black > 100) {
throw new Exception\InvalidArgumentException('Black must be between 0 and 100');
}
$this->cyan = (int) $cyan;
$this->magenta = (int) $magenta;
$this->yellow = (int) $yellow;
$this->black = (int) $black;
}
/**
* Returns the cyan value.
*
* @return integer
*/
public function getCyan()
{
return $this->cyan;
}
/**
* Returns the magenta value.
*
* @return integer
*/
public function getMagenta()
{
return $this->magenta;
}
/**
* Returns the yellow value.
*
* @return integer
*/
public function getYellow()
{
return $this->yellow;
}
/**
* Returns the black value.
*
* @return integer
*/
public function getBlack()
{
return $this->black;
}
/**
* toRgb(): defined by ColorInterface.
*
* @see ColorInterface::toRgb()
* @return Rgb
*/
public function toRgb()
{
$k = $this->black / 100;
$c = (-$k * $this->cyan + $k * 100 + $this->cyan) / 100;
$m = (-$k * $this->magenta + $k * 100 + $this->magenta) / 100;
$y = (-$k * $this->yellow + $k * 100 + $this->yellow) / 100;
return new Rgb(
-$c * 255 + 255,
-$m * 255 + 255,
-$y * 255 + 255
);
}
/**
* toCmyk(): defined by ColorInterface.
*
* @see ColorInterface::toCmyk()
* @return Cmyk
*/
public function toCmyk()
{
return $this;
}
/**
* toGray(): defined by ColorInterface.
*
* @see ColorInterface::toGray()
* @return Gray
*/
public function toGray()
{
return $this->toRgb()->toGray();
}
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Color;
/**
* Color interface.
*/
interface ColorInterface
{
/**
* Converts the color to RGB.
*
* @return Rgb
*/
public function toRgb();
/**
* Converts the color to CMYK.
*
* @return Cmyk
*/
public function toCmyk();
/**
* Converts the color to gray.
*
* @return Gray
*/
public function toGray();
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Color;
use BaconQrCode\Exception;
/**
* Gray color.
*/
class Gray implements ColorInterface
{
/**
* Gray value.
*
* @var integer
*/
protected $gray;
/**
* Creates a new gray color.
*
* A low gray value means black, while a high value means white.
*
* @param integer $gray
*/
public function __construct($gray)
{
if ($gray < 0 || $gray > 100) {
throw new Exception\InvalidArgumentException('Gray must be between 0 and 100');
}
$this->gray = (int) $gray;
}
/**
* Returns the gray value.
*
* @return integer
*/
public function getGray()
{
return $this->gray;
}
/**
* toRgb(): defined by ColorInterface.
*
* @see ColorInterface::toRgb()
* @return Rgb
*/
public function toRgb()
{
return new Rgb($this->gray * 2.55, $this->gray * 2.55, $this->gray * 2.55);
}
/**
* toCmyk(): defined by ColorInterface.
*
* @see ColorInterface::toCmyk()
* @return Cmyk
*/
public function toCmyk()
{
return new Cmyk(0, 0, 0, 100 - $this->gray);
}
/**
* toGray(): defined by ColorInterface.
*
* @see ColorInterface::toGray()
* @return Gray
*/
public function toGray()
{
return $this;
}
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Color;
use BaconQrCode\Exception;
/**
* RGB color.
*/
class Rgb implements ColorInterface
{
/**
* Red value.
*
* @var integer
*/
protected $red;
/**
* Green value.
*
* @var integer
*/
protected $green;
/**
* Blue value.
*
* @var integer
*/
protected $blue;
/**
* Creates a new RGB color.
*
* @param integer $red
* @param integer $green
* @param integer $blue
*/
public function __construct($red, $green, $blue)
{
if ($red < 0 || $red > 255) {
throw new Exception\InvalidArgumentException('Red must be between 0 and 255');
}
if ($green < 0 || $green > 255) {
throw new Exception\InvalidArgumentException('Green must be between 0 and 255');
}
if ($blue < 0 || $blue > 255) {
throw new Exception\InvalidArgumentException('Blue must be between 0 and 255');
}
$this->red = (int) $red;
$this->green = (int) $green;
$this->blue = (int) $blue;
}
/**
* Returns the red value.
*
* @return integer
*/
public function getRed()
{
return $this->red;
}
/**
* Returns the green value.
*
* @return integer
*/
public function getGreen()
{
return $this->green;
}
/**
* Returns the blue value.
*
* @return integer
*/
public function getBlue()
{
return $this->blue;
}
/**
* Returns a hexadecimal string representation of the RGB value.
*
* @return string
*/
public function __toString()
{
return sprintf('%02x%02x%02x', $this->red, $this->green, $this->blue);
}
/**
* toRgb(): defined by ColorInterface.
*
* @see ColorInterface::toRgb()
* @return Rgb
*/
public function toRgb()
{
return $this;
}
/**
* toCmyk(): defined by ColorInterface.
*
* @see ColorInterface::toCmyk()
* @return Cmyk
*/
public function toCmyk()
{
$c = 1 - ($this->red / 255);
$m = 1 - ($this->green / 255);
$y = 1 - ($this->blue / 255);
$k = min($c, $m, $y);
return new Cmyk(
100 * ($c - $k) / (1 - $k),
100 * ($m - $k) / (1 - $k),
100 * ($y - $k) / (1 - $k),
100 * $k
);
}
/**
* toGray(): defined by ColorInterface.
*
* @see ColorInterface::toGray()
* @return Gray
*/
public function toGray()
{
return new Gray(($this->red * 0.21 + $this->green * 0.71 + $this->blue * 0.07) / 2.55);
}
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Image;
use BaconQrCode\Encoder\QrCode;
use BaconQrCode\Renderer\Color;
use BaconQrCode\Renderer\Image\Decorator\DecoratorInterface;
use BaconQrCode\Exception;
/**
* Image renderer, supporting multiple backends.
*/
abstract class AbstractRenderer implements RendererInterface
{
/**
* Margin around the QR code, also known as quiet zone.
*
* @var integer
*/
protected $margin = 4;
/**
* Requested width of the rendered image.
*
* @var integer
*/
protected $width = 0;
/**
* Requested height of the rendered image.
*
* @var integer
*/
protected $height = 0;
/**
* Whether dimensions should be rounded down.
*
* @var boolean
*/
protected $roundDimensions = true;
/**
* Final width of the image.
*
* @var integer
*/
protected $finalWidth;
/**
* Final height of the image.
*
* @var integer
*/
protected $finalHeight;
/**
* Size of each individual block.
*
* @var integer
*/
protected $blockSize;
/**
* Background color.
*
* @var Color\ColorInterface
*/
protected $backgroundColor;
/**
* Whether dimensions should be rounded down
*
* @var boolean
*/
protected $floorToClosestDimension;
/**
* Foreground color.
*
* @var Color\ColorInterface
*/
protected $foregroundColor;
/**
* Decorators used on QR codes.
*
* @var array
*/
protected $decorators = array();
/**
* Sets the margin around the QR code.
*
* @param integer $margin
* @return AbstractRenderer
* @throws Exception\InvalidArgumentException
*/
public function setMargin($margin)
{
if ($margin < 0) {
throw new Exception\InvalidArgumentException('Margin must be equal to greater than 0');
}
$this->margin = (int) $margin;
return $this;
}
/**
* Gets the margin around the QR code.
*
* @return integer
*/
public function getMargin()
{
return $this->margin;
}
/**
* Sets the height around the renderd image.
*
* If the width is smaller than the matrix width plus padding, the renderer
* will automatically use that as the width instead of the specified one.
*
* @param integer $width
* @return AbstractRenderer
*/
public function setWidth($width)
{
$this->width = (int) $width;
return $this;
}
/**
* Gets the width of the rendered image.
*
* @return integer
*/
public function getWidth()
{
return $this->width;
}
/**
* Sets the height around the renderd image.
*
* If the height is smaller than the matrix height plus padding, the
* renderer will automatically use that as the height instead of the
* specified one.
*
* @param integer $height
* @return AbstractRenderer
*/
public function setHeight($height)
{
$this->height = (int) $height;
return $this;
}
/**
* Gets the height around the rendered image.
*
* @return integer
*/
public function getHeight()
{
return $this->height;
}
/**
* Sets whether dimensions should be rounded down.
*
* @param boolean $flag
* @return AbstractRenderer
*/
public function setRoundDimensions($flag)
{
$this->floorToClosestDimension = $flag;
return $this;
}
/**
* Gets whether dimensions should be rounded down.
*
* @return boolean
*/
public function shouldRoundDimensions()
{
return $this->floorToClosestDimension;
}
/**
* Sets background color.
*
* @param Color\ColorInterface $color
* @return AbstractRenderer
*/
public function setBackgroundColor(Color\ColorInterface $color)
{
$this->backgroundColor = $color;
return $this;
}
/**
* Gets background color.
*
* @return Color\ColorInterface
*/
public function getBackgroundColor()
{
if ($this->backgroundColor === null) {
$this->backgroundColor = new Color\Gray(100);
}
return $this->backgroundColor;
}
/**
* Sets foreground color.
*
* @param Color\ColorInterface $color
* @return AbstractRenderer
*/
public function setForegroundColor(Color\ColorInterface $color)
{
$this->foregroundColor = $color;
return $this;
}
/**
* Gets foreground color.
*
* @return Color\ColorInterface
*/
public function getForegroundColor()
{
if ($this->foregroundColor === null) {
$this->foregroundColor = new Color\Gray(0);
}
return $this->foregroundColor;
}
/**
* Adds a decorator to the renderer.
*
* @param DecoratorInterface $decorator
* @return AbstractRenderer
*/
public function addDecorator(DecoratorInterface $decorator)
{
$this->decorators[] = $decorator;
return $this;
}
/**
* render(): defined by RendererInterface.
*
* @see RendererInterface::render()
* @param QrCode $qrCode
* @return string
*/
public function render(QrCode $qrCode)
{
$input = $qrCode->getMatrix();
$inputWidth = $input->getWidth();
$inputHeight = $input->getHeight();
$qrWidth = $inputWidth + ($this->getMargin() << 1);
$qrHeight = $inputHeight + ($this->getMargin() << 1);
$outputWidth = max($this->getWidth(), $qrWidth);
$outputHeight = max($this->getHeight(), $qrHeight);
$multiple = (int) min($outputWidth / $qrWidth, $outputHeight / $qrHeight);
if ($this->shouldRoundDimensions()) {
$outputWidth -= $outputWidth % $multiple;
$outputHeight -= $outputHeight % $multiple;
}
// Padding includes both the quiet zone and the extra white pixels to
// accommodate the requested dimensions. For example, if input is 25x25
// the QR will be 33x33 including the quiet zone. If the requested size
// is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
$leftPadding = (int) (($outputWidth - ($inputWidth * $multiple)) / 2);
$topPadding = (int) (($outputHeight - ($inputHeight * $multiple)) / 2);
// Store calculated parameters
$this->finalWidth = $outputWidth;
$this->finalHeight = $outputHeight;
$this->blockSize = $multiple;
$this->init();
$this->addColor('background', $this->getBackgroundColor());
$this->addColor('foreground', $this->getForegroundColor());
$this->drawBackground('background');
foreach ($this->decorators as $decorator) {
$decorator->preProcess(
$qrCode,
$this,
$outputWidth,
$outputHeight,
$leftPadding,
$topPadding,
$multiple
);
}
for ($inputY = 0, $outputY = $topPadding; $inputY < $inputHeight; $inputY++, $outputY += $multiple) {
for ($inputX = 0, $outputX = $leftPadding; $inputX < $inputWidth; $inputX++, $outputX += $multiple) {
if ($input->get($inputX, $inputY) === 1) {
$this->drawBlock($outputX, $outputY, 'foreground');
}
}
}
foreach ($this->decorators as $decorator) {
$decorator->postProcess(
$qrCode,
$this,
$outputWidth,
$outputHeight,
$leftPadding,
$topPadding,
$multiple
);
}
return $this->getByteStream();
}
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Image\Decorator;
use BaconQrCode\Encoder\QrCode;
use BaconQrCode\Renderer\Image\RendererInterface;
/**
* Decorator interface.
*/
interface DecoratorInterface
{
/**
* Pre-process a QR code.
*
* @param QrCode $qrCode
* @param RendererInterface $renderer
* @param integer $outputWidth
* @param integer $outputHeight
* @param integer $leftPadding
* @param integer $topPadding
* @param integer $multiple
* @return void
*/
public function preProcess(
QrCode $qrCode,
RendererInterface $renderer,
$outputWidth,
$outputHeight,
$leftPadding,
$topPadding,
$multiple
);
/**
* Post-process a QR code.
*
* @param QrCode $qrCode
* @param RendererInterface $renderer
* @param integer $outputWidth
* @param integer $outputHeight
* @param integer $leftPadding
* @param integer $topPadding
* @param integer $multiple
* @return void
*/
public function postProcess(
QrCode $qrCode,
RendererInterface $renderer,
$outputWidth,
$outputHeight,
$leftPadding,
$topPadding,
$multiple
);
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Image\Decorator;
use BaconQrCode\Encoder\QrCode;
use BaconQrCode\Renderer\Image\RendererInterface;
use BaconQrCode\Renderer\Color;
/**
* Finder pattern decorator.
*/
class FinderPattern implements DecoratorInterface
{
/**
* @var Color\ColorInterface
*/
protected $innerColor;
/**
* @varColor\ColorInterface
*/
protected $outerColor;
/**
* Outer position detection pattern.
*
* @var array
*/
protected static $outerPositionDetectionPattern = array(
array(1, 1, 1, 1, 1, 1, 1),
array(1, 0, 0, 0, 0, 0, 1),
array(1, 0, 0, 0, 0, 0, 1),
array(1, 0, 0, 0, 0, 0, 1),
array(1, 0, 0, 0, 0, 0, 1),
array(1, 0, 0, 0, 0, 0, 1),
array(1, 1, 1, 1, 1, 1, 1),
);
/**
* Inner position detection pattern.
*
* @var array
*/
protected static $innerPositionDetectionPattern = array(
array(0, 0, 0, 0, 0, 0, 0),
array(0, 0, 0, 0, 0, 0, 0),
array(0, 0, 1, 1, 1, 0, 0),
array(0, 0, 1, 1, 1, 0, 0),
array(0, 0, 1, 1, 1, 0, 0),
array(0, 0, 0, 0, 0, 0, 0),
array(0, 0, 0, 0, 0, 0, 0),
);
/**
* Sets outer color.
*
* @param Color\ColorInterface $color
* @return FinderPattern
*/
public function setOuterColor(Color\ColorInterface $color)
{
$this->outerColor = $color;
return $this;
}
/**
* Gets outer color.
*
* @return Color\ColorInterface
*/
public function getOuterColor()
{
if ($this->outerColor === null) {
$this->outerColor = new Color\Gray(100);
}
return $this->outerColor;
}
/**
* Sets inner color.
*
* @param Color\ColorInterface $color
* @return FinderPattern
*/
public function setInnerColor(Color\ColorInterface $color)
{
$this->innerColor = $color;
return $this;
}
/**
* Gets inner color.
*
* @return Color\ColorInterface
*/
public function getInnerColor()
{
if ($this->innerColor === null) {
$this->innerColor = new Color\Gray(0);
}
return $this->innerColor;
}
/**
* preProcess(): defined by DecoratorInterface.
*
* @see DecoratorInterface::preProcess()
* @param QrCode $qrCode
* @param RendererInterface $renderer
* @param integer $outputWidth
* @param integer $outputHeight
* @param integer $leftPadding
* @param integer $topPadding
* @param integer $multiple
* @return void
*/
public function preProcess(
QrCode $qrCode,
RendererInterface $renderer,
$outputWidth,
$outputHeight,
$leftPadding,
$topPadding,
$multiple
) {
$matrix = $qrCode->getMatrix();
$positions = array(
array(0, 0),
array($matrix->getWidth() - 7, 0),
array(0, $matrix->getHeight() - 7),
);
foreach (self::$outerPositionDetectionPattern as $y => $row) {
foreach ($row as $x => $isSet) {
foreach ($positions as $position) {
$matrix->set($x + $position[0], $y + $position[1], 0);
}
}
}
}
/**
* postProcess(): defined by DecoratorInterface.
*
* @see DecoratorInterface::postProcess()
*
* @param QrCode $qrCode
* @param RendererInterface $renderer
* @param integer $outputWidth
* @param integer $outputHeight
* @param integer $leftPadding
* @param integer $topPadding
* @param integer $multiple
* @return void
*/
public function postProcess(
QrCode $qrCode,
RendererInterface $renderer,
$outputWidth,
$outputHeight,
$leftPadding,
$topPadding,
$multiple
) {
$matrix = $qrCode->getMatrix();
$positions = array(
array(0, 0),
array($matrix->getWidth() - 7, 0),
array(0, $matrix->getHeight() - 7),
);
$renderer->addColor('finder-outer', $this->getOuterColor());
$renderer->addColor('finder-inner', $this->getInnerColor());
foreach (self::$outerPositionDetectionPattern as $y => $row) {
foreach ($row as $x => $isOuterSet) {
$isInnerSet = self::$innerPositionDetectionPattern[$y][$x];
if ($isOuterSet) {
foreach ($positions as $position) {
$renderer->drawBlock(
$leftPadding + $x * $multiple + $position[0] * $multiple,
$topPadding + $y * $multiple + $position[1] * $multiple,
'finder-outer'
);
}
}
if ($isInnerSet) {
foreach ($positions as $position) {
$renderer->drawBlock(
$leftPadding + $x * $multiple + $position[0] * $multiple,
$topPadding + $y * $multiple + $position[1] * $multiple,
'finder-inner'
);
}
}
}
}
}
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Image;
use BaconQrCode\Renderer\Color\ColorInterface;
use BaconQrCode\Renderer\Color\Rgb;
use BaconQrCode\Renderer\Color\Cmyk;
use BaconQrCode\Renderer\Color\Gray;
/**
* EPS backend.
*/
class Eps extends AbstractRenderer
{
/**
* EPS string.
*
* @var string
*/
protected $eps;
/**
* Colors used for drawing.
*
* @var array
*/
protected $colors = array();
/**
* Current color.
*
* @var string
*/
protected $currentColor;
/**
* init(): defined by RendererInterface.
*
* @see ImageRendererInterface::init()
* @return void
*/
public function init()
{
$this->eps = "%!PS-Adobe-3.0 EPSF-3.0\n"
. "%%BoundingBox: 0 0 " . $this->finalWidth . " " . $this->finalHeight . "\n"
. "/F { rectfill } def\n";
}
/**
* addColor(): defined by RendererInterface.
*
* @see ImageRendererInterface::addColor()
* @param string $id
* @param ColorInterface $color
* @return void
*/
public function addColor($id, ColorInterface $color)
{
if (
!$color instanceof Rgb
&& !$color instanceof Cmyk
&& !$color instanceof Gray
) {
$color = $color->toCmyk();
}
$this->colors[$id] = $color;
}
/**
* drawBackground(): defined by RendererInterface.
*
* @see ImageRendererInterface::drawBackground()
* @param string $colorId
* @return void
*/
public function drawBackground($colorId)
{
$this->setColor($colorId);
$this->eps .= "0 0 " . $this->finalWidth . " " . $this->finalHeight . " F\n";
}
/**
* drawBlock(): defined by RendererInterface.
*
* @see ImageRendererInterface::drawBlock()
* @param integer $x
* @param integer $y
* @param string $colorId
* @return void
*/
public function drawBlock($x, $y, $colorId)
{
$this->setColor($colorId);
$this->eps .= $x . " " . ($this->finalHeight - $y - $this->blockSize) . " " . $this->blockSize . " " . $this->blockSize . " F\n";
}
/**
* getByteStream(): defined by RendererInterface.
*
* @see ImageRendererInterface::getByteStream()
* @return string
*/
public function getByteStream()
{
return $this->eps;
}
/**
* Sets color to use.
*
* @param string $colorId
* @return void
*/
protected function setColor($colorId)
{
if ($colorId !== $this->currentColor) {
$color = $this->colors[$colorId];
if ($color instanceof Rgb) {
$this->eps .= sprintf(
"%F %F %F setrgbcolor\n",
$color->getRed() / 100,
$color->getGreen() / 100,
$color->getBlue() / 100
);
} elseif ($color instanceof Cmyk) {
$this->eps .= sprintf(
"%F %F %F %F setcmykcolor\n",
$color->getCyan() / 100,
$color->getMagenta() / 100,
$color->getYellow() / 100,
$color->getBlack() / 100
);
} elseif ($color instanceof Gray) {
$this->eps .= sprintf(
"%F setgray\n",
$color->getGray() / 100
);
}
$this->currentColor = $colorId;
}
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Image;
use BaconQrCode\Exception;
use BaconQrCode\Renderer\Color\ColorInterface;
/**
* PNG backend.
*/
class Png extends AbstractRenderer
{
/**
* Image resource used when drawing.
*
* @var resource
*/
protected $image;
/**
* Colors used for drawing.
*
* @var array
*/
protected $colors = array();
/**
* init(): defined by RendererInterface.
*
* @see ImageRendererInterface::init()
* @return void
*/
public function init()
{
$this->image = imagecreatetruecolor($this->finalWidth, $this->finalHeight);
}
/**
* addColor(): defined by RendererInterface.
*
* @see ImageRendererInterface::addColor()
* @param string $id
* @param ColorInterface $color
* @return void
* @throws Exception\RuntimeException
*/
public function addColor($id, ColorInterface $color)
{
if ($this->image === null) {
throw new Exception\RuntimeException('Colors can only be added after init');
}
$color = $color->toRgb();
$this->colors[$id] = imagecolorallocate(
$this->image,
$color->getRed(),
$color->getGreen(),
$color->getBlue()
);
}
/**
* drawBackground(): defined by RendererInterface.
*
* @see ImageRendererInterface::drawBackground()
* @param string $colorId
* @return void
*/
public function drawBackground($colorId)
{
imagefill($this->image, 0, 0, $this->colors[$colorId]);
}
/**
* drawBlock(): defined by RendererInterface.
*
* @see ImageRendererInterface::drawBlock()
* @param integer $x
* @param integer $y
* @param string $colorId
* @return void
*/
public function drawBlock($x, $y, $colorId)
{
imagefilledrectangle(
$this->image,
$x,
$y,
$x + $this->blockSize - 1,
$y + $this->blockSize - 1,
$this->colors[$colorId]
);
}
/**
* getByteStream(): defined by RendererInterface.
*
* @see ImageRendererInterface::getByteStream()
* @return string
*/
public function getByteStream()
{
ob_start();
imagepng($this->image);
return ob_get_clean();
}
}
\ No newline at end of file
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Image;
use BaconQrCode\Renderer\Color\ColorInterface;
use BaconQrCode\Renderer\RendererInterface as GeneralRendererInterface;
/**
* Renderer interface.
*/
interface RendererInterface extends GeneralRendererInterface
{
/**
* Initiates the drawing area.
*
* @return void
*/
public function init();
/**
* Adds a color to the drawing area.
*
* @param string $id
* @param ColorInterface $color
* @return void
*/
public function addColor($id, ColorInterface $color);
/**
* Draws the background.
*
* @param string $colorId
* @return void
*/
public function drawBackground($colorId);
/**
* Draws a block at a specified position.
*
* @param integer $x
* @param integer $y
* @param string $colorId
* @return void
*/
public function drawBlock($x, $y, $colorId);
/**
* Returns the byte stream representing the QR code.
*
* @return string
*/
public function getByteStream();
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Image;
use BaconQrCode\Exception;
use BaconQrCode\Renderer\Color\ColorInterface;
use SimpleXMLElement;
/**
* SVG backend.
*/
class Svg extends AbstractRenderer
{
/**
* SVG resource.
*
* @var SimpleXMLElement
*/
protected $svg;
/**
* Colors used for drawing.
*
* @var array
*/
protected $colors = array();
/**
* Prototype IDs.
*
* @var array
*/
protected $prototypeIds = array();
/**
* init(): defined by RendererInterface.
*
* @see ImageRendererInterface::init()
* @return void
*/
public function init()
{
$this->svg = new SimpleXMLElement(
'<?xml version="1.0" encoding="UTF-8"?>'
. '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>'
);
$this->svg->addAttribute('version', '1.1');
$this->svg->addAttribute('width', $this->finalWidth . 'px');
$this->svg->addAttribute('height', $this->finalHeight . 'px');
$this->svg->addAttribute('viewBox', '0 0 ' . $this->finalWidth . ' ' . $this->finalHeight);
$this->svg->addChild('defs');
}
/**
* addColor(): defined by RendererInterface.
*
* @see ImageRendererInterface::addColor()
* @param string $id
* @param ColorInterface $color
* @return void
* @throws Exception\InvalidArgumentException
*/
public function addColor($id, ColorInterface $color)
{
$this->colors[$id] = (string) $color->toRgb();
}
/**
* drawBackground(): defined by RendererInterface.
*
* @see ImageRendererInterface::drawBackground()
* @param string $colorId
* @return void
*/
public function drawBackground($colorId)
{
$rect = $this->svg->addChild('rect');
$rect->addAttribute('x', 0);
$rect->addAttribute('y', 0);
$rect->addAttribute('width', $this->finalWidth);
$rect->addAttribute('height', $this->finalHeight);
$rect->addAttribute('fill', '#' . $this->colors[$colorId]);
}
/**
* drawBlock(): defined by RendererInterface.
*
* @see ImageRendererInterface::drawBlock()
* @param integer $x
* @param integer $y
* @param string $colorId
* @return void
*/
public function drawBlock($x, $y, $colorId)
{
$use = $this->svg->addChild('use');
$use->addAttribute('x', $x);
$use->addAttribute('y', $y);
$use->addAttribute(
'xlink:href',
$this->getRectPrototypeId($colorId),
'http://www.w3.org/1999/xlink'
);
}
/**
* getByteStream(): defined by RendererInterface.
*
* @see ImageRendererInterface::getByteStream()
* @return string
*/
public function getByteStream()
{
return $this->svg->asXML();
}
/**
* Get the prototype ID for a color.
*
* @param integer $colorId
* @return string
*/
protected function getRectPrototypeId($colorId)
{
if (!isset($this->prototypeIds[$colorId])) {
$id = 'r' . dechex(count($this->prototypeIds));
$rect = $this->svg->defs->addChild('rect');
$rect->addAttribute('id', $id);
$rect->addAttribute('width', $this->blockSize);
$rect->addAttribute('height', $this->blockSize);
$rect->addAttribute('fill', '#' . $this->colors[$colorId]);
$this->prototypeIds[$colorId] = '#' . $id;
}
return $this->prototypeIds[$colorId];
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer;
use BaconQrCode\Encoder\QrCode;
/**
* Renderer interface.
*/
interface RendererInterface
{
/**
* Renders a QR code.
*
* @param QrCode $qrCode
* @return string
*/
public function render(QrCode $qrCode);
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Text;
use BaconQrCode\Encoder\QrCode;
/**
* Html renderer.
*/
class Html extends Plain
{
/**
* HTML CSS class attribute value.
*
* @var string
*/
protected $class = '';
/**
* HTML CSS style definition for the code element.
*
* @var string
*/
protected $style = 'font-family: monospace; line-height: 0.65em; letter-spacing: -1px';
/**
* Set CSS class name.
*
* @param string $class
*/
public function setClass($class)
{
$this->class = $class;
}
/**
* Get CSS class name.
*
* @return string
*/
public function getClass()
{
return $this->class;
}
/**
* Set CSS style value.
*
* @param string $style
*/
public function setStyle($style)
{
$this->style = $style;
}
/**
* Get CSS style value.
*
* @return string
*/
public function getStyle()
{
return $this->style;
}
/**
* render(): defined by RendererInterface.
*
* @see RendererInterface::render()
* @param QrCode $qrCode
* @return string
*/
public function render(QrCode $qrCode)
{
$textCode = parent::render($qrCode);
$result = '<pre'
. ' style="' . htmlspecialchars($this->style, ENT_QUOTES, 'utf-8') . '"'
. ' class="' . htmlspecialchars($this->class, ENT_QUOTES, 'utf-8') . '"'
. '>' . $textCode . '</pre>';
return $result;
}
}
<?php
/**
* BaconQrCode
*
* @link http://github.com/Bacon/BaconQrCode For the canonical source repository
* @copyright 2013 Ben 'DASPRiD' Scholzen
* @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
*/
namespace BaconQrCode\Renderer\Text;
use BaconQrCode\Exception;
use BaconQrCode\Encoder\QrCode;
use BaconQrCode\Renderer\RendererInterface;
/**
* Plaintext renderer.
*/
class Plain implements RendererInterface
{
/**
* Margin around the QR code, also known as quiet zone.
*
* @var integer
*/
protected $margin = 1;
/**
* Char used for full block.
*
* UTF-8 FULL BLOCK (U+2588)
*
* @var string
* @link http://www.fileformat.info/info/unicode/char/2588/index.htm
*/
protected $fullBlock = "\xE2\x96\x88";
/**
* Char used for empty space
*
* @var string
*/
protected $emptyBlock = ' ';
/**
* Set char used as full block (occupied space, "black").
*
* @param string $fullBlock
*/
public function setFullBlock($fullBlock)
{
$this->fullBlock = $fullBlock;
}
/**
* Get char used as full block (occupied space, "black").
*
* @return string
*/
public function getFullBlock()
{
return $this->fullBlock;
}
/**
* Set char used as empty block (empty space, "white").
*
* @param string $emptyBlock
*/
public function setEmptyBlock($emptyBlock)
{
$this->emptyBlock = $emptyBlock;
}
/**
* Get char used as empty block (empty space, "white").
*
* @return string
*/
public function getEmptyBlock()
{
return $this->emptyBlock;
}
/**
* Sets the margin around the QR code.
*
* @param integer $margin
* @return AbstractRenderer
* @throws Exception\InvalidArgumentException
*/
public function setMargin($margin)
{
if ($margin < 0) {
throw new Exception\InvalidArgumentException('Margin must be equal to greater than 0');
}
$this->margin = (int) $margin;
return $this;
}
/**
* Gets the margin around the QR code.
*
* @return integer
*/
public function getMargin()
{
return $this->margin;
}
/**
* render(): defined by RendererInterface.
*
* @see RendererInterface::render()
* @param QrCode $qrCode
* @return string
*/
public function render(QrCode $qrCode)
{
$result = '';
$matrix = $qrCode->getMatrix();
$width = $matrix->getWidth();
// Top margin
for ($x = 0; $x < $this->margin; $x++) {
$result .= str_repeat($this->emptyBlock, $width + 2 * $this->margin)."\n";
}
// Body
$array = $matrix->getArray();
foreach ($array as $row) {
$result .= str_repeat($this->emptyBlock, $this->margin); // left margin
foreach ($row as $byte) {
$result .= $byte ? $this->fullBlock : $this->emptyBlock;
}
$result .= str_repeat($this->emptyBlock, $this->margin); // right margin
$result .= "\n";
}
// Bottom margin
for ($x = 0; $x < $this->margin; $x++) {
$result .= str_repeat($this->emptyBlock, $width + 2 * $this->margin)."\n";
}
return $result;
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment