barcode.lib.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <?php
  2. /* Copyright (C) 2004-2012 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 <http://www.gnu.org/licenses/>.
  19. */
  20. /**
  21. * \file htdocs/core/lib/barcode.lib.php
  22. * \brief Set of functions used for barcode generation
  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')) $font_loc=constant('DOL_DEFAULT_TTF_BOLD');
  35. // Automatic-Detection of Font if running Windows
  36. // DOL_CHANGE LDR
  37. if (isset($_SERVER['WINDIR']) && @file_exists($_SERVER['WINDIR'])) $font_loc=$_SERVER['WINDIR'].'\Fonts\arialbd.ttf';
  38. if (empty($font_loc)) die('DOL_DEFAULT_TTF_BOLD must de defined with full path to a TTF font.');
  39. /* ******************************************************************** */
  40. /* GENBARCODE */
  41. /* ******************************************************************** */
  42. /* location of 'genbarcode'
  43. * leave blank if you don't have them :(
  44. * genbarcode is needed to render encodings other than EAN-12/EAN-13/ISBN
  45. */
  46. if (defined('PHP-BARCODE_PATH_COMMAND')) $genbarcode_loc=constant('PHP-BARCODE_PATH_COMMAND');
  47. else $genbarcode_loc = $conf->global->GENBARCODE_LOCATION;
  48. //dol_syslog("genbarcode_loc=".$genbarcode_loc." - env_windows=".$_SERVER['WINDIR']);
  49. /**
  50. * Print barcode
  51. *
  52. * @param string $code Code
  53. * @param string $encoding Encoding
  54. * @param string $scale Scale
  55. * @param string $mode 'png' or 'jpg' ...
  56. *
  57. *
  58. * @return array $bars array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info)
  59. */
  60. function barcode_print($code, $encoding="ANY", $scale = 2 ,$mode = "png")
  61. {
  62. // DOLCHANGE LDR Add log
  63. dol_syslog("barcode.lib.php::barcode_print $code $encoding $scale $mode");
  64. $bars=barcode_encode($code,$encoding);
  65. if (! $bars || ! empty($bars['error']))
  66. {
  67. // DOLCHANGE LDR Return error message instead of array
  68. if (empty($bars['error'])) $error='Bad Value '.$code.' for encoding '.$encoding;
  69. else $error=$bars['error'];
  70. dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR);
  71. return $error;
  72. }
  73. if (! $mode) $mode="png";
  74. //if (preg_match("/^(text|txt|plain)$/i",$mode)) print barcode_outtext($bars['text'],$bars['bars']);
  75. //elseif (preg_match("/^(html|htm)$/i",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0);
  76. //else
  77. barcode_outimage($bars['text'], $bars['bars'], $scale, $mode);
  78. return $bars;
  79. }
  80. /**
  81. * Encodes $code with $encoding using genbarcode OR built-in encoder if you don't have genbarcode only EAN-13/ISBN is possible
  82. *
  83. * You can use the following encodings (when you have genbarcode):
  84. * ANY choose best-fit (default)
  85. * EAN 8 or 13 EAN-Code
  86. * UPC 12-digit EAN
  87. * ISBN isbn numbers (still EAN-13)
  88. * 39 code 39
  89. * 128 code 128 (a,b,c: autoselection)
  90. * 128C code 128 (compact form for digits)
  91. * 128B code 128, full printable ascii
  92. * I25 interleaved 2 of 5 (only digits)
  93. * 128RAW Raw code 128 (by Leonid A. Broukhis)
  94. * CBR Codabar (by Leonid A. Broukhis)
  95. * MSI MSI (by Leonid A. Broukhis)
  96. * PLS Plessey (by Leonid A. Broukhis)
  97. *
  98. * @param string $code Code
  99. * @param string $encoding Encoding
  100. * @return array array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info)
  101. */
  102. function barcode_encode($code,$encoding)
  103. {
  104. global $genbarcode_loc;
  105. if (
  106. ((preg_match("/^ean$/i", $encoding)
  107. && ( strlen($code)==12 || strlen($code)==13)))
  108. || (($encoding) && (preg_match("/^isbn$/i", $encoding))
  109. && (( strlen($code)==9 || strlen($code)==10) ||
  110. (((preg_match("/^978/", $code) && strlen($code)==12) ||
  111. (strlen($code)==13)))))
  112. || (( !isset($encoding) || !$encoding || (preg_match("/^ANY$/i", $encoding) ))
  113. && (preg_match("/^[0-9]{12,13}$/", $code)))
  114. )
  115. {
  116. /* use built-in EAN-Encoder */
  117. dol_syslog("barcode.lib.php::barcode_encode Use barcode_encode_ean");
  118. $bars=barcode_encode_ean($code, $encoding);
  119. }
  120. else if (file_exists($genbarcode_loc)) // For example C39
  121. {
  122. /* use genbarcode */
  123. dol_syslog("barcode.lib.php::barcode_encode Use genbarcode ".$genbarcode_loc." code=".$code." encoding=".$encoding);
  124. $bars=barcode_encode_genbarcode($code, $encoding);
  125. }
  126. else
  127. {
  128. print "barcode_encode needs an external programm for encodings other then EAN/ISBN<BR>\n";
  129. print "<UL>\n";
  130. print "<LI>download gnu-barcode from <A href=\"http://www.gnu.org/software/barcode/\">www.gnu.org/software/barcode/</A>\n";
  131. print "<LI>compile and install them\n";
  132. print "<LI>download genbarcode from <A href=\"http://www.ashberg.de/bar/\">www.ashberg.de/bar/</A>\n";
  133. print "<LI>compile and install them\n";
  134. print "<LI>specify path the genbarcode in barcode module setup\n";
  135. print "</UL>\n";
  136. print "<BR>\n";
  137. return false;
  138. }
  139. return $bars;
  140. }
  141. /**
  142. * Calculate EAN sum
  143. *
  144. * @param string $ean EAN to encode
  145. * @return string Sum
  146. */
  147. function barcode_gen_ean_sum($ean)
  148. {
  149. $even=true; $esum=0; $osum=0;
  150. $ln=strlen($ean)-1;
  151. for ($i=$ln; $i>=0; $i--)
  152. {
  153. if ($even) $esum+=$ean[$i]; else $osum+=$ean[$i];
  154. $even=!$even;
  155. }
  156. return (10-((3*$esum+$osum)%10))%10;
  157. }
  158. /**
  159. * Encode EAN
  160. *
  161. * @param string $ean Code
  162. * @param string $encoding Encoding
  163. * @return array array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info)
  164. */
  165. function barcode_encode_ean($ean, $encoding = "EAN-13")
  166. {
  167. $digits=array(3211,2221,2122,1411,1132,1231,1114,1312,1213,3112);
  168. $mirror=array("000000","001011","001101","001110","010011","011001","011100","010101","010110","011010");
  169. $guards=array("9a1a","1a1a1","a1a");
  170. $ean=trim($ean);
  171. if (preg_match("/[^0-9]/i",$ean))
  172. {
  173. return array("text"=>"Invalid EAN-Code");
  174. }
  175. $encoding=strtoupper($encoding);
  176. if ($encoding=="ISBN")
  177. {
  178. if (!preg_match("/^978/", $ean)) $ean="978".$ean;
  179. }
  180. if (preg_match("/^978/", $ean)) $encoding="ISBN";
  181. if (strlen($ean)<12 || strlen($ean)>13)
  182. {
  183. return array("text"=>"Invalid $encoding Code (must have 12/13 numbers)");
  184. }
  185. $ean=substr($ean,0,12);
  186. $eansum=barcode_gen_ean_sum($ean);
  187. $ean.=$eansum;
  188. $line=$guards[0];
  189. for ($i=1;$i<13;$i++)
  190. {
  191. $str=$digits[$ean[$i]];
  192. if ($i<7 && $mirror[$ean[0]][$i-1]==1) $line.=strrev($str); else $line.=$str;
  193. if ($i==6) $line.=$guards[1];
  194. }
  195. $line.=$guards[2];
  196. /* create text */
  197. $pos=0;
  198. $text="";
  199. for ($a=0;$a<13;$a++)
  200. {
  201. if ($a>0) $text.=" ";
  202. $text.="$pos:12:{$ean[$a]}";
  203. if ($a==0) $pos+=12;
  204. else if ($a==6) $pos+=12;
  205. else $pos+=7;
  206. }
  207. return array(
  208. "encoding" => $encoding,
  209. "bars" => $line,
  210. "text" => $text
  211. );
  212. }
  213. /**
  214. * Encode result of genbarcode command
  215. *
  216. * @param string $code Code
  217. * @param string $encoding Encoding
  218. * @return array array('encoding': the encoding which has been used, 'bars': the bars, 'text': text-positioning info)
  219. */
  220. function barcode_encode_genbarcode($code,$encoding)
  221. {
  222. global $genbarcode_loc;
  223. // Clean parameters
  224. if (preg_match("/^ean$/i", $encoding) && strlen($code)==13) $code=substr($code,0,12);
  225. if (!$encoding) $encoding="ANY";
  226. $encoding=preg_replace("/[\\\|]/", "_", $encoding);
  227. $code=preg_replace("/[\\\|]/", "_", $code);
  228. $command=escapeshellarg($genbarcode_loc);
  229. //$paramclear=" \"".str_replace("\"", "\\\"",$code)."\" \"".str_replace("\"", "\\\"",strtoupper($encoding))."\"";
  230. $paramclear=" ".escapeshellarg($code)." ".escapeshellarg(strtoupper($encoding));
  231. $fullcommandclear=$command." ".$paramclear." 2>&1";
  232. //print $fullcommandclear."<br>\n";exit;
  233. dol_syslog("Run command ".$fullcommandclear);
  234. $fp=popen($fullcommandclear, "r");
  235. if ($fp)
  236. {
  237. $bars=fgets($fp, 1024);
  238. $text=fgets($fp, 1024);
  239. $encoding=fgets($fp, 1024);
  240. pclose($fp);
  241. }
  242. else
  243. {
  244. dol_syslog("barcode.lib.php::barcode_encode_genbarcode failed to run popen ".$fullcommandclear, LOG_ERR);
  245. return false;
  246. }
  247. //var_dump($bars);
  248. $ret=array(
  249. "bars" => trim($bars),
  250. "text" => trim($text),
  251. "encoding" => trim($encoding),
  252. "error" => ""
  253. );
  254. //var_dump($ret);
  255. if (preg_match('/permission denied/i',$ret['bars']))
  256. {
  257. $ret['error']=$ret['bars']; $ret['bars']='';
  258. return $ret;
  259. }
  260. if (!$ret['bars']) return false;
  261. if (!$ret['text']) return false;
  262. if (!$ret['encoding']) return false;
  263. return $ret;
  264. }
  265. /**
  266. * Output image onto standard output, or onto disk if global filebarcode is defined
  267. *
  268. * @param string $text the text-line (<position>:<font-size>:<character> ...)
  269. * @param string $bars where to place the bars (<space-width><bar-width><space-width><bar-width>...)
  270. * @param int $scale scale factor ( 1 < scale < unlimited (scale 50 will produce 5400x300 pixels when using EAN-13!!!))
  271. * @param string $mode png,gif,jpg (default='png')
  272. * @param int $total_y the total height of the image ( default: scale * 60 )
  273. * @param array $space default: $space[top] = 2 * $scale; $space[bottom]= 2 * $scale; $space[left] = 2 * $scale; $space[right] = 2 * $scale;
  274. * @return void
  275. */
  276. function barcode_outimage($text, $bars, $scale = 1, $mode = "png", $total_y = 0, $space = '')
  277. {
  278. global $bar_color, $bg_color, $text_color;
  279. global $font_loc, $filebarcode;
  280. //print "$text, $bars, $scale, $mode, $total_y, $space, $font_loc, $filebarcode<br>";
  281. //var_dump($text);
  282. //var_dump($bars);
  283. //var_dump($font_loc);
  284. /* set defaults */
  285. if ($scale<1) $scale=2;
  286. $total_y=(int) $total_y;
  287. if ($total_y<1) $total_y=(int) $scale * 60;
  288. if (!$space)
  289. $space=array('top'=>2*$scale,'bottom'=>2*$scale,'left'=>2*$scale,'right'=>2*$scale);
  290. /* count total width */
  291. $xpos=0;
  292. $width=true;
  293. $ln=strlen($bars);
  294. for ($i=0; $i<$ln; $i++)
  295. {
  296. $val=strtolower($bars[$i]);
  297. if ($width)
  298. {
  299. $xpos+=$val*$scale;
  300. $width=false;
  301. continue;
  302. }
  303. if (preg_match("/[a-z]/", $val))
  304. {
  305. /* tall bar */
  306. $val=ord($val)-ord('a')+1;
  307. }
  308. $xpos+=$val*$scale;
  309. $width=true;
  310. }
  311. /* allocate the image */
  312. $total_x=( $xpos )+$space['right']+$space['right'];
  313. $xpos=$space['left'];
  314. if (! function_exists("imagecreate"))
  315. {
  316. print "You don't have the gd2 extension enabled<br>\n";
  317. return "";
  318. }
  319. $im=imagecreate($total_x, $total_y);
  320. /* create two images */
  321. $col_bg=ImageColorAllocate($im,$bg_color[0],$bg_color[1],$bg_color[2]);
  322. $col_bar=ImageColorAllocate($im,$bar_color[0],$bar_color[1],$bar_color[2]);
  323. $col_text=ImageColorAllocate($im,$text_color[0],$text_color[1],$text_color[2]);
  324. $height=round($total_y-($scale*10));
  325. $height2=round($total_y-$space['bottom']);
  326. /* paint the bars */
  327. $width=true;
  328. $ln=strlen($bars);
  329. for ($i=0; $i<$ln; $i++)
  330. {
  331. $val=strtolower($bars[$i]);
  332. if ($width)
  333. {
  334. $xpos+=$val*$scale;
  335. $width=false;
  336. continue;
  337. }
  338. if (preg_match("/[a-z]/", $val))
  339. {
  340. /* tall bar */
  341. $val=ord($val)-ord('a')+1;
  342. $h=$height2;
  343. } else $h=$height;
  344. imagefilledrectangle($im, $xpos, $space['top'], $xpos+($val*$scale)-1, $h, $col_bar);
  345. $xpos+=$val*$scale;
  346. $width=true;
  347. }
  348. $chars=explode(" ", $text);
  349. reset($chars);
  350. while (list($n, $v)=each($chars))
  351. {
  352. if (trim($v))
  353. {
  354. $inf=explode(":", $v);
  355. $fontsize=$scale*($inf[1]/1.8);
  356. $fontheight=$total_y-($fontsize/2.7)+2;
  357. imagettftext($im, $fontsize, 0, $space['left']+($scale*$inf[0])+2, $fontheight, $col_text, $font_loc, $inf[2]);
  358. }
  359. }
  360. /* output the image */
  361. $mode=strtolower($mode);
  362. if ($mode=='jpg' || $mode=='jpeg')
  363. {
  364. header("Content-Type: image/jpeg; name=\"barcode.jpg\"");
  365. imagejpeg($im);
  366. }
  367. else if ($mode=='gif')
  368. {
  369. header("Content-Type: image/gif; name=\"barcode.gif\"");
  370. imagegif($im);
  371. }
  372. else if (! empty($filebarcode)) // To wxrite into afile onto disk
  373. {
  374. imagepng($im,$filebarcode);
  375. }
  376. else
  377. {
  378. header("Content-Type: image/png; name=\"barcode.png\"");
  379. imagepng($im);
  380. }
  381. }