barcode.lib.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. /* Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2004-2010 Folke Ashberg: Some lines of code were inspired from work
  4. * of Folke Ashberg into PHP-Barcode 0.3pl2, available as GPL
  5. * source code at http://www.ashberg.de/bar.
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. /**
  21. * \file htdocs/core/lib/barcode.lib.php
  22. * \brief Set of functions used for barcode generation (internal lib, also code 'phpbarcode')
  23. * \ingroup core
  24. */
  25. /* ******************************************************************** */
  26. /* COLORS */
  27. /* ******************************************************************** */
  28. $bar_color = array(0, 0, 0);
  29. $bg_color = array(255, 255, 255);
  30. $text_color = array(0, 0, 0);
  31. /* ******************************************************************** */
  32. /* FONT FILE */
  33. /* ******************************************************************** */
  34. if (defined('DOL_DEFAULT_TTF_BOLD')) {
  35. $font_loc = constant('DOL_DEFAULT_TTF_BOLD');
  36. }
  37. // Automatic-Detection of Font if running Windows
  38. // @CHANGE LDR
  39. if (isset($_SERVER['WINDIR']) && @file_exists($_SERVER['WINDIR'])) {
  40. $font_loc = $_SERVER['WINDIR'].'\Fonts\arialbd.ttf';
  41. }
  42. if (empty($font_loc)) {
  43. die('DOL_DEFAULT_TTF_BOLD must de defined with full path to a TTF font.');
  44. }
  45. /* ******************************************************************** */
  46. /* GENBARCODE */
  47. /* ******************************************************************** */
  48. /* location of 'genbarcode'
  49. * leave blank if you don't have them :(
  50. * genbarcode is needed to render encodings other than EAN-12/EAN-13/ISBN
  51. */
  52. if (defined('PHP-BARCODE_PATH_COMMAND')) {
  53. $genbarcode_loc = constant('PHP-BARCODE_PATH_COMMAND');
  54. } else {
  55. $genbarcode_loc = $conf->global->GENBARCODE_LOCATION;
  56. }
  57. /**
  58. * Print barcode
  59. *
  60. * @param string $code Code
  61. * @param string $encoding Encoding ('EAN13', 'ISBN', 'C128', 'UPC', 'CBR', 'QRCODE', 'DATAMATRIX', 'ANY'...)
  62. * @param integer $scale Scale
  63. * @param string $mode 'png' or 'jpg' ...
  64. * @return array|string $bars array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info) or string with error message
  65. */
  66. function barcode_print($code, $encoding = "ANY", $scale = 2, $mode = "png")
  67. {
  68. dol_syslog("barcode.lib.php::barcode_print $code $encoding $scale $mode");
  69. $bars = barcode_encode($code, $encoding);
  70. if (!$bars || !empty($bars['error'])) {
  71. // Return error message instead of array
  72. if (empty($bars['error'])) {
  73. $error = 'Bad Value '.$code.' for encoding '.$encoding;
  74. } else {
  75. $error = $bars['error'];
  76. }
  77. dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR);
  78. return $error;
  79. }
  80. if (!$mode) {
  81. $mode = "png";
  82. }
  83. //if (preg_match("/^(text|txt|plain)$/i",$mode)) print barcode_outtext($bars['text'],$bars['bars']);
  84. //elseif (preg_match("/^(html|htm)$/i",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0);
  85. //else
  86. barcode_outimage($bars['text'], $bars['bars'], $scale, $mode);
  87. return $bars;
  88. }
  89. /**
  90. * Encodes $code with $encoding using genbarcode OR built-in encoder if you don't have genbarcode only EAN-13/ISBN or UPC is possible
  91. *
  92. * You can use the following encodings (when you have genbarcode):
  93. * ANY choose best-fit (default)
  94. * EAN 8 or 13 EAN-Code
  95. * UPC 12-digit EAN
  96. * ISBN isbn numbers (still EAN-13)
  97. * 39 code 39
  98. * 128 code 128 (a,b,c: autoselection)
  99. * 128C code 128 (compact form for digits)
  100. * 128B code 128, full printable ascii
  101. * I25 interleaved 2 of 5 (only digits)
  102. * 128RAW Raw code 128 (by Leonid A. Broukhis)
  103. * CBR Codabar (by Leonid A. Broukhis)
  104. * MSI MSI (by Leonid A. Broukhis)
  105. * PLS Plessey (by Leonid A. Broukhis)
  106. *
  107. * @param string $code Code
  108. * @param string $encoding Encoding
  109. * @return array|false array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info)
  110. */
  111. function barcode_encode($code, $encoding)
  112. {
  113. global $genbarcode_loc;
  114. if ((preg_match("/^upc$/i", $encoding))
  115. && (preg_match("/^[0-9]{11,12}$/", $code))
  116. ) {
  117. /* use built-in UPC-Encoder */
  118. dol_syslog("barcode.lib.php::barcode_encode Use barcode_encode_upc");
  119. $bars = barcode_encode_upc($code, $encoding);
  120. } elseif ((preg_match("/^ean$/i", $encoding))
  121. || (($encoding) && (preg_match("/^isbn$/i", $encoding))
  122. && ((strlen($code) == 9 || strlen($code) == 10) ||
  123. (((preg_match("/^978/", $code) && strlen($code) == 12) ||
  124. (strlen($code) == 13)))))
  125. || ((!isset($encoding) || !$encoding || (preg_match("/^ANY$/i", $encoding)))
  126. && (preg_match("/^[0-9]{12,13}$/", $code)))
  127. ) {
  128. /* use built-in EAN-Encoder */
  129. dol_syslog("barcode.lib.php::barcode_encode Use barcode_encode_ean");
  130. $bars = barcode_encode_ean($code, $encoding);
  131. } elseif (file_exists($genbarcode_loc)) { // For example C39
  132. /* use genbarcode */
  133. dol_syslog("barcode.lib.php::barcode_encode Use genbarcode ".$genbarcode_loc." code=".$code." encoding=".$encoding);
  134. $bars = barcode_encode_genbarcode($code, $encoding);
  135. } else {
  136. print "barcode_encode needs an external program for encodings other then EAN/ISBN (code=".dol_escape_htmltag($code).", encoding=".dol_escape_htmltag($encoding).")<BR>\n";
  137. print "<UL>\n";
  138. print "<LI>download gnu-barcode from <A href=\"https://www.gnu.org/software/barcode/\">www.gnu.org/software/barcode/</A>\n";
  139. print "<LI>compile and install them\n";
  140. print "<LI>specify path the genbarcode in barcode module setup\n";
  141. print "</UL>\n";
  142. print "<BR>\n";
  143. return false;
  144. }
  145. return $bars;
  146. }
  147. /**
  148. * Calculate EAN sum
  149. *
  150. * @param string $ean EAN to encode
  151. * @return integer Sum
  152. */
  153. function barcode_gen_ean_sum($ean)
  154. {
  155. $even = true;
  156. $esum = 0;
  157. $osum = 0;
  158. $ln = strlen($ean) - 1;
  159. for ($i = $ln; $i >= 0; $i--) {
  160. if ($even) {
  161. $esum += $ean[$i];
  162. } else {
  163. $osum += $ean[$i];
  164. }
  165. $even = !$even;
  166. }
  167. return (10 - ((3 * $esum + $osum) % 10)) % 10;
  168. }
  169. /**
  170. * Generate EAN bars
  171. *
  172. * @param string $ean EAN to encode
  173. * @return string Encoded EAN
  174. */
  175. function barcode_gen_ean_bars($ean)
  176. {
  177. $digits = array(3211, 2221, 2122, 1411, 1132, 1231, 1114, 1312, 1213, 3112);
  178. $mirror = array("000000", "001011", "001101", "001110", "010011", "011001", "011100", "010101", "010110", "011010");
  179. $guards = array("9a1a", "1a1a1", "a1a7");
  180. $line = $guards[0];
  181. for ($i = 1; $i < 13; $i++) {
  182. $str = $digits[$ean[$i]];
  183. if ($i < 7 && $mirror[$ean[0]][$i - 1] == 1) {
  184. $line .= strrev($str);
  185. } else {
  186. $line .= $str;
  187. }
  188. if ($i == 6) {
  189. $line .= $guards[1];
  190. }
  191. }
  192. $line .= $guards[2];
  193. return $line;
  194. }
  195. /**
  196. * Encode EAN
  197. *
  198. * @param string $ean Code
  199. * @param string $encoding Encoding
  200. * @return array array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info, 'error': error message if error)
  201. */
  202. function barcode_encode_ean($ean, $encoding = "EAN-13")
  203. {
  204. $ean = trim($ean);
  205. if (preg_match("/[^0-9]/i", $ean)) {
  206. return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (not a numeric)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (not a numeric)");
  207. }
  208. $encoding = strtoupper($encoding);
  209. if ($encoding == "ISBN") {
  210. if (!preg_match("/^978/", $ean)) {
  211. $ean = "978".$ean;
  212. }
  213. }
  214. if (preg_match("/^97[89]/", $ean)) {
  215. $encoding = "ISBN";
  216. }
  217. if (strlen($ean) < 12 || strlen($ean) > 13) {
  218. return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (must have 12/13 numbers)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$ean." (must have 12/13 numbers)");
  219. }
  220. $ean = substr($ean, 0, 12);
  221. $eansum = barcode_gen_ean_sum($ean);
  222. $ean .= $eansum;
  223. $bars = barcode_gen_ean_bars($ean);
  224. /* create text */
  225. $pos = 0;
  226. $text = "";
  227. for ($a = 0; $a < 13; $a++) {
  228. if ($a > 0) {
  229. $text .= " ";
  230. }
  231. $text .= "$pos:12:{$ean[$a]}";
  232. if ($a == 0) {
  233. $pos += 12;
  234. } elseif ($a == 6) {
  235. $pos += 12;
  236. } else {
  237. $pos += 7;
  238. }
  239. }
  240. return array(
  241. "error" => '',
  242. "encoding" => $encoding,
  243. "bars" => $bars,
  244. "text" => $text
  245. );
  246. }
  247. /**
  248. * Encode UPC
  249. *
  250. * @param string $upc Code
  251. * @param string $encoding Encoding
  252. * @return array array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info, 'error': error message if error)
  253. */
  254. function barcode_encode_upc($upc, $encoding = "UPC")
  255. {
  256. $upc = trim($upc);
  257. if (preg_match("/[^0-9]/i", $upc)) {
  258. return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$upc." (not a numeric)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$upc." (not a numeric)");
  259. }
  260. $encoding = strtoupper($encoding);
  261. if (strlen($upc) < 11 || strlen($upc) > 12) {
  262. return array("error"=>"Invalid encoding/code. encoding=".$encoding." code=".$upc." (must have 11/12 numbers)", "text"=>"Invalid encoding/code. encoding=".$encoding." code=".$upc." (must have 11/12 numbers)");
  263. }
  264. $upc = substr("0".$upc, 0, 12);
  265. $eansum = barcode_gen_ean_sum($upc);
  266. $upc .= $eansum;
  267. $bars = barcode_gen_ean_bars($upc);
  268. /* create text */
  269. $pos = 0;
  270. $text = "";
  271. for ($a = 1; $a < 13; $a++) {
  272. if ($a > 1) {
  273. $text .= " ";
  274. }
  275. $text .= "$pos:12:{$upc[$a]}";
  276. if ($a == 1) {
  277. $pos += 15;
  278. } elseif ($a == 6) {
  279. $pos += 17;
  280. } elseif ($a == 11) {
  281. $pos += 15;
  282. } else {
  283. $pos += 7;
  284. }
  285. }
  286. return array(
  287. "error" => '',
  288. "encoding" => $encoding,
  289. "bars" => $bars,
  290. "text" => $text
  291. );
  292. }
  293. /**
  294. * Encode result of genbarcode command
  295. *
  296. * @param string $code Code
  297. * @param string $encoding Encoding
  298. * @return array|false array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info)
  299. */
  300. function barcode_encode_genbarcode($code, $encoding)
  301. {
  302. global $genbarcode_loc;
  303. // Clean parameters
  304. if (preg_match("/^ean$/i", $encoding) && strlen($code) == 13) {
  305. $code = substr($code, 0, 12);
  306. }
  307. if (!$encoding) {
  308. $encoding = "ANY";
  309. }
  310. $encoding = preg_replace("/[\\\|]/", "_", $encoding);
  311. $code = preg_replace("/[\\\|]/", "_", $code);
  312. $command = escapeshellarg($genbarcode_loc);
  313. //$paramclear=" \"".str_replace("\"", "\\\"",$code)."\" \"".str_replace("\"", "\\\"",strtoupper($encoding))."\"";
  314. $paramclear = " ".escapeshellarg($code)." ".escapeshellarg(strtoupper($encoding));
  315. $fullcommandclear = $command." ".$paramclear." 2>&1";
  316. //print $fullcommandclear."<br>\n";exit;
  317. dol_syslog("Run command ".$fullcommandclear);
  318. $fp = popen($fullcommandclear, "r");
  319. if ($fp) {
  320. $bars = fgets($fp, 1024);
  321. $text = fgets($fp, 1024);
  322. $encoding = fgets($fp, 1024);
  323. pclose($fp);
  324. } else {
  325. dol_syslog("barcode.lib.php::barcode_encode_genbarcode failed to run popen ".$fullcommandclear, LOG_ERR);
  326. return false;
  327. }
  328. //var_dump($bars);
  329. $ret = array(
  330. "bars" => trim($bars),
  331. "text" => trim($text),
  332. "encoding" => trim($encoding),
  333. "error" => ""
  334. );
  335. //var_dump($ret);
  336. if (preg_match('/permission denied/i', $ret['bars'])) {
  337. $ret['error'] = $ret['bars'];
  338. $ret['bars'] = '';
  339. return $ret;
  340. }
  341. if (!$ret['bars']) {
  342. return false;
  343. }
  344. if (!$ret['text']) {
  345. return false;
  346. }
  347. if (!$ret['encoding']) {
  348. return false;
  349. }
  350. return $ret;
  351. }
  352. /**
  353. * Output image onto standard output, or onto disk if global filebarcode is defined
  354. *
  355. * @param string $text the text-line (<position>:<font-size>:<character> ...)
  356. * @param string $bars where to place the bars (<space-width><bar-width><space-width><bar-width>...)
  357. * @param int $scale scale factor ( 1 < scale < unlimited (scale 50 will produce 5400x300 pixels when using EAN-13!!!))
  358. * @param string $mode png,gif,jpg (default='png')
  359. * @param int $total_y the total height of the image ( default: scale * 60 )
  360. * @param array $space default: $space[top] = 2 * $scale; $space[bottom]= 2 * $scale; $space[left] = 2 * $scale; $space[right] = 2 * $scale;
  361. * @return string|null
  362. */
  363. function barcode_outimage($text, $bars, $scale = 1, $mode = "png", $total_y = 0, $space = '')
  364. {
  365. global $bar_color, $bg_color, $text_color;
  366. global $font_loc, $filebarcode;
  367. //print "$text, $bars, $scale, $mode, $total_y, $space, $font_loc, $filebarcode<br>";
  368. //var_dump($text);
  369. //var_dump($bars);
  370. //var_dump($font_loc);
  371. /* set defaults */
  372. if ($scale < 1) {
  373. $scale = 2;
  374. }
  375. $total_y = (int) $total_y;
  376. if ($total_y < 1) {
  377. $total_y = (int) $scale * 60;
  378. }
  379. if (!$space) {
  380. $space = array('top'=>2 * $scale, 'bottom'=>2 * $scale, 'left'=>2 * $scale, 'right'=>2 * $scale);
  381. }
  382. /* count total width */
  383. $xpos = 0;
  384. $width = true;
  385. $ln = strlen($bars);
  386. for ($i = 0; $i < $ln; $i++) {
  387. $val = strtolower($bars[$i]);
  388. if ($width) {
  389. $xpos += $val * $scale;
  390. $width = false;
  391. continue;
  392. }
  393. if (preg_match("/[a-z]/", $val)) {
  394. /* tall bar */
  395. $val = ord($val) - ord('a') + 1;
  396. }
  397. $xpos += $val * $scale;
  398. $width = true;
  399. }
  400. /* allocate the image */
  401. $total_x = ($xpos) + $space['right'] + $space['right'];
  402. $xpos = $space['left'];
  403. if (!function_exists("imagecreate")) {
  404. print "You don't have the gd2 extension enabled<br>\n";
  405. return "";
  406. }
  407. $im = imagecreate($total_x, $total_y);
  408. /* create two images */
  409. $col_bg = ImageColorAllocate($im, $bg_color[0], $bg_color[1], $bg_color[2]);
  410. $col_bar = ImageColorAllocate($im, $bar_color[0], $bar_color[1], $bar_color[2]);
  411. $col_text = ImageColorAllocate($im, $text_color[0], $text_color[1], $text_color[2]);
  412. $height = round($total_y - ($scale * 10));
  413. $height2 = round($total_y - $space['bottom']);
  414. /* paint the bars */
  415. $width = true;
  416. $ln = strlen($bars);
  417. for ($i = 0; $i < $ln; $i++) {
  418. $val = strtolower($bars[$i]);
  419. if ($width) {
  420. $xpos += $val * $scale;
  421. $width = false;
  422. continue;
  423. }
  424. if (preg_match("/[a-z]/", $val)) {
  425. /* tall bar */
  426. $val = ord($val) - ord('a') + 1;
  427. $h = $height2;
  428. } else {
  429. $h = $height;
  430. }
  431. imagefilledrectangle($im, $xpos, $space['top'], $xpos + ($val * $scale) - 1, $h, $col_bar);
  432. $xpos += $val * $scale;
  433. $width = true;
  434. }
  435. $chars = explode(" ", $text);
  436. foreach ($chars as $v) {
  437. if (trim($v)) {
  438. $inf = explode(":", $v);
  439. $fontsize = $scale * ($inf[1] / 1.8);
  440. $fontheight = $total_y - ($fontsize / 2.7) + 2;
  441. imagettftext($im, $fontsize, 0, $space['left'] + ($scale * $inf[0]) + 2, $fontheight, $col_text, $font_loc, $inf[2]);
  442. }
  443. }
  444. /* output the image */
  445. $mode = strtolower($mode);
  446. if ($mode == 'jpg' || $mode == 'jpeg') {
  447. header("Content-Type: image/jpeg; name=\"barcode.jpg\"");
  448. imagejpeg($im);
  449. } elseif ($mode == 'gif') {
  450. header("Content-Type: image/gif; name=\"barcode.gif\"");
  451. imagegif($im);
  452. } elseif (!empty($filebarcode)) {
  453. // To wxrite into afile onto disk
  454. imagepng($im, $filebarcode);
  455. } else {
  456. header("Content-Type: image/png; name=\"barcode.png\"");
  457. imagepng($im);
  458. }
  459. }