PageRenderTime 47ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/core/lib/barcode.lib.php

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