1. Import

This commit is contained in:
2026-03-29 10:34:57 +02:00
parent b0e00c1259
commit a1129565af
4899 changed files with 3007593 additions and 0 deletions

BIN
html/include/Arimo-Bold.ttf Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,196 @@
<?php
/*
* PHP Class for handling Google Authenticator 2-factor authentication.
* @author Michael Kliewe | @copyright 2012 Michael Kliewe
*/
class GoogleAuthenticator
{
protected $_codeLength = 6;
// Create new secret (16 characters, randomly chosen from the allowed base32 characters)
public function createSecret($secretLength = 16)
{
$validChars = $this->_getBase32LookupTable();
// Valid secret lengths are 80 to 640 bits
if ($secretLength < 16 || $secretLength > 128) {
throw new Exception('Bad secret length');
}
$secret = '';
$rnd = false;
if (function_exists('random_bytes')) {
$rnd = random_bytes($secretLength);
} elseif (function_exists('mcrypt_create_iv')) {
$rnd = mcrypt_create_iv($secretLength, MCRYPT_DEV_URANDOM);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
if (!$cryptoStrong) {
$rnd = false;
}
}
if ($rnd !== false) {
for ($i = 0; $i < $secretLength; ++$i) {
$secret .= $validChars[ord($rnd[$i]) & 31];
}
} else {
throw new Exception('No source of secure random');
}
return $secret;
}
// Calculate the code, with given secret and point in time.
public function getCode($secret, $timeSlice = null)
{
if ($timeSlice === null) {
$timeSlice = floor(time() / 30);
}
$secretkey = $this->_base32Decode($secret);
// Pack time into binary string
$time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
// Hash it with users secret key
$hm = hash_hmac('SHA1', $time, $secretkey, true);
// Use last nipple of result as index/offset
$offset = ord(substr($hm, -1)) & 0x0F;
// grab 4 bytes of the result
$hashpart = substr($hm, $offset, 4);
// Unpak binary value
$value = unpack('N', $hashpart);
$value = $value[1];
// Only 32 bits
$value = $value & 0x7FFFFFFF;
$modulo = pow(10, $this->_codeLength);
return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
}
// Get QR-Code URL for image, from google charts.
public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
{
$width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
$height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
$level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';
$urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
if (isset($title)) {
$urlencoded .= urlencode('&issuer='.urlencode($title));
}
return "https://api.qrserver.com/v1/create-qr-code/?data=$urlencoded&size=${width}x${height}&ecc=$level";
}
// Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
{
if ($currentTimeSlice === null) {
$currentTimeSlice = floor(time() / 30);
}
if (strlen($code) != 6) {
return false;
}
for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
$calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
if ($this->timingSafeEquals($calculatedCode, $code)) {
return true;
}
}
return false;
}
// Set the code length, should be >=6.
public function setCodeLength($length)
{
$this->_codeLength = $length;
return $this;
}
// Helper class to decode base32.
protected function _base32Decode($secret)
{
if (empty($secret)) {
return '';
}
$base32chars = $this->_getBase32LookupTable();
$base32charsFlipped = array_flip($base32chars);
$paddingCharCount = substr_count($secret, $base32chars[32]);
$allowedValues = array(6, 4, 3, 1, 0);
if (!in_array($paddingCharCount, $allowedValues)) {
return false;
}
for ($i = 0; $i < 4; ++$i) {
if ($paddingCharCount == $allowedValues[$i] &&
substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
return false;
}
}
$secret = str_replace('=', '', $secret);
$secret = str_split($secret);
$binaryString = '';
for ($i = 0; $i < count($secret); $i = $i + 8) {
$x = '';
if (!in_array($secret[$i], $base32chars)) {
return false;
}
for ($j = 0; $j < 8; ++$j) {
$x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
}
$eightBits = str_split($x, 8);
for ($z = 0; $z < count($eightBits); ++$z) {
$binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
}
}
return $binaryString;
}
// Gets an array with all 32 characters for decoding from/encoding to base32.
protected function _getBase32LookupTable()
{
return array(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 7
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
'=', // padding char
);
}
// A timing safe equals comparison (more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html)
// $safeString The internal (safe) value to be checked
// $userString The user submitted (unsafe) value
private function timingSafeEquals($safeString, $userString)
{
if (function_exists('hash_equals')) {
return hash_equals($safeString, $userString);
}
$safeLen = strlen($safeString);
$userLen = strlen($userString);
if ($userLen != $safeLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $userLen; ++$i) {
$result |= (ord($safeString[$i]) ^ ord($userString[$i]));
}
// They are only identical strings if $result is exactly 0...
return $result === 0;
}
}
?>

View File

@@ -0,0 +1,360 @@
<?php
/**
* WkHtmlToPdf
*
* This class is a slim wrapper around wkhtmltopdf.
*
* It provides a simple and clean interface to ease PDF creation with wkhtmltopdf.
* The wkhtmltopdf binary must be installed and working on your system. The static
* binary is preferred but this class should also work with the non static version,
* even though a lot of features will be missing.
*
* Basic use
* ---------
*
* $pdf = new WkHtmlToPdf;
*
* // Add a HTML file, a HTML string or a page from URL
* $pdf->addPage('/home/joe/page.html');
* $pdf->addPage('<html>....</html>');
* $pdf->addPage('http://google.com');
*
* // Add a cover (same sources as above are possible)
* $pdf->addCover('mycover.html');
*
* // Add a Table of contents
* $pdf->addToc();
*
* // Save the PDF
* $pdf->saveAs('/tmp/new.pdf');
*
* // ... or send to client for inline display
* $pdf->send();
*
* // ... or send to client as file download
* $pdf->send('test.pdf');
*
*
* Setting options
* ---------------
*
* The wkhtmltopdf binary knows different types of options (please see wkhtmltopdf -H):
*
* * global options (e.g. to set the document's DPI)
* * page options (e.g. to supply a custom CSS file for a page)
* * toc options (e.g. to set a TOC header)
*
* In addition this class also supports global page options: You can set default page options
* that will be applied to every page you add. You can also override these defaults per page:
*
* $pdf = new WkHtmlToPdf($options); // Set global PDF options
* $pdf->setOptions($options); // Set global PDF options (alternative)
* $pdf->setPageOptions($options); // Set default page options
* $pdf->addPage($page, $options); // Add page with options (overrides default page options)
* $pdf->addCover($page, $options); // Add cover with options (overrides default page options)
* $pdf->addToc($options); // Add TOC with options
*
*
* Special global options
* ----------------------
*
* * bin: Path to the wkhtmltopdf binary. Defaults to /usr/bin/wkhtmltopdf.
* * tmp: Path to tmp directory. Defaults to PHP temp dir.
* * enableEscaping: Whether arguments to wkhtmltopdf should be escaped. Default is true.
* * version9: Whether to use command line syntax for wkhtmltopdf < 0.10
*
*
* Error handling
* --------------
*
* saveAs() and send() will return false on error. In this case the detailed error message
* from wkhtmltopdf can be obtained through getError():
*
* if(!$pdf->send())
* throw new Exception('Could not create PDF: '.$pdf->getError());
*
*
* Note for Windows users
* ----------------------
*
* If you use double quotes (") or percent signs (%) as option values, they may get
* converted to spaces. You can set `enableEscaping` to `false` in this case. But
* then you have to take care of proper escaping yourself. In some cases it may be
* neccessary to surround your argument values with extra double quotes.
*
*
* @author Michael Härtl <haertl.mike@gmail.com> (sponsored by PeoplePerHour.com)
* @version 1.1.6
* @license http://www.opensource.org/licenses/MIT
*/
class WkHtmlToPdf
{
// protected $bin = '/usr/bin/wkhtmltopdf'; // MC (10.08.2021) :: Activated after installation of package "wkhtmltopdf"
// protected $bin = '../include/wkhtmltopdf'; // MC (earlier) :: Binary in votian include path directly, this solutions works
protected $bin = 'wkhtmltopdf'; // MC (26.09.2025) :: Binary system call
protected $enableEscaping = true;
protected $version9 = false;
protected $options = array();
protected $pageOptions = array();
protected $objects = array();
protected $tmp;
protected $tmpFile;
protected $tmpFiles = array();
protected $error;
// Regular expression to detect HTML strings
const REGEX_HTML = '/<html/i';
/**
* @param array $options global options for wkhtmltopdf (optional)
*/
public function __construct($options=array())
{
if($options!==array())
$this->setOptions($options);
}
/**
* Remove temporary PDF file and pages when script completes
*/
public function __destruct()
{
if($this->tmpFile!==null)
unlink($this->tmpFile);
foreach($this->tmpFiles as $tmp)
unlink($tmp);
}
/**
* Add a page object to the output
*
* @param string $input either a URL, a HTML string or a PDF/HTML filename
* @param array $options optional options for this page
*/
public function addPage($input,$options=array())
{
$options['input'] = preg_match(self::REGEX_HTML, $input) ? $this->createTmpFile($input) : $input;
$this->objects[] = array_merge($this->pageOptions,$options);
}
/**
* Add a cover page object to the output
*
* @param string $input either a URL or a PDF filename
* @param array $options optional options for this page
*/
public function addCover($input,$options=array())
{
$options['input'] = ($this->version9 ? '--' : '')."cover $input";
$this->objects[] = array_merge($this->pageOptions,$options);
}
/**
* Add a TOC object to the output
*
* @param array $options optional options for the table of contents
*/
public function addToc($options=array())
{
$options['input'] = ($this->version9 ? '--' : '')."toc";
$this->objects[] = $options;
}
/**
* Save the PDF to given filename (triggers PDF creation)
*
* @param string $filename to save PDF as
* @return bool whether PDF was created successfully
*/
public function saveAs($filename)
{
if(($pdfFile = $this->getPdfFilename())===false)
return false;
copy($pdfFile,$filename);
return true;
}
/**
* Send PDF to client, either inline or as download (triggers PDF creation)
*
* @param mixed $filename the filename to send. If empty, the PDF is streamed.
* @return bool whether PDF was created successfully
*/
public function send($filename=null)
{
if(($pdfFile = $this->getPdfFilename())===false)
return false;
if (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($pdfFile));
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
if ($filename !== null)
header("Content-Disposition: attachment; filename=\"$filename\"");
readfile($filename);
exit;
return true;
}
/**
* Set global option(s)
*
* @param array $options list of global options to set as name/value pairs
*/
public function setOptions($options)
{
foreach($options as $key=>$val)
if($key==='bin')
$this->bin = $val;
elseif($key==='tmp')
$this->tmp = $val;
elseif($key==='enableEscaping')
$this->enableEscaping = (bool)$val;
elseif($key==='version9')
$this->version9 = (bool)$val;
elseif(is_int($key))
$this->options[] = $val;
else
$this->options[$key] = $val;
}
/**
* @param array $options that should be applied to all pages as name/value pairs
*/
public function setPageOptions($options=array())
{
$this->pageOptions = $options;
}
/**
* @return mixed the detailled error message including the wkhtmltopdf command or null if none
*/
public function getError()
{
return $this->error;
}
/**
* @return string path to temp directory
*/
public function getTmpDir()
{
if($this->tmp===null)
$this->tmp = sys_get_temp_dir();
return $this->tmp;
}
/**
* @param string $filename the filename of the output file
* @return string the wkhtmltopdf command string
*/
public function getCommand($filename)
{
$command = $this->enableEscaping ? escapeshellarg($this->bin) : $this->bin;
$command .= $this->renderOptions($this->options);
foreach($this->objects as $object)
{
$command .= ' '.$object['input'];
unset($object['input']);
$command .= $this->renderOptions($object);
}
return $command.' '.$filename;
}
/**
* @return mixed the temporary PDF filename or false on error (triggers PDf creation)
*/
protected function getPdfFilename()
{
if($this->tmpFile===null)
{
$tmpFile = tempnam($this->getTmpDir(),'tmp_WkHtmlToPdf_');
if($this->createPdf($tmpFile)===true)
$this->tmpFile = $tmpFile;
else
return false;
}
return $this->tmpFile;
}
/**
* Create the temporary PDF file
*/
protected function createPdf($fileName)
{
$command = $this->getCommand($fileName);
// we use proc_open with pipes to fetch error output
$descriptors = array(
2 => array('pipe','w'),
);
$process = proc_open($command, $descriptors, $pipes, null, null, array('bypass_shell'=>true));
if(is_resource($process)) {
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$result = proc_close($process);
if($result!==0)
{
if (!file_exists($fileName) || filesize($fileName)===0)
$this->error = "Could not run command $command:\n$stderr";
else
$this->error = "Warning: an error occured while creating the PDF.\n$stderr";
}
} else
$this->error = "Could not run command $command";
return $this->error===null;
}
/**
* Create a tmp file with given content
*
* @param string $content the file content
* @return string the path to the created file
*/
protected function createTmpFile($content)
{
$tmpFile = tempnam($this->getTmpDir(),'tmp_WkHtmlToPdf_');
rename($tmpFile, ($tmpFile.='.html'));
file_put_contents($tmpFile, $content);
$this->tmpFiles[] = $tmpFile;
return $tmpFile;
}
/**
* @param array $options for a wkhtml, either global or for an object
* @return string the string with options
*/
protected function renderOptions($options)
{
$out = '';
foreach($options as $key=>$val)
if(is_numeric($key))
$out .= " --$val";
else
$out .= " --$key ".($this->enableEscaping ? escapeshellarg($val) : $val);
return $out;
}
}

View File

@@ -0,0 +1,26 @@
<?php
/*=======================================================================
*
* js_error.php
*
* Autor: Carsten Annacker
*
=======================================================================*/
include_once("../include/auth.inc.php");
$fileHandle = @fopen("../log/js_errors_" . date("Ym") . ".log", 'a');
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "]\n");
@fwrite($fileHandle, " remote_addr = " . $HTTP_SERVER_VARS['REMOTE_ADDR'] . ";\n");
@fwrite($fileHandle, " usr_id = " . $HTTP_SESSION_VARS['usr_id'] . ";\n");
@fwrite($fileHandle, " hq_id = " . $HTTP_SESSION_VARS['hq_id'] . ";\n");
@fwrite($fileHandle, " emp_id = " . $HTTP_SESSION_VARS['emp_id'] . ";\n");
@fwrite($fileHandle, " url = " . $HTTP_GET_VARS['url'] . ";\n");
@fwrite($fileHandle, " line = " . $HTTP_GET_VARS['line'] . ";\n");
@fwrite($fileHandle, " message = " . $HTTP_GET_VARS['message'] . ";\n");
@fwrite($fileHandle, " user_agent = " . $HTTP_GET_VARS['user_agent'] . ";\n");
@fwrite($fileHandle, " jb_id = " . $HTTP_GET_VARS['jb_id'] . ";\n");
@fwrite($fileHandle, " out = " . $HTTP_GET_VARS['out'] . ";\n");
@fclose($fileHandle);
?>

View File

@@ -0,0 +1,86 @@
<?php
include_once ("../include/auth.inc.php");
include_once ("../include/global.inc.php");
include_once ("../locating/hha_alarm.inc.php");
getSecHttpVars("1", array("loc_created_ids", "pwd", "upd_pwd"));
//echo "alert(\"" . str_replace('"', "'", $ret_value) . "\");";
$ret_value = "";
if (trim($upd_pwd) != "") {
$ret_value = "fail";
//echo "UPDATE user SET usr_password = PASSWORD('" . $upd_pwd . "') WHERE usr_id = " . $_SESSION['usr_id'] . " AND usr_password = PASSWORD('" . $pwd . "')" . "\n";
// $res = $db->query("UPDATE user SET usr_password = PASSWORD('" . $upd_pwd . "') WHERE usr_id = " . $_SESSION['usr_id'] . " AND usr_password = PASSWORD('" . $pwd . "')");
// if ($db->affected_rows > 0)
// $ret_value = "ok";
$res = $db->exec("UPDATE user SET usr_password = PASSWORD('" . $upd_pwd . "') WHERE usr_id = " . $_SESSION['usr_id'] . " AND usr_password = PASSWORD('" . $pwd . "')");
if ($res > 0)
$ret_value = "ok";
echo "retValue = '" . $ret_value . "';\n";
}
if (trim($loc_created_ids) != "") {
$loc_created_idsArr = explode(";", $loc_created_ids);
$loc_created_ids = "";
for ($i = 0; $i < count($loc_created_idsArr) - 1; $i++) {
$loc_created_idsArrArr = explode("|", $loc_created_idsArr[$i]);
$sqlquery = "SELECT loc_type, ROUND(loc_long, 6) AS loc_long, ROUND(loc_lat, 6) AS loc_lat, loc_acc, loc_created" .
" FROM phoenix_log.locating WHERE usr_id = " . $loc_created_idsArrArr[0] . " AND loc_created > '" . $loc_created_idsArrArr[1] . "'" .
" AND loc_type != 3 AND loc_type != 14 AND loc_type != 9 " .
" ORDER BY loc_created DESC";
$res1 = $db->query($sqlquery);
if (DB::isError($res1)) die ("$PHP_SELF: '$sqlquery' : " . $res1->getMessage());
//$cnt = $res1->numRows();
$prev_loc_lat = 0.0;
$prev_loc_long = 0.0;
$pref_loc_created = "0000-00-00 00:00:00";
// $first_loc_lat = 0.0;
// $first_loc_long = 0.0;
// $first_loc_created = "0000-00-00 00:00:00";
$first_loc_lat = $loc_created_idsArrArr[3];
$first_loc_long = $loc_created_idsArrArr[4];
$first_loc_created = $loc_created_idsArrArr[1];
$cnt = 0;
$rows = array();
while ($row1 = $res1->fetch_assoc()) {
if (($row1["loc_long"] != $prev_loc_long && $row1["loc_lat"] != $prev_loc_lat)) {
if ($cnt == 0) {
$first_loc_created = $row1["loc_created"];
$first_loc_lat = $row1["loc_lat"];
$first_loc_long = $row1["loc_long"];
}
$rows[] = $row1;
$cnt++;
$prev_loc_lat = $row1["loc_lat"];
$prev_loc_long = $row1["loc_long"];
$prev_loc_created = $row1["loc_created"];
}
}
$res1->free();
$all_cnt = $loc_created_idsArrArr[2] + $cnt;
$loc_created_ids .= $loc_created_idsArrArr[0] . "|" . $first_loc_created . "|" . $all_cnt . "|" . $first_loc_lat . "|" . $first_loc_long . ";";
$prev_loc_lat = $loc_created_idsArrArr[3];
$prev_loc_long = $loc_created_idsArrArr[4];
$prev_loc_created = $loc_created_idsArrArr[1];
if (count($rows) > 0)
$ret_value .= " [\n";
for ($j = 0; $j < count($rows); $j++) {
$row1 = $rows[$j];
$direction = getDirection($row1["loc_long"], $row1["loc_lat"], $prev_loc_long, $prev_loc_lat);
$ret_value .= " [" . $loc_created_idsArrArr[0] . ", " . $all_cnt-- . ", " . $row1["loc_lat"] . ", " . $row1["loc_long"] . ", '" . $direction . "', '" . formDateTime($row1["loc_created"]) . "'" . "],\n";
$prev_loc_long = $row1["loc_long"];
$prev_loc_lat = $row1["loc_lat"];
$prev_loc_created = $row1["loc_created"];
}
if (count($rows) > 0)
$ret_value .= " ],\n";
}
}
if (trim($upd_pwd) == "")
echo "retValue = [\n ['" . $loc_created_ids . "'],\n" . $ret_value . "];\n";
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,84 @@
<?php
include_once ("../include/global.inc.php");
$doNotIncludeGeocode = "1";
// include_once ("../import/import.php");
include_once ("../include/inc_file.inc.php");
// include_once ("../include/ftp.inc.php");
// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdCurrent", "statusMessage", "deactivateMenu",
"mode", "hqId", "mdId", "csId", "cmpId", "f_day", "f_month", "f_year", "f_day_to", "f_month_to", "f_year_to"));
if ($mode != "") :
header("Content-Type: text/html; charset=ISO-8859-1\n");
endif;
// echo "alert('" . $mode . "' + '" . $hqId . "' + '" . $csId . "' + '" . $cmpId . "');";
if ($mode == "1") :
$rootDirDefault = "";
// Get number of documents
// Need $hqId and csEid of the selected payer only!!!
$objNumOfFiles = 0; // Init
if ($hqId != "" && ($csId != "" || $cscIdCurrent != "" || $cmpId != "")) :
if ($csId == "" && $cscIdCurrent != "") :
$csId = getFieldValueFromId("costcenter","csc_id",$cscIdCurrent,"cs_id");
endif;
if ($csId != "") :
$csEid = getFieldValueFromId("customer","cs_id",$csId,"cs_eid");
else :
$csEid = getFieldValueFromId("customer","cmp_id",$cmpId,"cs_eid");
endif;
$serverListArray = array();
$serverList = getParameterValue("0", "FTP_IMPORT_SERVERLIST", $hqId);
if ($serverList == "") : $serverList = getParameterValue("0", "FTP_IMPORT_SERVERLIST", "0"); endif;
if ($serverList != "") : $serverListArray = spliti(",",$serverList); endif;
$serverListArrayLen = count($serverListArray);
$servername = $serverListArray[0]; // Use first entry as default for. Should exist!!!
if ($servername != "") :
$upload_path = getFieldValueFromId("mandator","md_id",$mdId,"md_doc_path");
// $upload_path = getParameterValue("0", "FTP_DOWNLOADPATH_" . $servername, $hqId);
// if ($upload_path == "") : $upload_path = getParameterValue("0", "FTP_LOCALPATH_" . $servername, "0"); endif;
if ($upload_path == "") : $upload_path = "../import/upload/"; endif;
// E.g. $upload_path = "../import/upload/HTG/" !!!
$dirSpecialForObjType = getParameterValue("0", "DATATRANSFER_DIRECTORY_CS", $hqId); // Path for upload customer files
if ($dirSpecialForObjType == "") : $dirSpecialForObjType = "90b1a8efc903576bbb2d6e2a79b00a5e"; endif;
// Check for headquartes
if ($hqId != "") :
$hqMnemonic = getFieldValueFromId("headquarters","hq_id",$hqId,"hq_mnemonic");
if ($hqMnemonic == "") : $hqMnemonic = "MISC" ; endif;
$rootDirDefault .= $hqMnemonic . "/";
$dirSpecialForObjType .= "/" . $hqMnemonic . "/";
endif;
// Upload path
$upload_path = $upload_path . $dirSpecialForObjType;
// echo $upload_path . "<br>";
$objNumOfFiles = getNumOfFilesByFilterInFolder($upload_path, $csEid, "1"); // "-1" <=> Folder does not exist
// else :
// // No documents => Therefore there are no documents for the customer, too. ($objNumOfFiles = 0; !!!)
endif;
endif;
echo "retValue = '" . $objNumOfFiles . "';\n";
elseif ($mode == "2") :
// ...
elseif ($mode == "3") :
// ...
endif;
?>

View File

@@ -0,0 +1,177 @@
<?php
/*=======================================================================
*
* ajaxReqGeneric.php
*
* Autor: Marc Vollmann
*
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/inc_parseXML.inc.php");
// Check HTTP-Parameters
// Stocks
getSecHttpVarsAjax("1",array("f_act", "mode", "submode", "moId", "fun", "retIdx", "retParName", "incPath", "incFile", "incAllowAllTypes", "fixNumOfPars", "wrap_html",
"par_01", "par_02", "par_03", "par_04", "par_05", "par_06", "par_07", "par_08", "par_09", "par_10"));
if ($mode != "") :
header("Content-Type: text/html; charset=ISO-8859-1\n");
endif;
function wrap_html($aStr) {
global $wrap_html;
if ($wrap_html == "1") :
// $aStr = my_str_check_html($aStr);
$aStr = str_replace("%u20AC", '&euro;', $aStr);
endif;
return $aStr;
}
// echo "alert('" . $mode . " ' + '" . $submode . " ' + '" . $incFile . " ' + '" . $fun . " ' + '" . $par_01 . " ' + '" . $par_02 . " ' + '" . $par_03 . " ');";
// Gets all script-parameters (HTTP_GET_VARS and HTTP_POST_VARS).
// If "$mode == 1" then all id-parameters (only these!) will be decoded
function getSecHttpVarsAjax($getSecHttpVarsMode = "0", $httpVars)
{
global $HTTP_GET_VARS, $HTTP_POST_VARS;
$retArr = getHttpVars($httpVars);
$i = 0;
foreach ($httpVars as $par) {
global $$par;
$$par = $retArr[$i];
$i++;
}
// Decryption of the fields if encrypted
if ($getSecHttpVarsMode == "1") :
foreach ($httpVars as $par) {
$$par = dc($$par);
$$par = urldecode($$par);
$$par = str_replace("'", "", $$par);
// $$par = mcEncode($$par); // DISABLED because of "new browser based" decoding in "glob_defs"
// $$par = str_replace("'", "", $$par);
if ($wrap_html == "1") :
$$par = wrap_html($$par);
endif;
}
endif;
return $retArr;
}
// Decryption of called function name
// Takes the parameter "$value" and returns the decrypted, original value
function mdc($value) {
global $hq_id;
$parSecSeq = getParameterValue("0", "HTTP_VARS_SEC_SEQ", $hq_id);
if ($parSecSeq == "") : $parSecSeq = getParameterValue("0", "HTTP_VARS_SEC_SEQ", "0"); endif;
if ($parSecSeq == "") : $parSecSeq = "__"; endif;
$len = strlen($parSecSeq);
if ((substr($value, 0, $len) == $parSecSeq) && (substr($value, -$len) == $parSecSeq)) :
// Get real function name by hash
$value = $value;
endif;
return $value;
}
// Init
if ($retParName == "") : $retParName = "retValue"; endif;
$fun = mdc($fun); // Decode function name in $fun
if ($fun != "") :
// Include special file with requested function if requested
if ($incFile != "") :
if (!isset($incAllowAllTypes) || $incAllowAllTypes == "") :
if (substr($incFile,-4) != ".php") :
$incFile.= ".php";
endif;
endif;
if ($incPath == "") :
$incPath = "include";
endif;
include ("../" . $incPath . "/" . $incFile);
endif;
if (function_exists($fun)) :
// Get requested operational database instance via metaobject for each called service functions
// global $dbname, $dblogin, $dbpassword;
$db_op_conn = "";
if ($moId != "") :
$moValue = getOperationalDatabase($moId);
if ($moValue != "") :
$db_op_conn = getDbConnectionSpecial($moValue, $dbname, $dblogin, $dbpassword);
if ($db_op_conn != "" && is_object($db_op_conn)) : $db = $db_op_conn; endif;
endif;
endif;
if (true || ($db != "" && is_object($db))) :
// Get number of arguments of requested function
$fct = new ReflectionFunction($fun);
$numOfFunctionArguments = $fct->getNumberOfRequiredParameters();
if ($fixNumOfPars != "" && is_numeric($fixNumOfPars)) :
$numOfFunctionArguments = $fixNumOfPars;
endif;
$argumentArray = array();
for ($i = 1; $i <= $numOfFunctionArguments; $i++) :
$parValue = ${("par_" . pad($i, 2))};
array_push($argumentArray, $parValue);
endfor;
// Call function ang get HTML output
$retValue = call_user_func_array($fun, $argumentArray);
if (is_array($retValue)) :
if ($retIdx != "") :
$retValue = $retValue[$retIdx];
if (is_array($retValue)) :
echo $retParName . " = " . json_encode($retValue) . ";\n";
else :
echo $retParName . " = '" . my_str_check_js($retValue) . "';\n";
endif;
else :
echo $retParName . " = " . json_encode($retValue) . ";\n";
endif;
elseif (is_bool($retValue) === true) :
if ($retValue) : $retValue = "1"; else : $retValue = "0"; endif;
echo $retParName . " = '" . $retValue . "';\n";
else :
if ($retParName == "_RAW_TEXT_") :
if (strtolower($mode) == "html") :
$retValue = nl2br($retValue);
endif;
echo $retValue;
else :
echo $retParName . " = '" . my_str_check_js($retValue) . "';\n";
endif;
endif;
else :
$retValue = "ERR_03"; // No database available
echo $retParName . " = '" . $retValue . "';\n";
endif;
else :
$retValue = "ERR_02"; // Called function does not exist
echo $retParName . " = '" . $retValue . "';\n";
endif;
else :
$retValue = "ERR_01"; // No function name specified
echo $retParName . " = '" . $retValue . "';\n";
endif;
?>

116
html/include/ajaxReqJob.php Normal file
View File

@@ -0,0 +1,116 @@
<?php
include_once("../include/auth.inc.php");
include_once("../include/global.inc.php");
include_once("../include/inc_customer.inc.php");
getSecHttpVars("1",array("cs_id","csc_id","csc_id_ask_mail", "cs_id_ask_mail", "cs_id_photo", "hq_id", "vht_id", "csc_id_payer_cash"));
//echo "alert(" . $csId . "|" . $funcNo . "|" . $funcParms . ");\n";
$result = "''";
if ($cs_id != "") {
$arr = getContactsOfCustomer($cs_id, "1", "0", array(101,102));
//$today = getdate();
//$fileHandle = @fopen("../log/ajaxReqJob_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
//@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . "\$cs_id = " . $cs_id . "\n");
//@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . "\$arr = " . json_encode($arr) . "\n");
//@fclose($fileHandle);
sort($arr);
$result = "new Array(";
for ($i = 0; $i < count($arr); $i++) {
if (substr(trim($arr[$i]), -1, 1) == ",")
$arr[$i] = trim(substr(trim($arr[$i]), 0, -1));
if ($result == "new Array(")
$result .= "'" . rawurlencode($arr[$i]) . "'";
else
$result .= ",'" . rawurlencode($arr[$i]) . "'";
}
$result .= ")";
} elseif ($csc_id != "") {
$sqlquery = "SELECT usr.usr_email, cs.cs_jbstatusmail2csc, cs.cs_jbstatusmail, cs.cs_jbstatusmail2, cs.cs_jbstatusmail3, cscad.cscad_email"
. " FROM costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr"
. " WHERE csc.csc_id = " . $csc_id . " AND"
. " csc.cs_id = cs.cs_id AND"
. " cs.cs_admin = emp.emp_id AND"
. " emp.usr_id = usr.usr_id AND"
. " csc.csc_id = cscad.csc_id AND"
. " cscad.adt_id = '2' AND"
. " ((usr.usr_email != '' AND cs.cs_jbstatusmail2csc = '0') OR"
. " (cscad.cscad_email != '' AND cs.cs_jbstatusmail2csc = '1'))";
$res = $db->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
$result = "'";
if ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
$cs_jbstatusmailstr = "";
if ($row["cs_jbstatusmail"] == "1")
$cs_jbstatusmailstr .= "Erledigung";
if ($row["cs_jbstatusmail3"] == "1")
$cs_jbstatusmailstr .= ($cs_jbstatusmailstr == "" ? "" : "/") . "Erfassung";
if ($row["cs_jbstatusmail2"] == "1")
$cs_jbstatusmailstr .= ($cs_jbstatusmailstr == "" ? "" : "/") . "Abholung";
if ($cs_jbstatusmailstr != "") {
$result .= "Automatische Mail bei " . $cs_jbstatusmailstr . " an &lt";
if ($row["cs_jbstatusmail2csc"] == "0")
$result .= str_replace(" ", "", $row["usr_email"]);
else
$result .= str_replace(" ", "", $row["cscad_email"]);
$result .= "&gt";
}
endif;
$res->free();
$result .= "'";
} elseif (isset($csc_id_ask_mail) && $csc_id_ask_mail != "") {
$cs_jbstatusmail_fields = getFieldValueFromId("customer", "cs_id", $cs_id_ask_mail, "cs_jbstatusmail_fields");
$empIdActCC24State = false;
$empHqList = getParameterValue("0", "HEADQUARTERS_MULTIPLE_ACCESS_EMPLOYEES", "0") . "|300001";
if ($empHqList != "") {
$empIdActCC24State = isInParameterString($emp_id, $empHqList);
}
$result = "'";
if ((substr($cs_jbstatusmail_fields, 3, 1) == "1" && (getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "0" || $empIdActCC24State)) ||
(getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) != "0" && (getParameterValue($emp_id, "MODE_LATER_JOB") != "0" || $vht_id >= 7 /* Immer Status-Mails bei LKWs */ || getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "2"))):
$sqlquery = "SELECT usr.usr_email, cs.cs_jbstatusmail2csc, cs.cs_jbstatusmail, cscad.cscad_email"
. " FROM costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr"
. " WHERE csc.csc_id = " . ($csc_id_ask_mail == getParameterValue("0", "CSC_ID_PAYER_CASH", $hq_id) ? $csc_id_payer_cash : $csc_id_ask_mail) . " AND"
. " csc.cs_id = cs.cs_id AND"
. " cs.cs_admin = emp.emp_id AND"
. " emp.usr_id = usr.usr_id AND"
. " csc.csc_id = cscad.csc_id AND"
. " cscad.adt_id = '2'";
//echo $sqlquery . "<br>\n";
$today = getdate();
// $fileHandle = @fopen("../log/ajaxReqJob_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
// @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] \$jb_id = $jb_id [" . $sqlquery . "] . \n");
// @fclose($fileHandle);
$res = $db->query($sqlquery);
if (DB::isError($res)) die ("$PHP_SELF: " . $res->getMessage());
while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
$ask_for_statusmail =
(getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "0" || $empIdActCC24State) ||
((getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) != "0" && (getParameterValue($emp_id, "MODE_LATER_JOB") == "1" || $vht_id >= 7 || getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "2"))
&& ($row["cs_jbstatusmail"] == "1" || (substr($cs_jbstatusmail_fields, 3, 1) == "1"))
);
$statusmail2csc = $row["cs_jbstatusmail2csc"];
if (trim($row["usr_email"]) != "" && $ask_for_statusmail && $statusmail2csc == "0")
$result .= trim($row["usr_email"]);
if (trim($row["cscad_email"]) != "" && $ask_for_statusmail && $statusmail2csc == "1")
$result .= trim($row["cscad_email"]);
endwhile;
$res->free();
// $fileHandle = @fopen("../log/ajaxReqJob_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
// @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] \$ask_for_statusmail = " . $ask_for_statusmail . ", \$statusmail2csc = " . $statusmail2csc . " \n");
// @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [" . $result . "] \n");
// @fclose($fileHandle);
endif;
$result .= "'";
} elseif (isset($cs_id_photo) && $cs_id_photo != "") {
list($cs_photo_disabled, $cs_photo_hq, $cs_photo_cs, $cs_photo_range_from, $cs_photo_range_to) = getCsPhotoConf($cs_id_photo);
$result = "new Array('" . $cs_photo_disabled . "', '" . $cs_photo_hq . "', '" . $cs_photo_cs . "', '" . $cs_photo_range_from . "', '" . $cs_photo_range_to . "')";
}
echo "retValue = $result;";
?>

View File

@@ -0,0 +1,22 @@
<?php
/*=======================================================================
*
* ajaxReqJobUnlock.php
*
* Autor: Carsten Annacker
*
=======================================================================*/
include_once("../include/global.inc.php");
getSecHttpVars("1", array("jb_id"));
$fileHandle = @fopen("../log/ajaxReqJobUnlock_" . date("Ym") . ".log", 'a');
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] \$jb_id = " . $jb_id . "\n");
updateStmt("job", "jb_id", $jb_id, array("jb_locktime", NULL, "jb_lockuser", NULL));
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] ... unlocked\n");
@fclose($fileHandle);
?>

View File

@@ -0,0 +1,558 @@
<?php
//include_once("../include/auth.inc.php");
include_once("../include/global.inc.php");
include_once("../locating/xServer.inc.php");
include_once("../include/services_func.inc.php");
getSecHttpVars("1",array("hq_id", "cs_id", "vht_id", "jb_markup", "jb_ordertime", "a", "mode", "jb_id", "usr_id", "fake"));
writeLog_ajaxReqKmPrice("\$a = " . $a . ", \$hq_id = " . $hq_id . ", \$cs_id = " . $cs_id . ", \$vht_id = " . $vht_id . ", \$jb_markup = " . $jb_markup . ", \$jb_ordertime = " . $jb_ordertime . ", \$mode = " . $mode . ", \$jb_id = " . $jb_id . ", \$usr_id = " . $usr_id . ", \$fake = " . $fake);
//$mode = "zone";
$ajaxReqKmPrice = true;
$a = str_replace("\'", "'", $a);
$error_msg = "";
// extracted from [(isset($mode) && $mode == "coords")] because hq_id_dispo is needed in zone-price too
if (trim($a) == "") {
$error_msg = "Adressangaben fehlen";
} else {
$address_parts = explode(";", explode("|", $a)[0]);
writeLog_ajaxReqKmPrice("\$address_parts = " . json_encode($address_parts));
if ($address_parts[4] == "DE" || $address_parts[4] == "D") {
writeLog_ajaxReqKmPrice("\$sqlquery = " . "SELECT hq_id FROM serviceplz WHERE srvp_plz = '" . $address_parts[2] . "'");
$hq_id_dispo = $db->getOne("SELECT hq_id FROM serviceplz WHERE srvp_plz = '" . $address_parts[2] . "'");
if ($hq_id_dispo == "")
$hq_id_dispo = 0;
writeLog_ajaxReqKmPrice("\$address_parts[2] = " . $address_parts[2] . ", \$address_parts[4] = " . $address_parts[4] . ", \$hq_id_dispo = " . $hq_id_dispo . "\n");
} else {
$sqlquery =
"SELECT hq_id, hq_gps_long, hq_gps_lat" .
" FROM headquarters WHERE hq_gps_long > 0 AND hq_gps_lat > 0 ORDER BY (SQRT(POW(ABS(hq_gps_lat - " . $address_parts[5] . "),2) + POW(ABS(hq_gps_long - " . $address_parts[6] . "),2)) * 111) LIMIT 3";
writeLog_ajaxReqKmPrice("\$sqlquery = " . $sqlquery);
$res = $db->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
$round_kms_min = 0;
$hq_id_min = 0;
while ($row = $res->fetch_assoc()) {
writeLog_ajaxReqKmPrice("\$retValue = " . $retValue . "\n");
$round_kms = get_tour_distance(array(array($row["hq_gps_lat"], $row["hq_gps_long"]), array($address_parts[5], $address_parts[6])));
writeLog_ajaxReqKmPrice("\$row[\"hq_id\"] = " . $row["hq_id"] . ", \$round_kms[0] = " . $round_kms[0]);
if ($round_kms_min == 0 || $round_kms[0] < $round_kms_min) {
$round_kms_min = $round_kms[0];
$hq_id_min = $row["hq_id"];
}
}
$res->free();
$hq_id_dispo = $hq_id_min;
}
}
if ($error_msg == "" && isset($mode) && $mode == "coords") {
set_coords($address_parts[4], $address_parts[2], $address_parts[3], $address_parts[0], $address_parts[1], $address_parts[5], $address_parts[6], $address_parts[7]);
$retValue = "retValue = " . $hq_id_dispo . ";";
writeLog_ajaxReqKmPrice("\$retValue = " . $retValue . "\n");
echo $retValue;
exit();
}
if ($error_msg == "" && isset($mode) && $mode == "full_address") {
list ($accuracy, $country, $postal_code, $locality, $route, $street_number) = get_address(0, 0, $a);
$hq_id_dispo = $db->getOne("SELECT hq_id FROM serviceplz WHERE srvp_plz = '" . $postal_code . "'");
if ($hq_id_dispo == "")
$hq_id_dispo = 0;
$retValue = "retValue = ['" . $accuracy . "','" . $country . "','" . $postal_code . "','" . $locality . "','" . $route . "','" . $street_number . "','" . $hq_id_dispo . "'];";
writeLog_ajaxReqKmPrice("\$retValue = " . $retValue . "\n");
echo $retValue;
exit();
}
$hq_id_real = $hq_id;
if ($hq_id_dispo != 0)
$hq_id = $hq_id_dispo;
writeLog_ajaxReqKmPrice("\$hq_id_real = " . $hq_id_real . ", \$hq_id_dispo = " . $hq_id_dispo . " (\$address_parts[2] = " . $address_parts[2] . ")" . ", \$hq_id = " . $hq_id . "\n");
if (trim($jb_ordertime) == "")
$jb_ordertime = date("Y-m-d H:i:s");
$srvt_name = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '" . $vht_id . "' AND mt_type = 'vehicletype'");
if (trim($jb_markup) == "")
$jb_markup = getFuelMarkup($srvt_name, $cs_id, $hq_id, $jb_ordertime);
$retValue = "";
$total_km = 0;
$total_km_osm = 0;
$zones = array();
$total_km_price = 0;
$total_km_cr_price = 0;
$points = "";
$pointsPZM = "";
$stops = array();
$addresses = explode("|", $a);
$weitere_adressen = 0;
$country_codes = get_country_codes();
$log_optimized_route = "";
if ($error_msg == "") {
if (isset($mode) && $mode == "zone" && $vht_id == "") {
$error_msg = "Fahrzeugtyp muss für PZM-Preis definiert sein";
} else {
if (isset($mode) && $mode == "plz") {
$ad_zipcode = "";
$ad_zipcode_prev = "";
define("MASK_CASH_PAYER_SELECT", getParameterValue("0", "MASK_CASH_PAYER_SELECT", $hq_id));
$dontcheckfakezipcodes = ($fake == "false");
}
for ($i = 0; $i < count($addresses); $i++) {
$address_parts = explode(";", $addresses[$i]);
$ad_street = my_str_check($address_parts[0]);
$tr_hsno = my_str_check($address_parts[1]);
if (isset($mode) && $mode == "plz")
$ad_zipcode_prev = $ad_zipcode;
$ad_zipcode = $address_parts[2];
$ad_city = my_str_check($address_parts[3]);
$ad_country = $address_parts[4];
if ($i == 0 && isset($mode) && $mode == "zone" && $hq_id == "") {
$hq_id = $db->getOne("SELECT hq_id FROM serviceplz WHERE srvp_plz = '" . $ad_zipcode . "'");
if ($hq_id == "")
$error_msg = "Niederlassung muss für PZM-Preis definiert sein";
}
if (isset($mode) && $mode == "plz") {
// Wenn Auslandsadresse kann kein Preis ermittelt werden
if ($ad_country != "DE" && $ad_country != "D") {
$retValue = "retValue = [" . $jb_markup . ", ['" . $ad_country . "-" . $ad_zipcode . " ist im Ausland',0,0]";
break;
}
if (!$dontcheckfakezipcodes) {
// Wenn PLZ Fake-PLZs enthält, kann kein Preis ermittelt werden
$fake_zipcode = $db->getOne("SELECT DISTINCT srvp1.srvp_plz AS srvp1_plz FROM servicesubareamapping AS srvsam, serviceplz AS srvp1 WHERE srvsam.srva_id = srvp1.srvp_id AND srvp1.srvp_plz IN ('" . $ad_zipcode . "', '" . $ad_zipcode . "')");
if ($fake_zipcode != "") {
$retValue = "retValue = [" . $jb_markup . ", ['" . $fake_zipcode . " hat Fake-PLZs',0,0]";
break;
}
}
if ($i == 0) {
list ($fp, $fd, $fpm, $customer_specific) =
saveServiceCosts("Grundpreis", $srvt_name, $hq_id, $cs_id, 0 /*$jb_id*/, 0, $jb_ordertime, 0 /*count*/, 1 /*$costsplit_count*/, 1 /*$getPriceOnly*/, false /*$jb_cash*/, "0" /*$csc_id_payer*/, 0 /*$jb_storno*/, false /*zipcode1*/, false /*zipcode2*/, false, $jb_markup, 0 /*$jb_cr_markup*/, $vht_id);
$retValue = "retValue = [" . $jb_markup . ", ['" . $srvt_name . "'," . round($fp * ((100-$fd)/100), 2) . "," . round($fp * ((100-$fdm)/100), 2) . "]";
} else {
list ($fp, $fd, $fpm, $customer_specific) =
saveServiceCosts($ad_zipcode_prev, $ad_zipcode, $hq_id, $cs_id, 0 /*$jb_id*/, 0, $jb_ordertime, 0 /*count*/, 1 /*$costsplit_count*/, 1 /*$getPriceOnly*/, false /*$jb_cash*/, "0" /*$csc_id_payer*/, 0 /*$jb_storno*/, false /*zipcode1*/, false /*zipcode2*/, true, $jb_markup, 0 /*$jb_cr_markup*/, $vht_id);
// Ein einziger 0-Preis -> Gesamtpreis nicht ermittelbar
if ($fp == 0) {
$retValue = "retValue = [" . $jb_markup . ", ['". "PLZ " . $ad_zipcode_prev . " nach PLZ " . $ad_zipcode . " hat 0-Preis',0,0]";
break;
}
$retValue .= ",['" . "PLZ " . $ad_zipcode_prev . " nach PLZ " . $ad_zipcode . "'," . round($fp * ((100-$fd)/100), 2) . "," . round($fp * ((100-$fdm)/100), 2) . "]";
}
} else {
$coords = get_coords($ad_country, $ad_zipcode, $ad_city, $ad_street, $tr_hsno);
if ($coords[0] != 0 && $coords[1] != 0) {
$stops[] = $coords;
$stopMap = str_replace("/", "%2F", my_str_check($ad_street)) . " " . str_replace("/", "%2F", $tr_hsno) . ", " . str_replace("/", "%2F", $ad_zipcode) . " " .
str_replace("/", "%2F", my_str_check($ad_city)) . "," . $country_codes[($ad_country == "D" ? "DE" : $ad_country)];
$points .= "/" . $stopMap;
$pointsPZM .= "/" . $coords[0] . "," . $coords[1];
} else {
$error_msg = "Adresse in " . ($i + 1) . ". Station nicht ok";
break;
}
}
}
}
}
//https://bwv-test.assecutor.de/include/ajaxReqKmPrice.php?hq_id=3&cs_id=828755&vht_id=5&jb_markup=8.5&jb_ordertime=2025-05-19%2007:00:00&mode=optimize&a=Buschkrugallee;43;12359;Berlin;DE|Schulgasse;1;14624;Dallgow;DE|Soltauer Str.;10;13509;Berlin;DE|Berliner Str.;17;13127;Berlin;DE|Bergfelder Str.;4;16547;Birkenwerder;DE|Fabrikstr.;8a;16761;Hennigsdorf;DE|Buschkrugallee;43;12359;Berlin;DE|Korkedamm;6;12524;Berlin;DE|Buschkrugallee;43;12359;Berlin;DE|Soltauer Str.;10;13509;Berlin;DE|Berliner Str.;17;13127;Berlin;DE|Bergfelder Str.;4;16547;Birkenwerder;DE|Fabrikstr.;8a;16761;Hennigsdorf;DE
//https://bwv-test.assecutor.de/include/ajaxReqKmPrice.php?hq_id=3&cs_id=828755&vht_id=5&jb_markup=8.5&jb_ordertime=2025-05-19%2007:00:00&mode=optimize&a=Buschkrugallee;43;12359;Berlin;DE|Schulgasse;1;14624;Dallgow;DE|Soltauer Str.;10;13509;Berlin;DE|Berliner Str.;17;13127;Berlin;DE
if ($error_msg == "") {
if (isset($mode) && $mode == "plz") {
$retValue .= "];";
writeLog_ajaxReqKmPrice("\$retValue = " . $retValue . "\n");
echo $retValue;
exit();
}
if (count($stops) > 1) {
if (isset($mode) && $mode == "zone") {
$zones = get_zone_distance($stops, $hq_id);
$total_km = (float) str_replace(" km", "", $zones["distance"] / 1000);
$total_duration = (int) str_replace("s", "", $zones["duration"]);
$total_hours = intdiv($total_duration, 3600);
$total_minutes = round(($total_duration % 3600) / 60);
} elseif (isset($mode) && (($mode == "optimize" && count($stops) > 3) || ($mode == "optimizeAll") && count($stops) > 2)) {
// save distance of unchanged job for comparison reasons
list($total_km_old, $total_km_osm_old) = get_tour_distance($stops);
$total_km_min = 0;
$start = count($stops) - 2;
$end = count($stops) - 1;
if ($mode == "optimizeAll") {
$start = 1;
for($i = 1; $i < count($stops); $i++)
$realOptimizedStops[] = $i - 1;
$end = count($stops);
}
for ($i = $start; $i < $end; $i++) {
$zones = get_zone_distance($stops, $hq_id, 0, false, true);
writeLog_ajaxReqKmPrice("\$stops = " . json_encode($stops));
writeLog_ajaxReqKmPrice("\$zones[\"distance\"] = " . $zones["distance"] / 1000);
writeLog_ajaxReqKmPrice("\$realOptimizedStops = " . json_encode($realOptimizedStops));
if (isset($zones["error"]))
break;
$total_km = (float) str_replace(" km", "", $zones["distance"] / 1000);
if ($total_km_min == 0 || $total_km_min > $total_km) {
if ($mode == "optimizeAll") {
if (is_null($zones["optimizedRoute"]))
$zones["optimizedRoute"] = array(0);
writeLog_ajaxReqKmPrice("\$zones[\"optimizedRoute\"] = " . json_encode($zones["optimizedRoute"]) . " (original)");
for($j = 0; $j < count($zones["optimizedRoute"]); $j++)
$zones["optimizedRoute"][$j] = $realOptimizedStops[$zones["optimizedRoute"][$j]];
writeLog_ajaxReqKmPrice("\$zones[\"optimizedRoute\"] = " . json_encode($zones["optimizedRoute"]) . " (replaced by values in \$realOptimizedStops)");
$zones["optimizedRoute"][] = $realOptimizedStops[count($realOptimizedStops) - 1];
writeLog_ajaxReqKmPrice("\$zones[\"optimizedRoute\"] = " . json_encode($zones["optimizedRoute"]) . " (after adding last station)");
}
$total_km_min = $total_km;
$retValue = "retValue = [" . $total_km_old . "," . $total_km . ",[" . implode(",", $zones["optimizedRoute"]) . "]];";
$log_optimized_routeArr = array();
for($j = 0; $j < count($zones["optimizedRoute"]); $j++)
$log_optimized_routeArr[$j] = $zones["optimizedRoute"][$j] + 1;
$log_optimized_route = implode(",", $log_optimized_routeArr);
writeLog_ajaxReqKmPrice("\$retValue (preliminary) = " . $retValue);
}
//stops = [0,1,2] realOptimizedStops = [0,1] optimizedRoute = [0,1]
//stops = [0,2,1] realOptimizedStops = [1,0] optimizedRoute = [1,0]
//stops = [0,1,2,3] realOptimizedStops = [0,1,2] optimizedRoute = [0,1]
//stops = [0,3,2,1] realOptimizedStops = [2,1,0] optimizedRoute = [1,0]
if ($mode == "optimizeAll") {
$tmp_stop = $stops[count($stops) - 1];
$stops[count($stops) - 1] = $stops[$i];
$stops[$i] = $tmp_stop;
$tmp_real_stop = $realOptimizedStops[count($realOptimizedStops) - 1];
$realOptimizedStops[count($realOptimizedStops) - 1] = $realOptimizedStops[$i - 1];
$realOptimizedStops[$i - 1] = $tmp_real_stop;
}
}
} elseif (isset($mode) && ($mode == "optimize" || $mode == "optimizeAll")) {
$retValue = "retValue = ['ERROR','\$mode=" . $mode . ", count(\$stops) = " . count($stops) . "'];";
} else {
list($total_km, $total_km_osm) = get_tour_distance($stops);
// list($total_km, $total_km_osm) = get_tour_distance($stops, $jb_ordertime);
}
$weitere_adressen = count($stops) - 2;
}
if (isset($mode) && ($mode == "optimize" || $mode == "optimizeAll")) {
writeLog_ajaxReqKmPrice("\$retValue = " . $retValue . "\n");
writeToLogDB(201, $hq_id_real, $jb_id, $usr_id, "", "", "", "MODE=" . $mode . "|TOTAL_KM_OLD=" . $total_km_old . "|TOTAL_KM=" . $total_km . "|OPTIMIZED=" . $log_optimized_route);
if (isset($zones["error"]))
$retValue = "retValue = ['ERROR','\$mode=" . $mode . ", count(\$stops) = " . count($stops) . "'];";
echo $retValue;
exit();
}
writeLog_ajaxReqKmPrice("\$total_km = " . $total_km);
if (!(isset($mode) && $mode == "zone"))
$total_km = round($total_km, 2);
$final_discount = $db->getOne("SELECT cs_discount FROM customer WHERE cs_id = '$cs_id'");
if ($final_discount == "")
$final_discount = 0;
if ($cs_id == "")
$cs_id = 0;
// $srvt_name = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '" . $vht_id . "' AND mt_type = 'vehicletype'");
if ($phpVersion >= "7.0"):
$euro_sign = chr(128);
else:
$euro_sign = chr(0xe2) . chr(0x82) . chr(0xAC);
endif;
writeLog_ajaxReqKmPrice("\$cs_id = " . $cs_id . ", \$srvt_name = " . $srvt_name);
if (!(isset($mode) && $mode == "zone")) {
list($price_per_km, $price_per_km_correction, $final_discount, $final_discount_correction, $cr_price_per_km, $final_cr_discount, $customer_specific) =
getServicePrices("km-Preis", $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
if ($cr_price_per_km == "")
$cr_price_per_km = 0;
writeLog_ajaxReqKmPrice("\$price_per_km = " . $price_per_km . ", \$cr_price_per_km = " . $cr_price_per_km);
} else {
$minimum_price = 0;
$minimum_cr_price = 0;
$minimum_price_name = "";
$zoneDistanceStr = "";
foreach ($zones["zoneDistance"] as &$zone_price) {
$srv_name = $zone_price["zone"];
if (isset($srv_names_PZM[$hq_id][$zone_price["zone"]]))
$srv_name = $srv_names_PZM[$hq_id][$zone_price["zone"]];
writeLog_ajaxReqKmPrice("getServicePrices(" . $srv_name . ", $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);");
list($price_per_km, $price_per_km_correction, $final_discount, $final_discount_correction, $cr_price_per_km, $final_cr_discount, $customer_specific) =
getServicePrices($srv_name, $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
$zone_price["price_per_km"] = (float) $price_per_km;
$zone_price["cr_price_per_km"] = (float) $cr_price_per_km;
writeLog_ajaxReqKmPrice("\$zone_price[\"price_per_km\"] = " . $zone_price["price_per_km"] . ", \$zone_price[\"cr_price_per_km\"] = " . $zone_price["cr_price_per_km"]);
if ($zone_price["price_per_km"] > 0 && $zone_price["cr_price_per_km"] == 0) {
list($cr_price_per_km, $cr_price_per_km_rate) =
getCr_price_global($price_per_km, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
writeLog_ajaxReqKmPrice("\$cr_price_per_km_rate = " . $cr_price_per_km_rate);
// take unrounded value
$zone_price["cr_price_per_km"] = $price_per_km * (100 - $cr_price_per_km_rate) / 100;
}
if ($zone_price["price_per_km"] > 0) {
$total_km_price += (strpos($zone_price["zone"], "_fix") === false ? round($zone_price["price_per_km"] * round($zone_price["distance"] / 1000, 2), 2) : round($zone_price["price_per_km"], 2));
$total_km_cr_price += (strpos($zone_price["zone"], "_fix") === false ? round($zone_price["cr_price_per_km"] * round($zone_price["distance"] / 1000, 2), 2) : round($zone_price["cr_price_per_km"], 2));
$zoneDistanceStr .= ($zoneDistanceStr != "" ? " + " : "") .
(strpos($zone_price["zone"], "_fix") === false ? format_amount(round($zone_price["distance"] / 1000, 2)) . "km " : "") . str_replace("KM-Preis ", "", $srv_names_PZM[$hq_id][$zone_price["zone"]]) .
(strpos($zone_price["zone"], "_fix") === false ? " * " : " ") . format_amount($zone_price["price_per_km"]) . $euro_sign;
}
$srv_name_min = str_replace("_km", "", str_replace("_fix", "", $zone_price["zone"])) . "_min"; // eap_fix wird für Benamsung des Mindestpreises missbraucht
if (isset($srv_names_PZM[$hq_id][$srv_name_min]))
$srv_name_min = $srv_names_PZM[$hq_id][$srv_name_min];
writeLog_ajaxReqKmPrice("\$srv_name_min = " . $srv_name_min);
list($minimum_price_tmp, $minimum_price_correction, $minimum_discount, $minimum_discount_correction, $minimum_cr_price_tmp, $minimum_cr_discount, $customer_specific) =
getServicePrices($srv_name_min, $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
if ($minimum_price < $minimum_price_tmp) {
$minimum_price = $minimum_price_tmp;
$minimum_cr_price = $minimum_cr_price_tmp;
$minimum_price_name = $srv_name_min;
}
// list($price_fix, $price_fix_correction, $final_discount, $final_discount_correction, $cr_price_fix, $final_cr_discount, $customer_specific) =
// getServicePrices($zone_price["zone"] . "_fix", $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
// $zone_price["price_fix"] = (float) $price_fix;
// $zone_price["cr_price_fix"] = (float) $cr_price_fix;
// if ($zone_price["price_fix"] > 0 && $zone_price["cr_price_fix"] == 0) {
// list($cr_price_fix, $cr_price_fix_rate) =
// getCr_price_global($price_fix, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
// // take unrounded value
// $zone_price["cr_price_fix"] = $price_fix * (100 - $cr_price_fix_rate) / 100;
// }
// if ($zone_price["price_fix"] > 0) {
// $total_km_price += round($zone_price["price_fix"], 2);
// $total_km_cr_price += round($zone_price["cr_price_fix"], 2);
// $zoneDistanceStr .= ($zoneDistanceStr != "" ? " + " : "" ) . $zone_price["zone"] . "_fix" . " (" . format_amount($zone_price["price_fix"]) . " " . $euro_sign . ")";
// }
}
unset($zone_price);
// if ($zoneDistanceStr != "")
// $zoneDistanceStr = "(" . $zoneDistanceStr . ")";
writeLog_ajaxReqKmPrice("\$zones[\"zoneDistance\"] = " . var_export($zones["zoneDistance"], true));
$extraApproachDistanceStr = "";
foreach ($zones["extraApproachDistance"] as &$eap_price) {
$srv_name = $eap_price["zone"];
if (isset($srv_names_PZM[$hq_id][$eap_price["zone"]]))
$srv_name = $srv_names_PZM[$hq_id][$eap_price["zone"]];
list($price_per_km, $price_per_km_correction, $final_discount, $final_discount_correction, $cr_price_per_km, $final_cr_discount, $customer_specific) =
getServicePrices($srv_name, $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
$eap_price["price_per_km"] = (float) $price_per_km;
$eap_price["cr_price_per_km"] = (float) $cr_price_per_km;
if ($eap_price["price_per_km"] > 0 && $eap_price["cr_price_per_km"] == 0) {
list($cr_price_per_km, $cr_price_per_km_rate) =
getCr_price_global($price_per_km, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
// take unrounded value
$eap_price["cr_price_per_km"] = $price_per_km * (100 - $cr_price_per_km_rate) / 100;
}
if ($eap_price["price_per_km"] > 0) {
$total_km_price_old = $total_km_price;
$total_km_price += (strpos($eap_price["zone"], "_fix") === false ? $eap_price["price_per_km"] * round($eap_price["distance"] / 1000, 2) : round($eap_price["price_per_km"], 2));
$total_km_cr_price += (strpos($eap_price["zone"], "_fix") === false ? $eap_price["cr_price_per_km"] * round($eap_price["distance"] / 1000, 2) : round($eap_price["cr_price_per_km"], 2));
$extraApproachDistanceStr .= ($extraApproachDistanceStr != "" ? " + " : "" ) .
format_amount(round($eap_price["distance"] / 1000, 2)) . "km " . str_replace("KM-Preis ", "", $srv_names_PZM[$hq_id][$eap_price["zone"]]) .
" * " . format_amount($eap_price["price_per_km"]) . $euro_sign;
if ($total_km_price_old != $total_km_price)
$total_km += round($eap_price["distance"] / 1000, 2);
}
// list($price_fix, $price_fix_correction, $final_discount, $final_discount_correction, $cr_price_fix, $final_cr_discount, $customer_specific) =
// getServicePrices($eap_price["zone"] . "_eap_fix", $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
// $eap_price["price_fix"] = (float) $price_fix;
// $eap_price["cr_price_fix"] = (float) $cr_price_fix;
// if ($eap_price["price_fix"] > 0 && $eap_price["cr_price_fix"] == 0) {
// list($cr_price_fix, $cr_price_fix_rate) =
// getCr_price_global($price_fix, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
// // take unrounded value
// $eap_price["cr_price_fix"] = $price_fix * (100 - $cr_price_fix_rate) / 100;
// }
// if ($eap_price["price_fix"] > 0) {
// $total_km_price += round($eap_price["price_fix"], 2);
// $total_km_cr_price += round($eap_price["cr_price_fix"], 2);
// $extraApproachDistanceStr .= ($extraApproachDistanceStr != "" ? " + " : "" ) . $eap_price["zone"] . "_eap_fix" . " (" . format_amount($eap_price["price_fix"]) . " " . $euro_sign . ")";
// }
}
unset($eap_price);
// if ($extraApproachDistanceStr != "")
// $extraApproachDistanceStr = "An-/Abfahrt in " . $extraApproachDistanceStr;
writeLog_ajaxReqKmPrice("\$zones[\"extraApproachDistance\"] = " . var_export($zones["extraApproachDistance"], true));
$extraDepartureCalculationStr = "";
foreach ($zones["extraDepartureCalculation"] as &$edc_price) {
$edc_price["zone"] = str_replace("_edc", "_eap", $edc_price["zone"]);
$srv_name = $edc_price["zone"];
if (isset($srv_names_PZM[$hq_id][$edc_price["zone"]]))
$srv_name = $srv_names_PZM[$hq_id][$edc_price["zone"]];
list($price_per_km, $price_per_km_correction, $final_discount, $final_discount_correction, $cr_price_per_km, $final_cr_discount, $customer_specific) =
getServicePrices($srv_name, $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
$edc_price["price_per_km"] = (float) $price_per_km;
$edc_price["cr_price_per_km"] = (float) $cr_price_per_km;
if ($edc_price["price_per_km"] > 0 && $edc_price["cr_price_per_km"] == 0) {
list($cr_price_per_km, $cr_price_per_km_rate) =
getCr_price_global($price_per_km, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
// take unrounded value
$edc_price["cr_price_per_km"] = $price_per_km * (100 - $cr_price_per_km_rate) / 100;
}
if ($edc_price["price_per_km"] > 0) {
$total_km_price_old = $total_km_price;
$total_km_price += (strpos($edc_price["zone"], "_fix") === false ? $edc_price["price_per_km"] * round($edc_price["distance"] / 1000, 2) : round($edc_price["price_per_km"], 2));
$total_km_cr_price += (strpos($edc_price["zone"], "_fix") === false ? $edc_price["cr_price_per_km"] * round($edc_price["distance"] / 1000, 2) : round($edc_price["cr_price_per_km"], 2));
$extraDepartureCalculationStr .= ($extraDepartureCalculationStr != "" ? " + " : "" ) .
format_amount(round($edc_price["distance"] / 1000, 2)) . "km " . str_replace("KM-Preis ", "", $srv_names_PZM[$hq_id][$edc_price["zone"]]) .
" * " . format_amount($edc_price["price_per_km"]) . $euro_sign;
if ($total_km_price_old != $total_km_price)
$total_km += round($edc_price["distance"] / 1000, 2);
}
$edc_price["zone"] = str_replace("_eap", "_edc", $edc_price["zone"]);
}
unset($edc_price);
writeLog_ajaxReqKmPrice("\$zones[\"extraDepartureCalculation\"] = " . var_export($zones["extraDepartureCalculation"], true));
}
$price_per_stop = 0;
$cr_price_per_stop = 0;
list($price_per_stop, $price_per_stop_correction, $final_discount, $final_discount_correction, $cr_price_per_stop, $final_cr_discount, $customer_specific) =
getServicePrices("Weitere<br>Adressen", $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
if ($cr_price_per_stop == "")
$cr_price_per_stop = 0;
writeLog_ajaxReqKmPrice("\$price_per_stop = " . $price_per_stop . ", \$cr_price_per_stop = " . $cr_price_per_stop);
$basic_price = 0;
$basic_cr_price = 0;
$no_basic_price = getParameterValue("0", "MASK_NO_BASIC_PRICE_FOR_KM_PRICE", $hq_id);
if ($no_basic_price != "1") {
list($basic_price, $basic_price_correction, $basic_discount, $basic_discount_correction, $basic_cr_price, $basic_cr_discount, $customer_specific) =
getServicePrices("Grundpreis", $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
// $fuel_markup = getFuelMarkup($srvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
if ($basic_cr_price == "")
$basic_cr_price = 0;
}
writeLog_ajaxReqKmPrice("\$basic_price = " . $basic_price);
if (!(isset($mode) && $mode == "zone")) {
$total_km_price = round($price_per_km * $total_km + $weitere_adressen * $price_per_stop + $basic_price, 2);
writeLog_ajaxReqKmPrice("\$total_km_price = " . $total_km_price . " ($price_per_km * $total_km + $weitere_adressen * $price_per_stop + $basic_price)");
} else {
$total_km_price += $weitere_adressen * $price_per_stop + $basic_price;
writeLog_ajaxReqKmPrice("\$total_km_price = " . $total_km_price . " ($total_km_price + $weitere_adressen * $price_per_stop + $basic_price)");
}
$isMinimum = false;
if (!(isset($mode) && $mode == "zone")) {
list($minimum_price, $minimum_price_correction, $minimum_discount, $minimum_discount_correction, $minimum_cr_price, $minimum_cr_discount, $customer_specific) =
getServicePrices("Mindestpreis", $srvt_name, $cs_id, $hq_id, $jb_ordertime, 0, $final_discount, 0, false);
}
if ($total_km_price < $minimum_price) {
$total_km_price = $minimum_price;
$isMinimum = true;
}
writeLog_ajaxReqKmPrice("\$minimum_price = " . $minimum_price);
writeLog_ajaxReqKmPrice("\$total_km_price = " . $total_km_price);
writeLog_ajaxReqKmPrice("\$isMinimum = " . $isMinimum);
if (MASK_CR_PRICE_MODE == "1") {
if ($basic_cr_price == 0) {
list($basic_cr_price, $basic_cr_price_rate) =
getCr_price_global($basic_price, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
// take unrounded value
$basic_cr_price = $basic_price * (100 - $basic_cr_price_rate) / 100;
}
writeLog_ajaxReqKmPrice("\$basic_cr_price = " . $basic_cr_price);
if ($cr_price_per_km == 0 && !(isset($mode) && $mode == "zone")) {
list($cr_price_per_km, $cr_price_per_km_rate) =
getCr_price_global($price_per_km, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
// take unrounded value
$cr_price_per_km = $price_per_km * (100 - $cr_price_per_km_rate) / 100;
}
writeLog_ajaxReqKmPrice("\$cr_price_per_km = " . $cr_price_per_km);
if ($cr_price_per_stop == 0) {
list($cr_price_per_stop, $cr_price_per_stop_rate) =
getCr_price_global($price_per_stop, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
// take unrounded value
$cr_price_per_stop = $price_per_stop * (100 - $cr_price_per_stop_rate) / 100;
}
writeLog_ajaxReqKmPrice("\$cr_price_per_stop = " . $cr_price_per_stop);
if (!(isset($mode) && $mode == "zone")) {
$total_km_cr_price = round($cr_price_per_km * $total_km + $weitere_adressen * $cr_price_per_stop + $basic_cr_price, 2);
writeLog_ajaxReqKmPrice("\$total_km_cr_price = " . $total_km_cr_price . " ($cr_price_per_km * $total_km + $weitere_adressen * $cr_price_per_stop + $basic_cr_price)");
} else {
$total_km_cr_price += $weitere_adressen * $cr_price_per_stop + $basic_cr_price;
writeLog_ajaxReqKmPrice("\$total_km_cr_price = " . $total_km_cr_price . " (total_km_cr_price + $weitere_adressen * $cr_price_per_stop + $basic_cr_price)");
}
if ($minimum_cr_price == 0)
list($minimum_cr_price, $minimum_cr_price_rate) =
getCr_price_global($total_km_price, $hq_id, $cs_id, $jb_ordertime, $srvt_name, $vht_id);
writeLog_ajaxReqKmPrice("\$minimum_cr_price = " . $minimum_cr_price);
if($total_km_cr_price < $minimum_cr_price)
$total_km_cr_price = $minimum_cr_price;
writeLog_ajaxReqKmPrice("\$total_km_cr_price = " . $total_km_cr_price);
}
//writeLog_ajaxReqKmPrice("\$basic_price = $basic_price, \$basic_cr_price = $basic_cr_price, \$basic_cr_price_rate = $basic_cr_price_rate, \$price_per_km = $price_per_km, \$cr_price_per_km = $cr_price_per_km, \$cr_price_per_km_rate = $cr_price_per_km_rate, \$price_per_km * (100 - \$cr_price_per_km_rate) / 100 = " . ($price_per_km * (100 - $cr_price_per_km_rate) / 100));
$retValue = "retValue = [" .
" '" . format_amount(round($total_km_price * (100 + $jb_markup)) / 100) . " " . $euro_sign . ($isMinimum ? " [M]" : "") . "'," .
(!(isset($mode) && $mode == "zone")
? " '" . rawurlencode($points . "/") . "',"
// : " '" . rawurlencode(str_replace("\\", ".", $zones["poliline"])) . "&p1=" . (isset($zones["eapLeg"][0]["polyline"]["encodedPolyline"]) ? rawurlencode(str_replace("\\", ".", $zones["eapLeg"][0]["polyline"]["encodedPolyline"])) : "") .
: " '" . $zones["di_ids"]["legs"] . "&p1=" . $zones["di_ids"]["eapLeg"] . "&p2=" . $zones["di_ids"]["edcLeg"] .
"&s=" . rawurlencode($points) . rawurlencode($pointsPZM) . "',"
) .
" '" . format_amount($total_km) . " Km'," .
(!(isset($mode) && $mode == "zone")
? " '" . format_amount($price_per_km) . " " . $euro_sign . " pro Km', '" .
($weitere_adressen > 0 && $price_per_stop > 0
? " + " . format_amount($price_per_stop) . " " . $euro_sign . " pro " . $weitere_adressen . " weitere Adresse(n) "
: ""
) .
($basic_price > 0
? " + " . format_amount($basic_price) . " " . $euro_sign . " Anfahrt " . $srvt_name
: ($no_basic_price != "1" ? " (Anfahrtskosten fehlen!)" : "")
) .
" = " . format_amount($price_per_km * $total_km + $price_per_stop * $weitere_adressen + $basic_price) . " " . $euro_sign . " + " . format_amount($jb_markup) . "% Tz.',"
: " '(" . $extraApproachDistanceStr . ($extraApproachDistanceStr != "" ? " + " : "") . $zoneDistanceStr . ($extraDepartureCalculationStr != "" ? " + " : "") . $extraDepartureCalculationStr . ")" . ($basic_price > 0 ? " + " . format_amount($basic_price) . " " . $euro_sign . " " . $srvt_name : "") .
($price_per_stop > 0 && $weitere_adressen > 0 ? " + " . format_amount($price_per_stop) . " " . $euro_sign . " pro " . $weitere_adressen . " weitere Adresse(n)" : "") . "'," .
"' = " . format_amount($total_km_price) . " " . $euro_sign . " + " . format_amount($jb_markup) . "% Tz.',"
) .
" '" .
(!(isset($mode) && $mode == "zone") || $srv_names_PZM[$hq_id]["runden"]
? format_amount(ceil($total_km_price))
: format_amount($total_km_price)
) .
"'," .
" '" . format_amount($total_km_cr_price) . "'," .
" '" . $mode . "', '" .
((isset($mode) && $mode == "zone")
? $zones["di_ids"]["legs"] . (trim($zones["di_ids"]["eapLeg"]) != "" ? ";" : "") . $zones["di_ids"]["eapLeg"] . (trim($zones["di_ids"]["edcLeg"]) != "" ? ";" : "") . $zones["di_ids"]["edcLeg"] . "', '" . $total_hours . ":" . $total_minutes
: ""
) . "', '" .
($isMinimum ? "[M] " . $minimum_price_name : "") . "'" .
"];";
//https://www.google.de/maps/dir/Luruper+Weg+6,+25469+Halstenbek/Ottensener+Str.+8,+22525+Hamburg
//writeLog_ajaxReqKmPrice("hallo1");
} else {
$retValue = "retValue = ['ERROR'," .
" '" . $error_msg . "'];";
}
writeLog_ajaxReqKmPrice("\$retValue = " . $retValue . "\n");
echo $retValue;
function format_amount($the_price){
return(str_replace(".", ",", sprintf("%01.2f", $the_price)));
}
function writeLog_ajaxReqKmPrice($log_text) {
global $mode;
if (!(isset($mode) && ($mode == "zone" || $mode == "optimize" || $mode == "optimizeAll" || $mode == "coords" || $mode == "full_address" || $mode == "plz")))
$mode = "km";
$fileHandle = @fopen("../log/ajaxReqKmPrice_" . $mode . "_" . date("Ym") . ".log", 'a');
if (!$fileHandle) {
$fileHandle = @fopen("../log/ajaxReqKmPrice_" . $mode . "_" . date("Ym") . ".web.log", 'a');
}
fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . $log_text . "\n");
@fclose($fileHandle);
return;
}
?>

277
html/include/ajaxReqLib.php Normal file
View File

@@ -0,0 +1,277 @@
<?php
include_once ("../include/global.inc.php");
include_once ("../include/auth.inc.php");
// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "mode", "submode", "db_table", "db_id_field", "search_value", "db_return_field", "db_op_field", "new_content", "clause", "wrap_html",
"id_01", "id_02", "id_03", "id_04", "id_05", "value_01", "value_02", "value_03", "value_04", "value_05"));
if ($mode != "") :
header("Content-Type: text/html; charset=ISO-8859-1\n");
endif;
// echo "alert('" . $mode . " ' + '" . $db_table . " ' + '" . $db_id_field . " ' + '" . $search_value . " ' + '" . $db_return_field . " ' + '" . $db_op_field . " ');";
/*
MODE : FUNCTIONALITY
0 : Gets a value of a special field by ID [getFieldValueFromId(....)]
1 : Gets an array of field values by ID [getFieldsValueFromId(....)]
2 : Gets the first value of a special field if at least one entry does exist [getOneStmt(....)]
3 : Gets a vector of a specifield field
4 : Gets the maximum value of a DB field regarding a where clause [getMaxOfField(....)]
5 : Gets the value for a key in table "parameter" (getObjectBasedParameterValue($key, $objId, $hqId, $empId))
6 : Multi select statement; gets the first value of a special field if at least one entry does exist
7: Gets a value of a field clause [getFieldValueFromClause(....)]
100 : Update a field value by ID [updateStmt(....)]
200 : Insert fields into table and return last insert ID [insertStmt(...); getLastInsertId();]
300 : Write logdata into log database
400 : Inserts address and returns address ID
500 : Inserts entry in GDC if does not exist or update value
*/
function wrap_html($aStr) {
global $wrap_html;
if ($wrap_html == "1") :
// $aStr = my_str_check_html($aStr);
$aStr = str_replace("%u20AC", '&euro;', $aStr);
endif;
return $aStr;
}
if ($submode == "") :
$submode = "0";
endif;
if ($db_table != "") : $db_table = urldecode($db_table); else : $db_table = ""; endif;
if ($db_return_field != "") : $db_return_field = urldecode($db_return_field); else : $db_return_field = ""; endif;
if ($clause != "") : $clause = urldecode($clause); else : $clause = ""; endif;
if ($value_01 != "") : $value_01 = urldecode($value_01); else : $value_01 = ""; endif; $value_01 = wrap_html($value_01);
if ($value_02 != "") : $value_02 = urldecode($value_02); else : $value_02 = ""; endif; $value_02 = wrap_html($value_02);
if ($value_03 != "") : $value_03 = urldecode($value_03); else : $value_03 = ""; endif; $value_03 = wrap_html($value_03);
if ($value_04 != "") : $value_04 = urldecode($value_04); else : $value_04 = ""; endif; $value_04 = wrap_html($value_04);
if ($value_05 != "") : $value_05 = urldecode($value_05); else : $value_05 = ""; endif; $value_05 = wrap_html($value_05);
if ($mode == "0") :
// Gets a value of a special field by ID
$retValue = getFieldValueFromId($db_table,$db_id_field,$search_value,$db_return_field);
echo "retValue = '" . my_str_check_js($retValue) . "';\n";
elseif ($mode == "1") :
// Gets an array of field values by ID
echo "retValue = new Array();\n";
$db_return_field_array = spliti("---", $db_return_field);
$db_return_field_array_len = count($db_return_field_array);
if ($db_return_field_array_len > 0) :
$fieldValues = getFieldsValueFromId($db_table,$db_id_field,$search_value,$db_return_field_array);
$fieldValuesLen = count($fieldValues);
if ($fieldValuesLen > 0) :
for ($j = 0; $j < $fieldValuesLen; $j++) :
echo "retValue['" . $db_return_field_array[$j] . "'] = '" . $fieldValues[$j] . "';\n";
endfor;
endif;
endif;
elseif ($mode == "2") :
// Gets the first value of a special field if at least one entry does exist
if ($submode == "0") :
$retValue = getOneStmt("SELECT " . $db_return_field . " FROM " . $db_table . " WHERE " . $db_id_field . " = '" . $search_value . "' ", $db_return_field);
elseif ($submode == "1") :
$retValue = getOneStmt("SELECT " . $db_return_field . " FROM " . $db_table . " WHERE " . $clause, $db_return_field);
else :
$retValue = getOneStmt("SELECT " . $db_return_field . " FROM " . $db_table . " WHERE " . $db_id_field . " = '" . $search_value . "' ", $db_return_field);
endif;
echo "retValue = '" . my_str_check_js($retValue) . "';\n";
elseif ($mode == "3") :
// Gets a vector of a specifield field
/*
getColVectorFromDB2ArrayByClause($table, $pValName, $pWhereClause, $pKeyName = "", $pSortName = "")
getColVectorFromDB2ArrayByClause("metafieldkey", "mtfk_id", "", "", $sort)
getColVectorFromDB2ArrayByClause("metafieldvalue", "mtfv_value", "mtfv_id = '" . $objId . "' AND mtfck_id IN (" . implode($mtfck_mtfckIds, ",") . ")", "mtfck_id", "");
*/
elseif ($mode == "4") :
// Gets the maximum value of a DB field regarding a where clause
$retValue = getMaxOfField($db_table, $db_id_field, $clause);
echo "retValue = '" . $retValue . "';\n";
elseif ($mode == "5") :
// Gets the value for a key in table "parameter" (getObjectBasedParameterValue($key, $objId, $hqId, $empId))
$retValue = getObjectBasedParameterValue($search_value, $id_01, $id_02, $id_03);
echo "retValue = '" . $retValue . "';\n";
elseif ($mode == "6") :
// Gets the first value of a special field if at least one entry does exist
$retValue = "";
$whereClause = "";
if ($id_01 != "" && $value_01 != "") :
$whereClause .= " " . $id_01 . " = '" . $value_01 . "' ";
endif;
if ($id_02 != "" && $value_02 != "") :
if ($whereClause != "") : $whereClause .= " AND "; endif;
$whereClause .= " " . $id_02 . " = '" . $value_02 . "' ";
endif;
if ($id_03 != "" && $value_03 != "") :
if ($whereClause != "") : $whereClause .= " AND "; endif;
$whereClause .= " " . $id_03 . " = '" . $value_03 . "' ";
endif;
if ($id_04 != "" && $value_04 != "") :
if ($whereClause != "") : $whereClause .= " AND "; endif;
$whereClause .= " " . $id_04 . " = '" . $value_04 . "' ";
endif;
if ($id_05 != "" && $value_05 != "") :
if ($whereClause != "") : $whereClause .= " AND "; endif;
$whereClause .= " " . $id_05 . " = '" . $value_05 . "' ";
endif;
if ($db_table != "" && $db_return_field != "" && $whereClause != "") :
$retValue = getOneStmt("SELECT " . $db_return_field . " FROM " . $db_table . " WHERE " . $whereClause, $db_return_field);
endif;
echo "retValue = '" . my_str_check_js($retValue) . "';\n";
elseif ($mode == "7") :
// Gets a value of a field clause
$whereClause = "";
for ($i = 1; $i <= 5; $i++) :
$tmpKey = ${("id_" . pad($i,2))};
$tmpValue = ${("value_" . pad($i,2))};
if ($tmpKey != "" && $tmpValue != "") :
if ($whereClause != "") : $whereClause .= " AND "; endif;
$whereClause .= $tmpKey . "= '" . $tmpValue . "'";
endif;
endfor;
$retValue = getFieldValueFromClause($db_table,$db_return_field,$whereClause);
echo "retValue = '" . my_str_check_js($retValue) . "';\n";
elseif ($mode == "100") :
// Update a field value by ID
$new_content = urldecode($new_content);
$new_content = strWrapJs($new_content);
if ($submode == "1") :
if ($clause != "") : $clause .= " AND "; endif;
$clause .= $db_id_field . " = '" . $search_value . "'";
$old_content = getOneStmt("SELECT " . $db_op_field . " FROM " . $db_table . " WHERE " . $clause, $db_op_field);
$old_content = trim($old_content);
if ($old_content != "") : $old_content = " |||| " . $old_content; endif;
$new_content .= $old_content;
endif;
updateStmt($db_table, $db_id_field, $search_value, array($db_op_field, $new_content), $clause);
elseif ($mode == "200") :
// Insert fields into table and return last insert ID
$id_new = "-1";
$db_op_field = urldecode($db_op_field);
$db_op_field = strWrapJs($db_op_field);
$db_op_field = utf8_decode($db_op_field);
$db_op_field_array = spliti("---", $db_op_field);
$db_op_field_array_len = count($db_op_field_array);
if ($db_op_field_array_len > 0) :
insertStmt($db_table, $db_op_field_array);
$id_new = getLastInsertId();
if ($id_new == "") : $id_new = "0"; endif;
endif;
echo "retValue = '" . $id_new . "';\n";
elseif ($mode == "300") :
// Write logdata into log database
// db_id_field : logo_id
// db_op_field : jb (= job)
// search_value : jb_id, ....
// id_01, id_02, .... : Key
// value_01, value_02, .... : Value
if ($db_id_field != "" && is_numeric($db_id_field) && $db_op_field != "" && $search_value != "" && is_numeric($search_value)) :
$logDescription = "";
for ($i = 1; $i <= 5; $i++) :
$tmpKey = ${("id_" . pad($i,2))};
$tmpValue = ${("value_" . pad($i,2))};
if ($tmpKey != "" && $tmpValue != "") :
if ($logDescription != "") : $logDescription .= "|"; endif;
$logDescription .= $tmpKey . "=" . $tmpValue;
endif;
endfor;
$hqId = "0"; $usrId = "0"; $empId = "0";
if (isset($hq_id)) : $hqId = $hq_id; endif;
if (isset($usr_id)) : $usrId = $usr_id; endif;
if (isset($emp_id)) : $empId = $emp_id; endif;
$jbId = "0"; $crId = "0"; $csId = "0"; $atId = "0";
if ($db_op_field == "jb") :
$jbId = $search_value;
$hqId = getFieldValueFromId("job", "jb_id", $jbId, "hq_id");
endif;
if ($db_op_field == "cr") :
$crId = $search_value;
$hqId = getFieldValueFromId("courier", "cr_id", $crId, "hq_id");
endif;
if ($db_op_field == "cs") :
$csId = $search_value;
$hqId = getFieldValueFromId("customer", "cs_id", $csId, "hq_id");
endif;
if ($db_op_field == "at") :
$atId = $search_value;
$hqId = getFieldValueFromId("article", "at_id", $atId, "hq_id");
endif;
writeToLogDB($db_id_field,$hqId,$jbId,$usrId,$crId,"",$csId,$logDescription,$atId,"0",$empId);
endif;
elseif ($mode == "400") :
// Insert address and returns address ID
// value_01 : street
// value_02 : f_ad_zipcode
// value_03 : f_ad_city
// value_04 : f_ad_country
$retValue = "0";
if ($value_01 != "" && $value_02 != "" && $value_03 != "") :
$tmpArray = insertAddress($value_01, $value_02, $value_03, "", $value_04, true);
$retValue = $tmpArray[0];
if ($retValue == "") :
$retValue = "0";
endif;
endif;
echo "retValue = '" . $retValue . "';\n";
elseif ($mode == "500") :
// Update or Insert item in GDC
// value_01 : gdc_obj_type
// value_02 : gdc_obj_id
// value_03 : gdc_gen_fieldname
// value_04 : gdc_content
// value_05 : gdc_context
$retValue = "0";
if ($value_01 != "" && $value_02 != "" && $value_03 != "") :
if (existsEntry("genericdatacontainer",array("gdc_obj_type",$value_01,"gdc_obj_id",$value_02,"gdc_gen_fieldname",$value_03))) :
updateStmt("genericdatacontainer","gdc_obj_type",$value_01,array("gdc_content", $value_04, "gdc_context", $value_05),"gdc_obj_id = '" . $value_02 . "' AND gdc_gen_fieldname = '" . $value_03 . "'");
else :
insertStmt("genericdatacontainer", array("gdc_obj_type", $value_01, "gdc_obj_id", $value_02, "gdc_gen_fieldname", $value_03, "gdc_content", $value_04, "gdc_context", $value_05));
endif;
// if ($retValue == "") :
$retValue = "1";
// endif;
endif;
echo "retValue = '" . $retValue . "';\n";
endif;
?>

117
html/include/ajaxReqMap.php Normal file
View File

@@ -0,0 +1,117 @@
<?php
include_once ("../include/global.inc.php");
getSecHttpVars("1",array("cr_sid","hq_id","customer_special","jb_id","f_act"));
include_once ("../locating/map.inc.php");
//header("Content-Type: text/html; charset=ISO-8859-1\n");
//echo "alert('" . $cr_sid . "');";
if ($f_act == "setCourier" && $cr_sid != "" && $jb_id != ""):
$currentSessionUsrId = $usr_id;
setCourier($cr_sid, $jb_id);
echo "alert('Auftrag Nr. " . $jb_id . " wurde " . $cr_sid . " zugewiesen.');";
else:
$sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_available, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time, cr_gps_type, cr_mobile_pda, usr_phone, usr_phone2 FROM courier, user WHERE courier.hq_id = '$hq_id' AND cr_gps_time > '" . $start_time . "' AND courier.usr_id = user.usr_id"; //AND cr_available = 1 ORDER BY cr_gps_time, cr_sid";
if ($hq_id == 0 /*nur cr_sid*/ || $customer_special == 1):
$cr_sid = str_replace("\\", "", $cr_sid);
$sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_available, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time, cr_gps_type, cr_mobile_pda, usr_phone, usr_phone2 FROM courier, user WHERE cr_sid IN ($cr_sid) AND courier.usr_id = user.usr_id;";
// $sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_available, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time FROM courier WHERE cr_sid = '$cr_sid'";
endif;
$res = $db->query($sqlquery);
if (DB::isError($res)) die ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
$ret_value = "";
while ($row = $res->fetch_assoc()):
$cr_sid = $row["cr_sid"];
$ret_value .= "retValue['" . $cr_sid . "'] = new Array('" . $row["cr_gps_time"] . "', " . $row["cr_gps_lat"] . ", " . $row["cr_gps_long"] . ", " .
mk_text($row["cr_locationzipcode"], $row["cr_availabletime"], $row["cr_gps_time"], $row["cr_gps_type"], $row["cr_available"], $cr_sid, $row["vht_id"], $row["cr_mobile_pda"], $row["usr_phone"], $row["usr_phone2"], $jb_id) . ");\n";
endwhile;
$res->free();
//echo "alert(\"" . str_replace('"', "'", $ret_value) . "\");";
if ($jb_id != "")
echo $vht_id_str_js;
echo "retValue = new Array();\n$ret_value";
endif;
function setCourier($f_cr_sid, $f_jb_id, $f_cr_availabletime_reset = "0") {
global $db, $hq_id, $jb_status, $currentSessionUsrId;
// Get current cr_id of the job before changing the courier
$crIdCurrent = getFieldValueFromId("job","jb_id",$f_jb_id,"cr_id");
$crIdOrderCurrent = getFieldValueFromId("job","jb_id",$f_jb_id,"cr_id_order");
$jbHqId = getFieldValueFromId("job","jb_id",$f_jb_id,"hq_id");
if ($jbHqId == "" || !is_numeric($jbHqId)) : $jbHqId = $hq_id; endif;
if ($f_cr_availabletime_reset != "1") : $f_cr_availabletime_reset = "0"; endif;
// getDbFieldValues("courier",array("cr_id","cr_occupied"),array("cr_sid",$f_cr_sid));
$cr_id = getFieldValueFromClause("courier","cr_id","cr_sid = '" . $f_cr_sid . "' ORDER BY cr_logintime");
if ($cr_id != "") :
// RANKING
// Special treatment according to vehicletype ("BUS" or greater will NOT be revoked if job-order is "PKW")
// Get cr.vht_id and jb.vht_id
/*
$arLooseRanking = "1"; // Init: Loose ranking "yes"
$courierVhtId = getFieldValueFromId("courier","cr_id",$cr_id,"vht_id");
$jobVhtId = getFieldValueFromId("job","jb_id",$f_jb_id,"vht_id");
if ($courierVhtId != "" && $jobVhtId != "" && $courierVhtId >= '5' && $jobVhtId <= "3") :
$arLooseRanking = "0"; // Loose ranking "no"
endif;
*/
// Special treatment according areas
$jbAdressIdStart = getFieldValueFromClause("tour", "ad_id", "jb_id = '" . $f_jb_id . "' AND tr_sort = '1'");
$jbZipcodeStart = getFieldValueFromId("address", "ad_id", $jbAdressIdStart, "ad_zipcode");
$arLooseRanking = looseRanking($cr_id, $jbZipcodeStart, $jbHqId);
// Check first that courier is NOT occupied
// $cr_occupied = getFieldValueFromId("courier", "cr_id", $cr_id, "cr_occupied");
// if ($cr_occupied == "0") :
// if (getCountOfTable("job","cr_id_order = '" . $cr_id . "' AND (jb_status = '1' OR jb_status = '0') AND (isnull(jb_globaljob) or jb_globaljob = '0')") == 0) :
$currentTime = getDateTime("0");
TA("B");
// Update job
// According to be TA-safe the WHERE-Clause depends on the current list the user is in
$jbStatusString = " (jb_status = '8' OR jb_status = '9' OR jb_status = '0' OR jb_status = '1') ";
if (is_numeric($jb_status)) : $jbStatusString = "jb_status = '" . $jb_status . "'"; endif;
$res = updateStmt("job", "jb_id", $f_jb_id, array("cr_id", "", "cr_id_order", $cr_id, "jb_status", "0", "cr_sid", $f_cr_sid, "jb_globaljob", "0", "jb_autoranking", "0"), $jbStatusString);
// if ($db->affected_rows > 0) :
if ($res > 0) :
// Set current assigning time for revoking a job if not taken by the courier
if (existsEntry("autoranking",array("jb_id",$f_jb_id,"cr_id",$cr_id))) :
updateStmt("autoranking", "jb_id", $f_jb_id, array("ar_challenge", "0", "ar_lastassigntime", $currentTime, "ar_looseranking", $arLooseRanking, "ar_locating", "0"),"cr_id = '" . $cr_id . "'");
else :
insertStmt("autoranking", array("jb_id", $f_jb_id, "cr_id", $cr_id, "ar_challenge", "0", "ar_lastassigntime", $currentTime, "ar_looseranking", $arLooseRanking, "ar_locating", "0"));
endif;
// Insert PDA command to remove job (take cr_id/cr_id_order before changing)
$currentTimePDA = getDateTime("datetime_plus_offset", array(0,0,30,0,0,0), $formatStr = "Y-m-d H:i:s");
if ($crIdCurrent != "" && $crIdCurrent != "0") :
insertPDACommand($jbHqId, $crIdCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
endif;
if ($crIdOrderCurrent != "" && $crIdOrderCurrent != "0" && $crIdOrderCurrent != $crIdCurrent) :
insertPDACommand($jbHqId, $crIdOrderCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
endif;
// Reset availabletime of the OLD courier if requested by the disposition manually
if ($f_cr_availabletime_reset == "1") :
updateStmt("courier", "cr_id", $crIdCurrent, array("cr_availabletime", $currentTime));
endif;
// Write logdata into log database
writeToLogDB("7",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
endif;
TA("C");
TA("E");
// else :
// $statusMessage = getLngt("Dem Fahrzeug") . " " . $f_cr_sid . " " . getLngt("wurde zwischenzeitlich ein Auftrag zugewiesen! Bitte ein anderes Fahrzeug wählen.");
// endif;
endif;
}
?>

View File

@@ -0,0 +1,233 @@
<?php
include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
// include_once ("../include/inc_parseXML.inc.php");
// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "retMode", "objType", "searchValue", "fields", "hqAccess", "wrap_html"));
if ($retMode != "") :
header("Content-Type: text/html; charset=ISO-8859-1\n");
endif;
function wrap_html($aStr) {
global $wrap_html;
if ($wrap_html == "1") :
// $aStr = my_str_check_html($aStr);
$aStr = str_replace("%u20AC", '&euro;', $aStr);
endif;
return $aStr;
}
$retValue = "";
if ($searchValue != "") :
$searchValue = urldecode($searchValue);
$fields = urldecode($fields);
global $hq_id;
$sqlStmt = "";
$htmlOut = "";
// "JB"
if ($objType == "jb") :
if (is_numeric($searchValue)) :
$sqlStmt .= "
SELECT jb.jb_id, jb.cr_sid, tr.tr_id, tr.tr_commission_no
FROM
job AS jb,
tour AS tr
WHERE
jb.jb_id = '" . $searchValue . "' AND
jb.hq_id = '" . $hq_id . "' AND
jb.jb_id = tr.jb_id AND
tr.tr_sort = '1'";
endif;
$categoryTitle = getLngt("AUFTRÄGE");
$titleArray = array(getLngt("Auftrag") . "&nbsp;", getLngt("Kommissionsnummer") . "&nbsp;");
$fieldArray = array("jb_id", "tr_commission_no");
$aligns = "r,l";
$alignArray = spliti(",",$aligns);
$alignTitles = "left";
$widths = "80,250";
$widthArray = spliti(",",$widths);
$summationField = "";
$postParserField = "";
$rowLinkType = "jb";
$rowLinkField = "jb_id";
$mode = "1"; // Output from DB-RESULT
$sortDBField = ""; // Used in following include-file for sorting per column;
endif;
// "TR"
if ($objType == "tr") :
$sqlStmt .= "
SELECT jb.jb_id AS obj_id, jb.cr_sid, tr.tr_id, tr.tr_commission_no AS cmp_comp, '' AS cmp_comp2, '' AS usr_name, '' AS usr_firstname
FROM
tour AS tr,
job AS jb
WHERE
tr.tr_commission_no = '" . $searchValue . "' AND
tr.tr_sort = '1' AND
jb.jb_id = tr.jb_id AND
jb.hq_id = '3'";
// $categoryTitle = getLngt("AUFTRÄGE");
$titleArray = array(getLngt("Auftrag") . "&nbsp;", getLngt("Kommissionsnummer") . "&nbsp;");
$fieldArray = array("jb_id", "tr_commission_no");
$aligns = "r,l";
$alignArray = spliti(",",$aligns);
$alignTitles = "left";
$widths = "80,100";
$widthArray = spliti(",",$widths);
$summationField = "";
$postParserField = "";
$mode = "1";
$sortDBField = "";
endif;
// CS
if ($objType == "cs") :
$sqlStmt .= "
SELECT cs.cs_id, cs.cs_eid, cmp.cmp_id, cmp.cmp_comp, CONCAT(usr.usr_name,', ',usr.usr_firstname) AS usr_data
FROM
customer AS cs,
company AS cmp,
employee AS emp,
user AS usr
WHERE
cs.cmp_id = cmp.cmp_id AND
cmp.cmp_archived = '0' AND
cs.cs_admin = emp.emp_id AND
emp.usr_id = usr.usr_id AND
cs.hq_id = '" . $hq_id . "' AND
(
cs.cs_eid LIKE '%" . $searchValue . "%' OR
cmp.cmp_comp LIKE '%" . $searchValue . "%' OR
cmp.cmp_match LIKE '%" . $searchValue . "%' OR
usr.usr_name LIKE '%" . $searchValue . "%' OR
usr.usr_firstname LIKE '%" . $searchValue . "%'
)
ORDER BY cmp.cmp_comp";
$categoryTitle = getLngt("KUNDEN");
$titleArray = array(getLngt("EID") . "&nbsp;", getLngt("Firma") . "&nbsp;", getLngt("Name, Vorname") . "&nbsp;");
$fieldArray = array("cs_eid", "cmp_comp", "usr_data");
$aligns = "l,l,l";
$alignArray = spliti(",",$aligns);
$alignTitles = "left";
$widths = "80,350,250";
$widthArray = spliti(",",$widths);
$summationField = "";
$postParserField = "";
$postParserField2 = "";
$rowLinkType = "cs";
$rowLinkField = "cmp_id";
$mode = "1";
$sortDBField = "";
endif;
// CR
if ($objType == "cr") :
$sqlStmt .= "
SELECT cr.cr_id, cr.cr_eid, cmp.cmp_id, cmp.cmp_comp, CONCAT(usr.usr_name,', ',usr.usr_firstname) AS usr_data
FROM
courier AS cr,
company AS cmp,
user AS usr
WHERE
cr.cmp_id = cmp.cmp_id AND
cmp.cmp_archived = '0' AND
cr.usr_id = usr.usr_id AND
cr.hq_id = '" . $hq_id . "' AND
(
cr.cr_eid LIKE '%" . $searchValue . "%' OR
cmp.cmp_comp LIKE '%" . $searchValue . "%' OR
cmp.cmp_match LIKE '%" . $searchValue . "%' OR
usr.usr_name LIKE '%" . $searchValue . "%' OR
usr.usr_firstname LIKE '%" . $searchValue . "%'
)
ORDER BY usr_data";
$categoryTitle = getLngt("TRANSPORTEURE");
$titleArray = array(getLngt("EID") . "&nbsp;", getLngt("Firma") . "&nbsp;", getLngt("Name, Vorname") . "&nbsp;");
$fieldArray = array("cr_eid", "cmp_comp", "usr_data");
$aligns = "l,l,l";
$alignArray = spliti(",",$aligns);
$alignTitles = "left";
$widths = "80,350,250";
$widthArray = spliti(",",$widths);
$summationField = "";
$postParserField = "";
$rowLinkType = "cr";
$rowLinkField = "cmp_id";
$mode = "1";
$sortDBField = "";
endif;
// CRVH
if ($objType == "crvh") :
$sqlStmt .= "
SELECT crvh.crvh_id, crvh.crvh_sid, cr.cr_id, cr.cr_eid, CONCAT(usr.usr_name,', ',usr.usr_firstname) AS usr_data
FROM
couriervehicle AS crvh,
courier AS cr,
user AS usr
WHERE
crvh.cr_id = cr.cr_id AND
cr.hq_id = '" . $hq_id . "' AND
(
crvh.crvh_sid LIKE '%" . $searchValue . "%'
) AND
cr.usr_id = usr.usr_id
ORDER BY crvh_sid";
$categoryTitle = getLngt("FAHRZEUGE");
$titleArray = array(getLngt("SID") . "&nbsp;", getLngt("EID") . "&nbsp;", getLngt("Name, Vorname") . "&nbsp;");
$fieldArray = array("crvh_sid", "cr_eid", "usr_data");
$aligns = "l,l,l";
$alignArray = spliti(",",$aligns);
$alignTitles = "left";
$widths = "80,350,250";
$widthArray = spliti(",",$widths);
$summationField = "";
$postParserField = "";
$rowLinkType = "crvh";
$rowLinkField = "cr_id";
$mode = "1";
$sortDBField = "";
endif;
// Get result
if ($sqlStmt != "") :
$result = $db->query($sqlStmt);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
// Display result list
include ("../include/inc_list_defineoutput.inc.php");
// Post parsing if necessary
if ($postParserField != "") :
// $tableBody = substituteTagContent($tableBody, "<postparser>", "</postparser>", $substitutionString);
endif;
if ($rowCounter > 0) :
$categoryTitle = "<span style=\"width:100%; height:15px; color:green;\">" . $categoryTitle . "</span>";
$htmlOut = $categoryTitle . "</br>" . "<table>" . $tableHeader . $tableBody . "</table>";
endif;
endif;
$htmlOut = preg_replace("/\w*?$searchValue\w*/i", "<span style=\"background-color:yellow\">$0</span>", $htmlOut);
$retValue = my_char_conversion($htmlOut);
$retValue = my_str_check_js($retValue);
endif;
echo "searchResult = '" . $retValue . "';\n";
?>

View File

@@ -0,0 +1,196 @@
<?php
include_once("../include/auth.inc.php");
include_once("../include/global.inc.php");
$log_file_name = "../log/statistic_finishment_" . date("Ym") . ".log";
getSecHttpVars("1",array("cs_id", "attr", "val"));
myWriteLog("\$cs_id = $cs_id, \$attr = $attr, \$val = $val");
if ($attr == "Lademaße" || $attr == "Dispo-Info") {
if ($attr == "Lademaße")
$par_key = "RANKING_JB2CRVH_MEASURE_CS_IDS";
if ($attr == "Dispo-Info")
$par_key = "JB_DISPOINFO_ENABLED_CS_IDS";
$cs_ids = array();
$sql_query =
"SELECT par_text FROM parameter WHERE par_key = '" . $par_key . "' AND hq_id = " . $hq_id;
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
if ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())) {
$cs_ids = explode(",", $row['par_text']);
}
$new_par_text = "";
if ($val == 0) {
for ($i = 0; $i < count($cs_ids); $i++) {
if ($cs_ids[$i] != $cs_id)
$new_par_text .= $cs_ids[$i] . ",";
}
if ($new_par_text != "")
$new_par_text = substr($new_par_text, 0, -1);
}
if ($val == 1) {
$new_par_text = $row['par_text'] . "," . $cs_id;
}
$res->free();
$sql_query =
"UPDATE parameter SET par_text = '" . $new_par_text . "' WHERE par_key = '" . $par_key . "' AND hq_id = " . $hq_id;
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
}
if ($attr == "Orte") {
if ($val == 0) {
$sql_query =
"DELETE FROM parameter WHERE par_key IN ('CUSTOMER_MASK_JOBLIST_ADD_ON_ALIGNS', 'CUSTOMER_MASK_JOBLIST_ADD_ON_FIELDS', 'CUSTOMER_MASK_JOBLIST_ADD_ON_TITLES') AND emp_id = " . $cs_id;
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
}
if ($val == 1) {
$sql_query =
"INSERT INTO parameter (par_key, md_id, hq_id, emp_id, par_value) VALUES ('CUSTOMER_MASK_JOBLIST_ADD_ON_ALIGNS', 0, 0, " . $cs_id . ", 'l')";
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
$sql_query =
"INSERT INTO parameter (par_key, md_id, hq_id, emp_id, par_value) VALUES ('CUSTOMER_MASK_JOBLIST_ADD_ON_FIELDS', 0, 0, " . $cs_id . ", 'jb_tourcities')";
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
$sql_query =
"INSERT INTO parameter (par_key, md_id, hq_id, emp_id, par_value) VALUES ('CUSTOMER_MASK_JOBLIST_ADD_ON_TITLES', 0, 0, " . $cs_id . ", 'Stationen')";
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
}
}
if ($attr == "Stadtteile" || $attr == "Kartenansicht" || $attr == "Barzahler" || $attr == "ManuelleDisposition" /* || $attr == "Beweisfoto" || $attr == "Servicepreis" */) {
if ($attr == "Stadtteile") {
$par_key = "MASK_INSERTADDRESS_DISTRICT";
$par_value = "Berlin";
}
if ($attr == "Kartenansicht") {
$par_key = "MASK_JB_MAP_VIEW_ENABLED";
$par_value = "1";
}
if ($attr == "Barzahler") {
$par_key = "MASK_CUST_SET_PAYER";
$par_value = "1";
}
if ($attr == "ManuelleDisposition") {
$par_key = "CUSTOMER_MANUAL_DISPO";
$par_value = "1";
}
// if ($attr == "Beweisfoto") {
// $par_key = "MASK_TR_PHOTO_CS";
// $par_value = "2";
// }
if ($val == 0) {
$sql_query =
"DELETE FROM parameter WHERE par_key = '" . $par_key . "_" . $cs_id . "' ";
myWriteLog("\$sql_query = $sql_query");
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
// if ($attr == "Beweisfoto") {
// $sql_query =
// "DELETE FROM parameter WHERE par_key = 'MASK_MIN_MAX_TR_PHOTO_CS_" . $cs_id . "' ";
// myWriteLog("\$sql_query = $sql_query");
// $res = $db->query($sql_query);
// if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
// }
// if ($attr == "Servicepreis") {
// $sql_query =
// "DELETE FROM parameter WHERE par_key = 'INV_PRINT_SRVPRICE_" . $cs_id . "' ";
// myWriteLog("\$sql_query = $sql_query");
// $res = $db->query($sql_query);
// if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
// }
}
if ($val == 1) {
$sql_query =
"INSERT INTO parameter (par_key, md_id, hq_id, emp_id, par_value, par_text) VALUES ('" . $par_key . "_" . $cs_id . "', 0, 0, 0, '" . $par_value . "', '')";
myWriteLog("\$sql_query = $sql_query");
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
// if ($attr == "Beweisfoto") {
// $sql_query =
// "INSERT INTO parameter (par_key, md_id, hq_id, emp_id, par_value, par_text) VALUES ('MASK_MIN_MAX_TR_PHOTO_CS_" . $cs_id . "', 0, 0, 0, '0|1', '')";
// myWriteLog("\$sql_query = $sql_query");
// $res = $db->query($sql_query);
// if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
// }
}
}
if ($attr == "AnzahlFotos") {
$sql_query =
"UPDATE parameter SET par_value = ('" . $val . "') WHERE par_key = 'MASK_MIN_MAX_TR_PHOTO_CS_" . $cs_id . "'";
myWriteLog("\$sql_query = $sql_query");
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
}
if ($attr == "PZM-Modus") {
$hq_id = $cs_id;
$sql_query =
"UPDATE parameter SET par_value = '" . ($val == "Rundtour" ? "1" : "0") . "' WHERE par_key = 'PZM_ROUNDTRIPKM' AND hq_id = " . $hq_id;
myWriteLog("\$sql_query = $sql_query");
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
}
if ($attr == "Routenberechnung") {
$hq_id = $cs_id;
$sql_query =
"UPDATE parameter SET par_value = '" . ($val == "Absolut_kuerzeste" ? "2" : ($val == "Kuerzeste_von_drei" ? "1" : "0")) . "' WHERE par_key = 'PZM_SHORTEST' AND hq_id = " . $hq_id;
myWriteLog("\$sql_query = $sql_query");
$res = $db->query($sql_query);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sql_query' : " . $res->getMessage());
}
if (substr($attr, -4) == "_eap") {
$hq_id = $cs_id;
$url = "http://" . $dbhostPZM . "/api/zones/" . $hq_id;
$postArray = array(
"zone" => str_replace("_eap", "", $attr),
"eap" => ($val == 1 ? true : false)
);
$jsonData = json_encode(array($postArray));
myWriteLog("\$jsonData = " . $jsonData);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$json_response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// myWriteLog("get_zone_distance: [" . $json_response . "] [" . $status . "]");
// $responseArr = json_decode($json_response, true);
if ($status != 200) {
myWriteLog("Error: call to URL " . $url . " failed with status " . $status . ", response \"" . $json_response . "\", curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
echo "retValue = \"Error\";\n";
exit();
}
}
echo "retValue = \"ok\";\n";
function myWriteLog($log_text) {
global $log_file_name;
$fileHandle = @fopen($log_file_name, 'a');
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . $log_text . "\n");
@fclose($fileHandle);
}
?>

View File

@@ -0,0 +1,16 @@
<?php
include_once ("../include/global.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/inc_user.inc.php");
// Check HTTP-Parameters
// Stocks
getSecHttpVars("1",array("tickerHeader"));
if ($tickerHeader != "") :
header("Content-Type: text/html; charset=ISO-8859-1\n");
endif;
echo getUserMessages("1");
?>

View File

@@ -0,0 +1,39 @@
<?php
include_once ("../include/auth.inc.php");
include_once ("../include/global.inc.php");
getSecHttpVars("1", array("usrType", "usrFirstname", "usrName", "usrAccount", "usrPassword", "usrEmail"));
// echo "alert(\"" . str_replace('"', "'", $ret_value) . "\");";
$ret_value = "fail";
$usrType = trim($usrType);
$usrFirstname = trim($usrFirstname);
$usrName = trim($usrName);
$usrEmail = trim($usrEmail);
$usrAccount = trim($usrAccount);
$usrPassword = trim($usrPassword);
if ($usrType != "" && is_numeric($usrType) && $usrFirstname != "" && $usrName != "" && $usrEmail != "" && $usrAccount != "" && $usrPassword != "") :
$ret_value = "X1";
// Check existence of account
if (getFieldValueFromId("user","usr_account", $usrAccount,"usr_id") == "") :
$ret_value = "X2";
// Insert user
$sqlStmtPwd = "INSERT INTO user (hq_id,usr_type,usr_name,usr_firstname,usr_email,usr_inv_email,usr_phone,usr_phone2,usr_fax,usr_account,usr_password,usr_birthdate)" .
" VALUES ('$hq_id','$usrType','$usrName','$usrFirstname','$usrEmail,'','$usrPhone','$usrPhone2','$usrFax','$usrAccount',PASSWORD('$usrPassword'),'$usrBirthdate')";
// writeDbLog($sqlStmtPwd);
$res = $db->query($sqlStmtPwd);
if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
$usr_id_new = getLastInsertID();
if ($usr_id_new != "" && is_numeric($usr_id_new)) :
$ret_value = "ok";
endif;
endif;
echo "retValue = '" . $ret_value . "';\n";
endif;
?>

BIN
html/include/arial.ttf Normal file

Binary file not shown.

338
html/include/auth.inc.php Normal file
View File

@@ -0,0 +1,338 @@
<?php
/*=======================================================================
*
* auth.inc.php
*
* Autor: Carsten Annacker, Marc Vollmann
*
=======================================================================*/
if (!isset($usr_id)) : $usr_id = ""; endif;
if ($usr_id != -1):
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
session_start();
// if (!isset($_SESSION['usr_id']) && isset($_POST['usr_id'])) {
// $_SESSION['usr_id'] = $_POST['usr_id'];
// $_SESSION['hq_id'] = getOneStmt("SELECT hq_id FROM user WHERE usr_id = " . $_POST['usr_id'], "hq_id");
// $_SESSION['emp_id'] = getOneStmt("SELECT emp_id FROM employee WHERE usr_id = " . $_POST['usr_id'], "emp_id");
// $_SESSION['dbname'] = "phoenix";
// $_SESSION['randomCryptionNumber'] = 0;
// $_SESSION['chgpwd'] = 0;
// }
else
$_SESSION = array();
// if (isset($_SESSION['usr_id']))
// $_SESSION['emp_id'] = getOneStmt("SELECT emp_id FROM employee WHERE usr_id = " . $_SESSION['usr_id'], "emp_id");
// prevent db change on multiple installations on one server
$HTTP_SESSION_VARS = !empty($HTTP_SESSION_VARS) ? $HTTP_SESSION_VARS : $_SESSION;
if (!isset($HTTP_SESSION_VARS['usr_id']) || !isset($HTTP_SESSION_VARS['hq_id'])):
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
header("Location: ../admin/login.php");
endif;
else:
include_once("../include/glob_defs.inc.php");
if (substr(phpversion(), 0, 1) >= "5") :
$currDbName = mcArrIsSet($_SESSION, "dbname");
else :
$currDbName = $HTTP_SESSION_VARS['dbname'];
endif;
if ($currDbName != $dbname):
//print_r ($HTTP_SESSION_VARS);
//echo "'$dbname'" . "<br>";
session_unset();
session_destroy();
header("Location: ../admin/login.php");
endif;
endif;
if (substr(phpversion(), 0, 1) >= "5") :
// $usr_id = $_SESSION["usr_id"];
$usr_id = mcArrIsSet($_SESSION, "usr_id");
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
// $hq_id = $_SESSION["hq_id"];
$hq_id = mcArrIsSet($_SESSION, "hq_id");
// $emp_id = $_SESSION["emp_id"];
$emp_id = mcArrIsSet($_SESSION, "emp_id");
// if ($emp_id == "")
// $emp_id = getFieldValueFromId("employee","usr_id",$usr_id,"emp_id");
// $randomCryptionNumber = $_SESSION['randomCryptionNumber'];
$randomCryptionNumber = mcArrIsSet($_SESSION, "randomCryptionNumber");
else :
$usr_id = $HTTP_SESSION_VARS['usr_id'];
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
$hq_id = $HTTP_SESSION_VARS['hq_id'];
$emp_id = $HTTP_SESSION_VARS['emp_id'];
$randomCryptionNumber = $HTTP_SESSION_VARS['randomCryptionNumber'];
endif;
// Check for 2FA
if (!isset($authDoNotCheck2FA)) :
$authDoNotCheck2FA = false;
endif;
if(isset($_SESSION['sso'])) {
$authDoNotCheck2FA = true;
}
include_once ("../include/dbglobal.inc.php");
if (!$authDoNotCheck2FA) :
$usrTotpSecret = getFieldValueFromId("user", "usr_id", $usr_id, "usr_totp_secret");
$usrTotpActivated = getFieldValueFromId("user", "usr_id", $usr_id, "usr_totp_activated");
$usrTotpSessionkey = getFieldValueFromId("user", "usr_id", $usr_id, "usr_totp_sessionkey");
// echo "usrTotpSecret = " . $usrTotpSecret . "<br>";
// echo "usrTotpActivated = " . $usrTotpActivated . "<br>";
// echo "usrTotpSessionkey = " . $usrTotpSessionkey . "<br>";
// echo "SESSION[sessionkey_2fa] = " . $_SESSION["sessionkey_2fa"] . "<br>";
if ($usrTotpSecret != "" && $usrTotpActivated == "1" && ($usrTotpSessionkey == "" || $_SESSION["sessionkey_2fa"] == "" || $_SESSION["sessionkey_2fa"] != $usrTotpSessionkey)) :
session_unset();
session_destroy();
header("Location: ../admin/login.php");
endif;
endif;
// Load HQ specific constants
if (!isset($noExecGlobDefs) || $noExecGlobDefs != "1") :
if (!isset($hq_id_job)) : $hq_id_job = ""; endif;
defineGlobalParameters($hq_id_job);
endif;
if ($emp_id != "" && $hq_id != "") :
// Get employee settings according to the system language
$constLanguageSelected = getParameterValue($emp_id, "SYSTEM_LANGUAGE_DEFAULT", $hq_id);
if ($constLanguageSelected != "") :
$languageSelected = $constLanguageSelected;
endif;
endif;
// Init associative array for accessing scripts
$usrAccessArray = array();
// Get global mandator ID
$md_id = getFieldValueFromId("mandatorheadquarters", "hq_id", $hq_id, "md_id");
if ($md_id == "" || !is_numeric($md_id)) : die(); endif; // Has to exist
// Init parameter for the global master right ("menu right") of the current employee and the current script
// The value will be associated in function "authCheckEmployeeRights (....)"
$empGlobalMasterRights = array();
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
// Check whether a new password must be chosen
$tries = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'usr' AND gdc_obj_id = " . $usr_id . " AND gdc_gen_fieldname = 'set_new_pwd'" );
if ($tries != "" && $_SESSION['chgpwd'] == '1'):
header("Location: ../admin/chgpwd.php");
endif;
endif;
endif;
// Redirection to a special page
function gotoReferer($refererPage = "") {
if ($refererPage == "") : $refererPage = "../admin/start.php"; endif;
if ($refererPage == "1") : $refererPage = "../admin/start.php"; endif;
if (!headers_sent()) :
header("Location: " . $refererPage);
else :
exit('<meta http-equiv="refresh" content="0; url=' . urldecode($refererPage) . '"/>');
endif;
die();
}
// Checks the authentication of a special employee (ONLY customer-employee) logged in according
// to the existence of his/her customer- and costcenter-entry
// $hq_id : Id of the headquarter the customer is associated to
// $usr_id : Id of the user unique to the employee-id (stored in cookie)
// $emp_id : Id of the employee (stored in cookie)
// $csc_id : Id of the costcenter the employee is associated
// $emp_id : Id of the employee (stored in cookie)
// $csc_id_act : Id of the current costcenter to be in the subtree-path of the individual "root"-costcenter of the employee
function authCheck($hq_id,$usr_id,$emp_id,$csc_id,$cs_id,$csc_id_act = "",$referer = "") {
$hasAccess = FALSE;
// Check hq_id and usr_id
if ($hq_id == getFieldValueFromId("user","usr_id",$usr_id,"hq_id")) :
// Check usr_id and emp_id
if ($usr_id == getFieldValueFromId("employee","emp_id",$emp_id,"usr_id")) :
// Check existence of customer- and costcenter-parameters
if ($emp_id != "" && $csc_id != "" && $cs_id != "") :
// Get the "root"-costcenter of the employee
$cscId = getFieldValueFromId("employee","emp_id",$emp_id,"csc_id");
// Check the value with the parameter
if ($cscId != "" && $cscId == $csc_id) :
// Get fields of the costcenter
$tmpFields = getFieldsValueFromId("costcenter","csc_id",$csc_id,array("cs_id","csc_path","csc_name"));
$csId = $tmpFields[0];
$cscPath = $tmpFields[1];
$cscName = $tmpFields[2];
// Check customer-entry
if ($csId != "" && $csId == $cs_id) :
if ($csc_id_act != "") :
$tmpFields = getFieldsValueFromId("costcenter","csc_id",$csc_id_act,array("cs_id","csc_path","csc_name"));
$csIdAct = $tmpFields[0];
$cscPathAct = $tmpFields[1];
$cscNameAct = $tmpFields[2];
// Check for the actual costcenter being a child of the "root"-costcenter
$existsInPath = strpos($cscPathAct, $cscName);
if ($csIdAct == $csId && ($csc_id == $csc_id_act || !($existsInPath === FALSE))) :
// Authentication ok
$hasAccess = TRUE;
endif;
endif;
endif;
endif;
endif;
endif;
endif;
if (!$hasAccess && $referer != "") :
gotoReferer();
endif;
return $hasAccess;
}
// Checks the authentication of a special employee (ONLY customer-employee) logged in according
// to the existence of his/her customer- and costcenter-entry
// Compatible to authCheck(...)
function authCheckCS($hq_id,$usr_id,$emp_id,$csc_id,$cs_id,$csc_id_act = "",$referer = "") {
return authCheck($hq_id,$usr_id,$emp_id,$csc_id,$cs_id,$csc_id_act,$referer);
}
// Checks the authentication of a special employee of a headquarter logged in
// $emp_id : Id of the employee (stored in cookie)
function authCheckHQ($currentHqId,$usr_id,$emp_id,$referer = "") {
$hasAccess = FALSE;
// Check user ID
if ($usr_id != "" && is_numeric($usr_id) && $usr_id > 0) :
// Check employee ID
if ($emp_id != "" && is_numeric($emp_id) && $emp_id > 0) :
// Check usr_id and emp_id associated correctly
$tmpUsrId = getFieldValueFromId("employee","emp_id",$emp_id,"usr_id");
if ($tmpUsrId == $usr_id) :
// Checks user-type for being a headquarter
if (getFieldValueFromId("user","usr_id",$usr_id,"usr_type") == "1") :
// Get original hq_id of the usr_id
$usrHqId = getFieldValueFromId("user","usr_id",$usr_id,"hq_id");
// Check employee state to set the rights
$empHasMultipleHqAccess = false;
if ($currentHqId != $usrHqId) :
$empHqList = getParameterValue("0", "HEADQUARTERS_MULTIPLE_ACCESS_EMPLOYEES", "0");
$empHqList = str_replace("|", "-,-", $empHqList);
$empHqArray = spliti("-,-",$empHqList);
$empHqArrayLen = count($empHqArray);
for ($i = 0; $i < $empHqArrayLen; $i++) :
if ($emp_id == $empHqArray[$i]) :
$empHasMultipleHqAccess = true;
endif;
endfor;
endif;
if ($currentHqId == $usrHqId || $empHasMultipleHqAccess) :
// Authentication ok
$hasAccess = TRUE;
endif;
endif;
endif;
endif;
endif;
if (!$hasAccess && $referer != "") :
gotoReferer();
endif;
return $hasAccess;
}
// Checks the authentication of a special courier/carrier logged in
function authCheckCR($currentHqId,$usr_id,$referer = "") {
$hasAccess = FALSE;
// Check user ID
if ($usr_id != "" && is_numeric($usr_id) && $usr_id > 0) :
// Checks user-type for being a headquarter
if (getFieldValueFromId("user","usr_id",$usr_id,"usr_type") == "3") :
// Get original hq_id of the usr_id
$usrHqId = getFieldValueFromId("user","usr_id",$usr_id,"hq_id");
if ($currentHqId == $usrHqId) :
// Authentication ok
$hasAccess = TRUE;
endif;
endif;
endif;
if (!$hasAccess && $referer != "") :
gotoReferer();
endif;
return $hasAccess;
}
function authCheckForAccess($hqId, $usrId, $empId = "", $referer = "", $customerId = "", $cscIdRoot = "", $cscIdActual = "") {
global $userType, $userTypeName, $usrAccessArray;
$hasAccess = FALSE;
// Select user-type for mode of security check
$userType = getFieldValueFromId("user","usr_id",$usrId,"usr_type");
$userTypeName = getUserTypeName($userType);
if ($userTypeName != "" && $usrAccessArray[$userTypeName] == "1") :
if ($userTypeName == "cs" && $customerId != "" && $cscIdRoot != "" && $cscIdActual != "" && authCheckCS($hqId,$usrId,$empId,$cscIdRoot,$customerId,$cscIdActual)) :
$hasAccess = TRUE;
endif;
if ($userTypeName == "cr" && authCheckCR($hqId,$usrId)) :
$hasAccess = TRUE;
endif;
if ($userTypeName == "hq" && authCheckHQ($hqId,$usrId,$empId)) :
$hasAccess = TRUE;
endif;
endif;
// Check authentication verifying emmployee an his/her costcenter- and customer-association
if (!$hasAccess && $referer != "") :
gotoReferer("1");
endif;
return $hasAccess;
}
// Checks the authentication of a special employee of a headquarter logged in
// $emp_id : Id of the employee (stored in cookie)
function authCheckEmployeeRights($emp_id, $menuModeId, $referer = "") {
global $empGlobalMasterRights;
$hasAccess = FALSE;
// Get the rights of the employee logged in
$empRights = getRights($emp_id);
if (substr($empRights,$menuModeId,1) == "1") :
// Authentication ok
$hasAccess = TRUE;
endif;
if (!$hasAccess && $referer != "") :
gotoReferer();
endif;
// Important to set because of potential access restrictions regarding to create headquarters checkboxes
// Value has to be set if "$referer" is set! This is to decide a script will be executed.
if ($referer != "") :
$empGlobalMasterRights[] = $menuModeId + 1; // "Plus 1" because the array begins with "0" and the database begins with "1"
endif;
return $hasAccess;
}
?>

163
html/include/automailer.php Normal file
View File

@@ -0,0 +1,163 @@
<?php
/*=======================================================================
*
* automailer.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
if (isRunning(5)):
exit();
endif;
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", "0");
$semaphorKey = "automailer";
$semaphorLiveTime = 120;
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// *********************************
// *** Send emails automatically ***
// *********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArrayNoPhoto = getAutoMailerJobs(4);
$jobArrayWithPhoto = getAutoMailerJobs(4,1);
$jobArray = array_merge($jobArrayNoPhoto, $jobArrayWithPhoto);
// print_r($jobArray); echo "\n\n"; die();
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
for ($i = 0; $i < $lenJobArray; $i++) :
if ($i > 0) : sleep(1); endif;
// Init for each job
$jbMailAttachements = array();
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$takeCscMailAdress = $jobArray[$i][4];
$f_email_csc = $jobArray[$i][5];
$f_email_csc = str_replace(" ", "", $f_email_csc);
// Take email address stored to costcenter (invoice address) if activated
if ($f_email_csc != "" && $takeCscMailAdress == "1") :
$f_email = $f_email_csc;
endif;
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", $currentHqId);
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Standalone process
$automailer = "1";
if ($job_id != "" && $f_email != "" && $currentHqId != "") :
// The semaphore basically has to be generated by inserting a new job.
// Here the existence will be checked finally, but the code should not be executed (!!!!)
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey))) :
insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $job_id, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
die();
endif;
// Try to lock semaphore
$res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
if ($db->affected_rows > 0) :
include ("../admin/jb_detail.php");
// *** Mail was sent => Update jb_automailsent ***
// Get current mail status
$jbAutomailsent = getFieldValueFromId("job","jb_id",$job_id,"jb_automailsent");
if ($jbAutomailsent == "" || !is_numeric($jbAutomailsent)) : $jbAutomailsent = 0; endif;
if ($mailResult) :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", "999"));
$statusSent = "OK";
else :
$statusSent = "NOT OK";
$jbAutomailsent++;
// Check for maximum of 5 fault trials. If reached then finalize with error code
if ($jbAutomailsent > "5") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", "998"),"jb_automailsent != '999'");
else :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", $jbAutomailsent),"jb_automailsent != '999'");
endif;
endif;
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Erledigung] [Status: " . $statusSent . "]");
else :
// Check semaphore to be unlocked
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", "998"));
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Erledigung] [Status: NOT OK]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all jobs
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,163 @@
<?php
/*=======================================================================
*
* automailer2.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
if (isRunning(5)):
exit();
endif;
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_2", "0");
$semaphorKey = "automailer2";
$semaphorLiveTime = 120;
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// *********************************
// *** Send emails automatically ***
// *********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArray = getAutoMailerJobs2(1);
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
for ($i = 0; $i < $lenJobArray; $i++) :
if ($i > 0) : sleep(1); endif;
// Init for each job
$jbMailAttachements = array();
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$takeCscMailAdress = $jobArray[$i][4];
$f_email_csc = $jobArray[$i][5];
$f_email_csc = str_replace(" ", "", $f_email_csc);
// Take email address stored to costcenter (invoice address) if activated
if ($f_email_csc != "" && $takeCscMailAdress == "1") :
$f_email = $f_email_csc;
endif;
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_2", $currentHqId);
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Initiate switch for the mail text according to the caller mode for taken jobs (= 1)
$mailTextJobStatus = "1";
// Standalone process
$automailer = "1";
if ($job_id != "" && $f_email != "" && $currentHqId != "") :
// The semaphore basically has to be generated by inserting a new job.
// Here the existence will be checked finally, but the code should not be executed (!!!!)
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey))) :
insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $job_id, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
die();
endif;
// Try to lock semaphore
$res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
if ($db->affected_rows > 0) :
include ("../admin/jb_detail.php");
// *** Mail was sent => Update jb_automailsent2 ***
// Get current mail status
$jbAutomailsent = getFieldValueFromId("job","jb_id",$job_id,"jb_automailsent2");
if ($jbAutomailsent == "" || !is_numeric($jbAutomailsent)) : $jbAutomailsent = 0; endif;
if ($mailResult) :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent2", "999"));
$statusSent = "OK";
else :
$statusSent = "NOT OK";
$jbAutomailsent++;
// Check for maximum of 5 fault trials. If reached then finalize with error code
if ($jbAutomailsent > "5") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent2", "998"),"jb_automailsent2 != '999'");
else :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent2", $jbAutomailsent),"jb_automailsent2 != '999'");
endif;
endif;
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Abholung] [Status: " . $statusSent . "]");
else :
// Check semaphore to be unlocked
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent2", "998"));
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Erledigung] [Status: NOT OK]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all jobs
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,164 @@
<?php
/*=======================================================================
*
* automailer3.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
if (isRunning(5)):
exit();
endif;
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_3", "0");
$semaphorKey = "automailer3";
$semaphorLiveTime = 120;
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// ********************************
// *** Send mails automatically ***
// ********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArray = getAutoMailerJobs3(1);
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
for ($i = 0; $i < $lenJobArray; $i++) :
if ($i > 0) : sleep(1); endif;
// Init for each job
$jbMailAttachements = array();
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$takeCscMailAdress = $jobArray[$i][4];
$f_email_csc = $jobArray[$i][5];
$f_email_csc = str_replace(" ", "", $f_email_csc);
// Take email address stored to costcenter (invoice address) if activated
if ($f_email_csc != "" && $takeCscMailAdress == "1") :
$f_email = $f_email_csc;
endif;
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_3", $currentHqId);
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Initiate switch for the mail text according to the caller mode for new jobs (= 8) [or (= 9), it is ok]
$mailTextJobStatus = "8";
// Standalone process
$automailer = "1";
if ($job_id != "" && $f_email != "" && $currentHqId != "") :
// The semaphore basically has to be generated by inserting a new job.
// Here the existence will be checked finally, but the code should not be executed (!!!!)
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey))) :
insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $job_id, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
die();
endif;
// Try to lock semaphore
$res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
if ($db->affected_rows > 0) :
include ("../admin/jb_detail.php");
// *** Mail was sent => Update jb_automailsent3 ***
// Get current mail status
$jbAutomailsent = getFieldValueFromId("job","jb_id",$job_id,"jb_automailsent3");
if ($jbAutomailsent == "" || !is_numeric($jbAutomailsent)) : $jbAutomailsent = 0; endif;
if ($mailResult) :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent3", "999"));
$statusSent = "OK";
else :
$statusSent = "NOT OK";
$jbAutomailsent++;
// Check for maximum of 5 fault trials. If reached then finalize with error code
if ($jbAutomailsent > "5") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent3", "998"),"jb_automailsent3 != '999'");
else :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent3", $jbAutomailsent),"jb_automailsent3 != '999'");
endif;
endif;
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Erfassung] [Status: " . $statusSent . "]");
else :
// Check semaphore to be unlocked
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent3", "998"));
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Erledigung] [Status: NOT OK]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all jobs
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,505 @@
<?php
/*=======================================================================
*
* automailer4.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
if (isRunning(5)):
exit();
endif;
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", "0");
$semaphorKey = "automailer4";
$semaphorLiveTime = 120;
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// *********************************
// *** Send emails automatically ***
// *********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
// $stationArray = getAutoMailerStations(5);
$stationArrayNoPhoto = getAutoMailerStations(5);
$stationArrayWithPhoto = getAutoMailerStations(5,1);
$stationArray = array_merge($stationArrayNoPhoto, $stationArrayWithPhoto);
// print_r($stationArray); echo "\n\n"; die();
$lenStationArray = count($stationArray);
// Loop all stations
for ($i = 0; $i < $lenStationArray; $i++) :
if ($i > 0) : sleep(1); endif;
// Init for each job
$jbMailAttachements = array();
// Current station and mail address
$job_id = $stationArray[$i][0];
$tour_sort = $stationArray[$i][1];
$f_email = trim($stationArray[$i][2]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $stationArray[$i][3];
$currentHqId = $stationArray[$i][4];
$takeCscMailAdress = $stationArray[$i][5];
$f_email_csc = $stationArray[$i][6];
$f_email_csc = str_replace(" ", "", $f_email_csc);
$trId = $stationArray[$i][7];
$jbOrdertime = $stationArray[$i][8];
// Take email address stored to costcenter (invoice address) if activated
if ($f_email_csc != "" && $takeCscMailAdress == "1") :
$f_email = $f_email_csc;
endif;
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Initiate switch for the mail text according to the caller mode for new jobs (= 8) [or (= 9), it is ok]
$mailTextJobStatus = "ALL";
// Standalone process
$automailer = "1";
if ($job_id != "" && $tour_sort != "" && $f_email != "" && $currentHqId != "") :
// The semaphore basically has to be generated by inserting a new job.
// Here the existence will be checked finally, but the code should not be executed (!!!!)
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","tr","sp_obj_id",$trId,"sp_fieldname",$semaphorKey))) :
insertStmt("phoenix_log.semaphor", array("sp_obj_type", "tr", "sp_obj_id", $trId, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
die(); // Terminate here after INSERT (!!!!)
endif;
// Try to lock semaphore
$res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $trId, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'tr' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
if ($db->affected_rows > 0) :
// **** MAIL BEGIN ****************************
// include_once ("../admin/jb_detail.php");
if (checkEmailFormat($f_email)) :
$jobData = array();
getDBData("tour", $job_id); // Get station data
$tmpSignPath = "../temp/signs/";
$constSignPath = getParameterValue("0", "SIGNS_PATH", $currentHqId);
if ($constSignPath == "") : $constSignPath = getParameterValue("0", "SIGNS_PATH", "0"); endif;
if ($constSignPath != "") : $tmpSignPath = $constSignPath; endif;
// Generate sign image
$rawCoord = splitRawCoordinates ($jobData["tour"][$tour_sort]["tr_sign"]);
$maxCoord = checkMaxCoordinates($rawCoord);
$imgFilename = $tmpSignPath . $job_id . "_" . $tour_sort . ".png";
$imgFilenames[] = $imgFilename;
$im = createSignImage($rawCoord);
imagepng ($im, $imgFilename);
// Generate mail object
$mailObj = new htmlMimeMail();
$mailCssFontType = getParameterValue("0", "MAIL_CSS_FONT_TYPE", $currentHqId);
if ($mailCssFontType == "") : $mailCssFontType = "Verdana, Arial, Helvetica, sans-serif"; endif;
$mailtext = "<html><head><meta text/html>";
$mailtext .= "<style type=\"text/css\">";
$mailtext .= ".f8np1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px}";
$mailtext .= ".f8bp1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: bold; padding: 1px}";
$mailtext .= ".f10np1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: normal; padding: 1px}";
$mailtext .= ".f10bp1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: bold; padding: 1px}";
$mailtext .= ".f8np1_red { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
$mailtext .= "</style>";
$mailtext .= "</head><body><h4>";
$trFinishtime = $jobData["tour"][$tour_sort]["tr_finishtime"];
// $trFinishtime = substr($trFinishtime,8,2) . "." . substr($trFinishtime,5,2) . "." . substr($trFinishtime,0,4) . " " . substr($trFinishtime,11,2) . ":" . substr($trFinishtime,14,2);
$trFinishtime = substr($trFinishtime,11,2) . ":" . substr($trFinishtime,14,2) . " " . getLngt("Uhr") . " [" . substr($trFinishtime,8,2) . "." . substr($trFinishtime,5,2) . "." . substr($trFinishtime,0,4) . "]";
// BEGIN station data
$jobtext = "";
// Definition of the output place of the job data
$mailJobData = getParameterValue("0", "MAIL_JOBDATA", "0");
if ($mailJobData == "") : $mailJobData = "0"; endif;
// Transport date or current date
$mailJobDate = getParameterValue("0", "MAIL_JOBDATE", "0");
if ($mailJobDate == "1") :
$jobtext .= "<div class=\"f10bp1\">" . getLngt("Transportdatum:") . " " . formatOutput($jbOrdertime, "datetime", 4) . "</div>";
else :
$jobtext .= "<div class=\"f10bp1\">" . getLngt("Transportdatum:") . " " . getDateTime(5) . "</div>";
endif;
$jobtext .= "<div style=\"width:100%; height:10px;\"> </div>";
$tmpHeight = "20";
$jobtext .= "<table class=\"f8np1\">";
$jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("AUFTRAG:") . " " . $job_id . "</span></td></tr>";
$jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("KOMMISSIONSNUMMER:") . " " . $jobData["tour"][$tour_sort]["tr_commission_no"] . "</span></td></tr>";
$jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("ERLEDIGUNGSZEITPUNKT:") . " " . $trFinishtime . " " . "</span></td></tr>";
$jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("ERLEDIGTE STATION:") . "</span>" . "</td></tr>";
$jobtext .= "<tr><td>" . $jobData["tour"][$tour_sort]["tr_comp"] . " " . $jobData["tour"][$tour_sort]["tr_comp2"] . "</td></tr>";
$jobtext .= "<tr><td>" . "- " . getLngt("Annahme") . ": " . $jobData["tour"][$tour_sort]["tr_signname"] . " -" . "</td></tr>";
$jobtext .= "<tr><td>" . $jobData["tour"][$tour_sort]["ad_street"] . " " . $jobData["tour"][$tour_sort]["tr_hsno"] . "</td></tr>";
$jobtext .= "<tr><td>" . $jobData["tour"][$tour_sort]["ad_zipcode"] . " " . $jobData["tour"][$tour_sort]["ad_city"] . "</td></tr>";
$jobtext .= "</table>";
// $jobtext .= "<table class=\"f8np1\">" . $jobentry . "</table><br>";
// $jobtext .= "</td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td valign=\"top\">";
// if ($courierentry != "" && $mailTextJobStatus != "0" && $mailTextJobStatus != "8" && $mailTextJobStatus != "9") :
// $jobtext .= "<span class=\"f8bp1\">" . getLngt("TRANSPORTEUR:") . "</span><br>";
// $jobtext .= "<table class=\"f8np1\">" . $courierentry . "</table><br>";
// endif;
// Display events if activated
$cscIdPayer = getFieldValueFromId("job", "jb_id", $job_id, "csc_id_payer");
$csIdPayer = getFieldValueFromId("costcenter", "csc_id", $cscIdPayer, "cs_id");
$csJbstatusmailFields = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_fields");
$constMaskStationsPodScanEvents = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_SCAN_EVENTS", $hq_id);
if ($constMaskStationsPodScanEvents == "") : $constMaskStationsPodScanEvents = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_SCAN_EVENTS", "0"); endif;
if ($constMaskStationsPodScanEvents == "1" && substr($csJbstatusmailFields, 8, 1) == "1") :
$jobtext .= "<table>";
$jobtext .= "<tr style=\"height:15px;\"><td valign=\"top\">";
$eventBemerkung = "";
$tmpEventState = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'del_code'");
if ($tmpEventState != "" && is_numeric($tmpEventState)) :
$eventBemerkung .= $deliveryCodeArray[$tmpEventState] . "&nbsp;&nbsp;&nbsp;&nbsp;";
endif;
// Get scan event remark
$tmpEventRemark = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'del_rem'");
if ($tmpEventRemark != "") :
$eventBemerkung .= $tmpEventRemark;
endif;
// Output scan barcodes
// $eventBemerkung .= getOutputJobTratArticleData($job_id, "1", "1", "1", "1", $jobData["tour"][$tour_sort]["tr_sort"]);
$jobtext .= "<span class=\"f8bp1\">" . getLngt("EVENT-BEMERKUNG:") . " " . $eventBemerkung . "</span><br>";
$jobtext .= "</td></tr></table>";
endif;
// END station data
$mailCssFontClass = getParameterValue("0", "MAIL_CSS_FONT_CLASS", $currentHqId);
if ($mailCssFontClass == "") : $mailCssFontClass = "f8bp1"; endif;
$mailPreSalutationText = getParameterValue("0", "MAIL_PRE_SALUTATION_TEXT", $currentHqId);
if ($mailPreSalutationText == "") : $mailPreSalutationText = getLngt("Sehr geehrte Damen und Herren,"); endif;
$mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailPreSalutationText . "</div>";
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
$mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt("die Erledigung der Station erfolgte.") . "</div>";
// $mailTextJobdata = getParameterValue("0", "MAIL_TEXT_JOBDATA", $currentHqId);
// if ($mailTextJobdata == "") : $mailTextJobdata = getLngt("Anbei übersenden wir Ihnen die Auftragsdaten."); endif;
// $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextJobdata . "</div>";
// $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
if ($mailJobData == "1") :
$mailtext .= "<div style=\"width:100%; height:30px;\"> </div>";
$mailtext .= $jobtext;
$mailtext .= "<div style=\"width:100%; height:20px;\"> </div>";
endif;
// Signature
$mailTextRegards = getParameterValue("0", "MAIL_TEXT_REGARDS", $currentHqId);
if ($mailTextRegards == "") : $mailTextRegards = getLngt("Mit freundlichem Gruß,"); endif;
$mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextRegards . "</div>";
$mailSalutationText = getParameterValue("0", "MAIL_SALUTATION_TEXT", $currentHqId);
$mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailSalutationText) . "</div>";
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
// HOMEPAGE
$mailFooterWebPage = getParameterValue("0", "MAIL_FOOTER_WEB_PAGE", $currentHqId);
// LOGO
$logoName = getParameterValue("0", "IMG_LOGO_NAME", $currentHqId);
$logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId);
$logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId);
if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
if ($mailFooterWebPage != "") :
$mailtext .= "<div><a href=\"http://" . $mailFooterWebPage . "\"><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></a></div>";
else :
$mailtext .= "<div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div>";
endif;
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
endif;
$mailFooterEnabled = getParameterValue("0", "MAIL_FOOTER_ENABLED", $currentHqId);
if ($mailFooterEnabled == "1") :
$mailFooterAddress = getParameterValue("0", "MAIL_FOOTER_ADDRESS", $currentHqId);
if ($mailFooterAddress != "") :
$mailtext .= "<table style=\"font-family: Arial; font-size: 10pt; font-weight: normal; padding: 1px; color: #000000;\">";
$mailtext .= $mailFooterAddress;
$mailtext .= "</table>";
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
endif;
$mailFooterContact = getParameterValue("0", "MAIL_FOOTER_CONTACT", $currentHqId);
if ($mailFooterContact != "") :
if ($mailDisplayModeEmployeeData == "1" && ($mailEmployeeData[2] != "" || $mailEmployeeData[3] != "" || $mailEmployeeData[4] != "")) :
$mailtext .= "<table>";
if ($mailEmployeeData[2] != "") :
$mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Telefon") . ": " . $mailEmployeeData[2] . "</span></td></tr>";
endif;
if ($mailEmployeeData[4] != "") :
$mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Fax") . ": " . $mailEmployeeData[4] . "</span></td></tr>";
endif;
if ($mailEmployeeData[3] != "") :
$mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Email") . ": " . $mailEmployeeData[3] . "</span></td></tr>";
endif;
// $mailFooterWebPage = getParameterValue("0", "MAIL_FOOTER_WEB_PAGE", $currentHqId);
if ($mailFooterWebPage != "") :
// $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . $mailFooterWebPage . "</span></td></tr>";
$mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\"><a href=\"http://" . $mailFooterWebPage . "\">" . $mailFooterWebPage . "</a></span></td></tr>";
endif;
$mailtext .= "</table>";
else :
$mailtext .= "<table style=\"font-family: Arial; font-size: 10pt; font-weight: normal; padding: 1px; color: #000000;\">";
$mailtext .= $mailFooterContact;
$mailtext .= "</table>";
endif;
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
endif;
$mailFooterImpressum = getParameterValue("0", "MAIL_FOOTER_IMPRESSUM", $currentHqId);
if ($mailFooterImpressum != "") :
$mailtext .= "<table style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">";
$mailtext .= $mailFooterImpressum;
$mailtext .= "</table>";
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
endif;
$mailFooterResponsibility = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY", $currentHqId);
if ($mailFooterResponsibility == "") : $mailFooterResponsibility = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY", "0"); endif;
if ($mailFooterResponsibility != "") :
$mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility . "</div>";
// Extended text
$mailFooterResponsibility2 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_2", $currentHqId);
if ($mailFooterResponsibility2 == "") : $mailFooterResponsibility2 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_2", "0"); endif;
if ($mailFooterResponsibility2 != "") :
$mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility2 . "</div>";
$mailFooterResponsibility3 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_3", $currentHqId);
if ($mailFooterResponsibility3 == "") : $mailFooterResponsibility3 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_3", "0"); endif;
if ($mailFooterResponsibility3 != "") :
$mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility3 . "</div>";
$mailFooterResponsibility4 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_4", $currentHqId);
if ($mailFooterResponsibility4 == "") : $mailFooterResponsibility4 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_4", "0"); endif;
if ($mailFooterResponsibility4 != "") :
$mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility4 . "</div>";
$mailFooterResponsibility5 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_5", $currentHqId);
if ($mailFooterResponsibility5 == "") : $mailFooterResponsibility5 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_5", "0"); endif;
if ($mailFooterResponsibility5 != "") :
$mailtext .= "<div class=\"" . $mailFooterImpressum . "\">" . $mailFooterResponsibility5 . "</div>";
endif;
endif;
endif;
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
endif;
endif;
$mailFooterThinkGreen = getParameterValue("0", "MAIL_FOOTER_THINK_GREEN", $currentHqId);
if ($mailFooterThinkGreen != "") :
$mailtext .= $mailFooterThinkGreen;
$mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
endif;
$mailtext .= "<div style=\"width:100%; height:30px;\"> </div>";
endif;
if ($mailJobData == "0") :
$mailtext .= "</br>" . $jobtext;
endif;
$mailtext .= "</body></html>";
$mailObj->setSubject(getLngt("Station") . " " . $tour_sort . " " . getLngt("des Transportauftrags!") . " " . $job_id . " " . getLngt("wurde erledigt!"));
$mailObj->setHtml($mailtext, null, "./");
// $mailObj->setHtml($mailtext);
// Set From address
$mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
if ($mailSenderAddress == "" || !checkEmailFormat($mailSenderAddress)) :
$mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", "0");
endif;
$mailObj->setFrom($mailSenderAddress);
// Set Cc address
$mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", $currentHqId);
if ($mailCcAddress == "" || !checkEmailFormat($mailCcAddress)) :
$mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", "0");
endif;
if ($mailCcAddress != "" && checkEmailFormat($mailCcAddress)) :
$mailObj->setCc($mailCcAddress);
endif;
// Set Bcc address
$mailBccAddress = getParameterValue("0", "MAIL_BCC_STATION_ADDRESS", "0");
if ($mailBccAddress == "" || !checkEmailFormat($mailBccAddress)) :
$mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", $currentHqId);
if ($mailBccAddress == "" || !checkEmailFormat($mailBccAddress)) :
$mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", "0");
endif;
endif;
// $mailBccAddress = ($mailBccAddress != "" ? $mailBccAddress . "," : "") . "mv@assecutor.de";
if ($mailBccAddress != "" && checkEmailFormat($mailBccAddress)) :
$mailObj->setBcc($mailBccAddress);
endif;
// Generate PDF if enabled for customer
/*
$csJbstatusmailPdf = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_pdf");
if ($csJbstatusmailPdf == "1" && $job_status == "2") :
$tmpPdfPath = "../temp/pdf/";
$includePDFGeneric = "1";
$f_act = "generatePDFJob";
$storeAsFile = "1";
$jbId = $job_id;
$pdfFile = "Auftrag_" . $job_id . ".pdf";
include_once ("../admin/pdf_generic.php");
if (file_exists($tmpPdfPath . $pdfFile)) :
$attachment = $mailObj->getFile($tmpPdfPath . $pdfFile);
$mailObj->addAttachment($attachment, $pdfFile, 'application/pdf');
endif;
endif;
*/
$mailResult = $mailObj->send(array($f_email), 'smtp');
// $mailResult = $mailObj->send(array("admin@assecutor.de"), 'smtp');
if ($mailResult) :
$mailsendStatus = getLngt("Die Nachricht für die Station " . $tour_sort . " wurde versandt!");
// Write logdata into log database
writeToLogDB("22",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
else :
$mailsendStatus = getLngt("Die Nachricht für die Station " . $tour_sort . " konnte nicht gesendet werden!");
// Write logdata into log database
writeToLogDB("23",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
endif;
// $mailObj->free();
$mailObj = NULL;
// Remove stored temporary images on the filesystem
$imgFilenamesLen = count($imgFilenames);
for ($im = 0; $im < $imgFilenamesLen; $im++) :
if (file_exists($tmpSignPath . $imgFilenames[$im])) :
unlink($tmpSignPath . $imgFilenames[$im]);
endif;
endfor;
// Remove stored temporary pdf documents on the filesystem
// if (file_exists($tmpPdfPath . $pdfFile)) :
// unlink($tmpPdfPath . $pdfFile);
// endif;
else :
$mailsendStatus = getLngt("Die eingegebene Emailadresse ist syntaktisch nicht korrekt!");
endif;
// **** MAIL END ****************************
// *** Mail was sent => Update genericdatacontainer ***
// Get current mail status
$trAutomailsent = getFieldValueFromClause("genericdatacontainer","gdc_content","gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
if ($trAutomailsent == "" || !is_numeric($trAutomailsent)) : $trAutomailsent = 0; endif;
if ($mailResult) :
if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_obj_id",$trId,"gdc_gen_fieldname","auto_mail_station"))) :
updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", "999", "gdc_context", ""),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
else :
insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "auto_mail_station", "gdc_content", "999", "gdc_context", ""));
endif;
$statusSent = "OK";
else :
$statusSent = "NOT OK";
$trAutomailsent++;
// Check for maximum of 2 fault trials. If reached then finalize with error code
if ($trAutomailsent > "2") :
$trAutomailsent = "998";
endif;
if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_obj_id",$trId,"gdc_gen_fieldname","auto_mail_station"))) :
updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", $trAutomailsent, "gdc_context", ""),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
else :
insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "auto_mail_station", "gdc_content", $trAutomailsent, "gdc_context", ""));
endif;
endif;
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $mailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Erledigung Station " . $tour_sort . "] [Status: " . $statusSent . "]");
else :
// Check semaphore to be unlocked
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'tr' AND sp_obj_id = '" . $trId . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
updateStmt("phoenix_log.semaphor", "sp_obj_id", $trId, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'tr' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $tour_sort != "" && $currentHqId != "") :
if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_obj_id",$trId,"gdc_gen_fieldname","auto_mail_station"))) :
updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", "998", "gdc_context", ""),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
else :
insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "auto_mail_station", "gdc_content", "998", "gdc_context", ""));
endif;
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Station: " . $tour_sort . "] [Time: " . $currentTime . "] [From: " . $mailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Station] [Status: NOT OK]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all stations
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,181 @@
<?php
/*=======================================================================
*
* automailer5.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
if (isRunning(5)):
exit();
endif;
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_5", "0");
$gdcCashpayerMailKey = "jb_cashpayer_mail";
$semaphorKey = "automailer5";
$semaphorLiveTime = 120;
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// ********************************
// *** Send emails automatically ***
// ********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArray = getAutoMailerJobsGdc(1);
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
for ($i = 0; $i < $lenJobArray; $i++) :
if ($i > 0) : sleep(1); endif;
// Init for each job
$jbMailAttachements = array();
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$job_mode = $jobArray[$i][4];
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_5", $currentHqId);
if ($logFile == "") : $logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_5", "0"); endif;
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Standalone process
$automailer = "1";
if ($job_id != "" && $f_email != "" && $currentHqId != "") :
// The semaphore basically has to be generated by inserting a new job.
// Here the existence will be checked finally, but the code should not be executed (!!!!)
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey))) :
insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $job_id, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
die();
endif;
// Try to lock semaphore
$res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
if ($db->affected_rows > 0) :
// Initiate switch for the mail text according to the caller mode for taken jobs (= 1)
$gdcContextCurr = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
if ($gdcContextCurr == "" || !is_numeric($gdcContextCurr)) :
$gdcContextCurr = 1024;
endif;
$mailTextJobStatus = "";
$gdcContextNewValue = 1024;
switch ($job_mode) {
case "1":
$mailTextJobStatus = "8";
$gdcContextNewValue = ($gdcContextCurr | 1025);
$jbStatusText = "Erfassung";
break;
case "2":
$mailTextJobStatus = "1";
$gdcContextNewValue = ($gdcContextCurr | 1026);
$jbStatusText = "Abholung";
break;
case "3":
$gdcContextNewValue = ($gdcContextCurr | 1028);
$jbStatusText = "Erledigung";
break;
}
include ("../admin/jb_detail.php");
// Get current mail status
// $jbAutomailsent = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "' AND gdc_obj_id = '" . $job_id . "'");
// if ($jbAutomailsent == "" || !is_numeric($jbAutomailsent)) : $jbAutomailsent = 0; endif;
if ($mailResult) :
// updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_SENT"),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $gdcContextNewValue) ,"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
$statusSent = "OK";
else :
$statusSent = "NOT OK";
// $jbAutomailsent++;
// Check for maximum of 5 fault trials. If reached then finalize with error code
// if ($jbAutomailsent > "5") :
// updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $gdcContextNewValue) ,"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
// else :
// updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $jbAutomailsent),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
// endif;
endif;
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [" . $jbStatusText . "] [Status: " . $statusSent . "]");
else :
// Check semaphore to be unlocked
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Erledigung] [Status: NOT OK]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all jobs
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,212 @@
<?php
/*=======================================================================
*
* automailer6.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
// include_once ("../include/image.inc.php");
// include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
if (isRunning(5)):
exit();
endif;
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_6", "0");
if ($logFile == "") : $logFile = "../log/automailer6.log"; endif;
$gdcJobJamKey = "jb_job_jam";
$semaphorKey = "automailer6";
$semaphorLiveTime = 120;
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// *********************************
// *** Send emails automatically ***
// *********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArray = getAutoMailerJobsByJobJam(5);
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
if ($lenJobArray > 0) :
// writeToFile("../log/automailer6.log", "lenJobArray = " .$lenJobArray . " :: Jobs: " . $jobArray[0][0] . " " . $jobArray[1][0] . " " . $jobArray[2][0] . " " . $jobArray[3][0] . " " . $jobArray[4][0]);
endif;
for ($i = 0; $i < $lenJobArray; $i++) :
// Init for each job
$jbMailAttachements = array();
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$takeCscMailAdress = $jobArray[$i][4];
$f_email_csc = $jobArray[$i][5];
$f_email_csc = str_replace(" ", "", $f_email_csc);
$csIdPayer = $jobArray[$i][6];
$jbOrdertime = $jobArray[$i][7];
// writeToFile("../log/automailer6.log", "job_id = " .$job_id);
// Take email address stored to costcenter (invoice address) if activated
if ($f_email_csc != "" && $takeCscMailAdress == "1") :
$f_email = $f_email_csc;
endif;
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_6", "0");
if ($logFile == "") : $logFile = "../log/automailer6.log"; endif;
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Initiate switch for the mail text according to the caller mode for taken jobs (= 1)
$mailTextJobStatus = "1";
// Standalone process
$automailer = "1";
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// $f_email = "va@assecutor.de,mv@assecutor.de";
// $f_email = "ingo.kublenz@stadtbote.de,va@assecutor.de,mv@assecutor.de";
if ($job_id != "" && $f_email != "" && $currentHqId != "") :
// The semaphore basically has to be generated by inserting a new job.
// Here the existence will be checked finally, but the code should not be executed (!!!!)
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey))) :
insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $job_id, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
die();
endif;
// Try to lock semaphore
$res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
if ($db->affected_rows > 0) :
// include ("../admin/jb_detail.php");
// *****************
// Check language by payer for sending email and take customer parameter
$csLanguageMail = getParameterValue("0", "JOBDETAILS_EMAIL_LANGUAGE_" . $csIdPayer, "0");
if ($csLanguageMail == "") : $csLanguageMail = "0"; endif;
$remLanguageSelected = "";
if ($languageSelected != $csLanguageMail) :
$remLanguageSelected = $languageSelected;
$languageSelected = $csLanguageMail;
getLanguage(__FILE__);
endif;
$mailSubject = getLngt("Verzögerung bei Ihrem Auftrag Nr.: ") . " " . $job_id;
// $mailContent = getLngt("Der Transportauftrag") . " " . $job_id . " ". getLngt("befindet sich noch in der Vermittlung!");
$mailContent = getLngt("wir möchten Sie darüber informieren, dass es bei Ihrem aktuellen Auftrag geplant für") . " " . formatOutput($jbOrdertime, "datetime", "14") . " "
. getLngt("zu einer Verzögerung in der Vermittlung kommt.") . "<br>"
. getLngt("Unser Team arbeitet aktiv daran, einen verfügbaren Boten für Ihren Auftrag zu finden. Wir prüfen alle Optionen, um Ihre Lieferung schnellstmöglich zu vermitteln.") . "<br>"
. getLngt("Sobald Ihr Auftrag erfolgreich vermittelt wurde, werden wir Sie per Mail informieren.") . "<br><br>"
. getLngt("Wir hoffen auf Ihr Verständnis und bedanken uns für Ihr Vertrauen in STADTBOTE.") . "<br><br>";
$mailContent = "<div class=\"f8np1\">" . $mailContent . "</div>";
$mailResult = sendExternalMailExtended($mailContent, $mailSubject, $f_email);
// $mailResult = sendExternalMailExtended($mailContent, $mailSubject, $f_email, "EMPTY", "EMPTY", "mv@assecutor.de");
// Reset language
if ($remLanguageSelected != "") :
$languageSelected = $remLanguageSelected;
getLanguage(__FILE__);
endif;
// *****************
// *** Mail was sent => Update jb_automailsent6 ***
// Get current mail status
$jbAutomailsent = getFieldValueFromClause("phoenix.genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
if ($jbAutomailsent == "") : $jbAutomailsent = 0; endif;
if ($mailResult) :
// updateStmt("job", "jb_id", $job_id, array("jb_automailsent6", "999"));
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_SENT"),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
// Insert into GDC to check job jam order wil be mediated within n minutes
$constAmStarttimeInMinutes = getParameterValue("0", "CS_JB_JAM_WAITTIME_CTRL", $currentHqId);
if ($constAmStarttimeInMinutes == "") : $constAmStarttimeInMinutes = getParameterValue("0", "CS_JB_JAM_WAITTIME_CTRL", "0"); endif;
if ($constAmStarttimeInMinutes == "") : $constAmStarttimeInMinutes = 10; endif;
$execTime = getDateTime("datetime_plus_offset", array(0,$constAmStarttimeInMinutes,0,0,0,0), "Y-m-d H:i:s");
insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $job_id, "gdc_gen_fieldname", "jb_job_jam_ctrl", "gdc_content", $execTime, "gdc_context", ""));
$statusSent = "SENT";
else :
$statusSent = "NOT SENT";
$jbAutomailsent++;
// Check for maximum of 3 fault trials. If reached then finalize with error code
if ($jbAutomailsent > 3) :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
else :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $jbAutomailsent),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
endif;
endif;
// Write logdata into log database
writeToLogDB("188",$currentHqId,$job_id,"","","","","MAIL_STATE=" . $statusSent . "|MAIL_TO=" . $f_email);
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Vermittlungsstau] [Status: " . $statusSent . "]");
else :
// Check semaphore to be unlocked
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Vermittlungsstau] [Status: NOT OK]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all jobs
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,262 @@
<?php
/*=======================================================================
*
* automailer7.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/image.inc.php");
include_once ("../locating/xServer.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
include_once ("../include/inc_tracking.inc.php");
// Execution-Time for script
set_time_limit(120);
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0");
$parAutomailer2TrackingEnabled = getParameterValue("0", "AUTOMAILER_2_TRACKING_ENABLED", "0");
if ($constAutomailerEnabled == '1' && $parAutomailer2TrackingEnabled == '1') :
if ($argv[1] == "acapella7890") :
// Error reporting
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$currentTime = getDateTime("0");
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_7", "0");
// if ($logFile == "") : $logFile = $path . "/log/automailer7.log"; endif;
if ($logFile == "") : $logFile = "../log/automailer7.log"; endif;
$semaphorKey = "automailer7";
$semaphorLiveTime = 120;
$jobArray = getAutoMailerTracking();
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
for ($i = 0; $i < $lenJobArray; $i++) :
// Current job and mail address
$job_id = $jobArray[$i][0];
$tr_id = $jobArray[$i][1];
$tr_sort = $jobArray[$i][2];
$gdc_content = $jobArray[$i][3];
$gdc_context = $jobArray[$i][4];
$currentHqId = $jobArray[$i][5];
$jbCscIdPayer = $jobArray[$i][6];
$jbCsIdPayer = $jobArray[$i][7];
$jb_ordertime = $jobArray[$i][8];
$job_crSid = $jobArray[$i][9];
if ($job_id != "" && is_numeric($job_id)) :
// Get tracking state
// $jbCscIdPayer = getFieldValueFromId("job","jb_id",$job_id,"csc_id_payer");
if ($jbCscIdPayer > 0) :
// $jbCsIdPayer = getFieldValueFromId("costcenter","csc_id",$jbCscIdPayer,"cs_id");
if ($jbCsIdPayer > 0) :
$tmpGdcContent = trim($gdc_content);
$tmpGdcContentArr = explode("|", $tmpGdcContent);
$f_email = $tmpGdcContentArr[0];
$f_email = str_replace(" ", "", $f_email);
// Define constants
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$mailResult = FALSE;
// Standalone process
$automailer = "1";
// if ($tr_sort > 1) :
if ($f_email != "" && $currentHqId != "") :
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey,"sp_content",$f_email))) :
// Insert tracking link into
$constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");
// $tmpArray = insertMetaTrackingItem($constGlobalDbInstNo, "tracking_tr", $tr_id);
$tmpArray = insertTrackingItems("", $tr_id, "", "", "", "SINGLE_TR");
$trackingLink = getParameterValue("0", "GLOBAL_URL", $currentHqId);
if ($trackingLink == "") : $trackingLink = getParameterValue("0", "GLOBAL_URL", "0"); endif;
if ($trackingLink == "") :
// Send info mail to sysop
sendInternalMail("Parameter for URL of instance not specified!");
die();
endif;
$trackingLink .= "/tracking/tracking_ADSG.php?trackingID=";
$parLogoFile = getParameterValue("0", "IMG_LOGO_NAME_EMAIL", $currentHqId, "0");
$parLogoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId, "0");
$parLogoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId, "0");
$parCssBackground = getParameterValue("0", "IMG_LOGO_BGCOL_EMAIL", $currentHqId, "0");
$parLogoArr = array($parLogoFile, $parLogoHeight, $parLogoWidth, $parCssBackground);
$jbCsBlurMarkupTimePayer = getFieldValueFromId("customer","cs_id",$jbCsIdPayer,"cs_blur_markup_time");
if ($jbCsBlurMarkupTimePayer == "") : $jbCsBlurMarkupTimePayer = 0; endif;
$jbCmpIdPayer = getFieldValueFromId("customer","cs_id",$jbCsIdPayer,"cmp_id");
$jbCmpCompPayer = getFieldValueFromId("company","cmp_id",$jbCmpIdPayer,"cmp_comp");
$trComp = getFieldValueFromId("tour","tr_id",$tr_id,"tr_comp");
// $trComp2 = getFieldValueFromId("tour","tr_id",$tr_id,"tr_comp2");
$adId = getFieldValueFromId("tour","tr_id",$tr_id,"ad_id");
$adStreet = getFieldValueFromId("address","ad_id",$adId,"ad_street");
$adHsno = getFieldValueFromId("tour","tr_id",$tr_id,"tr_hsno ");
$adZipcode = getFieldValueFromId("address","ad_id",$adId,"ad_zipcode");
$adCity = getFieldValueFromId("address","ad_id",$adId,"ad_city");
$currAddress = $adStreet . " " . $adHsno . " in " . $adZipcode . " " . $adCity;
// ETA
$etaOut = "";
$etaOffset = get_tour_duration($tr_id);
$roundToXMinutes = 5;
$sendEmail = true;
if (is_numeric($etaOffset)) :
if ($etaOffset != -1) :
// ETA
$currUnixTimestamp = time();
if ($roundToXMinutes != "" && is_numeric($roundToXMinutes) && $roundToXMinutes > 1) :
$eta = (floor(($currUnixTimestamp + $etaOffset) / 60) - (floor(($currUnixTimestamp + $etaOffset) / 60) % $roundToXMinutes)) * 60; // Full x minutes (e.g. 5)
else :
$eta = floor(($currUnixTimestamp + $etaOffset) / 60) * 60; // Full minute
endif;
$etaTime = date("H:i", $eta);
if ($jbCsBlurMarkupTimePayer > 0) :
// Time window
$etaTimeLowerRange = date("H:i", $eta - ($jbCsBlurMarkupTimePayer * 60));
$etaTimeUpperRange = date("H:i", $eta + ($jbCsBlurMarkupTimePayer * 60));
$etaOut .= getLngt("Ihre Sendung von") . " " . $jbCmpCompPayer . " " . getLngt("wird voraussichtlich zwischen") . "<br><br>";
$etaOut .= "<span class=\"f12bp1_blue\">" . $etaTimeLowerRange . " " . getLngt("Uhr") . " " . getLngt("und") . " " . $etaTimeUpperRange . " " . getLngt("Uhr") . "</span><br><br>";
$etaOut .= getLngt("bei") . " " . $trComp . " " . "<br><br>";
$etaOut .= "<b>" . $currAddress . " </b><br><br>";
$etaOut .= getLngt("eintreffen") . "." . "<br><br>";
else :
$etaOut .= getLngt("Ihre Sendung von") . " " . $jbCmpCompPayer . " " . getLngt("wird voraussichtlich um ca.") . "<br><br>";
$etaOut .= "<span class=\"f12bp1_blue\">" . $etaTime . " " . getLngt("Uhr") . "</span><br><br>";
$etaOut .= getLngt("bei") . " " . $trComp . " " . "<br><br>";
$etaOut .= "<b>" . $currAddress . " </b><br><br>";
$etaOut .= getLngt("eintreffen") . "." . "<br><br>";
endif;
else :
// updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_NOK"),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
// sendExternalMail ("[DEBUG] [JB: " . $job_id . "] [TR: " . $tr_id . "] [Time: " . $currentTime . "] [ETA_OFFSET: " . $etaOffset . "] [TO: " . $f_email . "] [LR: " . $etaTimeLowerRange . "] [UR: " . $etaTimeUpperRange . "]", "Tracking_Internal", "mv@assecutor.de", "", "", "", "", "", "");
// $sendEmail = false;
$etaOut .= getLngt("Ihre Sendung von") . " " . $jbCmpCompPayer . "<br><br>";
$etaOut .= getLngt("an") . " " . $trComp . " " . "<br><br>";
$etaOut .= "<b>" . $currAddress . " </b><br><br>";
$etaOut .= getLngt("ist unterwegs") . "." . "<br><br>";
$sendEmail = true;
endif;
endif;
// Send tracking email. "array($tmpArray)" equals "array(array(...))" !!!!
if ($sendEmail) :
$mailSubject = getLngt("Ihre Sendung ist auf dem Weg zu Ihnen!");
$emailResArr = sendTrackingHTMLMail($f_email, $tmpArray, $constGlobalDbInstNo, $job_id, $trackingLink, $currentHqId, "0", $parLogoArr, $etaOut, $mailSubject);
// Get current mail status
$statusSent = "NOT OK";
if ($emailResArr[0] == "0") :
$mailResult = ($emailResArr[1] == "1" ? true : false);
if ($mailResult) :
// updateStmt("job", "jb_id", $job_id, array("jb_automailsent6", "999"));
updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_OK"),"gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
$statusSent = "OK";
else :
// Get number of tries and increment
$trEmailSentCount = getFieldValueFromClause("phoenix.genericdatacontainer", "gdc_context", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
if ($trEmailSentCount == "") : $trEmailSentCount = 0; endif;
$trEmailSentCount++;
// Check for maximum of 3 fault trials. If reached then finalize with error code
if ($trEmailSentCount > 3) :
updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_NOK"),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
else :
updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", $trEmailSentCount),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
endif;
endif;
else :
updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_NOK"),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
endif;
// Write logdata into log file
writeToFile($logFile, "[JB: " . $job_id . "] [TR: " . $tr_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [End_customer] [Status: " . $statusSent . "] [Err: " . ($emailResArr[0] != "0" ? $emailResArr[2] : "NO") . "]");
else :
// Write logdata into log file
$statusSent = "NOT OK";
writeToFile($logFile, "[JB: " . $job_id . "] [TR: " . $tr_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [End_customer, no email sent!] [Status: " . $statusSent . "] [Err: " . ($emailResArr[0] != "0" ? $emailResArr[2] : "NO") . "]");
endif;
else :
// Check semaphor to be removed
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
deleteStmt("phoenix_log.semaphor","sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "SENT_NOK"),"gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Erledigung] [Status: NOT OK]");
endif;
endif;
// else :
// updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "SENT_NOK"),"gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
// endif; // tr_sort
sleep(1);
else :
writeToFile($logFile, "[" . $currentTime . "] " . "[" . $job_id . "] " . "No Customer ID!");
endif; // cs_id
else :
writeToFile($logFile, "[" . $currentTime . "] " . "[" . $job_id . "] " . "No invoice payer!");
endif; // csc_id_payer
else :
writeToFile($logFile, "[" . $currentTime . "] " . "[" . $job_id . "] " . "Called without job!");
endif; // $job_id
endfor; // Loop jobs
endif; // $argv[1]
endif; // AUTOMAILER_ENABLED && AUTOMAILER_2_TRACKING_ENABLED
?>

View File

@@ -0,0 +1,58 @@
<?php
/*=======================================================================
*
* automailer7_main.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
// if (isRunning(1)):
// exit();
// endif;
// Execution-Time for script
set_time_limit(0);
function call_automailer7() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer7.php acapella7890 >" . $path . "/log/automailer7.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", "0");
$constAutomailerSleeptime = getParameterValue("0", "AUTOMAILER_SLEEP_TIME", "0");
if ($constAutomailerSleeptime == "" || !is_numeric($constAutomailerSleeptime) || $constAutomailerSleeptime < 2 || $constAutomailerSleeptime > 9) :
$constAutomailerSleeptime = 4;
endif;
// Endless loop
while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "automailer7", array("ka_lastexecutiontime", $currentTime),"");
if (true) :
call_automailer7();
endif;
sleep(10);
endwhile; // Endless loop
?>

View File

@@ -0,0 +1,203 @@
<?php
/*=======================================================================
*
* automailer8.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
// include_once ("../include/image.inc.php");
// include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");
if (isRunning(5)):
exit();
endif;
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_8", "0");
if ($logFile == "") : $logFile = "../log/automailer8.log"; endif;
$gdcJobJamKey = "jb_job_jam_ctrl";
$semaphorKey = "automailer8";
$semaphorLiveTime = 120;
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// ********************************
// *** Send mails automatically ***
// ********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArray = getAutoMailerJobJamControl(5);
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
if ($lenJobArray > 0) :
// writeToFile("../log/automailer8.log", "lenJobArray = " .$lenJobArray . " :: Jobs: " . $jobArray[0][0] . " " . $jobArray[1][0] . " " . $jobArray[2][0] . " " . $jobArray[3][0] . " " . $jobArray[4][0]);
endif;
for ($i = 0; $i < $lenJobArray; $i++) :
// Init for each job
$jbMailAttachements = array();
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$takeCscMailAdress = $jobArray[$i][4];
$f_email_csc = $jobArray[$i][5];
$f_email_csc = str_replace(" ", "", $f_email_csc);
$csIdPayer = $jobArray[$i][6];
$jbOrdertime = $jobArray[$i][7];
// writeToFile("../log/automailer8.log", "job_id = " .$job_id);
// Take email address stored to costcenter (invoice address) if activated
if ($f_email_csc != "" && $takeCscMailAdress == "1") :
$f_email = $f_email_csc;
endif;
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_8", "0");
if ($logFile == "") : $logFile = "../log/automailer8.log"; endif;
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Initiate switch for the mail text according to the caller mode for taken jobs (= 1)
$mailTextJobStatus = "1";
// Standalone process
$automailer = "1";
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// $f_email = "va@assecutor.de,mv@assecutor.de";
// $f_email = "ingo.kublenz@stadtbote.de,va@assecutor.de,mv@assecutor.de";
if ($job_id != "" && $f_email != "" && $currentHqId != "") :
// The semaphore basically has to be generated by inserting a new job.
// Here the existence will be checked finally, but the code should not be executed (!!!!)
if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey))) :
insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $job_id, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
die();
endif;
// Try to lock semaphore
$res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
if ($db->affected_rows > 0) :
// include ("../admin/jb_detail.php");
// *****************
// Check language by payer for sending email and take customer parameter
$csLanguageMail = getParameterValue("0", "JOBDETAILS_EMAIL_LANGUAGE_" . $csIdPayer, "0");
if ($csLanguageMail == "") : $csLanguageMail = "0"; endif;
$remLanguageSelected = "";
if ($languageSelected != $csLanguageMail) :
$remLanguageSelected = $languageSelected;
$languageSelected = $csLanguageMail;
getLanguage(__FILE__);
endif;
$mailSubject = getLngt("Ihr Auftrag") . " " . $job_id . " " . getLngt("wurde erfolgreich vermittelt");
$mailContent = getLngt("wir möchten Sie darüber informieren, dass Ihr aktueller Auftrag, geplant für") . " " . formatOutput($jbOrdertime, "datetime", "14") . ", "
. getLngt("nun erfolgreich an einen Boten vermittelt wurde.") . "<br>"
. getLngt("Unser Fahrer befindet sich bereits auf dem Weg zu Ihnen und wird die Lieferung schnellstmöglich zustellen.") . "<br>"
. getLngt("Sollten Sie weitere Fragen haben, stehen wir Ihnen gerne zur Verfügung.") . "<br><br>"
. getLngt("Wir danken Ihnen für Ihr Vertrauen in STADTBOTE und wünschen Ihnen einen angenehmen Tag.") . "<br><br>";
$mailContent = "<div class=\"f8np1\">" . $mailContent . "</div>";
$mailResult = sendExternalMailExtended($mailContent, $mailSubject, $f_email);
// $mailResult = sendExternalMailExtended($mailContent, $mailSubject, $f_email, "EMPTY", "EMPTY", "mv@assecutor.de");
// Reset language
if ($remLanguageSelected != "") :
$languageSelected = $remLanguageSelected;
getLanguage(__FILE__);
endif;
// *****************
// *** Mail was sent => Update jb_automailsent8 ***
// Get current mail status
$jbAutomailsent = getFieldValueFromClause("phoenix.genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
if ($jbAutomailsent == "") : $jbAutomailsent = 0; endif;
if ($mailResult) :
// updateStmt("job", "jb_id", $job_id, array("jb_automailsent8", "999"));
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_SENT"),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
$statusSent = "SENT";
else :
$statusSent = "NOT SENT";
$jbAutomailsent++;
// Check for maximum of 3 fault trials. If reached then finalize with error code
if ($jbAutomailsent > 3) :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
else :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $jbAutomailsent),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
endif;
endif;
// Write logdata into log database
writeToLogDB("193",$currentHqId,$job_id,"","","","","MAIL_STATE=" . $statusSent . "|MAIL_TO=" . $f_email);
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [In_Abwicklung_nach_Vermittlungsstau] [Status: " . $statusSent . "]");
else :
// Check semaphore to be unlocked
$spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
$spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
if ($spSecDiff > $semaphorLiveTime) :
updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
endif;
endif;
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [In_Abwicklung_nach_Vermittlungsstau] [Status: NOT OK]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all jobs
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,205 @@
<?php
/*=======================================================================
*
* automailer.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
// include_once ("../include/inc_automailer.inc.php");
// Execution-Time for script
set_time_limit(120);
// Get jobs for automailer
function getAutoMailerJobs_MC($limit) {
global $db, $logFile;
// Try to connect request server because of performance
global $db2;
getDb2Connection();
$retArray = array();
// Limit
if (is_numeric($limit) && $limit > 0) :
$limit = "LIMIT 0," . $limit;
else :
$limit = "";
endif;
$limit = "";
// Exclude jobs with special vehicles (E.g.: Do not generate a mail if internal job is generated with vehicle SID=1888)
$excludedVehicles = getParameterValue("0", "EMAIL_CRVHSID_NO_MAIL", "0"); // "Meta-Global" <=> hq_id = 0
$whereClauseExcludedVehicles = "";
if ($excludedVehicles != "") :
$tmp = spliti(",",$excludedVehicles);
$lenTmp = count($tmp);
for ($i = 0; $i < $lenTmp; $i++) {
$whereClauseExcludedVehicles .= " jb.cr_sid != '" . $tmp[$i] . "' AND ";
};
endif;
$constAmStarttimeInDays = getParameterValue("0", "AUTOMAILER_STARTTIME_IN_DAYS", "0"); // "Meta-Global" <=> hq_id = 0
$startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");
// $currentTime = getDateTime("0");
// jb.jb_automailsent = '999' <=> Mail was sent correctly
// jb.jb_automailsent = '998' <=> Mail was NOT sent correctly. Process iteration terminated!
// jb.jb_automailsent = '997' <=> Mail will never be sent because it is a batch job
// Otherwise number is equal to the number of faults.
$sqlquery = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email, cs.cs_eid, cmp.cmp_comp, cs.cs_jbstatusmail_pdf, jb.jb_finishtime, jb.jb_automailsent"
. " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr, company AS cmp"
. " WHERE jb.jb_status = '2' AND"
. " jb.jb_finishtime > '" . $startTime . "' AND"
. " jb.jb_automailsent != '997' AND"
. " jb.jb_automailsent != '998' AND"
. " jb.jb_automailsent != '999' AND"
. $whereClauseExcludedVehicles
. " (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') AND"
. " jb.csc_id_payer = csc.csc_id AND"
. " csc.cs_id = cs.cs_id AND"
. " cs.cs_jbstatusmail = '1' AND"
. " cmp.cmp_id = cs.cmp_id AND"
. " cs.cs_admin = emp.emp_id AND"
. " emp.usr_id = usr.usr_id AND"
. " csc.csc_id = cscad.csc_id AND"
. " cscad.adt_id = '2' AND"
. " jb.jb_id = tr.jb_id AND"
. " tr.tr_sort = '1' AND"
. " tr.tr_status = '1' "
. " ORDER BY jb.jb_finishtime " . $limit;
$sqlquery2 = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email, cs.cs_eid, cmp.cmp_comp, cs.cs_jbstatusmail_pdf, jb.jb_finishtime, jb.jb_automailsent"
. " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr, company AS cmp"
. " WHERE jb.jb_status = '2' AND"
. " jb.jb_finishtime > '" . $startTime . "' AND"
. " jb.jb_automailsent != '997' AND"
. " jb.jb_automailsent != '998' AND"
. " jb.jb_automailsent != '999' AND"
. $whereClauseExcludedVehicles
. " (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') AND"
. " jb.csc_id_payer_cash = csc.csc_id AND"
. " csc.cs_id = cs.cs_id AND"
. " cs.cs_jbstatusmail = '1' AND"
. " cmp.cmp_id = cs.cmp_id AND"
. " cs.cs_admin = emp.emp_id AND"
. " emp.usr_id = usr.usr_id AND"
. " csc.csc_id = cscad.csc_id AND"
. " cscad.adt_id = '2' AND"
. " jb.jb_id = tr.jb_id AND"
. " tr.tr_sort = '1' AND"
. " tr.tr_status = '1' "
. " ORDER BY jb.jb_finishtime " . $limit;
// echo "(" . $sqlquery . ") UNION (" . $sqlquery2 . ")"; die();
$result = $db2->query("(" . $sqlquery . ") UNION (" . $sqlquery2 . ")");
// $result = $db2->query($sqlquery . " UNION " . $sqlquery2);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
while ($row = $result->fetch_assoc()):
$retArray[] = array($row["jb_id"], $row["usr_email"], $row["cr_sid"], $row["hq_id"], $row["cs_jbstatusmail2csc"], $row["cscad_email"], $row["cs_eid"], $row["cmp_comp"], $row["cs_jbstatusmail_pdf"], $row["jb_finishtime"], $row["jb_automailsent"]);
endwhile;
$result->free();
return $retArray;
}
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", "0");
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// ********************************
// *** Send mails automatically ***
// ********************************
$output = "";
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArray = getAutoMailerJobs_MC(1);
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
$output .= "<table>";
$output .= "<tr>";
$output .= "<td>AUFTRAG</td>";
$output .= "<td>ERLEDIGUNGSZEIT</td>";
$output .= "<td>KURIER</td>";
$output .= "<td>HQ</td>";
$output .= "<td>EID</td>";
$output .= "<td>FIRMA</td>";
$output .= "<td>PDF JA_NEIN</td>";
$output .= "<td>AUTOMAILSENT_STATE</td>";
$output .= "<td>MAIL (CS)</td>";
$output .= "<td>MAIL_CSC?</td>";
$output .= "<td>MAIL (CSC)</td>";
$output .= "</tr>";
$count = 0;
for ($i = 0; $i < $lenJobArray; $i++) :
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_jb_finishtime = $jobArray[$i][9];
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$takeCscMailAdress = $jobArray[$i][4];
$f_cs_eid = $jobArray[$i][6];
$f_cmp_comp = $jobArray[$i][7];
$f_cs_jbstatusmail_pdf = $jobArray[$i][8];
$f_jb_automailsent = $jobArray[$i][10];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$f_email_csc = $jobArray[$i][5];
$f_email_csc = str_replace(" ", "", $f_email_csc);
$output .= "<tr>";
$output .= "<td>" . $job_id . "</td>";
$output .= "<td>" . $f_jb_finishtime . "</td>";
$output .= "<td>" . $job_crSid . "</td>";
$output .= "<td>" . $currentHqId . "</td>";
$output .= "<td>" . $f_cs_eid . "</td>";
$output .= "<td>" . $f_cmp_comp . "</td>";
$output .= "<td>" . $f_cs_jbstatusmail_pdf . "</td>";
$output .= "<td>" . $f_jb_automailsent . "</td>";
$output .= "<td>" . $f_email . "</td>";
$output .= "<td>" . $takeCscMailAdress . "</td>";
$output .= "<td>" . $f_email_csc . "</td>";
$output .= "</tr>";
$count++;
endfor; // Loop all jobs
$output .= "</table>";
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
echo $count;
echo "<br><br><br><br>";
echo $output
?>

View File

@@ -0,0 +1,95 @@
<?php
/*=======================================================================
*
* automailer_internal.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
// include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
// getSecHttpVars("0", array("auth", "errMsg"));
$auth = trim($argv[1]);
$mailText = trim($argv[2]);
$mailSubject = trim($argv[3]);
$mailTo = trim($argv[4]);
$mailFrom = trim($argv[5]);
$mailCc = trim($argv[6]);
$mailBcc = trim($argv[7]);
$mailMode = trim($argv[8]);
$mailLogContent = trim($argv[9]);
$mailLogFile = trim($argv[10]);
$mailText = urldecode($mailText);
$mailSubject = urldecode($mailSubject);
$mailLogContent = urldecode($mailLogContent);
// Execution-Time for script
set_time_limit(120);
// Writes a string to a file optional with or without linefeed
function writeToInternalMailLogFile($fileName, $stringToOperate, $mode = 'a', $noLf = "") {
$fileHandle = fopen("../log/" . $fileName, $mode);
if ($noLf == "") : $stringToOperate .= "\n"; endif;
$opCode = fwrite($fileHandle, $stringToOperate);
fclose($fileHandle);
return $opCode;
}
if ($mailLogFile == "" || $mailLogFile == "EMPTY") : $mailLogFile = "external_mail.log"; endif;
writeToInternalMailLogFile($mailLogFile, "To: " . $mailTo);
writeToInternalMailLogFile($mailLogFile, "Subject: [" . $mailSubject . "]");
writeToInternalMailLogFile($mailLogFile, "Text: " . $mailText);
if ($auth == "comegetsome97531" && $mailText != "" && $mailTo != "") :
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$currentTime = getDateTime("0");
$currentClientIP = trim($_SERVER['REMOTE_ADDR']);
writeToInternalMailLogFile($mailLogFile, $currentTime . " | " . $currentClientIP);
if ($mailLogContent != "" && $mailLogContent != "EMPTY") :
writeToInternalMailLogFile($mailLogFile, $mailLogContent);
endif;
// Send mail to admin@assecutor.de
$mailObj = new htmlMimeMail();
if ($mailFrom == "" || $mailFrom == "EMPTY") :
$mailFrom = "admin@assecutor.de";
endif;
$mailObj->setFrom($mailFrom);
if ($mailCc != "" && $mailCc != "EMPTY") :
$mailObj->setCc($mailCc);
endif;
if ($mailBcc != "" && $mailBcc != "EMPTY") :
$mailObj->setBcc($mailBcc);
endif;
$mailObj->setSubject($mailSubject);
if (strtolower($mailMode) == "html") :
// HTML
$mailObj->setHtml($mailText, null, "./");
else :
// PLAIN-TEXT
$mailObj->setText($mailText);
endif;
$mailResult = $mailObj->send(array($mailTo), 'smtp');
if ($mailResult) :
writeToInternalMailLogFile($mailLogFile, "MAIL SENT!");
else :
writeToInternalMailLogFile($mailLogFile, "MAIL NOT SENT!");
endif;
$mailObj = NULL;
writeToInternalMailLogFile($mailLogFile, "---------------------------------------------------");
endif;
?>

View File

@@ -0,0 +1,68 @@
<?php
/*=======================================================================
*
* automailer_internal.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
// include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
// getSecHttpVars("0", array("auth", "errMsg"));
$auth = trim($argv[1]);
$errMsg = trim($argv[2]);
// Execution-Time for script
set_time_limit(120);
// Writes a string to a file optional with or without linefeed
function writeToInternalMailLogFile($fileName, $stringToOperate, $mode = 'a', $noLf = "") {
$fileHandle = fopen($fileName, $mode);
if ($noLf == "") : $stringToOperate .= "\n"; endif;
$opCode = fwrite($fileHandle, $stringToOperate);
fclose($fileHandle);
return $opCode;
}
writeToInternalMailLogFile("test_internal_mail.log", $auth . " | " . $errMsg);
if ($auth == "comegetsome97531" && $errMsg != "") :
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$currentTime = getDateTime("0");
$currentClientIP = trim($_SERVER['REMOTE_ADDR']);
writeToInternalMailLogFile("test_internal_mail.log", $currentTime . " | " . $currentClientIP);
// Send mail to admin@assecutor.de
$mailObj = new htmlMimeMail();
$mailObj->setFrom("admin@assecutor.de");
// $mailObj->setCc($mailCcAddress);
// $mailObj->setBcc($mailBccAddress);
$mailObj->setSubject("VOTIAN - INTERNE MELDUNG!");
// PLAIN-TEXT
$mailtext = "<" . $errMsg . ">";
if ($errMsg == "metaobject_db_fail") :
$mailtext .= " - " . "METAOBJECT-DATENBANK VERMUTLICH NICHT ERREICHBAR!";
endif;
$mailObj->setText($mailtext);
$mailResult = $mailObj->send(array("dev@assecutor.de"), 'smtp');
if ($mailResult) :
writeToInternalMailLogFile("test_internal_mail.log", "MAIL SENT!");
else :
writeToInternalMailLogFile("test_internal_mail.log", "MAIL NOT SENT!");
endif;
$mailObj = NULL;
writeToInternalMailLogFile("test_internal_mail.log", "---------------------------------------------------");
endif;
?>

View File

@@ -0,0 +1,160 @@
<?php
/*=======================================================================
*
* automailer_main.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
// if (isRunning(1)):
// exit();
// endif;
// Execution-Time for script
set_time_limit(0);
function call_automailer() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer.php >" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
function call_automailer2() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer2.php >" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
function call_automailer3() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer3.php >" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
function call_automailer4() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer4.php >" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
function call_automailer5() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer5.php >" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
function call_automailer6() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer6.php >" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
function call_automailer8() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer8.php >" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
}
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", "0");
$constAutomailerSleeptime = getParameterValue("0", "AUTOMAILER_SLEEP_TIME", "0");
if ($constAutomailerSleeptime == "" || !is_numeric($constAutomailerSleeptime) || $constAutomailerSleeptime < 2 || $constAutomailerSleeptime > 9) :
$constAutomailerSleeptime = 4;
endif;
// Endless loop
while (TRUE):
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0");
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
if ($constAutomailerEnabled == '1') :
call_automailer();
endif;
sleep($constAutomailerSleeptime);
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
if ($constAutomailerEnabled == '1') :
call_automailer2();
endif;
sleep($constAutomailerSleeptime);
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
if ($constAutomailerEnabled == '1') :
call_automailer3();
endif;
sleep($constAutomailerSleeptime);
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
if ($constAutomailerEnabled == '1') :
call_automailer4();
endif;
sleep(1);
// Set execution time for keepalive
// $currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
if ($constAutomailerEnabled == '1') :
call_automailer5();
endif;
sleep(1);
if ($constAutomailerEnabled == '1') :
call_automailer6();
endif;
sleep(1);
if ($constAutomailerEnabled == '1') :
call_automailer8();
endif;
sleep(1);
endwhile; // Endless loop
?>

View File

@@ -0,0 +1,197 @@
<?php
/*=======================================================================
*
* automailer_related.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
$hq_id = HQ_ID_DEFAULT;
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/jb_detail_history.inc.php");
include_once ("../include/inc_html2pdf.inc.php");
include_once ("../include/inc_automailer_related.inc.php");
include_once ("../include/inc_metafield.inc.php");
// Execution-Time for script
set_time_limit(120);
// START SCRIPT
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_RELATED", "0");
// Endless loop
// while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
// updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
// ********************************
// *** Send mails automatically ***
// ********************************
$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0"); // "Meta-Global" <=> hq_id = 0
if ($constAutomailerEnabled == '1') :
// Get next job(s) to send per mail to the customer
$jobArray = getAutoMailerJobs(1,"csc_id_related");
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
for ($i = 0; $i < $lenJobArray; $i++) :
// Current job and mail address
$job_id = $jobArray[$i][0];
$f_email = trim($jobArray[$i][1]);
$f_email = str_replace(" ", "", $f_email);
$job_crSid = $jobArray[$i][2];
$currentHqId = $jobArray[$i][3];
$takeCscMailAdress = $jobArray[$i][4];
$f_email_csc = $jobArray[$i][5];
$f_email_csc = str_replace(" ", "", $f_email_csc);
// Take email address stored to costcenter (invoice address) if activated
if ($f_email_csc != "" && $takeCscMailAdress == "1") :
$f_email = $f_email_csc;
endif;
// Define constants
$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_RELATED", $currentHqId);
$constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
// Set action parameters
$f_act = "mailsend";
$mailResult = FALSE;
// Standalone process
$automailer = "1";
if ($job_id != "" && $f_email != "" && $currentHqId != "") :
$tmpPdfPath = "../temp/pdf/";
$jbMailAttachements = array();
// **** Acceptance protocol ****
$hq_id = $currentHqId;
$category = "300";
$objId = $job_id;
$cascadingObjType = "jb";
$gHqId = true;
$constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ_" . $category, "0");
if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
$gHqId = false;
else :
$constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ", "0");
if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
$gHqId = false;
endif;
endif;
initMetaFieldStructure();
$pathAndFilename = generateMetafieldPDF($tmpPdfPath);
// $filename = substr($pathAndFilename, strlen($tmpPdfPath));
$filename = "Abnahmeprotokoll_" . $job_id . ".pdf";
$jbMailAttachements[0][0] = $pathAndFilename;
$jbMailAttachements[0][1] = $filename;
// ****************************************************************
// **** Customer service protocol ****
$hq_id = $currentHqId;
$category = "306";
$objId = $job_id;
$cascadingObjType = "jb";
$gHqId = true;
$constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ_" . $category, "0");
if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
$gHqId = false;
else :
$constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ", "0");
if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
$gHqId = false;
endif;
endif;
initMetaFieldStructure();
$pathAndFilename = generateMetafieldPDF($tmpPdfPath);
// $filename = substr($pathAndFilename, strlen($tmpPdfPath));
$filename = "Kundendienstaufnahme_" . $job_id . ".pdf";
$jbMailAttachements[1][0] = $pathAndFilename;
$jbMailAttachements[1][1] = $filename;
include_once ("../admin/jb_detail.php");
// $output = getJobMailText($currentHqId, $job_id, "2");
// *** Mail was sent => Update jb_automailsent ***
// Get current mail status
$jbAutomailsent = getFieldValueFromId("job","jb_id",$job_id,"jb_automailsent");
if ($jbAutomailsent == "" || !is_numeric($jbAutomailsent)) : $jbAutomailsent = 0; endif;
if ($mailResult) :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", "999"));
$statusSent = "OK";
else :
$statusSent = "NOT OK";
$jbAutomailsent++;
// Check for maximum of 5 fault trials. If reached then finalize with error code
if ($jbAutomailsent > "5") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", "998"));
else :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", $jbAutomailsent));
endif;
endif;
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Erledigung] [Status: " . $statusSent . "] [RELATED]");
// $mailObj.dispose();
else :
// If email address is empty then set sent status to NOT OK
if ($f_email == "" && $job_id != "" && $currentHqId != "") :
updateStmt("job", "jb_id", $job_id, array("jb_automailsent", "998"));
// Write logdata into log file
writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Erledigung] [Status: NOT OK] [RELATED]");
endif;
endif;
$job_id = "";
$f_email = "";
endfor; // Loop all jobs
endif; // AUTOMAILER_ENABLED
// sleep(30);
// endwhile; // Endless loop
?>

View File

@@ -0,0 +1,246 @@
<?php
/*=======================================================================
*
* autoranking_keepalive.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$isCronJob = FALSE; // Switch for cron-job
$loopFlag = TRUE; // Flag for endless flag
$logFile = $path . "/log/autoranking.log"; // Logfile
function call_autoranking_main() {
global $logFile, $path;
$result = "";
// $cmd = $_SERVER['DOCUMENT_ROOT'] . " /phoenix/include/autoranking_main.php >" . $_SERVER['DOCUMENT_ROOT'] . "/phoenix/log/autoranking.stdout+err 2>&1 &";
$cmd = "php " . $path . "/include/autoranking_main.php >" . $path . "/log/autoranking.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Restart autoranking process [Time: " . $currentTime . "]");
}
function call_autoranking() {
global $logFile, $path;
$result = "";
// $cmd = $_SERVER['DOCUMENT_ROOT'] . " /phoenix/include/autoranking.php >" . $_SERVER['DOCUMENT_ROOT'] . "/phoenix/log/autoranking.stdout+err 2>&1 &";
$cmd = "php " . $path . "/include/autoranking.php >" . $path . "/log/autoranking.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Restart autoranking process [Time: " . $currentTime . "]");
}
function call_standing_orders() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/jobs/check_jb_permanent.php >>" . $path . "/log/check_jb_permanent.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Restart check_jb_permanent process [Time: " . $currentTime . "]");
}
function call_automailer() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer_main.php >>" . $path . "/log/automailer.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Restart automailer process [Time: " . $currentTime . "]");
}
function call_automailer7() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/automailer7_main.php >>" . $path . "/log/automailer7.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Restart automailer7 process [Time: " . $currentTime . "]");
}
function call_DPF() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/ckeck_DPF_main.php >>" . $path . "/log/dpf.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Restart check_DPF_main process [Time: " . $currentTime . "]");
}
function call_vhtDispoDays() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/cron_vht_dispo_days.php >>" . $path . "/log/vhtDispoDays.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Executed vht_dispo_days process [Time: " . $currentTime . "]");
}
function call_serviceAcceptanceProtocol() {
global $logFile, $path;
$result = "";
$cmd = "php " . $path . "/include/cron_service_acceptance_protocol.php >>" . $path . "/log/acceptance_protocol.stdout+err 2>&1 &";
$ausgabe = system($cmd, $result);
// Log restart
$currentTime = getDateTime("0");
writeToFile($logFile, "WATCHDOG: Restart service_acceptance_protocol process [Time: " . $currentTime . "]");
}
// Execution-Time for script
if (!$isCronJob) :
set_time_limit(0);
endif;
// Endless loop if no cron-job
while ($loopFlag):
// Set loop flag
if ($isCronJob) : $loopFlag = FALSE; endif;
// Get last execution time of the autoranking script
$lastExecutionTime = getFieldValueFromId("keepalive","ka_process","autoranking","ka_lastexecutiontime");
// Get timestamps
// ("checkTime" = NOW() minus 2 minutes)
$currentTime = getDateTime("0");
$checkTime = getDateTime("datetime_plus_offset", array(0,-1,0,0,0,0), $formatStr = "Y-m-d H:i:s");
// Watchdog execution
writeToFile($logFile, "Watchdog executed: " . $currentTime);
// Check autoranking being alive
if ($checkTime > $lastExecutionTime) :
// call_autoranking();
call_autoranking_main();
endif;
// *********************************************************************************************************************
// Check check_jb_permanent being alive
$lastExecutionTime = getFieldValueFromId("keepalive","ka_process","standing_orders","ka_lastexecutiontime");
// ("checkTime" = NOW() minus 30 minutes)
$checkTime = getDateTime("datetime_plus_offset", array(0,-30,0,0,0,0), $formatStr = "Y-m-d H:i:s");
if ($checkTime > $lastExecutionTime):
call_standing_orders();
endif;
// *********************************************************************************************************************
// Get last execution time of the automailer script
$lastExecutionTime = getFieldValueFromId("keepalive","ka_process","automailer","ka_lastexecutiontime");
// ("checkTime" = NOW() minus 2 minutes)
$checkTime = getDateTime("datetime_plus_offset", array(0,-2,0,0,0,0), $formatStr = "Y-m-d H:i:s");
// Check autoranking being alive
if ($checkTime > $lastExecutionTime) :
call_automailer();
endif;
// *********************************************************************************************************************
// Get last execution time of the automailer script
$lastExecutionTime = getFieldValueFromId("keepalive","ka_process","automailer7","ka_lastexecutiontime");
// ("checkTime" = NOW() minus 2 minutes)
$checkTime = getDateTime("datetime_plus_offset", array(0,-2,0,0,0,0), $formatStr = "Y-m-d H:i:s");
// Check autoranking being alive
if ($checkTime > $lastExecutionTime) :
call_automailer7();
endif;
// *********************************************************************************************************************
// Get last execution time of the dpf script
/*
$lastExecutionTime = getFieldValueFromId("keepalive","ka_process","dpf","ka_lastexecutiontime");
// ("checkTime" = NOW() minus 30 minutes)
$checkTime = getDateTime("datetime_plus_offset", array(0,-30,0,0,0,0), $formatStr = "Y-m-d H:i:s");
// Check autoranking being alive
if ($checkTime > $lastExecutionTime) :
call_DPF();
endif;
*/
// *********************************************************************************************************************
// Get last execution time of the vhtDispoDays script
/*
$lastExecutionTime = getFieldValueFromId("keepalive","ka_process","vhtDispoDays","ka_lastexecutiontime");
// ("checkTime" = NOW() minus 7 days)
$checkTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-1,0), $formatStr = "Y-m-d H:i:s");
// Check autoranking being alive
if ($checkTime > $lastExecutionTime) :
call_vhtDispoDays();
endif;
*/
// *********************************************************************************************************************
// Get last execution time of the service acceptance protocol script
/*
$lastExecutionTime = getFieldValueFromId("keepalive","ka_process","serviceAcceptanceProtocol","ka_lastexecutiontime");
// ("checkTime" = NOW() minus 30 minutes)
$checkTime = getDateTime("datetime_plus_offset", array(0,-1,0,0,0,0), $formatStr = "Y-m-d H:i:s");
// Check autoranking being alive
if ($checkTime > $lastExecutionTime) :
call_serviceAcceptanceProtocol();
endif;
*/
if (!$isCronJob) :
sleep(60);
endif;
endwhile; // Endless loop
?>

View File

@@ -0,0 +1,176 @@
<?php
/*=======================================================================
*
* autoranking_main.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
$standalone = "1"; // has to be set before including "ranking.inc.php"
include_once ("../include/ranking.inc.php");
include_once ("../include/inc_autoranking.inc.php");
// if (isRunning(3)):
// exit();
// endif;
// Execution-Time for script
set_time_limit(0);
// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
// Get single job for autoranking with the zipcode of the startaddress and other informations
function getLockedCouriersByAutoranking ($limit = "") {
global $db;
$retArray = array();
$limitClause = "";
if ($limit != "" && is_numeric($limit)) : $limitClause = "LIMIT 0," . $limit; endif;
$sqlquery = "SELECT cr.cr_id, cr.cr_ar_jb_id FROM courier AS cr WHERE cr.cr_ar_jb_id > '0' ORDER BY cr.cr_ar_jb_id " . $limitClause;
$result = $db->dbQ($sqlquery);
while ($row = $result->fetch_assoc()):
$retArray[] = array($row["cr_id"], $row["cr_ar_jb_id"]);
endwhile;
$result->free();
return $retArray;
}
// Endless loop
while (TRUE):
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");
// *******************
// *** Assign jobs ***
// *******************
// Get next job(s) with status 8 for the specified headquarter (no storno)
$jobArray = getAutoRankingJobs(40);
// Loop all jobs (default one)
$lenJobArray = count($jobArray);
for ($i = 0; $i < $lenJobArray; $i++) :
$jobId = $jobArray[$i][0];
$system_result = "";
$cmd = "php " . $path . "/include/autoranking_single.php " . $jobId . " >" . $path . "/log/autoranking.stdout+err 2>&1 &";
$ausgabe = system($cmd, $system_result);
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");
endfor; // Loop all jobs
// *******************
// *** Revoke jobs ***
// *******************
// Get job(s) to be revoked because timeout
if (!isset($arRevokeJobModeToggler) || $arRevokeJobModeToggler == "") : $arRevokeJobModeToggler = "1"; else : $arRevokeJobModeToggler = ""; endif;
$jobArray = getRevokeJobs(40, $arRevokeJobModeToggler);
$jobArrayLen = count($jobArray);
if ($jobArrayLen > 0) :
for ($i = 0; $i < $jobArrayLen; $i++) :
$jbId = $jobArray[$i][0];
$currentHqId = $jobArray[$i][1];
$jbAutoranking = $jobArray[$i][2];
$logFile = getParameterValue("0", "AUTORANKING_LOGFILE", $currentHqId);
if ($logFile == "") : writeToFile($logFile, "CONSTANT ERR.: AUTORANKING_LOGFILE [HQ: " . $currentHqId . "]"); endif;
// Check REVOKING enabled
$constArRevokingEnabled = getParameterValue("0", "AUTORANKING_REVOCATION_ENABLED", $currentHqId);
if ($constArRevokingEnabled != "") :
$constArRevokeJobMode = getParameterValue("0", "AUTORANKING_REVOKE_JOB_MODE", $currentHqId);
if (($constArRevokeJobMode == "1" && $jbAutoranking != "1") || ($constArRevokeJobMode == "2" && $jbAutoranking != "0")) :
$constArRevokingEnabled = ""; // Do NOT revoke the current job (ATTENTION: $constArRevokingEnabled is set !!!)
endif;
endif;
if ($constArRevokingEnabled == '1') :
$revokedData = revokeJobFromCourier($jbId);
if (count($revokedData) > 0) :
$currentHqId = $revokedData[8];
$crSid = getFieldValueFromId("courier","cr_id",$revokedData[1],"cr_sid");
$crUsrId = getFieldValueFromId("courier","cr_id",$revokedData[1],"usr_id");
// UNLOCK courier regarding autoranking process
updateStmt("courier", "cr_id", $revokedData[1], array("cr_ar_jb_id", "0"), "cr_ar_jb_id = '" . $jbId . "'");
// Write logdata into log database
writeToLogDB("8",$currentHqId,$revokedData[0],$crUsrId,$revokedData[1],$crSid,"",
"CR_VHT_ID=" . $revokedData[3] . "|JB_VHT_ID = " . $revokedData[4] .
"|LOST_RANKING=" . $revokedData[5] . "|JB_STATUS_NEW=" . $revokedData[6] . "|JB_RESERV=" . $revokedData[7]);
// Write logdata into log file
writeToFile($logFile, "Job " . $revokedData[0] . " revoked from courier " . $revokedData[1] .
" [SID: " . $crSid . "] [Time: " . $revokedData[2] . "]" .
" [cr.vht_id = " . $revokedData[3] . "] [jb.vht_id = " . $revokedData[4] . "]" .
" [Lost Ranking: " . $revokedData[5] . "]" .
" [Set Status: " . $revokedData[6] . "]" .
" [Reservation: " . $revokedData[7] . "]");
endif;
endif; // AUTORANKING_REVOCATION_ENABLED
endfor;
endif;
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");
// ********************************************
// *** Check occupied state of the couriers ***
// ********************************************
$crArray = getLockedCouriersByAutoranking();
// Loop all jobs (default one)
$lenCrArray = count($crArray);
for ($i = 0; $i < $lenCrArray; $i++) :
$crId = $crArray[$i][0];
$jbId = $crArray[$i][1];
$jbFields = getFieldsValueFromId("job", "jb_id", $jbId, array("jb_status","cr_id","cr_id_order"));
if ( ($jbFields[0] > "0") || ($jbFields[1] != "" && $jbFields[1] != $crId) || ($jbFields[2] != $crId) ) :
// UNLOCK courier regarding autoranking process
updateStmt("courier", "cr_id", $crId, array("cr_ar_jb_id", "0"), "cr_ar_jb_id > '0'");
// Write logdata into log file
// writeToFile($logFile, " Courier UNLOCKED - " . "[CR_ID: " . $crId . "] [JB_ID: " . $jbId . "] [JB_STATUS: " . $jbFields[0] . "] [JB_CR_ID: " . $jbFields[1] . "] [JB_CR_ID_ORDER: " . $jbFields[2] . "]");
else :
// Write logdata into log file
// writeToFile($logFile, " Courier NOT UNLOCKED - " . "[CR_ID: " . $crId . "] [JB_ID: " . $jbId . "] [JB_STATUS: " . $jbFields[0] . "] [JB_CR_ID: " . $jbFields[1] . "] [JB_CR_ID_ORDER: " . $jbFields[2] . "]");
endif;
endfor; // Loop all jobs
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");
sleep(15);
endwhile; // Endless loop
?>

View File

@@ -0,0 +1,273 @@
<?php
/*=======================================================================
*
* autoranking_single.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
$standalone = "1"; // has to be set before including "ranking.inc.php"
include_once ("../include/ranking.inc.php");
include_once ("../include/inc_autoranking.inc.php");
// Execution-Time for script
set_time_limit(0);
// Get current job ID from the argument
$jobId = trim($argv[1]);
// Define constants
define("TA_STATUS", "1");
// Get single job for autoranking with the zipcode of the startaddress and other informations
function getSingleAutoRankingJob ($jobId) {
global $db, $logFile;
$retArray = array();
$currentTime = getDateTime("0");
$sqlquery = "SELECT jb.jb_id, jb.hq_id, jb.hq_id_dispo, ad.ad_zipcode, jb.jb_reserv, jb.jb_permanent, jb.cr_id_order, srvpt.srvpt_traveltime, jb.jb_globaljob"
. " FROM tour AS tr, address AS ad LEFT JOIN serviceplz AS srvp ON ad.ad_zipcode = srvp.srvp_plz LEFT JOIN serviceplztraveltime AS srvpt ON srvp.srvp_id = srvpt.srvp_id, job AS jb"
. " WHERE jb.jb_id = '" . $jobId . "' AND"
. " jb.jb_status = '8' AND"
. " (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') AND"
. " (jb.jb_globaljob != '1') AND"
. " ( (ISNULL(jb.jb_reserv) OR jb.jb_reserv = '0') OR"
. " (jb_globaljob = '2' AND jb.jb_reserv = '1') OR"
. " (jb.jb_reserv = '1' AND "
. " DATE_SUB(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime,30) MINUTE) <= '" . $currentTime . "') ) AND"
. " jb.jb_id = tr.jb_id AND"
. " tr.tr_sort = 1 AND"
. " tr.ad_id = ad.ad_id AND"
. " (srvpt.hq_id = jb.hq_id_dispo OR srvpt.hq_id IS NULL)";
$result = $db->dbQ($sqlquery);
while ($row = $result->fetch_assoc()):
// $retArray = array($row["jb_id"], $row["ad_zipcode"], $row["jb_reserv"], $row["jb_permanent"], $row["cr_id_order"], $row["hq_id"], $row["jb_globaljob"]);
$retArray = array($row["jb_id"], $row["ad_zipcode"], $row["jb_reserv"], $row["jb_permanent"], $row["cr_id_order"], $row["hq_id_dispo"], $row["jb_globaljob"]);
endwhile;
$result->free();
return $retArray;
}
if ($jobId != "") :
// Define assign status values for RANKING and LOG
$assignStatusDefine[0] = "ASSIGN_STATUS=RESERVED";
$assignStatusDefine[1] = "ASSIGN_STATUS=FAVOURED";
$assignStatusDefine[2] = "ASSIGN_STATUS=AREA";
$assignStatusDefine[3] = "ASSIGN_STATUS=NEIGHBOUR_AREA";
$assignStatusDefine[4] = "ASSIGN_STATUS=NEIGHBOUR_AREA_2";
$assignStatusDefine[5] = "ASSIGN_STATUS=NEIGHBOUR_AREA_3";
$assignStatusDefine[6] = "ASSIGN_STATUS=NEIGHBOUR_AREA_4";
$assignStatusDefine[7] = "ASSIGN_STATUS=NEIGHBOUR_AREA_5";
$assignStatusDefine[8] = "ASSIGN_STATUS=NEIGHBOUR_AREA_6";
$assignStatusDefine[9] = "ASSIGN_STATUS=NEIGHBOUR_AREA_7";
$assignStatusDefine[10] = "ASSIGN_STATUS=NEIGHBOUR_AREA_8";
$assignStatusDefine[11] = "ASSIGN_STATUS=NEIGHBOUR_AREA_9";
// Set execution time for keepalive
$currentTime = getDateTime("0");
updateStmt("keepalive", " ka_process", "autoranking", array(" ka_lastexecutiontime", $currentTime),"");
// *************************
// *** Assign single job ***
// *************************
// Get next job(s) with status 8 for the specified headquarter (no storno)
$jobArray = getSingleAutoRankingJob($jobId);
$lenJobArray = count($jobArray);
if ($lenJobArray > 0) :
// Initialization (important at this place only)
$status = "";
$enterRankingLists = TRUE;
// $jobId = $jobArray[$i][0];
$zipcode = $jobArray[1];
$jobReserv = $jobArray[2];
$jobPermanent = $jobArray[3];
$jobCrIdOrder = $jobArray[4];
$currentHqId = $jobArray[5];
$jobGlobal = $jobArray[6];
// Check AUTORANKING enabled
$constArAssignmentEnabled = getParameterValue("0", "AUTORANKING_ASSIGNMENT_ENABLED", $currentHqId);
if ($constArAssignmentEnabled == '1') :
$logFile = getParameterValue("0", "AUTORANKING_LOGFILE", $currentHqId);
if ($logFile == "") : writeToFile($logFile, "CONSTANT ERR.: AUTORANKING_LOGFILE [HQ: " . $currentHqId . "]"); endif;
$logDebug = false;
$parLogDebug = getParameterValue("0", "AUTORANKING_DEBUG_LOG", $currentHqId);
if ($parLogDebug == "") : $parLogDebug = getParameterValue("0", "AUTORANKING_DEBUG_LOG", "0"); endif;
if ($parLogDebug == "1") :
$logDebug = true;
writeToFile($logFile, "AUTORANKING_DEBUG ENABLED!");
endif;
// Get the general mediation mode for the headquarter
$mediationMode = getParameterValue("0", "MODE_INTERMEDIATION", $currentHqId);
if ($mediationMode == "") : writeToFile($logFile, "CONSTANT ERR.: MODE_INTERMEDIATION [HQ: " . $currentHqId . "]"); endif;
if ($mediationMode == "") : $mediationMode = getFieldValueFromId("headquarters", "hq_id", $currentHqId, "hq_invmode"); endif;
$constNeighbourLevelPar = getParameterValue("0", "AUTORANKING_NEIGHBOUR_LEVEL", $currentHqId);
if ($constNeighbourLevelPar == "") : writeToFile($logFile, "CONSTANT ERR.: AUTORANKING_NEIGHBOUR_LEVEL [HQ: " . $currentHqId . "]"); endif;
// Get neighbour level for the number of neighbour areas of an area
$neighbourLevel = "";
if ($mediationMode == "3") : // Currently set level ONLY if mediation area is combined mode
$neighbourLevel = 3;
if ($constNeighbourLevelPar != "" && is_numeric($constNeighbourLevelPar)) :
$neighbourLevel = $constNeighbourLevelPar;
endif;
endif;
// Check PDA locating enabled
$locatingByPDA = getPDALocatingStatus($currentHqId);
// Check customer regarding behavior according to (ONLY) favoured couriers
$jobCsOnlyCrFavoured = getCustomerNeedsOnlyFavouredCouriers($jobId, $currentHqId);
// If job is a reservation (or permanent) try to assign courier associated in $jobCrIdOrder, if $jobCrIdOrder is not empty
if ($status == "" && ($jobReserv == "1" || $jobPermanent == "1") && ($jobCrIdOrder != "" && $jobCrIdOrder != "0")) :
$status = assignCourierToJob($jobId, array($jobCrIdOrder), "1", "0", "0", "1", $zipcode); // 0 = "ASSIGN_STATUS=RESERVED"
$enterRankingLists = FALSE; // Do not continue association because no other courier may take the job => Set jb_status = "9" directly
endif;
if ($enterRankingLists) :
// Get number of iterations per AREA
$constArNumOfIter = getParameterValue("0", "AUTORANKING_NUMBER_OF_ITERATIONS", $currentHqId);
// Trace potential errors
if ($constArNumOfIter == "" || $constArNumOfIter == "0") :
writeToFile($logFile, "CONSTANT ERR.: AUTORANKING_NUMBER_OF_ITERATIONS");
$constArNumOfIter = 2; // Default value of iterations of each AREA
endif;
// Get list of the favoured couriers
if ($status == "") :
// Check locating has to be activated because favoured have to be located explicitly by job defined in GDC
$gdcJbIgnoreFavOnly = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jobId . "' AND gdc_gen_fieldname = 'jb_ignore_fav_only'");
if ($gdcJbIgnoreFavOnly == "" || $gdcJbIgnoreFavOnly != "1") :
// Check for filter that only all couriers inside the areas will be involved
$constRankingFavCrAreaRestriction = getParameterValue("0", "RANKING_FAVOURED_COURIER_AREA_RESTRICTION", $currentHqId);
for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
if ($constRankingFavCrAreaRestriction == "1") :
$favouredCourierArray = getCourierByRanking($zipcode, "0000000100", $jobId, "", $currentHqId);
else :
$favouredCourierArray = getCourierByRanking($zipcode, "0010000000", $jobId, "", $currentHqId);
endif;
// Check locating has to be activated because favoured have to be located explicitly by job defined in GDC
$tmpLocatingByPDA = "0";
/*
if ($locatingByPDA != "0") :
if ($gdcJbIgnoreFavOnly == "1") :
$tmpLocatingByPDA = $locatingByPDA;
endif;
endif;
*/
$status = assignCourierToJob($jobId, $favouredCourierArray[2], "1", "1", $tmpLocatingByPDA, "0", $zipcode); // 1 = "ASSIGN_STATUS=FAVOURED"
if ($status != "") : break; endif;
endfor;
endif;
endif;
// Do NOT enter if customer needs ONLY FAVOURED couriers ("0" = normal mode, "1" = only favoured couriers) and
// do NOT enter if the job is a potential global job ($jobGlobal = "2") to be converted into a real global job
if ($jobCsOnlyCrFavoured == "0" && $jobGlobal != "2") :
// Get list of the current mediation area
if ($status == "") :
// Without blocked couriers
for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
$currentAreaCourierArray = getCourierByRanking($zipcode, "0101000000", $jobId, "", $currentHqId);
$status = assignCourierToJob($jobId, $currentAreaCourierArray[3], "", "2", $locatingByPDA, "0", $zipcode); // 2 = "ASSIGN_STATUS=AREA"
if ($status != "") : break; endif;
endfor;
endif;
// Get list of the neighbour mediation areas
if ($neighbourLevel == "") :
if ($status == "") :
// Without blocked couriers
for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
$currentAreaCourierArray = getCourierByRanking($zipcode, "0100100000", $jobId, "", $currentHqId);
$status = assignCourierToJob($jobId, $currentAreaCourierArray[4], "", "3", $locatingByPDA, "0", $zipcode); // 3 = "ASSIGN_STATUS=NEIGHBOUR_AREA"
if ($status != "") : break; endif;
endfor;
endif;
else :
if ($status == "") :
for ($nl = 1; $nl <= $constNeighbourLevelPar; $nl++) :
for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
$currentAreaCourierArray = getCourierByRanking($zipcode, "0100100000", $jobId, $nl, $currentHqId);
$status = assignCourierToJob($jobId, $currentAreaCourierArray[4], "", ($nl + 2), $locatingByPDA, "0", $zipcode);
if ($status != "") : break 2; endif;
endfor;
endfor;
endif;
endif;
endif;
endif;
// Update job for setting to jb_status = '9' because job could not be arbitrated by autoranking
if ($status == "") :
// Get status of resetting the cr_sid or not according to be displayed in list with jb_status = '9' (ONLY for reservations or permanent jobs)
$constRankingNoResetCrSid = "";
if ($jobReserv == "1" || $jobPermanent == "1") :
$constRankingNoResetCrSid = getParameterValue("0", "RANKING_NORESET_CRSID", $currentHqId);
endif;
// Update current timestamp
$currentTime = getDateTime("0");
if ($jobGlobal == "2") :
// Job is a potential global job and has to be converted into a real global job
if ($constRankingNoResetCrSid == "1") :
$res = updateStmt("job", "jb_id", $jobId, array("jb_status", "0", "jb_global", "1"), "jb_status = '8'");
else :
$res = updateStmt("job", "jb_id", $jobId, array("jb_status", "0", "jb_global", "1", "cr_sid", ""), "jb_status = '8'");
endif;
if ($db->affected_rows > 0) :
// Write logdata into log database
writeToLogDB("12",$currentHqId,$jobId,"","","","","CONVERTED_INTO_A_REAL_GLOBAL_JOB");
// Write logdata into log file
writeToFile($logFile, "Job " . $jobId . " CONVERTED INTO A REAL GLOBAL JOB! [Time: " . $currentTime . "]");
endif;
else :
if ($constRankingNoResetCrSid == "1") :
$res = updateStmt("job", "jb_id", $jobId, array("jb_status", "9"), "jb_status = '8'");
else :
$res = updateStmt("job", "jb_id", $jobId, array("jb_status", "9", "cr_sid", ""), "jb_status = '8'");
endif;
if ($db->affected_rows > 0) :
// Write logdata into log database
writeToLogDB("12",$currentHqId,$jobId,"","","","","NOT_ASSOCIATED_PER_AUTORANKING");
// Write logdata into log file
writeToFile($logFile, "Job " . $jobId . " NOT ASSOCIATED! [Time: " . $currentTime . "]");
endif;
endif;
endif;
endif; // AUTORANKING_ASSIGNMENT_ENABLED
endif;
endif;
?>

874
html/include/barcode/DB.php Normal file
View File

@@ -0,0 +1,874 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Stig Bakken <ssb@fast.no> |
// | Tomas V.V.Cox <cox@idecnet.com> |
// +----------------------------------------------------------------------+
//
// $Id: DB.php,v 1.86.2.2 2002/04/09 19:04:02 ssb Exp $
//
// Database independent query interface.
//
require_once "PEAR.php";
/*
* The method mapErrorCode in each DB_dbtype implementation maps
* native error codes to one of these.
*
* If you add an error code here, make sure you also add a textual
* version of it in DB::errorMessage().
*/
define("DB_OK", 1);
define("DB_ERROR", -1);
define("DB_ERROR_SYNTAX", -2);
define("DB_ERROR_CONSTRAINT", -3);
define("DB_ERROR_NOT_FOUND", -4);
define("DB_ERROR_ALREADY_EXISTS", -5);
define("DB_ERROR_UNSUPPORTED", -6);
define("DB_ERROR_MISMATCH", -7);
define("DB_ERROR_INVALID", -8);
define("DB_ERROR_NOT_CAPABLE", -9);
define("DB_ERROR_TRUNCATED", -10);
define("DB_ERROR_INVALID_NUMBER", -11);
define("DB_ERROR_INVALID_DATE", -12);
define("DB_ERROR_DIVZERO", -13);
define("DB_ERROR_NODBSELECTED", -14);
define("DB_ERROR_CANNOT_CREATE", -15);
define("DB_ERROR_CANNOT_DELETE", -16);
define("DB_ERROR_CANNOT_DROP", -17);
define("DB_ERROR_NOSUCHTABLE", -18);
define("DB_ERROR_NOSUCHFIELD", -19);
define("DB_ERROR_NEED_MORE_DATA", -20);
define("DB_ERROR_NOT_LOCKED", -21);
define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
define("DB_ERROR_INVALID_DSN", -23);
define("DB_ERROR_CONNECT_FAILED", -24);
define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
define("DB_ERROR_NOSUCHDB", -25);
define("DB_ERROR_ACCESS_VIOLATION", -26);
/*
* Warnings are not detected as errors by DB::isError(), and are not
* fatal. You can detect whether an error is in fact a warning with
* DB::isWarning().
*/
define('DB_WARNING', -1000);
define('DB_WARNING_READ_ONLY', -1001);
/*
* These constants are used when storing information about prepared
* statements (using the "prepare" method in DB_dbtype).
*
* The prepare/execute model in DB is mostly borrowed from the ODBC
* extension, in a query the "?" character means a scalar parameter.
* There are two extensions though, a "&" character means an opaque
* parameter. An opaque parameter is simply a file name, the real
* data are in that file (useful for putting uploaded files into your
* database and such). The "!" char means a parameter that must be
* left as it is.
* They modify the quote behavoir:
* DB_PARAM_SCALAR (?) => 'original string quoted'
* DB_PARAM_OPAQUE (&) => 'string from file quoted'
* DB_PARAM_MISC (!) => original string
*/
define('DB_PARAM_SCALAR', 1);
define('DB_PARAM_OPAQUE', 2);
define('DB_PARAM_MISC', 3);
/*
* These constants define different ways of returning binary data
* from queries. Again, this model has been borrowed from the ODBC
* extension.
*
* DB_BINMODE_PASSTHRU sends the data directly through to the browser
* when data is fetched from the database.
* DB_BINMODE_RETURN lets you return data as usual.
* DB_BINMODE_CONVERT returns data as well, only it is converted to
* hex format, for example the string "123" would become "313233".
*/
define('DB_BINMODE_PASSTHRU', 1);
define('DB_BINMODE_RETURN', 2);
define('DB_BINMODE_CONVERT', 3);
/**
* This is a special constant that tells DB the user hasn't specified
* any particular get mode, so the default should be used.
*/
define('DB_FETCHMODE_DEFAULT', 0);
/**
* Column data indexed by numbers, ordered from 0 and up
*/
define('DB_FETCHMODE_ORDERED', 1);
/**
* Column data indexed by column names
*/
define('DB_FETCHMODE_ASSOC', 2);
/**
* Column data as object properties
*/
define('DB_FETCHMODE_OBJECT', 3);
/**
* For multi-dimensional results: normally the first level of arrays
* is the row number, and the second level indexed by column number or name.
* DB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
* is the column name, and the second level the row number.
*/
define('DB_FETCHMODE_FLIPPED', 4);
/* for compatibility */
define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
/**
* these are constants for the tableInfo-function
* they are bitwised or'ed. so if there are more constants to be defined
* in the future, adjust DB_TABLEINFO_FULL accordingly
*/
define('DB_TABLEINFO_ORDER', 1);
define('DB_TABLEINFO_ORDERTABLE', 2);
define('DB_TABLEINFO_FULL', 3);
/**
* The main "DB" class is simply a container class with some static
* methods for creating DB objects as well as some utility functions
* common to all parts of DB.
*
* The object model of DB is as follows (indentation means inheritance):
*
* DB The main DB class. This is simply a utility class
* with some "static" methods for creating DB objects as
* well as common utility functions for other DB classes.
*
* DB_common The base for each DB implementation. Provides default
* | implementations (in OO lingo virtual methods) for
* | the actual DB implementations as well as a bunch of
* | query utility functions.
* |
* +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
* When calling DB::factory or DB::connect for MySQL
* connections, the object returned is an instance of this
* class.
*
* @package DB
* @author Stig Bakken <ssb@fast.no>
* @since PHP 4.0
*/
class DB
{
/**
* Create a new DB connection object for the specified database
* type
*
* @param string $type database type, for example "mysql"
*
* @return mixed a newly created DB object, or a DB error code on
* error
*
* access public
*/
function &factory($type)
{
@include_once("DB/${type}.php");
$classname = "DB_${type}";
if (!class_exists($classname)) {
return PEAR::raiseError(null, DB_ERROR_NOT_FOUND,
null, null, null, 'DB_Error', true);
}
@$obj =& new $classname;
return $obj;
}
/**
* Create a new DB connection object and connect to the specified
* database
*
* @param mixed $dsn "data source name", see the DB::parseDSN
* method for a description of the dsn format. Can also be
* specified as an array of the format returned by DB::parseDSN.
*
* @param mixed $options An associative array of option names and
* their values. For backwards compatibility, this parameter may
* also be a boolean that tells whether the connection should be
* persistent. See DB_common::setOption for more information on
* connection options.
*
* @return mixed a newly created DB connection object, or a DB
* error object on error
*
* @see DB::parseDSN
* @see DB::isError
* @see DB_common::setOption
*/
function &connect($dsn, $options = false)
{
if (is_array($dsn)) {
$dsninfo = $dsn;
} else {
$dsninfo = DB::parseDSN($dsn);
}
$type = $dsninfo["phptype"];
if (is_array($options) && isset($options["debug"]) &&
$options["debug"] >= 2) {
// expose php errors with sufficient debug level
include_once "DB/${type}.php";
} else {
@include_once "DB/${type}.php";
}
$classname = "DB_${type}";
if (!class_exists($classname)) {
return PEAR::raiseError(null, DB_ERROR_NOT_FOUND,
null, null, null, 'DB_Error', true);
}
@$obj =& new $classname;
if (is_array($options)) {
foreach ($options as $option => $value) {
$test = $obj->setOption($option, $value);
if (DB::isError($test)) {
return $test;
}
}
} else {
$obj->setOption('persistent', $options);
}
$err = $obj->connect($dsninfo, $obj->getOption('persistent'));
if (DB::isError($err)) {
$err->addUserInfo($dsn);
return $err;
}
return $obj;
}
/**
* Return the DB API version
*
* @return int the DB API version number
*
* @access public
*/
function apiVersion()
{
return 2;
}
/**
* Tell whether a result code from a DB method is an error
*
* @param $value int result code
*
* @return bool whether $value is an error
*
* @access public
*/
function isError($value)
{
return (is_object($value) &&
(get_class($value) == 'db_error' ||
is_subclass_of($value, 'db_error')));
}
/**
* Tell whether a query is a data manipulation query (insert,
* update or delete) or a data definition query (create, drop,
* alter, grant, revoke).
*
* @access public
*
* @param string $query the query
*
* @return boolean whether $query is a data manipulation query
*/
function isManip($query)
{
$manips = 'INSERT|UPDATE|DELETE|'.'REPLACE|CREATE|DROP|'.
'ALTER|GRANT|REVOKE|'.'LOCK|UNLOCK';
if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) {
return true;
}
return false;
}
/**
* Tell whether a result code from a DB method is a warning.
* Warnings differ from errors in that they are generated by DB,
* and are not fatal.
*
* @param mixed $value result value
*
* @return boolean whether $value is a warning
*
* @access public
*/
function isWarning($value)
{
return (is_object($value) &&
(get_class($value) == "db_warning" ||
is_subclass_of($value, "db_warning")));
}
/**
* Return a textual error message for a DB error code
*
* @param integer $value error code
*
* @return string error message, or false if the error code was
* not recognized
*/
function errorMessage($value)
{
static $errorMessages;
if (!isset($errorMessages)) {
$errorMessages = array(
DB_ERROR => 'unknown error',
DB_ERROR_ALREADY_EXISTS => 'already exists',
DB_ERROR_CANNOT_CREATE => 'can not create',
DB_ERROR_CANNOT_DELETE => 'can not delete',
DB_ERROR_CANNOT_DROP => 'can not drop',
DB_ERROR_CONSTRAINT => 'constraint violation',
DB_ERROR_DIVZERO => 'division by zero',
DB_ERROR_INVALID => 'invalid',
DB_ERROR_INVALID_DATE => 'invalid date or time',
DB_ERROR_INVALID_NUMBER => 'invalid number',
DB_ERROR_MISMATCH => 'mismatch',
DB_ERROR_NODBSELECTED => 'no database selected',
DB_ERROR_NOSUCHFIELD => 'no such field',
DB_ERROR_NOSUCHTABLE => 'no such table',
DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
DB_ERROR_NOT_FOUND => 'not found',
DB_ERROR_NOT_LOCKED => 'not locked',
DB_ERROR_SYNTAX => 'syntax error',
DB_ERROR_UNSUPPORTED => 'not supported',
DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
DB_ERROR_INVALID_DSN => 'invalid DSN',
DB_ERROR_CONNECT_FAILED => 'connect failed',
DB_OK => 'no error',
DB_WARNING => 'unknown warning',
DB_WARNING_READ_ONLY => 'read only',
DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
DB_ERROR_NOSUCHDB => 'no such database',
DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions'
);
}
if (DB::isError($value)) {
$value = $value->getCode();
}
return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[DB_ERROR];
}
/**
* Parse a data source name
*
* A array with the following keys will be returned:
* phptype: Database backend used in PHP (mysql, odbc etc.)
* dbsyntax: Database used with regards to SQL syntax etc.
* protocol: Communication protocol to use (tcp, unix etc.)
* hostspec: Host specification (hostname[:port])
* database: Database to use on the DBMS server
* username: User name for login
* password: Password for login
*
* The format of the supplied DSN is in its fullest form:
*
* phptype(dbsyntax)://username:password@protocol+hostspec/database
*
* Most variations are allowed:
*
* phptype://username:password@protocol+hostspec:110//usr/db_file.db
* phptype://username:password@hostspec/database_name
* phptype://username:password@hostspec
* phptype://username@hostspec
* phptype://hostspec/database
* phptype://hostspec
* phptype(dbsyntax)
* phptype
*
* @param string $dsn Data Source Name to be parsed
*
* @return array an associative array
*
* @author Tomas V.V.Cox <cox@idecnet.com>
*/
function parseDSN($dsn)
{
if (is_array($dsn)) {
return $dsn;
}
$parsed = array(
'phptype' => false,
'dbsyntax' => false,
'username' => false,
'password' => false,
'protocol' => false,
'hostspec' => false,
'port' => false,
'socket' => false,
'database' => false
);
// Find phptype and dbsyntax
if (($pos = strpos($dsn, '://')) !== false) {
$str = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 3);
} else {
$str = $dsn;
$dsn = NULL;
}
// Get phptype and dbsyntax
// $str => phptype(dbsyntax)
if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
$parsed['phptype'] = $arr[1];
$parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
} else {
$parsed['phptype'] = $str;
$parsed['dbsyntax'] = $str;
}
if (empty($dsn)) {
return $parsed;
}
// Get (if found): username and password
// $dsn => username:password@protocol+hostspec/database
if (($at = strrpos($dsn,'@')) !== false) {
$str = substr($dsn, 0, $at);
$dsn = substr($dsn, $at + 1);
if (($pos = strpos($str, ':')) !== false) {
$parsed['username'] = urldecode(substr($str, 0, $pos));
$parsed['password'] = urldecode(substr($str, $pos + 1));
} else {
$parsed['username'] = urldecode($str);
}
}
// Find protocol and hostspec
// $dsn => proto(proto_opts)/database
if (preg_match('|^(.+?)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
$proto = $match[1];
$proto_opts = (!empty($match[2])) ? $match[2] : false;
$dsn = $match[3];
// $dsn => protocol+hostspec/database (old format)
} else {
if (strpos($dsn, '+') !== false) {
list($proto, $dsn) = explode('+', $dsn, 2);
}
if (strpos($dsn, '/') !== false) {
list($proto_opts, $dsn) = explode('/', $dsn, 2);
} else {
$proto_opts = $dsn;
$dsn = null;
}
}
// process the different protocol options
$parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
$proto_opts = urldecode($proto_opts);
if ($parsed['protocol'] == 'tcp') {
if (strpos($proto_opts, ':') !== false) {
list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
} else {
$parsed['hostspec'] = $proto_opts;
}
} elseif ($parsed['protocol'] == 'unix') {
$parsed['socket'] = $proto_opts;
}
// Get dabase if any
// $dsn => database
if (!empty($dsn)) {
// /database
if (($pos = strpos($dsn, '?')) === false) {
$parsed['database'] = $dsn;
// /database?param1=value1&param2=value2
} else {
$parsed['database'] = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 1);
if (strpos($dsn, '&') !== false) {
$opts = explode('&', $dsn);
} else { // database?param1=value1
$opts = array($dsn);
}
foreach ($opts as $opt) {
list($key, $value) = explode('=', $opt);
if (!isset($parsed[$key])) { // don't allow params overwrite
$parsed[$key] = urldecode($value);
}
}
}
}
return $parsed;
}
/**
* Load a PHP database extension if it is not loaded already.
*
* @access public
*
* @param string $name the base name of the extension (without the .so or
* .dll suffix)
*
* @return boolean true if the extension was already or successfully
* loaded, false if it could not be loaded
*/
function assertExtension($name)
{
if (!extension_loaded($name)) {
$dlext = OS_WINDOWS ? '.dll' : '.so';
@dl($name . $dlext);
}
return extension_loaded($name);
}
}
/**
* DB_Error implements a class for reporting portable database error
* messages.
*
* @package DB
* @author Stig Bakken <ssb@fast.no>
*/
class DB_Error extends PEAR_Error
{
/**
* DB_Error constructor.
*
* @param mixed $code DB error code, or string with error message.
* @param integer $mode what "error mode" to operate in
* @param integer $level what error level to use for $mode & PEAR_ERROR_TRIGGER
* @param smixed $debuginfo additional debug info, such as the last query
*
* @access public
*
* @see PEAR_Error
*/
function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
$level = E_USER_NOTICE, $debuginfo = null)
{
if (is_int($code)) {
$this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo);
} else {
$this->PEAR_Error("DB Error: $code", DB_ERROR, $mode, $level, $debuginfo);
}
}
}
/**
* DB_Warning implements a class for reporting portable database
* warning messages.
*
* @package DB
* @author Stig Bakken <ssb@fast.no>
*/
class DB_Warning extends PEAR_Error
{
/**
* DB_Warning constructor.
*
* @param mixed $code DB error code, or string with error message.
* @param integer $mode what "error mode" to operate in
* @param integer $level what error level to use for $mode == PEAR_ERROR_TRIGGER
* @param mmixed $debuginfo additional debug info, such as the last query
*
* @access public
*
* @see PEAR_Error
*/
function DB_Warning($code = DB_WARNING, $mode = PEAR_ERROR_RETURN,
$level = E_USER_NOTICE, $debuginfo = null)
{
if (is_int($code)) {
$this->PEAR_Error('DB Warning: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo);
} else {
$this->PEAR_Error("DB Warning: $code", 0, $mode, $level, $debuginfo);
}
}
}
/**
* This class implements a wrapper for a DB result set.
* A new instance of this class will be returned by the DB implementation
* after processing a query that returns data.
*
* @package DB
* @author Stig Bakken <ssb@fast.no>
*/
class DB_result
{
var $dbh;
var $result;
var $row_counter = null;
/**
* for limit queries, the row to start fetching
* @var integer
*/
var $limit_from = null;
/**
* for limit queries, the number of rows to fetch
* @var integer
*/
var $limit_count = null;
/**
* DB_result constructor.
* @param resource $dbh DB object reference
* @param resource $result result resource id
*/
function DB_result(&$dbh, $result)
{
$this->dbh = &$dbh;
$this->result = $result;
}
/**
* Fetch and return a row of data (it uses driver->fetchInto for that)
* @param int $fetchmode format of fetched row
* @param int $rownum the row number to fetch
*
* @return array a row of data, NULL on no more rows or PEAR_Error on error
*
* @access public
*/
function fetch_assoc($fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
{
if ($fetchmode === DB_FETCHMODE_DEFAULT) {
$fetchmode = $this->dbh->fetchmode;
}
if ($fetchmode === DB_FETCHMODE_OBJECT) {
$fetchmode = DB_FETCHMODE_ASSOC;
$object_class = $this->dbh->fetchmode_object_class;
}
if ($this->limit_from !== null) {
if ($this->row_counter === null) {
$this->row_counter = $this->limit_from;
// For Interbase
if ($this->dbh->features['limit'] == false) {
$i = 0;
while ($i++ < $this->limit_from) {
$this->dbh->fetchInto($this->result, $arr, $fetchmode);
}
}
}
if ($this->row_counter >= (
$this->limit_from + $this->limit_count))
{
return null;
}
if ($this->dbh->features['limit'] == 'emulate') {
$rownum = $this->row_counter;
}
$this->row_counter++;
}
$res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
if ($res !== DB_OK) {
return $res;
}
if (isset($object_class)) {
// default mode specified in DB_common::fetchmode_object_class property
if ($object_class == 'stdClass') {
$ret = (object) $arr;
} else {
$ret =& new $object_class($arr);
}
return $ret;
}
return $arr;
}
/**
* Fetch a row of data into an existing variable.
*
* @param mixed $arr reference to data containing the row
* @param integer $fetchmode format of fetched row
* @param integer $rownum the row number to fetch
*
* @return mixed DB_OK on success, NULL on no more rows or
* a DB_Error object on error
*
* @access public
*/
function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
{
if ($fetchmode === DB_FETCHMODE_DEFAULT) {
$fetchmode = $this->dbh->fetchmode;
}
if ($fetchmode === DB_FETCHMODE_OBJECT) {
$fetchmode = DB_FETCHMODE_ASSOC;
$object_class = $this->dbh->fetchmode_object_class;
}
if ($this->limit_from !== null) {
if ($this->row_counter === null) {
$this->row_counter = $this->limit_from;
// For Interbase
if ($this->dbh->features['limit'] == false) {
$i = 0;
while ($i++ < $this->limit_from) {
$this->dbh->fetchInto($this->result, $arr, $fetchmode);
}
}
}
if ($this->row_counter >= (
$this->limit_from + $this->limit_count))
{
return null;
}
if ($this->dbh->features['limit'] == 'emulate') {
$rownum = $this->row_counter;
}
$this->row_counter++;
}
$res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
if (($res === DB_OK) && isset($object_class)) {
// default mode specified in DB_common::fetchmode_object_class property
if ($object_class == 'stdClass') {
$arr = (object) $arr;
} else {
$arr = new $object_class($arr);
}
}
return $res;
}
/**
* Get the the number of columns in a result set.
*
* @return int the number of columns, or a DB error
*
* @access public
*/
function numCols()
{
return $this->dbh->numCols($this->result);
}
/**
* Get the number of rows in a result set.
*
* @return int the number of rows, or a DB error
*
* @access public
*/
function numRows()
{
return $this->dbh->numRows($this->result);
}
/**
* Get the next result if a batch of queries was executed.
*
* @return bool true if a new result is available or false if not.
*
* @access public
*/
function nextResult()
{
return $this->dbh->nextResult($this->result);
}
/**
* Frees the resources allocated for this result set.
* @return int error code
*
* @access public
*/
function free()
{
$err = $this->dbh->freeResult($this->result);
if(DB::isError($err)) {
return $err;
}
$this->result = false;
return true;
}
/**
* @deprecated
*/
function tableInfo($mode = null)
{
return $this->dbh->tableInfo($this->result, $mode);
}
/**
* returns the actual rows number
* @return integer
*/
function getRowCounter()
{
return $this->row_counter;
}
}
/**
* Pear DB Row Object
* @see DB_common::setFetchMode()
*/
class DB_row
{
/**
* constructor
*
* @param resource row data as array
*/
function DB_row(&$arr)
{
for (reset($arr); $key = key($arr); next($arr)) {
$this->$key = &$arr[$key];
}
}
}
?>

View File

@@ -0,0 +1,8 @@
You must modify the file config.php, change the following line to point to the /html/ folder with a real path
Vous devez modifier le fichier config.php, changez la ligne suivante pour qu'elle redirige vers le dossier /class/ avec le chemin complet
$class_dir = '../class';
change it for / changez le pour
$class_dir = 'C:/where/barcode_gen/is_installed/class';
Start with code39.php and you will be able to make barcodes
Commencez avec code39.php et vous serez capable de faire des codes barres

View File

@@ -0,0 +1,793 @@
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Sterling Hughes <sterling@php.net> |
// | Stig Bakken <ssb@fast.no> |
// | Tomas V.V.Cox <cox@idecnet.com> |
// +----------------------------------------------------------------------+
//
// $Id: PEAR.php,v 1.32.2.2 2002/04/09 19:04:07 ssb Exp $
//
define('PEAR_ERROR_RETURN', 1);
define('PEAR_ERROR_PRINT', 2);
define('PEAR_ERROR_TRIGGER', 4);
define('PEAR_ERROR_DIE', 8);
define('PEAR_ERROR_CALLBACK', 16);
if (substr(PHP_OS, 0, 3) == 'WIN') {
define('OS_WINDOWS', true);
define('OS_UNIX', false);
define('PEAR_OS', 'Windows');
} else {
define('OS_WINDOWS', false);
define('OS_UNIX', true);
define('PEAR_OS', 'Unix'); // blatant assumption
}
$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN;
$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE;
$GLOBALS['_PEAR_default_error_callback'] = '';
$GLOBALS['_PEAR_destructor_object_list'] = array();
//
// Tests needed: - PEAR inheritance
//
/**
* Base class for other PEAR classes. Provides rudimentary
* emulation of destructors.
*
* If you want a destructor in your class, inherit PEAR and make a
* destructor method called _yourclassname (same name as the
* constructor, but with a "_" prefix). Also, in your constructor you
* have to call the PEAR constructor: $this->PEAR();.
* The destructor method will be called without parameters. Note that
* at in some SAPI implementations (such as Apache), any output during
* the request shutdown (in which destructors are called) seems to be
* discarded. If you need to get any debug information from your
* destructor, use error_log(), syslog() or something similar.
*
* @since PHP 4.0.2
* @author Stig Bakken <ssb@fast.no>
*/
class PEAR
{
// {{{ properties
/**
* Whether to enable internal debug messages.
*
* @var bool
* @access private
*/
var $_debug = false;
/**
* Default error mode for this object.
*
* @var int
* @access private
*/
var $_default_error_mode = null;
/**
* Default error options used for this object when error mode
* is PEAR_ERROR_TRIGGER.
*
* @var int
* @access private
*/
var $_default_error_options = null;
/**
* Default error handler (callback) for this object, if error mode is
* PEAR_ERROR_CALLBACK.
*
* @var string
* @access private
*/
var $_default_error_handler = '';
/**
* Which class to use for error objects.
*
* @var string
* @access private
*/
var $_error_class = 'PEAR_Error';
/**
* An array of expected errors.
*
* @var array
* @access private
*/
var $_expected_errors = array();
// }}}
// {{{ constructor
/**
* Constructor. Registers this object in
* $_PEAR_destructor_object_list for destructor emulation if a
* destructor object exists.
*
* @param string (optional) which class to use for error objects,
* defaults to PEAR_Error.
* @access public
* @return void
*/
function PEAR($error_class = null)
{
$classname = get_class($this);
if ($this->_debug) {
print "PEAR constructor called, class=$classname\n";
}
if ($error_class !== null) {
$this->_error_class = $error_class;
}
while ($classname) {
$destructor = "_$classname";
if (method_exists($this, $destructor)) {
global $_PEAR_destructor_object_list;
$_PEAR_destructor_object_list[] = &$this;
break;
} else {
$classname = get_parent_class($classname);
}
}
}
// }}}
// {{{ destructor
/**
* Destructor (the emulated type of...). Does nothing right now,
* but is included for forward compatibility, so subclass
* destructors should always call it.
*
* See the note in the class desciption about output from
* destructors.
*
* @access public
* @return void
*/
function _PEAR() {
if ($this->_debug) {
printf("PEAR destructor called, class=%s\n", get_class($this));
}
}
// }}}
// {{{ isError()
/**
* Tell whether a value is a PEAR error.
*
* @param mixed the value to test
* @access public
* @return bool true if parameter is an error
*/
function isError($data) {
return (bool)(is_object($data) &&
(get_class($data) == 'pear_error' ||
is_subclass_of($data, 'pear_error')));
}
// }}}
// {{{ setErrorHandling()
/**
* Sets how errors generated by this DB object should be handled.
* Can be invoked both in objects and statically. If called
* statically, setErrorHandling sets the default behaviour for all
* PEAR objects. If called in an object, setErrorHandling sets
* the default behaviour for that object.
*
* @param int $mode
* One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
* PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE or
* PEAR_ERROR_CALLBACK.
*
* @param mixed $options
* When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
* of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
*
* When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
* to be the callback function or method. A callback
* function is a string with the name of the function, a
* callback method is an array of two elements: the element
* at index 0 is the object, and the element at index 1 is
* the name of the method to call in the object.
*
* When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
* a printf format string used when printing the error
* message.
*
* @access public
* @return void
* @see PEAR_ERROR_RETURN
* @see PEAR_ERROR_PRINT
* @see PEAR_ERROR_TRIGGER
* @see PEAR_ERROR_DIE
* @see PEAR_ERROR_CALLBACK
*
* @since PHP 4.0.5
*/
function setErrorHandling($mode = null, $options = null)
{
if (isset($this)) {
$setmode = &$this->_default_error_mode;
$setoptions = &$this->_default_error_options;
//$setcallback = &$this->_default_error_callback;
} else {
$setmode = &$GLOBALS['_PEAR_default_error_mode'];
$setoptions = &$GLOBALS['_PEAR_default_error_options'];
//$setcallback = &$GLOBALS['_PEAR_default_error_callback'];
}
switch ($mode) {
case PEAR_ERROR_RETURN:
case PEAR_ERROR_PRINT:
case PEAR_ERROR_TRIGGER:
case PEAR_ERROR_DIE:
case null:
$setmode = $mode;
$setoptions = $options;
break;
case PEAR_ERROR_CALLBACK:
$setmode = $mode;
if ((is_string($options) && function_exists($options)) ||
(is_array($options) && method_exists(@$options[0], @$options[1])))
{
$setoptions = $options;
} else {
trigger_error("invalid error callback", E_USER_WARNING);
}
break;
default:
trigger_error("invalid error mode", E_USER_WARNING);
break;
}
}
// }}}
// {{{ expectError()
/**
* This method is used to tell which errors you expect to get.
* Expected errors are always returned with error mode
* PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
* and this method pushes a new element onto it. The list of
* expected errors are in effect until they are popped off the
* stack with the popExpect() method.
*
* @param mixed a single error code or an array of error codes
* to expect
*
* @return int the new depth of the "expected errors" stack
*/
function expectError($code = "*")
{
if (is_array($code)) {
array_push($this->_expected_errors, $code);
} else {
array_push($this->_expected_errors, array($code));
}
return sizeof($this->_expected_errors);
}
// }}}
// {{{ popExpect()
/**
* This method pops one element off the expected error codes
* stack.
*
* @return array the list of error codes that were popped
*/
function popExpect()
{
return array_pop($this->_expected_errors);
}
// }}}
// {{{ raiseError()
/**
* This method is a wrapper that returns an instance of the
* configured error class with this object's default error
* handling applied. If the $mode and $options parameters are not
* specified, the object's defaults are used.
*
* @param $message a text error message or a PEAR error object
*
* @param $code a numeric error code (it is up to your class
* to define these if you want to use codes)
*
* @param $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
* PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE or
* PEAR_ERROR_CALLBACK.
*
* @param $options If $mode is PEAR_ERROR_TRIGGER, this parameter
* specifies the PHP-internal error level (one of
* E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
* If $mode is PEAR_ERROR_CALLBACK, this
* parameter specifies the callback function or
* method. In other error modes this parameter
* is ignored.
*
* @param $userinfo If you need to pass along for example debug
* information, this parameter is meant for that.
*
* @param $error_class The returned error object will be instantiated
* from this class, if specified.
*
* @param $skipmsg If true, raiseError will only pass error codes,
* the error message parameter will be dropped.
*
* @access public
* @return object a PEAR error object
* @see PEAR::setErrorHandling
* @since PHP 4.0.5
*/
function &raiseError($message = null,
$code = null,
$mode = null,
$options = null,
$userinfo = null,
$error_class = null,
$skipmsg = false)
{
// The error is yet a PEAR error object
if (is_object($message)) {
$code = $message->getCode();
$userinfo = $message->getUserInfo();
$error_class = $message->getType();
$message = $message->getMessage();
}
if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) {
if ($exp[0] == "*" ||
(is_int(reset($exp)) && in_array($code, $exp)) ||
(is_string(reset($exp)) && in_array($message, $exp))) {
$mode = PEAR_ERROR_RETURN;
}
}
if ($mode === null) {
if (isset($this) && isset($this->_default_error_mode)) {
$mode = $this->_default_error_mode;
} else {
$mode = $GLOBALS['_PEAR_default_error_mode'];
}
}
if ($mode == PEAR_ERROR_TRIGGER && $options === null) {
if (isset($this)) {
if (isset($this->_default_error_options)) {
$options = $this->_default_error_options;
}
} else {
$options = $GLOBALS['_PEAR_default_error_options'];
}
}
if ($mode == PEAR_ERROR_CALLBACK) {
if (!is_string($options) &&
!(is_array($options) && sizeof($options) == 2 &&
is_object($options[0]) && is_string($options[1])))
{
if (isset($this) && isset($this->_default_error_options)) {
$options = $this->_default_error_options;
} else {
$options = $GLOBALS['_PEAR_default_error_options'];
}
}
} else {
if ($options === null) {
if (isset($this)) {
if (isset($this->_default_error_options)) {
$options = $this->_default_error_options;
}
} else {
$options = $GLOBALS['_PEAR_default_error_options'];
}
}
}
if ($error_class !== null) {
$ec = $error_class;
} elseif (isset($this) && isset($this->_error_class)) {
$ec = $this->_error_class;
} else {
$ec = 'PEAR_Error';
}
if ($skipmsg) {
return new $ec($code, $mode, $options, $userinfo);
} else {
return new $ec($message, $code, $mode, $options, $userinfo);
}
}
// }}}
// {{{ pushErrorHandling()
/**
* Push a new error handler on top of the error handler options stack. With this
* you can easily override the actual error handler for some code and restore
* it later with popErrorHandling.
*
* @param $mode mixed (same as setErrorHandling)
* @param $options mixed (same as setErrorHandling)
*
* @return bool Always true
*
* @see PEAR::setErrorHandling
*/
function pushErrorHandling($mode, $options = null)
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
if (!is_array($stack)) {
if (isset($this)) {
$def_mode = &$this->_default_error_mode;
$def_options = &$this->_default_error_options;
// XXX Used anywhere?
//$def_callback = &$this->_default_error_callback;
} else {
$def_mode = &$GLOBALS['_PEAR_default_error_mode'];
$def_options = &$GLOBALS['_PEAR_default_error_options'];
// XXX Used anywhere?
//$def_callback = &$GLOBALS['_PEAR_default_error_callback'];
}
$stack = array();
$stack[] = array($def_mode, $def_options);
}
if (isset($this)) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
}
$stack[] = array($mode, $options);
return true;
}
// }}}
// {{{ popErrorHandling()
/**
* Pop the last error handler used
*
* @return bool Always true
*
* @see PEAR::pushErrorHandling
*/
function popErrorHandling()
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
array_pop($stack);
list($mode, $options) = $stack[sizeof($stack) - 1];
if (isset($this)) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
}
return true;
}
// }}}
}
// {{{ _PEAR_call_destructors()
function _PEAR_call_destructors()
{
global $_PEAR_destructor_object_list;
if (is_array($_PEAR_destructor_object_list) &&
sizeof($_PEAR_destructor_object_list))
{
reset($_PEAR_destructor_object_list);
while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
$classname = get_class($objref);
while ($classname) {
$destructor = "_$classname";
if (method_exists($objref, $destructor)) {
$objref->$destructor();
break;
} else {
$classname = get_parent_class($classname);
}
}
}
// Empty the object list to ensure that destructors are
// not called more than once.
$_PEAR_destructor_object_list = array();
}
}
// }}}
class PEAR_Error
{
// {{{ properties
var $error_message_prefix = '';
var $mode = PEAR_ERROR_RETURN;
var $level = E_USER_NOTICE;
var $code = -1;
var $message = '';
var $userinfo = '';
// Wait until we have a stack-groping function in PHP.
//var $file = '';
//var $line = 0;
// }}}
// {{{ constructor
/**
* PEAR_Error constructor
*
* @param $message error message
*
* @param $code (optional) error code
*
* @param $mode (optional) error mode, one of: PEAR_ERROR_RETURN,
* PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER or
* PEAR_ERROR_CALLBACK
*
* @param $level (optional) error level, _OR_ in the case of
* PEAR_ERROR_CALLBACK, the callback function or object/method
* tuple.
*
* @access public
*
*/
function PEAR_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
if ($mode === null) {
$mode = PEAR_ERROR_RETURN;
}
$this->message = $message;
$this->code = $code;
$this->mode = $mode;
$this->userinfo = $userinfo;
if ($mode & PEAR_ERROR_CALLBACK) {
$this->level = E_USER_NOTICE;
$this->callback = $options;
} else {
if ($options === null) {
$options = E_USER_NOTICE;
}
$this->level = $options;
$this->callback = null;
}
if ($this->mode & PEAR_ERROR_PRINT) {
if (is_null($options) || is_int($options)) {
$format = "%s";
} else {
$format = $options;
}
printf($format, $this->getMessage());
}
if ($this->mode & PEAR_ERROR_TRIGGER) {
trigger_error($this->getMessage(), $this->level);
}
if ($this->mode & PEAR_ERROR_DIE) {
$msg = $this->getMessage();
if (is_null($options) || is_int($options)) {
$format = "%s";
if (substr($msg, -1) != "\n") {
$msg .= "\n";
}
} else {
$format = $options;
}
die(sprintf($format, $msg));
}
if ($this->mode & PEAR_ERROR_CALLBACK) {
if (is_string($this->callback) && strlen($this->callback)) {
call_user_func($this->callback, $this);
} elseif (is_array($this->callback) &&
sizeof($this->callback) == 2 &&
is_object($this->callback[0]) &&
is_string($this->callback[1]) &&
strlen($this->callback[1])) {
@call_user_method($this->callback[1], $this->callback[0],
$this);
}
}
}
// }}}
// {{{ getMode()
/**
* Get the error mode from an error object.
*
* @return int error mode
* @access public
*/
function getMode() {
return $this->mode;
}
// }}}
// {{{ getCallback()
/**
* Get the callback function/method from an error object.
*
* @return mixed callback function or object/method array
* @access public
*/
function getCallback() {
return $this->callback;
}
// }}}
// {{{ getMessage()
/**
* Get the error message from an error object.
*
* @return string full error message
* @access public
*/
function getMessage ()
{
return ($this->error_message_prefix . $this->message);
}
// }}}
// {{{ getCode()
/**
* Get error code from an error object
*
* @return int error code
* @access public
*/
function getCode()
{
return $this->code;
}
// }}}
// {{{ getType()
/**
* Get the name of this error/exception.
*
* @return string error/exception name (type)
* @access public
*/
function getType ()
{
return get_class($this);
}
// }}}
// {{{ getUserInfo()
/**
* Get additional user-supplied information.
*
* @return string user-supplied information
* @access public
*/
function getUserInfo ()
{
return $this->userinfo;
}
// }}}
// {{{ getDebugInfo()
/**
* Get additional debug information supplied by the application.
*
* @return string debug information
* @access public
*/
function getDebugInfo ()
{
return $this->getUserInfo();
}
// }}}
// {{{ addUserInfo()
function addUserInfo($info)
{
if (empty($this->userinfo)) {
$this->userinfo = $info;
} else {
$this->userinfo .= " ** $info";
}
}
// }}}
// {{{ toString()
/**
* Make a string representation of this object.
*
* @return string a string with an object summary
* @access public
*/
function toString() {
$modes = array();
$levels = array(E_USER_NOTICE => 'notice',
E_USER_WARNING => 'warning',
E_USER_ERROR => 'error');
if ($this->mode & PEAR_ERROR_CALLBACK) {
if (is_array($this->callback)) {
$callback = get_class($this->callback[0]) . '::' .
$this->callback[1];
} else {
$callback = $this->callback;
}
return sprintf('[%s: message="%s" code=%d mode=callback '.
'callback=%s prefix="%s" info="%s"]',
get_class($this), $this->message, $this->code,
$callback, $this->error_message_prefix,
$this->userinfo);
}
if ($this->mode & PEAR_ERROR_CALLBACK) {
$modes[] = 'callback';
}
if ($this->mode & PEAR_ERROR_PRINT) {
$modes[] = 'print';
}
if ($this->mode & PEAR_ERROR_TRIGGER) {
$modes[] = 'trigger';
}
if ($this->mode & PEAR_ERROR_DIE) {
$modes[] = 'die';
}
if ($this->mode & PEAR_ERROR_RETURN) {
$modes[] = 'return';
}
return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
'prefix="%s" info="%s"]',
get_class($this), $this->message, $this->code,
implode("|", $modes), $levels[$this->level],
$this->error_message_prefix,
$this->userinfo);
}
// }}}
}
register_shutdown_function("_PEAR_call_destructors");
/*
* Local Variables:
* mode: php
* tab-width: 4
* c-basic-offset: 4
* End:
*/
?>

View File

@@ -0,0 +1,12 @@
This script is free for personal use. The program is provide "AS IS"
without warranty of any kind. If you want to use it as
commercial use, you have to purchase it on
http://www.barcodephp.com
You must let the copyright intact.
Ce script est gratuit pour usage personnel. Le programme est
fourni "TEL QUEL" sans aucune garantie que ce soit.
Si vous voulez l'utiliser pour un usage commercial,
vous devez l'acheter sur
http://www.barcodephp.com
Vous devez laisser le copyright intact.

View File

@@ -0,0 +1,72 @@
v2.2.0 13 feb 2010 Added the support for GS1-128 (EAN-128).
Fix ISBN text support to be the right font.
Make sure the /html files are formatted.
v2.1.0 8 nov 2009 Added a way to change the DPI before saving (BCGDrawing::setDPI()). Set the value to null if you want to improve the performance and still have 72dpi.
But you can set it to 300 if you wish to print it.
You do not need an additional DLL for this.
Added a way to rotate in degree the barcode before saving (BCGDrawing::setRotationAngle()).
Added a verification if you have GD installed... So that way you know it before contacting support :)
Fix HTML display for Code 93 and Code 39 Extended buttons
You can now specify a specific table for Code 128. For instance, if you want to force to use the table B, you would write the following to parse
array(CODE128_B, 'The Text To Encode')
The default table selection for Code 128 is automatically chosen.
Fix many PHP4 errors.
v2.0.1Fix 28 jul 2009 Change UPC-E encoding from UTF-8 to ANSI
v2.0.1 21 may 2009 Fix the Code 128C, Fix EAN-8, EAN-13, UPC-A, UPC-E and Postnet padding, MSI checksum can be 1 or 2
Fix JoinDraw class
Added GIF and WBMP support
Fix the Checksum Text displayed for ISBN
Fix padding for ISBN with setOffsetY
Fix Button in /html for IE8
v2.0.0 23 apr 2008 The new version has been released... All the codes have been revamped to fit with
common file for 2D barcodes. Instead of using "setText()" method, the method
parse() is used.
Thickness is modified by the scale.
Code 128: it has been modified completely, no need to specify which encoding you want to
use, it will select it for you automatically and try to get the shortest barcode.
Codabar: you can't only put one letter as a barcode.
Code 93: supports now the extended full ASCII 0 to 127
Code 39 extended has been added in a separate file since the extended
version of Code 39 is totally optional.
Codabar has been fixed for B and C letter
We got our real nice domain: http://www.barcodephp.com
v1.3.0 13 apr 2007 Remove ISBN from EAN-13 and a new file has been created to handle
ISBN-10 and ISBN-13.
v1.2.4 1 feb 2007 Fix Code128. There were some errors dealing with C table
v1.2.3pl1 11 mar 2006 Correct the EAN-13/ISBN file. There was a problem with displaying correctly an ISBN.
v1.2.3 8 feb 2006 Int for font is no longer deprecated and can be used.
Correct many labels' positions : ean8, ean13, upca, upce
Correct getWidth of Font.
v1.2.3b 5 jan 2006 Add separate checksum method to calculate and get this special number created and a way to display it with the label.
Correct code for PHP5.1 compatibility. Selecting a char by { } is now deprecated. Using of [ ] is used instead.
Correct checksum for Code11. In some case, the checksum was bad.
Correct problem displaying label with text under the baseline (letters such as p, g...).
SIZE_SPACING_FONT_END has been suppressed since the previous bug has been fixed.
Correct label if two barcode were generated with the same font. The font is now cloned immediately before using.
The FDrawing has new methods now, use setBarcode and draw instead of add_barcode and draw_all. Only one barcode per FDrawing is possible now.
Correct errors of othercode if no text font has been selected.
othercode was not working for PHP4 due to the lack of the str_split function. Now the function is emulated.
New file : JoinDraw allows you to join 2 graphic and align each of them. (Useful for UCPExt). PHP5 only
Currently Working on UPC-A label
v1.2.2 23 jul 2005 Correct checksum for i25 and s25 barcode (thanks to Gerald Pienkowski (Germany))
Enhance rapidity for some barcode
Change almost all comment in files : the update 1.2.1 was in 2005, not in 2004 ;)
v1.2.1 27 jun 2005 The php code is now cleaner :)
Increase rapidity of execution
Type verifications in conditions
NEW support of exterior font (Arial, Courier, etc.) with a size that you can specify
Use PHP fonts is deprecated and they will be deleted in further versions.
Remove the "alt" text on the image (IE displays it as a tooltip)
Color class has been enhanced and accept new parameter for constructor
Now you don't have to provide a specific size of the image, it will be calculated automatically for barcodes and errors
Added the version number at the bottom of the script html.
Correcting code 128 to output code correctly when passing from code C to another code
v1.05 27 jun 2005 UPCext2 has been corrected. It could display a wrong barcode.
Correcting UPC-A, bad output when writting text
v1.04 2 apr 2005 Correcting some bugs and makes available for commercial usage : purchase it on http://www.barcodephp.com
v1.03 28 mar 2005 Correcting DrawChar
v1.02 8 mar 2005 Transforming PHPDOC and converting to XHTML1.0 Transitionnal
And adding a special option that check if you have PHP5 installed
Because to many people are writing to me that saying the script doesn't work (because they have PHP4).
v1.01 7 jul 2004 Correcting code39.barcode.php
v1.00 17 jun 2004 New :)

View File

@@ -0,0 +1,218 @@
<?php
/**
* BCGBarcode.php
*--------------------------------------------------------------------
*
* Base class for Barcode 1D and 2D
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
*--------------------------------------------------------------------
* $Id: BCGBarcode.php,v 1.12 2010/02/14 00:25:14 jsgoupil Exp $
* PHP5-Revision: 1.13
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGColor.php');
class BCGBarcode { // abstract
var $COLOR_BG = 0; // const
var $COLOR_FG = 1; // const
var $error; // protected
var $colorFg, $colorBg; // Color Foreground, Barckground
var $scale; // Scale of the graphic, default: 1
var $offsetX, $offsetY; // Position where to start the drawing
function BCGBarcode() { // protected
$this->setForegroundColor(0x000000);
$this->setBackgroundColor(0xffffff);
$this->setScale(1);
$this->setOffsetX(0);
$this->setOffsetY(0);
$this->error = 0;
}
/**
* Parses the text before displaying it.
*
* @param mixed $text
*/
function parse($text) {} // public abstract
/**
* Sets the foreground color of the barcode. It could be a BCGColor
* value or simply a language code (white, black, yellow...) or hex value.
*
* @param mixed $code
*/
function setForegroundColor($code) {
if(is_a($code, 'BCGColor')) {
$this->colorFg =& $code;
} else {
$this->colorFg =& new BCGColor($code);
}
}
/**
* Sets the background color of the barcode. It could be a BCGColor
* value or simply a language code (white, black, yellow...) or hex value.
*
* @param mixed $code
*/
function setBackgroundColor($code) {
if(is_a($code, 'BCGColor')) {
$this->colorBg =& $code;
} else {
$this->colorBg =& new BCGColor($code);
}
}
/**
* Sets the color
*
* @param mixed $fg
* @param mixed $bg
*/
function setColor($fg, $bg) {
$this->setForegroundColor($fg);
$this->setBackgroundColor($bg);
}
function getScale() {
return $this->scale;
}
function setScale($scale) {
$scale = intval($scale);
if($scale <= 0) {
$scale = 1;
}
$this->scale = $scale;
}
function draw(&$im) {} // public abstract
/**
* Returns the maximal size of a barcode.
* [0]->width
* [1]->height
*
* @return int[]
*/
function getMaxSize() {
return array($this->offsetX * $this->scale, $this->offsetY * $this->scale);
}
/**
* Sets the X offset
*
* @param int $offsetX
*/
function setOffsetX($offsetX) {
$offsetX = intval($offsetX);
if($offsetX < 0) {
$offsetX = 0;
}
$this->offsetX = $offsetX;
}
/**
* Sets the Y offset
*
* @param int $offsetY
*/
function setOffsetY($offsetY) {
$offsetY = intval($offsetY);
if($offsetY < 0) {
$offsetY = 0;
}
$this->offsetY = $offsetY;
}
function drawPixel(&$im, $x, $y, $color = 1) { // protected
$xR = ($x + $this->offsetX) * $this->scale;
$yR = ($y + $this->offsetY) * $this->scale;
// we always draw a rectangle
imagefilledrectangle($im,
$xR,
$yR,
$xR + $this->scale - 1,
$yR + $this->scale - 1,
$this->getColor($im, $color));
}
function drawRectangle(&$im, $x1, $y1, $x2, $y2, $color = 1) { // protected
if($this->scale === 1) {
imagerectangle($im,
($x1 + $this->offsetX) * $this->scale,
($y1 + $this->offsetY) * $this->scale,
($x2 + $this->offsetX) * $this->scale,
($y2 + $this->offsetY) * $this->scale,
$this->getColor($im, $color));
} else {
imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale, ($y1 + $this->offsetY) * $this->scale, ($x2 + $this->offsetX) * $this->scale + $this->scale - 1, ($y1 + $this->offsetY) * $this->scale + $this->scale - 1, $this->getColor($im, $color));
imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale, ($y1 + $this->offsetY) * $this->scale, ($x1 + $this->offsetX) * $this->scale + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->scale - 1, $this->getColor($im, $color));
imagefilledrectangle($im, ($x2 + $this->offsetX) * $this->scale, ($y1 + $this->offsetY) * $this->scale, ($x2 + $this->offsetX) * $this->scale + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->scale - 1, $this->getColor($im, $color));
imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale, ($y2 + $this->offsetY) * $this->scale, ($x2 + $this->offsetX) * $this->scale + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->scale - 1, $this->getColor($im, $color));
}
}
function drawFilledRectangle(&$im, $x1, $y1, $x2, $y2, $color = 1) { // protected
if($x1 > $x2) { // Swap
$x1 ^= $x2 ^= $x1 ^= $x2;
}
if($y1 > $y2) { // Swap
$y1 ^= $y2 ^= $y1 ^= $y2;
}
imagefilledrectangle($im,
($x1 + $this->offsetX) * $this->scale,
($y1 + $this->offsetY) * $this->scale,
($x2 + $this->offsetX) * $this->scale + $this->scale - 1,
($y2 + $this->offsetY) * $this->scale + $this->scale - 1,
$this->getColor($im, $color));
}
function getColor(&$im, $color) { // protected
if($color === $this->COLOR_BG) {
return $this->colorBg->allocate($im);
} else {
return $this->colorFg->allocate($im);
}
}
/**
* Writes the Error on the picture
*
* @param ressource $img
* @param string $text
*/
function drawError(&$im, $text) { // protected
// Is the image big enough?
$w = imagesx($im);
$h = imagesy($im);
$text = 'Error: ' . $text;
$width = imagefontwidth(2) * strlen($text);
$height = imagefontheight(2) + $this->error * 15;
if($width > $w || $height > $h) {
$width = max($w, $width);
$height = max($h, $height);
// We change the size of the image
$newimg = imagecreatetruecolor($width, $height);
imagefill($newimg, 0, 0, imagecolorat($im, 0, 0));
imagecopy($newimg, $im, 0, 0, 0, 0, $w, $h);
$im = $newimg;
}
imagestring($im, 2, 0, $this->error * 15, $text, $this->colorFg->allocate($im));
$this->error++;
}
}
?>

View File

@@ -0,0 +1,226 @@
<?php
/**
* BCGBarcode1D.php
*--------------------------------------------------------------------
*
* Holds all type of barcodes for 1D generation
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
*--------------------------------------------------------------------
* $Id: BCGBarcode1D.php,v 1.3 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.3
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode.php');
include_once('BCGFont.php');
class BCGBarcode1D extends BCGBarcode { // abstract
var $SIZE_SPACING_FONT = 5; // const
var $AUTO_LABEL = '##!!AUTO_LABEL!!##'; // const
var $thickness;
var $keys, $code;
var $positionX;
var $textfont;
var $text, $label;
var $checksumValue;
var $displayChecksum;
function BCGBarcode1D() { // protected
BCGBarcode::BCGBarcode();
$this->setThickness(30);
$this->text = '';
$this->checksumValue = false;
$this->setLabel($this->AUTO_LABEL);
$this->setFont(5);
}
function setThickness($thickness) { // public
$this->thickness = $thickness;
}
function getThickness() { // public
return $this->thickness;
}
function parse($text) { // public
$this->text = $text;
$this->checksumValue = false; // Reset checksumValue
}
function setLabel($label) { // public
$this->label = $label;
}
function getLabel() { // public
$label = $this->label;
if($this->label === $this->AUTO_LABEL) {
$label = $this->text;
if($this->displayChecksum === true && ($checksum = $this->processChecksum()) !== false) {
$label .= $checksum;
}
}
return $label;
}
/**
* Saves the font.
*
* @param mixed $font BCGFont or int
*/
function setFont($font) { // public
if(is_a($font, 'BCGFont')) {
$this->textfont = $font; // clone
$this->textfont->setText($this->text);
} else {
$this->textfont = min(5, max(0, intval($font)));
}
}
function getMaxSize() { // public
$p = BCGBarcode::getMaxSize();
$label = $this->getLabel();
$textHeight = 0;
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$textfont = $this->textfont; // clone
$textfont->setText($label);
$textHeight = $textfont->getHeight() + $this->SIZE_SPACING_FONT;
} elseif($this->textfont !== 0) {
$textHeight = imagefontheight($this->textfont) + $this->SIZE_SPACING_FONT;
}
}
return array($p[0], $p[1] + $this->thickness * $this->scale + $textHeight);
}
/**
* Gets the checksum of a Barcode.
* If no checksum is available, return FALSE.
*
* @return string
*/
function getChecksum() { // public
return $this->processChecksum();
}
/**
* Sets if the checksum is displayed with the label or not.
* The checksum must be activated in some case to make this variable effective.
*
* @param boolean $display
*/
function setDisplayChecksum($display) { // public
$this->displayChecksum = (bool)$display;
}
/**
* Returns the index in $keys (useful for checksum)
*
* @param mixed $var
* @return mixed
*/
function findIndex($var) { // protected
return array_search($var, $this->keys);
}
/**
* Returns the code of the char (useful for drawing bars)
*
* @param mixed $var
* @return string
*/
function findCode($var) { // protected
return $this->code[$this->findIndex($var)];
}
/**
* Draws all chars thanks to $code. if $start is true, the line begins by a space.
* if $start is false, the line begins by a bar.
*
* @param resource $im
* @param string $code
* @param boolean $start
*/
function drawChar(&$im, $code, $startBar = true) { // protected
$colors = array($this->COLOR_FG, $this->COLOR_BG);
$currentColor = $startBar ? 0 : 1;
$c = strlen($code);
for($i = 0; $i < $c; $i++) {
for($j = 0; $j < intval($code[$i]) + 1; $j++) {
$this->drawSingleBar($im, $colors[$currentColor]);
$this->nextX();
}
$currentColor = ($currentColor + 1) % 2;
}
}
/**
* Draws a Bar of $color depending of the resolution
*
* @param resource $img
* @param FColor $color
*/
function drawSingleBar(&$im, $color) { // protected
$this->drawFilledRectangle($im, $this->positionX, 0, $this->positionX, $this->thickness - 1, $color);
}
/**
* Moving the pointer right to write a bar
*/
function nextX() { // protected
$this->positionX++;
}
/**
* Draws the label under the barcode
*
* @param resource $im
*/
function drawText(&$im) { // protected
$label = $this->getLabel();
if(!empty($label)) {
$pA = $this->getMaxSize();
$pB = BCGBarcode1D::getMaxSize();
$w = $pA[0] - $pB[0];
if(is_a($this->textfont, 'BCGFont')) {
$textfont = $this->textfont; // clone
$textfont->setText($label);
$xPosition = ($w / 2) - ($textfont->getWidth() / 2) + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $textfont->getHeight() - $textfont->getUnderBaseline() + $this->SIZE_SPACING_FONT + $this->offsetY * $this->scale;
$textfont->draw($im, $this->colorFg->allocate($im), $xPosition, $yPosition);
} elseif($this->textfont !== 0) {
$xPosition = ($w / 2) - (strlen($label) / 2) * imagefontwidth($this->textfont) + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->SIZE_SPACING_FONT + $this->offsetY * $this->scale;
imagestring($im, $this->textfont, $xPosition, $yPosition, $label, $this->colorFg->allocate($im));
}
}
}
/**
* Method that saves FALSE into the checksumValue. This means no checksum
* but this method should be overloaded when needed.
*/
function calculateChecksum() { // protected
$this->checksumValue = false;
}
/**
* Returns FALSE because there is no checksum. This method should be
* overloaded to return correctly the checksum in string with checksumValue.
*
* @return string
*/
function processChecksum() { // protected
return false;
}
}

View File

@@ -0,0 +1,147 @@
<?php
/**
* BCGColor.php
*--------------------------------------------------------------------
*
* Holds Color in RGB Format.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil New functionality
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGColor.php,v 1.7 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.6
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
class BCGColor {
var $r, $g, $b; // int Hexadecimal Value
/**
* Save RGB value into the classes
*
* There are 4 way to associate color with this classes :
* 1. Gives 3 parameters int (R, G, B)
* 2. Gives 1 parameter string hex value (#ff0000) (preceding with #)
* 3. Gives 1 parameter int hex value (0xff0000)
* 4. Gives 1 parameter string color code (white, black, orange...)
*
* @param mixed ...
*/
function BCGColor() {
$args = func_get_args();
$c = count($args);
if ($c === 3) {
$this->r = intval($args[0]);
$this->g = intval($args[1]);
$this->b = intval($args[2]);
} elseif ($c === 1) {
if (is_string($args[0]) && strlen($args[0]) === 7 && $args[0]{0} === '#') { // Hex Value in String
$this->r = intval(substr($args[0], 1, 2), 16);
$this->g = intval(substr($args[0], 3, 2), 16);
$this->b = intval(substr($args[0], 5, 2), 16);
} else {
if (is_string($args[0])) {
$args[0] = BCGColor::getColor($args[0]);
}
$args[0] = intval($args[0]);
$this->r = ($args[0] & 0xff0000) >> 16;
$this->g = ($args[0] & 0x00ff00) >> 8;
$this->b = ($args[0] & 0x0000ff);
}
} else {
$this->r = $this->g = $this->b = 0;
}
}
/**
* Returns Red Color
*
* @return int
*/
function r() {
return $this->r;
}
/**
* Returns Green Color
*
* @return int
*/
function g() {
return $this->g;
}
/**
* Returns Blue Color
*
* @return int
*/
function b() {
return $this->b;
}
/**
* Returns the int value for PHP color
*
* @param resource $im
* @return int
*/
function allocate(&$im) {
return imagecolorallocate($im, $this->r, $this->g, $this->b);
}
/**
* Returns class of BCGColor depending of the string color
*
* If the color doens't exist, it takes the default one.
*
* @param string $code
* @param string $default
*/
function getColor($code, $default = 'white') { // static
switch(strtolower($code)) {
case '':
case 'white':
return 0xffffff;
case 'black':
return 0x000000;
case 'maroon':
return 0x800000;
case 'red':
return 0xff0000;
case 'orange':
return 0xffa500;
case 'yellow':
return 0xffff00;
case 'olive':
return 0x808000;
case 'purple':
return 0x800080;
case 'fuchsia':
return 0xff00ff;
case 'lime':
return 0x00ff00;
case 'green':
return 0x008000;
case 'navy':
return 0x000080;
case 'blue':
return 0x0000ff;
case 'aqua':
return 0x00ffff;
case 'teal':
return 0x008080;
case 'silver':
return 0xc0c0c0;
case 'gray':
return 0x808080;
default:
return BCGColor::getColor($default, 'white');
}
}
};
?>

View File

@@ -0,0 +1,196 @@
<?php
/**
* BCGDrawing.php
*--------------------------------------------------------------------
*
* Holds the drawing $im
* You can use get_im() to add other kind of form not held into these classes.
*
*--------------------------------------------------------------------
* Revision History
* v2.1.0 8 nov 2009 Jean-Sébastien Goupil Support DPI, Rotation
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Supports GIF and WBMP
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Just one barcode per drawing
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGDrawing.php,v 1.10 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.12
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode.php');
include_once('drawer/BCGDrawJPG.php');
include_once('drawer/BCGDrawPNG.php');
class BCGDrawing {
var $IMG_FORMAT_PNG = 1; // const
var $IMG_FORMAT_JPEG = 2; // const
var $IMG_FORMAT_GIF = 3; // const
var $IMG_FORMAT_WBMP = 4; // const
var $w, $h; // int
var $color; // BCGColor
var $filename; // char *
var $im; // {object}
var $barcode; // BCGBarcode
var $dpi; // int
var $rotateDegree; // float
/**
* Constructor
*
* @param int $w
* @param int $h
* @param string filename
* @param BCGColor $color
*/
function BCGDrawing($filename, &$color) {
$this->im = null;
$this->setFilename($filename);
$this->color =& $color;
$this->dpi = null;
$this->rotateDegree = 0.0;
}
/**
* Destructor
*/
//public function __destruct() {
// $this->destroy();
//}
/**
* Sets the filename
*
* @param string $filaneme
*/
function setFilename($filename) {
$this->filename = $filename;
}
/**
* Init Image and color background
*/
function init() {
if($this->im === null) {
$this->im = imagecreatetruecolor($this->w, $this->h)
or die('Can\'t Initialize the GD Libraty');
imagefilledrectangle($this->im, 0, 0, $this->w - 1, $this->h - 1, $this->color->allocate($this->im));
}
}
/**
* @return resource
*/
function &get_im() {
return $this->im;
}
/**
* @param resource $im
*/
function set_im(&$im) {
$this->im = $im;
}
/**
* Set Barcode for drawing
*
* @param BCGBarcode $barcode
*/
function setBarcode(&$barcode) {
$this->barcode =& $barcode;
}
/**
* Get the DPI for supported filetype
*
* @return int
*/
function getDPI() {
return $this->dpi;
}
/**
* Set the DPI for supported filetype
*
* @param float $dpi
*/
function setDPI($dpi) {
$this->dpi = $dpi;
}
/**
* Get the rotation angle in degree
*
* @return float
*/
function getRotationAngle() {
return $this->rotateDegree;
}
/**
* Set the rotation angle in degree
*
* @param float $degree
*/
function setRotationAngle($degree) {
$this->rotateDegree = (float)$degree;
}
/**
* Draw the barcode on the image $im
*/
function draw() {
$size = $this->barcode->getMaxSize();
$this->w = max(1, $size[0]);
$this->h = max(1, $size[1]);
$this->init();
$this->barcode->draw($this->im);
}
/**
* Save $im into the file (many format available)
*
* @param int $image_style
* @param int $quality
*/
function finish($image_style = 2, $quality = 100) {
$drawer = null;
$im = $this->im;
if($this->rotateDegree > 0.0) {
$im = imagerotate($this->im, $this->rotateDegree, $this->color->allocate($this->im));
}
if ($image_style === $this->IMG_FORMAT_PNG) {
$drawer =& new BCGDrawPNG($im);
$drawer->setFilename($this->filename);
$drawer->setDPI($this->dpi);
} elseif ($image_style === $this->IMG_FORMAT_JPEG) {
$drawer =& new BCGDrawJPG($im);
$drawer->setFilename($this->filename);
$drawer->setDPI($this->dpi);
$drawer->setQuality($quality);
} elseif ($image_style === $this->IMG_FORMAT_GIF) {
imagegif($this->im, $this->filename);
} elseif ($image_style === $this->IMG_FORMAT_WBMP) {
imagewbmp($this->im, $this->filename);
}
if($drawer !== null) {
$drawer->draw();
}
}
/**
* Free the memory of PHP (called also by destructor)
*/
function destroy() {
@imagedestroy($this->im);
}
};
?>

View File

@@ -0,0 +1,102 @@
<?php
/**
* BCGFont.php
*--------------------------------------------------------------------
*
* Holds font family and size.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3 6 feb 2006 Jean-Sébastien Goupil Correct getWidth()
* v1.2.3b 30 dec 2005 Jean-Sébastien Goupil Add getUnderBaseline()
* V1.2.1 27 jun 2005 Jean-Sebastien Goupil New
*--------------------------------------------------------------------
* $Id: BCGFont.php,v 1.6 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.7
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
class BCGFont {
var $path;
var $text;
var $size;
var $box;
/**
* Constructor
*
* @param string $fontPath path to the file
* @param int $size size in point
*/
function BCGFont($fontPath, $size) {
$this->path = $fontPath;
$this->size = $size;
}
/**
* Text associated to the font
*
* @param string text
*/
function setText($text) {
$this->text = $text;
$im = imagecreate(1, 1);
$this->box = imagettftext($im, $this->size, 0, 0, 0, imagecolorallocate($im, 0, 0, 0), $this->path, $this->text);
}
/**
* Returns the width that the text takes to be written
*
* @return float
*/
function getWidth() {
if ($this->box !== NULL) {
// Bug fixed : a number is aligned on the "right" in the box...
// If we are writting the number "1" with minX at 2 and maxX at 10
// The maxWidth will be 10 and not 8 because we don't squeeze the number
// on its left. So now we don't remove the minX.
return abs(max($this->box[2], $this->box[4]));
} else {
return 0;
}
}
/**
* Returns the height that the text takes.
*
* @return float
*/
function getHeight() {
if ($this->box !== NULL) {
return (float) abs(max($this->box[5], $this->box[7]) - min($this->box[1], $this->box[3]));
} else {
return 0.0;
}
}
/**
* Returns the number of pixel under the baseline located at 0.
*
* @return float
*/
function getUnderBaseline() {
// Y for imagettftext : This sets the position of the fonts baseline, not the very bottom of the character.
return (float) max($this->box[1], $this->box[3]);
}
/**
* Draws the text on the image at a specific position.
* $x and $y represent the left bottom corner.
*
* @param resource $im
* @param int $color
* @param int $x
* @param int $y
*/
function draw(&$im, $color, $x, $y) {
imagettftext($im, $this->size, 0, $x, $y, $color, $this->path, $this->text);
}
}
?>

View File

@@ -0,0 +1,121 @@
<?php
/**
* BCGcodabar.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Codabar
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update + fix B and C
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil PHP5.1 compatible
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGcodabar.barcode.php,v 1.9 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.11
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGcodabar extends BCGBarcode1D {
/**
* Constructor
*/
function BCGcodabar() { // public
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9','-','$',':','/','.','+','A','B','C','D');
$this->code = array( // 0 added to add an extra space
'00000110', /* 0 */
'00001100', /* 1 */
'00010010', /* 2 */
'11000000', /* 3 */
'00100100', /* 4 */
'10000100', /* 5 */
'01000010', /* 6 */
'01001000', /* 7 */
'01100000', /* 8 */
'10010000', /* 9 */
'00011000', /* - */
'00110000', /* $ */
'10001010', /* : */
'10100010', /* / */
'10101000', /* . */
'00111110', /* + */
'00110100', /* A */
'01010010', /* B */
'00010110', /* C */
'00011100' /* D */
);
}
/**
* Saves Text
*
* @param string $text
*/
function parse($text) {
BCGBarcode1D::parse(strtoupper($text)); // Only Capital Letters are Allowed
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must start by A, B, C or D
if($this->text[0] !== 'A' && $this->text[0] !== 'B' && $this->text[0] !== 'C' && $this->text[0] !== 'D') {
$this->drawError($im, 'Must start by char A, B, C or D.');
$error_stop = true;
}
// Must over by A, B, C or D
$c2 = $c - 1;
if($c2 === 0 || ($this->text[$c2] !== 'A' && $this->text[$c2] !== 'B' && $this->text[$c2] !== 'C' && $this->text[$c2] !== 'D')) {
$this->drawError($im, 'Must end by char A, B, C or D.');
$error_stop = true;
}
if($error_stop === false) {
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->findCode($this->text[$i]), true);
}
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$w = 0;
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
$index = $this->findIndex($this->text[$i]);
if($index !== false) {
$w += 8;
$w += substr_count($this->code[$index], '1');
}
}
return array($p[0] + $w * $this->scale, $p[1]);
}
};
?>

View File

@@ -0,0 +1,164 @@
<?php
/**
* BCGcode11.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Code 11
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 30 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible + Error in checksum
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil WS Fix
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGcode11.barcode.php,v 1.9 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.11
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGcode11 extends BCGBarcode1D {
/**
* Constructor
*/
function BCGcode11() { // public
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9','-');
$this->code = array( // 0 added to add an extra space
'000010', /* 0 */
'100010', /* 1 */
'010010', /* 2 */
'110000', /* 3 */
'001010', /* 4 */
'101000', /* 5 */
'011000', /* 6 */
'000110', /* 7 */
'100100', /* 8 */
'100000', /* 9 */
'001000' /* - */
);
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im,'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Starting Code
$this->drawChar($im, '001100', true);
// Chars
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->findCode($this->text[$i]), true);
}
// Checksum
$this->calculateChecksum();
$c = count($this->checksumValue);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->code[$this->checksumValue[$i]], true);
}
// Ending Code
$this->drawChar($im, '00110', true);
$this->drawText($im);
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$w = 0;
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
$index = $this->findIndex($this->text[$i]);
if($index !== false) {
$w += 6;
$w += substr_count($this->code[$index], '1');
}
}
$startlength = 8 * $this->scale;
$textlength = $w * $this->scale;
// We take the max length possible for checksums (it is 7 or 8...)
$checksumlength = 8 * $this->scale;
if($c >= 10) {
$checksumlength += 8 * $this->scale;
}
$endlength = 7 * $this->scale;
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Checksum
// First CheckSUM "C"
// The "C" checksum character is the modulo 11 remainder of the sum of the weighted
// value of the data characters. The weighting value starts at "1" for the right-most
// data character, 2 for the second to last, 3 for the third-to-last, and so on up to 20.
// After 10, the sequence wraps around back to 1.
// Second CheckSUM "K"
// Same as CheckSUM "C" but we count the CheckSum "C" at the end
// After 9, the sequence wraps around back to 1.
$sequence_multiplier = array(10, 9);
$temp_text = $this->text;
$this->checksumValue = array();
for($z = 0; $z < 2; $z++) {
$c = strlen($temp_text);
// We don't display the K CheckSum if the original text had a length less than 10
if($c <= 10 && $z === 1) {
break;
}
$checksum = 0;
for($i = $c, $j = 0; $i > 0; $i--, $j++) {
$multiplier = $i % $sequence_multiplier[$z];
if($multiplier === 0) {
$multiplier = $sequence_multiplier[$z];
}
$checksum += $this->findIndex($temp_text[$j]) * $multiplier;
}
$this->checksumValue[$z] = $checksum % 11;
$temp_text .= $this->keys[$this->checksumValue[$z]];
}
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
$ret = '';
$c = count($this->checksumValue);
for($i = 0; $i < $c; $i++) {
$ret .= $this->keys[$this->checksumValue[$i]];
}
return $ret;
}
return false;
}
};
?>

View File

@@ -0,0 +1,874 @@
<?php
/**
* BCGcode128.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Code 128, A, B, C
*
* # Code C Working properly only on PHP4 or PHP5.0.3+ due to bug :
* http://bugs.php.net/bug.php?id=28862
*
* !! Warning !!
* If you display the checksum on the label, you may obtain
* some garbage since some characters are not displayable.
*
*--------------------------------------------------------------------
* Revision History
* v2.1.0 8 nov 2009 Jean-Sébastien Goupil Specify exact table for encoding
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Fix Code 128 C
* v2.00 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3pl2 27 sep 2006 Jean-Sébastien Goupil There were some errors dealing with C table
* v1.2.3b 30 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added + Correct bug if passing C to another code
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGcode128.barcode.php,v 1.13 2010/02/14 00:25:14 jsgoupil Exp $
* PHP5-Revision: 1.17
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
define('CODE128_A', 1); // Table A
define('CODE128_B', 2); // Table B
define('CODE128_C', 3); // Table C
class BCGcode128 extends BCGBarcode1D {
var $KEYA_FNC3 = 96; // const
var $KEYA_FNC2 = 97; // const
var $KEYA_SHIFT = 98; // const
var $KEYA_CODEC = 99; // const
var $KEYA_CODEB = 100; // const
var $KEYA_FNC4 = 101; // const
var $KEYA_FNC1 = 102; // const
var $KEYB_FNC3 = 96; // const
var $KEYB_FNC2 = 97; // const
var $KEYB_SHIFT = 98; // const
var $KEYB_CODEC = 99; // const
var $KEYB_FNC4 = 100; // const
var $KEYB_CODEA = 101; // const
var $KEYB_FNC1 = 102; // const
var $KEYC_CODEB = 100; // const
var $KEYC_CODEA = 101; // const
var $KEYC_FNC1 = 102; // const
var $KEY_STARTA = 103; // const
var $KEY_STARTB = 104; // const
var $KEY_STARTC = 105; // const
var $KEY_STOP = 106; // const
var $keysA, $keysB, $keysC;
var $starting_text;
var $indcheck, $data;
var $tilde;
var $errorText;
var $shift;
var $latch;
var $fnc;
var $METHOD = NULL; // Array of method available to create PDF417 (PDF417_TM, PDF417_NM, PDF417_BM)
/**
* Constructor
*
* @param char $start
*/
function BCGcode128($start = NULL) { // public
BCGBarcode1D::BCGBarcode1D();
/* CODE 128 A */
$this->keysA = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_';
for($i = 0; $i < 32; $i++) {
$this->keysA .= chr($i);
}
/* CODE 128 B */
$this->keysB = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'.chr(127);
/* CODE 128 C */
$this->keysC = '0123456789';
$this->code = array(
'101111', /* 00 */
'111011', /* 01 */
'111110', /* 02 */
'010112', /* 03 */
'010211', /* 04 */
'020111', /* 05 */
'011102', /* 06 */
'011201', /* 07 */
'021101', /* 08 */
'110102', /* 09 */
'110201', /* 10 */
'120101', /* 11 */
'001121', /* 12 */
'011021', /* 13 */
'011120', /* 14 */
'002111', /* 15 */
'012011', /* 16 */
'012110', /* 17 */
'112100', /* 18 */
'110021', /* 19 */
'110120', /* 20 */
'102101', /* 21 */
'112001', /* 22 */
'201020', /* 23 */
'200111', /* 24 */
'210011', /* 25 */
'210110', /* 26 */
'201101', /* 27 */
'211001', /* 28 */
'211100', /* 29 */
'101012', /* 30 */
'101210', /* 31 */
'121010', /* 32 */
'000212', /* 33 */
'020012', /* 34 */
'020210', /* 35 */
'001202', /* 36 */
'021002', /* 37 */
'021200', /* 38 */
'100202', /* 39 */
'120002', /* 40 */
'120200', /* 41 */
'001022', /* 42 */
'001220', /* 43 */
'021020', /* 44 */
'002012', /* 45 */
'002210', /* 46 */
'022010', /* 47 */
'202010', /* 48 */
'100220', /* 49 */
'120020', /* 50 */
'102002', /* 51 */
'102200', /* 52 */
'102020', /* 53 */
'200012', /* 54 */
'200210', /* 55 */
'220010', /* 56 */
'201002', /* 57 */
'201200', /* 58 */
'221000', /* 59 */
'203000', /* 60 */
'110300', /* 61 */
'320000', /* 62 */
'000113', /* 63 */
'000311', /* 64 */
'010013', /* 65 */
'010310', /* 66 */
'030011', /* 67 */
'030110', /* 68 */
'001103', /* 69 */
'001301', /* 70 */
'011003', /* 71 */
'011300', /* 72 */
'031001', /* 73 */
'031100', /* 74 */
'130100', /* 75 */
'110003', /* 76 */
'302000', /* 77 */
'130001', /* 78 */
'023000', /* 79 */
'000131', /* 80 */
'010031', /* 81 */
'010130', /* 82 */
'003101', /* 83 */
'013001', /* 84 */
'013100', /* 85 */
'300101', /* 86 */
'310001', /* 87 */
'310100', /* 88 */
'101030', /* 89 */
'103010', /* 90 */
'301010', /* 91 */
'000032', /* 92 */
'000230', /* 93 */
'020030', /* 94 */
'003002', /* 95 */
'003200', /* 96 */
'300002', /* 97 */
'300200', /* 98 */
'002030', /* 99 */
'003020', /* 100*/
'200030', /* 101*/
'300020', /* 102*/
'100301', /* 103*/
'100103', /* 104*/
'100121', /* 105*/
'122000' /*STOP*/
);
$this->errorText = '';
$this->setStart($start);
$this->setTilde(true);
// Latches and Shifts
$this->latch = array(
array(null, $this->KEYA_CODEB, $this->KEYA_CODEC),
array($this->KEYB_CODEA, null, $this->KEYB_CODEC),
array($this->KEYC_CODEA, $this->KEYC_CODEB, null)
);
$this->shift = array(
array(null, $this->KEYA_SHIFT),
array($this->KEYB_SHIFT, null)
);
$this->fnc = array(
array($this->KEYA_FNC1, $this->KEYA_FNC2, $this->KEYA_FNC3, $this->KEYA_FNC4),
array($this->KEYB_FNC1, $this->KEYB_FNC2, $this->KEYB_FNC3, $this->KEYB_FNC4),
array($this->KEYC_FNC1, null, null, null)
);
// Method available
$this->METHOD = array(CODE128_A => 'A', CODE128_B => 'B', CODE128_C => 'C');
}
/**
* Specifies the start code. Can be 'A', 'B', 'C' or NULL
* - Table A: Capitals + ASCII 0-31 + punct
* - Table B: Capitals + LowerCase + punct
* - Table C: Numbers
*
* If NULL is specified, the table selection is automatically made.
* The default is NULL.
*
* @param string $table
*/
function setStart($table) {
if($table !== 'A' && $table !== 'B' && $table !== 'C' && $table !== NULL) $table = NULL;
$this->starting_text = $table;
}
/**
* Accepts tilde to be process as a special character.
* If true, you can do this:
* - ~~ : to make ONE tilde
* - ~Fx : to insert FCNx. x is equal from 1 to 4.
*
* @param boolean $accept
*/
function setTilde($accept) {
$this->tilde = (bool)$accept;
}
/**
* Saves Text
*
* @param string $text
*/
function parse($text) {
$this->setStartFromText($text);
$this->errorText = ''; // Reset Error
$this->text = '';
$seq = '';
$currentMode = $this->starting_text;
// Here, we format correctly what the user gives.
if(!is_array($text)) {
$seq = $this->getSequence($text, $currentMode);
$this->text = $text;
} else {
// This loop checks for UnknownText AND raises an error if a character is not allowed in a table
reset($text);
while(list($key1, $val1) = each($text)) { // We take each value
if(!is_array($val1)) { // This is not a table
if(is_string($val1)) { // If it's a string, parse as unknown
$seq .= $this->getSequence($val1, $currentMode);
$this->text .= $val1;
} else {
// it's the case of "array(ENCODING, 'text')"
// We got ENCODING in $val1, calling 'each' again will get 'text' in $val2
list($key2, $val2) = each($text);
$seq .= $this->{'setParse' . $this->METHOD[$val1]}($val2, $currentMode);
$this->text .= $val2;
}
} else { // The method is specified
// $val1[0] = ENCODING
// $val1[1] = 'text'
$value = isset($val1[1]) ? $val1[1] : ''; // If data available
$seq .= $this->{'setParse' . $this->METHOD[$val1[0]]}($value, $currentMode);
$this->text .= $value;
}
if($this->errorText) {
break;
}
}
}
if($seq !== '') {
$bitstream = $this->createBinaryStream($this->text, $seq);
$this->setData($bitstream);
}
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
if(!empty($this->errorText)) {
$this->drawError($im, $this->errorText);
} else {
$c = count($this->data);
if($c === 0) {
$this->drawError($im, 'No text has been entered.');
} else {
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->data[$i], true);
}
$this->drawChar($im, '1', true);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
// Contains start + text + checksum + stop
$textlength = count($this->data) * 11 * $this->scale;
$endlength = 2 * $this->scale; // + final bar
return array($p[0] + $textlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Checksum
// First Char (START)
// + Starting with the first data character following the start character,
// take the value of the character (between 0 and 102, inclusive) multiply
// it by its character position (1) and add that to the running checksum.
// Modulated 103
$this->checksumValue = $this->indcheck[0];
$c = count($this->indcheck);
for($i = 1; $i < $c; $i++) {
$this->checksumValue += $this->indcheck[$i] * $i;
}
$this->checksumValue = $this->checksumValue % 103;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
/**
* Specifies the starting_text table if none has been specified earlier.
*
* @param string $text
*/
function setStartFromText($text) {
if($this->starting_text === NULL) {
// If we have a forced table at the start, we get that one...
if(is_array($text)) {
if(is_array($text[0])) {
// Code like array(array(ENCODING, ''))
$this->starting_text = $this->METHOD[$text[0][0]];
return;
} else {
if(is_string($text[0])) {
// Code like array('test') (Automatic text)
$text = $text[0];
} else {
// Code like array(ENCODING, '')
$this->starting_text = $this->METHOD[$text[0]];
return;
}
}
}
// At this point, we had an "automatic" table selection...
// If we can get at least 4 numbers, go in C; otherwise go in B.
$tmp = preg_quote($this->keysC, '/');
if(strlen($text) >= 4 && preg_match('/[' . $tmp . ']/', substr($text, 0, 4))) {
$this->starting_text = 'C';
} else {
if(strpos($this->keysB, $text[0])) {
$this->starting_text = 'B';
} else {
$this->starting_text = 'A';
}
}
}
}
/**
* Extracts the ~ value from the $text at the $pos.
* If the tilde is not ~~, ~F1, ~F2, ~F3, ~F4; an error is raised.
*
* @param string $text
* @param int $pos
* @return string
*/
function extractTilde($text, $pos) {
if($text[$pos] === '~') {
if(isset($text[$pos + 1])) {
// Do we have a tilde?
if($text[$pos + 1] === '~') {
return '~~';
} elseif($text[$pos + 1] === 'F') {
// Do we have a number after?
if(isset($text[$pos + 2])) {
$v = intval($text[$pos + 2]);
if($v >= 1 && $v <= 4) {
return '~F' . $v;
} else {
$this->errorText = 'Bad ~F. You must provide a number from 1 to 4.';
return '';
}
} else {
$this->errorText = 'Bad ~F. You must provide a number from 1 to 4.';
return '';
}
} else {
// Wrong code
$this->errorText = 'Wrong code after the ~.';
return '';
}
} else {
// Wrong code
$this->errorText = 'Wrong code after the ~.';
return '';
}
} else {
// Can't happen
$this->errorText = 'There is no ~ at this location';
return '';
}
}
/**
* Gets the "dotted" sequence for the $text based on the $currentMode.
* There is also a check if we use the special tilde ~
*
* @param string $text
* @param string $currentMode
* @return string
*/
function getSequenceParsed($text, $currentMode) {
if($this->tilde) {
$sequence = '';
$previousPos = 0;
while(($pos = strpos($text, '~', $previousPos)) !== false) {
$tildeData = $this->extractTilde($text, $pos);
if($tildeData === '') {
// Something bad happened in extractTilde(). The errorText is already populated.
return '';
}
$simpleTilde = ($tildeData === '~~');
if($simpleTilde && $currentMode !== 'B') {
$this->errorText = 'The Table ' . $currentMode . ' doesn\'t contain the character ~.';
return '';
}
// At this point, we know we have ~Fx
if($tildeData !== '~F1' && $currentMode === 'C') {
// The mode C doesn't support ~F2, ~F3, ~F4
$this->errorText = 'The Table C doesn\'t contain the function ' . $tildeData . '.';
return '';
}
$length = $pos - $previousPos;
if($currentMode === 'C') {
if($length % 2 === 1) {
$this->errorText = 'The text "'.$text.'" must have an even number of character to be encoded in Table C.';
return '';
}
}
$sequence .= str_repeat('.', $length);
$sequence .= '.';
$sequence .= (!$simpleTilde) ? 'F' : '';
$previousPos = $pos + strlen($tildeData);
}
// Flushing
$length = strlen($text) - $previousPos;
if($currentMode === 'C') {
if($length % 2 === 1) {
$this->errorText = 'The text "'.$text.'" must have an even number of character to be encoded in Table C.';
return '';
}
}
$sequence .= str_repeat('.', $length);
return $sequence;
} else {
return str_repeat('.', strlen($text));
}
}
/**
* Parses the text and returns the appropriate sequence for the Table A.
*
* @param string $text
* @param string $currentMode
* @return string
*/
function setParseA($text, &$currentMode) {
$tmp = preg_quote($this->keysA, '/');
// If we accept the ~ for special character, we must allow it.
if($this->tilde) {
$tmp .= '~';
}
$match = array();
if(preg_match('/[^' . $tmp . ']/', $text, $match) === 1) {
// We found something not allowed
$this->errorText = 'The text "' . $text . '" can\'t be parsed with the Table A. The character "' . $match[0] . '" is not allowed.';
return '';
} else {
$latch = ($currentMode === 'A') ? '' : '0';
$currentMode = 'A';
return $latch . $this->getSequenceParsed($text, $currentMode);
}
}
/**
* Parses the text and returns the appropriate sequence for the Table B.
*
* @param string $text
* @param string $currentMode
* @return string
*/
function setParseB($text, &$currentMode) {
$tmp = preg_quote($this->keysB, '/');
$match = array();
if(preg_match('/[^' . $tmp . ']/', $text, $match) === 1) {
// We found something not allowed
$this->errorText = 'The text "'.$text.'" can\'t be parsed with the Table B. The character "' . $match[0] . '" is not allowed.';
return '';
} else {
$latch = ($currentMode === 'B') ? '' : '1';
$currentMode = 'B';
return $latch . $this->getSequenceParsed($text, $currentMode);
}
}
/**
* Parses the text and returns the appropriate sequence for the Table C.
*
* @param string $text
* @param string $currentMode
* @return string
*/
function setParseC($text, &$currentMode) {
$tmp = preg_quote($this->keysC, '/');
// If we accept the ~ for special character, we must allow it.
if($this->tilde) {
$tmp .= '~F';
}
$match = array();
if(preg_match('/[^' . $tmp . ']/', $text, $match) === 1) {
// We found something not allowed
$this->errorText = 'The text "'.$text.'" can\'t be parsed with the Table C. The character "' . $match[0] . '" is not allowed.';
return '';
} else {
$latch = ($currentMode === 'C') ? '' : '2';
$currentMode = 'C';
return $latch . $this->getSequenceParsed($text, $currentMode);
}
}
/**
* Depending on the $text, it will return the correct
* sequence to encode the text.
*
* @param string $text
* @param string $starting_text
* @return string
*/
function getSequence(&$text, &$starting_text) {
$e = 10000;
$latLen = array(
array(0, 1, 1),
array(1, 0, 1),
array(1, 1, 0)
);
$shftLen = array(
array($e, 1, $e),
array(1, $e, $e),
array($e, $e, $e)
);
$charSiz = array(2, 2, 1);
$startA = $e;
$startB = $e;
$startC = $e;
if($starting_text === 'A') $startA = 0;
if($starting_text === 'B') $startB = 0;
if($starting_text === 'C') $startC = 0;
$curLen = array($startA, $startB, $startC);
$curSeq = array(null, null, null);
$nextNumber = false;
$x = 0;
$xLen = strlen($text);
for($x = 0; $x < $xLen; $x++) {
$input = $text[$x];
// 1.
for($i = 0; $i < 3; $i++) {
for($j = 0; $j < 3; $j++) {
if(($curLen[$i] + $latLen[$i][$j]) < $curLen[$j]) {
$curLen[$j] = $curLen[$i] + $latLen[$i][$j];
$curSeq[$j] = $curSeq[$i] . $j;
}
}
}
// 2.
$nxtLen = array($e, $e, $e);
$nxtSeq = array();
// 3.
$flag = false;
$posArray = array();
// Special case, we do have a tilde and we process them
if($this->tilde && $input === '~') {
$tildeData = $this->extractTilde($text, $x);
if($tildeData === '') {
// Something bad happened in extractTilde(). The errorText is already populated.
return '';
} elseif($tildeData === '~~') {
// We simply skip a tilde
$posArray[] = 1;
$x++;
} elseif(substr($tildeData, 0, 2) === '~F') {
$v = intval($tildeData[2]);
$posArray[] = 0;
$posArray[] = 1;
if($v === 1) {
$posArray[] = 2;
}
$x += 2;
$flag = true;
}
} else {
$pos = strpos($this->keysA, $input);
if($pos !== false) {
$posArray[] = 0;
}
$pos = strpos($this->keysB, $input);
if($pos !== false) {
$posArray[] = 1;
}
$pos = strpos($this->keysC, $input);
// Do we have the next char a number?? OR a ~F1
if($nextNumber || ($pos !== false && isset($text[$x + 1]) && strpos($this->keysC, $text[$x + 1]) !== false)) {
$nextNumber = !$nextNumber;
$posArray[] = 2;
}
}
$c = count($posArray);
for($i = 0; $i < $c; $i++) {
if(($curLen[$posArray[$i]] + $charSiz[$posArray[$i]]) < $nxtLen[$posArray[$i]]) {
$nxtLen[$posArray[$i]] = $curLen[$posArray[$i]] + $charSiz[$posArray[$i]];
$nxtSeq[$posArray[$i]] = $curSeq[$posArray[$i]] . '.';
}
for($j = 0; $j < 2; $j++) {
if($j === $posArray[$i]) continue;
if(($curLen[$j] + $shftLen[$j][$posArray[$i]] + $charSiz[$posArray[$i]]) < $nxtLen[$j]) {
$nxtLen[$j] = $curLen[$j] + $shftLen[$j][$posArray[$i]] + $charSiz[$posArray[$i]];
$nxtSeq[$j] = $curSeq[$j] . chr($posArray[$i] + 65) . '.';
}
}
}
if($c === 0) {
// We found an unsuported character
$this->errorText = 'Character ' . $input . ' not supported.';
return '';
}
if($flag) {
for($i = 0; $i < 5; $i++) {
if(isset($nxtSeq[$i])) {
$nxtSeq[$i] .= 'F';
}
}
}
// 4.
for($i = 0; $i < 3; $i++) {
$curLen[$i] = $nxtLen[$i];
if(isset($nxtSeq[$i])) {
$curSeq[$i] = $nxtSeq[$i];
}
}
}
// Every curLen under $e are possible but we take the smallest !
$m = $e;
$k = -1;
for($i = 0; $i < 3; $i++) {
if($curLen[$i] < $m) {
$k = $i;
$m = $curLen[$i];
}
}
if($k === -1) {
return '';
}
$starting_text = chr($k + 65);
return $curSeq[$k];
}
/**
* Depending on the sequence $seq given (returned from getSequence()),
* this method will return the code stream in an array. Each char will be a
* string of bit based on the Code 128.
*
* Each letter from the sequence represents bits.
*
* 0 to 2 are latches
* A to B are Shift + Letter
* . is a char in the current encoding
*
* @param string $text
* @param string $seq
* @return string[][]
*/
function createBinaryStream($text, $seq) {
$c = strlen($seq);
$data = array(); // code stream
$indcheck = array(); // index for checksum
$currentEncoding = 0;
if($this->starting_text === 'A') {
$currentEncoding = 0;
$indcheck[] = $this->KEY_STARTA;
} elseif($this->starting_text === 'B') {
$currentEncoding = 1;
$indcheck[] = $this->KEY_STARTB;
} elseif($this->starting_text === 'C') {
$currentEncoding = 2;
$indcheck[] = $this->KEY_STARTC;
}
$data[] = $this->code[103 + $currentEncoding];
$temporaryEncoding = -1;
for($i = 0, $counter = 0; $i < $c; $i++) {
$input = $seq[$i];
$inputI = intval($input);
if($input === '.') {
$this->encodeChar($data, $currentEncoding, $seq, $text, $i, $counter, $indcheck);
if($temporaryEncoding !== -1) {
$currentEncoding = $temporaryEncoding;
$temporaryEncoding = -1;
}
} elseif($input >= 'A' && $input <= 'B') {
// We shift
$encoding = ord($input) - 65;
$shift = $this->shift[$currentEncoding][$encoding];
$indcheck[] = $shift;
$data[] = $this->code[$shift];
if($temporaryEncoding === -1) {
$temporaryEncoding = $currentEncoding;
}
$currentEncoding = $encoding;
} elseif($inputI >= 0 && $inputI < 3) {
$temporaryEncoding = -1;
// We latch
$latch = $this->latch[$currentEncoding][$inputI];
if($latch !== NULL) {
$indcheck[] = $latch;
$data[] = $this->code[$latch];
$currentEncoding = $inputI;
}
}
}
return array($indcheck, $data);
}
function encodeChar(&$data, $encoding, $seq, $text, &$i, &$counter, &$indcheck) {
if(isset($seq[$i + 1]) && $seq[$i + 1] === 'F') {
// We have a flag !!
if($text[$counter + 1] === 'F') {
$number = $text[$counter + 2];
$fnc = $this->fnc[$encoding][$number - 1];
$indcheck[] = $fnc;
$data[] = $this->code[$fnc];
// Skip F + number
$counter += 2;
} else {
// Not supposed
}
$i++;
} else {
if($encoding === 2) {
// We take 2 numbers in the same time
$code = (int)substr($text, $counter, 2);
$indcheck[] = $code;
$data[] = $this->code[$code];
$counter++;
$i++;
} else {
$keys = ($encoding === 0) ? $this->keysA : $this->keysB;
$pos = strpos($keys, $text[$counter]);
$indcheck[] = $pos;
$data[] = $this->code[$pos];
}
}
$counter++;
}
/**
* Saves data into the classes.
*
* This method will save data, calculate real column number
* (if -1 was selected), the real error level (if -1 was
* selected)... It will add Padding to the end and generate
* the error codes.
*
* @param array $data
*/
function setData($data) {
$this->indcheck = $data[0];
$this->data = $data[1];
$this->calculateChecksum();
$this->data[] = $this->code[$this->checksumValue];
$this->data[] = $this->code[$this->KEY_STOP];
}
};
?>

View File

@@ -0,0 +1,183 @@
<?php
/**
* BCGcode39.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Code 39
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 30 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* v1.01 7 jul 2004 Jean-Sebastien Goupil Correction + Sign
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGcode39.barcode.php,v 1.8 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.10
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGcode39 extends BCGBarcode1D {
var $starting, $ending;
var $checksum;
/**
* Constructor
*/
function BCGcode39() { // public
BCGBarcode1D::BCGBarcode1D();
$this->starting = $this->ending = 43;
$this->keys = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','-','.',' ','$','/','+','%','*');
$this->code = array( // 0 added to add an extra space
'0001101000', /* 0 */
'1001000010', /* 1 */
'0011000010', /* 2 */
'1011000000', /* 3 */
'0001100010', /* 4 */
'1001100000', /* 5 */
'0011100000', /* 6 */
'0001001010', /* 7 */
'1001001000', /* 8 */
'0011001000', /* 9 */
'1000010010', /* A */
'0010010010', /* B */
'1010010000', /* C */
'0000110010', /* D */
'1000110000', /* E */
'0010110000', /* F */
'0000011010', /* G */
'1000011000', /* H */
'0010011000', /* I */
'0000111000', /* J */
'1000000110', /* K */
'0010000110', /* L */
'1010000100', /* M */
'0000100110', /* N */
'1000100100', /* O */
'0010100100', /* P */
'0000001110', /* Q */
'1000001100', /* R */
'0010001100', /* S */
'0000101100', /* T */
'1100000010', /* U */
'0110000010', /* V */
'1110000000', /* W */
'0100100010', /* X */
'1100100000', /* Y */
'0110100000', /* Z */
'0100001010', /* - */
'1100001000', /* . */
'0110001000', /* */
'0101010000', /* $ */
'0101000100', /* / */
'0100010100', /* + */
'0001010100', /* % */
'0100101000' /* * */
);
$this->setChecksum(false);
}
function setChecksum($checksum) {
$this->checksum = (bool)$checksum;
}
/**
* Saves Text
*
* @param string $text
*/
function parse($text) {
BCGBarcode1D::parse(strtoupper($text)); // Only Capital Letters are Allowed
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for ($i = 0; $i < $c; $i++) {
if (array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if ($error_stop === false) {
// The * is not allowed
if (strpos($this->text, '*') !== false) {
$this->drawError($im, 'Char \'*\' not allowed.');
$error_stop = true;
}
if ($error_stop === false) {
// Starting *
$this->drawChar($im, $this->code[$this->starting], true);
// Chars
for ($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->findCode($this->text[$i]), true);
}
// Checksum (rarely used)
if ($this->checksum === true) {
$this->calculateChecksum();
$this->drawChar($im, $this->code[$this->checksumValue % 43], true);
}
// Ending *
$this->drawChar($im, $this->code[$this->ending], true);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$textlength = 13 * strlen($this->text) * $this->scale;
$startlength = 13 * $this->scale;
$checksumlength = 0;
if ($this->checksum === true) {
$checksumlength = 13 * $this->scale;
}
$endlength = 13 * $this->scale;
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
$this->checksumValue = 0;
$c = strlen($this->text);
for ($i = 0; $i < $c; $i++) {
$this->checksumValue += $this->findIndex($this->text[$i]);
}
$this->checksumValue = $this->checksumValue % 43;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if ($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if ($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
};
?>

View File

@@ -0,0 +1,203 @@
<?php
/**
* BCGcode39extended.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Code 39 Extended
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
*--------------------------------------------------------------------
* $Id: BCGcode39extended.barcode.php,v 1.3 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.3
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGcode39.barcode.php');
class BCGcode39extended extends BCGcode39 {
var $EXTENDED_1 = 39; // const
var $EXTENDED_2 = 40; // const
var $EXTENDED_3 = 41; // const
var $EXTENDED_4 = 42; // const
var $errorText;
var $indcheck, $data;
/**
* Constructor
*/
function BCGcode39extended() { // public
BCGcode39::BCGcode39();
// We just put parenthesis around special characters.
$this->keys[$this->EXTENDED_1] = '($)';
$this->keys[$this->EXTENDED_2] = '(/)';
$this->keys[$this->EXTENDED_3] = '(+)';
$this->keys[$this->EXTENDED_4] = '(%)';
$this->errorText = '';
}
/**
* Saves Text
*
* @param string $text
*/
function parse($text) {
$this->text = $text;
$data = array();
$indcheck = array();
$this->errorText = ''; // Reset Error
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
$pos = array_search($this->text[$i], $this->keys);
if($pos === false) {
// Search in extended?
$extended = $this->getExtendedVersion($this->text[$i]);
if($extended === false) {
$this->errorText .= 'Char \'' . $this->text[$i] . '\' not allowed.'."\n";
} else {
$extc = strlen($extended);
for($j = 0; $j < $extc; $j++) {
$v = $extended[$j];
if($v === '$') {
$indcheck[] = $this->EXTENDED_1;
$data[] = $this->code[$this->EXTENDED_1];
} elseif($v === '%') {
$indcheck[] = $this->EXTENDED_2;
$data[] = $this->code[$this->EXTENDED_2];
} elseif($v === '/') {
$indcheck[] = $this->EXTENDED_3;
$data[] = $this->code[$this->EXTENDED_3];
} elseif($v === '+') {
$indcheck[] = $this->EXTENDED_4;
$data[] = $this->code[$this->EXTENDED_4];
} else {
$pos2 = array_search($v, $this->keys);
$indcheck[] = $pos2;
$data[] = $this->code[$pos2];
}
}
}
} else {
$indcheck[] = $pos;
$data[] = $this->code[$pos];
}
}
$this->setData(array($indcheck, $data));
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
if(!empty($this->errorText)) {
$error = explode("\n", trim($this->errorText));
$c = count($error);
for($i = 0; $i < $c; $i++) {
$this->drawError($im, $error[$i]);
}
} else {
$c = count($this->data);
if($c === 0) {
$this->drawError($im, 'No text has been entered.');
} else {
// Starting *
$this->drawChar($im, $this->code[$this->starting], true);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->data[$i], true);
}
// Checksum (rarely used)
if ($this->checksum === true) {
$this->drawChar($im, $this->code[$this->checksumValue % 43], true);
}
// Ending *
$this->drawChar($im, $this->code[$this->ending], true);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$textlength = 13 * count($this->data) * $this->scale;
$startlength = 13 * $this->scale;
$checksumlength = 0;
if ($this->checksum === true) {
$checksumlength = 13 * $this->scale;
}
$endlength = 13 * $this->scale;
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
$this->checksumValue = 0;
$c = count($this->indcheck);
for ($i = 0; $i < $c; $i++) {
$this->checksumValue += $this->indcheck[$i];
}
$this->checksumValue = $this->checksumValue % 43;
}
/**
* Saves data into the classes.
*
* This method will save data, calculate real column number
* (if -1 was selected), the real error level (if -1 was
* selected)... It will add Padding to the end and generate
* the error codes.
*
* @param array $data
*/
function setData($data) {
$this->indcheck = $data[0];
$this->data = $data[1];
$this->calculateChecksum();
}
function getExtendedVersion($char) {
$o = ord($char);
if($o === 0)
return '%U';
elseif($o >= 1 && $o <= 26)
return '$' . chr($o + 64);
elseif(($o >= 33 && $o <= 44) || $o === 47 || $o === 48)
return '/' . chr($o + 32);
elseif($o >= 97 && $o <= 122)
return '+' . chr($o - 32);
elseif($o >= 27 && $o <= 31)
return '%' . chr($o + 38);
elseif($o >= 59 && $o <= 63)
return '%' . chr($o + 11);
elseif($o >= 91 && $o <= 95)
return '%' . chr($o - 16);
elseif($o >= 123 && $o <= 127)
return '%' . chr($o - 43);
elseif($o === 64)
return '%V';
elseif($o === 96)
return '%W';
elseif($o > 127)
return false;
else
return $char;
}
};
?>

View File

@@ -0,0 +1,295 @@
<?php
/**
* BCGcode93.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Code 93
*
* !! Warning !!
* If you display the checksum on the barcode, you may obtain
* some garbage since some characters are not displayable.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 30 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGcode93.barcode.php,v 1.8 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.10
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGcode93 extends BCGBarcode1D {
var $EXTENDED_1 = 43; // const
var $EXTENDED_2 = 44; // const
var $EXTENDED_3 = 45; // const
var $EXTENDED_4 = 46; // const
var $starting, $ending;
var $indcheck, $data;
var $errorText;
/**
* Constructor
*/
function BCGcode93() { // public
BCGBarcode1D::BCGBarcode1D();
$this->starting = $this->ending = 47; /* * */
$this->keys = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','-','.',' ','$','/','+','%','($)','(%)','(/)','(+)','(*)');
$this->code = array(
'020001', /* 0 */
'000102', /* 1 */
'000201', /* 2 */
'000300', /* 3 */
'010002', /* 4 */
'010101', /* 5 */
'010200', /* 6 */
'000003', /* 7 */
'020100', /* 8 */
'030000', /* 9 */
'100002', /* A */
'100101', /* B */
'100200', /* C */
'110001', /* D */
'110100', /* E */
'120000', /* F */
'001002', /* G */
'001101', /* H */
'001200', /* I */
'011001', /* J */
'021000', /* K */
'000012', /* L */
'000111', /* M */
'000210', /* N */
'010011', /* O */
'020010', /* P */
'101001', /* Q */
'101100', /* R */
'100011', /* S */
'100110', /* T */
'110010', /* U */
'111000', /* V */
'001011', /* W */
'001110', /* X */
'011010', /* Y */
'012000', /* Z */
'010020', /* - */
'200001', /* . */
'200100', /* */
'210000', /* $ */
'001020', /* / */
'002010', /* + */
'100020', /* % */
'010110', /*($)*/
'201000', /*(%)*/
'200010', /*(/)*/
'011100', /*(+)*/
'000030' /*(*)*/
);
$this->errorText = '';
}
/**
* Saves Text
*
* @param string $text
*/
function parse($text) {
$this->text = $text;
$data = array();
$indcheck = array();
$this->errorText = ''; // Reset Error
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
$pos = array_search($this->text[$i], $this->keys);
if($pos === false) {
// Search in extended?
$extended = $this->getExtendedVersion($this->text[$i]);
if($extended === false) {
$this->errorText .= 'Char \'' . $this->text[$i] . '\' not allowed.'."\n";
} else {
$extc = strlen($extended);
for($j = 0; $j < $extc; $j++) {
$v = $extended[$j];
if($v === '$') {
$indcheck[] = $this->EXTENDED_1;
$data[] = $this->code[$this->EXTENDED_1];
} elseif($v === '%') {
$indcheck[] = $this->EXTENDED_2;
$data[] = $this->code[$this->EXTENDED_2];
} elseif($v === '/') {
$indcheck[] = $this->EXTENDED_3;
$data[] = $this->code[$this->EXTENDED_3];
} elseif($v === '+') {
$indcheck[] = $this->EXTENDED_4;
$data[] = $this->code[$this->EXTENDED_4];
} else {
$pos2 = array_search($v, $this->keys);
$indcheck[] = $pos2;
$data[] = $this->code[$pos2];
}
}
}
} else {
$indcheck[] = $pos;
$data[] = $this->code[$pos];
}
}
$this->setData(array($indcheck, $data));
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
if(!empty($this->errorText)) {
$error = explode("\n", trim($this->errorText));
$c = count($error);
for($i = 0; $i < $c; $i++) {
$this->drawError($im, $error[$i]);
}
} else {
$c = count($this->data);
if($c === 0) {
$this->drawError($im, 'No text has been entered.');
} else {
// Starting *
$this->drawChar($im, $this->code[$this->starting], true);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->data[$i], true);
}
// Checksum
$c = count($this->checksumValue);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->code[$this->checksumValue[$i]], true);
}
// Ending *
$this->drawChar($im, $this->code[$this->ending], true);
// Draw a Final Bar
$this->drawChar($im, '0', true);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$startlength = 9 * $this->scale;
$textlength = 9 * count($this->data) * $this->scale;
$checksumlength = 2 * 9 * $this->scale;
$endlength = 9 * $this->scale + $this->scale; // + final bar
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Checksum
// First CheckSUM "C"
// The "C" checksum character is the modulo 47 remainder of the sum of the weighted
// value of the data characters. The weighting value starts at "1" for the right-most
// data character, 2 for the second to last, 3 for the third-to-last, and so on up to 20.
// After 20, the sequence wraps around back to 1.
// Second CheckSUM "K"
// Same as CheckSUM "C" but we count the CheckSum "C" at the end
// After 15, the sequence wraps around back to 1.
$sequence_multiplier = array(20, 15);
$this->checksumValue = array();
$indcheck = $this->indcheck;
for($z = 0; $z < 2; $z++) {
$checksum = 0;
for($i = count($indcheck), $j = 0; $i > 0; $i--, $j++) {
$multiplier = $i % $sequence_multiplier[$z];
if($multiplier === 0) {
$multiplier = $sequence_multiplier[$z];
}
$checksum += $indcheck[$j] * $multiplier;
}
$this->checksumValue[$z] = $checksum % 47;
$indcheck[] = $this->checksumValue[$z];
}
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
$ret = '';
$c = count($this->checksumValue);
for($i = 0; $i < $c; $i++) {
$ret .= $this->keys[$this->checksumValue[$i]];
}
return $ret;
}
return false;
}
/**
* Saves data into the classes.
*
* This method will save data, calculate real column number
* (if -1 was selected), the real error level (if -1 was
* selected)... It will add Padding to the end and generate
* the error codes.
*
* @param array $data
*/
function setData($data) {
$this->indcheck = $data[0];
$this->data = $data[1];
$this->calculateChecksum();
}
function getExtendedVersion($char) {
$o = ord($char);
if($o === 0)
return '%U';
elseif($o >= 1 && $o <= 26)
return '$' . chr($o + 64);
elseif(($o >= 33 && $o <= 44) || $o === 47 || $o === 48)
return '/' . chr($o + 32);
elseif($o >= 97 && $o <= 122)
return '+' . chr($o - 32);
elseif($o >= 27 && $o <= 31)
return '%' . chr($o + 38);
elseif($o >= 59 && $o <= 63)
return '%' . chr($o + 11);
elseif($o >= 91 && $o <= 95)
return '%' . chr($o - 16);
elseif($o >= 123 && $o <= 127)
return '%' . chr($o - 43);
elseif($o === 64)
return '%V';
elseif($o === 96)
return '%W';
elseif($o > 127)
return false;
else
return $char;
}
};
?>

View File

@@ -0,0 +1,342 @@
<?php
/**
* BCGean13.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - EAN-13
*
* EAN-13 contains
* - 2 system digits (1 not displayed but coded with parity)
* - 5 manufacturer code digits
* - 5 product digits
* - 1 checksum digit
*
* The checksum is always displayed.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Fix padding for the barcode
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.3.0 13 apr 2007 Jean-Sébastien Goupil Move ISBN implementation to isbn.php
* v1.2.3pl1 11 mar 2006 Jean-Sébastien Goupil Correct getMaxWidth if ISBN
* v1.2.3 6 feb 2006 Jean-Sébastien Goupil Fix label position + Using correctly static method
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil Enhance rapidity
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGean13.barcode.php,v 1.14 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.13
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGean13 extends BCGBarcode1D {
var $codeParity = array();
/**
* Constructor
*/
function BCGean13() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
// Left-Hand Odd Parity starting with a space
// Left-Hand Even Parity is the inverse (0=0012) starting with a space
// Right-Hand is the same of Left-Hand starting with a bar
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
// Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit
$this->codeParity = array(
array(0,0,0,0,0), /* 0 */
array(0,1,0,1,1), /* 1 */
array(0,1,1,0,1), /* 2 */
array(0,1,1,1,0), /* 3 */
array(1,0,0,1,1), /* 4 */
array(1,1,0,0,1), /* 5 */
array(1,1,1,0,0), /* 6 */
array(1,0,1,0,1), /* 7 */
array(1,0,1,1,0), /* 8 */
array(1,1,0,1,0) /* 9 */
);
}
function parse($text) {
BCGBarcode1D::parse($text);
$this->setLabelOffset();
}
function setFont($font) {
BCGBarcode1D::setFont($font);
$this->setLabelOffset();
}
function setLabel($label) {
BCGBarcode1D::setLabel($label);
$this->setLabelOffset();
}
function setOffsetX($offsetX) {
BCGBarcode1D::setOffsetX($offsetX);
$this->setLabelOffset();
}
function setScale($scale) {
BCGBarcode1D::setScale($scale);
$this->setLabelOffset();
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
if($this->isCharsAllowed($im)) {
if($this->isLengthCorrect($im)) {
$this->drawBars($im);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$startlength = 3 * $this->scale;
$centerlength = 5 * $this->scale;
$textlength = 12 * 7 * $this->scale;
$endlength = 3 * $this->scale;
return array($p[0] + $startlength + $centerlength + $textlength + $endlength, $p[1]);
}
function setLabelOffset() {
$label = $this->getLabel();
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$f = $this->textfont; // clone
$f->setText(substr($label, 0, 1));
$val = ($f->getWidth() + 5) / $this->scale;
if($val > $this->offsetX) {
$this->offsetX = $val;
}
} elseif($this->textfont !== 0) {
$val = (imagefontwidth($this->textfont) + 2) / $this->scale;
if($val > $this->offsetX) {
$this->offsetX = $val;
}
}
}
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$odd = true;
$this->checksumValue = 0;
$c = strlen($this->text);
for($i = $c; $i > 0; $i--) {
if($odd === true) {
$multiplier = 3;
$odd = false;
} else {
$multiplier = 1;
$odd = true;
}
if(!isset($this->keys[$this->text[$i - 1]])) {
return;
}
$this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$this->checksumValue = (10 - $this->checksumValue % 10) % 10;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
function isCharsAllowed(&$im) {
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
return false;
}
}
return true;
}
function isLengthCorrect(&$im) {
$c = strlen($this->text);
// If we have 13 chars just flush the last one
if($c === 13) {
$this->text = substr($this->text, 0, 12);
return true;
} elseif($c === 12) {
return true;
}
$this->drawError($im, 'Must provide 12 or 13 digits.');
return false;
}
function drawBars(&$im) {
// Checksum
$this->calculateChecksum();
$temp_text = $this->text . $this->keys[$this->checksumValue];
// Starting Code
$this->drawChar($im, '000', true);
// Draw Second Code
$this->drawChar($im, $this->findCode($temp_text[1]), false);
// Draw Manufacturer Code
for($i = 0; $i < 5; $i++) {
$this->drawChar($im, BCGean13::inverse($this->findCode($temp_text[$i + 2]), $this->codeParity[(int)$temp_text[0]][$i]), false);
}
// Draw Center Guard Bar
$this->drawChar($im, '00000', false);
// Draw Product Code
for($i = 7; $i < 13; $i++) {
$this->drawChar($im, $this->findCode($temp_text[$i]), true);
}
// Draw Right Guard Bar
$this->drawChar($im, '000', true);
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
if($this->label !== $this->AUTO_LABEL) {
BCGBarcode1D::drawText($im);
} elseif($this->label !== '') {
$temp_text = $this->text . $this->keys[$this->checksumValue];
if (is_a($this->textfont, 'BCGFont')) {
$code1 = 0;
$code2 = 0;
$this->textfont->setText($temp_text);
$this->drawExtendedBars($im, $this->textfont->getHeight(), $code1, $code2);
// We need to separate the text, one on the left and one on the right and one starting
$text0 = substr($temp_text, 0, 1);
$text1 = substr($temp_text, 1, 6);
$text2 = substr($temp_text, 7, 6);
$font0 = $this->textfont; // clone
$font1 = $this->textfont; // clone
$font2 = $this->textfont; // clone
$font0->setText($text0);
$font1->setText($text1);
$font2->setText($text2);
$xPosition0 = $this->offsetX * $this->scale - $font0->getWidth() - 4; // -4 is just for beauty
$yPosition0 = $this->thickness * $this->scale + $font0->getHeight() / 2 + $this->offsetY * $this->scale;
$xPosition1 = ($this->scale * 44 - $font1->getWidth()) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$xPosition2 = ($this->scale * 44 - $font1->getWidth()) / 2 + $code2 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->textfont->getHeight() + $this->SIZE_SPACING_FONT + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
$font0->draw($im, $text_color, $xPosition0, $yPosition0);
$font1->draw($im, $text_color, $xPosition1, $yPosition);
$font2->draw($im, $text_color, $xPosition2, $yPosition);
} elseif($this->textfont !== 0) {
$code1 = 0;
$code2 = 0;
$this->drawExtendedBars($im, 9, $code1, $code2);
$startPosition = 10;
$xPosition0 = $this->offsetX * $this->scale - imagefontwidth($this->textfont);
$yPosition0 = $this->thickness * $this->scale - imagefontheight($this->textfont) / 2 + $this->offsetY * $this->scale;
$xPosition1 = ($this->scale * 44 - imagefontwidth($this->textfont) * 6) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$xPosition2 = ($this->scale * 44 - imagefontwidth($this->textfont) * 6) / 2 + $code2 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + 1 * $this->scale + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
imagechar($im, $this->textfont, $xPosition0, $yPosition0, $temp_text[0], $text_color);
imagestring($im, $this->textfont, $xPosition1, $yPosition, substr($temp_text, 1, 6), $text_color);
imagestring($im, $this->textfont, $xPosition2, $yPosition, substr($temp_text, 7, 6), $text_color);
}
}
}
function drawExtendedBars(&$im, $plus, &$code1, &$code2) {
$rememberX = $this->positionX;
$rememberH = $this->thickness;
// We increase the bars
$this->thickness = $this->thickness + ceil($plus / $this->scale);
$this->positionX = 0;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
$code1 = $this->positionX;
// Center Guard Bar
$this->positionX += 44;
$this->DrawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->DrawSingleBar($im, $this->COLOR_FG);
// Last Bars
$code2 = $this->positionX;
$this->positionX += 44;
$this->DrawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->DrawSingleBar($im, $this->COLOR_FG);
$this->positionX = $rememberX;
$this->thickness = $rememberH;
}
function inverse($text, $inverse = 1) { // static
if($inverse === 1) {
$text = strrev($text);
}
return $text;
}
};
?>

View File

@@ -0,0 +1,238 @@
<?php
/**
* BCGean8.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - EAN-8
*
* EAN-8 contains
* - 4 digits
* - 3 digits
* - 1 checksum
*
* The checksum is always displayed.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Fix padding for the barcode
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3 6 feb 2006 Jean-Sébastien Goupil Fix label position
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil Enhance rapidity
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGean8.barcode.php,v 1.11 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.12
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGean8 extends BCGBarcode1D {
/**
* Constructor
*/
function BCGean8() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
// Left-Hand Odd Parity starting with a space
// Right-Hand is the same of Left-Hand starting with a bar
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must contain 7 chars
if($c !== 7) {
$this->drawError($im, 'Must contain 7 chars, the 8th digit is automatically added.');
$error_stop = true;
}
if($error_stop === false) {
// Checksum
$this->calculateChecksum();
$temp_text = $this->text . $this->keys[$this->checksumValue];
// Starting Code
$this->drawChar($im, '000', true);
// Draw First 4 Chars (Left-Hand)
for($i = 0; $i < 4; $i++) {
$this->drawChar($im, $this->findCode($temp_text[$i]), false);
}
// Draw Center Guard Bar
$this->drawChar($im, '00000', false);
// Draw Last 4 Chars (Right-Hand)
for($i = 4; $i < 8; $i++) {
$this->drawChar($im, $this->findCode($temp_text[$i]), true);
}
// Draw Right Guard Bar
$this->drawChar($im, '000', true);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$startlength = 3 * $this->scale;
$centerlength = 5 * $this->scale;
$textlength = 8 * 7 * $this->scale;
$endlength = 3 * $this->scale;
return array($p[0] + $startlength + $centerlength + $textlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$odd = true;
$this->checksumValue = 0;
$c = strlen($this->text);
for($i = $c; $i > 0; $i--) {
if($odd === true) {
$multiplier = 3;
$odd = false;
} else {
$multiplier = 1;
$odd = true;
}
if(!isset($this->keys[$this->text[$i - 1]])) {
return;
}
$this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$this->checksumValue = (10 - $this->checksumValue % 10) % 10;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
if($this->label !== $this->AUTO_LABEL) {
BCGBarcode1D::drawText($im);
} elseif($this->label !== '') {
$temp_text = $this->text . $this->keys[$this->checksumValue];
if(is_a($this->textfont, 'BCGFont')) {
$code1 = 0;
$code2 = 0;
$this->textfont->setText($temp_text);
$this->drawExtendedBars($im, $this->textfont->getHeight(), $code1, $code2);
// We need to separate the text, one on the left and one on the right
$text1 = substr($temp_text, 0, 4);
$text2 = substr($temp_text, 4, 4);
$font1 = $this->textfont; // clone
$font2 = $this->textfont; // clone
$font1->setText($text1);
$font2->setText($text2);
// The $this->res offset is to center without thinking of the white space in the guard
$xPosition1 = ($this->scale * 30 - $font1->getWidth()) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$xPosition2 = ($this->scale * 30 - $font2->getWidth()) / 2 + $code2 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->textfont->getHeight() + $this->SIZE_SPACING_FONT + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
$font1->draw($im, $text_color, $xPosition1, $yPosition);
$font2->draw($im, $text_color, $xPosition2, $yPosition);
} elseif($this->textfont !== 0) {
$code1 = 0;
$code2 = 0;
$this->drawExtendedBars($im, 9, $code1, $code2);
$xPosition1 = ($this->scale * 30 - imagefontwidth($this->textfont) * 4) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$xPosition2 = ($this->scale * 30 - imagefontwidth($this->textfont) * 4) / 2 + $code2 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + 1 * $this->scale + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
imagestring($im, $this->textfont, $xPosition1, $yPosition, substr($temp_text, 0, 4), $text_color);
imagestring($im, $this->textfont, $xPosition2, $yPosition, substr($temp_text, 4, 4), $text_color);
}
}
}
function drawExtendedBars(&$im, $plus, &$code1, &$code2) {
$rememberX = $this->positionX;
$rememberH = $this->thickness;
// We increase the bars
$this->thickness = $this->thickness + ceil($plus / $this->scale);
$this->positionX = 0;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
$code1 = $this->positionX;
// Center Guard Bar
$this->positionX += 30;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
// Last Bars
$code2 = $this->positionX;
$this->positionX += 30;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX = $rememberX;
$this->thickness = $rememberH;
}
};
?>

View File

@@ -0,0 +1,592 @@
<?php
/**
* BCGgs1128.barcode.php
*--------------------------------------------------------------------
*
* Calculate the GS1-128 based on the Code-128 encoding.
*
*--------------------------------------------------------------------
* Revision History
* V2.2.0 10 feb 2010 Kevin Gilbert, reviewed by Jean-Sébastien Goupil, new version
*--------------------------------------------------------------------
* $Id: BCGgs1128.barcode.php,v 1.1 2010/02/14 00:25:14 jsgoupil Exp $<
* PHP5-Revision: 1.1
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGcode128.barcode.php');
class BCGgs1128 extends BCGcode128 {
var $KIND_OF_DATA = 0; // const
var $MINLENGTH = 1; // const
var $MAXLENGTH = 2; // const
var $CHECKSUM = 3; // const
var $NUMERIC = 0; // const
var $ALPHA_NUMERIC = 1; // const
var $DATE_YYMMDD = 2; // const
var $ID = 0; // const
var $CONTENT = 1; // const
var $MAX_ID_FORMATED = 6; // const
var $MAX_ID_NOT_FORMATED = 4; // const
var $MAX_GS1128_CHARS = 48; // const
var $errorTextGS1128;
var $strictMode;
var $identifiersId = array();
var $identifiersContent = array();
var $identifiersAi = array();
/**
* Constructor
*
* @param char $start
*/
function BCGgs1128($start = NULL) { // public
if($start === NULL) {
$start = 'C';
}
BCGcode128::BCGcode128($start);
/* Application Identifiers (AIs) */
/*
array ( KIND_OF_DATA , MINLENGTH , MAXLENGTH , CHECKSUM )
KIND_OF_DATA: NUMERIC , ALPHA_NUMERIC or DATE_YYMMDD
CHECKSUM: bool (true / false)
*/
$this->identifiersAi = array(
'00' => array($this->NUMERIC, 18, 18, true),
'01' => array($this->NUMERIC, 14, 14, true),
'02' => array($this->NUMERIC, 14, 14, true),
'10' => array($this->ALPHA_NUMERIC, 1, 20, false),
'11' => array($this->DATE_YYMMDD, 6, 6, false),
'12' => array($this->DATE_YYMMDD, 6, 6, false),
'13' => array($this->DATE_YYMMDD, 6, 6, false),
'15' => array($this->DATE_YYMMDD, 6, 6, false),
'17' => array($this->DATE_YYMMDD, 6, 6, false),
'20' => array($this->NUMERIC, 2, 2, false),
'21' => array($this->ALPHA_NUMERIC, 1, 20, false),
'240' => array($this->ALPHA_NUMERIC, 1, 30, false),
'241' => array($this->ALPHA_NUMERIC, 1, 30, false),
'250' => array($this->ALPHA_NUMERIC, 1, 30, false),
'251' => array($this->ALPHA_NUMERIC, 1, 30, false),
'253' => array($this->NUMERIC, 14, 30, false),
'30' => array($this->NUMERIC, 1, 8, false),
'310y' => array($this->NUMERIC, 6, 6, false),
'311y' => array($this->NUMERIC, 6, 6, false),
'312y' => array($this->NUMERIC, 6, 6, false),
'313y' => array($this->NUMERIC, 6, 6, false),
'314y' => array($this->NUMERIC, 6, 6, false),
'315y' => array($this->NUMERIC, 6, 6, false),
'316y' => array($this->NUMERIC, 6, 6, false),
'320y' => array($this->NUMERIC, 6, 6, false),
'321y' => array($this->NUMERIC, 6, 6, false),
'322y' => array($this->NUMERIC, 6, 6, false),
'323y' => array($this->NUMERIC, 6, 6, false),
'324y' => array($this->NUMERIC, 6, 6, false),
'325y' => array($this->NUMERIC, 6, 6, false),
'326y' => array($this->NUMERIC, 6, 6, false),
'327y' => array($this->NUMERIC, 6, 6, false),
'328y' => array($this->NUMERIC, 6, 6, false),
'329y' => array($this->NUMERIC, 6, 6, false),
'330y' => array($this->NUMERIC, 6, 6, false),
'331y' => array($this->NUMERIC, 6, 6, false),
'332y' => array($this->NUMERIC, 6, 6, false),
'333y' => array($this->NUMERIC, 6, 6, false),
'334y' => array($this->NUMERIC, 6, 6, false),
'335y' => array($this->NUMERIC, 6, 6, false),
'336y' => array($this->NUMERIC, 6, 6, false),
'337y' => array($this->NUMERIC, 6, 6, false),
'340y' => array($this->NUMERIC, 6, 6, false),
'341y' => array($this->NUMERIC, 6, 6, false),
'342y' => array($this->NUMERIC, 6, 6, false),
'343y' => array($this->NUMERIC, 6, 6, false),
'344y' => array($this->NUMERIC, 6, 6, false),
'345y' => array($this->NUMERIC, 6, 6, false),
'346y' => array($this->NUMERIC, 6, 6, false),
'347y' => array($this->NUMERIC, 6, 6, false),
'348y' => array($this->NUMERIC, 6, 6, false),
'349y' => array($this->NUMERIC, 6, 6, false),
'350y' => array($this->NUMERIC, 6, 6, false),
'351y' => array($this->NUMERIC, 6, 6, false),
'352y' => array($this->NUMERIC, 6, 6, false),
'353y' => array($this->NUMERIC, 6, 6, false),
'354y' => array($this->NUMERIC, 6, 6, false),
'355y' => array($this->NUMERIC, 6, 6, false),
'356y' => array($this->NUMERIC, 6, 6, false),
'357y' => array($this->NUMERIC, 6, 6, false),
'360y' => array($this->NUMERIC, 6, 6, false),
'361y' => array($this->NUMERIC, 6, 6, false),
'362y' => array($this->NUMERIC, 6, 6, false),
'363y' => array($this->NUMERIC, 6, 6, false),
'364y' => array($this->NUMERIC, 6, 6, false),
'365y' => array($this->NUMERIC, 6, 6, false),
'366y' => array($this->NUMERIC, 6, 6, false),
'367y' => array($this->NUMERIC, 6, 6, false),
'368y' => array($this->NUMERIC, 6, 6, false),
'369y' => array($this->NUMERIC, 6, 6, false),
'37' => array($this->NUMERIC, 1, 8, false),
'390y' => array($this->NUMERIC, 1, 15, false),
'391y' => array($this->NUMERIC, 4, 18, false),
'392y' => array($this->NUMERIC, 1, 15, false),
'393y' => array($this->NUMERIC, 4, 18, false),
'400' => array($this->ALPHA_NUMERIC, 1, 30, false),
'401' => array($this->ALPHA_NUMERIC, 1, 30, false),
'402' => array($this->NUMERIC, 17, 17, false),
'403' => array($this->ALPHA_NUMERIC, 1, 30, false),
'410' => array($this->NUMERIC, 13, 13, true),
'411' => array($this->NUMERIC, 13, 13, true),
'412' => array($this->NUMERIC, 13, 13, true),
'413' => array($this->NUMERIC, 13, 13, true),
'414' => array($this->NUMERIC, 13, 13, true),
'415' => array($this->NUMERIC, 13, 13, true),
'420' => array($this->ALPHA_NUMERIC, 1, 20, false),
'421' => array($this->ALPHA_NUMERIC, 4, 12, false),
'422' => array($this->NUMERIC, 3, 3, false),
'8001' => array($this->NUMERIC, 14, 14, false),
'8002' => array($this->ALPHA_NUMERIC, 1, 20, false),
'8003' => array($this->ALPHA_NUMERIC, 15, 30, false),
'8004' => array($this->ALPHA_NUMERIC, 1, 30, false),
'8005' => array($this->NUMERIC, 6, 6, false),
'8006' => array($this->NUMERIC, 18, 18, false),
'8007' => array($this->ALPHA_NUMERIC, 1, 30, false),
'8018' => array($this->NUMERIC, 18, 18, false),
'8020' => array($this->ALPHA_NUMERIC, 1, 25, false),
'8100' => array($this->NUMERIC, 6, 6, false),
'8101' => array($this->NUMERIC, 10, 10, false),
'8102' => array($this->NUMERIC, 2, 2, false),
'90' => array($this->ALPHA_NUMERIC, 1, 30, false),
'91' => array($this->ALPHA_NUMERIC, 1, 30, false),
'92' => array($this->ALPHA_NUMERIC, 1, 30, false),
'93' => array($this->ALPHA_NUMERIC, 1, 30, false),
'94' => array($this->ALPHA_NUMERIC, 1, 30, false),
'95' => array($this->ALPHA_NUMERIC, 1, 30, false),
'96' => array($this->ALPHA_NUMERIC, 1, 30, false),
'97' => array($this->ALPHA_NUMERIC, 1, 30, false),
'98' => array($this->ALPHA_NUMERIC, 1, 30, false),
'99' => array($this->ALPHA_NUMERIC, 1, 30, false)
);
$this->setStrictMode(true);
$this->setTilde(true);
}
/**
* Enables or disables the strict mode
*
* @param bool strictMode
*/
function setStrictMode($strictMode) { // public
$this->strictMode = $strictMode;
}
/**
* Parses Text
*
* @param string $text
*/
function parse($text) { // public
parent::parse($this->parseGs1128($text));
$this->errorText .= $this->errorTextGS1128;
}
/**
* Formats data for gs1-128
*
* @return string
*/
function formatGs1128() { // private
$formatedText = '~F1';
$formatedLabel = '';
$c = count($this->identifiersId);
for($i = 0; $i < $c; $i++) {
if($i > 0) {
$formatedLabel .= ' ';
}
$formatedLabel .= '(' . $this->identifiersId[$i] . ')';
$formatedText .= $this->identifiersId[$i];
$formatedLabel .= $this->identifiersContent[$i];
$formatedText .= $this->identifiersContent[$i];
if(isset($this->identifiersAi[$this->identifiersId[$i]])) {
$ai_data = $this->identifiersAi[$this->identifiersId[$i]];
} elseif(isset($this->identifiersId[$i][3])) {
$identifierWithVar = substr($this->identifiersId[$i], 0, -1) . 'y';
$ai_data = isset($this->identifiersAi[$identifierWithVar]) ? $this->identifiersAi[$identifierWithVar] : NULL;
} else {
$ai_data = NULL;
}
/* We'll check if we need to add a ~F1 (<GS>) char */
/* If we use the legacy mode, we always add a ~F1 (<GS>) char between AIs */
if($ai_data !== NULL) {
if(strlen($this->identifiersContent[$i]) < $ai_data[$this->MAXLENGTH] && ($i + 1) !== $c || !$this->strictMode && ($i + 1) !== $c) {
$formatedText .= '~F1';
}
}
}
if((strlen($formatedText) - 3) > $this->MAX_GS1128_CHARS) {
$this->errorTextGS1128 = 'The barcode can\'t be bigger than ' . $this->MAX_GS1128_CHARS . ' characters.';
}
$this->label = $formatedLabel;
return $formatedText;
}
/**
* Parses the text to gs1-128
*
* @param mixed $text
* @return mixed
*/
function parseGs1128($text) { // private
/* We format correctly what the user gives */
if(is_array($text)) {
$formatArray = array();
foreach($text as $content) {
if(is_array($content)) { /* double array */
if(count($content) === 2) {
if(is_array($content[$this->ID]) || is_array($content[$this->CONTENT])) {
$this->errorTextGS1128 = 'Double arrays can\'t contain arrays.';
return false;
} else {
$formatArray[] = '(' . $content[$this->ID] . ')' . $content[$this->CONTENT];
}
} else {
$this->errorTextGS1128 = 'Double arrays must contain 2 values.';
return false;
}
} else { /* simple array */
$formatArray[] = $content;
}
}
unset($text);
$text = $formatArray;
} else { /* string */
$text = array($text);
}
$textCount = count($text);
for($cmpt = 0; $cmpt < $textCount; $cmpt++) {
/* We parse the content of the array */
if(!$this->parseContent($text[$cmpt])) {
return false;
}
}
return $this->formatGs1128();
}
/**
* Splits the id and the content for each application identifiers (AIs)
*
* @param string $text
* @param int $cmpt
*
* @return bool
*/
function parseContent($text) { // private
/* $yAlreadySet has 3 states: */
/* null: There is no variable in the ID; true: the variable is already set; false: the variable is not set yet; */
$yAlreadySet = NULL;
$realNameId = NULL;
$separatorsFound = 0;
$checksumAdded = 0;
$decimalPointRemoved = 0;
$toParse = str_replace('~F1' ,chr(29), $text);
$nbCharToParse = strlen($toParse);
$isFormated = $toParse[0] === '(' ? true : false;
$maxCharId = $isFormated ? $this->MAX_ID_FORMATED : $this->MAX_ID_NOT_FORMATED;
$id = strtolower(substr($toParse, 0, min($maxCharId, $nbCharToParse)));
$id = $isFormated ? $this->findIdFormated($id, $yAlreadySet, $realNameId) : $this->findIdNotFormated($id, $yAlreadySet, $realNameId);
if($id === false) {
return false;
}
$nbCharId = $isFormated ? strlen($id) + 2 : strlen($id);
$n = min($this->identifiersAi[$realNameId][$this->MAXLENGTH], $nbCharToParse);
$content = substr($toParse, $nbCharId, $n);
/* If we have an AI with an "y" var, we check if there is a decimal point in the next *MAXLENGTH* characters */
/* if there is one, we take an extra character */
if($yAlreadySet !== NULL) {
if(strpos($content, '.') !== false || strpos($content, ',') !== false) {
$n++;
if($n <= $nbCharToParse) {
/* We take an extra char */
$content = substr($toParse, $nbCharId, $n);
}
}
}
/* We check for separator */
$separator = strpos($content, chr(29));
if($separator !== false) {
$content = substr($content, 0, $separator);
$separatorsFound++;
}
/* We check the conformity */
if(!$this->checkConformity($content, $id, $realNameId)) {
return false;
}
/* We check the checksum */
if(!$this->checkChecksum($content, $id, $realNameId, $checksumAdded)) {
return false;
}
/* We check the vars */
if(!$this->checkVars($content, $id, $yAlreadySet, $decimalPointRemoved)) {
return false;
}
$this->identifiersId[] = $id;
$this->identifiersContent[] = $content;
$nbCharLastContent = (((strlen($content) + $nbCharId) - $checksumAdded) + $decimalPointRemoved) + $separatorsFound;
if($nbCharToParse - $nbCharLastContent > 0) {
/* If there is more than one content in this array, we parse again */
$otherContent = substr($toParse, $nbCharLastContent, $nbCharToParse);
$nbCharOtherContent = strlen($otherContent);
if($otherContent[0] === chr(29)) {
$otherContent = substr($otherContent, 1);
$nbCharOtherContent--;
}
if($nbCharOtherContent > 0) {
$text = $otherContent;
$this->parseContent($text);
}
}
return true;
}
/**
* Checks if an id exists
*
* @param string $id
* @param bool $yAlreadySet
* @param string $realNameId
*
* @return bool
*/
function idExists($id, &$yAlreadySet, &$realNameId) { // private
$yFound = isset($id[3]) && $id[3] === 'y';
$idVarAdded = substr($id, 0, -1) . 'y';
if(isset($this->identifiersAi[$id])) {
if($yFound) {
$yAlreadySet = false;
}
$realNameId = $id;
return true;
} elseif(!$yFound && isset($this->identifiersAi[$idVarAdded])) {
/* if the id don't exist, we try to find this id with "y" at the last char */
$yAlreadySet = true;
$realNameId = $idVarAdded;
return true;
}
return false;
}
/**
* Finds ID with formated content
*
* @param string $id
* @param bool $yAlreadySet
* @param string $realNameId
* @return mixed
*/
function findIdFormated($id, &$yAlreadySet, &$realNameId) { // private
$pos = strpos($id, ')');
if($pos === false) {
$this->errorTextGS1128 = 'Identifiers must have no more than 4 characters.';
return false;
} else {
if($pos < 3) {
$this->errorTextGS1128 = 'Identifiers must have at least 2 characters.';
return false;
}
$id = substr($id, 1, $pos - 1);
if($this->idExists($id, $yAlreadySet, $realNameId)) {
return $id;
} else {
$this->errorTextGS1128 = 'The identifier ' . $id . ' doesn\'t exist.';
return false;
}
}
}
/**
* Finds ID with non-formated content
*
* @param string $id
* @param bool $yAlreadySet
* @param string $realNameId
* @return mixed
*/
function findIdNotFormated($id, &$yAlreadySet, &$realNameId) { // private
$tofind = $id;
while(strlen($tofind) >= 2) {
if($this->idExists($tofind, $yAlreadySet, $realNameId)) {
return $tofind;
} else {
$tofind = substr($tofind, 0, -1);
}
}
$this->errorTextGS1128 = 'Error in formatting, can\'t find an identifier.';
return false;
}
/**
* Checks confirmity of the content
*
* @param string $content
* @param string $id
* @param string $realNameId
* @return bool
*/
function checkConformity(&$content, $id, $realNameId) { // private
switch($this->identifiersAi[$realNameId][$this->KIND_OF_DATA]) {
case $this->NUMERIC:
$content = str_replace(',', '.', $content);
if(!preg_match("/^[0-9.]+$/", $content)) {
$this->errorTextGS1128 = 'The value of "' . $id . '" must be numerical.';
return false;
}
break;
case $this->DATE_YYMMDD:
$valid_date = true;
if(preg_match("/^[0-9]{6}$/", $content)) {
$year = substr($content, 0, 2);
$month = substr($content, 2, 2);
$day = substr($content, 4, 2);
/* day can be 00 if we only need month and year */
if(intval($month) < 1 || intval($month) > 12 || intval($day) < 0 || intval($day) > 31) {
$valid_date = false;
}
} else {
$valid_date = false;
}
if(!$valid_date) {
$this->errorTextGS1128 = 'The value of "' . $id . '" must be in YYMMDD format.';
return false;
}
break;
}
/* We check the length of the content */
$nbCharContent = strlen($content);
$checksumChar = 0;
$minlengthContent = $this->identifiersAi[$realNameId][$this->MINLENGTH];
$maxlengthContent = $this->identifiersAi[$realNameId][$this->MAXLENGTH];
if($this->identifiersAi[$realNameId][$this->CHECKSUM]) {
$checksumChar++;
}
if($nbCharContent < ($minlengthContent - $checksumChar)) {
if($minlengthContent === $maxlengthContent) {
$this->errorTextGS1128 = 'The value of "' . $id . '" must contain ' . $minlengthContent . ' character(s).';
return false;
} else {
$this->errorTextGS1128 = 'The value of "' . $id . '" must contain between ' . $minlengthContent . ' and ' . $maxlengthContent . ' character(s).';
return false;
}
}
return true;
}
/**
* Verifies the checksum
*
* @param string $content
* @param string $id
* @param int $realNameId
* @param int $checksumAdded
* @return bool
*/
function checkChecksum(&$content, $id, $realNameId, &$checksumAdded) { // private
if($this->identifiersAi[$realNameId][$this->CHECKSUM]) {
$nbCharContent = strlen($content);
$minlengthContent = $this->identifiersAi[$realNameId][$this->MINLENGTH];
if($nbCharContent === ($minlengthContent - 1)) {
/* we need to calculate the checksum */
$content .= $this->calculateChecksumMod10($content);
$checksumAdded++;
} elseif($nbCharContent === $minlengthContent) {
/* we need to check the checksum */
$checksum = $this->calculateChecksumMod10(substr($content, 0, -1));
if(intval($content[$nbCharContent - 1]) !== $checksum) {
$this->errorTextGS1128 = 'The checksum of "(' . $id . ') ' . $content . '" must be: ' . $checksum;
return false;
}
}
}
return true;
}
/**
* Checks vars "y"
*
* @param string $content
* @param string $id
* @param bool $yAlreadySet
* @param int $decimalPointRemoved
* @return bool
*/
function checkVars(&$content, &$id, $yAlreadySet, &$decimalPointRemoved) { // private
$nbCharContent = strlen($content);
/* We check for "y" var in AI */
if($yAlreadySet) {
/* We'll check if we have a decimal point */
if(strpos($content, '.') !== false) {
$this->errorTextGS1128 = 'If you do not use any "y" variable, you have to insert a whole number.';
return false;
}
} elseif($yAlreadySet !== NULL) {
/* We need to replace the "y" var with the position of the decimal point */
$pos = strpos($content, '.');
if($pos === false) {
$this->errorTextGS1128 = 'If you use a "y" variable, you have to insert a decimal number.';
return false;
} else {
$id = str_replace('y', $nbCharContent - ($pos + 1), strtolower($id));
$content = str_replace('.', '', $content);
$decimalPointRemoved++;
}
}
return true;
}
/**
* Checksum Mod10
* @param int $content
* @return int
*/
function calculateChecksumMod10($content) { // private
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$odd = true;
$checksumValue = 0;
$c = strlen($content);
for($i = $c; $i > 0; $i--) {
if($odd === true) {
$multiplier = 3;
$odd = false;
} else {
$multiplier = 1;
$odd = true;
}
$checksumValue += ($content[$i - 1] * $multiplier);
}
return (10 - $checksumValue % 10) % 10;
}
};
?>

View File

@@ -0,0 +1,164 @@
<?php
/**
* BCGi25.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Interleaved 2 of 5
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil Correct Checksum
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGi25.barcode.php,v 1.8 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.10
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGi25 extends BCGBarcode1D {
var $checksum;
/**
* Constructor
*/
function BCGi25() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
$this->code = array(
'00110', /* 0 */
'10001', /* 1 */
'01001', /* 2 */
'11000', /* 3 */
'00101', /* 4 */
'10100', /* 5 */
'01100', /* 6 */
'00011', /* 7 */
'10010', /* 8 */
'01010' /* 9 */
);
$this->setChecksum(false);
}
function setChecksum($checksum) {
$this->checksum = (bool)$checksum;
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must be even
if($c % 2 !== 0 && $this->checksum === false) {
$this->drawError($im, 'i25 must be even if checksum is false.');
$error_stop = true;
} elseif($c % 2 === 0 && $this->checksum === true) {
$this->drawError($im, 'i25 must be odd if checksum is true.');
$error_stop = true;
}
if($error_stop === false) {
$temp_text = $this->text;
// Checksum
if($this->checksum === true) {
$this->calculateChecksum();
$temp_text .= $this->keys[$this->checksumValue];
}
// Starting Code
$this->drawChar($im, '0000', true);
// Chars
$c = strlen($temp_text);
for($i = 0; $i < $c; $i += 2) {
$temp_bar = '';
$c2 = strlen($this->findCode($temp_text[$i]));
for($j = 0; $j < $c2; $j++) {
$temp_bar .= substr($this->findCode($temp_text[$i]), $j, 1);
$temp_bar .= substr($this->findCode($temp_text[$i + 1]), $j, 1);
}
$this->drawChar($im, $temp_bar, true);
}
// Ending Code
$this->drawChar($im, '100', true);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$textlength = 7 * strlen($this->text) * $this->scale;
$startlength = 4 * $this->scale;
$checksumlength = 0;
if($this->checksum === true) {
$checksumlength = 7 * $this->scale;
}
$endlength = 4 * $this->scale;
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "even" position,
// and assign odd/even to each character moving from right to left
// Even Position = 3, Odd Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$even = true;
$this->checksumValue = 0;
$c = strlen($this->text);
for($i = $c; $i > 0; $i--) {
if($even === true) {
$multiplier = 3;
$even = false;
} else {
$multiplier = 1;
$even = true;
}
$this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$this->checksumValue = (10 - $this->checksumValue % 10) % 10;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
};
?>

View File

@@ -0,0 +1,268 @@
<?php
/**
* BCGisbn.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - ISBN-10 and ISBN-13
*
* You can provide an ISBN with 10 digits with or without the checksum.
* You can provide an ISBN with 13 digits with or without the checksum.
* Calculate the ISBN based on the EAN-13 encoding.
*
* The checksum is always displayed.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.5 13 apr 2007 Jean-Sébastien Goupil
*--------------------------------------------------------------------
* $Id: BCGisbn.barcode.php,v 1.6 2010/02/14 00:25:14 jsgoupil Exp $
* PHP5-Revision: 1.7
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGean13.barcode.php');
class BCGisbn extends BCGean13 {
var $GS1_AUTO = 0; // const
var $GS1_PREFIX978 = 1; // const
var $GS1_PREFIX979 = 2; // const
var $gs1;
var $isbn_created;
var $isbn_text;
var $isbn_textfont;
var $forceOffsetY;
/**
* Constructor
*
* @param int $gs1
* @param string $isbn_text
* @param mixed $textfont2 BCGFont or int
*/
function BCGisbn($gs1 = 0, $isbn_text = '##!!AUTO_LABEL!!##', $isbn_font = null) {
BCGean13::BCGean13();
$this->forceOffsetY = false;
$this->setISBNFont($isbn_font);
$this->setISBNText($isbn_text);
$this->setGS1($gs1);
}
/**
* Saves Text
*
* @param string $text
*/
function parse($text) {
BCGBarcode1D::parse(str_replace(array('-', ' '), '', $text));
$this->createISBNText();
$this->setLabelOffset();
}
/**
* Sets the first numbers of the barcode.
* - GS1_AUTO: Adds 978 before the code
* - GS1_PREFIX978: Adds 978 before the code
* - GS1_PREFIX979: Adds 979 before the code
*
* @param int $gs1
*/
function setGS1($gs1) {
$gs1 = (int)$gs1;
if($gs1 !== $this->GS1_AUTO && $gs1 !== $this->GS1_PREFIX978 && $gs1 !== $this->GS1_PREFIX979) {
$gs1 = $this->GS1_AUTO;
}
$this->gs1 = $gs1;
}
/**
* Sets the font to write the ISBN text on the top of the barcode.
*
* @param mixed $font
*/
function setISBNFont($font) {
if(is_a($font, 'BCGFont')) {
$this->isbn_textfont = $font; // clone
} else if($font === null) {
$this->isbn_textfont = null;
} else {
$this->isbn_textfont = intval($font);
}
$this->setLabelOffset();
}
/**
* Sets the text for the ISBN value.
*
* @param string $isbn_text
*/
function setISBNText($text) {
$this->isbn_text = $text;
$this->createISBNText();
$this->setLabelOffset();
}
function setOffsetY($offsetY) {
BCGean13::setOffsetY($offsetY);
// We force the offsetY, so we won't position based on the label position
$this->forceOffsetY = true;
}
function getMaxSize() {
// We must compute the first digit calculating the width
$null = null;
$this->isLengthCorrect($null);
return BCGean13::getMaxSize();
}
function setLabelOffset() {
BCGean13::setLabelOffset();
if(!empty($this->isbn_created) && !$this->forceOffsetY) {
if(is_a($this->getISBNFont(), 'BCGFont')) {
$f = $this->getISBNFont(); // clone
$f->setText($this->isbn_created);
$val = ($f->getHeight() - $f->getUnderBaseline()) / $this->scale + $this->SIZE_SPACING_FONT;
$this->offsetY = $val;
} elseif($this->getISBNFont() !== 0) {
$val = (imagefontheight($this->getISBNFont()) + 2) / $this->scale;
$this->offsetY = $val;
}
}
}
function isCharsAllowed(&$im) {
$c = strlen($this->text);
// Special case, if we have 10 digits, the last one can be X
if($c === 10) {
if(array_search($this->text[9], $this->keys) === false && $this->text[9] !== 'X') {
$this->drawError($im, 'Char \'' . $this->text[9] . '\' not allowed.');
return false;
}
// Drop the last char
$this->text = substr($this->text, 0, 9);
}
return BCGean13::isCharsAllowed($im);
}
function isLengthCorrect(&$im) {
$c = strlen($this->text);
// If we have 13 chars just flush the last one
if($c === 13) {
$this->text = substr($this->text, 0, 12);
return true;
} elseif($c === 12) {
return true;
} elseif($c === 9 || $c === 10) {
if($c === 10) {
// Before dropping it, we check if it's legal
if(array_search($this->text[9], $this->keys) === false && $this->text[9] !== 'X') {
return false;
}
$this->text = substr($this->text, 0, 9);
}
if($this->gs1 === $this->GS1_AUTO || $this->gs1 === $this->GS1_PREFIX978) {
$this->text = '978' . $this->text;
} elseif($this->gs1 === $this->GS1_PREFIX979) {
$this->text = '979' . $this->text;
}
// We changed the start, recalculate the offset label
BCGean13::setLabelOffset();
return true;
} else {
if($im !== null) {
$this->drawError($im, 'Must provide 9, 10, 12 or 13 digits.');
}
return false;
}
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
BCGean13::drawText($im);
if(strlen($this->isbn_created) > 0) {
$pA = $this->getMaxSize();
$pB = BCGBarcode1D::getMaxSize();
$w = $pA[0] - $pB[0];
if(is_a($this->getISBNFont(), 'BCGFont')) {
$textfont = $this->getISBNFont(); // clone
$textfont->setText($this->isbn_created);
$xPosition = ($w / 2) - ($textfont->getWidth() / 2) + $this->offsetX * $this->scale;
$yPosition = $this->offsetY * $this->scale - $this->SIZE_SPACING_FONT;
$textfont->draw($im, $this->colorFg->allocate($im), $xPosition, $yPosition);
} elseif($this->getISBNFont() !== 0) {
$xPosition = ($w / 2) - (strlen($this->isbn_created) / 2) * imagefontwidth($this->getISBNFont()) + $this->offsetX * $this->scale;
$yPosition = $this->offsetY * $this->scale - $this->SIZE_SPACING_FONT - imagefontheight($this->getISBNFont());
imagestring($im, $this->getISBNFont(), $xPosition, $yPosition, $this->isbn_created, $this->colorFg->allocate($im));
}
}
}
function &getISBNFont() {
if($this->isbn_textfont === null) {
return $this->textfont;
} else {
return $this->isbn_textfont;
}
}
function createISBNText() {
if($this->isbn_text === $this->AUTO_LABEL && !empty($this->text)) {
// We try to create the ISBN Text... the hyphen really depends the ISBN agency.
// We just put one before the checksum and one after the GS1 if present.
$c = strlen($this->text);
if($c === 12 || $c === 13) {
// If we have 13 characters now, just transform it temporarily to find the checksum...
// Further in the code we take care of that anyway.
$lastCharacter = '';
if($c === 13) {
$lastCharacter = $this->text[12];
$this->text = substr($this->text, 0, 12);
}
$checksum = $this->processChecksum();
$this->isbn_created = 'ISBN ' . substr($this->text, 0, 3) . '-' . substr($this->text, 3, 9) . '-' . $checksum;
// Put the last character back
if($c === 13) {
$this->text .= $lastCharacter;
}
} elseif($c === 9 || $c === 10) {
$checksum = 0;
for($i = 10; $i >= 2; $i--) {
$checksum += $this->text[10 - $i] * $i;
}
$checksum = 11 - $checksum % 11;
if($checksum === 10) {
$checksum = 'X';
}
$this->isbn_created = 'ISBN ' . substr($this->text, 0, 9) . '-' . $checksum;
} else {
$this->isbn_created = '';
}
} else {
$this->isbn_created = $this->isbn_text;
}
}
};
?>

View File

@@ -0,0 +1,170 @@
<?php
/**
* BCGmsi.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - MSI Plessey
*
*--------------------------------------------------------------------
* Revision History
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Fix checksum 1 or 2
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil Enhance rapidity
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGmsi.barcode.php,v 1.9 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.10
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGmsi extends BCGBarcode1D {
var $checksum;
/**
* Constructor
*/
function BCGmsi() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
$this->code = array(
'01010101', /* 0 */
'01010110', /* 1 */
'01011001', /* 2 */
'01011010', /* 3 */
'01100101', /* 4 */
'01100110', /* 5 */
'01101001', /* 6 */
'01101010', /* 7 */
'10010101', /* 8 */
'10010110' /* 9 */
);
$this->setChecksum(0);
}
function setChecksum($checksum) {
$checksum = intval($checksum);
if($checksum < 0 && $checksum > 2) {
$checksum = 0;
}
$this->checksum = $checksum;
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Checksum
$this->calculateChecksum();
// Starting Code
$this->drawChar($im, '10', true);
// Chars
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->findCode($this->text[$i]), true);
}
$c = count($this->checksumValue);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->findCode($this->checksumValue[$i]), true);
}
// Ending Code
$this->drawChar($im, '010', true);
$this->drawText($im);
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$textlength = 12 * strlen($this->text) * $this->scale;
$startlength = 3 * $this->scale;
$checksumlength = $this->checksum * 12 * $this->scale;
$endlength = 4 * $this->scale;
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Forming a new number
// If the original number is even, we take all even position
// If the original number is odd, we take all odd position
// 123456 = 246
// 12345 = 135
// Multiply by 2
// Add up all the digit in the result (270 : 2+7+0)
// Add up other digit not used.
// 10 - (? Modulo 10). If result = 10, change to 0
$last_text = $this->text;
$this->checksumValue = array();
for($i = 0; $i < $this->checksum; $i++) {
$new_text = '';
$new_number = 0;
$c = strlen($last_text);
if($c % 2 === 0) { // Even
$starting = 1;
} else {
$starting = 0;
}
for($j = $starting; $j < $c; $j += 2) {
$new_text .= $last_text[$j];
}
$new_text = strval(intval($new_text) * 2);
$c2 = strlen($new_text);
for($j = 0; $j < $c2; $j++) {
$new_number += intval($new_text[$j]);
}
for($j = ($starting === 0) ? 1 : 0; $j < $c; $j += 2) {
$new_number += intval($last_text[$j]);
}
$new_number = (10 - $new_number % 10) % 10;
$this->checksumValue[] = $new_number;
$last_text .= $new_number;
}
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
$ret = '';
$c = count($this->checksumValue);
for($i = 0; $i < $c; $i++) {
$ret .= $this->keys[$this->checksumValue[$i]];
}
return $ret;
}
return false;
}
};
?>

View File

@@ -0,0 +1,107 @@
<?php
/**
* BCGothercode.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - othercode
*
* Other Codes
* Starting with a bar and altern to space, bar, ...
* 0 is the smallest
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 2 jan 2006 Jean-Sébastien Goupil Correct error if $textfont was empty
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGothercode.barcode.php,v 1.9 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.10
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
// Function str_split is not available for PHP4. So we emulate it here.
if (!function_exists('str_split')) {
function str_split($string, $split_length = 1) {
$array = explode("\r\n", chunk_split($string, $split_length));
array_pop($array);
return $array;
}
}
class BCGothercode extends BCGBarcode1D {
/**
* Constructor
*/
function BCGothercode() {
BCGBarcode1D::BCGBarcode1D();
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$this->drawChar($im, $this->text, true);
$this->drawText($im);
}
function getLabel() {
$label = $this->label;
if($this->label === $this->AUTO_LABEL) {
$label = '';
}
return $label;
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$array = str_split($this->text, 1);
$textlength = (array_sum($array) + count($array)) * $this->scale;
return array($p[0] + $textlength, $p[1]);
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
if($this->label !== $this->AUTO_LABEL && $this->label !== '') {
$pA = $this->getMaxSize();
$pB = BCGBarcode1D::getMaxSize();
$w = $pA[0] - $pB[0];
if(is_a($this->textfont, 'BCGFont')) {
$textfont = $this->textfont; // clone
$textfont->setText($this->label);
$xPosition = ($w / 2) - $textfont->getWidth() / 2 + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $textfont->getHeight() - $textfont->getUnderBaseline() + $this->SIZE_SPACING_FONT + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
$textfont->draw($im, $text_color, $xPosition, $yPosition);
} elseif($this->textfont !== 0) {
$xPosition = ($w / 2) - (strlen($this->label) * imagefontwidth($this->textfont)) / 2 + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->offsetY * $this->scale + $this->SIZE_SPACING_FONT;
$text_color = $this->colorFg->allocate($im);
imagestring($im, $this->textfont, $xPosition, $yPosition, $this->label, $text_color);
}
}
}
};
?>

View File

@@ -0,0 +1,135 @@
<?php
/**
* BCGpostnet.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - PostNet
*
* ################ NOT TESTED ################
*
*--------------------------------------------------------------------
* Revision History
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Fix padding for the barcode
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil PHP5.1 compatible
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added + Redesign output
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGpostnet.barcode.php,v 1.12 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.13
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGpostnet extends BCGBarcode1D {
/**
* Constructor
*/
function BCGpostnet() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
$this->code = array(
'11000', /* 0 */
'00011', /* 1 */
'00101', /* 2 */
'00110', /* 3 */
'01001', /* 4 */
'01010', /* 5 */
'01100', /* 6 */
'10001', /* 7 */
'10010', /* 8 */
'10100' /* 9 */
);
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must contain 5, 9 or 11 chars
if($c !== 5 && $c !== 9 && $c !== 11) {
$this->drawError($im, 'Must contain 5, 9 or 11 chars.');
$error_stop = true;
}
if($error_stop === false) {
// Checksum
$checksum = 0;
for($i = 0; $i < $c; $i++) {
$checksum += intval($this->text[$i]);
}
$checksum = 10 - ($checksum % 10);
// Starting Code
$this->drawChar($im, '1');
// Code
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->findCode($this->text[$i]));
}
// Checksum
$this->drawChar($im, $this->findCode($checksum));
//Ending Code
$this->drawChar($im, '1');
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$c = strlen($this->text);
$startlength = 6 * $this->scale;
$textlength = $c * 5 * 6 * $this->scale;
$checksumlength = 5 * 6 * $this->scale;
$endlength = 6 * $this->scale;
// We remove the white on the right
$removelength = - 3 * $this->scale;
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength + $removelength, $p[1]);
}
/**
* Overloaded method for drawing special barcode
*
* @param resource $im
* @param string $code
* @param boolean $last
*/
function drawChar(&$im, $code, $last = false) {
$c = strlen($code);
for($i = 0; $i < $c; $i++) {
if($code[$i] === '0') {
$posY = $this->thickness / 2;
} else {
$posY = 0;
}
$this->drawFilledRectangle($im, $this->positionX, $posY, $this->positionX + 2, $this->thickness, $this->COLOR_FG);
$this->positionX += 2 * 3;
}
}
};
?>

View File

@@ -0,0 +1,161 @@
<?php
/**
* BCGs25.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - Standard 2 of 5
*
* NOTE: It is really tough to read this barcode !
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil Correct Checksum
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGs25.barcode.php,v 1.8 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.10
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGs25 extends BCGBarcode1D {
var $checksum;
/**
* Constructor
*/
function BCGs25() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
$this->code = array(
'0000202000', /* 0 */
'2000000020', /* 1 */
'0020000020', /* 2 */
'2020000000', /* 3 */
'0000200020', /* 4 */
'2000200000', /* 5 */
'0020200000', /* 6 */
'0000002020', /* 7 */
'2000002000', /* 8 */
'0020002000' /* 9 */
);
$this->setChecksum(false);
}
function setChecksum($checksum) {
$this->checksum = (bool)$checksum;
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must be even
if($c % 2 !== 0 && $this->checksum === false) {
$this->drawError($im, 's25 must be even if checksum is false.');
$error_stop = true;
} elseif($c % 2 === 0 && $this->checksum === true) {
$this->drawError($im, 's25 must be odd if checksum is true.');
$error_stop = true;
}
if($error_stop === false) {
$temp_text = $this->text;
// Checksum
if($this->checksum === true) {
$this->calculateChecksum();
$temp_text .= $this->keys[$this->checksumValue];
}
// Starting Code
$this->drawChar($im, '101000', true);
// Chars
$c = strlen($temp_text);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, $this->findCode($temp_text[$i]), true);
}
// Ending Code
$this->drawChar($im, '10001', true);
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$c = strlen($this->text);
$startlength = 8 * $this->scale;
$textlength = $c * 14 * $this->scale;
$checksumlength = 0;
if($c % 2 !== 0) {
$checksumlength = 14 * $this->scale;
}
$endlength = 7 * $this->scale;
return array($p[0] + $startlength + $textlength + $checksumlength + $endlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "even" position,
// and assign odd/even to each character moving from right to left
// Even Position = 3, Odd Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$even = true;
$this->checksumValue = 0;
$c = strlen($this->text);
for($i = $c; $i > 0; $i--) {
if($even === true) {
$multiplier = 3;
$even = false;
} else {
$multiplier = 1;
$even = true;
}
$this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$this->checksumValue = (10 - $this->checksumValue % 10) % 10;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
};
?>

View File

@@ -0,0 +1,362 @@
<?php
/**
* BCGupca.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - UPC-A
*
* UPC-A contains
* - 2 system digits (1 not provided, a 0 is added automatically)
* - 5 manufacturer code digits
* - 5 product digits
* - 1 checksum digit
*
* The checksum is always displayed.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Fix padding for the barcode
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3 6 feb 2006 Jean-Sébastien Goupil Fix label position + Using correctly static method
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil Enhance rapidity
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added + correcting output when text was present
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGupca.barcode.php,v 1.12 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.15
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGupca extends BCGBarcode1D {
var $codeParity = array();
/**
* Constructor
*/
function BCGupca() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
// Left-Hand Odd Parity starting with a space
// Left-Hand Even Parity is the inverse (0=0012) starting with a space
// Right-Hand is the same of Left-Hand starting with a bar
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
// Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit
$this->codeParity = array(
array(0,0,0,0,0), /* 0 */
array(0,1,0,1,1), /* 1 */
array(0,1,1,0,1), /* 2 */
array(0,1,1,1,0), /* 3 */
array(1,0,0,1,1), /* 4 */
array(1,1,0,0,1), /* 5 */
array(1,1,1,0,0), /* 6 */
array(1,0,1,0,1), /* 7 */
array(1,0,1,1,0), /* 8 */
array(1,1,0,1,0) /* 9 */
);
}
function parse($text) {
BCGBarcode1D::parse($text);
$this->setLabelOffset();
}
function setFont($font) {
BCGBarcode1D::setFont($font);
$this->setLabelOffset();
}
function setLabel($label) {
BCGBarcode1D::setLabel($label);
$this->setLabelOffset();
}
function setOffsetX($offsetX) {
BCGBarcode1D::setOffsetX($offsetX);
$this->setLabelOffset();
}
function setScale($scale) {
BCGBarcode1D::setScale($scale);
$this->setLabelOffset();
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must contain 11 chars
if($c !== 11) {
$this->drawError($im, 'Must contain 11 chars, the 12th digit is automatically added.');
$error_stop = true;
}
if($error_stop === false) {
// The following code is exactly the same as EAN13. We just add a 0 in front of the code !
$this->text = '0'.$this->text; // We will remove it at the end... don't worry
// Checksum
$this->calculateChecksum();
$temp_text = $this->text . $this->keys[$this->checksumValue];
// Starting Code
$this->drawChar($im, '000', true);
// Draw Second Code
$this->drawChar($im, $this->findCode($temp_text[1]), false);
// Draw Manufacturer Code
for($i = 0; $i < 5; $i++) {
$this->drawChar($im, BCGupca::inverse($this->findCode($temp_text[$i + 2]), $this->codeParity[$temp_text[0]][$i]), false);
}
// Draw Center Guard Bar
$this->drawChar($im, '00000', false);
// Draw Product Code
for($i = 7; $i < 13; $i++) {
$this->drawChar($im, $this->findCode($temp_text[$i]), true);
}
// Draw Right Guard Bar
$this->drawChar($im, '000', true);
$this->drawText($im);
// We remove the 0 in front, as we said :)
$this->text = substr($this->text, 1);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$startlength = 3 * $this->scale;
$centerlength = 5 * $this->scale;
$textlength = 12 * 7 * $this->scale;
$endlength = 3 * $this->scale;
$lastcharlength = $this->getEndPosition() + 2;
return array($p[0] + $startlength + $centerlength + $textlength + $endlength + $lastcharlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$odd = true;
$this->checksumValue = 0;
$c = strlen($this->text);
for($i = $c; $i > 0; $i--) {
if($odd === true) {
$multiplier = 3;
$odd = false;
} else {
$multiplier = 1;
$odd = true;
}
if(!isset($this->keys[$this->text[$i - 1]])) {
return;
}
$this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$this->checksumValue = (10 - $this->checksumValue % 10) % 10;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
if($this->label !== $this->AUTO_LABEL) {
BCGBarcode1D::drawText($im);
} elseif($this->label !== '') {
$temp_text = $this->text . $this->keys[$this->checksumValue];
if(is_a($this->textfont, 'BCGFont')) {
$code1 = 0;
$code2 = 0;
$this->textfont->setText($temp_text);
$this->drawExtendedBars($im, $this->textfont->getHeight(), $code1, $code2);
// We need to separate the text, one on the left and one on the right, one starting and one ending
$text0 = substr($temp_text, 1, 1);
$text1 = substr($temp_text, 2, 5);
$text2 = substr($temp_text, 7, 5);
$text3 = substr($temp_text, 12, 1);
$font0 = $this->textfont; // clone
$font1 = $this->textfont; // clone
$font2 = $this->textfont; // clone
$font3 = $this->textfont; // clone
$font0->setText($text0);
$font1->setText($text1);
$font2->setText($text2);
$font3->setText($text3);
$xPosition0 = $this->offsetX * $this->scale - $font0->getWidth() - 4; // -4 is just for beauty;
$xPosition3 = $this->offsetX * $this->scale + $this->positionX * $this->scale + 2;
$yPosition0 = $this->thickness * $this->scale + $font0->getHeight() / 2 + $this->offsetY * $this->scale;
$xPosition1 = ($this->scale * 36 - $font1->getWidth()) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$xPosition2 = ($this->scale * 37 - $font2->getWidth()) / 2 + $code2 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->textfont->getHeight() + $this->SIZE_SPACING_FONT + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
$font0->draw($im, $text_color, $xPosition0, $yPosition0);
$font1->draw($im, $text_color, $xPosition1, $yPosition);
$font2->draw($im, $text_color, $xPosition2, $yPosition);
$font3->draw($im, $text_color, $xPosition3, $yPosition0);
} elseif($this->textfont !== 0) {
$code1 = 0;
$code2 = 0;
$this->drawExtendedBars($im, 9, $code1, $code2);
$xPosition0 = $this->offsetX * $this->scale - imagefontwidth($this->textfont);
$xPosition3 = $this->offsetX * $this->scale + $this->positionX * $this->scale + 2;
$yPosition0 = $this->thickness * $this->scale - imagefontheight($this->textfont) / 2 + $this->offsetY * $this->scale;
$xPosition1 = ($this->scale * 36 - imagefontwidth($this->textfont) * 5) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$xPosition2 = ($this->scale * 37 - imagefontwidth($this->textfont) * 5) / 2 + $code2 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
imagechar($im, $this->textfont, $xPosition0, $yPosition0, $temp_text[1], $text_color);
imagestring($im, $this->textfont, $xPosition1, $yPosition, substr($temp_text, 2, 5), $text_color);
imagestring($im, $this->textfont, $xPosition2, $yPosition, substr($temp_text, 7, 5), $text_color);
imagechar($im, $this->textfont, $xPosition3, $yPosition0, $temp_text[12], $text_color);
}
}
}
function setLabelOffset() {
$label = $this->getLabel();
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$f = $this->textfont; // clone
$f->setText(substr($label, 0, 1));
$val = ($f->getWidth() + 5) / $this->scale;
if($val > $this->offsetX) {
$this->offsetX = $val;
}
} elseif($this->textfont !== 0) {
$val = (imagefontwidth($this->textfont) + 2) / $this->scale;
if($val > $this->offsetX) {
$this->offsetX = $val;
}
}
}
}
function drawExtendedBars(&$im, $plus, &$code1, &$code2) {
$temp_text = $this->text . $this->keys[$this->checksumValue];
$rememberX = $this->positionX;
$rememberH = $this->thickness;
// We increase the bars
// First 2 Bars
$this->thickness += ceil($plus / $this->scale);
$this->positionX = 0;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
// Attemping to increase the 2 following bars
$this->positionX += 1;
$code1 = $this->positionX;
$temp_value = $this->findCode($temp_text[1]);
$this->drawChar($im, $temp_value, false);
$code1 = $this->positionX;
// Center Guard Bar
$this->positionX += 36;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
$code2 = $this->positionX;
// Attemping to increase the 2 last bars
$this->positionX += 37;
$temp_value = $this->findCode($temp_text[12]);
$this->drawChar($im, $temp_value, true);
// Completly last bars
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX = $rememberX;
$this->thickness = $rememberH;
}
function getEndPosition() {
if($this->label === $this->AUTO_LABEL) {
$this->calculateChecksum();
if(is_a($this->textfont, 'BCGFont')) {
$f = $this->textfont; // clone
$f->setText($this->checksumValue);
return $f->getWidth();
} elseif($this->textfont !== 0) {
return imagefontwidth($this->textfont);
}
}
return 0;
}
function inverse($text, $inverse = 1) { // static
if($inverse === 1) {
$text = strrev($text);
}
return $text;
}
};
?>

View File

@@ -0,0 +1,395 @@
<?php
/**
* BCGupce.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - UPC-E
*
* You can provide a UPC-A code (without dash), the code will transform
* it into a UPC-E format if it's possible.
* UPC-E contains
* - 1 system digits (not displayed but coded with parity)
* - 6 digits
* - 1 checksum digit (not displayed but coded with parity)
*
* The text returned is the UPC-E without the checksum.
* The checksum is always displayed.
*
*--------------------------------------------------------------------
* Revision History
* v2.0.1 8 mar 2009 Jean-Sébastien Goupil Fix padding for the barcode
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3 6 feb 2006 Jean-Sébastien Goupil Fix label position + Using correctly static method
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.2 23 jul 2005 Jean-Sébastien Goupil Enhance rapidity
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGupce.barcode.php,v 1.12 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.16
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGupce extends BCGBarcode1D {
var $codeParity = array();
/**
* Constructor
*/
function BCGupce() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
// Odd Parity starting with a space
// Even Parity is the inverse (0=0012) starting with a space
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
// Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit and Checksum
$this->codeParity = array(
array(
array(1,1,1,0,0,0), /* 0,0 */
array(1,1,0,1,0,0), /* 0,1 */
array(1,1,0,0,1,0), /* 0,2 */
array(1,1,0,0,0,1), /* 0,3 */
array(1,0,1,1,0,0), /* 0,4 */
array(1,0,0,1,1,0), /* 0,5 */
array(1,0,0,0,1,1), /* 0,6 */
array(1,0,1,0,1,0), /* 0,7 */
array(1,0,1,0,0,1), /* 0,8 */
array(1,0,0,1,0,1) /* 0,9 */
),
array(
array(0,0,0,1,1,1), /* 0,0 */
array(0,0,1,0,1,1), /* 0,1 */
array(0,0,1,1,0,1), /* 0,2 */
array(0,0,1,1,1,0), /* 0,3 */
array(0,1,0,0,1,1), /* 0,4 */
array(0,1,1,0,0,1), /* 0,5 */
array(0,1,1,1,0,0), /* 0,6 */
array(0,1,0,1,0,1), /* 0,7 */
array(0,1,0,1,1,0), /* 0,8 */
array(0,1,1,0,1,0) /* 0,9 */
)
);
}
function parse($text) {
BCGBarcode1D::parse($text);
$this->setLabelOffset();
}
function setFont($font) {
BCGBarcode1D::setFont($font);
$this->setLabelOffset();
}
function setLabel($label) {
BCGBarcode1D::setLabel($label);
$this->setLabelOffset();
}
function setOffsetX($offsetX) {
BCGBarcode1D::setOffsetX($offsetX);
$this->setLabelOffset();
}
function setScale($scale) {
BCGBarcode1D::setScale($scale);
$this->setLabelOffset();
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must contain 11 chars
// Must contain 8 chars (if starting with upce directly)
// First Chars must be 0 or 1
if($c !== 11 && $c !== 6) {
$this->drawError($im, 'Provide an UPC-A (11 chars) or');
$this->drawError($im, 'You can also provide UPC-E directly (6 chars).');
$error_stop = true;
} elseif($this->text[0] !== '0' && $this->text[0] !== '1' && $c !== 6) {
$this->drawError($im, 'Must start with 0 or 1.');
$error_stop = true;
}
if($error_stop === false) {
if($c !== 6) {
// Checking if UPC-A is convertible
$upce = '';
if(substr($this->text, 3, 3) === '000' || substr($this->text, 3, 3) === '100' || substr($this->text, 3, 3) === '200') { // manufacturer code ends with 100,200 or 300
if(substr($this->text, 6, 2) === '00') { // Product must start with 00
$upce = substr($this->text, 1, 2) . substr($this->text, 8, 3) . substr($this->text, 3, 1);
} else {
$error_stop = true;
}
} elseif(substr($this->text, 4, 2) === '00') { // manufacturer code ends with 00
if(substr($this->text, 6, 3) === '000') { // Product must start with 000
$upce = substr($this->text, 1, 3) . substr($this->text, 9, 2) . '3';
} else {
$error_stop = true;
}
} elseif(substr($this->text, 5, 1) === '0') { // manufacturer code ends with 0
if(substr($this->text, 6, 4) === '0000') { // Product must start with 0000
$upce = substr($this->text, 1, 4) . substr($this->text, 10, 1) . '4';
} else {
$error_stop = true;
}
} else { // No zero leading at manufacturer code
if(substr($this->text, 6, 4) === '0000' && intval(substr($this->text, 10, 1)) >= 5 && intval(substr($this->text, 10, 1)) <= 9) { // Product must start with 0000 and must end by 5,6,7,8 or 9
$upce = substr($this->text, 1, 5) . substr($this->text, 10, 1);
} else {
$error_stop = true;
}
}
} else {
$upce = $this->text;
}
if($error_stop === false) {
if($c === 6) {
// We convert UPC-E to UPC-A to find the checksum
if($this->text[5] === '0' || $this->text[5] === '1' || $this->text[5] === '2') {
$upca = substr($this->text, 0, 2) . $this->text[5] . '0000' . substr($this->text, 2, 3);
} elseif($this->text[5] === '3') {
$upca = substr($this->text, 0, 3) . '00000' . substr($this->text, 3, 2);
} elseif($this->text[5] === '4') {
$upca = substr($this->text, 0, 4) . '00000' . $this->text[4];
} else {
$upca = substr($this->text, 0, 5) . '0000' . $this->text[5];
}
$this->text = '0' . $upca;
}
$this->calculateChecksum();
// Starting Code
$this->drawChar($im, '000', true);
$c = strlen($upce);
for($i = 0; $i < $c; $i++) {
$this->drawChar($im, BCGupce::inverse($this->findCode($upce[$i]), $this->codeParity[$this->text[0]][$this->checksumValue][$i]), false);
}
// Draw Center Guard Bar
$this->drawChar($im, '00000', false);
// Draw Right Bar
$this->drawChar($im, '0', true);
$this->text = $this->text[0] . $upce;
$this->drawText($im);
} else {
$this->drawError($im, 'Your UPC-A can\'t be converted to UPC-E.');
}
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$startlength = 3 * $this->scale;
$centerlength = 5 * $this->scale;
$textlength = 6 * 7 * $this->scale;
$endlength = $this->scale;
$lastcharlength = $this->getEndPosition() + 2;
return array($p[0] + $startlength + $centerlength + $textlength + $endlength + $lastcharlength, $p[1]);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$odd = true;
$this->checksumValue = 0;
$c = strlen($this->text);
for($i = $c; $i > 0; $i--) {
if($odd === true) {
$multiplier = 3;
$odd = false;
} else {
$multiplier = 1;
$odd = true;
}
if(!isset($this->keys[$this->text[$i - 1]])) {
return;
}
$this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$this->checksumValue = (10 - $this->checksumValue % 10) % 10;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
if($this->label !== $this->AUTO_LABEL) {
BCGBarcode1D::drawText($im);
} elseif($this->label !== '') {
$temp_text = $this->text . $this->keys[$this->checksumValue];
if(is_a($this->textfont, 'BCGFont')) {
$thic->code1 = 0;
$this->textfont->setText($temp_text);
$this->drawExtendedBars($im, $this->textfont->getHeight(), $code1);
// We need to separate the text, one on the left and one on the right, one starting and one ending
$text0 = substr($temp_text, 0, 1);
$text1 = substr($temp_text, 1, 6);
$text2 = substr($temp_text, 7, 1);
$font0 = $this->textfont; // clone
$font1 = $this->textfont; // clone
$font2 = $this->textfont; // clone
$font0->setText($text0);
$font1->setText($text1);
$font2->setText($text2);
$xPosition0 = $this->offsetX * $this->scale - $font0->getWidth() - 4; // -4 is just for beauty;
$xPosition2 = $this->offsetX * $this->scale + $this->positionX * $this->scale + 2;
$yPosition0 = $this->thickness * $this->scale + $font0->getHeight() / 2 + $this->offsetY * $this->scale;
$xPosition1 = ($this->scale * 46 - $font1->getWidth()) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->textfont->getHeight() + $this->SIZE_SPACING_FONT + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
$font0->draw($im, $text_color, $xPosition0, $yPosition0);
$font1->draw($im, $text_color, $xPosition1, $yPosition);
$font2->draw($im, $text_color, $xPosition2, $yPosition0);
} elseif($this->textfont !== 0) {
$thic->code1 = 0;
$this->drawExtendedBars($im, 9, $code1);
$xPosition0 = $this->offsetX * $this->scale - imagefontwidth($this->textfont);
$xPosition2 = $this->offsetX * $this->scale + $this->positionX * $this->scale + 2;
$yPosition0 = $this->thickness * $this->scale - imagefontheight($this->textfont) / 2 + $this->offsetY * $this->scale;
$xPosition1 = ($this->scale * 46 - imagefontwidth($this->textfont) * 6) / 2 + $code1 * $this->scale + $this->offsetX * $this->scale;
$yPosition = $this->thickness * $this->scale + $this->offsetY * $this->scale;
$text_color = $this->colorFg->allocate($im);
imagechar($im, $this->textfont, $xPosition0, $yPosition0, $temp_text[0], $text_color);
imagestring($im, $this->textfont, $xPosition1, $yPosition, substr($temp_text, 1, 6), $text_color);
imagechar($im, $this->textfont, $xPosition2, $yPosition0, $temp_text[7], $text_color);
}
}
}
function drawExtendedBars(&$im, $plus, &$code1) {
$rememberX = $this->positionX;
$rememberH = $this->thickness;
// We increase the bars
$this->thickness += ceil($plus / $this->scale);
$this->positionX = 0;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
$code1 = $this->positionX;
// Last Bars
$this->positionX += 46;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX += 2;
$this->drawSingleBar($im, $this->COLOR_FG);
$this->positionX = $rememberX;
$this->thickness = $rememberH;
}
function getEndPosition() {
if($this->label === $this->AUTO_LABEL) {
$this->calculateChecksum();
if(is_a($this->textfont, 'BCGFont')) {
$f = $this->textfont; // clone
$f->setText($this->checksumValue);
return $f->getWidth();
} elseif($this->textfont !== 0) {
return imagefontwidth($this->textfont);
}
}
return 0;
}
function setLabelOffset() {
$label = $this->getLabel();
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$f = $this->textfont; // clone
$f->setText(substr($label, 0, 1));
$val = ($f->getWidth() + 5) / $this->scale;
if($val > $this->offsetX) {
$this->offsetX = $val;
}
} elseif($this->textfont !== 0) {
$val = (imagefontwidth($this->textfont) + 2) / $this->scale;
if($val > $this->offsetX) {
$this->offsetX = $val;
}
}
}
}
function inverse($text, $inverse = 1) { // static
if($inverse === 1) {
$text = strrev($text);
}
return $text;
}
};
?>

View File

@@ -0,0 +1,207 @@
<?php
/**
* BCGupcext2.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - UPC Supplemental Barcode 2 digits
*
* Working with UPC-A, UPC-E, EAN-13, EAN-8
* This includes 2 digits (normaly for publications)
* Must be placed next to UPC or EAN Code
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3 6 feb 2006 Jean-Sébastien Goupil Using correctly static method
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil PHP5.1 compatible
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added + correcting output error
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGupcext2.barcode.php,v 1.10 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.13
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGupcext2 extends BCGBarcode1D {
var $codeParity = array();
/**
* Constructor
*/
function BCGupcext2() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
// Parity, 0=Odd, 1=Even. Depending on ?%4
$this->codeParity = array(
array(0,0), /* 0 */
array(0,1), /* 1 */
array(1,0), /* 2 */
array(1,1) /* 3 */
);
}
function parse($text) {
BCGBarcode1D::parse($text);
$this->setLabelOffset();
}
function setFont($font) {
BCGBarcode1D::setFont($font);
$this->setLabelOffset();
}
function setLabel($label) {
BCGBarcode1D::setLabel($label);
$this->setLabelOffset();
}
function setOffsetY($offsetY) {
BCGBarcode1D::setOffsetY($offsetY);
$this->setLabelOffset();
}
function setScale($scale) {
BCGBarcode1D::setScale($scale);
$this->setLabelOffset();
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must contain 2 chars
if($c !== 2) {
$this->drawError($im, 'Must contain 2 chars.');
$error_stop = true;
}
if($error_stop === false) {
// Starting Code
$this->drawChar($im, '001', true);
// Code
for($i = 0; $i < 2; $i++) {
$this->drawChar($im, BCGupcext2::inverse($this->findCode($this->text[$i]), $this->codeParity[intval($this->text) % 4][$i]), false);
if($i === 0) {
$this->DrawChar($im, '00', false); // Inter-char
}
}
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$startlength = 4 * $this->scale;
$textlength = 2 * 7 * $this->scale;
$intercharlength = 2 * $this->scale;
$label = $this->getLabel();
$textHeight = 0;
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$textfont = $this->textfont; // clone
$textfont->setText($label);
$textHeight = $textfont->getHeight() + $this->SIZE_SPACING_FONT;
} elseif($this->textfont !== 0) {
$textHeight = imagefontheight($this->textfont) + $this->SIZE_SPACING_FONT;
}
}
return array($p[0] + $startlength + $textlength + $intercharlength, $p[1] - $textHeight);
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
$label = $this->getLabel();
if(!empty($label)) {
$pA = $this->getMaxSize();
$pB = BCGBarcode1D::getMaxSize();
$w = $pA[0] - $pB[0];
if(is_a($this->textfont, 'BCGFont')) {
$textfont = $this->textfont; // clone
$textfont->setText($label);
$xPosition = ($w / 2) - ($textfont->getWidth() / 2) + $this->offsetX * $this->scale;
$yPosition = $this->offsetY * $this->scale - $this->SIZE_SPACING_FONT;
$textfont->draw($im, $this->colorFg->allocate($im), $xPosition, $yPosition);
} elseif($this->textfont !== 0) {
$xPosition = ($w / 2) - (strlen($label) / 2) * imagefontwidth($this->textfont) + $this->offsetX * $this->scale;
$yPosition = $this->offsetY * $this->scale - $this->SIZE_SPACING_FONT - imagefontheight($this->textfont);
imagestring($im, $this->textfont, $xPosition, $yPosition, $label, $this->colorFg->allocate($im));
}
}
}
function setLabelOffset() {
$label = $this->getLabel();
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$f = $this->textfont; // clone
$f->setText($label);
$val = ($f->getHeight() - $f->getUnderBaseline()) / $this->scale + $this->SIZE_SPACING_FONT;
if($val > $this->offsetY) {
$this->offsetY = $val;
}
} elseif($this->textfont !== 0) {
$val = (imagefontheight($this->textfont) + 2) / $this->scale;
if($val > $this->offsetY) {
$this->offsetY = $val;
}
}
}
}
function inverse($text, $inverse = 1) { // static
if($inverse === 1) {
$text = strrev($text);
}
return $text;
}
};
?>

View File

@@ -0,0 +1,263 @@
<?php
/**
* BCGupcext5.barcode.php
*--------------------------------------------------------------------
*
* Sub-Class - UPC Supplemental Barcode 2 digits
*
* Working with UPC-A, UPC-E, EAN-13, EAN-8
* This includes 5 digits (normaly for suggested retail price)
* Must be placed next to UPC or EAN Code
* If 90000 -> No suggested Retail Price
* If 99991 -> Book Complimentary (normally free)
* If 90001 to 98999 -> Internal Purpose of Publisher
* If 99990 -> Used by the National Association of College Stores to mark used books
* If 0xxxx -> Price Expressed in British Pounds (xx.xx)
* If 5xxxx -> Price Expressed in U.S. dollars (US$xx.xx)
*
*--------------------------------------------------------------------
* Revision History
* v2.0.0 23 apr 2008 Jean-Sébastien Goupil New Version Update
* v1.2.3 6 feb 2006 Jean-Sébastien Goupil Using correctly static method
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil Checksum separated + PHP5.1 compatible
* v1.2.1 27 jun 2005 Jean-Sébastien Goupil Font support added
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* $Id: BCGupcext5.barcode.php,v 1.10 2009/11/09 04:13:35 jsgoupil Exp $
* PHP5-Revision: 1.13
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGBarcode1D.php');
class BCGupcext5 extends BCGBarcode1D {
var $codeParity = array();
/**
* Constructor
*/
function BCGupcext5() {
BCGBarcode1D::BCGBarcode1D();
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
// Parity, 0=Odd, 1=Even. Depending Checksum
$this->codeParity = array(
array(1,1,0,0,0), /* 0 */
array(1,0,1,0,0), /* 1 */
array(1,0,0,1,0), /* 2 */
array(1,0,0,0,1), /* 3 */
array(0,1,1,0,0), /* 4 */
array(0,0,1,1,0), /* 5 */
array(0,0,0,1,1), /* 6 */
array(0,1,0,1,0), /* 7 */
array(0,1,0,0,1), /* 8 */
array(0,0,1,0,1) /* 9 */
);
}
function parse($text) {
BCGBarcode1D::parse($text);
$this->setLabelOffset();
}
function setFont($font) {
BCGBarcode1D::setFont($font);
$this->setLabelOffset();
}
function setLabel($label) {
BCGBarcode1D::setLabel($label);
$this->setLabelOffset();
}
function setOffsetY($offsetY) {
BCGBarcode1D::setOffsetY($offsetY);
$this->setLabelOffset();
}
function setScale($scale) {
BCGBarcode1D::setScale($scale);
$this->setLabelOffset();
}
/**
* Draws the barcode
*
* @param resource $im
*/
function draw(&$im) {
$error_stop = false;
// Checking if all chars are allowed
$c = strlen($this->text);
for($i = 0; $i < $c; $i++) {
if(array_search($this->text[$i], $this->keys) === false) {
$this->drawError($im, 'Char \'' . $this->text[$i] . '\' not allowed.');
$error_stop = true;
}
}
if($error_stop === false) {
// Must contain 5 chars
if($c !== 5) {
$this->drawError($im, 'Must contain 5 chars.');
$error_stop = true;
}
if($error_stop === false) {
// Checksum
$this->calculateChecksum();
// Starting Code
$this->drawChar($im, '001', true);
// Code
for($i = 0; $i < 5; $i++) {
$this->drawChar($im, BCGupcext5::inverse($this->findCode($this->text[$i]), $this->codeParity[$this->checksumValue][$i]), false);
if($i < 4) {
$this->drawChar($im, '00', false); // Inter-char
}
}
$this->drawText($im);
}
}
}
/**
* Returns the maximal size of a barcode
*
* @return int[]
*/
function getMaxSize() {
$p = BCGBarcode1D::getMaxSize();
$startlength = 4 * $this->scale;
$textlength = 5 * 7 * $this->scale;
$intercharlength = 2 * 4 * $this->scale;
$label = $this->getLabel();
$textHeight = 0;
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$textfont = $this->textfont; // clone
$textfont->setText($label);
$textHeight = $textfont->getHeight() + $this->SIZE_SPACING_FONT;
} elseif($this->textfont !== 0) {
$textHeight = imagefontheight($this->textfont) + $this->SIZE_SPACING_FONT;
}
}
return array($p[0] + $startlength + $textlength + $intercharlength, $p[1] - $textHeight);
}
/**
* Overloaded method to calculate checksum
*/
function calculateChecksum() {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 9
// Multiply it by the number
// Add all of that and do ?mod10
$odd = true;
$this->checksumValue = 0;
$c = strlen($this->text);
for($i = $c; $i > 0; $i--) {
if($odd === true) {
$multiplier = 3;
$odd = false;
} else {
$multiplier = 9;
$odd = true;
}
if(!isset($this->keys[$this->text[$i - 1]])) {
return;
}
$this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$this->checksumValue = $this->checksumValue % 10;
}
/**
* Overloaded method to display the checksum
*/
function processChecksum() {
if($this->checksumValue === false) { // Calculate the checksum only once
$this->calculateChecksum();
}
if($this->checksumValue !== false) {
return $this->keys[$this->checksumValue];
}
return false;
}
/**
* Overloaded method for drawing special label
*
* @param resource $im
*/
function drawText(&$im) {
$label = $this->getLabel();
if(!empty($label)) {
$pA = $this->getMaxSize();
$pB = BCGBarcode1D::getMaxSize();
$w = $pA[0] - $pB[0];
if(is_a($this->textfont, 'BCGFont')) {
$textfont = $this->textfont; // clone
$textfont->setText($label);
$xPosition = ($w / 2) - ($textfont->getWidth() / 2) + $this->offsetX * $this->scale;
$yPosition = $this->offsetY * $this->scale - $this->SIZE_SPACING_FONT;
$textfont->draw($im, $this->colorFg->allocate($im), $xPosition, $yPosition);
} elseif($this->textfont !== 0) {
$xPosition = ($w / 2) - (strlen($label) / 2) * imagefontwidth($this->textfont) + $this->offsetX * $this->scale;
$yPosition = $this->offsetY * $this->scale - $this->SIZE_SPACING_FONT - imagefontheight($this->textfont);
imagestring($im, $this->textfont, $xPosition, $yPosition, $label, $this->colorFg->allocate($im));
}
}
}
function setLabelOffset() {
$label = $this->getLabel();
if(!empty($label)) {
if(is_a($this->textfont, 'BCGFont')) {
$f = $this->textfont; // clone
$f->setText($label);
$val = ($f->getHeight() - $f->getUnderBaseline()) / $this->scale + $this->SIZE_SPACING_FONT;
if($val > $this->offsetY) {
$this->offsetY = $val;
}
} elseif($this->textfont !== 0) {
$val = (imagefontheight($this->textfont) + 2) / $this->scale;
if($val > $this->offsetY) {
$this->offsetY = $val;
}
}
}
}
function inverse($text, $inverse = 1) { // static
if($inverse === 1) {
$text = strrev($text);
}
return $text;
}
};
?>

View File

@@ -0,0 +1,48 @@
<?php
/**
* JoinDraw.php
*--------------------------------------------------------------------
*
* Enable to join 2 BCGDrawing or 2 image object to make only one image.
* There are some options for alignement.
*
* ! THIS CLASS IS NOT AVAILABLE FOR PHP4 !
*
*--------------------------------------------------------------------
* Revision History
* v2.0.1 09 mar 2009 Jean-Sébastien Goupil Update for BCG classes
* v1.2.3b 31 dec 2005 Jean-Sébastien Goupil
*--------------------------------------------------------------------
* $Id: JoinDraw.php,v 1.4 2009/03/08 23:12:27 jsgoupil Exp $
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
class JoinDraw {
/**
* Construct the JoinDrawing Object.
* - $image1 and $image2 have to be BCGDrawing object or image object.
* - $space is the space between the two graphics in pixel.
* - $position is the position of the $image2 depending the $image1.
* - $alignment is the alignment of the $image2 if this one is smaller than $image1;
* if $image2 is bigger than $image1, the $image1 will be positionned on the opposite side specified.
*
* @param mixed $image1
* @param mixed $image2
* @param BCGColor $background
* @param int space
* @param int $position
* @param int $alignment
*/
function JoinDraw(&$image1, &$image2, $background, $space = 10, $position = 0, $alignment = 0) {
}
/**
* Returns the new $im created.
*
* @return resource
*/
function get_im() {
return false;
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* BCGDraw.php
*--------------------------------------------------------------------
*
* Base class to draw images
*
*--------------------------------------------------------------------
* Revision History
* v2.1.0 8 nov 2009 Jean-Sébastien Goupil
*--------------------------------------------------------------------
* $Id: BCGDraw.php,v 1.1 2009/11/09 04:15:10 jsgoupil Exp $
* PHP5-Revision: 1.1
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
class BCGDraw { // abstract
var $im;
var $filename;
/**
* Constructor
*
* @param resource $im
*/
function BCGDraw(&$im) {
$this->im = $im;
}
/**
* Sets the filename
*
* @param string $filename
*/
function setFilename($filename) {
$this->filename = $filename;
}
/**
* Method needed to draw the image based on its specification (JPG, GIF, etc.)
*/
function draw() {} // abstract public
}
?>

View File

@@ -0,0 +1,109 @@
<?php
/**
* BCGDrawJPG.php
*--------------------------------------------------------------------
*
* Image Class to draw JPG images with possibility to set DPI
*
*--------------------------------------------------------------------
* Revision History
* v2.1.0 8 nov 2009 Jean-Sébastien Goupil
*--------------------------------------------------------------------
* $Id: BCGDrawJPG.php,v 1.1 2009/11/09 04:15:10 jsgoupil Exp $
* PHP5-Revision: 1.1
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGDraw.php');
if (!function_exists('file_put_contents')) {
function file_put_contents($filename, $data) {
$f = @fopen($filename, 'w');
if (!$f) {
return false;
} else {
$bytes = fwrite($f, $data);
fclose($f);
return $bytes;
}
}
}
class BCGDrawJPG extends BCGDraw {
var $dpi;
var $quality;
/**
* Constructor
*
* @param resource $im
*/
function BCGDrawJPG(&$im) {
BCGDraw::BCGDraw($im);
}
/**
* Sets the DPI
*
* @param int $dpi
*/
function setDPI($dpi) {
if(is_int($dpi)) {
$this->dpi = max(1, $dpi);
} else {
$this->dpi = null;
}
}
/**
* Sets the quality of the JPG
*
* @param int $quality
*/
function setQuality($quality) {
$this->quality = $quality;
}
/**
* Draws the JPG on the screen or in a file
*/
function draw() {
ob_start();
imagejpeg($this->im, null, $this->quality);
$bin = ob_get_contents();
ob_end_clean();
$this->setInternalProperties($bin);
if (empty($this->filename)) {
echo $bin;
} else {
file_put_contents($this->filename, $bin);
}
}
function setInternalProperties(&$bin) { // private
$this->internalSetDPI($bin);
$this->internalSetC($bin);
}
function internalSetDPI(&$bin) { // private
if($this->dpi !== null) {
$bin = substr_replace($bin, pack("Cnn", 0x01, $this->dpi, $this->dpi), 13, 5);
}
}
function internalSetC(&$bin) { // private
if(strcmp(substr($bin, 0, 4), pack('H*', 'FFD8FFE0')) === 0) {
$offset = 4 + (ord($bin[4]) << 8 | ord($bin[5]));
$firstPart = substr($bin, 0, $offset);
$secondPart = substr($bin, $offset);
$cr = pack('H*', 'FFFE004447656E657261746564207769746820426172636F64652047656E657261746F7220666F722050485020687474703A2F2F7777772E626172636F64657068702E636F6D');
$bin = $firstPart;
$bin .= $cr;
$bin .= $secondPart;
}
}
}
?>

View File

@@ -0,0 +1,209 @@
<?php
/**
* BCGDrawPNG.php
*--------------------------------------------------------------------
*
* Image Class to draw PNG images with possibility to set DPI
*
*--------------------------------------------------------------------
* Revision History
* v2.1.0 8 nov 2009 Jean-Sébastien Goupil
*--------------------------------------------------------------------
* $Id: BCGDrawPNG.php,v 1.1 2009/11/09 04:15:10 jsgoupil Exp $
* PHP5-Revision: 1.1
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://www.barcodephp.com
*/
include_once('BCGDraw.php');
if (!function_exists('file_put_contents')) {
function file_put_contents($filename, $data) {
$f = @fopen($filename, 'w');
if (!$f) {
return false;
} else {
$bytes = fwrite($f, $data);
fclose($f);
return $bytes;
}
}
}
class BCGDrawPNG extends BCGDraw {
var $dpi;
/**
* Constructor
*
* @param resource $im
*/
function BCGDrawPNG(&$im) {
BCGDraw::BCGDraw($im);
}
/**
* Sets the DPI
*
* @param int $dpi
*/
function setDPI($dpi) {
if(is_numeric($dpi)) {
$this->dpi = max(1, $dpi);
} else {
$this->dpi = null;
}
}
/**
* Draws the PNG on the screen or in a file
*/
function draw() {
ob_start();
imagepng($this->im);
$bin = ob_get_contents();
ob_end_clean();
$this->setInternalProperties($bin);
if (empty($this->filename)) {
echo $bin;
} else {
file_put_contents($this->filename, $bin);
}
}
function setInternalProperties(&$bin) { // private
// Scan all the ChunkType
if(strcmp(substr($bin, 0, 8), pack('H*', '89504E470D0A1A0A')) === 0) {
$chunks = $this->detectChunks($bin);
$this->internalSetDPI($bin, $chunks);
$this->internalSetC($bin, $chunks);
}
}
function detectChunks($bin) { // private
$data = substr($bin, 8);
$chunks = array();
$c = strlen($data);
$offset = 0;
while($offset < $c) {
$packed = unpack('Nsize/a4chunk', $data);
$size = $packed['size'];
$chunk = $packed['chunk'];
$chunks[] = array('offset'=>$offset + 8, 'size'=>$size, 'chunk'=>$chunk);
$jump = $size + 12;
$offset += $jump;
$data = substr($data, $jump);
}
return $chunks;
}
function internalSetDPI(&$bin, &$chunks) { // private
if($this->dpi !== null) {
$meters = (int)($this->dpi * 39.37007874);
$found = -1;
$c = count($chunks);
for($i = 0; $i < $c; $i++) {
// We already have a pHYs
if($chunks[$i]['chunk'] === 'pHYs') {
$found = $i;
break;
}
}
$data = 'pHYs' . pack('NNC', $meters, $meters, 0x01);
$crc = BCGDrawPNG::crc($data, 13);
$cr = pack('Na13N', 9, $data, $crc);
// We didn't have a pHYs
if($found == -1) {
// Don't do anything if we have a bad PNG
if($c >= 2 && $chunk[0]['chunk'] = 'IHDR') {
array_splice($chunks, 1, 0, array(array('offset'=>33, 'size'=>9, 'chunk'=>'pHYs')));
// Push the data
for($i = 2; $i < $c; $i++) {
$chunks[$i]['offset'] += 21;
}
$firstPart = substr($bin, 0, 33);
$secondPart = substr($bin, 33);
$bin = $firstPart;
$bin .= $cr;
$bin .= $secondPart;
}
} else {
$bin = substr_replace($bin, $cr, $chunks[$i]['offset'], 21);
}
}
}
function internalSetC(&$bin, &$chunks) { // private
if(count($chunks) >= 2 && $chunk[0]['chunk'] = 'IHDR') {
$firstPart = substr($bin, 0, 33);
$secondPart = substr($bin, 33);
$cr = pack('H*', '0000004C74455874436F707972696768740047656E657261746564207769746820426172636F64652047656E657261746F7220666F722050485020687474703A2F2F7777772E626172636F64657068702E636F6D597F70B8');
$bin = $firstPart;
$bin .= $cr;
$bin .= $secondPart;
}
// Chunks is dirty!! But we are done.
}
var $crc_table = array();
var $crc_table_computed = false;
function make_crc_table() { // private static
for($n = 0; $n < 256; $n++) {
$c = $n;
for ($k = 0; $k < 8; $k++) {
if (($c & 1) == 1) {
$c = 0xedb88320 ^ (BCGDrawPNG::SHR($c, 1));
} else {
$c = BCGDrawPNG::SHR($c, 1);
}
}
$this->crc_table[$n] = $c;
}
$this->crc_table_computed = true;
}
function SHR($x, $n) { // private static
$mask = 0x40000000;
if ($x < 0) {
$x &= 0x7FFFFFFF;
$mask >>= $n - 1;
return ($x >> $n) | $mask;
}
return (int)$x >> (int)$n;
}
function update_crc($crc, $buf, $len) { // private static
$c = $crc;
if (!$this->crc_table_computed) {
BCGDrawPNG::make_crc_table();
}
for($n = 0; $n < $len; $n++) {
$c = $this->crc_table[($c ^ ord($buf[$n])) & 0xff] ^ (BCGDrawPNG::SHR($c, 8));
}
return $c;
}
function crc($data, $len) { // private static
return BCGDrawPNG::update_crc(-1, $data, $len) ^ -1;
}
}
?>

Binary file not shown.

View File

@@ -0,0 +1,43 @@
<?php
// Including all required classes
require('class/BCGFont.php');
require('class/BCGColor.php');
require('class/BCGDrawing.php');
// Including the barcode technology
include('class/BCGcode39.barcode.php');
include_once ("../../include/mcglobal.inc.php");
// Check HTTP-Parameters
getSecHttpVars("1",array("text"));
// Loading Font
$font =& new BCGFont('./class/font/Arial.ttf', 18);
// The arguments are R, G, B for color.
$color_black =& new BCGColor(0, 0, 0);
$color_white =& new BCGColor(255, 255, 255);
$code =& new BCGcode39();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse($text); // Text
/* Here is the list of the arguments
1 - Filename (empty : display on screen)
2 - Background color */
$drawing =& new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
// Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
// Draw (or save) the image into PNG format.
$drawing->finish($drawing->IMG_FORMAT_PNG);
?>

View File

@@ -0,0 +1,691 @@
<?php
//////////////////////////////////////////////////////////////////////
// table.class.php
//--------------------------------------------------------------------
//
// Class Table - Don't modify this file !
//
//--------------------------------------------------------------------
// Revision History
// $Id: LSTable.php,v 1.3 2008/07/10 04:23:26 jsgoupil Exp $
//--------------------------------------------------------------------
// Copyright (C) Jean-Sebastien Goupil
// http://www.barcodephp.com
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
define( 'TABLE_DEFAULT_ROW_HIDDEN', FALSE );
define( 'TABLE_DEFAULT_COL_HIDDEN', FALSE );
define( 'TABLE_DEFAULT_CELL_VALUE', '&nbsp;' ); // If '&nbsp;', a cell will appear, if NULL, no cell will appear
define( 'TABLE_DEFAULT_TEMPLATE', 'tpl_LS' );
include( 'Table_template.php' );
class LSTable {
// PRIVATE ARGUMENTS
var $template; // string
var $numRows, $numCols; // int
var $title; // string
var $text = array(); // string
var $cellsAttributes = array(), $rowsAttributes = array(); // string
var $hiddenRows = array(), $hiddenCols = array(); // bool
var $width; // string
var $temp_col; // int
var $temp_ascending; // bool
// PUBLIC FUNCTIONS
/**
* @return
* @param int $numRows
* @param int $numCols
* @param string $width
* @param object $parent
* @desc Constructor. You can put a $parent object. This will search the first empty place into the parent.
**/
function LSTable ( $numRows, $numCols, $width, &$parent ) {
$this->numRows = intval( $numRows );
$this->numCols = intval( $numCols );
for( $i = 0; $i < $numRows; $i++ )
$this->_setVariable( $i );
for( $i = 0; $i < $numCols; $i++ )
$this->hiddenCols[ $i ] = TABLE_DEFAULT_COL_HIDDEN;
$this->title = '';
$this->width = strval( $width );
if( defined( 'TABLE_DEFAULT_TEMPLATE' ) )
$this->setTemplate( TABLE_DEFAULT_TEMPLATE );
// We look for an empty place if $parent isn't null
if( is_object( $parent ) ) {
$stop = false;
for( $i = 0; $i < $parent->numRows; $i++ ) {
for( $j = 0; $j < $parent->numCols; $j++ ) {
if( $parent->text[ $i ][ $j ] == TABLE_DEFAULT_CELL_VALUE ) {
$parent->text[ $i ][ $j ] =& $this;
$stop = true;
}
if( $stop == true )
break;
}
if( $stop == true )
break;
}
}
}
// No destructor for PHP4
//function __destruct() {
//
//}
/**
* @return void
* @param int $row
* @param int $col
* @param mixed $string
* @desc Writes Text or Object into $row and $col.
**/
function setText ( $row, $col, $string ) {
if( is_int( $row ) && is_int( $col ) )
if( $row < $this->numRows && $col < $this->numCols )
$this->text[ $row ][ $col ] = $string;
}
/**
* @return void
* @param int $row
* @param int $col
* @param string $attrib
* @param mixed $value
* @desc Adds a Cell Attribute at $row and $col.
**/
function addCellAttribute ( $row, $col, $attrib, $value ) {
if( is_int( $row ) && is_int( $col ) && is_string( $attrib ) )
if( $row < $this->numRows && $col < $this->numCols )
$this->cellsAttributes[ $row ][ $col ][ strtolower( $attrib ) ] = $value;
}
/**
* @return void
* @param int $row
* @param int $col
* @param string $attrib
* @desc Deletes a Cell Attribute at $row and $col.
**/
function delCellAttribute ( $row, $col, $attrib ) {
if( is_int( $row ) && is_int( $col ) && is_string( $attrib ) )
if( $row < $this->numRows && $col < $this->numCols )
unset( $this->cellsAttributes[ $row ][ $col ][ strtolower( $attrib ) ] );
}
/**
* @return void
* @param int $row
* @param string $attrib
* @param mixed $value
* @desc Adds a Row Attribute at $row. Will be located in TR.
**/
function addRowAttribute ( $row, $attrib, $value ) {
if( is_int( $row ) && is_string( $attrib ) )
if( $row < $this->numRows )
$this->rowsAttributes[ $row ][ strtolower( $attrib ) ] = $value;
}
/**
* @return void
* @param int $row
* @param string $attrib
* @desc Deletes a Row Attribute at $row.
**/
function delRowAttribute ( $row, $attrib ) {
if( is_int( $row ) && is_string( $attrib ) )
if( $row < $this->numRows )
unset( $this->rowsAttributes[ $row ][ strtolower( $attrib ) ] );
}
/**
* @return void
* @param int $row
* @param string $attrib
* @param mixed $value
* @desc Adds a Cell Attribute in all cells located on $row row.
**/
function addAllCellsInRowAttribute ( $row, $attrib, $value ) {
if( is_int( $row ) && is_string( $attrib ) )
if( $row < $this->numRows )
for( $i = 0; $i < $this->numCols; $i++ )
$this->cellsAttributes[ $row ][ $i ][ strtolower( $attrib ) ] = $value;
}
/**
* @return void
* @param int $col
* @param string $attrib
* @param mixed $value
* @desc Adds a Cell Attribute in all cells located on $col column.
**/
function addAllCellsInColAttribute ( $col, $attrib, $value ) {
if( is_int( $col ) && is_string( $attrib ) )
if( $col < $this->numCols )
for( $i = 0; $i < $this->numRows; $i++ )
$this->cellsAttributes[ $i ][ $col ][ strtolower( $attrib ) ] = $value;
}
/**
* @return void
* @param callback $template
* @desc Sets Template (Class)
**/
function setTemplate ( $template ) {
if( is_string( $template ) )
if( class_exists( $template ) )
$this->template = strval( $template );
}
/**
* @return string
* @desc Returns current Template
**/
function template () {
return $this->template;
}
/**
* @return mixed
* @param int $row
* @param int $col
* @desc Returns the text or object contained into $row and $col
**/
function text ( $row, $col ) {
if( is_int( $row ) && is_int( $col ) )
if( $row < $this->numRows && $col < $this->numCols )
return $this->text[ $row ][ $col ];
return FALSE;
}
/**
* @return void
* @param int $row
* @param int $col
* @desc Clears the cell located into $row and $col. Keeps the Cell.
*/
function clearCell ( $row, $col ) {
if( is_int( $row ) && is_int( $col ) ) {
if( $row < $this->numRows && $col < $this->numCols ) {
$this->text[ $row ][ $col ] = TABLE_DEFAULT_CELL_VALUE;
unset( $this->cellsAttributes[ $row ][ $col ] );
$this->cellsAttributes[ $row ][ $col ] = array();
}
}
}
/**
* @return int
* @desc Returns the number of Rows
**/
function numRows () {
return $this->numRows;
}
/**
* @return int
* @desc Returns the number of Columns
**/
function numCols () {
return $this->numCols;
}
/**
* @return void
* @param int $col
* @param bool $ascending
* @desc Sorts table based on $col.
**/
function sortColumn ( $col, $ascending = TRUE ) {
if( is_int( $col ) && is_bool( $ascending ) ) {
if( $col < $this->numCols ) {
$this->temp_col = $col;
$this->temp_ascending = $ascending;
$this->_sort_merge( $this->text );
}
}
}
/**
* @return void
* @param int $r
* @desc Sets the number of rows of the table.
**/
function setNumRows ( $r ) {
if( is_int( $r ) )
if( $r >= 0 )
if( $r > $this->numRows )
$this->insertRows( $this->numRows, $r - $this->numRows );
elseif( $r < $this->numRows )
for( $i = $this->numRows; $i > $r; $i-- )
$this->removeRow( $i - 1 );
}
/**
* @return void
* @param int $r
* @desc Sets the number of columns of the table.
**/
function setNumCols ( $r ) {
if( is_int( $r ) )
if( $r >= 0 )
if( $r > $this->numCols )
$this->insertColumns( $this->numCols, $r - $this->numCols );
elseif( $r < $this->numCols )
for( $i = $this->numCols; $i > $r; $i-- )
$this->removeColumn( $i - 1 );
}
/**
* @return void
* @param int $row
* @desc Hides a $row from table
**/
function hideRow ( $row ) {
if( is_int( $row ) )
if( $row < $this->numRows )
$this->hiddenRows[ $row ] = TRUE;
}
/**
* @return void
* @param int $col
* @desc Hides a $col from table
**/
function hideColumn ( $col ) {
if( is_int( $col ) )
if( $col < $this->numCols )
$this->hiddenCols[ $col ] = TRUE;
}
/**
* @return void
* @param int $row
* @desc Shows a $row from table
**/
function showRow ( $row ) {
if( is_int( $row ) )
if( $row < $this->numRows )
$this->hiddenRows[ $row ] = FALSE;
}
/**
* @return void
* @param int $col
* @desc Shows a $col from table
**/
function showColumn ( $col ) {
if( is_int( $col ) )
if( $col < $this->numCols )
$this->hiddenCols[ $col ] = FALSE;
}
/**
* @return bool
* @param int $row
* @desc Returns TRUE if a row is hidden.
**/
function isRowHidden ( $row ) {
if( is_int( $row ) )
if( $row < $this->numRows )
return $this->hiddenRows[ $row ];
return FALSE;
}
/**
* @return bool
* @param int $col
* @desc Returns TRUE if a col is hidden.
**/
function isColumnHidden ( $col ) {
if( is_int( $col ) )
if( $col < $this->numCols )
return $this->hiddenCols[ $col ];
return FALSE;
}
/**
* @return void
* @param int $row1
* @param int $row2
* @param bool $swapAttributes
* @desc Swaps 2 rows. Swaps attributes if $switchAttributes is TRUE.
**/
function swapRows ( $row1, $row2, $swapAttributes = FALSE ) {
if( is_int( $row1 ) && is_int( $row2 ) && is_bool( $swapAttributes ) ) {
if( $row1 < $this->numRows && $row2 < $this->numRows ) {
$temp =& $this->text[ $row1 ];
$this->text[ $row1 ] =& $this->text[ $row2 ];
$this->text[ $row2 ] =& $temp;
if( $swapAttributes == TRUE ) {
$temp2 = $this->cellsAttributes[ $row1 ];
$this->cellsAttributes[ $row1 ] = $this->cellsAttributes[ $row2 ];
$this->cellsAttributes[ $row2 ] = $temp2;
$temp2 = $this->rowsAttributes[ $row1 ];
$this->rowsAttributes[ $row1 ] = $this->rowsAttributes[ $row2 ];
$this->rowsAttributes[ $row2 ] = $temp2;
}
}
}
}
/**
* @return void
* @param int $col1
* @param int $col2
* @param bool $swapAttributes
* @desc Swaps 2 cols. Swaps attributes if $switchAttributes is TRUE.
**/
function swapColumns ( $col1, $col2, $swapAttributes = FALSE ) {
if( is_int( $col1 ) && is_int( $col2 ) && is_bool( $swapAttributes ) ) {
if( $col1 < $this->numCols && $col2 < $this->numCols ) {
for( $i = 0; $i < $this->numRows; $i++ ){
$temp =& $this->text[ $i ][ $col1 ];
$this->text[ $i ][ $col1 ] =& $this->text[ $i ][ $col2 ];
$this->text[ $i ][ $col2 ] =& $temp;
if( $swapAttributes == TRUE ) {
$temp2 = $this->cellsAttributes[ $i ][ $col1 ];
$this->cellsAttributes[ $i ][ $col1 ] = $this->cellsAttributes[ $i ][ $col2 ];
$this->cellsAttributes[ $i ][ $col2 ] = $temp2;
}
}
}
}
}
/**
* @return void
* @param int $row1
* @param int $col1
* @param int $row2
* @param int $col2
* @param bool $swapAttributes
* @desc Swaps 2 cells. Swaps attributes if $switchAttributes is TRUE.
**/
function swapCells ( $row1, $col1, $row2, $col2, $swapAttributes = FALSE ) {
if( is_int( $row1 ) && is_int( $col1 ) && is_int( $row2 ) && is_int( $col2 ) && is_bool( $swapAttributes ) ) {
if( $row1 < $this->numRows && $col1 < $this->numCols && $row2 < $this->numRows && $col2 < $this->numCols ) {
$temp =& $this->text[ $row1 ][ $col1 ];
$this->text[ $row1 ][ $col1 ] =& $this->text[ $row2 ][ $col2 ];
$this->text[ $row2 ][ $col2 ] =& $temp;
if( $swapAttributes == TRUE ) {
$temp2 = $this->cellsAttributes[ $row1 ][ $col1 ];
$this->cellsAttributes[ $row1 ][ $col1 ] = $this->cellsAttributes[ $row2 ][ $col2 ];
$this->cellsAttributes[ $row2 ][ $col2 ] = $temp2;
}
}
}
}
/**
* @return void
* @param int $row
* @param int $count
* @desc Inserts $count row at $row position.
**/
function insertRows ( $row, $count = 1 ) {
if( is_int( $row ) && is_int( $count ) ) {
if( $row >= 0 && $row <= $this->numRows ) {
for( $i = 0; $i < $count; $i++) {
array_splice( $this->text, $row, 0, '' );
array_splice( $this->hiddenRows, $row, 0, FALSE );
array_splice( $this->cellsAttributes, $row, 0, FALSE );
array_splice( $this->rowsAttributes, $row, 0, FALSE );
$this->_setVariable( $row );
$this->numRows += 1;
}
}
}
}
/**
* @return void
* @param int $col
* @param int $count
* @desc Inserts $count columns at $col position.
**/
function insertColumns ( $col, $count = 1 ) {
if( is_int( $col ) && is_int( $count ) ) {
if( $col >= 0 && $col <= $this->numCols ) {
for( $i = 0; $i < $this->numRows; $i++ ) {
$temp_text = array();
$temp_attributes = array();
reset($this->text[ $i ]);
for( $j = 0; $j <= $this->numCols; $j++ ) {
if( $col == $j ) {
for( $k = 0; $k < $count; $k++ ){
$temp_text[] = '';
$temp_attributes[] = array();
}
}
if( $j == $this->numCols )
break;
$temp_text[] = $this->text[ $i ][ $j ];
$temp_attributes[] = $this->cellsAttributes[ $i ][ $j ];
}
$this->text[ $i ] = $temp_text;
$this->cellsAttributes[ $i ] = $temp_attributes;
}
for( $i = 0; $i < $count; $i++ )
array_splice( $this->hiddenCols, $col, 0, FALSE );
$this->numCols += $count;
}
}
}
/**
* @return void
* @param int $row
* @desc Removes $row.
**/
function removeRow ( $row ) {
if( is_int( $row ) ) {
if( $row < $this->numRows ) {
array_splice( $this->text, $row, 1 );
array_splice( $this->hiddenRows, $row, 1 );
array_splice( $this->cellsAttributes, $row, 1 );
array_splice( $this->rowsAttributes, $row, 1 );
$this->numRows -= 1;
}
}
}
/**
* @return void
* @param int $col
* @desc Removes $col.
**/
function removeColumn ( $col ) {
if( is_int( $col ) ) {
if( $col < $this->numCols ) {
for( $i = 0; $i < $this->numRows; $i++ ) {
$temp_text = array();
$temp_attributes = array();
reset($this->text[ $i ]);
while ( list( $key, ) = each( $this->text[ $i ] ) ) {
if( $key != $col ) {
$temp_text[] = $this->text[ $i ][ $key ];
$temp_attributes[] = $this->cellsAttributes[ $i ][ $key ];
}
}
$this->text[ $i ] = $temp_text;
$this->cellsAttributes[ $i ] = $temp_attributes;
}
array_splice( $this->hiddenCols, $col, 1 );
$this->numCols -= 1;
}
}
}
/**
* @return void
* @param int $width
* @desc Sets Table Width.
**/
function setWidth ( $width ) {
if( is_string( $width ) )
$this->width = strval( $width );
}
/**
* @return string
* @desc Returns Table Width.
**/
function width () {
return $this->width;
}
/**
* @return void
* @param int $title
* @desc Sets Table Title.
**/
function setTitle ( $title ) {
if( is_string( $title ) )
$this->title = strval( $title );
}
/**
* @return string
* @desc Returns Table Title.
**/
function title () {
return $this->title;
}
/**
* @return void
* @desc Displays the table with its cells.
**/
function draw () {
if( $this->template != '' ) {
$tpl = new $this->template;
$tpl->__header( $this->width, $this->title );
$this->_check_rowcol_span();
for( $i = 0; $i < $this->numRows; $i++ ) {
if( $this->hiddenRows[ $i ] == FALSE ) {
$tpl->__row_start( $this->rowsAttributes[ $i ] );
for( $j = 0; $j < $this->numCols; $j++ ) {
if( $this->hiddenCols[ $j ] == FALSE ) {
if( $this->text[ $i ][ $j ] !== NULL ) {
if( is_object( $this->text[ $i ][ $j ] ) ) {
$tpl->__cell_start( '', $this->cellsAttributes[ $i ][ $j ] );
$this->text[ $i ][ $j ]->draw();
}
else
$tpl->__cell_start( $this->text[ $i ][ $j ], $this->cellsAttributes[ $i ][ $j ] );
$tpl->__cell_stop( $this->text[ $i ][ $j ], $this->cellsAttributes[ $i ][ $j ] );
}
}
}
$tpl->__row_stop( $this->rowsAttributes[ $i ] );
}
}
$tpl->__footer( $this->width, $this->title );
}
}
// PRIVATE FUNCTIONS
/**
* @return void
* @desc Sets NULL to cells if colspan or rowspan go on the cells
**/
function _check_rowcol_span() {
for( $i = 0; $i < $this->numRows; $i++ ) {
for( $j = 0; $j < $this->numCols; $j++ ) {
if( isset( $this->cellsAttributes[ $i ][ $j ][ 'colspan' ] ) )
if( $this->cellsAttributes[ $i ][ $j ][ 'colspan' ] > 0 )
for( $z = 1; $z < intval( $this->cellsAttributes[ $i ][ $j ][ 'colspan' ] ); $z++ )
$this->text[ $i ][ $j + $z ] = NULL;
if( isset( $this->cellsAttributes[ $i ][ $j ][ 'rowspan' ] ) )
if( $this->cellsAttributes[ $i ][ $j ][ 'rowspan' ] > 0 )
for( $z = 1; $z < intval( $this->cellsAttributes[ $i ][ $j ][ 'rowspan' ] ); $z++ )
$this->text[ $i + $z ][ $j ] = NULL;
}
}
}
/**
* @return void
* @param int $r
* @desc Sets Default Variables for row $r.
**/
function _setVariable ( $r ) {
$this->text[ $r ] = array_fill( 0, $this->numCols, TABLE_DEFAULT_CELL_VALUE );
$this->cellsAttributes[ $r ] = array_fill( 0, $this->numCols, array() );
$this->rowsAttributes[ $r ] = array();
$this->hiddenRows[ $r ] = TABLE_DEFAULT_ROW_HIDDEN;
}
/**
* @return void
* @param int $r
* @desc Unsets Default Variables for row $r.
**/
function _unsetVariable ( $r ) {
unset( $this->text[ $r ] );
unset( $this->cellsAttributes[ $r ] );
unset( $this->rowsAttributes[ $r ] );
unset( $this->hiddenRows[ $r ] );
}
/**
* @return void
* @param string $tab
* @desc Merge Function
**/
function _sort_merge ( &$tab ) {
if( count( $tab ) <= 1 ) return;
else {
$tab1 = array();
$tab2 = array();
for( $i = 0; $i < count( $tab ); $i++) {
if( $i < ( count( $tab ) ) / 2 )
$tab1[] = $tab[ $i ];
else
$tab2[] = $tab[ $i ];
}
$this->_sort_merge( $tab1 );
$this->_sort_merge( $tab2 );
$this->_merge_all( $tab1, $tab2, $tab );
}
}
/**
* @return void
* @param string $tab1
* @param string $tab2
* @param string $tab
* @desc Merge Function
**/
function _merge_all ( $tab1, $tab2, &$tab ) {
$i = 0;
$i1 = $i2 = 0;
while( $i1 < count( $tab1 ) && $i2 < count( $tab2 ) ) {
if( strcmp( $tab1[ $i1 ][ $this->temp_col ], $tab2[ $i2 ][ $this->temp_col ] ) == (($this->temp_ascending==TRUE)?-1:1) )
$tab[ $i ] = $tab1[ $i1++ ];
else
$tab[ $i ] = $tab2[ $i2++ ];
$i++;
}
while( $i1 < count( $tab1 ) ) {
$tab[ $i ] = $tab1[ $i1++ ];
$i++;
}
while( $i2 < count( $tab2 ) ) {
$tab[ $i ] = $tab2[ $i2++ ];
$i++;
}
}
}
?>

View File

@@ -0,0 +1,71 @@
<?php
class tpl_LS {
function __header ( $width, $title ) {
echo '<table width="'.$width.'" border="0" cellpadding="0" cellspacing="0" align="center" bgcolor="#004163" class="tableline"><tr><th><u>'.$title.'</u>'."\n".'</th></tr><tr><td>'."\n".'<table width="100%" border="0" cellpadding="4" cellspacing="1" align="center">';
}
function __footer ( $width, $title ) {
echo '</table>'."\n".'</td></tr></table>'."\n";
}
function __row_start ( $attributes ) {
$code = '';
$found_class = false;
reset( $attributes );
while( list( $key, $value ) = each( $attributes ) ) {
$code .= ' '.$key.'="'.$value.'"';
if( $key == 'class' )
$found_class = true;
}
if( $found_class=== false )
$code .= ' class="'.next_color().'"';
echo '<tr'.$code.'>';
}
function __row_stop ( $attributes ) {
echo '</tr>';
}
function __cell_start ( $text, $attributes ) {
$code = '';
reset( $attributes );
while( list( $key, $value ) = each( $attributes ) )
$code .= ' '.$key.'="'.$value.'"';
echo '<td'.$code.'>'.$text;
}
function __cell_stop ( $text, $attributes ) {
echo '</td>';
}
}
class tpl_BLANK {
function __header ( $width, $title ) {
echo '<table width="'.$width.'" border="0" cellpadding="0" cellspacing="0" align="center">';
}
function __footer ( $width, $title ) {
echo '</table>';
}
function __row_start ( $attributes ) {
echo '<tr>';
}
function __row_stop ( $attributes ) {
echo '</tr>';
}
function __cell_start ( $text, $attributes ) {
$code = '';
reset( $attributes );
while( list( $key, $value ) = each( $attributes ) )
$code .= ' '.$key.'="'.$value.'"';
echo '<td'.$code.'>'.$text;
}
function __cell_stop ( $text, $attributes ) {
echo '</td>';
}
}
?>

View File

@@ -0,0 +1,27 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D');
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Known also as Ames Code, NW-7, Monarch, 2 of 7, Rationalized Codabar.</li><li>Codabar was developed in 1972 by Pitney Bowes, Inc.</li><li>This symbology is useful to encode digital information. It is a self-checking code, there is no check digit.</li><li>Codabar is used by blood bank, photo labs, library, FedEx...</li><li>Coding can be with an unspecified length composed by numbers, plus and minus sign, colon, slash, dot, dollar.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,27 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-');
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i].'" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Known also as USD-8.</li><li>Code 11 was developed in 1977 as a high-density numeric symbology.</li><li>Used to identify telecommunications equipment.</li><li>Code 11 is a numeric symbology and its character set consists of 10 digital characters and the dash symbol (-).</li><li>There is a "C" check digit. If the length of encoded message is greater thant 10, a "K" check digit may be used.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,57 @@
<?php
define('IN_CB', true);
include('header.php');
$vals = array();
for($i = 0; $i <= 127; $i++) {
$vals[] = '%' . sprintf('%02X', $i);
}
$keys = array(
'NUL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'TAB', 'LF', 'VT', 'FF', 'CR', 'SO', 'SI', 'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', 'FS', 'GS', 'RS', 'US',
' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 'DEL'
);
if($a2 === '') {
$a2 = 'NULL';
}
$n = $table->numRows();
$table->insertRows($n, 4);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Starts With');
$text2display = '<select size="1" name="a2"><option value="NULL"';
if($a2=='NULL') {
$text2display .= ' selected="selected"';
}
$text2display .= '>Auto</option><option value="A"';
if($a2 === 'A') {
$text2display .= ' selected="selected"';
}
$text2display .= '>Code 128-A</option><option value="B"';
if($a2 === 'B') {
$text2display .= ' selected="selected"';
}
$text2display .= '>Code 128-B</option><option value="C"';
if($a2 === 'C') {
$text2display .= ' selected="selected"';
}
$text2display .= '>Code 128-C</option></select>';
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . htmlentities($keys[$i]) . '" style="width:37px;padding:0px;" onclick="newkey(this.form,unescape(\'' . $vals[$i] . '\'))" /> ';
}
$table->setText($n + 2, 1, $text2display);
$table->setText($n + 3, 0, 'Explanation');
$table->setText($n + 3, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Code 128 is a high-density alphanumeric symbology.</li><li>Used extensively worldwide.</li><li>Code 128 is designed to encode 128 full ASCII characters.</li><li>The symbology includes a checksum digit.</li><li>Code 128A handles capital letters<br />Code 128B handles capital letters and lowercase<br />Code 128C handles group of 2 numbers</li><li>Your browser may not be able to write the special characters (NUL, SOH, etc.) but you can write them with the code.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,34 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '.', ' ', '$', '/', '+', '%');
$n = $table->numRows();
$table->insertRows($n, 4);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, '<label for="checksum">Checksum</label>');
$text2display = '<input type="checkbox" name="a1" id="checksum" value="1"';
if($a1 == 1) {
$text2display .= ' checked="checked"';
}
$text2display .= ' />';
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 2, 1, $text2display);
$table->setText($n + 3, 0, 'Explanation');
$table->setText($n + 3, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Known also as USS Code 39, 3 of 9.</li><li>Code 39 can encode alphanumeric characters.</li><li>The symbology is used in non-retail environment.</li><li>Code 39 is designed to encode 26 upper case letters, 10 digits and 7 special characters.</li><li>Code 39 has a checksum but it\'s rarely used.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,43 @@
<?php
define('IN_CB', true);
include('header.php');
$vals = array();
for($i = 0; $i <= 127; $i++) {
$vals[] = '%' . sprintf('%02X', $i);
}
$keys = array(
'NUL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'TAB', 'LF', 'VT', 'FF', 'CR', 'SO', 'SI', 'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', 'FS', 'GS', 'RS', 'US',
' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 'DEL'
);
$n = $table->numRows();
$table->insertRows($n, 4);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, '<label for="checksum">Checksum</label>');
$text2display = '<input type="checkbox" name="a1" id="checksum" value="1"';
if($a1==1) {
$text2display .= ' checked="checked"';
}
$text2display .= ' />';
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . htmlentities($keys[$i]) . '" style="width:37px;padding:0px;" onclick="newkey(this.form,unescape(\'' . $vals[$i] . '\'))" /> ';
}
$table->setText($n + 2, 1, $text2display);
$table->setText($n + 3, 0, 'Explanation');
$table->setText($n + 3, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Supports the ASCII 0 to 127</li><li>This mode is "optional" for Code 39, you have to specify your reader that you have extended code.</li><li>Your browser may not be able to write the special characters (NUL, SOH, etc.) but you can write them with the code.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,36 @@
<?php
define('IN_CB', true);
include('header.php');
$vals = array();
for($i = 0; $i <= 127; $i++) {
$vals[] = '%' . sprintf('%02X', $i);
}
$keys = array(
'NUL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'TAB', 'LF', 'VT', 'FF', 'CR', 'SO', 'SI', 'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', 'FS', 'GS', 'RS', 'US',
' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 'DEL'
);
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n ,0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . htmlentities($keys[$i]) . '" style="width:37px;padding:0px;" onclick="newkey(this.form,unescape(\'' . $vals[$i] . '\'))" /> ';
}
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Known also as USS Code 93.</li><li>Code 93 was designed to provide a higher density and data security enhancement to Code39.</li><li>Used primarily by Canadian postal office to encode supplementary delivery information.</li><li>Similar to Code 39, Code 93 has the same 43 characters plus 5 special ones to encode the ASCII 0 to 127.</li><li>This symbology composed of 2 check digits ("C" and "K").</li><li>Your browser may not be able to write the special characters (NUL, SOH, etc.) but you can write them with the code.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,3 @@
<?php
$class_dir = '../include/barcode/class';
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 B

View File

@@ -0,0 +1,27 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>EAN means Internal Article Numbering.</li><li>It is an extension of UPC-A to include the country information.</li><li>Used with consumer products internationally.</li><li>Composed by 2 number system, 5 manufacturer code, 5 product code and 1 check digit.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,27 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>EAN-8 is a short version of EAN-13.</li><li>Composed by 7 digits and 1 check digit.</li><li>There is no conversion available between EAN-8 and EAN-13.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1,11 @@
<?php
if(!defined('IN_CB'))die('You are not allowed to access to this page.');
?>
<p style="text-align:center;font-size:10px">
All Rights Reserved &copy; 2004-2010 <a href="http://www.barcodephp.com" target="_blank">Barcode Generator</a> PHP4-v<?php echo constant('VERSION'); ?>
<br />by Jean-Sébastien Goupil
</p>
</body>
</html>

View File

@@ -0,0 +1,188 @@
<?php
if(!defined('IN_CB')) die('You are not allowed to access to this page.');
/**
* Displays Select Code bar Box
*
* @param string $filename
*/
function display_select($filename) {
$table_value = array('codabar', 'code11', 'code39', 'code39extended', 'code93', 'code128', 'ean8', 'ean13', 'gs1128', 'isbn', 'i25', 's25', 'msi', 'upca', 'upce', 'upcext2', 'upcext5', 'postnet', 'othercode');
$table_text = array('Codabar', 'Code 11', 'Code 39', 'Code 39 Extended', 'Code 93', 'Code 128', 'EAN-8', 'EAN-13', 'GS1-128 (EAN-128)', 'ISBN-10 / ISBN-13', 'Interleaved 2 of 5', 'Standard 2 of 5', 'MSI Plessey', 'UPC-A', 'UPC-E', 'UPC Extension 2 Digits', 'UPC Extension 5 Digits', 'PostNet', 'Other Barcode');
$text2display = '';
$text2display .= '<select name="barcode_type" size="1" onchange="location.href=barcode_type.options[barcode_type.selectedIndex].value + \'.php\'" style="width: 300px">';
$c = count($table_value);
for ($i = 0; $i < $c; $i++) {
$text2display .= '<option value="' . $table_value[$i] . '"';
if ($table_value[$i] === $filename) {
$text2display .= ' selected="selected"';
}
$text2display .= '>' . $table_text[$i] . '</option>';
}
$text2display .= '</select>';
return $text2display;
}
/**
* Displays the output (PNG, JPEG, GIF)
*
* @param int $number
*/
function display_output($number) {
$table_value = array('1', '2', '3');
$table_text = array('Portable Network Graphics (PNG)', 'Joint Photographic Experts Group (JPEG)', 'Graphics Interchange Format (GIF)');
$text2display = '';
$text2display .= '<select onchange="if(this.value==1||this.value==2)disableDPI(false);else disableDPI(true);" name="output" size="1" style="width:300px">';
$c = count($table_value);
for ($i = 0; $i < $c; $i++) {
$text2display .= '<option value="' . $table_value[$i] . '"';
if (intval($table_value[$i]) === intval($number)) {
$text2display .= ' selected="selected"';
}
$text2display .= '>' . $table_text[$i] . '</option>';
}
$text2display .= '</select>';
return $text2display;
}
/**
* Displays the DPI
*
* @param int $output
* @param float $dpi
*/
function display_dpi($output, $dpi) {
$disabled = ($output != 1 && $output != 2);
$disableText = $disabled ? ' disabled="disabled"' : '';
$showExplain = $disabled ? '' : ' display: none;';
return '<script type="text/javascript">
function disableDPI(disable){
document.getElementById("dpi").disabled = disable;
document.getElementById("dpi_explain").style.display = disable ? "inline" : "none";
}
</script><input type="text" id="dpi" name="dpi" value="' . $dpi . '" size="5"' . $disableText . ' /> <span id="dpi_explain" style="color: red;' . $showExplain . '">DPI is available only for PNG and JPEG.</span><div style="font-size: 8pt;">If you set <i>null</i>, the image generation will be faster and will be the same as 72dpi.</div>';
}
/**
* Displays the thickness of the bars
*
* @param int $number
*/
function display_thickness($number) {
return '<input type="text" name="thickness" value="' . $number . '" size="5" />';
}
/**
* Displays the resolution of the code
*
* @param int $number
*/
function display_res($number) {
$table = new LSTable(1, 3, '100%', $null);
$table->setTemplate('tpl_BLANK');
for ($i = 1; $i <= 3; $i++) {
$text2display = '';
$text2display .= '<input type="radio" id="res' . $i . '" name="res" value="' . $i . '"';
if ($number === $i) {
$text2display .= ' checked="checked"';
}
$text2display .= ' /> <label for="res' . $i . '">' . $i . '</label>';
$table->setText(0, $i - 1, $text2display);
}
return $table;
}
/**
* Displays the rotation
*
* @param int $rotation
*/
function display_rotation($rotation) {
$availableRotation = array(0, 90, 180, 270);
$c = count($availableRotation);
$table = new LSTable(1, $c, '100%', $null);
$table->setTemplate('tpl_BLANK');
for ($i = 0; $i < $c; $i++) {
$text2display = '';
$text2display .= '<input type="radio" id="rotation' . $i . '" name="rotation" value="' . $availableRotation[$i] . '"';
if ($rotation == $availableRotation[$i]) {
$text2display .= ' checked="checked"';
}
$text2display .= ' /> <label for="rotation' . $i . '">' . $availableRotation[$i] . '&deg;</label>';
$table->setText(0, $i, $text2display);
}
return $table;
}
/**
* Displays the fontsize of the label
*
* @param int $number
*/
function display_font($family, $size) {
if($family === '0') $family = 'Arial.ttf';
$text2display = '';
$text2display .= '<select name="font_family" size="1" style="width:130px">';
$text2display .= '<option value="-1">No Text</option>';
// List of all fonts available
$f = listfonts();
$c = count($f);
for ($i = 0; $i < $c; $i++) {
$text2display .= '<option value="' . $f[$i] . '"';
if ($f[$i] === $family) {
$text2display .= ' selected="selected"';
}
$text2display .= '>' . $f[$i] . '</option>';
}
$text2display .= '</select>';
$text2display .= ' ';
$text2display .= '<input type="text" name="font_size" value="' . $size . '" size="3" style="width:30px" />';
return $text2display;
}
/**
* Displays the textbox
*
* @param string $text
*/
function display_text($text) {
return '<input type="text" name="text2display" value="' . $text . '" size="20" />';
}
/**
* Returns the next class for a table line.
*
* @param int $restart If 1, then restart color to 1
* @return string
*/
function next_color($restart = 0) {
global $sys_conf;
static $color = 0;
if ($restart === 1) { $color = NULL; }
if ($color === 1) { $couleur = 'row2'; $color = 2; }
else { $couleur = 'row1'; $color = 1; }
return $couleur;
}
/**
* Returns the font available for drawing
*
* @return string[]
*/
function listfonts() {
global $class_dir;
$array = array();
if (($handle = opendir($class_dir . '/font')) !== false) {
while (($file = readdir($handle)) !== false) {
if(substr($file, -4, 4) === '.ttf') {
$array[] = $file;
}
}
}
closedir($handle);
return $array;
}
?>

View File

@@ -0,0 +1,46 @@
var nbIdentifiers = 0;
var idRow = 0;
function addIdentifier(id) {
nbIdentifiers++;
idRow++;
if(document.getElementById('identifiersContainer').style.display === 'none') {
document.getElementById('identifiersContainer').style.display = '';
}
if(document.getElementById('identifiersButton').style.display === 'none') {
document.getElementById('identifiersButton').style.display = '';
}
var newIdentifier = document.createElement("DIV");
newIdentifier.id = 'identifier_' + idRow;
newIdentifier.style.height = '25px';
newIdentifier.style.position = 'relative';
newIdentifier.style.marginTop = '2px';
newIdentifier.innerHTML = '<input type="text" name="textTemp[0][]" value="' + id + '" style="width:40px;" /> - <input type="text" name="textTemp[1][]" style="width:295px;" /><a href="javascript:removeIdentifier(' + idRow + ');"><img src="delete.png" alt="Delete" style="border:0px; margin-left:5px; margin-top:5px;" /></a>';
document.getElementById('identifiersContainer').appendChild(newIdentifier);
document.getElementById('identifier').value = '';
}
function removeIdentifier(id) {
nbIdentifiers--;
document.getElementById('identifiersContainer').removeChild(document.getElementById('identifier_' + id));
if(nbIdentifiers === 0) {
document.getElementById('identifiersButton').style.display = 'none';
document.getElementById('identifiersContainer').style.display = 'none';
}
}
function sendForm() {
var text2display = document.getElementsByName("text2display");
var barcodeDrawer = document.getElementsByName("barcode_drawer");
var gs1128Id = document.getElementsByName("textTemp[0][]");
var gs1128Content = document.getElementsByName("textTemp[1][]");
text2display[0].value = '';
for(var i = 0; i < gs1128Id.length; i++) {
text2display[0].value = text2display[0].value + '(' + gs1128Id[i].value + ')';
text2display[0].value = text2display[0].value + gs1128Content[i].value + unescape('%1D');
}
barcodeDrawer[0].submit();
}

View File

@@ -0,0 +1,212 @@
<?php
define('IN_CB', true);
include('header.php');
$vals = array();
for($i = 0; $i <= 127; $i++) {
$vals[] = '%' . sprintf('%02X', $i);
}
$keys = array(
'NUL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'TAB', 'LF', 'VT', 'FF', 'CR', 'SO', 'SI', 'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB', 'CAN', 'EM', 'SUB', 'ESC', 'FS', 'GS', 'RS', 'US',
' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 'DEL'
);
if($a2 == '') {
$a2 = 'C';
}
$n = $table->numRows();
$table->insertRows($n, 5);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Starts With');
$text2display = '<select size="1" name="a2"><option value="A"';
if($a2 == 'A') {
$text2display .= ' selected="selected"';
}
$text2display .= '>Code 128-A</option><option value="B"';
if($a2 == 'B') {
$text2display .= ' selected="selected"';
}
$text2display .= '>Code 128-B</option><option value="C"';
if($a2 == 'C') {
$text2display .= ' selected="selected"';
}
$text2display .= '>Code 128-C</option></select>';
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . htmlentities($keys[$i]) . '" style="width:37px;padding:0px;" onclick="newkey(this.form,unescape(\'' . $vals[$i] . '\'))" /> ';
}
$table->setText($n + 2, 1, $text2display);
/* Application Identifiers (AIs) */
$table->setText($n + 3, 0, 'Identifiers');
$text2display = '<script type="text/javascript" src="gs1128.js"></script>';
$identifiers = array(
'00' => 'Serial Shipping Container Code (SSCC-18)',
'01' => 'Shipping Container Code (SSC)',
'02' => 'Number of containers',
'10' => 'Batch Number',
'11' => 'Production Date',
'12' => 'Due date',
'13' => 'Packaging Date',
'15' => 'Sell by Date (Quality Control)',
'17' => 'Expiration Date',
'20' => 'Product Variant',
'21' => 'Serial Number',
'240' => 'Additional Product Identification',
'241' => 'Customer part number',
'250' => 'Second Serial Number',
'251' => 'Reference to source entity',
'253' => 'Global Document Type Identifier',
'30' => 'Quantity Each',
'310y' => 'Product Net Weight in kg',
'311y' => 'Product Length/1st Dimension, in meters',
'312y' => 'Product Width/Diameter/2nd Dimension, in meters',
'313y' => 'Product Depth/Thickness/3rd Dimension, in meters',
'314y' => 'Product Area, in square meters',
'315y' => 'Product Volume, in liters',
'316y' => 'product Volume, in cubic meters',
'320y' => 'Product Net Weight, in pounds',
'321y' => 'Product Length/1st Dimension, in inches',
'322y' => 'Product Length/1st Dimension, in feet',
'323y' => 'Product Length/1st Dimension, in yards',
'324y' => 'Product Width/Diameter/2nd Dimension, in inches',
'325y' => 'Product Width/Diameter/2nd Dimension, in feet',
'326y' => 'Product Width/Diameter/2nd Dimension, in yards',
'327y' => 'Product Depth/Thickness/3rd Dimension, in inches',
'328y' => 'Product Depth/Thickness/3rd Dimension, in feet',
'329y' => 'Product Depth/Thickness/3rd Dimension, in yards',
'330y' => 'Container Gross Weight (Kg)',
'331y' => 'Container Length/1st Dimension (Meters)',
'332y' => 'Container Width/Diameter/2nd Dimension (Meters)',
'333y' => 'Container Depth/Thickness/3rd Dimension (Meters)',
'334y' => 'Container Area (Square Meters)',
'335y' => 'Container Gross Volume (Liters)',
'336y' => 'Container Gross Volume (Cubic Meters)',
'337y' => 'Kilograms per square meter',
'340y' => 'Container Gross Weight (Pounds)',
'341y' => 'Container Length/1st Dimension, in inches',
'342y' => 'Container Length/1st Dimension, in feet',
'343y' => 'Container Length/1st Dimension in, in yards',
'344y' => 'Container Width/Diameter/2nd Dimension, in inches',
'345y' => 'Container Width/Diameter/2nd Dimension, in feet',
'346y' => 'Container Width/Diameter/2nd Dimension, in yards',
'347y' => 'Container Depth/Thickness/Height/3rd Dimension, in inches',
'348y' => 'Container Depth/Thickness/Height/3rd Dimension, in feet',
'349y' => 'Container Depth/Thickness/Height/3rd Dimension, in yards',
'350y' => 'Product Area (Square Inches)',
'351y' => 'Product Area (Square Feet)',
'352y' => 'Product Area (Square Yards)',
'353y' => 'Container Area (Square Inches)',
'354y' => 'Container Area (Square Feet)',
'355y' => 'Container Area (Square Yards)',
'356y' => 'Net Weight (Troy Ounces)',
'357y' => 'Kilograms per square meter',
'360y' => 'Product Volume (Quarts)',
'361y' => 'Product Volume (Gallons)',
'362y' => 'Container Gross Volume (Quarts)',
'363y' => 'Container Gross Volume (Gallons)',
'364y' => 'Product Volume (Cubic Inches)',
'365y' => 'Product Volume (Cubic Feet)',
'366y' => 'Product Volume (Cubic Yards)',
'367y' => 'Container Gross Volume (Cubic Inches)',
'368y' => 'Container Gross Volume (Cubic Feet)',
'369y' => 'Container Gross Volume (Cubic Yards)',
'37' => 'Number of Units Contained',
'390y' => 'Amount payable-single monetary area',
'391y' => 'Amount payable with ISO currency code',
'392y' => 'Amount payable for a Variable Measure Trade Item single monetary unit',
'393y' => 'Amount payable for a Variable Measure Trade Item - with ISO currency code',
'400' => 'Customer Purchase Order Number',
'401' => 'Consignment number',
'402' => 'Shipment Identification Number',
'403' => 'Routing code',
'410' => 'Ship To/Deliver To Location Code (EAN13 or DUNS code)',
'411' => 'Bill To/Invoice Location Code (EAN13 or DUNS code)',
'412' => 'Purchase From Location Code (EAN13 or DUNS code)',
'413' => 'Ship for - deliver for - forward to EAN.UCC Global Location Number',
'414' => 'Identification of a physical location EAN.UCC Global Location Number',
'415' => 'EAN.UCC Global Location Number of the invoicing party',
'420' => 'Ship To/Deliver To Postal Code (Single Postal Authority)',
'421' => 'Ship To/Deliver To Postal Code (Multiple Postal Authority)',
'422' => 'Country of origin of a trade item',
'8001' => 'Roll Products - Width/Length/Core Diameter',
'8002' => 'Electronic Serial Number (ESN) for Cellular Phone',
'8003' => 'UPC/EAN Number and Serial Number of Returnable Asset',
'8004' => 'UPC/EAN Serial Identification',
'8005' => 'Price per Unit of Measure',
'8006' => 'Identification of the component of a trade item',
'8007' => 'International Bank Account Number',
'8018' => 'EAN.UCC Global Service Relation Number',
'8020' => 'Payment Slip Reference Number',
'8100' => 'Coupon Extended Code: Number System and Offer',
'8101' => '8101 Coupon Extended Code: Number System, Offer, End of Offer',
'8102' => 'Coupon Extended Code: Number System preceded by 0',
'90' => 'Mutually Agreed Between Trading Partners',
'91' => 'Internal Company Codes',
'92' => 'Internal Company Codes',
'93' => 'Internal Company Codes',
'94' => 'Internal Company Codes',
'95' => 'Internal Company Codes',
'96' => 'Internal Company Codes',
'97' => 'Internal Company Codes',
'98' => 'Internal Company Codes',
'99' => 'Internal Company Codes'
);
$identifiersPost = isset($_POST['textTemp']) ? $_POST['textTemp'] : '';
if(!is_array($identifiersPost)) {
$identifiersPost = '';
}
if($identifiersPost != '') {
$displayDiv = '';
} else {
$displayDiv = 'none';
}
$text2display .= '<select name="identifier" id="identifier" style="width:300px;" onchange="addIdentifier(identifier.options[identifier.selectedIndex].value)">';
$text2display .= '<option value="">Please select an identifier ...</option>';
foreach($identifiers as $id => $identifiers) {
$text2display .= '<option value="' . $id . '">' . $id . ' - ' . $identifiers . '</option>';
}
$text2display .= '</select><div id="identifiersContainer" style="display:' . $displayDiv . '; padding-bottom:5px;">';
if($identifiersPost != '') {
$identifiersIdPost = $identifiersPost[0];
$identifiersContentPost = $identifiersPost[1];
$c = count($identifiersIdPost);
for($i = 0; $i < $c; $i++) {
$text2display .= '<div id="identifier_' . $i . '" style="height:25px; position:relative; margin-top:2px;">';
$text2display .= '<input type="text" name="textTemp[0][]" value="' . $identifiersIdPost[$i] . '" style="width:40px;" /> - <input type="text" name="textTemp[1][]" style="width:295px;" value="' . $identifiersContentPost[$i] . '" /><a href="javascript:removeIdentifier(' . $i . ');"><img src="delete.png" alt="" style="border:0px; margin-left:5px; margin-top:5px;" /></a>';
$text2display .= '</div>';
}
$text2display .= '<script type="text/javascript">var nbIdentifiers = ' . $c . '; var idRow = ' . $c . ';</script>';
}
$text2display .= '</div>';
$text2display .= '<div style="text-align:center;"><input id="identifiersButton" type="button" value="Generate GS1-128 CODE" style="display:' . $displayDiv . '; margin-top:5px;" onclick="sendForm()" /></div>';
$table->setText($n + 3, 1, $text2display);
$table->setText($n + 4, 0, 'Explanation');
$table->setText($n + 4, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Encoded as Code 128.</li><li>The former correct name was UCC/EAN-128.</li><li>Use for shipping containers.</li><li>Based on the GS1 standard.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,107 @@
<?php
if(!defined('IN_CB')) die('You are not allowed to access to this page.');
define('VERSION', '2.2.0');
if(version_compare(phpversion(), '4.3.0', '>=') !== true)
exit('Sorry, but you have to run this script with PHP4.3+... You currently have the version <b>'.phpversion().'</b>.');
if(!function_exists('imagecreate'))
exit('Sorry, make sure you have the GD extension installed before running this script.');
include('config.php');
require('function.php');
include('LSTable.php');
echo '<?xml version="1.0" encoding="iso-8859-1"?>' . "\n";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Drawing Barcode</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link type="text/CSS" rel="stylesheet" href="./style.css" />
<script language="JavaScript" type="text/javascript">
function newkey(form,variable){
form.text2display.value += variable;
}
function newkeyCode(form,variable){
form.text2display.value += String.fromCharCode(variable);
}
</script>
</head>
<body bgcolor="#ffffff">
<?php
if(version_compare(phpversion(), '5.0.0', '>=') === true)
echo '<i>[WARNING] You currently run this script with PHP5... we advise you to use the PHP5 version of this script if you experience any problems.</i>';
// FileName & Extension
$system_temp_array = explode('/', $_SERVER['PHP_SELF']);
$system_temp_array2 = explode('.', $system_temp_array[count($system_temp_array) - 1]);
$filename = $system_temp_array2[0];
$default_value = array();
$default_value['output'] = 1;
$default_value['dpi'] = 72;
$default_value['thickness'] = 30;
$default_value['res'] = 1;
$default_value['rotation'] = 0.0;
$default_value['font_family'] = '0';
$default_value['font_size'] = 8;
$default_value['text2display'] = '';
$default_value['a1'] = '';
$default_value['a2'] = '';
$default_value['a3'] = '';
$output = intval(isset($_POST['output']) ? $_POST['output'] : $default_value['output']);
$dpi = isset($_POST['dpi']) ? $_POST['dpi'] : $default_value['dpi'];
$thickness = intval(isset($_POST['thickness']) ? $_POST['thickness'] : $default_value['thickness']);
$res = intval(isset($_POST['res']) ? $_POST['res'] : $default_value['res']);
$rotation = isset($_POST['rotation']) ? $_POST['rotation'] : $default_value['rotation'];
$font_family = isset($_POST['font_family']) ? $_POST['font_family'] : $default_value['font_family'];
$font_size = intval(isset($_POST['font_size']) ? $_POST['font_size'] : $default_value['font_size']);
$text2display = isset($_POST['text2display']) ? $_POST['text2display'] : $default_value['text2display'];
$a1 = isset($_POST['a1']) ? $_POST['a1'] : $default_value['a1'];
$a2 = isset($_POST['a2']) ? $_POST['a2'] : $default_value['a2'];
$a3 = isset($_POST['a3']) ? $_POST['a3'] : $default_value['a3'];
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="barcode_drawer" method="post">
<?php
$table = new LSTable(10, 2, '500', $null);
$table->setTitle('Configs for ' . $filename);
$table->addRowAttribute(0, 'class', 'table_title');
$table->addCellAttribute(0, 0, 'colspan', '2');
$table->addCellAttribute(0, 0, 'align', 'center');
$table->setText(0, 0, '<font color="#ffffff"><b>General Configs</b></font>');
$table->addCellAttribute(1, 0, 'width', '100');
$table->setText(1, 0, 'Type');
$table->setText(1, 1, display_select($filename));
$table->setText(2, 0, 'Output');
$table->setText(2, 1, display_output($output, $dpi));
$table->setText(3, 0, 'DPI');
$table->setText(3, 1, display_dpi($output, $dpi));
$table->setText(4, 0, 'Thickness');
$table->setText(4, 1, display_thickness($thickness));
$table->setText(5, 0, 'Resolution');
$table->setText(5, 1, display_res($res));
$table->setText(6, 0, 'Rotation');
$table->setText(6, 1, display_rotation($rotation));
$table->setText(7, 0, 'Font');
$table->setText(7, 1, display_font($font_family, $font_size));
$table->setText(8, 0, 'Text');
$table->setText(8, 1, display_text($text2display));
$table->addCellAttribute(9, 0, 'align', 'center');
$table->addCellAttribute(9, 0, 'colspan', '2');
$table->setText(9, 0, '<input type="submit" value="Generate" />');
if(!empty($text2display)) {
$table->insertRows(10, 1);
$table->addCellAttribute(10, 0, 'align', 'center');
$table->addCellAttribute(10, 0, 'colspan', '2');
$table->addRowAttribute(10, 'style','background-color: #ffffff');
$table->setText(10, 0, '<img src="image.php?code=' . $filename . '&amp;o=' . $output . '&amp;dpi=' . $dpi . '&amp;t=' . $thickness . '&amp;r=' . $res . '&amp;rot=' . $rotation . '&amp;text=' . urlencode($text2display) . '&amp;f1=' . $font_family . '&amp;f2=' . $font_size . '&amp;a1=' . $a1 . '&amp;a2=' . $a2 . '&amp;a3=' . $a3 . '" alt="Barcode Image" />');
}
?>

View File

@@ -0,0 +1,34 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$n = $table->numRows();
$table->insertRows($n, 4);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, '<label for="checksum">Checksum</label>');
$text2display = '<input type="checkbox" name="a1" id="checksum" value="1"';
if($a1 == 1) {
$text2display .= ' checked="checked"';
}
$text2display .= ' />';
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' .$keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 2, 1, $text2display);
$table->setText($n + 3, 0, 'Explanation');
$table->setText($n + 3, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Interleaved 2 of 5 is based on Standard 2 of 5 symbology.</li><li>There is an optional checksum.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,57 @@
<?php
if(isset($_GET['code'], $_GET['t'], $_GET['r'], $_GET['rot'], $_GET['text'], $_GET['f1'], $_GET['f2'], $_GET['o'], $_GET['dpi'], $_GET['a1'], $_GET['a2'])) {
require('config.php');
require($class_dir . '/BCGColor.php');
require($class_dir . '/BCGBarcode.php');
require($class_dir . '/BCGDrawing.php');
require($class_dir . '/BCGFont.php');
if(include($class_dir . '/BCG' . $_GET['code'] . '.barcode.php')) {
if($_GET['f1'] !== '0' && $_GET['f1'] !== '-1' && intval($_GET['f2']) >= 1) {
$font =& new BCGFont($class_dir . '/font/' . $_GET['f1'], intval($_GET['f2']));
} else {
$font = 0;
}
$color_black =& new BCGColor(0, 0, 0);
$color_white =& new BCGColor(255, 255, 255);
$codebar = 'BCG' . $_GET['code'];
$code_generated =& new $codebar();
if(isset($_GET['a1']) && intval($_GET['a1']) === 1) {
$code_generated->setChecksum(true);
}
if(isset($_GET['a2']) && !empty($_GET['a2'])) {
$code_generated->setStart($_GET['a2']);
}
if(isset($_GET['a3']) && !empty($_GET['a3'])) {
$code_generated->setLabel($_GET['a3']);
}
$code_generated->setThickness($_GET['t']);
$code_generated->setScale($_GET['r']);
$code_generated->setBackgroundColor($color_white);
$code_generated->setForegroundColor($color_black);
$code_generated->setFont($font);
$code_generated->parse($_GET['text']);
$drawing =& new BCGDrawing('', $color_white);
$drawing->setBarcode($code_generated);
$drawing->setRotationAngle($_GET['rot']);
$drawing->setDPI($_GET['dpi'] == 'null' ? null : (int)$_GET['dpi']);
$drawing->draw();
if(intval($_GET['o']) === 1) {
header('Content-Type: image/png');
} elseif(intval($_GET['o']) === 2) {
header('Content-Type: image/jpeg');
} elseif(intval($_GET['o']) === 3) {
header('Content-Type: image/gif');
}
$drawing->finish(intval($_GET['o']));
}
else{
header('Content-Type: image/png');
readfile('error.png');
}
}
else{
header('Content-Type: image/png');
readfile('error.png');
}
?>

View File

@@ -0,0 +1,3 @@
<?php
header('Location: code39.php');
?>

View File

@@ -0,0 +1,27 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>ISBN stands for International Standard Book Number.</li><li>ISBN type is based on EAN-13.</li><li>Previously, all ISBN were in EAN-10 format. EAN-13 uses the same encoding but may contain different data in the ISBN number.</li><li>Composed by a GS1 prefix (for ISBN-13), a group identifier, a publisher code, an item number and a check digit.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,34 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$n = $table->numRows();
$table->insertRows($n, 4);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, '<label for="checksum">Checksum</label>');
$text2display = '<input type="checkbox" name="a1" id="checksum" value="1"';
if($a1==1) {
$text2display .= ' checked="checked"';
}
$text2display .= ' />';
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 2, 1, $text2display);
$table->setText($n + 3, 0, 'Explanation');
$table->setText($n + 3, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Developed by the MSI Data Corporation.</li><li>Used primarily to mark retail shelves for inventory control.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,20 @@
<?php
define('IN_CB', true);
include('header.php');
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Text Label');
$table->setText($n + 1, 1, '<input type="text" name="a3" value="' . $a3 . '" />');
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Enter width of each bars with one characters. Begin by a bar.</li><li>10523 : Will do 2px bar, 1px space, 6px bar, 3px space, 4px bar.</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,27 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$n = $table->numRows();
$table->insertRows($n, 3);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0, 'align', 'center');
$table->addCellAttribute($n, 0, 'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Explanation');
$table->setText($n + 2, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Used to encode enveloppe in USA.</li><li>You can provide<br />5 digits (ZIP Code)<br />9 digits (ZIP+4 code)<br />11 digits (ZIP+4 code+2 digits)<br />(Those 2 digits are taken from your address. If your address is 6453, the code will be 53.)</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

View File

@@ -0,0 +1,34 @@
<?php
define('IN_CB', true);
include('header.php');
$keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$n = $table->numRows();
$table->insertRows($n, 4);
$table->addRowAttribute($n, 'class', 'table_title');
$table->addCellAttribute($n, 0,'align', 'center');
$table->addCellAttribute($n, 0,'colspan', '2');
$table->setText($n, 0, '<font color="#ffffff"><b>Specifics Configs</b></font>');
$table->setText($n + 1, 0, '<label for="checksum">Checksum</label>');
$text2display = '<input type="checkbox" name="a1" id="checksum" value="1"';
if($a1 == 1) {
$text2display .= ' checked="checked"';
}
$text2display .= ' />';
$table->setText($n + 1, 1, $text2display);
$table->setText($n + 2, 0, 'Keys');
$text2display = '';
$c = count($keys);
for($i = 0; $i < $c; $i++) {
$text2display .= '<input type="button" value="' . $keys[$i] . '" style="width:25px;padding:0px;" onclick="newkey(this.form,\'' . $keys[$i] . '\')" /> ';
}
$table->setText($n + 2, 1, $text2display);
$table->setText($n + 3, 0, 'Explanation');
$table->setText($n + 3, 1, '<ul style="margin: 0px; padding-left: 25px;"><li>Known also as Industrial 2 of 5.</li><li>Standard 2 of 5 is a low-density numeric symbology that has been with us since the 1960s.</li><li>There is an optional checksum.</li><li>Note : Standard 2 of 5 is REALLY tough to read !</li></ul>');
$table->draw();
echo '</form>';
include('footer.php');
?>

Some files were not shown because too many files have changed in this diff Show More